WaterRefractionShader.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /**
  2. * @author Mugen87 / https://github.com/Mugen87
  3. *
  4. */
  5. THREE.WaterRefractionShader = {
  6. uniforms: {
  7. 'color': {
  8. type: 'c',
  9. value: null
  10. },
  11. 'time': {
  12. type: 'f',
  13. value: 0
  14. },
  15. 'tDiffuse': {
  16. type: 't',
  17. value: null
  18. },
  19. 'tDudv': {
  20. type: 't',
  21. value: null
  22. },
  23. 'textureMatrix': {
  24. type: 'm4',
  25. value: null
  26. }
  27. },
  28. vertexShader: [
  29. 'uniform mat4 textureMatrix;',
  30. 'varying vec2 vUv;',
  31. 'varying vec4 vUvRefraction;',
  32. 'void main() {',
  33. ' vUv = uv;',
  34. ' vUvRefraction = textureMatrix * vec4( position, 1.0 );',
  35. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  36. '}'
  37. ].join( '\n' ),
  38. fragmentShader: [
  39. 'uniform vec3 color;',
  40. 'uniform float time;',
  41. 'uniform sampler2D tDiffuse;',
  42. 'uniform sampler2D tDudv;',
  43. 'varying vec2 vUv;',
  44. 'varying vec4 vUvRefraction;',
  45. 'float blendOverlay( float base, float blend ) {',
  46. ' return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );',
  47. '}',
  48. 'vec3 blendOverlay( vec3 base, vec3 blend ) {',
  49. ' return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ),blendOverlay( base.b, blend.b ) );',
  50. '}',
  51. 'void main() {',
  52. ' float waveStrength = 0.1;',
  53. ' float waveSpeed = 0.03;',
  54. // simple distortion (ripple) via dudv map (see https://www.youtube.com/watch?v=6B7IF6GOu7s)
  55. ' vec2 distortedUv = texture2D( tDudv, vec2( vUv.x + time * waveSpeed, vUv.y ) ).rg * waveStrength;',
  56. ' distortedUv = vUv.xy + vec2( distortedUv.x, distortedUv.y + time * waveSpeed );',
  57. ' vec2 distortion = ( texture2D( tDudv, distortedUv ).rg * 2.0 - 1.0 ) * waveStrength;',
  58. // new uv coords
  59. ' vec4 uv = vec4( vUvRefraction );',
  60. ' uv.xy += distortion;',
  61. ' vec4 base = texture2DProj( tDiffuse, uv );',
  62. ' gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );',
  63. '}'
  64. ].join( '\n' )
  65. };