Water.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. import {
  10. Color,
  11. FrontSide,
  12. LinearEncoding,
  13. LinearFilter,
  14. MathUtils,
  15. Matrix4,
  16. Mesh,
  17. NoToneMapping,
  18. PerspectiveCamera,
  19. Plane,
  20. RGBFormat,
  21. ShaderMaterial,
  22. UniformsLib,
  23. UniformsUtils,
  24. Vector3,
  25. Vector4,
  26. WebGLRenderTarget
  27. } from "../../../build/three.module.js";
  28. var Water = function ( geometry, options ) {
  29. Mesh.call( this, geometry );
  30. var scope = this;
  31. options = options || {};
  32. var textureWidth = options.textureWidth !== undefined ? options.textureWidth : 512;
  33. var textureHeight = options.textureHeight !== undefined ? options.textureHeight : 512;
  34. var clipBias = options.clipBias !== undefined ? options.clipBias : 0.0;
  35. var alpha = options.alpha !== undefined ? options.alpha : 1.0;
  36. var time = options.time !== undefined ? options.time : 0.0;
  37. var normalSampler = options.waterNormals !== undefined ? options.waterNormals : null;
  38. var sunDirection = options.sunDirection !== undefined ? options.sunDirection : new Vector3( 0.70707, 0.70707, 0.0 );
  39. var sunColor = new Color( options.sunColor !== undefined ? options.sunColor : 0xffffff );
  40. var waterColor = new Color( options.waterColor !== undefined ? options.waterColor : 0x7F7F7F );
  41. var eye = options.eye !== undefined ? options.eye : new Vector3( 0, 0, 0 );
  42. var distortionScale = options.distortionScale !== undefined ? options.distortionScale : 20.0;
  43. var side = options.side !== undefined ? options.side : FrontSide;
  44. var fog = options.fog !== undefined ? options.fog : false;
  45. //
  46. var mirrorPlane = new Plane();
  47. var normal = new Vector3();
  48. var mirrorWorldPosition = new Vector3();
  49. var cameraWorldPosition = new Vector3();
  50. var rotationMatrix = new Matrix4();
  51. var lookAtPosition = new Vector3( 0, 0, - 1 );
  52. var clipPlane = new Vector4();
  53. var view = new Vector3();
  54. var target = new Vector3();
  55. var q = new Vector4();
  56. var textureMatrix = new Matrix4();
  57. var mirrorCamera = new PerspectiveCamera();
  58. var parameters = {
  59. minFilter: LinearFilter,
  60. magFilter: LinearFilter,
  61. format: RGBFormat,
  62. stencilBuffer: false
  63. };
  64. var renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, parameters );
  65. if ( ! MathUtils.isPowerOfTwo( textureWidth ) || ! MathUtils.isPowerOfTwo( textureHeight ) ) {
  66. renderTarget.texture.generateMipmaps = false;
  67. }
  68. var mirrorShader = {
  69. uniforms: UniformsUtils.merge( [
  70. UniformsLib[ 'fog' ],
  71. UniformsLib[ 'lights' ],
  72. {
  73. "normalSampler": { value: null },
  74. "mirrorSampler": { value: null },
  75. "alpha": { value: 1.0 },
  76. "time": { value: 0.0 },
  77. "size": { value: 1.0 },
  78. "distortionScale": { value: 20.0 },
  79. "textureMatrix": { value: new Matrix4() },
  80. "sunColor": { value: new Color( 0x7F7F7F ) },
  81. "sunDirection": { value: new Vector3( 0.70707, 0.70707, 0 ) },
  82. "eye": { value: new Vector3() },
  83. "waterColor": { value: new Color( 0x555555 ) }
  84. }
  85. ] ),
  86. vertexShader: [
  87. 'uniform mat4 textureMatrix;',
  88. 'uniform float time;',
  89. 'varying vec4 mirrorCoord;',
  90. 'varying vec4 worldPosition;',
  91. '#include <common>',
  92. '#include <fog_pars_vertex>',
  93. '#include <shadowmap_pars_vertex>',
  94. '#include <logdepthbuf_pars_vertex>',
  95. 'void main() {',
  96. ' mirrorCoord = modelMatrix * vec4( position, 1.0 );',
  97. ' worldPosition = mirrorCoord.xyzw;',
  98. ' mirrorCoord = textureMatrix * mirrorCoord;',
  99. ' vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );',
  100. ' gl_Position = projectionMatrix * mvPosition;',
  101. '#include <beginnormal_vertex>',
  102. '#include <defaultnormal_vertex>',
  103. '#include <logdepthbuf_vertex>',
  104. '#include <fog_vertex>',
  105. '#include <shadowmap_vertex>',
  106. '}'
  107. ].join( '\n' ),
  108. fragmentShader: [
  109. 'uniform sampler2D mirrorSampler;',
  110. 'uniform float alpha;',
  111. 'uniform float time;',
  112. 'uniform float size;',
  113. 'uniform float distortionScale;',
  114. 'uniform sampler2D normalSampler;',
  115. 'uniform vec3 sunColor;',
  116. 'uniform vec3 sunDirection;',
  117. 'uniform vec3 eye;',
  118. 'uniform vec3 waterColor;',
  119. 'varying vec4 mirrorCoord;',
  120. 'varying vec4 worldPosition;',
  121. 'vec4 getNoise( vec2 uv ) {',
  122. ' vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0);',
  123. ' vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 );',
  124. ' vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 );',
  125. ' vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 );',
  126. ' vec4 noise = texture2D( normalSampler, uv0 ) +',
  127. ' texture2D( normalSampler, uv1 ) +',
  128. ' texture2D( normalSampler, uv2 ) +',
  129. ' texture2D( normalSampler, uv3 );',
  130. ' return noise * 0.5 - 1.0;',
  131. '}',
  132. 'void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor ) {',
  133. ' vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) );',
  134. ' float direction = max( 0.0, dot( eyeDirection, reflection ) );',
  135. ' specularColor += pow( direction, shiny ) * sunColor * spec;',
  136. ' diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse;',
  137. '}',
  138. '#include <common>',
  139. '#include <packing>',
  140. '#include <bsdfs>',
  141. '#include <fog_pars_fragment>',
  142. '#include <logdepthbuf_pars_fragment>',
  143. '#include <lights_pars_begin>',
  144. '#include <shadowmap_pars_fragment>',
  145. '#include <shadowmask_pars_fragment>',
  146. 'void main() {',
  147. '#include <logdepthbuf_fragment>',
  148. ' vec4 noise = getNoise( worldPosition.xz * size );',
  149. ' vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) );',
  150. ' vec3 diffuseLight = vec3(0.0);',
  151. ' vec3 specularLight = vec3(0.0);',
  152. ' vec3 worldToEye = eye-worldPosition.xyz;',
  153. ' vec3 eyeDirection = normalize( worldToEye );',
  154. ' sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight );',
  155. ' float distance = length(worldToEye);',
  156. ' vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale;',
  157. ' vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.w + distortion ) );',
  158. ' float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 );',
  159. ' float rf0 = 0.3;',
  160. ' float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 );',
  161. ' vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor;',
  162. ' vec3 albedo = mix( ( sunColor * diffuseLight * 0.3 + scatter ) * getShadowMask(), ( vec3( 0.1 ) + reflectionSample * 0.9 + reflectionSample * specularLight ), reflectance);',
  163. ' vec3 outgoingLight = albedo;',
  164. ' gl_FragColor = vec4( outgoingLight, alpha );',
  165. '#include <tonemapping_fragment>',
  166. '#include <fog_fragment>',
  167. '}'
  168. ].join( '\n' )
  169. };
  170. var material = new ShaderMaterial( {
  171. fragmentShader: mirrorShader.fragmentShader,
  172. vertexShader: mirrorShader.vertexShader,
  173. uniforms: UniformsUtils.clone( mirrorShader.uniforms ),
  174. lights: true,
  175. side: side,
  176. fog: fog
  177. } );
  178. material.uniforms[ "mirrorSampler" ].value = renderTarget.texture;
  179. material.uniforms[ "textureMatrix" ].value = textureMatrix;
  180. material.uniforms[ "alpha" ].value = alpha;
  181. material.uniforms[ "time" ].value = time;
  182. material.uniforms[ "normalSampler" ].value = normalSampler;
  183. material.uniforms[ "sunColor" ].value = sunColor;
  184. material.uniforms[ "waterColor" ].value = waterColor;
  185. material.uniforms[ "sunDirection" ].value = sunDirection;
  186. material.uniforms[ "distortionScale" ].value = distortionScale;
  187. material.uniforms[ "eye" ].value = eye;
  188. scope.material = material;
  189. scope.onBeforeRender = function ( renderer, scene, camera ) {
  190. mirrorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
  191. cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  192. rotationMatrix.extractRotation( scope.matrixWorld );
  193. normal.set( 0, 0, 1 );
  194. normal.applyMatrix4( rotationMatrix );
  195. view.subVectors( mirrorWorldPosition, cameraWorldPosition );
  196. // Avoid rendering when mirror is facing away
  197. if ( view.dot( normal ) > 0 ) return;
  198. view.reflect( normal ).negate();
  199. view.add( mirrorWorldPosition );
  200. rotationMatrix.extractRotation( camera.matrixWorld );
  201. lookAtPosition.set( 0, 0, - 1 );
  202. lookAtPosition.applyMatrix4( rotationMatrix );
  203. lookAtPosition.add( cameraWorldPosition );
  204. target.subVectors( mirrorWorldPosition, lookAtPosition );
  205. target.reflect( normal ).negate();
  206. target.add( mirrorWorldPosition );
  207. mirrorCamera.position.copy( view );
  208. mirrorCamera.up.set( 0, 1, 0 );
  209. mirrorCamera.up.applyMatrix4( rotationMatrix );
  210. mirrorCamera.up.reflect( normal );
  211. mirrorCamera.lookAt( target );
  212. mirrorCamera.far = camera.far; // Used in WebGLBackground
  213. mirrorCamera.updateMatrixWorld();
  214. mirrorCamera.projectionMatrix.copy( camera.projectionMatrix );
  215. // Update the texture matrix
  216. textureMatrix.set(
  217. 0.5, 0.0, 0.0, 0.5,
  218. 0.0, 0.5, 0.0, 0.5,
  219. 0.0, 0.0, 0.5, 0.5,
  220. 0.0, 0.0, 0.0, 1.0
  221. );
  222. textureMatrix.multiply( mirrorCamera.projectionMatrix );
  223. textureMatrix.multiply( mirrorCamera.matrixWorldInverse );
  224. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  225. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  226. mirrorPlane.setFromNormalAndCoplanarPoint( normal, mirrorWorldPosition );
  227. mirrorPlane.applyMatrix4( mirrorCamera.matrixWorldInverse );
  228. clipPlane.set( mirrorPlane.normal.x, mirrorPlane.normal.y, mirrorPlane.normal.z, mirrorPlane.constant );
  229. var projectionMatrix = mirrorCamera.projectionMatrix;
  230. q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  231. q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  232. q.z = - 1.0;
  233. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  234. // Calculate the scaled plane vector
  235. clipPlane.multiplyScalar( 2.0 / clipPlane.dot( q ) );
  236. // Replacing the third row of the projection matrix
  237. projectionMatrix.elements[ 2 ] = clipPlane.x;
  238. projectionMatrix.elements[ 6 ] = clipPlane.y;
  239. projectionMatrix.elements[ 10 ] = clipPlane.z + 1.0 - clipBias;
  240. projectionMatrix.elements[ 14 ] = clipPlane.w;
  241. eye.setFromMatrixPosition( camera.matrixWorld );
  242. // Render
  243. if ( renderer.outputEncoding !== LinearEncoding ) {
  244. console.warn( 'THREE.Water: WebGLRenderer must use LinearEncoding as outputEncoding.' );
  245. scope.onBeforeRender = function () {};
  246. return;
  247. }
  248. if ( renderer.toneMapping !== NoToneMapping ) {
  249. console.warn( 'THREE.Water: WebGLRenderer must use NoToneMapping as toneMapping.' );
  250. scope.onBeforeRender = function () {};
  251. return;
  252. }
  253. var currentRenderTarget = renderer.getRenderTarget();
  254. var currentXrEnabled = renderer.xr.enabled;
  255. var currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
  256. scope.visible = false;
  257. renderer.xr.enabled = false; // Avoid camera modification and recursion
  258. renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows
  259. renderer.setRenderTarget( renderTarget );
  260. renderer.state.buffers.depth.setMask( true ); // make sure the depth buffer is writable so it can be properly cleared, see #18897
  261. if ( renderer.autoClear === false ) renderer.clear();
  262. renderer.render( scene, mirrorCamera );
  263. scope.visible = true;
  264. renderer.xr.enabled = currentXrEnabled;
  265. renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
  266. renderer.setRenderTarget( currentRenderTarget );
  267. // Restore viewport
  268. var viewport = camera.viewport;
  269. if ( viewport !== undefined ) {
  270. renderer.state.viewport( viewport );
  271. }
  272. };
  273. };
  274. Water.prototype = Object.create( Mesh.prototype );
  275. Water.prototype.constructor = Water;
  276. export { Water };