Water2.js 8.2 KB

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