watersample.frag 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #ifdef OPENGL_ES
  2. precision highp float;
  3. #endif
  4. //////////////////////////
  5. // Uniforms
  6. uniform sampler2D u_refractionTexture;
  7. uniform sampler2D u_reflectionTexture;
  8. uniform sampler2D u_normalMap;
  9. uniform float u_time;
  10. //////////////////////////
  11. // Varyings
  12. varying vec4 v_vertexRefractionPosition;
  13. varying vec4 v_vertexReflectionPosition;
  14. varying vec2 v_texCoord;
  15. varying vec3 v_eyePosition;
  16. //////////////////////////
  17. const float distortAmount = 0.05;
  18. const float specularAmount = 2.5;
  19. const float textureRepeat = 2.0;
  20. const vec4 tangent = vec4(1.0, 0.0, 0.0, 0.0);
  21. const vec4 viewNormal = vec4(0.0, 1.0, 0.0, 0.0);
  22. const vec4 bitangent = vec4(0.0, 0.0, 1.0, 0.0);
  23. const vec4 waterColour = vec4(0.36, 0.32, 0.2,1.0);
  24. vec2 fromClipSpace(vec4 position)
  25. {
  26. return position.xy / position.w / 2.0 + 0.5;
  27. }
  28. void main()
  29. {
  30. // Get normal
  31. vec4 normal = texture2D(u_normalMap, v_texCoord * textureRepeat + u_time);
  32. normal = normalize(normal * 2.0 - 1.0);
  33. // Distortion offset
  34. vec4 dudv = normal * distortAmount;
  35. // Refraction sample
  36. vec2 textureCoord = fromClipSpace(v_vertexRefractionPosition) + dudv.rg;
  37. textureCoord = clamp(textureCoord, 0.001, 0.999);
  38. vec4 refractionColour = texture2D(u_refractionTexture, textureCoord) * waterColour;
  39. // Calc fog distance
  40. // Version 1 (linear)
  41. float z = (gl_FragCoord.z / gl_FragCoord.w) / 300.0; //const is max fog distance
  42. const float fogDensity = 6.0;
  43. float fogAmount = z * fogDensity;
  44. fogAmount = clamp(fogAmount, 0.0, 1.0);
  45. // Version 2 (exponential)
  46. //float z = gl_FragCoord.z / gl_FragCoord.w;
  47. //const float fogDensity = 0.0005;
  48. //float fogAmount = exp2(-fogDensity * fogDensity * z * z * 1.442695);
  49. //fogAmount = clamp(fogAmount, 0.0, 0.7);
  50. refractionColour = mix(refractionColour, waterColour, fogAmount);
  51. // Sample reflection
  52. textureCoord = fromClipSpace(v_vertexReflectionPosition) + dudv.rg;
  53. textureCoord = clamp(textureCoord, 0.001, 0.999);
  54. vec4 reflectionColour = texture2D(u_reflectionTexture, textureCoord);
  55. // View in tangent space
  56. vec4 viewDir = normalize(vec4(v_eyePosition, 1.0));
  57. vec4 viewTanSpace = normalize(vec4(dot(viewDir, tangent), dot(viewDir, bitangent), dot(viewDir, viewNormal), 1.0));
  58. vec4 viewReflection = normalize(reflect(-1.0 * viewTanSpace, normal));
  59. float fresnel = dot(normal, viewReflection);
  60. vec3 specular = vec3(clamp(pow(dot(viewTanSpace, normal), 255.0), 0.0, 1.0)) * specularAmount;
  61. gl_FragColor = mix(reflectionColour, refractionColour, fresnel) + vec4(specular, 1.0);
  62. }