webgl_gpgpu_water.html 21.0 KB
Newer Older
1
 <!DOCTYPE html>
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
<html lang="en">
	<head>
		<title>three.js webgl - gpgpu - water</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<style>
			body {
				background-color: #000000;
				margin: 0px;
				overflow: hidden;
				font-family:Monospace;
				font-size:13px;
				text-align:center;
				text-align:center;
			}

			a {
				color:#0078ff;
			}

			#info {
				color: #ffffff;
				position: absolute;
				top: 10px;
				width: 100%;
			}

		</style>
	</head>
	<body>

		<div id="info">
34
			<a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - <span id="waterSize"></span> webgl gpgpu water<br/>
35 36 37 38 39 40
			Select <span id="options"></span> water size<br/>
			Move mouse to disturb water.<br>
			Press mouse button to orbit around. 'W' key toggles wireframe.
		</div>

		<script src="../build/three.js"></script>
M
Mr.doob 已提交
41
		<script src="js/WebGL.js"></script>
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
		<script src="js/libs/stats.min.js"></script>
		<script src="js/libs/dat.gui.min.js"></script>
		<script src="js/controls/OrbitControls.js"></script>
		<script src="js/SimplexNoise.js"></script>

		<script src="js/GPUComputationRenderer.js"></script>


		<!-- This is the 'compute shader' for the water heightmap: -->
		<script id="heightmapFragmentShader" type="x-shader/x-fragment">

			#include <common>

			uniform vec2 mousePos;
			uniform float mouseSize;
			uniform float viscosityConstant;
Y
yomboprime 已提交
58
			uniform float heightCompensation;
59 60 61 62 63 64 65

			void main()	{

				vec2 cellSize = 1.0 / resolution.xy;

				vec2 uv = gl_FragCoord.xy * cellSize;

66 67
				// heightmapValue.x == height from previous frame
				// heightmapValue.y == height from penultimate frame
68 69 70 71 72 73 74 75 76
				// heightmapValue.z, heightmapValue.w not used
				vec4 heightmapValue = texture2D( heightmap, uv );

				// Get neighbours
				vec4 north = texture2D( heightmap, uv + vec2( 0.0, cellSize.y ) );
				vec4 south = texture2D( heightmap, uv + vec2( 0.0, - cellSize.y ) );
				vec4 east = texture2D( heightmap, uv + vec2( cellSize.x, 0.0 ) );
				vec4 west = texture2D( heightmap, uv + vec2( - cellSize.x, 0.0 ) );

M
Mr.doob 已提交
77 78
				// https://web.archive.org/web/20080618181901/http://freespace.virgin.net/hugo.elias/graphics/x_water.htm

79
				float newHeight = ( ( north.x + south.x + east.x + west.x ) * 0.5 - heightmapValue.y ) * viscosityConstant;
80 81 82

				// Mouse influence
				float mousePhase = clamp( length( ( uv - vec2( 0.5 ) ) * BOUNDS - vec2( mousePos.x, - mousePos.y ) ) * PI / mouseSize, 0.0, PI );
83
				newHeight += ( cos( mousePhase ) + 1.0 ) * 0.28;
M
Mr.doob 已提交
84

85 86
				heightmapValue.y = heightmapValue.x;
				heightmapValue.x = newHeight;
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

				gl_FragColor = heightmapValue;

			}

		</script>

		<!-- This is just a smoothing 'compute shader' for using manually: -->
		<script id="smoothFragmentShader" type="x-shader/x-fragment">

			uniform sampler2D texture;

			void main()	{

				vec2 cellSize = 1.0 / resolution.xy;

				vec2 uv = gl_FragCoord.xy * cellSize;

				// Computes the mean of texel and 4 neighbours
				vec4 textureValue = texture2D( texture, uv );
				textureValue += texture2D( texture, uv + vec2( 0.0, cellSize.y ) );
				textureValue += texture2D( texture, uv + vec2( 0.0, - cellSize.y ) );
				textureValue += texture2D( texture, uv + vec2( cellSize.x, 0.0 ) );
				textureValue += texture2D( texture, uv + vec2( - cellSize.x, 0.0 ) );

				textureValue /= 5.0;

				gl_FragColor = textureValue;

			}

		</script>
