WaterShader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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.Water = function ( renderer, camera, scene, options ) {
  10. THREE.Object3D.call( this );
  11. function optionalParameter( value, defaultValue ) {
  12. return value !== undefined ? value : defaultValue;
  13. }
  14. options = options || {};
  15. var width = optionalParameter( options.textureWidth, 512 );
  16. var height = optionalParameter( options.textureHeight, 512 );
  17. this.clipBias = optionalParameter( options.clipBias, 0.0 );
  18. this.alpha = optionalParameter( options.alpha, 1.0 );
  19. this.time = optionalParameter( options.time, 0.0 );
  20. this.normalSampler = optionalParameter( options.waterNormals, null );
  21. this.sunDirection = optionalParameter( options.sunDirection, new THREE.Vector3( 0.70707, 0.70707, 0.0 ) );
  22. this.sunColor = new THREE.Color( optionalParameter( options.sunColor, 0xffffff ) );
  23. this.waterColor = new THREE.Color( optionalParameter( options.waterColor, 0x7F7F7F ) );
  24. this.eye = optionalParameter( options.eye, new THREE.Vector3( 0, 0, 0 ) );
  25. this.distortionScale = optionalParameter( options.distortionScale, 20.0 );
  26. this.side = optionalParameter( options.side, THREE.FrontSide );
  27. this.fog = optionalParameter( options.fog, false );
  28. this.renderer = renderer;
  29. this.scene = scene;
  30. this.mirrorPlane = new THREE.Plane();
  31. this.normal = new THREE.Vector3( 0, 0, 1 );
  32. this.mirrorWorldPosition = new THREE.Vector3();
  33. this.cameraWorldPosition = new THREE.Vector3();
  34. this.rotationMatrix = new THREE.Matrix4();
  35. this.lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
  36. this.clipPlane = new THREE.Vector4();
  37. if ( camera instanceof THREE.PerspectiveCamera ) {
  38. this.camera = camera;
  39. } else {
  40. this.camera = new THREE.PerspectiveCamera();
  41. console.log( this.name + ': camera is not a Perspective Camera!' );
  42. }
  43. this.textureMatrix = new THREE.Matrix4();
  44. this.mirrorCamera = this.camera.clone();
  45. this.renderTarget = new THREE.WebGLRenderTarget( width, height );
  46. this.renderTarget2 = new THREE.WebGLRenderTarget( width, height );
  47. var mirrorShader = {
  48. uniforms: THREE.UniformsUtils.merge( [
  49. THREE.UniformsLib[ 'fog' ],
  50. THREE.UniformsLib[ 'lights' ],
  51. {
  52. normalSampler: { value: null },
  53. mirrorSampler: { value: null },
  54. alpha: { value: 1.0 },
  55. time: { value: 0.0 },
  56. size: { value: 1.0 },
  57. distortionScale: { value: 20.0 },
  58. noiseScale: { value: 1.0 },
  59. textureMatrix: { value: new THREE.Matrix4() },
  60. sunColor: { value: new THREE.Color( 0x7F7F7F ) },
  61. sunDirection: { value: new THREE.Vector3( 0.70707, 0.70707, 0 ) },
  62. eye: { value: new THREE.Vector3() },
  63. waterColor: { value: new THREE.Color( 0x555555 ) }
  64. }
  65. ] ),
  66. vertexShader: [
  67. 'uniform mat4 textureMatrix;',
  68. 'uniform float time;',
  69. 'varying vec4 mirrorCoord;',
  70. 'varying vec4 worldPosition;',
  71. THREE.ShaderChunk[ 'fog_pars_vertex' ],
  72. THREE.ShaderChunk[ 'shadowmap_pars_vertex' ],
  73. 'void main() {',
  74. ' mirrorCoord = modelMatrix * vec4( position, 1.0 );',
  75. ' worldPosition = mirrorCoord.xyzw;',
  76. ' mirrorCoord = textureMatrix * mirrorCoord;',
  77. ' vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );',
  78. ' gl_Position = projectionMatrix * mvPosition;',
  79. THREE.ShaderChunk[ 'fog_vertex' ],
  80. THREE.ShaderChunk[ 'shadowmap_vertex' ],
  81. '}'
  82. ].join( '\n' ),
  83. fragmentShader: [
  84. 'uniform sampler2D mirrorSampler;',
  85. 'uniform float alpha;',
  86. 'uniform float time;',
  87. 'uniform float size;',
  88. 'uniform float distortionScale;',
  89. 'uniform sampler2D normalSampler;',
  90. 'uniform vec3 sunColor;',
  91. 'uniform vec3 sunDirection;',
  92. 'uniform vec3 eye;',
  93. 'uniform vec3 waterColor;',
  94. 'varying vec4 mirrorCoord;',
  95. 'varying vec4 worldPosition;',
  96. 'vec4 getNoise( vec2 uv ) {',
  97. ' vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0);',
  98. ' vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 );',
  99. ' vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 );',
  100. ' vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 );',
  101. ' vec4 noise = texture2D( normalSampler, uv0 ) +',
  102. ' texture2D( normalSampler, uv1 ) +',
  103. ' texture2D( normalSampler, uv2 ) +',
  104. ' texture2D( normalSampler, uv3 );',
  105. ' return noise * 0.5 - 1.0;',
  106. '}',
  107. 'void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor ) {',
  108. ' vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) );',
  109. ' float direction = max( 0.0, dot( eyeDirection, reflection ) );',
  110. ' specularColor += pow( direction, shiny ) * sunColor * spec;',
  111. ' diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse;',
  112. '}',
  113. THREE.ShaderChunk[ 'common' ],
  114. THREE.ShaderChunk[ 'packing' ],
  115. THREE.ShaderChunk[ 'bsdfs' ],
  116. THREE.ShaderChunk[ 'fog_pars_fragment' ],
  117. THREE.ShaderChunk[ 'lights_pars' ],
  118. THREE.ShaderChunk[ 'shadowmap_pars_fragment' ],
  119. THREE.ShaderChunk[ 'shadowmask_pars_fragment' ],
  120. 'void main() {',
  121. ' vec4 noise = getNoise( worldPosition.xz * size );',
  122. ' vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) );',
  123. ' vec3 diffuseLight = vec3(0.0);',
  124. ' vec3 specularLight = vec3(0.0);',
  125. ' vec3 worldToEye = eye-worldPosition.xyz;',
  126. ' vec3 eyeDirection = normalize( worldToEye );',
  127. ' sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight );',
  128. ' float distance = length(worldToEye);',
  129. ' vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale;',
  130. ' vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.z + distortion ) );',
  131. ' float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 );',
  132. ' float rf0 = 0.3;',
  133. ' float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 );',
  134. ' vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor;',
  135. ' vec3 albedo = mix( ( sunColor * diffuseLight * 0.3 + scatter ) * getShadowMask(), ( vec3( 0.1 ) + reflectionSample * 0.9 + reflectionSample * specularLight ), reflectance);',
  136. ' vec3 outgoingLight = albedo;',
  137. ' gl_FragColor = vec4( outgoingLight, alpha );',
  138. THREE.ShaderChunk[ 'tonemapping_fragment' ],
  139. THREE.ShaderChunk[ 'fog_fragment' ],
  140. '}'
  141. ].join( '\n' )
  142. };
  143. var mirrorUniforms = THREE.UniformsUtils.clone( mirrorShader.uniforms );
  144. this.material = new THREE.ShaderMaterial( {
  145. fragmentShader: mirrorShader.fragmentShader,
  146. vertexShader: mirrorShader.vertexShader,
  147. uniforms: mirrorUniforms,
  148. transparent: true,
  149. lights: true,
  150. side: this.side,
  151. fog: this.fog
  152. } );
  153. this.material.uniforms.mirrorSampler.value = this.renderTarget.texture;
  154. this.material.uniforms.textureMatrix.value = this.textureMatrix;
  155. this.material.uniforms.alpha.value = this.alpha;
  156. this.material.uniforms.time.value = this.time;
  157. this.material.uniforms.normalSampler.value = this.normalSampler;
  158. this.material.uniforms.sunColor.value = this.sunColor;
  159. this.material.uniforms.waterColor.value = this.waterColor;
  160. this.material.uniforms.sunDirection.value = this.sunDirection;
  161. this.material.uniforms.distortionScale.value = this.distortionScale;
  162. this.material.uniforms.size.value = this.size;
  163. this.material.uniforms.eye.value = this.eye;
  164. if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) ) {
  165. this.renderTarget.texture.generateMipmaps = false;
  166. this.renderTarget.texture.minFilter = THREE.LinearFilter;
  167. this.renderTarget2.texture.generateMipmaps = false;
  168. this.renderTarget2.texture.minFilter = THREE.LinearFilter;
  169. }
  170. this.updateTextureMatrix();
  171. this.render();
  172. };
  173. THREE.Water.prototype = Object.create( THREE.Object3D.prototype );
  174. THREE.Water.prototype.constructor = THREE.Water;
  175. THREE.Water.prototype.render = function () {
  176. this.updateTextureMatrix();
  177. // Render the mirrored view of the current scene into the target texture
  178. var scene = this;
  179. while ( scene.parent !== null ) {
  180. scene = scene.parent;
  181. }
  182. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  183. this.material.visible = false;
  184. this.renderer.render( scene, this.mirrorCamera, this.renderTarget, true );
  185. this.material.visible = true;
  186. }
  187. };
  188. THREE.Water.prototype.updateTextureMatrix = function () {
  189. this.updateMatrixWorld();
  190. this.camera.updateMatrixWorld();
  191. this.mirrorWorldPosition.setFromMatrixPosition( this.matrixWorld );
  192. this.cameraWorldPosition.setFromMatrixPosition( this.camera.matrixWorld );
  193. this.rotationMatrix.extractRotation( this.matrixWorld );
  194. this.normal.set( 0, 0, 1 );
  195. this.normal.applyMatrix4( this.rotationMatrix );
  196. var view = this.mirrorWorldPosition.clone().sub( this.cameraWorldPosition );
  197. view.reflect( this.normal ).negate();
  198. view.add( this.mirrorWorldPosition );
  199. this.rotationMatrix.extractRotation( this.camera.matrixWorld );
  200. this.lookAtPosition.set( 0, 0, -1 );
  201. this.lookAtPosition.applyMatrix4( this.rotationMatrix );
  202. this.lookAtPosition.add( this.cameraWorldPosition );
  203. var target = this.mirrorWorldPosition.clone().sub( this.lookAtPosition );
  204. target.reflect( this.normal ).negate();
  205. target.add( this.mirrorWorldPosition );
  206. this.up.set( 0, - 1, 0 );
  207. this.up.applyMatrix4( this.rotationMatrix );
  208. this.up.reflect( this.normal ).negate();
  209. this.mirrorCamera.position.copy( view );
  210. this.mirrorCamera.up = this.up;
  211. this.mirrorCamera.lookAt( target );
  212. this.mirrorCamera.aspect = this.camera.aspect;
  213. this.mirrorCamera.updateProjectionMatrix();
  214. this.mirrorCamera.updateMatrixWorld();
  215. // Update the texture matrix
  216. this.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. this.textureMatrix.multiply( this.mirrorCamera.projectionMatrix );
  223. this.textureMatrix.multiply( this.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. this.mirrorPlane.setFromNormalAndCoplanarPoint( this.normal, this.mirrorWorldPosition );
  227. this.mirrorPlane.applyMatrix4( this.mirrorCamera.matrixWorldInverse );
  228. this.clipPlane.set( this.mirrorPlane.normal.x, this.mirrorPlane.normal.y, this.mirrorPlane.normal.z, this.mirrorPlane.constant );
  229. var q = new THREE.Vector4();
  230. var projectionMatrix = this.mirrorCamera.projectionMatrix;
  231. q.x = ( Math.sign( this.clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  232. q.y = ( Math.sign( this.clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  233. q.z = - 1.0;
  234. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  235. // Calculate the scaled plane vector
  236. var c = this.clipPlane.multiplyScalar( 2.0 / this.clipPlane.dot( q ) );
  237. // Replacing the third row of the projection matrix
  238. projectionMatrix.elements[ 2 ] = c.x;
  239. projectionMatrix.elements[ 6 ] = c.y;
  240. projectionMatrix.elements[ 10 ] = c.z + 1.0 - this.clipBias;
  241. projectionMatrix.elements[ 14 ] = c.w;
  242. var worldCoordinates = new THREE.Vector3();
  243. worldCoordinates.setFromMatrixPosition( this.camera.matrixWorld );
  244. this.eye = worldCoordinates;
  245. this.material.uniforms.eye.value = this.eye;
  246. };
  247. THREE.WaterMesh = function ( width, height, renderer, camera, scene, options ) {
  248. var waterMaterial = new THREE.Water( renderer, camera, scene, options );
  249. var waterGeometry = new THREE.PlaneBufferGeometry( width, height );
  250. var waterMesh = new THREE.Mesh( waterGeometry, waterMaterial.material );
  251. waterMesh.water = waterMaterial;
  252. waterMesh.add( waterMaterial );
  253. waterMesh.render = function () { waterMaterial.render() };
  254. return waterMesh;
  255. };