webgpu_compute_water.html 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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. Click and 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 { instanceIndex, struct, If, uint, int, 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 { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  29. import { RGBELoader } from 'three/addons/loaders/RGBELoader.js';
  30. import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
  31. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  32. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  33. import Stats from 'three/addons/libs/stats.module.js';
  34. // Dimensions of simulation grid.
  35. const WIDTH = 128;
  36. // Water size in system units.
  37. const BOUNDS = 6;
  38. const BOUNDS_HALF = BOUNDS * 0.5;
  39. const limit = BOUNDS_HALF - 0.2;
  40. const waterMaxHeight = 0.1;
  41. let container, stats;
  42. let camera, scene, renderer, controls;
  43. let mouseDown = false;
  44. let firstClick = true;
  45. let updateOriginMouseDown = false;
  46. const mouseCoords = new THREE.Vector2();
  47. const raycaster = new THREE.Raycaster();
  48. let frame = 0;
  49. const effectController = {
  50. mousePos: uniform( new THREE.Vector2() ).label( 'mousePos' ),
  51. mouseSpeed: uniform( new THREE.Vector2() ).label( 'mouseSpeed' ),
  52. mouseDeep: uniform( .5 ).label( 'mouseDeep' ),
  53. mouseSize: uniform( 0.12 ).label( 'mouseSize' ),
  54. viscosity: uniform( 0.96 ).label( 'viscosity' ),
  55. ducksEnabled: true,
  56. wireframe: false,
  57. speed: 5,
  58. };
  59. let sun;
  60. let waterMesh;
  61. let poolBorder;
  62. let meshRay;
  63. let computeHeight, computeDucks;
  64. let duckModel = null;
  65. const NUM_DUCKS = 100;
  66. const simplex = new SimplexNoise();
  67. init();
  68. function noise( x, y ) {
  69. let multR = waterMaxHeight;
  70. let mult = 0.025;
  71. let r = 0;
  72. for ( let i = 0; i < 15; i ++ ) {
  73. r += multR * simplex.noise( x * mult, y * mult );
  74. multR *= 0.53 + 0.025 * i;
  75. mult *= 1.25;
  76. }
  77. return r;
  78. }
  79. async function init() {
  80. container = document.createElement( 'div' );
  81. document.body.appendChild( container );
  82. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  83. camera.position.set( 0, 2.00, 4 );
  84. camera.lookAt( 0, 0, 0 );
  85. scene = new THREE.Scene();
  86. sun = new THREE.DirectionalLight( 0xFFFFFF, 4.0 );
  87. sun.position.set( - 1, 2.6, 1.4 );
  88. scene.add( sun );
  89. //
  90. // Initialize height storage buffers
  91. const heightArray = new Float32Array( WIDTH * WIDTH );
  92. const prevHeightArray = new Float32Array( WIDTH * WIDTH );
  93. let p = 0;
  94. for ( let j = 0; j < WIDTH; j ++ ) {
  95. for ( let i = 0; i < WIDTH; i ++ ) {
  96. const x = i * 128 / WIDTH;
  97. const y = j * 128 / WIDTH;
  98. const height = noise( x, y );
  99. heightArray[ p ] = height;
  100. prevHeightArray[ p ] = height;
  101. p ++;
  102. }
  103. }
  104. const heightStorage = instancedArray( heightArray ).label( 'Height' );
  105. const prevHeightStorage = instancedArray( prevHeightArray ).label( 'PrevHeight' );
  106. // Get Indices of Neighbor Values of an Index in the Simulation Grid
  107. const getNeighborIndicesTSL = ( index ) => {
  108. const width = uint( WIDTH );
  109. // Get 2-D compute coordinate from one-dimensional instanceIndex. The calculation will
  110. // still work even if you dispatch your compute shader 2-dimensionally, since within a compute
  111. // context, instanceIndex is a 1-dimensional value derived from the workgroup dimensions.
  112. // Cast to int to prevent unintended index overflow upon subtraction.
  113. const x = int( index.mod( WIDTH ) );
  114. const y = int( index.div( WIDTH ) );
  115. // The original shader accesses height via texture uvs. However, unlike with textures, we can't
  116. // access areas that are out of bounds. Accordingly, we emulate the Clamp to Edge Wrapping
  117. // behavior of accessing a DataTexture with out of bounds uvs.
  118. const leftX = max( 0, x.sub( 1 ) );
  119. const rightX = min( x.add( 1 ), width.sub( 1 ) );
  120. const bottomY = max( 0, y.sub( 1 ) );
  121. const topY = min( y.add( 1 ), width.sub( 1 ) );
  122. const westIndex = y.mul( width ).add( leftX );
  123. const eastIndex = y.mul( width ).add( rightX );
  124. const southIndex = bottomY.mul( width ).add( x );
  125. const northIndex = topY.mul( width ).add( x );
  126. return { northIndex, southIndex, eastIndex, westIndex };
  127. };
  128. // Get simulation index neighbor values
  129. const getNeighborValuesTSL = ( index, store ) => {
  130. const { northIndex, southIndex, eastIndex, westIndex } = getNeighborIndicesTSL( index );
  131. const north = store.element( northIndex );
  132. const south = store.element( southIndex );
  133. const east = store.element( eastIndex );
  134. const west = store.element( westIndex );
  135. return { north, south, east, west };
  136. };
  137. // Get new normals of simulation area.
  138. const getNormalsFromHeightTSL = ( index, store ) => {
  139. const { north, south, east, west } = getNeighborValuesTSL( index, store );
  140. const normalX = ( west.sub( east ) ).mul( WIDTH / BOUNDS );
  141. const normalY = ( south.sub( north ) ).mul( WIDTH / BOUNDS );
  142. return { normalX, normalY };
  143. };
  144. computeHeight = Fn( () => {
  145. const { viscosity, mousePos, mouseSize, mouseDeep, mouseSpeed } = effectController;
  146. const height = heightStorage.element( instanceIndex ).toVar();
  147. const prevHeight = prevHeightStorage.element( instanceIndex ).toVar();
  148. const { north, south, east, west } = getNeighborValuesTSL( instanceIndex, heightStorage );
  149. const neighborHeight = north.add( south ).add( east ).add( west );
  150. neighborHeight.mulAssign( 0.5 );
  151. neighborHeight.subAssign( prevHeight );
  152. const newHeight = neighborHeight.mul( viscosity );
  153. // Get 2-D compute coordinate from one-dimensional instanceIndex.
  154. const x = float( instanceIndex.mod( WIDTH ) ).mul( 1 / WIDTH );
  155. const y = float( instanceIndex.div( WIDTH ) ).mul( 1 / WIDTH );
  156. // Mouse influence
  157. const centerVec = vec2( 0.5 );
  158. // Get length of position in range [ -BOUNDS / 2, BOUNDS / 2 ], offset by mousePos, then scale.
  159. const mousePhase = clamp( length( ( vec2( x, y ).sub( centerVec ) ).mul( BOUNDS ).sub( mousePos ) ).mul( Math.PI ).div( mouseSize ), 0.0, Math.PI );
  160. // "Indent" water down by scaled distance from center of mouse impact
  161. newHeight.addAssign( cos( mousePhase ).add( 1.0 ).mul( mouseDeep ).mul( mouseSpeed.length() ) );
  162. prevHeightStorage.element( instanceIndex ).assign( height );
  163. heightStorage.element( instanceIndex ).assign( newHeight );
  164. } )().compute( WIDTH * WIDTH );
  165. // Water Geometry corresponds with buffered compute grid.
  166. const waterGeometry = new THREE.PlaneGeometry( BOUNDS, BOUNDS, WIDTH - 1, WIDTH - 1 );
  167. const waterMaterial = new THREE.MeshStandardNodeMaterial( {
  168. color: 0x9bd2ec,
  169. metalness: 0.9,
  170. roughness: 0,
  171. transparent: true,
  172. opacity: 0.8,
  173. side: THREE.DoubleSide
  174. } );
  175. waterMaterial.normalNode = Fn( () => {
  176. // To correct the lighting as our mesh undulates, we have to reassign the normals in the normal shader.
  177. const { normalX, normalY } = getNormalsFromHeightTSL( vertexIndex, heightStorage );
  178. return transformNormalToView( vec3( normalX, normalY.negate(), 1.0 ) ).toVertexStage();
  179. } )();
  180. waterMaterial.positionNode = Fn( () => {
  181. return vec3( positionLocal.x, positionLocal.y, heightStorage.element( vertexIndex ) );
  182. } )();
  183. waterMesh = new THREE.Mesh( waterGeometry, waterMaterial );
  184. waterMesh.rotation.x = - Math.PI * 0.5;
  185. waterMesh.matrixAutoUpdate = false;
  186. waterMesh.updateMatrix();
  187. scene.add( waterMesh );
  188. // Pool border
  189. const borderGeom = new THREE.TorusGeometry( 4.2, 0.1, 12, 4 );
  190. borderGeom.rotateX( Math.PI * 0.5 );
  191. borderGeom.rotateY( Math.PI * 0.25 );
  192. poolBorder = new THREE.Mesh( borderGeom, new THREE.MeshStandardMaterial( { color: 0x908877, roughness: 0.2 } ) );
  193. scene.add( poolBorder );
  194. // THREE.Mesh just for mouse raycasting
  195. const geometryRay = new THREE.PlaneGeometry( BOUNDS, BOUNDS, 1, 1 );
  196. meshRay = new THREE.Mesh( geometryRay, new THREE.MeshBasicMaterial( { color: 0xFFFFFF, visible: false } ) );
  197. meshRay.rotation.x = - Math.PI / 2;
  198. meshRay.matrixAutoUpdate = false;
  199. meshRay.updateMatrix();
  200. scene.add( meshRay );
  201. // Initialize sphere mesh instance position and velocity.
  202. // position<vec3> + velocity<vec2> + unused<vec3> = 8 floats per sphere.
  203. // for structs arrays must be enclosed in multiple of 4
  204. const duckStride = 8;
  205. const duckInstanceDataArray = new Float32Array( NUM_DUCKS * duckStride );
  206. // Only hold velocity in x and z directions.
  207. // The sphere is wedded to the surface of the water, and will only move vertically with the water.
  208. for ( let i = 0; i < NUM_DUCKS; i ++ ) {
  209. duckInstanceDataArray[ i * duckStride + 0 ] = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  210. duckInstanceDataArray[ i * duckStride + 1 ] = 0;
  211. duckInstanceDataArray[ i * duckStride + 2 ] = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  212. }
  213. const DuckStruct = struct( {
  214. position: 'vec3',
  215. velocity: 'vec2'
  216. } );
  217. // Duck instance data storage
  218. const duckInstanceDataStorage = instancedArray( duckInstanceDataArray, DuckStruct ).label( 'DuckInstanceData' );
  219. computeDucks = Fn( () => {
  220. const yOffset = float( - 0.04 );
  221. const verticalResponseFactor = float( 0.98 );
  222. const waterPushFactor = float( 0.015 );
  223. const linearDamping = float( 0.92 );
  224. const bounceDamping = float( - 0.4 );
  225. // Get 2-D compute coordinate from one-dimensional instanceIndex. The calculation will
  226. const instancePosition = duckInstanceDataStorage.element( instanceIndex ).get( 'position' ).toVar();
  227. const velocity = duckInstanceDataStorage.element( instanceIndex ).get( 'velocity' ).toVar();
  228. const gridCoordX = instancePosition.x.div( BOUNDS ).add( 0.5 ).mul( WIDTH );
  229. const gridCoordZ = instancePosition.z.div( BOUNDS ).add( 0.5 ).mul( WIDTH );
  230. // Cast to int to prevent unintended index overflow upon subtraction.
  231. const xCoord = uint( clamp( floor( gridCoordX ), 0, WIDTH - 1 ) );
  232. const zCoord = uint( clamp( floor( gridCoordZ ), 0, WIDTH - 1 ) );
  233. const heightInstanceIndex = zCoord.mul( WIDTH ).add( xCoord );
  234. // Get height of water at the duck's position
  235. const waterHeight = heightStorage.element( heightInstanceIndex );
  236. const { normalX, normalY } = getNormalsFromHeightTSL( heightInstanceIndex, heightStorage );
  237. // Calculate the target Y position based on the water height and the duck's vertical offset
  238. const targetY = waterHeight.add( yOffset );
  239. const deltaY = targetY.sub( instancePosition.y );
  240. instancePosition.y.addAssign( deltaY.mul( verticalResponseFactor ) ); // Atualiza Y gradualmente
  241. // Get the normal of the water surface at the duck's position
  242. const pushX = normalX.mul( waterPushFactor );
  243. const pushZ = normalY.mul( waterPushFactor );
  244. // Apply the water push to the duck's velocity
  245. velocity.x.mulAssign( linearDamping );
  246. velocity.y.mulAssign( linearDamping );
  247. velocity.x.addAssign( pushX );
  248. velocity.y.addAssign( pushZ );
  249. // update position based on velocity
  250. instancePosition.x.addAssign( velocity.x );
  251. instancePosition.z.addAssign( velocity.y );
  252. // Clamp position to the pool bounds
  253. If( instancePosition.x.lessThan( - limit ), () => {
  254. instancePosition.x = - limit;
  255. velocity.x.mulAssign( bounceDamping );
  256. } ).ElseIf( instancePosition.x.greaterThan( limit ), () => {
  257. instancePosition.x = limit;
  258. velocity.x.mulAssign( bounceDamping );
  259. } );
  260. If( instancePosition.z.lessThan( - limit ), () => {
  261. instancePosition.z = - limit;
  262. velocity.y.mulAssign( bounceDamping ); // Inverte e amortece vz (velocity.y)
  263. } ).ElseIf( instancePosition.z.greaterThan( limit ), () => {
  264. instancePosition.z = limit;
  265. velocity.y.mulAssign( bounceDamping );
  266. } );
  267. // assignment of new values to the instance data storage
  268. duckInstanceDataStorage.element( instanceIndex ).get( 'position' ).assign( instancePosition );
  269. duckInstanceDataStorage.element( instanceIndex ).get( 'velocity' ).assign( velocity );
  270. } )().compute( NUM_DUCKS );
  271. // Models / Textures
  272. const rgbeLoader = new RGBELoader().setPath( './textures/equirectangular/' );
  273. const glbloader = new GLTFLoader().setPath( 'models/gltf/' );
  274. glbloader.setDRACOLoader( new DRACOLoader().setDecoderPath( 'jsm/libs/draco/gltf/' ) );
  275. const [ env, model ] = await Promise.all( [ rgbeLoader.loadAsync( 'blouberg_sunrise_2_1k.hdr' ), glbloader.loadAsync( 'duck.glb' ) ] );
  276. env.mapping = THREE.EquirectangularReflectionMapping;
  277. scene.environment = env;
  278. scene.background = env;
  279. scene.backgroundBlurriness = 0.3;
  280. scene.environmentIntensity = 1.25;
  281. duckModel = model.scene.children[ 0 ];
  282. duckModel.material.positionNode = Fn( () => {
  283. const instancePosition = duckInstanceDataStorage.element( instanceIndex ).get( 'position' );
  284. const newPosition = positionLocal.add( instancePosition );
  285. return newPosition;
  286. } )();
  287. const duckMesh = new THREE.InstancedMesh( duckModel.geometry, duckModel.material, NUM_DUCKS );
  288. scene.add( duckMesh );
  289. renderer = new THREE.WebGPURenderer( { antialias: true } );
  290. renderer.setPixelRatio( window.devicePixelRatio );
  291. renderer.setSize( window.innerWidth, window.innerHeight );
  292. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  293. renderer.toneMappingExposure = 0.5;
  294. renderer.setAnimationLoop( animate );
  295. container.appendChild( renderer.domElement );
  296. controls = new OrbitControls( camera, container );
  297. container.style.touchAction = 'none';
  298. // Stats
  299. stats = new Stats();
  300. container.appendChild( stats.dom );
  301. container.style.touchAction = 'none';
  302. container.addEventListener( 'pointermove', onPointerMove );
  303. container.addEventListener( 'pointerdown', onPointerDown );
  304. container.addEventListener( 'pointerup', onPointerUp );
  305. window.addEventListener( 'resize', onWindowResize );
  306. // GUI
  307. const gui = new GUI();
  308. gui.add( effectController.mouseSize, 'value', 0.1, .3 ).name( 'Mouse Size' );
  309. gui.add( effectController.mouseDeep, 'value', 0.1, 1 ).name( 'Mouse Deep' );
  310. gui.add( effectController.viscosity, 'value', 0.9, 0.96, 0.001 ).name( 'viscosity' );
  311. gui.add( effectController, 'speed', 1, 6, 1 );
  312. gui.add( effectController, 'ducksEnabled' ).onChange( () => {
  313. duckMesh.visible = effectController.ducksEnabled;
  314. } );
  315. gui.add( effectController, 'wireframe' ).onChange( () => {
  316. waterMesh.material.wireframe = ! waterMesh.material.wireframe;
  317. poolBorder.material.wireframe = ! poolBorder.material.wireframe;
  318. duckModel.material.wireframe = ! duckModel.material.wireframe;
  319. waterMesh.material.needsUpdate = true;
  320. poolBorder.material.needsUpdate = true;
  321. } );
  322. }
  323. function onWindowResize() {
  324. camera.aspect = window.innerWidth / window.innerHeight;
  325. camera.updateProjectionMatrix();
  326. renderer.setSize( window.innerWidth, window.innerHeight );
  327. }
  328. function setMouseCoords( x, y ) {
  329. mouseCoords.set( ( x / renderer.domElement.clientWidth ) * 2 - 1, - ( y / renderer.domElement.clientHeight ) * 2 + 1 );
  330. }
  331. function onPointerDown() {
  332. mouseDown = true;
  333. firstClick = true;
  334. updateOriginMouseDown = true;
  335. }
  336. function onPointerUp() {
  337. mouseDown = false;
  338. firstClick = false;
  339. updateOriginMouseDown = false;
  340. controls.enabled = true;
  341. }
  342. function onPointerMove( event ) {
  343. if ( event.isPrimary === false ) return;
  344. setMouseCoords( event.clientX, event.clientY );
  345. }
  346. function animate() {
  347. render();
  348. stats.update();
  349. }
  350. function raycast() {
  351. if ( mouseDown && ( firstClick || ! controls.enabled ) ) {
  352. raycaster.setFromCamera( mouseCoords, camera );
  353. const intersects = raycaster.intersectObject( meshRay );
  354. if ( intersects.length > 0 ) {
  355. const point = intersects[ 0 ].point;
  356. if ( updateOriginMouseDown ) {
  357. effectController.mousePos.value.set( point.x, point.z );
  358. updateOriginMouseDown = false;
  359. }
  360. effectController.mouseSpeed.value.set(
  361. ( point.x - effectController.mousePos.value.x ),
  362. ( point.z - effectController.mousePos.value.y )
  363. );
  364. effectController.mousePos.value.set( point.x, point.z );
  365. if ( firstClick ) {
  366. controls.enabled = false;
  367. }
  368. } else {
  369. updateOriginMouseDown = true;
  370. effectController.mouseSpeed.value.set( 0, 0 );
  371. }
  372. firstClick = false;
  373. } else {
  374. updateOriginMouseDown = true;
  375. effectController.mouseSpeed.value.set( 0, 0 );
  376. }
  377. }
  378. function render() {
  379. raycast();
  380. frame ++;
  381. if ( frame >= 7 - effectController.speed ) {
  382. renderer.computeAsync( computeHeight );
  383. if ( effectController.ducksEnabled ) {
  384. renderer.computeAsync( computeDucks );
  385. }
  386. frame = 0;
  387. }
  388. renderer.render( scene, camera );
  389. }
  390. </script>
  391. </body>
  392. </html>
粤ICP备19079148号