M
Mr.doob 已提交
119

120
		<!-- This is a 'compute shader' to read the current level and normal of water at a point -->
Y
yomboprime 已提交
121
		<!-- It is used with a variable of size 1x1 -->
122 123 124
		<script id="readWaterLevelFragmentShader" type="x-shader/x-fragment">

			uniform vec2 point1;
M
Mr.doob 已提交
125

Y
yomboprime 已提交
126
			uniform sampler2D texture;
M
Mr.doob 已提交
127

Y
yomboprime 已提交
128
			// Integer to float conversion from https://stackoverflow.com/questions/17981163/webgl-read-pixels-from-floating-point-render-target
M
Mr.doob 已提交
129

Y
yomboprime 已提交
130
			float shift_right( float v, float amt ) {
131

Y
yomboprime 已提交
132 133
				v = floor( v ) + 0.5;
				return floor( v / exp2( amt ) );
134

Y
yomboprime 已提交
135
			}
136

M
Mr.doob 已提交
137
			float shift_left( float v, float amt ) {
138

Y
yomboprime 已提交
139
				return floor( v * exp2( amt ) + 0.5 );
140

Y
yomboprime 已提交
141
			}
142

Y
yomboprime 已提交
143
			float mask_last( float v, float bits ) {
144

Y
yomboprime 已提交
145
				return mod( v, shift_left( 1.0, bits ) );
146

Y
yomboprime 已提交
147
			}
148

Y
yomboprime 已提交
149
			float extract_bits( float num, float from, float to ) {
150

Y
yomboprime 已提交
151 152
				from = floor( from + 0.5 ); to = floor( to + 0.5 );
				return mask_last( shift_right( num, from ), to - from );
153

Y
yomboprime 已提交
154
			}
155

