webgpu_compute_particles_fluid.html 23 KB

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