2
0

WaterRefractionShader.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. THREE.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. };