Water2.js 8.4 KB

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