Y
yomboprime 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
			vec4 encode_float( float val ) {
				if ( val == 0.0 ) return vec4( 0, 0, 0, 0 );
				float sign = val > 0.0 ? 0.0 : 1.0;
				val = abs( val );
				float exponent = floor( log2( val ) );
				float biased_exponent = exponent + 127.0;
				float fraction = ( ( val / exp2( exponent ) ) - 1.0 ) * 8388608.0;
				float t = biased_exponent / 2.0;
				float last_bit_of_biased_exponent = fract( t ) * 2.0;
				float remaining_bits_of_biased_exponent = floor( t );
				float byte4 = extract_bits( fraction, 0.0, 8.0 ) / 255.0;
				float byte3 = extract_bits( fraction, 8.0, 16.0 ) / 255.0;
				float byte2 = ( last_bit_of_biased_exponent * 128.0 + extract_bits( fraction, 16.0, 23.0 ) ) / 255.0;
				float byte1 = ( sign * 128.0 + remaining_bits_of_biased_exponent ) / 255.0;
				return vec4( byte4, byte3, byte2, byte1 );
			}

			void main()	{

175
				vec2 cellSize = 1.0 / resolution.xy;
Y
yomboprime 已提交
176

177 178 179 180 181 182 183 184 185
				float waterLevel = texture2D( texture, point1 ).x;

				vec2 normal = vec2(
					( texture2D( texture, point1 + vec2( - cellSize.x, 0 ) ).x - texture2D( texture, point1 + vec2( cellSize.x, 0 ) ).x ) * WIDTH / BOUNDS,
					( texture2D( texture, point1 + vec2( 0, - cellSize.y ) ).x - texture2D( texture, point1 + vec2( 0, cellSize.y ) ).x ) * WIDTH / BOUNDS );

				if ( gl_FragCoord.x < 1.5 ) {

					gl_FragColor = encode_float( waterLevel );
M
Mr.doob 已提交
186 187

				} else if ( gl_FragCoord.x < 2.5 ) {
188 189 190

					gl_FragColor = encode_float( normal.x );

M
Mr.doob 已提交
191
				} else if ( gl_FragCoord.x < 3.5 ) {
192 193 194

					gl_FragColor = encode_float( normal.y );

M
Mr.doob 已提交
195
				} else {
196 197 198 199

					gl_FragColor = encode_float( 0.0 );

				}
Y
yomboprime 已提交
200 201 202 203

			}

		</script>
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

		<!-- This is the water visualization shader, copied from the MeshPhongMaterial and modified: -->
		<script id="waterVertexShader" type="x-shader/x-vertex">

			uniform sampler2D heightmap;

			#define PHONG

			varying vec3 vViewPosition;

			#ifndef FLAT_SHADED

				varying vec3 vNormal;

			#endif

			#include <common>
			#include <uv_pars_vertex>
			#include <uv2_pars_vertex>
			#include <displacementmap_pars_vertex>
			#include <envmap_pars_vertex>
			#include <color_pars_vertex>
			#include <morphtarget_pars_vertex>
			#include <skinning_pars_vertex>
			#include <shadowmap_pars_vertex>
			#include <logdepthbuf_pars_vertex>
			#include <clipping_planes_pars_vertex>

			void main() {

				vec2 cellSize = vec2( 1.0 / WIDTH, 1.0 / WIDTH );

				#include <uv_vertex>
				#include <uv2_vertex>
				#include <color_vertex>

				// # include <beginnormal_vertex>
				// Compute normal from heightmap
				vec3 objectNormal = vec3(
					( texture2D( heightmap, uv + vec2( - cellSize.x, 0 ) ).x - texture2D( heightmap, uv + vec2( cellSize.x, 0 ) ).x ) * WIDTH / BOUNDS,
					( texture2D( heightmap, uv + vec2( 0, - cellSize.y ) ).x - texture2D( heightmap, uv + vec2( 0, cellSize.y ) ).x ) * WIDTH / BOUNDS,
					1.0 );
				//<beginnormal_vertex>

				#include <morphnormal_vertex>
				#include <skinbase_vertex>
				#include <skinnormal_vertex>
				#include <defaultnormal_vertex>

			#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED

				vNormal = normalize( transformedNormal );

			#endif

				//# include <begin_vertex>
				float heightValue = texture2D( heightmap, uv ).x;
				vec3 transformed = vec3( position.x, position.y, heightValue );
				//<begin_vertex>

				#include <morphtarget_vertex>
				#include <skinning_vertex>
W
WestLangley 已提交
266
				#include <displacementmap_vertex>
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
				#include <project_vertex>
				#include <logdepthbuf_vertex>
				#include <clipping_planes_vertex>

				vViewPosition = - mvPosition.xyz;

				#include <worldpos_vertex>
				#include <envmap_vertex>
				#include <shadowmap_vertex>

			}

		</script>

		<script>

M
Mr.doob 已提交
283 284 285 286 287
			if ( WEBGL.isWebGLAvailable() === false ) {

				document.body.appendChild( WEBGL.getWebGLErrorMessage() );

			}
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311

			var hash = document.location.hash.substr( 1 );
			if ( hash ) hash = parseInt( hash, 0 );

			// Texture width for simulation
			var WIDTH = hash || 128;
			var NUM_TEXELS = WIDTH * WIDTH;

			// Water size in system units
			var BOUNDS = 512;
			var BOUNDS_HALF = BOUNDS * 0.5;

			var container, stats;
			var camera, scene, renderer, controls;
			var mouseMoved = false;
			var mouseCoords = new THREE.Vector2();
			var raycaster = new THREE.Raycaster();

			var waterMesh;
			var meshRay;
			var gpuCompute;
			var heightmapVariable;
			var waterUniforms;
			var smoothShader;
Y
yomboprime 已提交
312 313 314
			var readWaterLevelShader;
			var readWaterLevelRenderTarget;
			var readWaterLevelImage;
315
			var waterNormal = new THREE.Vector3();
M
Mr.doob 已提交
316

