WaterShader.js 11 KB

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