0
0

WaterRefractionShader.js 1.7 KB

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