webgl_gpgpu_water.html 21 KB

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