webgpu_compute_particles.html 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. <html lang="en">
  2. <head>
  3. <title>three.js - WebGPU - Compute Particles</title>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  6. <link type="text/css" rel="stylesheet" href="main.css">
  7. </head>
  8. <body>
  9. <div id="info">
  10. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> WebGPU - Compute - 1M Particles
  11. <div id="timestamps" style="
  12. position: absolute;
  13. top: 60px;
  14. left: 0;
  15. padding: 10px;
  16. background: rgba( 0, 0, 0, 0.5 );
  17. color: #fff;
  18. font-family: monospace;
  19. font-size: 12px;
  20. line-height: 1.5;
  21. pointer-events: none;
  22. text-align: left;
  23. "></div>
  24. </div>
  25. <script type="importmap">
  26. {
  27. "imports": {
  28. "three": "../build/three.webgpu.js",
  29. "three/tsl": "../build/three.webgpu.js",
  30. "three/addons/": "./jsm/"
  31. }
  32. }
  33. </script>
  34. <script type="module">
  35. import * as THREE from 'three';
  36. import { Fn, uniform, texture, instanceIndex, float, hash, vec3, storage, If } from 'three/tsl';
  37. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  38. import Stats from 'three/addons/libs/stats.module.js';
  39. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  40. const particleCount = 1000000;
  41. const gravity = uniform( - .0098 );
  42. const bounce = uniform( .8 );
  43. const friction = uniform( .99 );
  44. const size = uniform( .12 );
  45. const clickPosition = uniform( new THREE.Vector3() );
  46. let camera, scene, renderer;
  47. let controls, stats;
  48. let computeParticles;
  49. const timestamps = document.getElementById( 'timestamps' );
  50. init();
  51. function init() {
  52. const { innerWidth, innerHeight } = window;
  53. camera = new THREE.PerspectiveCamera( 50, innerWidth / innerHeight, .1, 1000 );
  54. camera.position.set( 15, 30, 15 );
  55. scene = new THREE.Scene();
  56. // textures
  57. const textureLoader = new THREE.TextureLoader();
  58. const map = textureLoader.load( 'textures/sprite1.png' );
  59. //
  60. const createBuffer = () => storage( new THREE.StorageInstancedBufferAttribute( particleCount, 3 ), 'vec3', particleCount );
  61. const positionBuffer = createBuffer();
  62. const velocityBuffer = createBuffer();
  63. const colorBuffer = createBuffer();
  64. // compute
  65. const computeInit = Fn( () => {
  66. const position = positionBuffer.element( instanceIndex );
  67. const color = colorBuffer.element( instanceIndex );
  68. const randX = hash( instanceIndex );
  69. const randY = hash( instanceIndex.add( 2 ) );
  70. const randZ = hash( instanceIndex.add( 3 ) );
  71. position.x = randX.mul( 100 ).add( - 50 );
  72. position.y = 0; // randY.mul( 10 );
  73. position.z = randZ.mul( 100 ).add( - 50 );
  74. color.assign( vec3( randX, randY, randZ ) );
  75. } )().compute( particleCount );
  76. //
  77. const computeUpdate = Fn( () => {
  78. const position = positionBuffer.element( instanceIndex );
  79. const velocity = velocityBuffer.element( instanceIndex );
  80. velocity.addAssign( vec3( 0.00, gravity, 0.00 ) );
  81. position.addAssign( velocity );
  82. velocity.mulAssign( friction );
  83. // floor
  84. If( position.y.lessThan( 0 ), () => {
  85. position.y = 0;
  86. velocity.y = velocity.y.negate().mul( bounce );
  87. // floor friction
  88. velocity.x = velocity.x.mul( .9 );
  89. velocity.z = velocity.z.mul( .9 );
  90. } );
  91. } );
  92. computeParticles = computeUpdate().compute( particleCount );
  93. // create nodes
  94. const textureNode = texture( map );
  95. // create particles
  96. const particleMaterial = new THREE.SpriteNodeMaterial();
  97. particleMaterial.colorNode = textureNode.mul( colorBuffer.element( instanceIndex ) );
  98. particleMaterial.positionNode = positionBuffer.toAttribute();
  99. particleMaterial.scaleNode = size;
  100. particleMaterial.depthWrite = false;
  101. particleMaterial.depthTest = true;
  102. particleMaterial.transparent = true;
  103. const particles = new THREE.Mesh( new THREE.PlaneGeometry( 1, 1 ), particleMaterial );
  104. particles.count = particleCount;
  105. particles.frustumCulled = false;
  106. scene.add( particles );
  107. //
  108. const helper = new THREE.GridHelper( 60, 40, 0x303030, 0x303030 );
  109. scene.add( helper );
  110. const geometry = new THREE.PlaneGeometry( 1000, 1000 );
  111. geometry.rotateX( - Math.PI / 2 );
  112. const plane = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { visible: false } ) );
  113. scene.add( plane );
  114. const raycaster = new THREE.Raycaster();
  115. const pointer = new THREE.Vector2();
  116. //
  117. renderer = new THREE.WebGPURenderer( { antialias: true, trackTimestamp: true } );
  118. renderer.setPixelRatio( window.devicePixelRatio );
  119. renderer.setSize( window.innerWidth, window.innerHeight );
  120. renderer.setAnimationLoop( animate );
  121. document.body.appendChild( renderer.domElement );
  122. stats = new Stats();
  123. document.body.appendChild( stats.dom );
  124. //
  125. renderer.compute( computeInit );
  126. // click event
  127. const computeHit = Fn( () => {
  128. const position = positionBuffer.element( instanceIndex );
  129. const velocity = velocityBuffer.element( instanceIndex );
  130. const dist = position.distance( clickPosition );
  131. const direction = position.sub( clickPosition ).normalize();
  132. const distArea = float( 6 ).sub( dist ).max( 0 );
  133. const power = distArea.mul( .01 );
  134. const relativePower = power.mul( hash( instanceIndex ).mul( .5 ).add( .5 ) );
  135. velocity.assign( velocity.add( direction.mul( relativePower ) ) );
  136. } )().compute( particleCount );
  137. //
  138. function onMove( event ) {
  139. pointer.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );
  140. raycaster.setFromCamera( pointer, camera );
  141. const intersects = raycaster.intersectObjects( [ plane ], false );
  142. if ( intersects.length > 0 ) {
  143. const { point } = intersects[ 0 ];
  144. // move to uniform
  145. clickPosition.value.copy( point );
  146. clickPosition.value.y = - 1;
  147. // compute
  148. renderer.compute( computeHit );
  149. }
  150. }
  151. // events
  152. renderer.domElement.addEventListener( 'pointermove', onMove );
  153. //
  154. controls = new OrbitControls( camera, renderer.domElement );
  155. controls.minDistance = 5;
  156. controls.maxDistance = 200;
  157. controls.target.set( 0, 0, 0 );
  158. controls.update();
  159. //
  160. window.addEventListener( 'resize', onWindowResize );
  161. // gui
  162. const gui = new GUI();
  163. gui.add( gravity, 'value', - .0098, 0, 0.0001 ).name( 'gravity' );
  164. gui.add( bounce, 'value', .1, 1, 0.01 ).name( 'bounce' );
  165. gui.add( friction, 'value', .96, .99, 0.01 ).name( 'friction' );
  166. gui.add( size, 'value', .12, .5, 0.01 ).name( 'size' );
  167. }
  168. function onWindowResize() {
  169. const { innerWidth, innerHeight } = window;
  170. camera.aspect = innerWidth / innerHeight;
  171. camera.updateProjectionMatrix();
  172. renderer.setSize( innerWidth, innerHeight );
  173. }
  174. async function animate() {
  175. stats.update();
  176. await renderer.computeAsync( computeParticles );
  177. await renderer.renderAsync( scene, camera );
  178. // throttle the logging
  179. if ( renderer.hasFeature( 'timestamp-query' ) ) {
  180. if ( renderer.info.render.calls % 5 === 0 ) {
  181. timestamps.innerHTML = `
  182. Compute ${renderer.info.compute.frameCalls} pass in ${renderer.info.compute.timestamp.toFixed( 6 )}ms<br>
  183. Draw ${renderer.info.render.drawCalls} pass in ${renderer.info.render.timestamp.toFixed( 6 )}ms`;
  184. }
  185. } else {
  186. timestamps.innerHTML = 'Timestamp queries not supported';
  187. }
  188. }
  189. </script>
  190. </body>
  191. </html>