webgpu_compute_particles_fluid.html 21 KB

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