webgpu_compute_water.html 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - compute - 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="https://threejs.org" target="_blank" rel="noopener">three.js</a> - <span id="waterSize"></span> webgpu compute water<br/>
  12. Move mouse to disturb water.
  13. </div>
  14. <script type="importmap">
  15. {
  16. "imports": {
  17. "three": "../build/three.webgpu.js",
  18. "three/webgpu": "../build/three.webgpu.js",
  19. "three/tsl": "../build/three.tsl.js",
  20. "three/addons/": "./jsm/"
  21. }
  22. }
  23. </script>
  24. <script type="module">
  25. import * as THREE from 'three';
  26. import { color, instanceIndex, If, varyingProperty, uint, int, negate, floor, float, length, clamp, vec2, cos, vec3, vertexIndex, Fn, uniform, instancedArray, min, max, positionLocal, transformNormalToView } from 'three/tsl';
  27. import { SimplexNoise } from 'three/addons/math/SimplexNoise.js';
  28. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  29. import Stats from 'three/addons/libs/stats.module.js';
  30. // Dimensions of simulation grid.
  31. const WIDTH = 128;
  32. // Water size in system units.
  33. const BOUNDS = 512;
  34. const BOUNDS_HALF = BOUNDS * 0.5;
  35. const waterMaxHeight = 10;
  36. let container, stats;
  37. let camera, scene, renderer;
  38. let mouseMoved = false;
  39. const mouseCoords = new THREE.Vector2();
  40. const raycaster = new THREE.Raycaster();
  41. let effectController;
  42. let waterMesh, meshRay;
  43. let computeHeight, computeSmooth, computeSphere;
  44. const NUM_SPHERES = 100;
  45. const simplex = new SimplexNoise();
  46. init();
  47. function noise( x, y ) {
  48. let multR = waterMaxHeight;
  49. let mult = 0.025;
  50. let r = 0;
  51. for ( let i = 0; i < 15; i ++ ) {
  52. r += multR * simplex.noise( x * mult, y * mult );
  53. multR *= 0.53 + 0.025 * i;
  54. mult *= 1.25;
  55. }
  56. return r;
  57. }
  58. function init() {
  59. container = document.createElement( 'div' );
  60. document.body.appendChild( container );
  61. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  62. camera.position.set( 0, 200, 350 );
  63. camera.lookAt( 0, 0, 0 );
  64. scene = new THREE.Scene();
  65. const sun = new THREE.DirectionalLight( 0xFFFFFF, 3.0 );
  66. sun.position.set( 300, 400, 175 );
  67. scene.add( sun );
  68. const sun2 = new THREE.DirectionalLight( 0x40A040, 2.0 );
  69. sun2.position.set( - 100, 350, - 200 );
  70. scene.add( sun2 );
  71. //
  72. effectController = {
  73. mousePos: uniform( new THREE.Vector2( 10000, 10000 ) ).label( 'mousePos' ),
  74. mouseSize: uniform( 30.0 ).label( 'mouseSize' ),
  75. viscosity: uniform( 0.95 ).label( 'viscosity' ),
  76. spheresEnabled: true,
  77. wireframe: false
  78. };
  79. // Initialize height storage buffers
  80. const heightArray = new Float32Array( WIDTH * WIDTH );
  81. const prevHeightArray = new Float32Array( WIDTH * WIDTH );
  82. let p = 0;
  83. for ( let j = 0; j < WIDTH; j ++ ) {
  84. for ( let i = 0; i < WIDTH; i ++ ) {
  85. const x = i * 128 / WIDTH;
  86. const y = j * 128 / WIDTH;
  87. const height = noise( x, y );
  88. heightArray[ p ] = height;
  89. prevHeightArray[ p ] = height;
  90. p ++;
  91. }
  92. }
  93. const heightStorage = instancedArray( heightArray ).label( 'Height' );
  94. const prevHeightStorage = instancedArray( prevHeightArray ).label( 'PrevHeight' );
  95. // Get Indices of Neighbor Values of an Index in the Simulation Grid
  96. const getNeighborIndicesTSL = ( index ) => {
  97. const width = uint( WIDTH );
  98. // Get 2-D compute coordinate from one-dimensional instanceIndex. The calculation will
  99. // still work even if you dispatch your compute shader 2-dimensionally, since within a compute
  100. // context, instanceIndex is a 1-dimensional value derived from the workgroup dimensions.
  101. // Cast to int to prevent unintended index overflow upon subtraction.
  102. const x = int( index.modInt( WIDTH ) );
  103. const y = int( index.div( WIDTH ) );
  104. // The original shader accesses height via texture uvs. However, unlike with textures, we can't
  105. // access areas that are out of bounds. Accordingly, we emulate the Clamp to Edge Wrapping
  106. // behavior of accessing a DataTexture with out of bounds uvs.
  107. const leftX = max( 0, x.sub( 1 ) );
  108. const rightX = min( x.add( 1 ), width.sub( 1 ) );
  109. const bottomY = max( 0, y.sub( 1 ) );
  110. const topY = min( y.add( 1 ), width.sub( 1 ) );
  111. const westIndex = y.mul( width ).add( leftX );
  112. const eastIndex = y.mul( width ).add( rightX );
  113. const southIndex = bottomY.mul( width ).add( x );
  114. const northIndex = topY.mul( width ).add( x );
  115. return { northIndex, southIndex, eastIndex, westIndex };
  116. };
  117. // Get simulation index neighbor values
  118. const getNeighborValuesTSL = ( index, store ) => {
  119. const { northIndex, southIndex, eastIndex, westIndex } = getNeighborIndicesTSL( index );
  120. const north = store.element( northIndex );
  121. const south = store.element( southIndex );
  122. const east = store.element( eastIndex );
  123. const west = store.element( westIndex );
  124. return { north, south, east, west };
  125. };
  126. // Get new normals of simulation area.
  127. const getNormalsFromHeightTSL = ( index, store ) => {
  128. const { north, south, east, west } = getNeighborValuesTSL( index, store );
  129. const normalX = ( west.sub( east ) ).mul( WIDTH / BOUNDS );
  130. const normalY = ( south.sub( north ) ).mul( WIDTH / BOUNDS );
  131. return { normalX, normalY };
  132. };
  133. computeHeight = Fn( () => {
  134. const { viscosity, mousePos, mouseSize } = effectController;
  135. const height = heightStorage.element( instanceIndex ).toVar();
  136. const prevHeight = prevHeightStorage.element( instanceIndex ).toVar();
  137. const { north, south, east, west } = getNeighborValuesTSL( instanceIndex, heightStorage );
  138. const neighborHeight = north.add( south ).add( east ).add( west );
  139. neighborHeight.mulAssign( 0.5 );
  140. neighborHeight.subAssign( prevHeight );
  141. const newHeight = neighborHeight.mul( viscosity );
  142. // Get 2-D compute coordinate from one-dimensional instanceIndex.
  143. const x = float( instanceIndex.modInt( WIDTH ) ).mul( 1 / WIDTH );
  144. const y = float( instanceIndex.div( WIDTH ) ).mul( 1 / WIDTH );
  145. // Mouse influence
  146. const centerVec = vec2( 0.5 );
  147. // Get length of position in range [ -BOUNDS / 2, BOUNDS / 2 ], offset by mousePos, then scale.
  148. const mousePhase = clamp( length( ( vec2( x, y ).sub( centerVec ) ).mul( BOUNDS ).sub( mousePos ) ).mul( Math.PI ).div( mouseSize ), 0.0, Math.PI );
  149. newHeight.addAssign( cos( mousePhase ).add( 1.0 ).mul( 0.28 ) );
  150. prevHeightStorage.element( instanceIndex ).assign( height );
  151. heightStorage.element( instanceIndex ).assign( newHeight );
  152. } )().compute( WIDTH * WIDTH );
  153. computeSmooth = Fn( () => {
  154. const height = heightStorage.element( instanceIndex ).toVar();
  155. const prevHeight = prevHeightStorage.element( instanceIndex ).toVar();
  156. // Get neighboring height values.
  157. const { north: northH, south: southH, east: eastH, west: westH } = getNeighborValuesTSL( instanceIndex, heightStorage );
  158. // Get neighboring prev height values.
  159. const { north: northP, south: southP, east: eastP, west: westP } = getNeighborValuesTSL( instanceIndex, prevHeightStorage );
  160. height.addAssign( northH.add( southH ).add( eastH ).add( westH ) );
  161. prevHeight.addAssign( northP.add( southP ).add( eastP ).add( westP ) );
  162. heightStorage.element( instanceIndex ).assign( height.div( 5 ) );
  163. prevHeightStorage.element( instanceIndex ).assign( height.div( 5 ) );
  164. } )().compute( WIDTH * WIDTH/*, [ 8, 8 ]*/ );
  165. // Water Geometry corresponds with buffered compute grid.
  166. const waterGeometry = new THREE.PlaneGeometry( BOUNDS, BOUNDS, WIDTH - 1, WIDTH - 1 );
  167. // material: make a THREE.ShaderMaterial clone of THREE.MeshPhongMaterial, with customized position shader.
  168. const waterMaterial = new THREE.MeshPhongNodeMaterial();
  169. waterMaterial.lights = true;
  170. waterMaterial.colorNode = color( 0x0040C0 );
  171. waterMaterial.specularNode = color( 0x111111 );
  172. waterMaterial.shininess = Math.max( 50, 1e-4 );
  173. waterMaterial.positionNode = Fn( () => {
  174. // To correct the lighting as our mesh undulates, we have to reassign the normals in the position shader.
  175. const { normalX, normalY } = getNormalsFromHeightTSL( vertexIndex, heightStorage );
  176. varyingProperty( 'vec3', 'v_normalView' ).assign( transformNormalToView( vec3( normalX, negate( normalY ), 1.0 ) ) );
  177. return vec3( positionLocal.x, positionLocal.y, heightStorage.element( vertexIndex ) );
  178. } )();
  179. waterMesh = new THREE.Mesh( waterGeometry, waterMaterial );
  180. waterMesh.rotation.x = - Math.PI / 2;
  181. waterMesh.matrixAutoUpdate = false;
  182. waterMesh.updateMatrix();
  183. scene.add( waterMesh );
  184. // THREE.Mesh just for mouse raycasting
  185. const geometryRay = new THREE.PlaneGeometry( BOUNDS, BOUNDS, 1, 1 );
  186. meshRay = new THREE.Mesh( geometryRay, new THREE.MeshBasicMaterial( { color: 0xFFFFFF, visible: false } ) );
  187. meshRay.rotation.x = - Math.PI / 2;
  188. meshRay.matrixAutoUpdate = false;
  189. meshRay.updateMatrix();
  190. scene.add( meshRay );
  191. // Create sphere THREE.InstancedMesh
  192. const sphereGeometry = new THREE.SphereGeometry( 4, 24, 12 );
  193. const sphereMaterial = new THREE.MeshPhongMaterial( { color: 0xFFFF00 } );
  194. // Initialize sphere mesh instance position and velocity.
  195. const spherePositionArray = new Float32Array( NUM_SPHERES * 3 );
  196. // Only hold velocity in x and z directions.
  197. // The sphere is wedded to the surface of the water, and will only move vertically with the water.
  198. const sphereVelocityArray = new Float32Array( NUM_SPHERES * 2 );
  199. for ( let i = 0; i < NUM_SPHERES; i ++ ) {
  200. spherePositionArray[ i * 3 + 0 ] = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  201. spherePositionArray[ i * 3 + 1 ] = 0;
  202. spherePositionArray[ i * 3 + 2 ] = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  203. }
  204. sphereVelocityArray.fill( 0.0 );
  205. // Sphere Instance Storage
  206. const sphereInstancePositionStorage = instancedArray( spherePositionArray, 'vec3' ).label( 'SpherePosition' );
  207. const sphereVelocityStorage = instancedArray( sphereVelocityArray, 'vec2' ).label( 'SphereVelocity' );
  208. computeSphere = Fn( () => {
  209. const instancePosition = sphereInstancePositionStorage.element( instanceIndex );
  210. const velocity = sphereVelocityStorage.element( instanceIndex );
  211. // Bring position from range of [ -BOUNDS/2, BOUNDS/2 ] to [ 0, BOUNDS ]
  212. const tempX = instancePosition.x.add( BOUNDS_HALF );
  213. const tempZ = instancePosition.z.add( BOUNDS_HALF );
  214. // Bring position from range [ 0, BOUNDS ] to [ 0, WIDTH ]
  215. // ( i.e bring geometry range into 'heightmap' range )
  216. // WIDTH = 128, BOUNDS = 512... same as dividing by 4
  217. tempX.mulAssign( WIDTH / BOUNDS );
  218. tempZ.mulAssign( WIDTH / BOUNDS );
  219. // Can only access storage buffers with uints
  220. const xCoord = uint( floor( tempX ) );
  221. const zCoord = uint( floor( tempZ ) );
  222. // Get one dimensional index
  223. const heightInstanceIndex = zCoord.mul( WIDTH ).add( xCoord );
  224. // Set to read-only to be safe, even if it's not strictly necessary for compute access.
  225. const height = heightStorage.element( heightInstanceIndex );
  226. // Assign height to sphere position
  227. instancePosition.y.assign( height );
  228. // Calculate normal of the water mesh at this location.
  229. const { normalX, normalY } = getNormalsFromHeightTSL( heightInstanceIndex, heightStorage );
  230. normalX.mulAssign( 0.1 );
  231. normalY.mulAssign( 0.1 );
  232. const waterNormal = vec3( normalX, 0.0, negate( normalY ) );
  233. const newVelocity = vec3( velocity.x, 0.0, velocity.y ).add( waterNormal );
  234. newVelocity.mulAssign( 0.998 );
  235. const newPosition = instancePosition.add( newVelocity ).toVar();
  236. // Reverse velocity and reset position when exceeding bounds.
  237. If( newPosition.x.lessThan( - BOUNDS_HALF ), () => {
  238. newPosition.x = float( - BOUNDS_HALF ).add( 0.001 );
  239. newVelocity.x.mulAssign( - 0.3 );
  240. } ).ElseIf( newPosition.x.greaterThan( BOUNDS_HALF ), () => {
  241. newPosition.x = float( BOUNDS_HALF ).sub( 0.001 );
  242. newVelocity.x.mulAssign( - 0.3 );
  243. } );
  244. If( newPosition.z.lessThan( - BOUNDS_HALF ), () => {
  245. newPosition.z = float( - BOUNDS_HALF ).add( 0.001 );
  246. newVelocity.z.mulAssign( - 0.3 );
  247. } ).ElseIf( newPosition.z.greaterThan( BOUNDS_HALF ), () => {
  248. newPosition.z = float( BOUNDS_HALF ).sub( 0.001 );
  249. newVelocity.z.mulAssign( - 0.3 );
  250. } );
  251. instancePosition.assign( newPosition );
  252. velocity.assign( vec2( newVelocity.x, newVelocity.z ) );
  253. } )().compute( NUM_SPHERES );
  254. sphereMaterial.positionNode = Fn( () => {
  255. const instancePosition = sphereInstancePositionStorage.element( instanceIndex );
  256. const newPosition = positionLocal.add( instancePosition );
  257. return newPosition;
  258. } )();
  259. const sphereMesh = new THREE.InstancedMesh( sphereGeometry, sphereMaterial, NUM_SPHERES );
  260. scene.add( sphereMesh );
  261. renderer = new THREE.WebGPURenderer( { antialias: true } );
  262. renderer.setPixelRatio( window.devicePixelRatio );
  263. renderer.setSize( window.innerWidth, window.innerHeight );
  264. renderer.setAnimationLoop( animate );
  265. container.appendChild( renderer.domElement );
  266. stats = new Stats();
  267. container.appendChild( stats.dom );
  268. container.style.touchAction = 'none';
  269. container.addEventListener( 'pointermove', onPointerMove );
  270. window.addEventListener( 'resize', onWindowResize );
  271. const gui = new GUI();
  272. gui.add( effectController.mouseSize, 'value', 1.0, 100.0, 1.0 ).name( 'Mouse Size' );
  273. gui.add( effectController.viscosity, 'value', 0.9, 0.999, 0.001 ).name( 'viscosity' );
  274. const buttonCompute = {
  275. smoothWater: function () {
  276. renderer.computeAsync( computeSmooth );
  277. }
  278. };
  279. gui.add( buttonCompute, 'smoothWater' );
  280. gui.add( effectController, 'spheresEnabled' ).onChange( () => {
  281. sphereMesh.visible = effectController.spheresEnabled;
  282. } );
  283. gui.add( effectController, 'wireframe' ).onChange( () => {
  284. waterMesh.material.wireframe = ! waterMesh.material.wireframe;
  285. waterMesh.material.needsUpdate = true;
  286. } );
  287. }
  288. function onWindowResize() {
  289. camera.aspect = window.innerWidth / window.innerHeight;
  290. camera.updateProjectionMatrix();
  291. renderer.setSize( window.innerWidth, window.innerHeight );
  292. }
  293. function setMouseCoords( x, y ) {
  294. mouseCoords.set( ( x / renderer.domElement.clientWidth ) * 2 - 1, - ( y / renderer.domElement.clientHeight ) * 2 + 1 );
  295. mouseMoved = true;
  296. }
  297. function onPointerMove( event ) {
  298. if ( event.isPrimary === false ) return;
  299. setMouseCoords( event.clientX, event.clientY );
  300. }
  301. function animate() {
  302. render();
  303. stats.update();
  304. }
  305. function render() {
  306. if ( mouseMoved ) {
  307. raycaster.setFromCamera( mouseCoords, camera );
  308. const intersects = raycaster.intersectObject( meshRay );
  309. if ( intersects.length > 0 ) {
  310. const point = intersects[ 0 ].point;
  311. effectController.mousePos.value.set( point.x, point.z );
  312. } else {
  313. effectController.mousePos.value.set( 10000, 10000 );
  314. }
  315. mouseMoved = false;
  316. } else {
  317. effectController.mousePos.value.set( 10000, 10000 );
  318. }
  319. renderer.computeAsync( computeHeight );
  320. if ( effectController.spheresEnabled ) {
  321. renderer.computeAsync( computeSphere );
  322. }
  323. renderer.render( scene, camera );
  324. }
  325. </script>
  326. </body>
  327. </html>
粤ICP备19079148号