webgl_gpgpu_water.html 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - gpgpu - water</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - <span id="waterSize"></span> webgl gpgpu water<br/>
  12. Move mouse to disturb water.<br>
  13. 'W' key toggles wireframe.
  14. </div>
  15. <!-- This is the 'compute shader' for the water heightmap: -->
  16. <script id="heightmapFragmentShader" type="x-shader/x-fragment">
  17. #include <common>
  18. uniform vec2 mousePos;
  19. uniform float mouseSize;
  20. uniform float viscosityConstant;
  21. uniform float heightCompensation;
  22. void main() {
  23. vec2 cellSize = 1.0 / resolution.xy;
  24. vec2 uv = gl_FragCoord.xy * cellSize;
  25. // heightmapValue.x == height from previous frame
  26. // heightmapValue.y == height from penultimate frame
  27. // heightmapValue.z, heightmapValue.w not used
  28. vec4 heightmapValue = texture2D( heightmap, uv );
  29. // Get neighbours
  30. vec4 north = texture2D( heightmap, uv + vec2( 0.0, cellSize.y ) );
  31. vec4 south = texture2D( heightmap, uv + vec2( 0.0, - cellSize.y ) );
  32. vec4 east = texture2D( heightmap, uv + vec2( cellSize.x, 0.0 ) );
  33. vec4 west = texture2D( heightmap, uv + vec2( - cellSize.x, 0.0 ) );
  34. // https://web.archive.org/web/20080618181901/http://freespace.virgin.net/hugo.elias/graphics/x_water.htm
  35. float newHeight = ( ( north.x + south.x + east.x + west.x ) * 0.5 - heightmapValue.y ) * viscosityConstant;
  36. // Mouse influence
  37. float mousePhase = clamp( length( ( uv - vec2( 0.5 ) ) * BOUNDS - vec2( mousePos.x, - mousePos.y ) ) * PI / mouseSize, 0.0, PI );
  38. newHeight += ( cos( mousePhase ) + 1.0 ) * 0.28;
  39. heightmapValue.y = heightmapValue.x;
  40. heightmapValue.x = newHeight;
  41. gl_FragColor = heightmapValue;
  42. }
  43. </script>
  44. <!-- This is just a smoothing 'compute shader' for using manually: -->
  45. <script id="smoothFragmentShader" type="x-shader/x-fragment">
  46. uniform sampler2D smoothTexture;
  47. void main() {
  48. vec2 cellSize = 1.0 / resolution.xy;
  49. vec2 uv = gl_FragCoord.xy * cellSize;
  50. // Computes the mean of texel and 4 neighbours
  51. vec4 textureValue = texture2D( smoothTexture, uv );
  52. textureValue += texture2D( smoothTexture, uv + vec2( 0.0, cellSize.y ) );
  53. textureValue += texture2D( smoothTexture, uv + vec2( 0.0, - cellSize.y ) );
  54. textureValue += texture2D( smoothTexture, uv + vec2( cellSize.x, 0.0 ) );
  55. textureValue += texture2D( smoothTexture, uv + vec2( - cellSize.x, 0.0 ) );
  56. textureValue /= 5.0;
  57. gl_FragColor = textureValue;
  58. }
  59. </script>
  60. <!-- This is a 'compute shader' to read the current level and normal of water at a point -->
  61. <!-- It is used with a variable of size 1x1 -->
  62. <script id="readWaterLevelFragmentShader" type="x-shader/x-fragment">
  63. uniform vec2 point1;
  64. uniform sampler2D levelTexture;
  65. // Integer to float conversion from https://stackoverflow.com/questions/17981163/webgl-read-pixels-from-floating-point-render-target
  66. float shift_right( float v, float amt ) {
  67. v = floor( v ) + 0.5;
  68. return floor( v / exp2( amt ) );
  69. }
  70. float shift_left( float v, float amt ) {
  71. return floor( v * exp2( amt ) + 0.5 );
  72. }
  73. float mask_last( float v, float bits ) {
  74. return mod( v, shift_left( 1.0, bits ) );
  75. }
  76. float extract_bits( float num, float from, float to ) {
  77. from = floor( from + 0.5 ); to = floor( to + 0.5 );
  78. return mask_last( shift_right( num, from ), to - from );
  79. }
  80. vec4 encode_float( float val ) {
  81. if ( val == 0.0 ) return vec4( 0, 0, 0, 0 );
  82. float sign = val > 0.0 ? 0.0 : 1.0;
  83. val = abs( val );
  84. float exponent = floor( log2( val ) );
  85. float biased_exponent = exponent + 127.0;
  86. float fraction = ( ( val / exp2( exponent ) ) - 1.0 ) * 8388608.0;
  87. float t = biased_exponent / 2.0;
  88. float last_bit_of_biased_exponent = fract( t ) * 2.0;
  89. float remaining_bits_of_biased_exponent = floor( t );
  90. float byte4 = extract_bits( fraction, 0.0, 8.0 ) / 255.0;
  91. float byte3 = extract_bits( fraction, 8.0, 16.0 ) / 255.0;
  92. float byte2 = ( last_bit_of_biased_exponent * 128.0 + extract_bits( fraction, 16.0, 23.0 ) ) / 255.0;
  93. float byte1 = ( sign * 128.0 + remaining_bits_of_biased_exponent ) / 255.0;
  94. return vec4( byte4, byte3, byte2, byte1 );
  95. }
  96. void main() {
  97. vec2 cellSize = 1.0 / resolution.xy;
  98. float waterLevel = texture2D( levelTexture, point1 ).x;
  99. vec2 normal = vec2(
  100. ( texture2D( levelTexture, point1 + vec2( - cellSize.x, 0 ) ).x - texture2D( levelTexture, point1 + vec2( cellSize.x, 0 ) ).x ) * WIDTH / BOUNDS,
  101. ( texture2D( levelTexture, point1 + vec2( 0, - cellSize.y ) ).x - texture2D( levelTexture, point1 + vec2( 0, cellSize.y ) ).x ) * WIDTH / BOUNDS );
  102. if ( gl_FragCoord.x < 1.5 ) {
  103. gl_FragColor = encode_float( waterLevel );
  104. } else if ( gl_FragCoord.x < 2.5 ) {
  105. gl_FragColor = encode_float( normal.x );
  106. } else if ( gl_FragCoord.x < 3.5 ) {
  107. gl_FragColor = encode_float( normal.y );
  108. } else {
  109. gl_FragColor = encode_float( 0.0 );
  110. }
  111. }
  112. </script>
  113. <!-- This is the water visualization shader, copied from the THREE.MeshPhongMaterial and modified: -->
  114. <script id="waterVertexShader" type="x-shader/x-vertex">
  115. uniform sampler2D heightmap;
  116. #define PHONG
  117. varying vec3 vViewPosition;
  118. #ifndef FLAT_SHADED
  119. varying vec3 vNormal;
  120. #endif
  121. #include <common>
  122. #include <uv_pars_vertex>
  123. #include <displacementmap_pars_vertex>
  124. #include <envmap_pars_vertex>
  125. #include <color_pars_vertex>
  126. #include <morphtarget_pars_vertex>
  127. #include <skinning_pars_vertex>
  128. #include <shadowmap_pars_vertex>
  129. #include <logdepthbuf_pars_vertex>
  130. #include <clipping_planes_pars_vertex>
  131. void main() {
  132. vec2 cellSize = vec2( 1.0 / WIDTH, 1.0 / WIDTH );
  133. #include <uv_vertex>
  134. #include <color_vertex>
  135. // # include <beginnormal_vertex>
  136. // Compute normal from heightmap
  137. vec3 objectNormal = vec3(
  138. ( texture2D( heightmap, uv + vec2( - cellSize.x, 0 ) ).x - texture2D( heightmap, uv + vec2( cellSize.x, 0 ) ).x ) * WIDTH / BOUNDS,
  139. ( texture2D( heightmap, uv + vec2( 0, - cellSize.y ) ).x - texture2D( heightmap, uv + vec2( 0, cellSize.y ) ).x ) * WIDTH / BOUNDS,
  140. 1.0 );
  141. //<beginnormal_vertex>
  142. #include <morphnormal_vertex>
  143. #include <skinbase_vertex>
  144. #include <skinnormal_vertex>
  145. #include <defaultnormal_vertex>
  146. #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED
  147. vNormal = normalize( transformedNormal );
  148. #endif
  149. //# include <begin_vertex>
  150. float heightValue = texture2D( heightmap, uv ).x;
  151. vec3 transformed = vec3( position.x, position.y, heightValue );
  152. //<begin_vertex>
  153. #include <morphtarget_vertex>
  154. #include <skinning_vertex>
  155. #include <displacementmap_vertex>
  156. #include <project_vertex>
  157. #include <logdepthbuf_vertex>
  158. #include <clipping_planes_vertex>
  159. vViewPosition = - mvPosition.xyz;
  160. #include <worldpos_vertex>
  161. #include <envmap_vertex>
  162. #include <shadowmap_vertex>
  163. }
  164. </script>
  165. <script type="importmap">
  166. {
  167. "imports": {
  168. "three": "../build/three.module.js",
  169. "three/addons/": "./jsm/"
  170. }
  171. }
  172. </script>
  173. <script type="module">
  174. import * as THREE from 'three';
  175. import Stats from 'three/addons/libs/stats.module.js';
  176. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  177. import { GPUComputationRenderer } from 'three/addons/misc/GPUComputationRenderer.js';
  178. import { SimplexNoise } from 'three/addons/math/SimplexNoise.js';
  179. // Texture width for simulation
  180. const WIDTH = 128;
  181. // Water size in system units
  182. const BOUNDS = 512;
  183. const BOUNDS_HALF = BOUNDS * 0.5;
  184. let container, stats;
  185. let camera, scene, renderer;
  186. let mouseMoved = false;
  187. const mouseCoords = new THREE.Vector2();
  188. const raycaster = new THREE.Raycaster();
  189. let waterMesh;
  190. let meshRay;
  191. let gpuCompute;
  192. let heightmapVariable;
  193. let waterUniforms;
  194. let smoothShader;
  195. let readWaterLevelShader;
  196. let readWaterLevelRenderTarget;
  197. let readWaterLevelImage;
  198. const waterNormal = new THREE.Vector3();
  199. const NUM_SPHERES = 5;
  200. const spheres = [];
  201. let spheresEnabled = true;
  202. const simplex = new SimplexNoise();
  203. init();
  204. function init() {
  205. container = document.createElement( 'div' );
  206. document.body.appendChild( container );
  207. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  208. camera.position.set( 0, 200, 350 );
  209. camera.lookAt( 0, 0, 0 );
  210. scene = new THREE.Scene();
  211. const sun = new THREE.DirectionalLight( 0xFFFFFF, 3.0 );
  212. sun.position.set( 300, 400, 175 );
  213. scene.add( sun );
  214. const sun2 = new THREE.DirectionalLight( 0x40A040, 2.0 );
  215. sun2.position.set( - 100, 350, - 200 );
  216. scene.add( sun2 );
  217. renderer = new THREE.WebGLRenderer();
  218. renderer.setPixelRatio( window.devicePixelRatio );
  219. renderer.setSize( window.innerWidth, window.innerHeight );
  220. renderer.setAnimationLoop( animate );
  221. container.appendChild( renderer.domElement );
  222. stats = new Stats();
  223. container.appendChild( stats.dom );
  224. container.style.touchAction = 'none';
  225. container.addEventListener( 'pointermove', onPointerMove );
  226. document.addEventListener( 'keydown', function ( event ) {
  227. // W Pressed: Toggle wireframe
  228. if ( event.keyCode === 87 ) {
  229. waterMesh.material.wireframe = ! waterMesh.material.wireframe;
  230. waterMesh.material.needsUpdate = true;
  231. }
  232. } );
  233. window.addEventListener( 'resize', onWindowResize );
  234. const gui = new GUI();
  235. const effectController = {
  236. mouseSize: 20.0,
  237. viscosity: 0.98,
  238. spheresEnabled: spheresEnabled
  239. };
  240. const valuesChanger = function () {
  241. heightmapVariable.material.uniforms[ 'mouseSize' ].value = effectController.mouseSize;
  242. heightmapVariable.material.uniforms[ 'viscosityConstant' ].value = effectController.viscosity;
  243. spheresEnabled = effectController.spheresEnabled;
  244. for ( let i = 0; i < NUM_SPHERES; i ++ ) {
  245. if ( spheres[ i ] ) {
  246. spheres[ i ].visible = spheresEnabled;
  247. }
  248. }
  249. };
  250. gui.add( effectController, 'mouseSize', 1.0, 100.0, 1.0 ).onChange( valuesChanger );
  251. gui.add( effectController, 'viscosity', 0.9, 0.999, 0.001 ).onChange( valuesChanger );
  252. gui.add( effectController, 'spheresEnabled' ).onChange( valuesChanger );
  253. const buttonSmooth = {
  254. smoothWater: function () {
  255. smoothWater();
  256. }
  257. };
  258. gui.add( buttonSmooth, 'smoothWater' );
  259. initWater();
  260. createSpheres();
  261. valuesChanger();
  262. }
  263. function initWater() {
  264. const materialColor = 0x0040C0;
  265. const geometry = new THREE.PlaneGeometry( BOUNDS, BOUNDS, WIDTH - 1, WIDTH - 1 );
  266. // material: make a THREE.ShaderMaterial clone of THREE.MeshPhongMaterial, with customized vertex shader
  267. const material = new THREE.ShaderMaterial( {
  268. uniforms: THREE.UniformsUtils.merge( [
  269. THREE.ShaderLib[ 'phong' ].uniforms,
  270. {
  271. 'heightmap': { value: null }
  272. }
  273. ] ),
  274. vertexShader: document.getElementById( 'waterVertexShader' ).textContent,
  275. fragmentShader: THREE.ShaderChunk[ 'meshphong_frag' ]
  276. } );
  277. material.lights = true;
  278. // Material attributes from THREE.MeshPhongMaterial
  279. // Sets the uniforms with the material values
  280. material.uniforms[ 'diffuse' ].value = new THREE.Color( materialColor );
  281. material.uniforms[ 'specular' ].value = new THREE.Color( 0x111111 );
  282. material.uniforms[ 'shininess' ].value = Math.max( 50, 1e-4 );
  283. material.uniforms[ 'opacity' ].value = material.opacity;
  284. // Defines
  285. material.defines.WIDTH = WIDTH.toFixed( 1 );
  286. material.defines.BOUNDS = BOUNDS.toFixed( 1 );
  287. waterUniforms = material.uniforms;
  288. waterMesh = new THREE.Mesh( geometry, material );
  289. waterMesh.rotation.x = - Math.PI / 2;
  290. waterMesh.matrixAutoUpdate = false;
  291. waterMesh.updateMatrix();
  292. scene.add( waterMesh );
  293. // THREE.Mesh just for mouse raycasting
  294. const geometryRay = new THREE.PlaneGeometry( BOUNDS, BOUNDS, 1, 1 );
  295. meshRay = new THREE.Mesh( geometryRay, new THREE.MeshBasicMaterial( { color: 0xFFFFFF, visible: false } ) );
  296. meshRay.rotation.x = - Math.PI / 2;
  297. meshRay.matrixAutoUpdate = false;
  298. meshRay.updateMatrix();
  299. scene.add( meshRay );
  300. // Creates the gpu computation class and sets it up
  301. gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );
  302. const heightmap0 = gpuCompute.createTexture();
  303. fillTexture( heightmap0 );
  304. heightmapVariable = gpuCompute.addVariable( 'heightmap', document.getElementById( 'heightmapFragmentShader' ).textContent, heightmap0 );
  305. gpuCompute.setVariableDependencies( heightmapVariable, [ heightmapVariable ] );
  306. heightmapVariable.material.uniforms[ 'mousePos' ] = { value: new THREE.Vector2( 10000, 10000 ) };
  307. heightmapVariable.material.uniforms[ 'mouseSize' ] = { value: 20.0 };
  308. heightmapVariable.material.uniforms[ 'viscosityConstant' ] = { value: 0.98 };
  309. heightmapVariable.material.uniforms[ 'heightCompensation' ] = { value: 0 };
  310. heightmapVariable.material.defines.BOUNDS = BOUNDS.toFixed( 1 );
  311. const error = gpuCompute.init();
  312. if ( error !== null ) {
  313. console.error( error );
  314. }
  315. // Create compute shader to smooth the water surface and velocity
  316. smoothShader = gpuCompute.createShaderMaterial( document.getElementById( 'smoothFragmentShader' ).textContent, { smoothTexture: { value: null } } );
  317. // Create compute shader to read water level
  318. readWaterLevelShader = gpuCompute.createShaderMaterial( document.getElementById( 'readWaterLevelFragmentShader' ).textContent, {
  319. point1: { value: new THREE.Vector2() },
  320. levelTexture: { value: null }
  321. } );
  322. readWaterLevelShader.defines.WIDTH = WIDTH.toFixed( 1 );
  323. readWaterLevelShader.defines.BOUNDS = BOUNDS.toFixed( 1 );
  324. // Create a 4x1 pixel image and a render target (Uint8, 4 channels, 1 byte per channel) to read water height and orientation
  325. readWaterLevelImage = new Uint8Array( 4 * 1 * 4 );
  326. readWaterLevelRenderTarget = new THREE.WebGLRenderTarget( 4, 1, {
  327. wrapS: THREE.ClampToEdgeWrapping,
  328. wrapT: THREE.ClampToEdgeWrapping,
  329. minFilter: THREE.NearestFilter,
  330. magFilter: THREE.NearestFilter,
  331. format: THREE.RGBAFormat,
  332. type: THREE.UnsignedByteType,
  333. depthBuffer: false
  334. } );
  335. }
  336. function fillTexture( texture ) {
  337. const waterMaxHeight = 10;
  338. function noise( x, y ) {
  339. let multR = waterMaxHeight;
  340. let mult = 0.025;
  341. let r = 0;
  342. for ( let i = 0; i < 15; i ++ ) {
  343. r += multR * simplex.noise( x * mult, y * mult );
  344. multR *= 0.53 + 0.025 * i;
  345. mult *= 1.25;
  346. }
  347. return r;
  348. }
  349. const pixels = texture.image.data;
  350. let p = 0;
  351. for ( let j = 0; j < WIDTH; j ++ ) {
  352. for ( let i = 0; i < WIDTH; i ++ ) {
  353. const x = i * 128 / WIDTH;
  354. const y = j * 128 / WIDTH;
  355. pixels[ p + 0 ] = noise( x, y );
  356. pixels[ p + 1 ] = pixels[ p + 0 ];
  357. pixels[ p + 2 ] = 0;
  358. pixels[ p + 3 ] = 1;
  359. p += 4;
  360. }
  361. }
  362. }
  363. function smoothWater() {
  364. const currentRenderTarget = gpuCompute.getCurrentRenderTarget( heightmapVariable );
  365. const alternateRenderTarget = gpuCompute.getAlternateRenderTarget( heightmapVariable );
  366. for ( let i = 0; i < 10; i ++ ) {
  367. smoothShader.uniforms[ 'smoothTexture' ].value = currentRenderTarget.texture;
  368. gpuCompute.doRenderTarget( smoothShader, alternateRenderTarget );
  369. smoothShader.uniforms[ 'smoothTexture' ].value = alternateRenderTarget.texture;
  370. gpuCompute.doRenderTarget( smoothShader, currentRenderTarget );
  371. }
  372. }
  373. function createSpheres() {
  374. const sphereTemplate = new THREE.Mesh( new THREE.SphereGeometry( 4, 24, 12 ), new THREE.MeshPhongMaterial( { color: 0xFFFF00 } ) );
  375. for ( let i = 0; i < NUM_SPHERES; i ++ ) {
  376. let sphere = sphereTemplate;
  377. if ( i < NUM_SPHERES - 1 ) {
  378. sphere = sphereTemplate.clone();
  379. }
  380. sphere.position.x = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  381. sphere.position.z = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  382. sphere.userData.velocity = new THREE.Vector3();
  383. scene.add( sphere );
  384. spheres[ i ] = sphere;
  385. }
  386. }
  387. function sphereDynamics() {
  388. const currentRenderTarget = gpuCompute.getCurrentRenderTarget( heightmapVariable );
  389. readWaterLevelShader.uniforms[ 'levelTexture' ].value = currentRenderTarget.texture;
  390. for ( let i = 0; i < NUM_SPHERES; i ++ ) {
  391. const sphere = spheres[ i ];
  392. if ( sphere ) {
  393. // Read water level and orientation
  394. const u = 0.5 * sphere.position.x / BOUNDS_HALF + 0.5;
  395. const v = 1 - ( 0.5 * sphere.position.z / BOUNDS_HALF + 0.5 );
  396. readWaterLevelShader.uniforms[ 'point1' ].value.set( u, v );
  397. gpuCompute.doRenderTarget( readWaterLevelShader, readWaterLevelRenderTarget );
  398. renderer.readRenderTargetPixels( readWaterLevelRenderTarget, 0, 0, 4, 1, readWaterLevelImage );
  399. const pixels = new Float32Array( readWaterLevelImage.buffer );
  400. // Get orientation
  401. waterNormal.set( pixels[ 1 ], 0, - pixels[ 2 ] );
  402. const pos = sphere.position;
  403. // Set height
  404. pos.y = pixels[ 0 ];
  405. // Move sphere
  406. waterNormal.multiplyScalar( 0.1 );
  407. sphere.userData.velocity.add( waterNormal );
  408. sphere.userData.velocity.multiplyScalar( 0.998 );
  409. pos.add( sphere.userData.velocity );
  410. if ( pos.x < - BOUNDS_HALF ) {
  411. pos.x = - BOUNDS_HALF + 0.001;
  412. sphere.userData.velocity.x *= - 0.3;
  413. } else if ( pos.x > BOUNDS_HALF ) {
  414. pos.x = BOUNDS_HALF - 0.001;
  415. sphere.userData.velocity.x *= - 0.3;
  416. }
  417. if ( pos.z < - BOUNDS_HALF ) {
  418. pos.z = - BOUNDS_HALF + 0.001;
  419. sphere.userData.velocity.z *= - 0.3;
  420. } else if ( pos.z > BOUNDS_HALF ) {
  421. pos.z = BOUNDS_HALF - 0.001;
  422. sphere.userData.velocity.z *= - 0.3;
  423. }
  424. }
  425. }
  426. }
  427. function onWindowResize() {
  428. camera.aspect = window.innerWidth / window.innerHeight;
  429. camera.updateProjectionMatrix();
  430. renderer.setSize( window.innerWidth, window.innerHeight );
  431. }
  432. function setMouseCoords( x, y ) {
  433. mouseCoords.set( ( x / renderer.domElement.clientWidth ) * 2 - 1, - ( y / renderer.domElement.clientHeight ) * 2 + 1 );
  434. mouseMoved = true;
  435. }
  436. function onPointerMove( event ) {
  437. if ( event.isPrimary === false ) return;
  438. setMouseCoords( event.clientX, event.clientY );
  439. }
  440. function animate() {
  441. render();
  442. stats.update();
  443. }
  444. function render() {
  445. // Set uniforms: mouse interaction
  446. const uniforms = heightmapVariable.material.uniforms;
  447. if ( mouseMoved ) {
  448. raycaster.setFromCamera( mouseCoords, camera );
  449. const intersects = raycaster.intersectObject( meshRay );
  450. if ( intersects.length > 0 ) {
  451. const point = intersects[ 0 ].point;
  452. uniforms[ 'mousePos' ].value.set( point.x, point.z );
  453. } else {
  454. uniforms[ 'mousePos' ].value.set( 10000, 10000 );
  455. }
  456. mouseMoved = false;
  457. } else {
  458. uniforms[ 'mousePos' ].value.set( 10000, 10000 );
  459. }
  460. // Do the gpu computation
  461. gpuCompute.compute();
  462. if ( spheresEnabled ) {
  463. sphereDynamics();
  464. }
  465. // Get compute output in custom uniform
  466. waterUniforms[ 'heightmap' ].value = gpuCompute.getCurrentRenderTarget( heightmapVariable ).texture;
  467. // Render
  468. renderer.render( scene, camera );
  469. }
  470. </script>
  471. </body>
  472. </html>