webgl_gpgpu_water.html 15 KB

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