webgpu_compute_particles_fluid.html 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - compute fluid particles</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="example.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  12. <div class="title-wrapper">
  13. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Fluid Particles</span>
  14. </div>
  15. <small>MLS-MPM particle simulation running in compute shaders.</small>
  16. </div>
  17. <script type="importmap">
  18. {
  19. "imports": {
  20. "three": "../build/three.webgpu.js",
  21. "three/webgpu": "../build/three.webgpu.js",
  22. "three/tsl": "../build/three.tsl.js",
  23. "three/addons/": "./jsm/"
  24. }
  25. }
  26. </script>
  27. <script type="module">
  28. import * as THREE from 'three/webgpu';
  29. import { Fn, If, Return, instancedArray, instanceIndex, uniform, attribute, uint, float, clamp, struct, atomicStore, int, ivec3, array, vec3, atomicAdd, Loop, atomicLoad, max, pow, mat3, vec4, cross, step, storage } from 'three/tsl';
  30. import { Inspector } from 'three/addons/inspector/Inspector.js';
  31. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  32. import { UltraHDRLoader } from 'three/addons/loaders/UltraHDRLoader.js';
  33. import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
  34. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  35. let renderer, scene, camera, controls;
  36. const clock = new THREE.Clock();
  37. const maxParticles = 8192 * 16;
  38. const gridSize1d = 64;
  39. const workgroupSize = 64;
  40. const gridSize = new THREE.Vector3( gridSize1d, gridSize1d, gridSize1d );
  41. const fixedPointMultiplier = 1e7;
  42. let particleCountUniform, stiffnessUniform, restDensityUniform, dynamicViscosityUniform, dtUniform, gravityUniform, gridSizeUniform;
  43. let particleBuffer, cellBuffer, cellBufferFloat;
  44. let clearGridKernel, p2g1Kernel, p2g2Kernel, updateGridKernel, g2pKernel, workgroupKernel;
  45. let p2g1KernelWorkgroupBuffer, p2g2KernelWorkgroupBuffer, g2pKernelWorkgroupBuffer;
  46. let particleMesh;
  47. const mouseCoord = new THREE.Vector3();
  48. const prevMouseCoord = new THREE.Vector3();
  49. let mouseRayOriginUniform, mouseRayDirectionUniform, mouseForceUniform;
  50. if ( WebGPU.isAvailable() === false ) {
  51. document.body.appendChild( WebGPU.getErrorMessage() );
  52. throw new Error( 'No WebGPU support' );
  53. }
  54. const params = {
  55. particleCount: 8192 * 4,
  56. };
  57. init();
  58. async function init() {
  59. renderer = new THREE.WebGPURenderer( { antialias: true } );
  60. renderer.setPixelRatio( window.devicePixelRatio );
  61. renderer.setSize( window.innerWidth, window.innerHeight );
  62. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  63. renderer.toneMappingExposure = 1.35;
  64. renderer.inspector = new Inspector();
  65. document.body.appendChild( renderer.domElement );
  66. scene = new THREE.Scene();
  67. camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 0.01, 10 );
  68. camera.position.set( - 1.3, 1.3, - 1.3 );
  69. controls = new OrbitControls( camera, renderer.domElement );
  70. controls.minDistance = 1;
  71. controls.maxDistance = 3;
  72. controls.maxPolarAngle = Math.PI * 0.35;
  73. controls.touches = { TWO: THREE.TOUCH.DOLLY_ROTATE };
  74. const hdrLoader = new UltraHDRLoader().setPath( 'textures/equirectangular/' );
  75. const hdrTexture = await hdrLoader.loadAsync( 'royal_esplanade_2k.hdr.jpg' );
  76. hdrTexture.mapping = THREE.EquirectangularReflectionMapping;
  77. scene.background = hdrTexture;
  78. scene.backgroundBlurriness = 0.5;
  79. scene.environment = hdrTexture;
  80. setupParticles();
  81. const gui = renderer.inspector.createParameters( 'Settings' );
  82. const numWorkgroups = Math.ceil( params.particleCount / workgroupSize );
  83. p2g1KernelWorkgroupBuffer = new THREE.IndirectStorageBufferAttribute( new Uint32Array( [ numWorkgroups, 1, 1 ] ), 1 );
  84. p2g2KernelWorkgroupBuffer = new THREE.IndirectStorageBufferAttribute( new Uint32Array( [ numWorkgroups, 1, 1 ] ), 1 );
  85. g2pKernelWorkgroupBuffer = new THREE.IndirectStorageBufferAttribute( new Uint32Array( [ numWorkgroups, 1, 1 ] ), 1 );
  86. const p2g1WorkgroupStorage = storage( p2g1KernelWorkgroupBuffer, 'uint', 3 );
  87. const p2g2WorkgroupStorage = storage( p2g2KernelWorkgroupBuffer, 'uint', 3 );
  88. const g2pWorkgroupStorage = storage( g2pKernelWorkgroupBuffer, 'uint', 3 );
  89. workgroupKernel = Fn( () => {
  90. const workgroupsToDispatch = ( particleCountUniform.sub( 1 ) ).div( workgroupSize ).add( 1 );
  91. p2g1WorkgroupStorage.element( 0 ).assign( workgroupsToDispatch );
  92. p2g2WorkgroupStorage.element( 0 ).assign( workgroupsToDispatch );
  93. g2pWorkgroupStorage.element( 0 ).assign( workgroupsToDispatch );
  94. } )().compute( 1 );
  95. gui.add( params, 'particleCount', 4096, maxParticles, 4096 ).onChange( value => {
  96. particleMesh.count = value;
  97. particleCountUniform.value = value;
  98. } );
  99. window.addEventListener( 'resize', onWindowResize );
  100. controls.update();
  101. renderer.setAnimationLoop( render );
  102. }
  103. function setupBuffers() {
  104. const particleStruct = struct( {
  105. position: { type: 'vec3' },
  106. velocity: { type: 'vec3' },
  107. C: { type: 'mat3' },
  108. } );
  109. const particleStructSize = 20; // each vec3 occupies 4 floats and mat3 occupies 12 floats in memory because of webgpu memory alignment
  110. const particleArray = new Float32Array( maxParticles * particleStructSize );
  111. for ( let i = 0; i < maxParticles; i ++ ) {
  112. particleArray[ i * particleStructSize ] = ( Math.random() * 0.8 + 0.1 );
  113. particleArray[ i * particleStructSize + 1 ] = ( Math.random() * 0.8 + 0.1 );
  114. particleArray[ i * particleStructSize + 2 ] = ( Math.random() * 0.8 + 0.1 );
  115. }
  116. particleBuffer = instancedArray( particleArray, particleStruct );
  117. const cellCount = gridSize.x * gridSize.y * gridSize.z;
  118. const cellStruct = struct( {
  119. x: { type: 'int', atomic: true },
  120. y: { type: 'int', atomic: true },
  121. z: { type: 'int', atomic: true },
  122. mass: { type: 'int', atomic: true },
  123. } );
  124. cellBuffer = instancedArray( cellCount, cellStruct );
  125. cellBufferFloat = instancedArray( cellCount, 'vec4' );
  126. }
  127. function setupUniforms() {
  128. gridSizeUniform = uniform( gridSize );
  129. particleCountUniform = uniform( params.particleCount, 'uint' );
  130. stiffnessUniform = uniform( 50 );
  131. restDensityUniform = uniform( 1.5 );
  132. dynamicViscosityUniform = uniform( 0.1 );
  133. dtUniform = uniform( 1 / 60 );
  134. gravityUniform = uniform( new THREE.Vector3( 0, - ( 9.81 * 9.81 ), 0 ) );
  135. mouseRayOriginUniform = uniform( new THREE.Vector3( 0, 0, 0 ) );
  136. mouseRayDirectionUniform = uniform( new THREE.Vector3( 0, 0, 0 ) );
  137. mouseForceUniform = uniform( new THREE.Vector3( 0, 0, 0 ) );
  138. // gui.add(restDensityUniform, "value", 1.0, 3, 0.1).name("restDensity");
  139. // it's interesting to adjust the restDensity but it might cause the simulation to become unstable
  140. }
  141. function setupComputeShaders() {
  142. // the MLS-MPM system uses five compute shaders:
  143. // 1. clearGridKernel: this clears the grid before each pass
  144. // 2. p2g1Kernel & 3. p2g2Kernel: These particle2grid kernels transfer the particles' energy to the grid
  145. // 4. updateGridKernel: updates the grid
  146. // 5. g2pKernel: grid2particle kernel, transfers the grid energy back to the particles
  147. // the implementation closely follows https://github.com/matsuoka-601/WebGPU-Ocean
  148. // because webgpu only supports int atomics, we use fixed point floats by multiplying/dividing the float values with a high integer constant
  149. const encodeFixedPoint = ( f32 ) => {
  150. return int( f32.mul( fixedPointMultiplier ) );
  151. };
  152. const decodeFixedPoint = ( i32 ) => {
  153. return float( i32 ).div( fixedPointMultiplier );
  154. };
  155. const cellCount = gridSize.x * gridSize.y * gridSize.z;
  156. clearGridKernel = Fn( () => {
  157. If( instanceIndex.greaterThanEqual( uint( cellCount ) ), () => {
  158. Return();
  159. } );
  160. atomicStore( cellBuffer.element( instanceIndex ).get( 'x' ), 0 );
  161. atomicStore( cellBuffer.element( instanceIndex ).get( 'y' ), 0 );
  162. atomicStore( cellBuffer.element( instanceIndex ).get( 'z' ), 0 );
  163. atomicStore( cellBuffer.element( instanceIndex ).get( 'mass' ), 0 );
  164. } )().compute( cellCount ).setName( 'clearGridKernel' );
  165. p2g1Kernel = Fn( () => {
  166. If( instanceIndex.greaterThanEqual( particleCountUniform ), () => {
  167. Return();
  168. } );
  169. const particlePosition = particleBuffer.element( instanceIndex ).get( 'position' ).toConst( 'particlePosition' );
  170. const particleVelocity = particleBuffer.element( instanceIndex ).get( 'velocity' ).toConst( 'particleVelocity' );
  171. const C = particleBuffer.element( instanceIndex ).get( 'C' ).toConst( 'C' );
  172. const gridPosition = particlePosition.mul( gridSizeUniform ).toVar();
  173. const cellIndex = ivec3( gridPosition ).sub( 1 ).toConst( 'cellIndex' );
  174. const cellDiff = gridPosition.fract().sub( 0.5 ).toConst( 'cellDiff' );
  175. const w0 = float( 0.5 ).mul( float( 0.5 ).sub( cellDiff ) ).mul( float( 0.5 ).sub( cellDiff ) );
  176. const w1 = float( 0.75 ).sub( cellDiff.mul( cellDiff ) );
  177. const w2 = float( 0.5 ).mul( float( 0.5 ).add( cellDiff ) ).mul( float( 0.5 ).add( cellDiff ) );
  178. const weights = array( [ w0, w1, w2 ] ).toConst( 'weights' );
  179. Loop( { start: 0, end: 3, type: 'int', name: 'gx', condition: '<' }, ( { gx } ) => {
  180. Loop( { start: 0, end: 3, type: 'int', name: 'gy', condition: '<' }, ( { gy } ) => {
  181. Loop( { start: 0, end: 3, type: 'int', name: 'gz', condition: '<' }, ( { gz } ) => {
  182. const weight = weights.element( gx ).x.mul( weights.element( gy ).y ).mul( weights.element( gz ).z );
  183. const cellX = cellIndex.add( ivec3( gx, gy, gz ) ).toConst();
  184. const cellDist = vec3( cellX ).add( 0.5 ).sub( gridPosition ).toConst( 'cellDist' );
  185. const Q = C.mul( cellDist );
  186. const massContrib = weight; // assuming particle mass = 1.0
  187. const velContrib = massContrib.mul( particleVelocity.add( Q ) ).toConst( 'velContrib' );
  188. const cellPtr = cellX.x.mul( int( gridSize.y * gridSize.z ) ).add( cellX.y.mul( int( gridSize.z ) ) ).add( cellX.z ).toConst();
  189. const cell = cellBuffer.element( cellPtr );
  190. atomicAdd( cell.get( 'x' ), encodeFixedPoint( velContrib.x ) );
  191. atomicAdd( cell.get( 'y' ), encodeFixedPoint( velContrib.y ) );
  192. atomicAdd( cell.get( 'z' ), encodeFixedPoint( velContrib.z ) );
  193. atomicAdd( cell.get( 'mass' ), encodeFixedPoint( massContrib ) );
  194. } );
  195. } );
  196. } );
  197. } )().compute( params.particleCount, [ workgroupSize, 1, 1 ] ).setName( 'p2g1Kernel' );
  198. p2g2Kernel = Fn( () => {
  199. If( instanceIndex.greaterThanEqual( particleCountUniform ), () => {
  200. Return();
  201. } );
  202. const particlePosition = particleBuffer.element( instanceIndex ).get( 'position' ).toConst( 'particlePosition' );
  203. const gridPosition = particlePosition.mul( gridSizeUniform ).toVar();
  204. const cellIndex = ivec3( gridPosition ).sub( 1 ).toConst( 'cellIndex' );
  205. const cellDiff = gridPosition.fract().sub( 0.5 ).toConst( 'cellDiff' );
  206. const w0 = float( 0.5 ).mul( float( 0.5 ).sub( cellDiff ) ).mul( float( 0.5 ).sub( cellDiff ) );
  207. const w1 = float( 0.75 ).sub( cellDiff.mul( cellDiff ) );
  208. const w2 = float( 0.5 ).mul( float( 0.5 ).add( cellDiff ) ).mul( float( 0.5 ).add( cellDiff ) );
  209. const weights = array( [ w0, w1, w2 ] ).toConst( 'weights' );
  210. const density = float( 0 ).toVar( 'density' );
  211. Loop( { start: 0, end: 3, type: 'int', name: 'gx', condition: '<' }, ( { gx } ) => {
  212. Loop( { start: 0, end: 3, type: 'int', name: 'gy', condition: '<' }, ( { gy } ) => {
  213. Loop( { start: 0, end: 3, type: 'int', name: 'gz', condition: '<' }, ( { gz } ) => {
  214. const weight = weights.element( gx ).x.mul( weights.element( gy ).y ).mul( weights.element( gz ).z );
  215. const cellX = cellIndex.add( ivec3( gx, gy, gz ) ).toConst();
  216. const cellPtr = cellX.x.mul( int( gridSize.y * gridSize.z ) ).add( cellX.y.mul( int( gridSize.z ) ) ).add( cellX.z ).toConst();
  217. const cell = cellBuffer.element( cellPtr );
  218. const mass = decodeFixedPoint( atomicLoad( cell.get( 'mass' ) ) );
  219. density.addAssign( mass.mul( weight ) );
  220. } );
  221. } );
  222. } );
  223. const volume = float( 1 ).div( density );
  224. const pressure = max( 0.0, pow( density.div( restDensityUniform ), 5.0 ).sub( 1 ).mul( stiffnessUniform ) ).toConst( 'pressure' );
  225. const stress = mat3( pressure.negate(), 0, 0, 0, pressure.negate(), 0, 0, 0, pressure.negate() ).toVar( 'stress' );
  226. const dudv = particleBuffer.element( instanceIndex ).get( 'C' ).toConst( 'C' );
  227. const strain = dudv.add( dudv.transpose() );
  228. stress.addAssign( strain.mul( dynamicViscosityUniform ) );
  229. const eq16Term0 = volume.mul( - 4 ).mul( stress ).mul( dtUniform );
  230. Loop( { start: 0, end: 3, type: 'int', name: 'gx', condition: '<' }, ( { gx } ) => {
  231. Loop( { start: 0, end: 3, type: 'int', name: 'gy', condition: '<' }, ( { gy } ) => {
  232. Loop( { start: 0, end: 3, type: 'int', name: 'gz', condition: '<' }, ( { gz } ) => {
  233. const weight = weights.element( gx ).x.mul( weights.element( gy ).y ).mul( weights.element( gz ).z );
  234. const cellX = cellIndex.add( ivec3( gx, gy, gz ) ).toConst();
  235. const cellDist = vec3( cellX ).add( 0.5 ).sub( gridPosition ).toConst( 'cellDist' );
  236. const momentum = eq16Term0.mul( weight ).mul( cellDist ).toConst( 'momentum' );
  237. const cellPtr = cellX.x.mul( int( gridSize.y * gridSize.z ) ).add( cellX.y.mul( int( gridSize.z ) ) ).add( cellX.z ).toConst();
  238. const cell = cellBuffer.element( cellPtr );
  239. atomicAdd( cell.get( 'x' ), encodeFixedPoint( momentum.x ) );
  240. atomicAdd( cell.get( 'y' ), encodeFixedPoint( momentum.y ) );
  241. atomicAdd( cell.get( 'z' ), encodeFixedPoint( momentum.z ) );
  242. } );
  243. } );
  244. } );
  245. } )().compute( params.particleCount, [ workgroupSize, 1, 1 ] ).setName( 'p2g2Kernel' );
  246. updateGridKernel = Fn( () => {
  247. If( instanceIndex.greaterThanEqual( uint( cellCount ) ), () => {
  248. Return();
  249. } );
  250. const cell = cellBuffer.element( instanceIndex );
  251. const mass = decodeFixedPoint( atomicLoad( cell.get( 'mass' ) ) ).toConst();
  252. If( mass.lessThanEqual( 0 ), () => {
  253. Return();
  254. } );
  255. const vx = decodeFixedPoint( atomicLoad( cell.get( 'x' ) ) ).div( mass ).toVar();
  256. const vy = decodeFixedPoint( atomicLoad( cell.get( 'y' ) ) ).div( mass ).toVar();
  257. const vz = decodeFixedPoint( atomicLoad( cell.get( 'z' ) ) ).div( mass ).toVar();
  258. const x = int( instanceIndex ).div( int( gridSize.z * gridSize.y ) );
  259. const y = int( instanceIndex ).div( int( gridSize.z ) ).mod( int( gridSize.y ) );
  260. const z = int( instanceIndex ).mod( int( gridSize.z ) );
  261. If( x.lessThan( int( 1 ) ).or( x.greaterThan( int( gridSize.x ).sub( int( 2 ) ) ) ), () => {
  262. vx.assign( 0 );
  263. } );
  264. If( y.lessThan( int( 1 ) ).or( y.greaterThan( int( gridSize.y ).sub( int( 2 ) ) ) ), () => {
  265. vy.assign( 0 );
  266. } );
  267. If( z.lessThan( int( 1 ) ).or( z.greaterThan( int( gridSize.z ).sub( int( 2 ) ) ) ), () => {
  268. vz.assign( 0 );
  269. } );
  270. cellBufferFloat.element( instanceIndex ).assign( vec4( vx, vy, vz, mass ) );
  271. } )().compute( cellCount ).setName( 'updateGridKernel' );
  272. const clampToRoundedBox = ( pos, box, radius ) => {
  273. const result = pos.sub( 0.5 ).toVar();
  274. const pp = step( box, result.abs() ).mul( result.add( box.negate().mul( result.sign() ) ) );
  275. const ppLen = pp.length().toVar();
  276. const dist = ppLen.sub( radius );
  277. If( dist.greaterThan( 0.0 ), () => {
  278. result.subAssign( pp.normalize().mul( dist ).mul( 1.3 ) );
  279. } );
  280. result.addAssign( 0.5 );
  281. return result;
  282. };
  283. g2pKernel = Fn( () => {
  284. If( instanceIndex.greaterThanEqual( particleCountUniform ), () => {
  285. Return();
  286. } );
  287. const particlePosition = particleBuffer.element( instanceIndex ).get( 'position' ).toVar( 'particlePosition' );
  288. const gridPosition = particlePosition.mul( gridSizeUniform ).toVar();
  289. const particleVelocity = vec3( 0 ).toVar();
  290. const cellIndex = ivec3( gridPosition ).sub( 1 ).toConst( 'cellIndex' );
  291. const cellDiff = gridPosition.fract().sub( 0.5 ).toConst( 'cellDiff' );
  292. const w0 = float( 0.5 ).mul( float( 0.5 ).sub( cellDiff ) ).mul( float( 0.5 ).sub( cellDiff ) );
  293. const w1 = float( 0.75 ).sub( cellDiff.mul( cellDiff ) );
  294. const w2 = float( 0.5 ).mul( float( 0.5 ).add( cellDiff ) ).mul( float( 0.5 ).add( cellDiff ) );
  295. const weights = array( [ w0, w1, w2 ] ).toConst( 'weights' );
  296. const B = mat3( 0 ).toVar( 'B' );
  297. Loop( { start: 0, end: 3, type: 'int', name: 'gx', condition: '<' }, ( { gx } ) => {
  298. Loop( { start: 0, end: 3, type: 'int', name: 'gy', condition: '<' }, ( { gy } ) => {
  299. Loop( { start: 0, end: 3, type: 'int', name: 'gz', condition: '<' }, ( { gz } ) => {
  300. const weight = weights.element( gx ).x.mul( weights.element( gy ).y ).mul( weights.element( gz ).z );
  301. const cellX = cellIndex.add( ivec3( gx, gy, gz ) ).toConst();
  302. const cellDist = vec3( cellX ).add( 0.5 ).sub( gridPosition ).toConst( 'cellDist' );
  303. const cellPtr = cellX.x.mul( int( gridSize.y * gridSize.z ) ).add( cellX.y.mul( int( gridSize.z ) ) ).add( cellX.z ).toConst();
  304. const weightedVelocity = cellBufferFloat.element( cellPtr ).xyz.mul( weight ).toConst( 'weightedVelocity' );
  305. const term = mat3(
  306. weightedVelocity.mul( cellDist.x ),
  307. weightedVelocity.mul( cellDist.y ),
  308. weightedVelocity.mul( cellDist.z )
  309. );
  310. B.addAssign( term );
  311. particleVelocity.addAssign( weightedVelocity );
  312. } );
  313. } );
  314. } );
  315. particleBuffer.element( instanceIndex ).get( 'C' ).assign( B.mul( 4 ) );
  316. // gravity
  317. particleVelocity.addAssign( gravityUniform.mul( dtUniform ) );
  318. // scale from (gridSize.x, gridSize.y, gridSize.z) to (1, 1, 1)
  319. particleVelocity.divAssign( gridSizeUniform );
  320. // mouseInteraction
  321. const dist = cross( mouseRayDirectionUniform, particlePosition.sub( mouseRayOriginUniform ) ).length();
  322. const force = dist.mul( 3.00 ).oneMinus().max( 0.0 ).pow( 2 );
  323. particleVelocity.addAssign( mouseForceUniform.mul( force ) );
  324. // add velocity to position
  325. particlePosition.addAssign( particleVelocity.mul( dtUniform ) );
  326. // clamp position so outermost gridCells are not reached
  327. particlePosition.assign( clamp( particlePosition, vec3( 1 ).div( gridSizeUniform ), vec3( gridSize ).sub( 1 ).div( gridSizeUniform ) ) );
  328. // add force for particles to stay within rounded box
  329. const innerBox = gridSizeUniform.mul( 0.5 ).sub( 9.0 ).div( gridSizeUniform ).toVar();
  330. const innerRadius = float( 6.0 ).div( gridSizeUniform.x );
  331. const posNext = particlePosition.add( particleVelocity.mul( dtUniform ).mul( 2.0 ) ).toConst( 'posNext' );
  332. const posNextClamped = clampToRoundedBox( posNext, innerBox, innerRadius );
  333. particleVelocity.addAssign( posNextClamped.sub( posNext ) );
  334. /*
  335. const wallStiffness = 1.0;
  336. const xN = particlePosition.add( particleVelocity.mul( dtUniform ).mul( 2.0 ) ).toConst( 'xN' );
  337. const wallMin = vec3( 3 ).div(gridSizeUniform).toConst( 'wallMin' );
  338. const wallMax = vec3( gridSize ).sub( 3 ).div(gridSizeUniform).toConst( 'wallMax' );
  339. particleVelocity.addAssign( wallMin.sub( xN ).max( 0.0 ).mul( wallStiffness ) );
  340. particleVelocity.addAssign( wallMax.sub( xN ).min( 0.0 ).mul( wallStiffness ) );
  341. */
  342. // scale from (1, 1, 1) back to (gridSize.x, gridSize.y, gridSize.z) to
  343. particleVelocity.mulAssign( gridSizeUniform );
  344. particleBuffer.element( instanceIndex ).get( 'position' ).assign( particlePosition );
  345. particleBuffer.element( instanceIndex ).get( 'velocity' ).assign( particleVelocity );
  346. } )().compute( params.particleCount, [ workgroupSize, 1, 1 ] ).setName( 'g2pKernel' );
  347. }
  348. function setupMesh() {
  349. // mergeVertices to reduce the number of vertexShaderCalls
  350. const geometry = BufferGeometryUtils.mergeVertices( new THREE.IcosahedronGeometry( 0.008, 1 ).deleteAttribute( 'uv' ) );
  351. const material = new THREE.MeshStandardNodeMaterial( {
  352. color: '#0066FF'
  353. } );
  354. material.positionNode = Fn( () => {
  355. const particlePosition = particleBuffer.element( instanceIndex ).get( 'position' );
  356. return attribute( 'position' ).add( particlePosition );
  357. } )();
  358. particleMesh = new THREE.Mesh( geometry, material );
  359. particleMesh.count = params.particleCount;
  360. particleMesh.position.set( - 0.5, 0, - 0.5 );
  361. particleMesh.frustumCulled = false;
  362. scene.add( particleMesh );
  363. }
  364. function setupMouse() {
  365. const raycaster = new THREE.Raycaster();
  366. const raycastPlane = new THREE.Plane( new THREE.Vector3( 0, 1, 0 ) );
  367. const onMove = ( event ) => {
  368. const pointer = new THREE.Vector2( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );
  369. raycaster.setFromCamera( pointer, camera );
  370. raycaster.ray.origin.x += 0.5;
  371. raycaster.ray.origin.z += 0.5;
  372. mouseRayOriginUniform.value.copy( raycaster.ray.origin );
  373. mouseRayDirectionUniform.value.copy( raycaster.ray.direction );
  374. raycaster.ray.intersectPlane( raycastPlane, mouseCoord );
  375. };
  376. renderer.domElement.addEventListener( 'pointermove', onMove );
  377. }
  378. function setupParticles() {
  379. setupBuffers();
  380. setupUniforms();
  381. setupComputeShaders();
  382. setupMesh();
  383. setupMouse();
  384. }
  385. function onWindowResize() {
  386. camera.aspect = window.innerWidth / window.innerHeight;
  387. camera.updateProjectionMatrix();
  388. renderer.setSize( window.innerWidth, window.innerHeight );
  389. }
  390. async function render() {
  391. const deltaTime = THREE.MathUtils.clamp( clock.getDelta(), 0.00001, 1 / 60 ); // don't advance the time too far, for example when the window is out of focus
  392. dtUniform.value = deltaTime;
  393. mouseForceUniform.value.copy( mouseCoord ).sub( prevMouseCoord ).multiplyScalar( 2 );
  394. const mouseForceLength = mouseForceUniform.value.length();
  395. if ( mouseForceLength > 0.3 ) {
  396. mouseForceUniform.value.multiplyScalar( 0.3 / mouseForceLength );
  397. }
  398. prevMouseCoord.copy( mouseCoord );
  399. renderer.compute( workgroupKernel );
  400. //renderer.compute( [ clearGridKernel, p2g1Kernel, p2g2Kernel, updateGridKernel, g2pKernel ] );
  401. renderer.compute( clearGridKernel );
  402. renderer.compute( p2g1Kernel, p2g1KernelWorkgroupBuffer );
  403. renderer.compute( p2g2Kernel, p2g2KernelWorkgroupBuffer );
  404. renderer.compute( updateGridKernel );
  405. renderer.compute( g2pKernel, g2pKernelWorkgroupBuffer );
  406. renderer.render( scene, camera );
  407. }
  408. </script>
  409. </body>
  410. </html>
粤ICP备19079148号