WaterRefractionShader.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. var WaterRefractionShader = {
  2. uniforms: {
  3. "color": {
  4. value: null
  5. },
  6. "time": {
  7. value: 0
  8. },
  9. "tDiffuse": {
  10. value: null
  11. },
  12. "tDudv": {
  13. value: null
  14. },
  15. "textureMatrix": {
  16. value: null
  17. }
  18. },
  19. vertexShader: [
  20. "uniform mat4 textureMatrix;",
  21. "varying vec2 vUv;",
  22. "varying vec4 vUvRefraction;",
  23. "void main() {",
  24. " vUv = uv;",
  25. " vUvRefraction = textureMatrix * vec4( position, 1.0 );",
  26. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  27. "}"
  28. ].join( "\n" ),
  29. fragmentShader: [
  30. "uniform vec3 color;",
  31. "uniform float time;",
  32. "uniform sampler2D tDiffuse;",
  33. "uniform sampler2D tDudv;",
  34. "varying vec2 vUv;",
  35. "varying vec4 vUvRefraction;",
  36. "float blendOverlay( float base, float blend ) {",
  37. " return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );",
  38. "}",
  39. "vec3 blendOverlay( vec3 base, vec3 blend ) {",
  40. " return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ),blendOverlay( base.b, blend.b ) );",
  41. "}",
  42. "void main() {",
  43. " float waveStrength = 0.1;",
  44. " float waveSpeed = 0.03;",
  45. // simple distortion (ripple) via dudv map (see https://www.youtube.com/watch?v=6B7IF6GOu7s)
  46. " vec2 distortedUv = texture2D( tDudv, vec2( vUv.x + time * waveSpeed, vUv.y ) ).rg * waveStrength;",
  47. " distortedUv = vUv.xy + vec2( distortedUv.x, distortedUv.y + time * waveSpeed );",
  48. " vec2 distortion = ( texture2D( tDudv, distortedUv ).rg * 2.0 - 1.0 ) * waveStrength;",
  49. // new uv coords
  50. " vec4 uv = vec4( vUvRefraction );",
  51. " uv.xy += distortion;",
  52. " vec4 base = texture2DProj( tDiffuse, uv );",
  53. " gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );",
  54. "}"
  55. ].join( "\n" )
  56. };
  57. export { WaterRefractionShader };