WaterRefractionShader.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. const WaterRefractionShader = {
  2. name: 'WaterRefractionShader',
  3. uniforms: {
  4. 'color': {
  5. value: null
  6. },
  7. 'time': {
  8. value: 0
  9. },
  10. 'tDiffuse': {
  11. value: null
  12. },
  13. 'tDudv': {
  14. value: null
  15. },
  16. 'textureMatrix': {
  17. value: null
  18. }
  19. },
  20. vertexShader: /* glsl */`
  21. uniform mat4 textureMatrix;
  22. varying vec2 vUv;
  23. varying vec4 vUvRefraction;
  24. void main() {
  25. vUv = uv;
  26. vUvRefraction = textureMatrix * vec4( position, 1.0 );
  27. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  28. }`,
  29. fragmentShader: /* glsl */`
  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.5;
  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. #include <tonemapping_fragment>
  55. #include <colorspace_fragment>
  56. }`
  57. };
  58. export { WaterRefractionShader };