WaterRefractionShader.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. ( function () {
  2. const 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:
  21. /* glsl */
  22. `
  23. uniform mat4 textureMatrix;
  24. varying vec2 vUv;
  25. varying vec4 vUvRefraction;
  26. void main() {
  27. vUv = uv;
  28. vUvRefraction = textureMatrix * vec4( position, 1.0 );
  29. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  30. }`,
  31. fragmentShader:
  32. /* glsl */
  33. `
  34. uniform vec3 color;
  35. uniform float time;
  36. uniform sampler2D tDiffuse;
  37. uniform sampler2D tDudv;
  38. varying vec2 vUv;
  39. varying vec4 vUvRefraction;
  40. float blendOverlay( float base, float blend ) {
  41. return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
  42. }
  43. vec3 blendOverlay( vec3 base, vec3 blend ) {
  44. return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ),blendOverlay( base.b, blend.b ) );
  45. }
  46. void main() {
  47. float waveStrength = 0.5;
  48. float waveSpeed = 0.03;
  49. // simple distortion (ripple) via dudv map (see https://www.youtube.com/watch?v=6B7IF6GOu7s)
  50. vec2 distortedUv = texture2D( tDudv, vec2( vUv.x + time * waveSpeed, vUv.y ) ).rg * waveStrength;
  51. distortedUv = vUv.xy + vec2( distortedUv.x, distortedUv.y + time * waveSpeed );
  52. vec2 distortion = ( texture2D( tDudv, distortedUv ).rg * 2.0 - 1.0 ) * waveStrength;
  53. // new uv coords
  54. vec4 uv = vec4( vUvRefraction );
  55. uv.xy += distortion;
  56. vec4 base = texture2DProj( tDiffuse, uv );
  57. gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
  58. }`
  59. };
  60. THREE.WaterRefractionShader = WaterRefractionShader;
  61. } )();