webgpu_compute_particles.html 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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, instancedArray, instanceIndex, float, hash, vec3, 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 positionBuffer = instancedArray( particleCount, 'vec3' );
  61. const velocityBuffer = instancedArray( particleCount, 'vec3' );
  62. const colorBuffer = instancedArray( particleCount, 'vec3' );
  63. // compute
  64. const computeInit = Fn( () => {
  65. const position = positionBuffer.element( instanceIndex );
  66. const color = colorBuffer.element( instanceIndex );
  67. const randX = hash( instanceIndex );
  68. const randY = hash( instanceIndex.add( 2 ) );
  69. const randZ = hash( instanceIndex.add( 3 ) );
  70. position.x = randX.mul( 100 ).add( - 50 );
  71. position.y = 0; // randY.mul( 10 );
  72. position.z = randZ.mul( 100 ).add( - 50 );
  73. color.assign( vec3( randX, randY, randZ ) );
  74. } )().compute( particleCount );
  75. //
  76. const computeUpdate = Fn( () => {
  77. const position = positionBuffer.element( instanceIndex );
  78. const velocity = velocityBuffer.element( instanceIndex );
  79. velocity.addAssign( vec3( 0.00, gravity, 0.00 ) );
  80. position.addAssign( velocity );
  81. velocity.mulAssign( friction );
  82. // floor
  83. If( position.y.lessThan( 0 ), () => {
  84. position.y = 0;
  85. velocity.y = velocity.y.negate().mul( bounce );
  86. // floor friction
  87. velocity.x = velocity.x.mul( .9 );
  88. velocity.z = velocity.z.mul( .9 );
  89. } );
  90. } );
  91. computeParticles = computeUpdate().compute( particleCount );
  92. // create nodes
  93. const textureNode = texture( map );
  94. // create particles
  95. const particleMaterial = new THREE.SpriteNodeMaterial();
  96. particleMaterial.colorNode = textureNode.mul( colorBuffer.element( instanceIndex ) );
  97. particleMaterial.positionNode = positionBuffer.toAttribute();
  98. particleMaterial.scaleNode = size;
  99. particleMaterial.depthWrite = false;
  100. particleMaterial.depthTest = true;
  101. particleMaterial.transparent = true;
  102. const particles = new THREE.Mesh( new THREE.PlaneGeometry( 1, 1 ), particleMaterial );
  103. particles.count = particleCount;
  104. particles.frustumCulled = false;
  105. scene.add( particles );
  106. //
  107. const helper = new THREE.GridHelper( 60, 40, 0x303030, 0x303030 );
  108. scene.add( helper );
  109. const geometry = new THREE.PlaneGeometry( 1000, 1000 );
  110. geometry.rotateX( - Math.PI / 2 );
  111. const plane = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { visible: false } ) );
  112. scene.add( plane );
  113. const raycaster = new THREE.Raycaster();
  114. const pointer = new THREE.Vector2();
  115. //
  116. renderer = new THREE.WebGPURenderer( { antialias: true, trackTimestamp: true } );
  117. renderer.setPixelRatio( window.devicePixelRatio );
  118. renderer.setSize( window.innerWidth, window.innerHeight );
  119. renderer.setAnimationLoop( animate );
  120. document.body.appendChild( renderer.domElement );
  121. stats = new Stats();
  122. document.body.appendChild( stats.dom );
  123. //
  124. renderer.computeAsync( computeInit );
  125. // click event
  126. const computeHit = Fn( () => {
  127. const position = positionBuffer.element( instanceIndex );
  128. const velocity = velocityBuffer.element( instanceIndex );
  129. const dist = position.distance( clickPosition );
  130. const direction = position.sub( clickPosition ).normalize();
  131. const distArea = float( 6 ).sub( dist ).max( 0 );
  132. const power = distArea.mul( .01 );
  133. const relativePower = power.mul( hash( instanceIndex ).mul( .5 ).add( .5 ) );
  134. velocity.assign( velocity.add( direction.mul( relativePower ) ) );
  135. } )().compute( particleCount );
  136. //
  137. function onMove( event ) {
  138. pointer.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );
  139. raycaster.setFromCamera( pointer, camera );
  140. const intersects = raycaster.intersectObjects( [ plane ], false );
  141. if ( intersects.length > 0 ) {
  142. const { point } = intersects[ 0 ];
  143. // move to uniform
  144. clickPosition.value.copy( point );
  145. clickPosition.value.y = - 1;
  146. // compute
  147. renderer.computeAsync( computeHit );
  148. }
  149. }
  150. // events
  151. renderer.domElement.addEventListener( 'pointermove', onMove );
  152. //
  153. controls = new OrbitControls( camera, renderer.domElement );
  154. controls.minDistance = 5;
  155. controls.maxDistance = 200;
  156. controls.target.set( 0, 0, 0 );
  157. controls.update();
  158. //
  159. window.addEventListener( 'resize', onWindowResize );
  160. // gui
  161. const gui = new GUI();
  162. gui.add( gravity, 'value', - .0098, 0, 0.0001 ).name( 'gravity' );
  163. gui.add( bounce, 'value', .1, 1, 0.01 ).name( 'bounce' );
  164. gui.add( friction, 'value', .96, .99, 0.01 ).name( 'friction' );
  165. gui.add( size, 'value', .12, .5, 0.01 ).name( 'size' );
  166. }
  167. function onWindowResize() {
  168. const { innerWidth, innerHeight } = window;
  169. camera.aspect = innerWidth / innerHeight;
  170. camera.updateProjectionMatrix();
  171. renderer.setSize( innerWidth, innerHeight );
  172. }
  173. async function animate() {
  174. stats.update();
  175. await renderer.computeAsync( computeParticles );
  176. await renderer.renderAsync( scene, camera );
  177. // throttle the logging
  178. if ( renderer.hasFeature( 'timestamp-query' ) ) {
  179. if ( renderer.info.render.calls % 5 === 0 ) {
  180. timestamps.innerHTML = `
  181. Compute ${renderer.info.compute.frameCalls} pass in ${renderer.info.compute.timestamp.toFixed( 6 )}ms<br>
  182. Draw ${renderer.info.render.drawCalls} pass in ${renderer.info.render.timestamp.toFixed( 6 )}ms`;
  183. }
  184. } else {
  185. timestamps.innerHTML = 'Timestamp queries not supported';
  186. }
  187. }
  188. </script>
  189. </body>
  190. </html>
粤ICP备19079148号