WaterShader.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /**
  2. * @author jbouny / https://github.com/jbouny
  3. *
  4. * Work based on :
  5. * @author Slayvin / http://slayvin.net : Flat mirror for three.js
  6. * @author Stemkoski / http://www.adelphi.edu/~stemkoski : An implementation of water shader based on the flat mirror
  7. * @author Jonas Wagner / http://29a.ch/ && http://29a.ch/slides/2012/webglwater/ : Water shader explanations in WebGL
  8. */
  9. THREE.ShaderLib[ 'water' ] = {
  10. uniforms: Object.assign(
  11. {
  12. "normalSampler": { value: null },
  13. "mirrorSampler": { value: null },
  14. "alpha": { value: 1.0 },
  15. "time": { value: 0.0 },
  16. "distortionScale": { value: 20.0 },
  17. "noiseScale": { value: 1.0 },
  18. "textureMatrix" : { value: new THREE.Matrix4() },
  19. "sunColor": { value: new THREE.Color( 0x7F7F7F ) },
  20. "sunDirection": { value: new THREE.Vector3( 0.70707, 0.70707, 0 ) },
  21. "eye": { value: new THREE.Vector3() },
  22. "waterColor": { value: new THREE.Color( 0x555555 ) }
  23. },
  24. THREE.UniformsLib[ "fog" ]
  25. ),
  26. vertexShader: [
  27. 'uniform mat4 textureMatrix;',
  28. 'uniform float time;',
  29. 'varying vec4 mirrorCoord;',
  30. 'varying vec3 worldPosition;',
  31. 'void main()',
  32. '{',
  33. ' mirrorCoord = modelMatrix * vec4( position, 1.0 );',
  34. ' worldPosition = mirrorCoord.xyz;',
  35. ' mirrorCoord = textureMatrix * mirrorCoord;',
  36. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  37. '}'
  38. ].join( '\n' ),
  39. fragmentShader: [
  40. 'precision highp float;',
  41. 'uniform sampler2D mirrorSampler;',
  42. 'uniform float alpha;',
  43. 'uniform float time;',
  44. 'uniform float distortionScale;',
  45. 'uniform sampler2D normalSampler;',
  46. 'uniform vec3 sunColor;',
  47. 'uniform vec3 sunDirection;',
  48. 'uniform vec3 eye;',
  49. 'uniform vec3 waterColor;',
  50. 'varying vec4 mirrorCoord;',
  51. 'varying vec3 worldPosition;',
  52. 'vec4 getNoise( vec2 uv )',
  53. '{',
  54. ' vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0);',
  55. ' vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 );',
  56. ' vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 );',
  57. ' vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 );',
  58. ' vec4 noise = texture2D( normalSampler, uv0 ) +',
  59. ' texture2D( normalSampler, uv1 ) +',
  60. ' texture2D( normalSampler, uv2 ) +',
  61. ' texture2D( normalSampler, uv3 );',
  62. ' return noise * 0.5 - 1.0;',
  63. '}',
  64. 'void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor )',
  65. '{',
  66. ' vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) );',
  67. ' float direction = max( 0.0, dot( eyeDirection, reflection ) );',
  68. ' specularColor += pow( direction, shiny ) * sunColor * spec;',
  69. ' diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse;',
  70. '}',
  71. THREE.ShaderChunk[ "common" ],
  72. THREE.ShaderChunk[ "fog_pars_fragment" ],
  73. 'void main()',
  74. '{',
  75. ' vec4 noise = getNoise( worldPosition.xz );',
  76. ' vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) );',
  77. ' vec3 diffuseLight = vec3(0.0);',
  78. ' vec3 specularLight = vec3(0.0);',
  79. ' vec3 worldToEye = eye-worldPosition;',
  80. ' vec3 eyeDirection = normalize( worldToEye );',
  81. ' sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight );',
  82. ' float distance = length(worldToEye);',
  83. ' vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale;',
  84. ' vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.z + distortion ) );',
  85. ' float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 );',
  86. ' float rf0 = 0.3;',
  87. ' float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 );',
  88. ' vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor;',
  89. ' vec3 albedo = mix( sunColor * diffuseLight * 0.3 + scatter, ( vec3( 0.1 ) + reflectionSample * 0.9 + reflectionSample * specularLight ), reflectance );',
  90. ' vec3 outgoingLight = albedo;',
  91. THREE.ShaderChunk[ "fog_fragment" ],
  92. ' gl_FragColor = vec4( outgoingLight, alpha );',
  93. '}'
  94. ].join( '\n' )
  95. };
  96. THREE.Water = function ( renderer, camera, scene, options ) {
  97. THREE.Object3D.call( this );
  98. this.name = 'water_' + this.id;
  99. function optionalParameter ( value, defaultValue ) {
  100. return value !== undefined ? value : defaultValue;
  101. }
  102. options = options || {};
  103. this.matrixNeedsUpdate = true;
  104. var width = optionalParameter( options.textureWidth, 512 );
  105. var height = optionalParameter( options.textureHeight, 512 );
  106. this.clipBias = optionalParameter( options.clipBias, 0.0 );
  107. this.alpha = optionalParameter( options.alpha, 1.0 );
  108. this.time = optionalParameter( options.time, 0.0 );
  109. this.normalSampler = optionalParameter( options.waterNormals, null );
  110. this.sunDirection = optionalParameter( options.sunDirection, new THREE.Vector3( 0.70707, 0.70707, 0.0 ) );
  111. this.sunColor = new THREE.Color( optionalParameter( options.sunColor, 0xffffff ) );
  112. this.waterColor = new THREE.Color( optionalParameter( options.waterColor, 0x7F7F7F ) );
  113. this.eye = optionalParameter( options.eye, new THREE.Vector3( 0, 0, 0 ) );
  114. this.distortionScale = optionalParameter( options.distortionScale, 20.0 );
  115. this.side = optionalParameter( options.side, THREE.FrontSide );
  116. this.fog = optionalParameter( options.fog, false );
  117. this.renderer = renderer;
  118. this.scene = scene;
  119. this.mirrorPlane = new THREE.Plane();
  120. this.normal = new THREE.Vector3( 0, 0, 1 );
  121. this.mirrorWorldPosition = new THREE.Vector3();
  122. this.cameraWorldPosition = new THREE.Vector3();
  123. this.rotationMatrix = new THREE.Matrix4();
  124. this.lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
  125. this.clipPlane = new THREE.Vector4();
  126. if ( camera instanceof THREE.PerspectiveCamera ) {
  127. this.camera = camera;
  128. } else {
  129. this.camera = new THREE.PerspectiveCamera();
  130. console.log( this.name + ': camera is not a Perspective Camera!' );
  131. }
  132. this.textureMatrix = new THREE.Matrix4();
  133. this.mirrorCamera = this.camera.clone();
  134. this.renderTarget = new THREE.WebGLRenderTarget( width, height );
  135. this.renderTarget2 = new THREE.WebGLRenderTarget( width, height );
  136. var mirrorShader = THREE.ShaderLib[ "water" ];
  137. var mirrorUniforms = Object.assign( {}, mirrorShader.uniforms );
  138. this.material = new THREE.ShaderMaterial( {
  139. fragmentShader: mirrorShader.fragmentShader,
  140. vertexShader: mirrorShader.vertexShader,
  141. uniforms: mirrorUniforms,
  142. transparent: true,
  143. side: this.side,
  144. fog: this.fog
  145. } );
  146. this.material.uniforms.mirrorSampler.value = this.renderTarget.texture;
  147. this.material.uniforms.textureMatrix.value = this.textureMatrix;
  148. this.material.uniforms.alpha.value = this.alpha;
  149. this.material.uniforms.time.value = this.time;
  150. this.material.uniforms.normalSampler.value = this.normalSampler;
  151. this.material.uniforms.sunColor.value = this.sunColor;
  152. this.material.uniforms.waterColor.value = this.waterColor;
  153. this.material.uniforms.sunDirection.value = this.sunDirection;
  154. this.material.uniforms.distortionScale.value = this.distortionScale;
  155. this.material.uniforms.eye.value = this.eye;
  156. if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) ) {
  157. this.renderTarget.texture.generateMipmaps = false;
  158. this.renderTarget.texture.minFilter = THREE.LinearFilter;
  159. this.renderTarget2.texture.generateMipmaps = false;
  160. this.renderTarget2.texture.minFilter = THREE.LinearFilter;
  161. }
  162. this.updateTextureMatrix();
  163. this.render();
  164. };
  165. THREE.Water.prototype = Object.create( THREE.Mirror.prototype );
  166. THREE.Water.prototype.constructor = THREE.Water;
  167. THREE.Water.prototype.updateTextureMatrix = function () {
  168. function sign( x ) {
  169. return x ? x < 0 ? - 1 : 1 : 0;
  170. }
  171. this.updateMatrixWorld();
  172. this.camera.updateMatrixWorld();
  173. this.mirrorWorldPosition.setFromMatrixPosition( this.matrixWorld );
  174. this.cameraWorldPosition.setFromMatrixPosition( this.camera.matrixWorld );
  175. this.rotationMatrix.extractRotation( this.matrixWorld );
  176. this.normal.set( 0, 0, 1 );
  177. this.normal.applyMatrix4( this.rotationMatrix );
  178. var view = this.mirrorWorldPosition.clone().sub( this.cameraWorldPosition );
  179. view.reflect( this.normal ).negate();
  180. view.add( this.mirrorWorldPosition );
  181. this.rotationMatrix.extractRotation( this.camera.matrixWorld );
  182. this.lookAtPosition.set( 0, 0, - 1 );
  183. this.lookAtPosition.applyMatrix4( this.rotationMatrix );
  184. this.lookAtPosition.add( this.cameraWorldPosition );
  185. var target = this.mirrorWorldPosition.clone().sub( this.lookAtPosition );
  186. target.reflect( this.normal ).negate();
  187. target.add( this.mirrorWorldPosition );
  188. this.up.set( 0, - 1, 0 );
  189. this.up.applyMatrix4( this.rotationMatrix );
  190. this.up.reflect( this.normal ).negate();
  191. this.mirrorCamera.position.copy( view );
  192. this.mirrorCamera.up = this.up;
  193. this.mirrorCamera.lookAt( target );
  194. this.mirrorCamera.aspect = this.camera.aspect;
  195. this.mirrorCamera.updateProjectionMatrix();
  196. this.mirrorCamera.updateMatrixWorld();
  197. this.mirrorCamera.matrixWorldInverse.getInverse( this.mirrorCamera.matrixWorld );
  198. // Update the texture matrix
  199. this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
  200. 0.0, 0.5, 0.0, 0.5,
  201. 0.0, 0.0, 0.5, 0.5,
  202. 0.0, 0.0, 0.0, 1.0 );
  203. this.textureMatrix.multiply( this.mirrorCamera.projectionMatrix );
  204. this.textureMatrix.multiply( this.mirrorCamera.matrixWorldInverse );
  205. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  206. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  207. this.mirrorPlane.setFromNormalAndCoplanarPoint( this.normal, this.mirrorWorldPosition );
  208. this.mirrorPlane.applyMatrix4( this.mirrorCamera.matrixWorldInverse );
  209. this.clipPlane.set( this.mirrorPlane.normal.x, this.mirrorPlane.normal.y, this.mirrorPlane.normal.z, this.mirrorPlane.constant );
  210. var q = new THREE.Vector4();
  211. var projectionMatrix = this.mirrorCamera.projectionMatrix;
  212. q.x = ( sign( this.clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  213. q.y = ( sign( this.clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  214. q.z = - 1.0;
  215. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  216. // Calculate the scaled plane vector
  217. var c = new THREE.Vector4();
  218. c = this.clipPlane.multiplyScalar( 2.0 / this.clipPlane.dot( q ) );
  219. // Replacing the third row of the projection matrix
  220. projectionMatrix.elements[ 2 ] = c.x;
  221. projectionMatrix.elements[ 6 ] = c.y;
  222. projectionMatrix.elements[ 10 ] = c.z + 1.0 - this.clipBias;
  223. projectionMatrix.elements[ 14 ] = c.w;
  224. var worldCoordinates = new THREE.Vector3();
  225. worldCoordinates.setFromMatrixPosition( this.camera.matrixWorld );
  226. this.eye = worldCoordinates;
  227. this.material.uniforms.eye.value = this.eye;
  228. };