webgl_gpgpu_water.html 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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="http://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. Press mouse button to orbit around. '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 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 <uv2_pars_vertex>
  124. #include <displacementmap_pars_vertex>
  125. #include <envmap_pars_vertex>
  126. #include <color_pars_vertex>
  127. #include <morphtarget_pars_vertex>
  128. #include <skinning_pars_vertex>
  129. #include <shadowmap_pars_vertex>
  130. #include <logdepthbuf_pars_vertex>
  131. #include <clipping_planes_pars_vertex>
  132. void main() {
  133. vec2 cellSize = vec2( 1.0 / WIDTH, 1.0 / WIDTH );
  134. #include <uv_vertex>
  135. #include <uv2_vertex>
  136. #include <color_vertex>
  137. // # include <beginnormal_vertex>
  138. // Compute normal from heightmap
  139. vec3 objectNormal = vec3(
  140. ( texture2D( heightmap, uv + vec2( - cellSize.x, 0 ) ).x - texture2D( heightmap, uv + vec2( cellSize.x, 0 ) ).x ) * WIDTH / BOUNDS,
  141. ( texture2D( heightmap, uv + vec2( 0, - cellSize.y ) ).x - texture2D( heightmap, uv + vec2( 0, cellSize.y ) ).x ) * WIDTH / BOUNDS,
  142. 1.0 );
  143. //<beginnormal_vertex>
  144. #include <morphnormal_vertex>
  145. #include <skinbase_vertex>
  146. #include <skinnormal_vertex>
  147. #include <defaultnormal_vertex>
  148. #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED
  149. vNormal = normalize( transformedNormal );
  150. #endif
  151. //# include <begin_vertex>
  152. float heightValue = texture2D( heightmap, uv ).x;
  153. vec3 transformed = vec3( position.x, position.y, heightValue );
  154. //<begin_vertex>
  155. #include <morphtarget_vertex>
  156. #include <skinning_vertex>
  157. #include <displacementmap_vertex>
  158. #include <project_vertex>
  159. #include <logdepthbuf_vertex>
  160. #include <clipping_planes_vertex>
  161. vViewPosition = - mvPosition.xyz;
  162. #include <worldpos_vertex>
  163. #include <envmap_vertex>
  164. #include <shadowmap_vertex>
  165. }
  166. </script>
  167. <script type="module">
  168. import {
  169. ClampToEdgeWrapping,
  170. Color,
  171. DirectionalLight,
  172. Mesh,
  173. MeshBasicMaterial,
  174. MeshPhongMaterial,
  175. NearestFilter,
  176. PerspectiveCamera,
  177. PlaneBufferGeometry,
  178. Raycaster,
  179. RGBAFormat,
  180. Scene,
  181. ShaderChunk,
  182. ShaderLib,
  183. ShaderMaterial,
  184. SphereBufferGeometry,
  185. UniformsUtils,
  186. UnsignedByteType,
  187. Vector2,
  188. Vector3,
  189. WebGLRenderer,
  190. WebGLRenderTarget,
  191. } from "../build/three.module.js";
  192. import Stats from './jsm/libs/stats.module.js';
  193. import { GUI } from './jsm/libs/dat.gui.module.js';
  194. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  195. import { GPUComputationRenderer } from './jsm/misc/GPUComputationRenderer.js';
  196. import { SimplexNoise } from './jsm/math/SimplexNoise.js';
  197. // Texture width for simulation
  198. var WIDTH = 128;
  199. // Water size in system units
  200. var BOUNDS = 512;
  201. var BOUNDS_HALF = BOUNDS * 0.5;
  202. var container, stats;
  203. var camera, scene, renderer;
  204. var mouseMoved = false;
  205. var mouseCoords = new Vector2();
  206. var raycaster = new Raycaster();
  207. var waterMesh;
  208. var meshRay;
  209. var gpuCompute;
  210. var heightmapVariable;
  211. var waterUniforms;
  212. var smoothShader;
  213. var readWaterLevelShader;
  214. var readWaterLevelRenderTarget;
  215. var readWaterLevelImage;
  216. var waterNormal = new Vector3();
  217. var NUM_SPHERES = 5;
  218. var spheres = [];
  219. var spheresEnabled = true;
  220. var simplex = new SimplexNoise();
  221. init();
  222. animate();
  223. function init() {
  224. container = document.createElement( 'div' );
  225. document.body.appendChild( container );
  226. camera = new PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  227. camera.position.set( 0, 200, 350 );
  228. scene = new Scene();
  229. var sun = new DirectionalLight( 0xFFFFFF, 1.0 );
  230. sun.position.set( 300, 400, 175 );
  231. scene.add( sun );
  232. var sun2 = new DirectionalLight( 0x40A040, 0.6 );
  233. sun2.position.set( - 100, 350, - 200 );
  234. scene.add( sun2 );
  235. renderer = new WebGLRenderer();
  236. renderer.setPixelRatio( window.devicePixelRatio );
  237. renderer.setSize( window.innerWidth, window.innerHeight );
  238. container.appendChild( renderer.domElement );
  239. var controls = new OrbitControls( camera, renderer.domElement );
  240. stats = new Stats();
  241. container.appendChild( stats.dom );
  242. document.addEventListener( 'mousemove', onDocumentMouseMove, false );
  243. document.addEventListener( 'touchstart', onDocumentTouchStart, false );
  244. document.addEventListener( 'touchmove', onDocumentTouchMove, false );
  245. document.addEventListener( 'keydown', function ( event ) {
  246. // W Pressed: Toggle wireframe
  247. if ( event.keyCode === 87 ) {
  248. waterMesh.material.wireframe = ! waterMesh.material.wireframe;
  249. waterMesh.material.needsUpdate = true;
  250. }
  251. }, false );
  252. window.addEventListener( 'resize', onWindowResize, false );
  253. var gui = new GUI();
  254. var effectController = {
  255. mouseSize: 20.0,
  256. viscosity: 0.98,
  257. spheresEnabled: spheresEnabled
  258. };
  259. var valuesChanger = function () {
  260. heightmapVariable.material.uniforms[ "mouseSize" ].value = effectController.mouseSize;
  261. heightmapVariable.material.uniforms[ "viscosityConstant" ].value = effectController.viscosity;
  262. spheresEnabled = effectController.spheresEnabled;
  263. for ( var i = 0; i < NUM_SPHERES; i ++ ) {
  264. if ( spheres[ i ] ) {
  265. spheres[ i ].visible = spheresEnabled;
  266. }
  267. }
  268. };
  269. gui.add( effectController, "mouseSize", 1.0, 100.0, 1.0 ).onChange( valuesChanger );
  270. gui.add( effectController, "viscosity", 0.9, 0.999, 0.001 ).onChange( valuesChanger );
  271. gui.add( effectController, "spheresEnabled", 0, 1, 1 ).onChange( valuesChanger );
  272. var buttonSmooth = {
  273. smoothWater: function () {
  274. smoothWater();
  275. }
  276. };
  277. gui.add( buttonSmooth, 'smoothWater' );
  278. initWater();
  279. createSpheres();
  280. valuesChanger();
  281. }
  282. function initWater() {
  283. var materialColor = 0x0040C0;
  284. var geometry = new PlaneBufferGeometry( BOUNDS, BOUNDS, WIDTH - 1, WIDTH - 1 );
  285. // material: make a ShaderMaterial clone of MeshPhongMaterial, with customized vertex shader
  286. var material = new ShaderMaterial( {
  287. uniforms: UniformsUtils.merge( [
  288. ShaderLib[ 'phong' ].uniforms,
  289. {
  290. "heightmap": { value: null }
  291. }
  292. ] ),
  293. vertexShader: document.getElementById( 'waterVertexShader' ).textContent,
  294. fragmentShader: ShaderChunk[ 'meshphong_frag' ]
  295. } );
  296. material.lights = true;
  297. // Material attributes from MeshPhongMaterial
  298. material.color = new Color( materialColor );
  299. material.specular = new Color( 0x111111 );
  300. material.shininess = 50;
  301. // Sets the uniforms with the material values
  302. material.uniforms[ "diffuse" ].value = material.color;
  303. material.uniforms[ "specular" ].value = material.specular;
  304. material.uniforms[ "shininess" ].value = Math.max( material.shininess, 1e-4 );
  305. material.uniforms[ "opacity" ].value = material.opacity;
  306. // Defines
  307. material.defines.WIDTH = WIDTH.toFixed( 1 );
  308. material.defines.BOUNDS = BOUNDS.toFixed( 1 );
  309. waterUniforms = material.uniforms;
  310. waterMesh = new Mesh( geometry, material );
  311. waterMesh.rotation.x = - Math.PI / 2;
  312. waterMesh.matrixAutoUpdate = false;
  313. waterMesh.updateMatrix();
  314. scene.add( waterMesh );
  315. // Mesh just for mouse raycasting
  316. var geometryRay = new PlaneBufferGeometry( BOUNDS, BOUNDS, 1, 1 );
  317. meshRay = new Mesh( geometryRay, new MeshBasicMaterial( { color: 0xFFFFFF, visible: false } ) );
  318. meshRay.rotation.x = - Math.PI / 2;
  319. meshRay.matrixAutoUpdate = false;
  320. meshRay.updateMatrix();
  321. scene.add( meshRay );
  322. // Creates the gpu computation class and sets it up
  323. gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );
  324. var heightmap0 = gpuCompute.createTexture();
  325. fillTexture( heightmap0 );
  326. heightmapVariable = gpuCompute.addVariable( "heightmap", document.getElementById( 'heightmapFragmentShader' ).textContent, heightmap0 );
  327. gpuCompute.setVariableDependencies( heightmapVariable, [ heightmapVariable ] );
  328. heightmapVariable.material.uniforms[ "mousePos" ] = { value: new Vector2( 10000, 10000 ) };
  329. heightmapVariable.material.uniforms[ "mouseSize" ] = { value: 20.0 };
  330. heightmapVariable.material.uniforms[ "viscosityConstant" ] = { value: 0.98 };
  331. heightmapVariable.material.uniforms[ "heightCompensation" ] = { value: 0 };
  332. heightmapVariable.material.defines.BOUNDS = BOUNDS.toFixed( 1 );
  333. var error = gpuCompute.init();
  334. if ( error !== null ) {
  335. console.error( error );
  336. }
  337. // Create compute shader to smooth the water surface and velocity
  338. smoothShader = gpuCompute.createShaderMaterial( document.getElementById( 'smoothFragmentShader' ).textContent, { smoothTexture: { value: null } } );
  339. // Create compute shader to read water level
  340. readWaterLevelShader = gpuCompute.createShaderMaterial( document.getElementById( 'readWaterLevelFragmentShader' ).textContent, {
  341. point1: { value: new Vector2() },
  342. levelTexture: { value: null }
  343. } );
  344. readWaterLevelShader.defines.WIDTH = WIDTH.toFixed( 1 );
  345. readWaterLevelShader.defines.BOUNDS = BOUNDS.toFixed( 1 );
  346. // Create a 4x1 pixel image and a render target (Uint8, 4 channels, 1 byte per channel) to read water height and orientation
  347. readWaterLevelImage = new Uint8Array( 4 * 1 * 4 );
  348. readWaterLevelRenderTarget = new WebGLRenderTarget( 4, 1, {
  349. wrapS: ClampToEdgeWrapping,
  350. wrapT: ClampToEdgeWrapping,
  351. minFilter: NearestFilter,
  352. magFilter: NearestFilter,
  353. format: RGBAFormat,
  354. type: UnsignedByteType,
  355. stencilBuffer: false,
  356. depthBuffer: false
  357. } );
  358. }
  359. function fillTexture( texture ) {
  360. var waterMaxHeight = 10;
  361. function noise( x, y ) {
  362. var multR = waterMaxHeight;
  363. var mult = 0.025;
  364. var r = 0;
  365. for ( var i = 0; i < 15; i ++ ) {
  366. r += multR * simplex.noise( x * mult, y * mult );
  367. multR *= 0.53 + 0.025 * i;
  368. mult *= 1.25;
  369. }
  370. return r;
  371. }
  372. var pixels = texture.image.data;
  373. var p = 0;
  374. for ( var j = 0; j < WIDTH; j ++ ) {
  375. for ( var i = 0; i < WIDTH; i ++ ) {
  376. var x = i * 128 / WIDTH;
  377. var y = j * 128 / WIDTH;
  378. pixels[ p + 0 ] = noise( x, y, 123.4 );
  379. pixels[ p + 1 ] = pixels[ p + 0 ];
  380. pixels[ p + 2 ] = 0;
  381. pixels[ p + 3 ] = 1;
  382. p += 4;
  383. }
  384. }
  385. }
  386. function smoothWater() {
  387. var currentRenderTarget = gpuCompute.getCurrentRenderTarget( heightmapVariable );
  388. var alternateRenderTarget = gpuCompute.getAlternateRenderTarget( heightmapVariable );
  389. for ( var i = 0; i < 10; i ++ ) {
  390. smoothShader.uniforms[ "smoothTexture" ].value = currentRenderTarget.texture;
  391. gpuCompute.doRenderTarget( smoothShader, alternateRenderTarget );
  392. smoothShader.uniforms[ "smoothTexture" ].value = alternateRenderTarget.texture;
  393. gpuCompute.doRenderTarget( smoothShader, currentRenderTarget );
  394. }
  395. }
  396. function createSpheres() {
  397. var sphereTemplate = new Mesh( new SphereBufferGeometry( 4, 24, 12 ), new MeshPhongMaterial( { color: 0xFFFF00 } ) );
  398. for ( var i = 0; i < NUM_SPHERES; i ++ ) {
  399. var sphere = sphereTemplate;
  400. if ( i < NUM_SPHERES - 1 ) {
  401. sphere = sphereTemplate.clone();
  402. }
  403. sphere.position.x = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  404. sphere.position.z = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  405. sphere.userData.velocity = new Vector3();
  406. scene.add( sphere );
  407. spheres[ i ] = sphere;
  408. }
  409. }
  410. function sphereDynamics() {
  411. var currentRenderTarget = gpuCompute.getCurrentRenderTarget( heightmapVariable );
  412. readWaterLevelShader.uniforms[ "levelTexture" ].value = currentRenderTarget.texture;
  413. for ( var i = 0; i < NUM_SPHERES; i ++ ) {
  414. var sphere = spheres[ i ];
  415. if ( sphere ) {
  416. // Read water level and orientation
  417. var u = 0.5 * sphere.position.x / BOUNDS_HALF + 0.5;
  418. var v = 1 - ( 0.5 * sphere.position.z / BOUNDS_HALF + 0.5 );
  419. readWaterLevelShader.uniforms[ "point1" ].value.set( u, v );
  420. gpuCompute.doRenderTarget( readWaterLevelShader, readWaterLevelRenderTarget );
  421. renderer.readRenderTargetPixels( readWaterLevelRenderTarget, 0, 0, 4, 1, readWaterLevelImage );
  422. var pixels = new Float32Array( readWaterLevelImage.buffer );
  423. // Get orientation
  424. waterNormal.set( pixels[ 1 ], 0, - pixels[ 2 ] );
  425. var pos = sphere.position;
  426. // Set height
  427. pos.y = pixels[ 0 ];
  428. // Move sphere
  429. waterNormal.multiplyScalar( 0.1 );
  430. sphere.userData.velocity.add( waterNormal );
  431. sphere.userData.velocity.multiplyScalar( 0.998 );
  432. pos.add( sphere.userData.velocity );
  433. if ( pos.x < - BOUNDS_HALF ) {
  434. pos.x = - BOUNDS_HALF + 0.001;
  435. sphere.userData.velocity.x *= - 0.3;
  436. } else if ( pos.x > BOUNDS_HALF ) {
  437. pos.x = BOUNDS_HALF - 0.001;
  438. sphere.userData.velocity.x *= - 0.3;
  439. }
  440. if ( pos.z < - BOUNDS_HALF ) {
  441. pos.z = - BOUNDS_HALF + 0.001;
  442. sphere.userData.velocity.z *= - 0.3;
  443. } else if ( pos.z > BOUNDS_HALF ) {
  444. pos.z = BOUNDS_HALF - 0.001;
  445. sphere.userData.velocity.z *= - 0.3;
  446. }
  447. }
  448. }
  449. }
  450. function onWindowResize() {
  451. camera.aspect = window.innerWidth / window.innerHeight;
  452. camera.updateProjectionMatrix();
  453. renderer.setSize( window.innerWidth, window.innerHeight );
  454. }
  455. function setMouseCoords( x, y ) {
  456. mouseCoords.set( ( x / renderer.domElement.clientWidth ) * 2 - 1, - ( y / renderer.domElement.clientHeight ) * 2 + 1 );
  457. mouseMoved = true;
  458. }
  459. function onDocumentMouseMove( event ) {
  460. setMouseCoords( event.clientX, event.clientY );
  461. }
  462. function onDocumentTouchStart( event ) {
  463. if ( event.touches.length === 1 ) {
  464. event.preventDefault();
  465. setMouseCoords( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  466. }
  467. }
  468. function onDocumentTouchMove( event ) {
  469. if ( event.touches.length === 1 ) {
  470. event.preventDefault();
  471. setMouseCoords( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  472. }
  473. }
  474. function animate() {
  475. requestAnimationFrame( animate );
  476. render();
  477. stats.update();
  478. }
  479. function render() {
  480. // Set uniforms: mouse interaction
  481. var uniforms = heightmapVariable.material.uniforms;
  482. if ( mouseMoved ) {
  483. raycaster.setFromCamera( mouseCoords, camera );
  484. var intersects = raycaster.intersectObject( meshRay );
  485. if ( intersects.length > 0 ) {
  486. var point = intersects[ 0 ].point;
  487. uniforms[ "mousePos" ].value.set( point.x, point.z );
  488. } else {
  489. uniforms[ "mousePos" ].value.set( 10000, 10000 );
  490. }
  491. mouseMoved = false;
  492. } else {
  493. uniforms[ "mousePos" ].value.set( 10000, 10000 );
  494. }
  495. // Do the gpu computation
  496. gpuCompute.compute();
  497. if ( spheresEnabled ) {
  498. sphereDynamics();
  499. }
  500. // Get compute output in custom uniform
  501. waterUniforms[ "heightmap" ].value = gpuCompute.getCurrentRenderTarget( heightmapVariable ).texture;
  502. // Render
  503. renderer.render( scene, camera );
  504. }
  505. </script>
  506. </body>
  507. </html>