Water2.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. ( function () {
  2. /**
  3. * References:
  4. * https://alex.vlachos.com/graphics/Vlachos-SIGGRAPH10-WaterFlow.pdf
  5. * http://graphicsrunner.blogspot.de/2010/08/water-using-flow-maps.html
  6. *
  7. */
  8. class Water extends THREE.Mesh {
  9. constructor( geometry, options = {} ) {
  10. super( geometry );
  11. this.isWater = true;
  12. this.type = 'Water';
  13. const scope = this;
  14. const color = options.color !== undefined ? new THREE.Color( options.color ) : new THREE.Color( 0xFFFFFF );
  15. const textureWidth = options.textureWidth || 512;
  16. const textureHeight = options.textureHeight || 512;
  17. const clipBias = options.clipBias || 0;
  18. const flowDirection = options.flowDirection || new THREE.Vector2( 1, 0 );
  19. const flowSpeed = options.flowSpeed || 0.03;
  20. const reflectivity = options.reflectivity || 0.02;
  21. const scale = options.scale || 1;
  22. const shader = options.shader || Water.WaterShader;
  23. const textureLoader = new THREE.TextureLoader();
  24. const flowMap = options.flowMap || undefined;
  25. const normalMap0 = options.normalMap0 || textureLoader.load( 'textures/water/Water_1_M_Normal.jpg' );
  26. const normalMap1 = options.normalMap1 || textureLoader.load( 'textures/water/Water_2_M_Normal.jpg' );
  27. const cycle = 0.15; // a cycle of a flow map phase
  28. const halfCycle = cycle * 0.5;
  29. const textureMatrix = new THREE.Matrix4();
  30. const clock = new THREE.Clock();
  31. // internal components
  32. if ( THREE.Reflector === undefined ) {
  33. console.error( 'THREE.Water: Required component THREE.Reflector not found.' );
  34. return;
  35. }
  36. if ( THREE.Refractor === undefined ) {
  37. console.error( 'THREE.Water: Required component THREE.Refractor not found.' );
  38. return;
  39. }
  40. const reflector = new THREE.Reflector( geometry, {
  41. textureWidth: textureWidth,
  42. textureHeight: textureHeight,
  43. clipBias: clipBias
  44. } );
  45. const refractor = new THREE.Refractor( geometry, {
  46. textureWidth: textureWidth,
  47. textureHeight: textureHeight,
  48. clipBias: clipBias
  49. } );
  50. reflector.matrixAutoUpdate = false;
  51. refractor.matrixAutoUpdate = false;
  52. // material
  53. this.material = new THREE.ShaderMaterial( {
  54. uniforms: THREE.UniformsUtils.merge( [ THREE.UniformsLib[ 'fog' ], shader.uniforms ] ),
  55. vertexShader: shader.vertexShader,
  56. fragmentShader: shader.fragmentShader,
  57. transparent: true,
  58. fog: true
  59. } );
  60. if ( flowMap !== undefined ) {
  61. this.material.defines.USE_FLOWMAP = '';
  62. this.material.uniforms[ 'tFlowMap' ] = {
  63. type: 't',
  64. value: flowMap
  65. };
  66. } else {
  67. this.material.uniforms[ 'flowDirection' ] = {
  68. type: 'v2',
  69. value: flowDirection
  70. };
  71. }
  72. // maps
  73. normalMap0.wrapS = normalMap0.wrapT = THREE.RepeatWrapping;
  74. normalMap1.wrapS = normalMap1.wrapT = THREE.RepeatWrapping;
  75. this.material.uniforms[ 'tReflectionMap' ].value = reflector.getRenderTarget().texture;
  76. this.material.uniforms[ 'tRefractionMap' ].value = refractor.getRenderTarget().texture;
  77. this.material.uniforms[ 'tNormalMap0' ].value = normalMap0;
  78. this.material.uniforms[ 'tNormalMap1' ].value = normalMap1;
  79. // water
  80. this.material.uniforms[ 'color' ].value = color;
  81. this.material.uniforms[ 'reflectivity' ].value = reflectivity;
  82. this.material.uniforms[ 'textureMatrix' ].value = textureMatrix;
  83. // inital values
  84. this.material.uniforms[ 'config' ].value.x = 0; // flowMapOffset0
  85. this.material.uniforms[ 'config' ].value.y = halfCycle; // flowMapOffset1
  86. this.material.uniforms[ 'config' ].value.z = halfCycle; // halfCycle
  87. this.material.uniforms[ 'config' ].value.w = scale; // scale
  88. // functions
  89. function updateTextureMatrix( camera ) {
  90. textureMatrix.set( 0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0 );
  91. textureMatrix.multiply( camera.projectionMatrix );
  92. textureMatrix.multiply( camera.matrixWorldInverse );
  93. textureMatrix.multiply( scope.matrixWorld );
  94. }
  95. function updateFlow() {
  96. const delta = clock.getDelta();
  97. const config = scope.material.uniforms[ 'config' ];
  98. config.value.x += flowSpeed * delta; // flowMapOffset0
  99. config.value.y = config.value.x + halfCycle; // flowMapOffset1
  100. // Important: The distance between offsets should be always the value of "halfCycle".
  101. // Moreover, both offsets should be in the range of [ 0, cycle ].
  102. // This approach ensures a smooth water flow and avoids "reset" effects.
  103. if ( config.value.x >= cycle ) {
  104. config.value.x = 0;
  105. config.value.y = halfCycle;
  106. } else if ( config.value.y >= cycle ) {
  107. config.value.y = config.value.y - cycle;
  108. }
  109. }
  110. //
  111. this.onBeforeRender = function ( renderer, scene, camera ) {
  112. updateTextureMatrix( camera );
  113. updateFlow();
  114. scope.visible = false;
  115. reflector.matrixWorld.copy( scope.matrixWorld );
  116. refractor.matrixWorld.copy( scope.matrixWorld );
  117. reflector.onBeforeRender( renderer, scene, camera );
  118. refractor.onBeforeRender( renderer, scene, camera );
  119. scope.visible = true;
  120. };
  121. }
  122. }
  123. Water.WaterShader = {
  124. uniforms: {
  125. 'color': {
  126. type: 'c',
  127. value: null
  128. },
  129. 'reflectivity': {
  130. type: 'f',
  131. value: 0
  132. },
  133. 'tReflectionMap': {
  134. type: 't',
  135. value: null
  136. },
  137. 'tRefractionMap': {
  138. type: 't',
  139. value: null
  140. },
  141. 'tNormalMap0': {
  142. type: 't',
  143. value: null
  144. },
  145. 'tNormalMap1': {
  146. type: 't',
  147. value: null
  148. },
  149. 'textureMatrix': {
  150. type: 'm4',
  151. value: null
  152. },
  153. 'config': {
  154. type: 'v4',
  155. value: new THREE.Vector4()
  156. }
  157. },
  158. vertexShader: /* glsl */`
  159. #include <common>
  160. #include <fog_pars_vertex>
  161. #include <logdepthbuf_pars_vertex>
  162. uniform mat4 textureMatrix;
  163. varying vec4 vCoord;
  164. varying vec2 vUv;
  165. varying vec3 vToEye;
  166. void main() {
  167. vUv = uv;
  168. vCoord = textureMatrix * vec4( position, 1.0 );
  169. vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
  170. vToEye = cameraPosition - worldPosition.xyz;
  171. vec4 mvPosition = viewMatrix * worldPosition; // used in fog_vertex
  172. gl_Position = projectionMatrix * mvPosition;
  173. #include <logdepthbuf_vertex>
  174. #include <fog_vertex>
  175. }`,
  176. fragmentShader: /* glsl */`
  177. #include <common>
  178. #include <fog_pars_fragment>
  179. #include <logdepthbuf_pars_fragment>
  180. uniform sampler2D tReflectionMap;
  181. uniform sampler2D tRefractionMap;
  182. uniform sampler2D tNormalMap0;
  183. uniform sampler2D tNormalMap1;
  184. #ifdef USE_FLOWMAP
  185. uniform sampler2D tFlowMap;
  186. #else
  187. uniform vec2 flowDirection;
  188. #endif
  189. uniform vec3 color;
  190. uniform float reflectivity;
  191. uniform vec4 config;
  192. varying vec4 vCoord;
  193. varying vec2 vUv;
  194. varying vec3 vToEye;
  195. void main() {
  196. #include <logdepthbuf_fragment>
  197. float flowMapOffset0 = config.x;
  198. float flowMapOffset1 = config.y;
  199. float halfCycle = config.z;
  200. float scale = config.w;
  201. vec3 toEye = normalize( vToEye );
  202. // determine flow direction
  203. vec2 flow;
  204. #ifdef USE_FLOWMAP
  205. flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0;
  206. #else
  207. flow = flowDirection;
  208. #endif
  209. flow.x *= - 1.0;
  210. // sample normal maps (distort uvs with flowdata)
  211. vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 );
  212. vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 );
  213. // linear interpolate to get the final normal color
  214. float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle;
  215. vec4 normalColor = mix( normalColor0, normalColor1, flowLerp );
  216. // calculate normal vector
  217. vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b, normalColor.g * 2.0 - 1.0 ) );
  218. // calculate the fresnel term to blend reflection and refraction maps
  219. float theta = max( dot( toEye, normal ), 0.0 );
  220. float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 );
  221. // calculate final uv coords
  222. vec3 coord = vCoord.xyz / vCoord.w;
  223. vec2 uv = coord.xy + coord.z * normal.xz * 0.05;
  224. vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) );
  225. vec4 refractColor = texture2D( tRefractionMap, uv );
  226. // multiply water color with the mix of both textures
  227. gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance );
  228. #include <tonemapping_fragment>
  229. #include <encodings_fragment>
  230. #include <fog_fragment>
  231. }`
  232. };
  233. THREE.Water = Water;
  234. } )();