317 318 319
			var NUM_SPHERES = 5;
			var spheres = [];
			var spheresEnabled = true;
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396

			var simplex = new SimplexNoise();

			var windowHalfX = window.innerWidth / 2;
			var windowHalfY = window.innerHeight / 2;

			document.getElementById( 'waterSize' ).innerText = WIDTH + ' x ' + WIDTH;

			function change(n) {
				location.hash = n;
				location.reload();
				return false;
			}


			var options = '';
			for ( var i = 4; i < 10; i++ ) {
				var j = Math.pow( 2, i );
				options += '<a href="#" onclick="return change(' + j + ')">' + j + 'x' + j + '</a> ';
			}
			document.getElementById('options').innerHTML = options;

			init();
			animate();

			function init() {

				container = document.createElement( 'div' );
				document.body.appendChild( container );

				camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
				camera.position.set( 0, 200, 350 );

				scene = new THREE.Scene();

				var sun = new THREE.DirectionalLight( 0xFFFFFF, 1.0 );
				sun.position.set( 300, 400, 175 );
				scene.add( sun );

				var sun2 = new THREE.DirectionalLight( 0x40A040, 0.6 );
				sun2.position.set( -100, 350, -200 );
				scene.add( sun2 );

				renderer = new THREE.WebGLRenderer();
				renderer.setPixelRatio( window.devicePixelRatio );
				renderer.setSize( window.innerWidth, window.innerHeight );
				container.appendChild( renderer.domElement );

				controls = new THREE.OrbitControls( camera, renderer.domElement );


				stats = new Stats();
				container.appendChild( stats.dom );

				document.addEventListener( 'mousemove', onDocumentMouseMove, false );
				document.addEventListener( 'touchstart', onDocumentTouchStart, false );
				document.addEventListener( 'touchmove', onDocumentTouchMove, false );

				document.addEventListener( 'keydown', function( event ) {

					// W Pressed: Toggle wireframe
					if ( event.keyCode === 87 ) {

						waterMesh.material.wireframe = ! waterMesh.material.wireframe;
						waterMesh.material.needsUpdate = true;

					}

				} , false );

				window.addEventListener( 'resize', onWindowResize, false );


				var gui = new dat.GUI();

				var effectController = {
					mouseSize: 20.0,
397 398
					viscosity: 0.98,
					spheresEnabled: spheresEnabled
399 400 401 402 403 404
				};

				var valuesChanger = function() {

					heightmapVariable.material.uniforms.mouseSize.value = effectController.mouseSize;
					heightmapVariable.material.uniforms.viscosityConstant.value = effectController.viscosity;
405 406 407 408 409 410
					spheresEnabled = effectController.spheresEnabled;
					for ( var i = 0; i < NUM_SPHERES; i++ ) {
						if ( spheres[ i ] ) {
							spheres[ i ].visible = spheresEnabled;
						}
					}
411 412 413 414

				};

				gui.add( effectController, "mouseSize", 1.0, 100.0, 1.0 ).onChange( valuesChanger );
415 416
				gui.add( effectController, "viscosity", 0.9, 0.999, 0.001 ).onChange( valuesChanger );
				gui.add( effectController, "spheresEnabled", 0, 1, 1 ).onChange( valuesChanger );
417 418
				var buttonSmooth = {
				    smoothWater: function() {
419
						smoothWater();
420 421 422 423 424 425
				    }
				};
				gui.add( buttonSmooth, 'smoothWater' );


				initWater();
M
Mr.doob 已提交
426

427
				createSpheres();
428 429 430 431 432 433 434 435 436 437 438 439 440 441

				valuesChanger();

			}


			function initWater() {

				var materialColor = 0x0040C0;

				var geometry = new THREE.PlaneBufferGeometry( BOUNDS, BOUNDS, WIDTH - 1, WIDTH -1 );

				// material: make a ShaderMaterial clone of MeshPhongMaterial, with customized vertex shader
				var material = new THREE.ShaderMaterial( {
442 443
					uniforms: THREE.UniformsUtils.merge( [
						THREE.ShaderLib[ 'phong' ].uniforms,
444 445
						{
							heightmap: { value: null }
446 447
						}
					] ),
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
					vertexShader: document.getElementById( 'waterVertexShader' ).textContent,
					fragmentShader: THREE.ShaderChunk[ 'meshphong_frag' ]

				} );

				material.lights = true;

				// Material attributes from MeshPhongMaterial
				material.color = new THREE.Color( materialColor );
				material.specular = new THREE.Color( 0x111111 );
				material.shininess = 50;

				// Sets the uniforms with the material values
				material.uniforms.diffuse.value = material.color;
				material.uniforms.specular.value = material.specular;
				material.uniforms.shininess.value = Math.max( material.shininess, 1e-4 );
				material.uniforms.opacity.value = material.opacity;

				// Defines
				material.defines.WIDTH = WIDTH.toFixed( 1 );
				material.defines.BOUNDS = BOUNDS.toFixed( 1 );

				waterUniforms = material.uniforms;

				waterMesh = new THREE.Mesh( geometry, material );
				waterMesh.rotation.x = - Math.PI / 2;
				waterMesh.matrixAutoUpdate = false;
				waterMesh.updateMatrix();

				scene.add( waterMesh );

				// Mesh just for mouse raycasting
				var geometryRay = new THREE.PlaneBufferGeometry( BOUNDS, BOUNDS, 1, 1 );
				meshRay = new THREE.Mesh( geometryRay, new THREE.MeshBasicMaterial( { color: 0xFFFFFF, visible: false } ) );
				meshRay.rotation.x = - Math.PI / 2;
				meshRay.matrixAutoUpdate = false;
				meshRay.updateMatrix();
				scene.add( meshRay );


				// Creates the gpu computation class and sets it up

				gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );

				var heightmap0 = gpuCompute.createTexture();

				fillTexture( heightmap0 );

				heightmapVariable = gpuCompute.addVariable( "heightmap", document.getElementById( 'heightmapFragmentShader' ).textContent, heightmap0 );

				gpuCompute.setVariableDependencies( heightmapVariable, [ heightmapVariable ] );

