71 vec2 dx = dFdx(texCoords);
72 vec2 dy = dFdy(texCoords);
73 const float minLayers = 2.0;
74 const float maxLayers = 16.0;
76 float tx_width = float(textureSize(normal_map, 0).x);
78 vec2 dx2 = max(dx * dx * tx_width * tx_width, dy * dy * tx_width * tx_width);
79 float mip_level = 0.5 * log2(max(dx2.
x, dx2.
y));
81 float fade =
clamp(1.0 - (mip_level / 3.0), 0.0, 1.0);
84 float current_max_layers = mix(minLayers, maxLayers, fade);
87 float numLayers = mix(current_max_layers, minLayers, abs(dot(
vec3(0.0, 0.0, 1.0), viewDir)));
89 float layerDepth = 1.0 / numLayers;
90 float currentLayerDepth = 0.0;
94 float uv_scale = length(fwidth(texCoords));
96 vec2 deltaTexCoords =
vec2(P.
x, -P.
y) / numLayers;
98 vec2 currentTexCoords = texCoords;
100 float currentDepthMapValue = textureGrad(normal_map, currentTexCoords, dx, dy).a;
104 while(currentLayerDepth < currentDepthMapValue && safety > cur)
106 currentTexCoords -= deltaTexCoords;
109 currentDepthMapValue = textureGrad(normal_map, currentTexCoords, dx, dy).a;
110 currentLayerDepth += layerDepth;
114 vec2 prevTexCoords = currentTexCoords + deltaTexCoords;
115 float afterDepth = currentLayerDepth - currentDepthMapValue;
116 float current_depth = textureGrad(normal_map, currentTexCoords, dx, dy).a;
117 float prev_depth = textureGrad(normal_map, prevTexCoords, dx, dy).a;
118 float beforeDepth = (prev_depth) - currentLayerDepth + layerDepth;
120 float weight = afterDepth / (afterDepth + beforeDepth);
121 vec2 finalTexCoords = mix(currentTexCoords, prevTexCoords, weight);
122 final_depth = mix(current_depth, prev_depth, weight);
124 return finalTexCoords;