depthBasic.fs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. varying vec2 vUv;
  2. uniform float opacity;
  3. uniform vec3 baseColor;
  4. uniform vec3 backColor;
  5. uniform float occlusionDistance;
  6. uniform float clipDistance;
  7. uniform float maxClipFactor;
  8. #if defined use_map
  9. uniform sampler2D map;
  10. #endif
  11. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  12. //似乎通过gl.getExtension('EXT_frag_depth')得到的GL_EXT_frag_depth
  13. uniform sampler2D depthTexture;
  14. uniform float nearPlane;
  15. uniform float farPlane;
  16. uniform vec2 resolution;
  17. uniform vec2 viewportOffset; // viewportOffset 范围从0-整个画布的像素
  18. float convertToLinear(float zValue)
  19. {
  20. float z = zValue * 2.0 - 1.0;
  21. return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane));
  22. }
  23. #endif
  24. void main() {
  25. vec4 color = vec4(baseColor, opacity);
  26. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  27. // mixFactor and clipFactor define the color mixing proportion between the states of
  28. // full visibility and occluded visibility
  29. // and
  30. // full visibility and total invisibility
  31. float mixFactor = 0.0;
  32. float clipFactor = 0.0;
  33. // The linear depth value of the current fragment
  34. float fragDepth = convertToLinear(gl_FragCoord.z);
  35. // The coordinates of the current fragment in the depth texture
  36. vec2 depthTxtCoords = vec2(gl_FragCoord.x-viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution;
  37. //gl_FragCoord大小为 viewport client大小
  38. // The linear depth value of the pixel occupied by this fragment in the depth buffer
  39. float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r);
  40. // The difference between the two depths
  41. float delta = fragDepth - textureDepth;
  42. if (delta > 0.0)//差距
  43. {
  44. // occlusionDistance and clipDistance define the width of the respective zones and
  45. // mixFactor and clipFactor express the interpolation between the two colors depending on the position
  46. // of the current fragment withing those zones.
  47. mixFactor = clamp(delta / occlusionDistance, 0.0, 1.0);
  48. clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor);
  49. }
  50. // If the fragment is totally transparent, don't bother drawing it
  51. if (clipFactor == 1.0)
  52. {
  53. discard;
  54. }else{
  55. #if defined use_map
  56. color = texture2D(map, vUv) * color;
  57. #endif
  58. color = vec4(mix(color.rgb, backColor, mixFactor), color.a * (1.0 - clipFactor));
  59. }
  60. #else
  61. #if defined use_map
  62. color = texture2D(map, vUv) * color;
  63. #endif
  64. #endif
  65. gl_FragColor = color;
  66. }