500 501
				heightmapVariable.material.uniforms.mousePos = { value: new THREE.Vector2( 10000, 10000 ) };
				heightmapVariable.material.uniforms.mouseSize = { value: 20.0 };
502
				heightmapVariable.material.uniforms.viscosityConstant = { value: 0.98 };
Y
yomboprime 已提交
503
				heightmapVariable.material.uniforms.heightCompensation = { value: 0 };
504 505 506 507 508 509 510 511
				heightmapVariable.material.defines.BOUNDS = BOUNDS.toFixed( 1 );

				var error = gpuCompute.init();
				if ( error !== null ) {
				    console.error( error );
				}

				// Create compute shader to smooth the water surface and velocity
512
				smoothShader = gpuCompute.createShaderMaterial( document.getElementById( 'smoothFragmentShader' ).textContent, { texture: { value: null } } );
513

Y
yomboprime 已提交
514
				// Create compute shader to read water level
515 516 517 518 519 520
				readWaterLevelShader = gpuCompute.createShaderMaterial( document.getElementById( 'readWaterLevelFragmentShader' ).textContent, {
					point1: { value: new THREE.Vector2() },
					texture: { value: null }
				} );
				readWaterLevelShader.defines.WIDTH = WIDTH.toFixed( 1 );
				readWaterLevelShader.defines.BOUNDS = BOUNDS.toFixed( 1 );
M
Mr.doob 已提交
521

522 523
				// Create a 4x1 pixel image and a render target (Uint8, 4 channels, 1 byte per channel) to read water height and orientation
				readWaterLevelImage = new Uint8Array( 4 * 1 * 4 );
Y
yomboprime 已提交
524

