WaterRefractionShader.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /**
  2. * @author Mugen87 / https://github.com/Mugen87
  3. *
  4. */
  5. THREE.WaterRefractionShader = {
  6. uniforms: {
  7. "color": {
  8. value: null
  9. },
  10. "time": {
  11. value: 0
  12. },
  13. "tDiffuse": {
  14. value: null
  15. },
  16. "tDudv": {
  17. value: null
  18. },
  19. "textureMatrix": {
  20. value: null
  21. }
  22. },
  23. vertexShader: [
  24. "uniform mat4 textureMatrix;",
  25. "varying vec2 vUv;",
  26. "varying vec4 vUvRefraction;",
  27. "void main() {",
  28. " vUv = uv;",
  29. " vUvRefraction = textureMatrix * vec4( position, 1.0 );",
  30. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  31. "}"
  32. ].join( "\n" ),
  33. fragmentShader: [
  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.1;",
  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. ].join( "\n" )
  60. };