Water2.js 10 KB

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