525
				readWaterLevelRenderTarget = new THREE.WebGLRenderTarget( 4, 1, {
Y
yomboprime 已提交
526 527 528 529 530 531 532 533 534 535
					wrapS: THREE.ClampToEdgeWrapping,
					wrapT: THREE.ClampToEdgeWrapping,
					minFilter: THREE.NearestFilter,
					magFilter: THREE.NearestFilter,
					format: THREE.RGBAFormat,
					type: THREE.UnsignedByteType,
					stencilBuffer: false,
					depthBuffer: false
				} );

536 537 538 539 540 541 542 543 544 545 546
			}

			function fillTexture( texture ) {

				var waterMaxHeight = 10;

				function noise( x, y, z ) {
					var multR = waterMaxHeight;
					var mult = 0.025;
					var r = 0;
					for ( var i = 0; i < 15; i++ ) {
547
						r += multR * simplex.noise( x * mult, y * mult );
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
						multR *= 0.53 + 0.025 * i;
						mult *= 1.25;
					}
					return r;
				}

				var pixels = texture.image.data;

				var p = 0;
				for ( var j = 0; j < WIDTH; j++ ) {
					for ( var i = 0; i < WIDTH; i++ ) {

						var x = i * 128 / WIDTH;
						var y = j * 128 / WIDTH;

563 564
						pixels[ p + 0 ] = noise( x, y, 123.4 );
						pixels[ p + 1 ] = pixels[ p + 0 ];
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
						pixels[ p + 2 ] = 0;
						pixels[ p + 3 ] = 1;

						p += 4;
					}
				}

			}

			function smoothWater() {

				var currentRenderTarget = gpuCompute.getCurrentRenderTarget( heightmapVariable );
				var alternateRenderTarget = gpuCompute.getAlternateRenderTarget( heightmapVariable );

				for ( var i = 0; i < 10; i++ ) {

					smoothShader.uniforms.texture.value = currentRenderTarget.texture;
					gpuCompute.doRenderTarget( smoothShader, alternateRenderTarget );

					smoothShader.uniforms.texture.value = alternateRenderTarget.texture;
					gpuCompute.doRenderTarget( smoothShader, currentRenderTarget );

				}
M
Mr.doob 已提交
588

589 590
			}

591 592 593 594 595 596 597 598 599 600 601 602 603
			function createSpheres() {

				var sphereTemplate = new THREE.Mesh( new THREE.SphereBufferGeometry( 4, 24, 12 ), new THREE.MeshPhongMaterial( { color: 0xFFFF00 } ) );

				for ( var i = 0; i < NUM_SPHERES; i++ ) {

					var sphere = sphereTemplate;
					if ( i < NUM_SPHERES - 1 ) {
						sphere = sphereTemplate.clone();
					}

					sphere.position.x = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
					sphere.position.z = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
M
Mr.doob 已提交
604

605 606 607 608 609 610 611 612 613 614 615
					sphere.userData.velocity = new THREE.Vector3();

					scene.add( sphere );

					spheres[ i ] = sphere;

				}

			}

			function sphereDynamics() {
Y
yomboprime 已提交
616 617 618

				var currentRenderTarget = gpuCompute.getCurrentRenderTarget( heightmapVariable );

Y
yomboprime 已提交
619
				readWaterLevelShader.uniforms.texture.value = currentRenderTarget.texture;
620
				var gl = renderer.context;
Y
yomboprime 已提交
621

622 623 624
				for ( var i = 0; i < NUM_SPHERES; i++ ) {

					var sphere = spheres[ i ];
M
Mr.doob 已提交
625

626 627 628 629 630 631 632 633 634
					if ( sphere ) {

						// Read water level and orientation
						var u = 0.5 * sphere.position.x / BOUNDS_HALF + 0.5;
						var v = 1 - ( 0.5 * sphere.position.z / BOUNDS_HALF + 0.5 );
						readWaterLevelShader.uniforms.point1.value.set( u, v );
						gpuCompute.doRenderTarget( readWaterLevelShader, readWaterLevelRenderTarget );
						gl.readPixels( 0, 0, 4, 1, gl.RGBA, gl.UNSIGNED_BYTE, readWaterLevelImage );
						var pixels = new Float32Array( readWaterLevelImage.buffer );
M
Mr.doob 已提交
635

636 637
						// Get orientation
						waterNormal.set( pixels[ 1 ], 0, - pixels[ 2 ] );
M
Mr.doob 已提交
638

639
						var pos = sphere.position;
M
Mr.doob 已提交
640

641 642
						// Set height
						pos.y = pixels[ 0 ];
M
Mr.doob 已提交
643

644 645 646 647 648
						// Move sphere
						waterNormal.multiplyScalar( 0.1 );
						sphere.userData.velocity.add( waterNormal );
						sphere.userData.velocity.multiplyScalar( 0.998 );
						pos.add( sphere.userData.velocity );
M
Mr.doob 已提交
649

650 651 652 653 654 655 656 657
						if ( pos.x < - BOUNDS_HALF ) {
							pos.x = - BOUNDS_HALF + 0.001;
							sphere.userData.velocity.x *= - 0.3;
						}
						else if ( pos.x > BOUNDS_HALF ) {
							pos.x = BOUNDS_HALF - 0.001;
							sphere.userData.velocity.x *= - 0.3;
						}
Y
yomboprime 已提交
658

659 660 661 662 663 664 665 666
						if ( pos.z < - BOUNDS_HALF ) {
							pos.z = - BOUNDS_HALF + 0.001;
							sphere.userData.velocity.z *= - 0.3;
						}
						else if ( pos.z > BOUNDS_HALF ) {
							pos.z = BOUNDS_HALF - 0.001;
							sphere.userData.velocity.z *= - 0.3;
						}
Y
yomboprime 已提交
667

668
					}
Y
yomboprime 已提交
669

670
				}
Y
yomboprime 已提交
671 672 673

			}

