webgpu_compute.html 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. <html lang="en">
  2. <head>
  3. <title>three.js - WebGPU - Compute</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. <!-- WebGPU (For Chrome 94-97), expires 10/11/2021 -->
  8. <meta http-equiv="origin-trial" content="Agfr4hEaaoH1kaTtGTZY4OU2lQQOv+gWq+8rYeHZBPWNnLww/smePFCIJOUdRFnQZkO3KAio+SNJapjzaoyFfQQAAABLeyJvcmlnaW4iOiJodHRwczovL3RocmVlanMub3JnOjQ0MyIsImZlYXR1cmUiOiJXZWJHUFUiLCJleHBpcnkiOjE2NDMxNTUxOTl9">
  9. </head>
  10. <body>
  11. <div id="info">
  12. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> WebGPU - Compute<br/>(Chrome Canary with flag: --enable-unsafe-webgpu)
  13. </div>
  14. <script type="importmap">
  15. {
  16. "imports": {
  17. "three": "../build/three.module.js"
  18. }
  19. }
  20. </script>
  21. <script type="module">
  22. import * as THREE from 'three';
  23. import { GUI } from './jsm/libs/dat.gui.module.js';
  24. import WebGPURenderer from './jsm/renderers/webgpu/WebGPURenderer.js';
  25. import WebGPU from './jsm/renderers/webgpu/WebGPU.js';
  26. import WebGPUStorageBuffer from './jsm/renderers/webgpu/WebGPUStorageBuffer.js';
  27. import WebGPUUniformBuffer from './jsm/renderers/webgpu/WebGPUUniformBuffer.js';
  28. import * as WebGPUBufferUtils from './jsm/renderers/webgpu/WebGPUBufferUtils.js';
  29. import WebGPUUniformsGroup from './jsm/renderers/webgpu/WebGPUUniformsGroup.js';
  30. import { Vector2Uniform } from './jsm/renderers/webgpu/WebGPUUniform.js';
  31. import * as Nodes from './jsm/renderers/nodes/Nodes.js';
  32. let camera, scene, renderer;
  33. let pointer;
  34. let scaleUniformBuffer;
  35. let scaleVector = new THREE.Vector3( 1, 1, 1 );
  36. const computeParams = [];
  37. init().then( animate ).catch( error );
  38. async function init() {
  39. if ( WebGPU.isAvailable() === false ) {
  40. document.body.appendChild( WebGPU.getErrorMessage() );
  41. throw 'No WebGPU support';
  42. }
  43. camera = new THREE.OrthographicCamera( - 1.0, 1.0, 1.0, - 1.0, 0, 1 );
  44. camera.position.z = 1;
  45. scene = new THREE.Scene();
  46. scene.background = new THREE.Color( 0x000000 );
  47. const particleNum = 65000; // 16-bit limit
  48. const particleSize = 3;
  49. const particleArray = new Float32Array( particleNum * particleSize );
  50. const velocityArray = new Float32Array( particleNum * particleSize );
  51. for ( let i = 0; i < particleArray.length; i += 3 ) {
  52. const r = Math.random() * 0.01 + 0.0005;
  53. const degree = Math.random() * 360;
  54. velocityArray[ i + 0 ] = r * Math.sin( degree * Math.PI / 180 );
  55. velocityArray[ i + 1 ] = r * Math.cos( degree * Math.PI / 180 );
  56. }
  57. const particleBuffer = new WebGPUStorageBuffer( 'particle', new THREE.BufferAttribute( particleArray, 3 ) );
  58. const velocityBuffer = new WebGPUStorageBuffer( 'velocity', new THREE.BufferAttribute( velocityArray, 3 ) );
  59. const scaleUniformLength = WebGPUBufferUtils.getVectorLength( 2, 3 ); // two vector3 for array
  60. scaleUniformBuffer = new WebGPUUniformBuffer( 'scaleUniform', new Float32Array( scaleUniformLength ) );
  61. pointer = new THREE.Vector2( - 10.0, - 10.0 ); // Out of bounds first
  62. const pointerGroup = new WebGPUUniformsGroup( 'mouseUniforms' ).addUniform(
  63. new Vector2Uniform( 'pointer', pointer )
  64. );
  65. // Object keys need follow the binding shader sequence
  66. const computeBindings = [
  67. particleBuffer,
  68. velocityBuffer,
  69. scaleUniformBuffer,
  70. pointerGroup
  71. ];
  72. const computeShader = /* glsl */`#version 450
  73. #define PARTICLE_NUM ${particleNum}
  74. #define PARTICLE_SIZE ${particleSize}
  75. #define ROOM_SIZE 1.0
  76. #define POINTER_SIZE 0.1
  77. // Limitation for now: the order should be the same as bindings order
  78. layout(set = 0, binding = 0) buffer Particle {
  79. float particle[ PARTICLE_NUM * PARTICLE_SIZE ];
  80. } particle;
  81. layout(set = 0, binding = 1) buffer Velocity {
  82. float velocity[ PARTICLE_NUM * PARTICLE_SIZE ];
  83. } velocity;
  84. layout(set = 0, binding = 2) uniform Scale {
  85. vec3 value[2];
  86. } scaleUniform;
  87. layout(set = 0, binding = 3) uniform MouseUniforms {
  88. vec2 pointer;
  89. } mouseUniforms;
  90. void main() {
  91. uint index = gl_GlobalInvocationID.x;
  92. if ( index >= PARTICLE_NUM ) { return; }
  93. vec3 position = vec3(
  94. particle.particle[ index * 3 + 0 ] + velocity.velocity[ index * 3 + 0 ],
  95. particle.particle[ index * 3 + 1 ] + velocity.velocity[ index * 3 + 1 ],
  96. particle.particle[ index * 3 + 2 ] + velocity.velocity[ index * 3 + 2 ]
  97. );
  98. if ( abs( position.x ) >= ROOM_SIZE ) {
  99. velocity.velocity[ index * 3 + 0 ] = - velocity.velocity[ index * 3 + 0 ];
  100. }
  101. if ( abs( position.y ) >= ROOM_SIZE ) {
  102. velocity.velocity[ index * 3 + 1 ] = - velocity.velocity[ index * 3 + 1 ];
  103. }
  104. if ( abs( position.z ) >= ROOM_SIZE ) {
  105. velocity.velocity[ index * 3 + 2 ] = - velocity.velocity[ index * 3 + 2 ];
  106. }
  107. float dx = mouseUniforms.pointer.x - position.x;
  108. float dy = mouseUniforms.pointer.y - position.y;
  109. float distanceFromPointer = sqrt( dx * dx + dy * dy );
  110. if ( distanceFromPointer <= POINTER_SIZE ) {
  111. position.x = 0.0;
  112. position.y = 0.0;
  113. position.z = 0.0;
  114. }
  115. particle.particle[ index * 3 + 0 ] = position.x * scaleUniform.value[0].x;
  116. particle.particle[ index * 3 + 1 ] = position.y * scaleUniform.value[0].y;
  117. particle.particle[ index * 3 + 2 ] = position.z * scaleUniform.value[0].z;
  118. }
  119. `;
  120. computeParams.push( {
  121. num: particleNum,
  122. shader: computeShader,
  123. bindings: computeBindings
  124. } );
  125. // Use a compute shader to animate the point cloud's vertex data.
  126. const pointsGeometry = new THREE.BufferGeometry().setAttribute(
  127. 'position', particleBuffer.attribute
  128. );
  129. const pointsMaterial = new Nodes.PointsNodeMaterial();
  130. pointsMaterial.colorNode = new Nodes.OperatorNode( '+', new Nodes.PositionNode(), new Nodes.ColorNode( new THREE.Color( 0x0000FF ) ) );
  131. const mesh = new THREE.Points( pointsGeometry, pointsMaterial );
  132. scene.add( mesh );
  133. renderer = new WebGPURenderer();
  134. renderer.setPixelRatio( window.devicePixelRatio );
  135. renderer.setSize( window.innerWidth, window.innerHeight );
  136. document.body.appendChild( renderer.domElement );
  137. window.addEventListener( 'resize', onWindowResize );
  138. window.addEventListener( 'mousemove', onMouseMove );
  139. // gui
  140. const gui = new GUI();
  141. gui.add( scaleVector, 'x', 0.9, 1.1, 0.01 );
  142. gui.add( scaleVector, 'y', 0.9, 1.1, 0.01 );
  143. gui.add( scaleVector, 'z', 0.9, 1.1, 0.01 );
  144. return renderer.init();
  145. }
  146. function onWindowResize() {
  147. camera.updateProjectionMatrix();
  148. renderer.setSize( window.innerWidth, window.innerHeight );
  149. }
  150. function onMouseMove( event ) {
  151. const x = event.clientX;
  152. const y = event.clientY;
  153. const width = window.innerWidth;
  154. const height = window.innerHeight;
  155. pointer.set(
  156. ( x / width - 0.5 ) * 2.0,
  157. ( - y / height + 0.5 ) * 2.0
  158. );
  159. }
  160. function animate() {
  161. requestAnimationFrame( animate );
  162. renderer.compute( computeParams );
  163. renderer.render( scene, camera );
  164. scaleVector.toArray( scaleUniformBuffer.buffer, 0 );
  165. }
  166. function error( error ) {
  167. console.error( error );
  168. }
  169. </script>
  170. </body>
  171. </html>