DepthOfField.glsl 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. uniform sampler2D colorTexture;
  2. uniform sampler2D blurTexture;
  3. uniform sampler2D depthTexture;
  4. uniform float focalDistance;
  5. varying vec2 v_textureCoordinates;
  6. vec4 toEye(vec2 uv, float depth)
  7. {
  8. vec2 xy = vec2((uv.x * 2.0 - 1.0), ((1.0 - uv.y) * 2.0 - 1.0));
  9. vec4 posInCamera = czm_inverseProjection * vec4(xy, depth, 1.0);
  10. posInCamera = posInCamera / posInCamera.w;
  11. return posInCamera;
  12. }
  13. float computeDepthBlur(float depth)
  14. {
  15. float f;
  16. if (depth < focalDistance)
  17. {
  18. f = (focalDistance - depth) / (focalDistance - czm_currentFrustum.x);
  19. }
  20. else
  21. {
  22. f = (depth - focalDistance) / (czm_currentFrustum.y - focalDistance);
  23. f = pow(f, 0.1);
  24. }
  25. f *= f;
  26. f = clamp(f, 0.0, 1.0);
  27. return pow(f, 0.5);
  28. }
  29. void main(void)
  30. {
  31. float depth = czm_readDepth(depthTexture, v_textureCoordinates);
  32. vec4 posInCamera = toEye(v_textureCoordinates, depth);
  33. float d = computeDepthBlur(-posInCamera.z);
  34. gl_FragColor = mix(texture2D(colorTexture, v_textureCoordinates), texture2D(blurTexture, v_textureCoordinates), d);
  35. }