webgl_gpgpu_water.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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/Detector.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 ( ! Detector.webgl ) Detector.addGetWebGLMessage();
  147. var hash = document.location.hash.substr( 1 );
  148. if ( hash ) hash = parseInt( hash, 0 );
  149. // Texture width for simulation
  150. var WIDTH = hash || 128;
  151. var NUM_TEXELS = WIDTH * WIDTH;
  152. // Water size in system units
  153. var BOUNDS = 512;
  154. var BOUNDS_HALF = BOUNDS * 0.5;
  155. var container, stats;
  156. var camera, scene, renderer, controls;
  157. var mouseMoved = false;
  158. var mouseCoords = new THREE.Vector2();
  159. var raycaster = new THREE.Raycaster();
  160. var waterMesh;
  161. var meshRay;
  162. var gpuCompute;
  163. var heightmapVariable;
  164. var waterUniforms;
  165. var smoothShader;
  166. var simplex = new SimplexNoise();
  167. var windowHalfX = window.innerWidth / 2;
  168. var windowHalfY = window.innerHeight / 2;
  169. document.getElementById( 'waterSize' ).innerText = WIDTH + ' x ' + WIDTH;
  170. function change(n) {
  171. location.hash = n;
  172. location.reload();
  173. return false;
  174. }
  175. var options = '';
  176. for ( var i = 4; i < 10; i++ ) {
  177. var j = Math.pow( 2, i );
  178. options += '<a href="#" onclick="return change(' + j + ')">' + j + 'x' + j + '</a> ';
  179. }
  180. document.getElementById('options').innerHTML = options;
  181. init();
  182. animate();
  183. function init() {
  184. container = document.createElement( 'div' );
  185. document.body.appendChild( container );
  186. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  187. camera.position.set( 0, 200, 350 );
  188. scene = new THREE.Scene();
  189. var sun = new THREE.DirectionalLight( 0xFFFFFF, 1.0 );
  190. sun.position.set( 300, 400, 175 );
  191. scene.add( sun );
  192. var sun2 = new THREE.DirectionalLight( 0x40A040, 0.6 );
  193. sun2.position.set( -100, 350, -200 );
  194. scene.add( sun2 );
  195. renderer = new THREE.WebGLRenderer();
  196. renderer.setPixelRatio( window.devicePixelRatio );
  197. renderer.setSize( window.innerWidth, window.innerHeight );
  198. container.appendChild( renderer.domElement );
  199. controls = new THREE.OrbitControls( camera, renderer.domElement );
  200. stats = new Stats();
  201. container.appendChild( stats.dom );
  202. document.addEventListener( 'mousemove', onDocumentMouseMove, false );
  203. document.addEventListener( 'touchstart', onDocumentTouchStart, false );
  204. document.addEventListener( 'touchmove', onDocumentTouchMove, false );
  205. document.addEventListener( 'keydown', function( event ) {
  206. // W Pressed: Toggle wireframe
  207. if ( event.keyCode === 87 ) {
  208. waterMesh.material.wireframe = ! waterMesh.material.wireframe;
  209. waterMesh.material.needsUpdate = true;
  210. }
  211. } , false );
  212. window.addEventListener( 'resize', onWindowResize, false );
  213. var gui = new dat.GUI();
  214. var effectController = {
  215. mouseSize: 20.0,
  216. viscosity: 0.03
  217. };
  218. var valuesChanger = function() {
  219. heightmapVariable.material.uniforms.mouseSize.value = effectController.mouseSize;
  220. heightmapVariable.material.uniforms.viscosityConstant.value = effectController.viscosity;
  221. };
  222. gui.add( effectController, "mouseSize", 1.0, 100.0, 1.0 ).onChange( valuesChanger );
  223. gui.add( effectController, "viscosity", 0.0, 0.1, 0.001 ).onChange( valuesChanger );
  224. var buttonSmooth = {
  225. smoothWater: function() {
  226. smoothWater();
  227. }
  228. };
  229. gui.add( buttonSmooth, 'smoothWater' );
  230. initWater();
  231. valuesChanger();
  232. }
  233. function initWater() {
  234. var materialColor = 0x0040C0;
  235. var geometry = new THREE.PlaneBufferGeometry( BOUNDS, BOUNDS, WIDTH - 1, WIDTH -1 );
  236. // material: make a ShaderMaterial clone of MeshPhongMaterial, with customized vertex shader
  237. var material = new THREE.ShaderMaterial( {
  238. uniforms: THREE.UniformsUtils.merge( [
  239. THREE.ShaderLib[ 'phong' ].uniforms,
  240. {
  241. heightmap: { value: null }
  242. }
  243. ] ),
  244. vertexShader: document.getElementById( 'waterVertexShader' ).textContent,
  245. fragmentShader: THREE.ShaderChunk[ 'meshphong_frag' ]
  246. } );
  247. material.lights = true;
  248. // Material attributes from MeshPhongMaterial
  249. material.color = new THREE.Color( materialColor );
  250. material.specular = new THREE.Color( 0x111111 );
  251. material.shininess = 50;
  252. // Sets the uniforms with the material values
  253. material.uniforms.diffuse.value = material.color;
  254. material.uniforms.specular.value = material.specular;
  255. material.uniforms.shininess.value = Math.max( material.shininess, 1e-4 );
  256. material.uniforms.opacity.value = material.opacity;
  257. // Defines
  258. material.defines.WIDTH = WIDTH.toFixed( 1 );
  259. material.defines.BOUNDS = BOUNDS.toFixed( 1 );
  260. waterUniforms = material.uniforms;
  261. waterMesh = new THREE.Mesh( geometry, material );
  262. waterMesh.rotation.x = - Math.PI / 2;
  263. waterMesh.matrixAutoUpdate = false;
  264. waterMesh.updateMatrix();
  265. scene.add( waterMesh );
  266. // Mesh just for mouse raycasting
  267. var geometryRay = new THREE.PlaneBufferGeometry( BOUNDS, BOUNDS, 1, 1 );
  268. meshRay = new THREE.Mesh( geometryRay, new THREE.MeshBasicMaterial( { color: 0xFFFFFF, visible: false } ) );
  269. meshRay.rotation.x = - Math.PI / 2;
  270. meshRay.matrixAutoUpdate = false;
  271. meshRay.updateMatrix();
  272. scene.add( meshRay );
  273. // Creates the gpu computation class and sets it up
  274. gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );
  275. var heightmap0 = gpuCompute.createTexture();
  276. fillTexture( heightmap0 );
  277. heightmapVariable = gpuCompute.addVariable( "heightmap", document.getElementById( 'heightmapFragmentShader' ).textContent, heightmap0 );
  278. gpuCompute.setVariableDependencies( heightmapVariable, [ heightmapVariable ] );
  279. heightmapVariable.material.uniforms.mousePos = { value: new THREE.Vector2( 10000, 10000 ) };
  280. heightmapVariable.material.uniforms.mouseSize = { value: 20.0 };
  281. heightmapVariable.material.uniforms.viscosityConstant = { value: 0.03 };
  282. heightmapVariable.material.defines.BOUNDS = BOUNDS.toFixed( 1 );
  283. var error = gpuCompute.init();
  284. if ( error !== null ) {
  285. console.error( error );
  286. }
  287. // Create compute shader to smooth the water surface and velocity
  288. smoothShader = gpuCompute.createShaderMaterial( document.getElementById( 'smoothFragmentShader' ).textContent, { texture: { value: null } } );
  289. }
  290. function fillTexture( texture ) {
  291. var waterMaxHeight = 10;
  292. function noise( x, y, z ) {
  293. var multR = waterMaxHeight;
  294. var mult = 0.025;
  295. var r = 0;
  296. for ( var i = 0; i < 15; i++ ) {
  297. r += multR * simplex.noise( x * mult, y * mult );
  298. multR *= 0.53 + 0.025 * i;
  299. mult *= 1.25;
  300. }
  301. return r;
  302. }
  303. var pixels = texture.image.data;
  304. var p = 0;
  305. for ( var j = 0; j < WIDTH; j++ ) {
  306. for ( var i = 0; i < WIDTH; i++ ) {
  307. var x = i * 128 / WIDTH;
  308. var y = j * 128 / WIDTH;
  309. pixels[ p + 0 ] = noise( x, y, 123.4 );
  310. pixels[ p + 1 ] = 0;
  311. pixels[ p + 2 ] = 0;
  312. pixels[ p + 3 ] = 1;
  313. p += 4;
  314. }
  315. }
  316. }
  317. function smoothWater() {
  318. var currentRenderTarget = gpuCompute.getCurrentRenderTarget( heightmapVariable );
  319. var alternateRenderTarget = gpuCompute.getAlternateRenderTarget( heightmapVariable );
  320. for ( var i = 0; i < 10; i++ ) {
  321. smoothShader.uniforms.texture.value = currentRenderTarget.texture;
  322. gpuCompute.doRenderTarget( smoothShader, alternateRenderTarget );
  323. smoothShader.uniforms.texture.value = alternateRenderTarget.texture;
  324. gpuCompute.doRenderTarget( smoothShader, currentRenderTarget );
  325. }
  326. }
  327. function onWindowResize() {
  328. windowHalfX = window.innerWidth / 2;
  329. windowHalfY = window.innerHeight / 2;
  330. camera.aspect = window.innerWidth / window.innerHeight;
  331. camera.updateProjectionMatrix();
  332. renderer.setSize( window.innerWidth, window.innerHeight );
  333. }
  334. function setMouseCoords( x, y ) {
  335. mouseCoords.set( ( x / renderer.domElement.clientWidth ) * 2 - 1, - ( y / renderer.domElement.clientHeight ) * 2 + 1 );
  336. mouseMoved = true;
  337. }
  338. function onDocumentMouseMove( event ) {
  339. setMouseCoords( event.clientX, event.clientY );
  340. }
  341. function onDocumentTouchStart( event ) {
  342. if ( event.touches.length === 1 ) {
  343. event.preventDefault();
  344. setMouseCoords( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  345. }
  346. }
  347. function onDocumentTouchMove( event ) {
  348. if ( event.touches.length === 1 ) {
  349. event.preventDefault();
  350. setMouseCoords( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  351. }
  352. }
  353. function animate() {
  354. requestAnimationFrame( animate );
  355. render();
  356. stats.update();
  357. }
  358. function render() {
  359. // Set uniforms: mouse interaction
  360. var uniforms = heightmapVariable.material.uniforms;
  361. if ( mouseMoved ) {
  362. this.raycaster.setFromCamera( mouseCoords, camera );
  363. var intersects = this.raycaster.intersectObject( meshRay );
  364. if ( intersects.length > 0 ) {
  365. var point = intersects[ 0 ].point;
  366. uniforms.mousePos.value.set( point.x, point.z );
  367. }
  368. else {
  369. uniforms.mousePos.value.set( 10000, 10000 );
  370. }
  371. mouseMoved = false;
  372. }
  373. else {
  374. uniforms.mousePos.value.set( 10000, 10000 );
  375. }
  376. // Do the gpu computation
  377. gpuCompute.compute();
  378. // Get compute output in custom uniform
  379. waterUniforms.heightmap.value = gpuCompute.getCurrentRenderTarget( heightmapVariable ).texture;
  380. // Render
  381. renderer.render( scene, camera );
  382. }
  383. </script>
  384. </body>
  385. </html>