WaterShader.js 10 KB

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