webgl_gpgpu_water.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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. <style>
  8. body {
  9. background-color: #000000;
  10. margin: 0px;
  11. overflow: hidden;
  12. font-family:Monospace;
  13. font-size:13px;
  14. text-align:center;
  15. text-align:center;
  16. }
  17. a {
  18. color:#0078ff;
  19. }
  20. #info {
  21. color: #ffffff;
  22. position: absolute;
  23. top: 10px;
  24. width: 100%;
  25. }
  26. </style>
  27. </head>
  28. <body>
  29. <div id="info">
  30. <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - <span id="waterSize"></span> webgl gpgpu water<br/>
  31. Select <span id="options"></span> water size<br/>
  32. Move mouse to disturb water.<br>
  33. Press mouse button to orbit around. 'W' key toggles wireframe.
  34. </div>
  35. <script src="../build/three.js"></script>
  36. <script src="js/WebGL.js"></script>
  37. <script src="js/libs/stats.min.js"></script>
  38. <script src="js/libs/dat.gui.min.js"></script>
  39. <script src="js/controls/OrbitControls.js"></script>
  40. <script src="js/SimplexNoise.js"></script>
  41. <script src="js/GPUComputationRenderer.js"></script>
  42. <!-- This is the 'compute shader' for the water heightmap: -->
  43. <script id="heightmapFragmentShader" type="x-shader/x-fragment">
  44. #include <common>
  45. uniform vec2 mousePos;
  46. uniform float mouseSize;
  47. uniform float viscosityConstant;
  48. #define deltaTime ( 1.0 / 60.0 )
  49. #define GRAVITY_CONSTANT ( resolution.x * deltaTime * 3.0 )
  50. void main() {
  51. vec2 cellSize = 1.0 / resolution.xy;
  52. vec2 uv = gl_FragCoord.xy * cellSize;
  53. // heightmapValue.x == height
  54. // heightmapValue.y == velocity
  55. // heightmapValue.z, heightmapValue.w not used
  56. vec4 heightmapValue = texture2D( heightmap, uv );
  57. // Get neighbours
  58. vec4 north = texture2D( heightmap, uv + vec2( 0.0, cellSize.y ) );
  59. vec4 south = texture2D( heightmap, uv + vec2( 0.0, - cellSize.y ) );
  60. vec4 east = texture2D( heightmap, uv + vec2( cellSize.x, 0.0 ) );
  61. vec4 west = texture2D( heightmap, uv + vec2( - cellSize.x, 0.0 ) );
  62. float sump = north.x + south.x + east.x + west.x - 4.0 * heightmapValue.x;
  63. float accel = sump * GRAVITY_CONSTANT;
  64. // Dynamics
  65. heightmapValue.y += accel;
  66. heightmapValue.x += heightmapValue.y * deltaTime;
  67. // Viscosity
  68. heightmapValue.x += sump * viscosityConstant;
  69. // Mouse influence
  70. float mousePhase = clamp( length( ( uv - vec2( 0.5 ) ) * BOUNDS - vec2( mousePos.x, - mousePos.y ) ) * PI / mouseSize, 0.0, PI );
  71. heightmapValue.x += cos( mousePhase ) + 1.0;
  72. gl_FragColor = heightmapValue;
  73. }
  74. </script>
  75. <!-- This is just a smoothing 'compute shader' for using manually: -->
  76. <script id="smoothFragmentShader" type="x-shader/x-fragment">
  77. uniform sampler2D texture;
  78. void main() {
  79. vec2 cellSize = 1.0 / resolution.xy;
  80. vec2 uv = gl_FragCoord.xy * cellSize;
  81. // Computes the mean of texel and 4 neighbours
  82. vec4 textureValue = texture2D( texture, uv );
  83. textureValue += texture2D( texture, uv + vec2( 0.0, cellSize.y ) );
  84. textureValue += texture2D( texture, uv + vec2( 0.0, - cellSize.y ) );
  85. textureValue += texture2D( texture, uv + vec2( cellSize.x, 0.0 ) );
  86. textureValue += texture2D( texture, uv + vec2( - cellSize.x, 0.0 ) );
  87. textureValue /= 5.0;
  88. gl_FragColor = textureValue;
  89. }
  90. </script>
  91. <!-- This is the water visualization shader, copied from the MeshPhongMaterial and modified: -->
  92. <script id="waterVertexShader" type="x-shader/x-vertex">
  93. uniform sampler2D heightmap;
  94. #define PHONG
  95. varying vec3 vViewPosition;
  96. #ifndef FLAT_SHADED
  97. varying vec3 vNormal;
  98. #endif
  99. #include <common>
  100. #include <uv_pars_vertex>
  101. #include <uv2_pars_vertex>
  102. #include <displacementmap_pars_vertex>
  103. #include <envmap_pars_vertex>
  104. #include <color_pars_vertex>
  105. #include <morphtarget_pars_vertex>
  106. #include <skinning_pars_vertex>
  107. #include <shadowmap_pars_vertex>
  108. #include <logdepthbuf_pars_vertex>
  109. #include <clipping_planes_pars_vertex>
  110. void main() {
  111. vec2 cellSize = vec2( 1.0 / WIDTH, 1.0 / WIDTH );
  112. #include <uv_vertex>
  113. #include <uv2_vertex>
  114. #include <color_vertex>
  115. // # include <beginnormal_vertex>
  116. // Compute normal from heightmap
  117. vec3 objectNormal = vec3(
  118. ( texture2D( heightmap, uv + vec2( - cellSize.x, 0 ) ).x - texture2D( heightmap, uv + vec2( cellSize.x, 0 ) ).x ) * WIDTH / BOUNDS,
  119. ( texture2D( heightmap, uv + vec2( 0, - cellSize.y ) ).x - texture2D( heightmap, uv + vec2( 0, cellSize.y ) ).x ) * WIDTH / BOUNDS,
  120. 1.0 );
  121. //<beginnormal_vertex>
  122. #include <morphnormal_vertex>
  123. #include <skinbase_vertex>
  124. #include <skinnormal_vertex>
  125. #include <defaultnormal_vertex>
  126. #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED
  127. vNormal = normalize( transformedNormal );
  128. #endif
  129. //# include <begin_vertex>
  130. float heightValue = texture2D( heightmap, uv ).x;
  131. vec3 transformed = vec3( position.x, position.y, heightValue );
  132. //<begin_vertex>
  133. #include <morphtarget_vertex>
  134. #include <skinning_vertex>
  135. #include <displacementmap_vertex>
  136. #include <project_vertex>
  137. #include <logdepthbuf_vertex>
  138. #include <clipping_planes_vertex>
  139. vViewPosition = - mvPosition.xyz;
  140. #include <worldpos_vertex>
  141. #include <envmap_vertex>
  142. #include <shadowmap_vertex>
  143. }
  144. </script>
  145. <script>
  146. if ( WEBGL.isWebGLAvailable() === false ) {
  147. document.body.appendChild( WEBGL.getWebGLErrorMessage() );
  148. }
  149. var hash = document.location.hash.substr( 1 );
  150. if ( hash ) hash = parseInt( hash, 0 );
  151. // Texture width for simulation
  152. var WIDTH = hash || 128;
  153. var NUM_TEXELS = WIDTH * WIDTH;
  154. // Water size in system units
  155. var BOUNDS = 512;
  156. var BOUNDS_HALF = BOUNDS * 0.5;
  157. var container, stats;
  158. var camera, scene, renderer, controls;
  159. var mouseMoved = false;
  160. var mouseCoords = new THREE.Vector2();
  161. var raycaster = new THREE.Raycaster();
  162. var waterMesh;
  163. var meshRay;
  164. var gpuCompute;
  165. var heightmapVariable;
  166. var waterUniforms;
  167. var smoothShader;
  168. var simplex = new SimplexNoise();
  169. var windowHalfX = window.innerWidth / 2;
  170. var windowHalfY = window.innerHeight / 2;
  171. document.getElementById( 'waterSize' ).innerText = WIDTH + ' x ' + WIDTH;
  172. function change(n) {
  173. location.hash = n;
  174. location.reload();
  175. return false;
  176. }
  177. var options = '';
  178. for ( var i = 4; i < 10; i++ ) {
  179. var j = Math.pow( 2, i );
  180. options += '<a href="#" onclick="return change(' + j + ')">' + j + 'x' + j + '</a> ';
  181. }
  182. document.getElementById('options').innerHTML = options;
  183. init();
  184. animate();
  185. function init() {
  186. container = document.createElement( 'div' );
  187. document.body.appendChild( container );
  188. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  189. camera.position.set( 0, 200, 350 );
  190. scene = new THREE.Scene();
  191. var sun = new THREE.DirectionalLight( 0xFFFFFF, 1.0 );
  192. sun.position.set( 300, 400, 175 );
  193. scene.add( sun );
  194. var sun2 = new THREE.DirectionalLight( 0x40A040, 0.6 );
  195. sun2.position.set( -100, 350, -200 );
  196. scene.add( sun2 );
  197. renderer = new THREE.WebGLRenderer();
  198. renderer.setPixelRatio( window.devicePixelRatio );
  199. renderer.setSize( window.innerWidth, window.innerHeight );
  200. container.appendChild( renderer.domElement );
  201. controls = new THREE.OrbitControls( camera, renderer.domElement );
  202. stats = new Stats();
  203. container.appendChild( stats.dom );
  204. document.addEventListener( 'mousemove', onDocumentMouseMove, false );
  205. document.addEventListener( 'touchstart', onDocumentTouchStart, false );
  206. document.addEventListener( 'touchmove', onDocumentTouchMove, false );
  207. document.addEventListener( 'keydown', function( event ) {
  208. // W Pressed: Toggle wireframe
  209. if ( event.keyCode === 87 ) {
  210. waterMesh.material.wireframe = ! waterMesh.material.wireframe;
  211. waterMesh.material.needsUpdate = true;
  212. }
  213. } , false );
  214. window.addEventListener( 'resize', onWindowResize, false );
  215. var gui = new dat.GUI();
  216. var effectController = {
  217. mouseSize: 20.0,
  218. viscosity: 0.03
  219. };
  220. var valuesChanger = function() {
  221. heightmapVariable.material.uniforms.mouseSize.value = effectController.mouseSize;
  222. heightmapVariable.material.uniforms.viscosityConstant.value = effectController.viscosity;
  223. };
  224. gui.add( effectController, "mouseSize", 1.0, 100.0, 1.0 ).onChange( valuesChanger );
  225. gui.add( effectController, "viscosity", 0.0, 0.1, 0.001 ).onChange( valuesChanger );
  226. var buttonSmooth = {
  227. smoothWater: function() {
  228. smoothWater();
  229. }
  230. };
  231. gui.add( buttonSmooth, 'smoothWater' );
  232. initWater();
  233. valuesChanger();
  234. }
  235. function initWater() {
  236. var materialColor = 0x0040C0;
  237. var geometry = new THREE.PlaneBufferGeometry( BOUNDS, BOUNDS, WIDTH - 1, WIDTH -1 );
  238. // material: make a ShaderMaterial clone of MeshPhongMaterial, with customized vertex shader
  239. var material = new THREE.ShaderMaterial( {
  240. uniforms: THREE.UniformsUtils.merge( [
  241. THREE.ShaderLib[ 'phong' ].uniforms,
  242. {
  243. heightmap: { value: null }
  244. }
  245. ] ),
  246. vertexShader: document.getElementById( 'waterVertexShader' ).textContent,
  247. fragmentShader: THREE.ShaderChunk[ 'meshphong_frag' ]
  248. } );
  249. material.lights = true;
  250. // Material attributes from MeshPhongMaterial
  251. material.color = new THREE.Color( materialColor );
  252. material.specular = new THREE.Color( 0x111111 );
  253. material.shininess = 50;
  254. // Sets the uniforms with the material values
  255. material.uniforms.diffuse.value = material.color;
  256. material.uniforms.specular.value = material.specular;
  257. material.uniforms.shininess.value = Math.max( material.shininess, 1e-4 );
  258. material.uniforms.opacity.value = material.opacity;
  259. // Defines
  260. material.defines.WIDTH = WIDTH.toFixed( 1 );
  261. material.defines.BOUNDS = BOUNDS.toFixed( 1 );
  262. waterUniforms = material.uniforms;
  263. waterMesh = new THREE.Mesh( geometry, material );
  264. waterMesh.rotation.x = - Math.PI / 2;
  265. waterMesh.matrixAutoUpdate = false;
  266. waterMesh.updateMatrix();
  267. scene.add( waterMesh );
  268. // Mesh just for mouse raycasting
  269. var geometryRay = new THREE.PlaneBufferGeometry( BOUNDS, BOUNDS, 1, 1 );
  270. meshRay = new THREE.Mesh( geometryRay, new THREE.MeshBasicMaterial( { color: 0xFFFFFF, visible: false } ) );
  271. meshRay.rotation.x = - Math.PI / 2;
  272. meshRay.matrixAutoUpdate = false;
  273. meshRay.updateMatrix();
  274. scene.add( meshRay );
  275. // Creates the gpu computation class and sets it up
  276. gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );
  277. var heightmap0 = gpuCompute.createTexture();
  278. fillTexture( heightmap0 );
  279. heightmapVariable = gpuCompute.addVariable( "heightmap", document.getElementById( 'heightmapFragmentShader' ).textContent, heightmap0 );
  280. gpuCompute.setVariableDependencies( heightmapVariable, [ heightmapVariable ] );
  281. heightmapVariable.material.uniforms.mousePos = { value: new THREE.Vector2( 10000, 10000 ) };
  282. heightmapVariable.material.uniforms.mouseSize = { value: 20.0 };
  283. heightmapVariable.material.uniforms.viscosityConstant = { value: 0.03 };
  284. heightmapVariable.material.defines.BOUNDS = BOUNDS.toFixed( 1 );
  285. var error = gpuCompute.init();
  286. if ( error !== null ) {
  287. console.error( error );
  288. }
  289. // Create compute shader to smooth the water surface and velocity
  290. smoothShader = gpuCompute.createShaderMaterial( document.getElementById( 'smoothFragmentShader' ).textContent, { texture: { value: null } } );
  291. }
  292. function fillTexture( texture ) {
  293. var waterMaxHeight = 10;
  294. function noise( x, y, z ) {
  295. var multR = waterMaxHeight;
  296. var mult = 0.025;
  297. var r = 0;
  298. for ( var i = 0; i < 15; i++ ) {
  299. r += multR * simplex.noise( x * mult, y * mult );
  300. multR *= 0.53 + 0.025 * i;
  301. mult *= 1.25;
  302. }
  303. return r;
  304. }
  305. var pixels = texture.image.data;
  306. var p = 0;
  307. for ( var j = 0; j < WIDTH; j++ ) {
  308. for ( var i = 0; i < WIDTH; i++ ) {
  309. var x = i * 128 / WIDTH;
  310. var y = j * 128 / WIDTH;
  311. pixels[ p + 0 ] = noise( x, y, 123.4 );
  312. pixels[ p + 1 ] = 0;
  313. pixels[ p + 2 ] = 0;
  314. pixels[ p + 3 ] = 1;
  315. p += 4;
  316. }
  317. }
  318. }
  319. function smoothWater() {
  320. var currentRenderTarget = gpuCompute.getCurrentRenderTarget( heightmapVariable );
  321. var alternateRenderTarget = gpuCompute.getAlternateRenderTarget( heightmapVariable );
  322. for ( var i = 0; i < 10; i++ ) {
  323. smoothShader.uniforms.texture.value = currentRenderTarget.texture;
  324. gpuCompute.doRenderTarget( smoothShader, alternateRenderTarget );
  325. smoothShader.uniforms.texture.value = alternateRenderTarget.texture;
  326. gpuCompute.doRenderTarget( smoothShader, currentRenderTarget );
  327. }
  328. }
  329. function onWindowResize() {
  330. windowHalfX = window.innerWidth / 2;
  331. windowHalfY = window.innerHeight / 2;
  332. camera.aspect = window.innerWidth / window.innerHeight;
  333. camera.updateProjectionMatrix();
  334. renderer.setSize( window.innerWidth, window.innerHeight );
  335. }
  336. function setMouseCoords( x, y ) {
  337. mouseCoords.set( ( x / renderer.domElement.clientWidth ) * 2 - 1, - ( y / renderer.domElement.clientHeight ) * 2 + 1 );
  338. mouseMoved = true;
  339. }
  340. function onDocumentMouseMove( event ) {
  341. setMouseCoords( event.clientX, event.clientY );
  342. }
  343. function onDocumentTouchStart( event ) {
  344. if ( event.touches.length === 1 ) {
  345. event.preventDefault();
  346. setMouseCoords( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  347. }
  348. }
  349. function onDocumentTouchMove( event ) {
  350. if ( event.touches.length === 1 ) {
  351. event.preventDefault();
  352. setMouseCoords( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  353. }
  354. }
  355. function animate() {
  356. requestAnimationFrame( animate );
  357. render();
  358. stats.update();
  359. }
  360. function render() {
  361. // Set uniforms: mouse interaction
  362. var uniforms = heightmapVariable.material.uniforms;
  363. if ( mouseMoved ) {
  364. raycaster.setFromCamera( mouseCoords, camera );
  365. var intersects = raycaster.intersectObject( meshRay );
  366. if ( intersects.length > 0 ) {
  367. var point = intersects[ 0 ].point;
  368. uniforms.mousePos.value.set( point.x, point.z );
  369. }
  370. else {
  371. uniforms.mousePos.value.set( 10000, 10000 );
  372. }
  373. mouseMoved = false;
  374. }
  375. else {
  376. uniforms.mousePos.value.set( 10000, 10000 );
  377. }
  378. // Do the gpu computation
  379. gpuCompute.compute();
  380. // Get compute output in custom uniform
  381. waterUniforms.heightmap.value = gpuCompute.getCurrentRenderTarget( heightmapVariable ).texture;
  382. // Render
  383. renderer.render( scene, camera );
  384. }
  385. </script>
  386. </body>
  387. </html>