674 675 676 677 678 679 680 681 682 683 684 685 686 687 688

			function onWindowResize() {

				windowHalfX = window.innerWidth / 2;
				windowHalfY = window.innerHeight / 2;

				camera.aspect = window.innerWidth / window.innerHeight;
				camera.updateProjectionMatrix();

				renderer.setSize( window.innerWidth, window.innerHeight );

			}

			function setMouseCoords( x, y ) {

J
Jaume Sanchez 已提交
689
				mouseCoords.set( ( x / renderer.domElement.clientWidth ) * 2 - 1, - ( y / renderer.domElement.clientHeight ) * 2 + 1 );
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
				mouseMoved = true;

			}

			function onDocumentMouseMove( event ) {

				setMouseCoords( event.clientX, event.clientY );

			}

			function onDocumentTouchStart( event ) {

				if ( event.touches.length === 1 ) {

					event.preventDefault();

					setMouseCoords( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );


				}

			}

			function onDocumentTouchMove( event ) {

				if ( event.touches.length === 1 ) {

					event.preventDefault();

					setMouseCoords( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );


				}

			}

			function animate() {

				requestAnimationFrame( animate );

				render();
				stats.update();

			}

			function render() {

				// Set uniforms: mouse interaction
				var uniforms = heightmapVariable.material.uniforms;
				if ( mouseMoved ) {

741
					raycaster.setFromCamera( mouseCoords, camera );
742

743
					var intersects = raycaster.intersectObject( meshRay );
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762

					if ( intersects.length > 0 ) {
					    var point = intersects[ 0 ].point;
					    uniforms.mousePos.value.set( point.x, point.z );

					}
					else {
					    uniforms.mousePos.value.set( 10000, 10000 );
					}

					mouseMoved = false;
				}
				else {
					uniforms.mousePos.value.set( 10000, 10000 );
				}

				// Do the gpu computation
				gpuCompute.compute();

763 764 765 766
				if ( spheresEnabled ) {
					sphereDynamics();
				}

767 768 769 770 771 772 773 774 775 776 777
				// Get compute output in custom uniform
				waterUniforms.heightmap.value = gpuCompute.getCurrentRenderTarget( heightmapVariable ).texture;

				// Render
				renderer.render( scene, camera );

			}

		</script>
	</body>
</html>