WaterShader.js 12 KB

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