WaterRefractionShader.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /** @module WaterRefractionShader */
  2. /**
  3. * Basic water refraction shader.
  4. *
  5. * @constant
  6. * @type {Object}
  7. */
  8. const WaterRefractionShader = {
  9. name: 'WaterRefractionShader',
  10. uniforms: {
  11. 'color': {
  12. value: null
  13. },
  14. 'time': {
  15. value: 0
  16. },
  17. 'tDiffuse': {
  18. value: null
  19. },
  20. 'tDudv': {
  21. value: null
  22. },
  23. 'textureMatrix': {
  24. value: null
  25. }
  26. },
  27. vertexShader: /* glsl */`
  28. uniform mat4 textureMatrix;
  29. varying vec2 vUv;
  30. varying vec4 vUvRefraction;
  31. void main() {
  32. vUv = uv;
  33. vUvRefraction = textureMatrix * vec4( position, 1.0 );
  34. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  35. }`,
  36. fragmentShader: /* glsl */`
  37. uniform vec3 color;
  38. uniform float time;
  39. uniform sampler2D tDiffuse;
  40. uniform sampler2D tDudv;
  41. varying vec2 vUv;
  42. varying vec4 vUvRefraction;
  43. float blendOverlay( float base, float blend ) {
  44. return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
  45. }
  46. vec3 blendOverlay( vec3 base, vec3 blend ) {
  47. return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ),blendOverlay( base.b, blend.b ) );
  48. }
  49. void main() {
  50. float waveStrength = 0.5;
  51. float waveSpeed = 0.03;
  52. // simple distortion (ripple) via dudv map (see https://www.youtube.com/watch?v=6B7IF6GOu7s)
  53. vec2 distortedUv = texture2D( tDudv, vec2( vUv.x + time * waveSpeed, vUv.y ) ).rg * waveStrength;
  54. distortedUv = vUv.xy + vec2( distortedUv.x, distortedUv.y + time * waveSpeed );
  55. vec2 distortion = ( texture2D( tDudv, distortedUv ).rg * 2.0 - 1.0 ) * waveStrength;
  56. // new uv coords
  57. vec4 uv = vec4( vUvRefraction );
  58. uv.xy += distortion;
  59. vec4 base = texture2DProj( tDiffuse, uv );
  60. gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
  61. #include <tonemapping_fragment>
  62. #include <colorspace_fragment>
  63. }`
  64. };
  65. export { WaterRefractionShader };
粤ICP备19079148号