Skip to content

Commit f57665f

Browse files
authored
Merge pull request #18696 from higharc/high-precision-z
MeshDepthMaterial: Compute depth manually rather than using gl_FragCoord.z
2 parents d4d21a2 + fb7edb9 commit f57665f

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/renderers/shaders/ShaderLib/depth_frag.glsl.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ export default /* glsl */`
1313
#include <logdepthbuf_pars_fragment>
1414
#include <clipping_planes_pars_fragment>
1515
16+
varying vec2 vHighPrecisionZW;
17+
1618
void main() {
1719
1820
#include <clipping_planes_fragment>
@@ -31,13 +33,16 @@ void main() {
3133
3234
#include <logdepthbuf_fragment>
3335
36+
// Higher precision equivalent of gl_FragCoord.z. This assumes depthRange has been left to its default values.
37+
float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;
38+
3439
#if DEPTH_PACKING == 3200
3540
36-
gl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );
41+
gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
3742
3843
#elif DEPTH_PACKING == 3201
3944
40-
gl_FragColor = packDepthToRGBA( gl_FragCoord.z );
45+
gl_FragColor = packDepthToRGBA( fragCoordZ );
4146
4247
#endif
4348

src/renderers/shaders/ShaderLib/depth_vert.glsl.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ export default /* glsl */`
77
#include <logdepthbuf_pars_vertex>
88
#include <clipping_planes_pars_vertex>
99
10+
// This is used for computing an equivalent of gl_FragCoord.z that is as high precision as possible.
11+
// Some platforms compute gl_FragCoord at a lower precision which makes the manually computed value better for
12+
// depth-based postprocessing effects. Reproduced on iPad with A10 processor / iPadOS 13.3.1.
13+
varying vec2 vHighPrecisionZW;
14+
1015
void main() {
1116
1217
#include <uv_vertex>
@@ -29,5 +34,7 @@ void main() {
2934
#include <logdepthbuf_vertex>
3035
#include <clipping_planes_vertex>
3136
37+
vHighPrecisionZW = gl_Position.zw;
38+
3239
}
3340
`;

0 commit comments

Comments
 (0)