webgpu_compute.html 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 WebGPURenderer from './jsm/renderers/webgpu/WebGPURenderer.js';
  24. import WebGPU from './jsm/renderers/webgpu/WebGPU.js';
  25. import WebGPUStorageBuffer from './jsm/renderers/webgpu/WebGPUStorageBuffer.js';
  26. import WebGPUUniformsGroup from './jsm/renderers/webgpu/WebGPUUniformsGroup.js';
  27. import { Vector2Uniform } from './jsm/renderers/webgpu/WebGPUUniform.js';
  28. import PositionNode from './jsm/renderers/nodes/accessors/PositionNode.js';
  29. import ColorNode from './jsm/renderers/nodes/inputs/ColorNode.js';
  30. import OperatorNode from './jsm/renderers/nodes/math/OperatorNode.js';
  31. let camera, scene, renderer;
  32. let pointer;
  33. const computeParams = [];
  34. init().then( animate ).catch( error );
  35. async function init() {
  36. if ( WebGPU.isAvailable() === false ) {
  37. document.body.appendChild( WebGPU.getErrorMessage() );
  38. throw 'No WebGPU support';
  39. }
  40. camera = new THREE.OrthographicCamera( - 1.0, 1.0, 1.0, - 1.0, 0, 1 );
  41. camera.position.z = 1;
  42. scene = new THREE.Scene();
  43. scene.background = new THREE.Color( 0x000000 );
  44. const particleNum = 50000; // 16-bit limit
  45. const particleSize = 3;
  46. const particleArray = new Float32Array( particleNum * particleSize );
  47. const velocityArray = new Float32Array( particleNum * particleSize );
  48. for ( let i = 0; i < particleArray.length; i += 3 ) {
  49. const r = Math.random() * 0.01 + 0.0005;
  50. const degree = Math.random() * 360;
  51. velocityArray[ i + 0 ] = r * Math.sin( degree * Math.PI / 180 );
  52. velocityArray[ i + 1 ] = r * Math.cos( degree * Math.PI / 180 );
  53. }
  54. const particleBuffer = new WebGPUStorageBuffer( 'particle', new THREE.BufferAttribute( particleArray, 3 ) );
  55. const velocityBuffer = new WebGPUStorageBuffer( 'velocity', new THREE.BufferAttribute( velocityArray, 3 ) );
  56. pointer = new THREE.Vector2( - 10.0, - 10.0 ); // Out of bounds first
  57. const pointerGroup = new WebGPUUniformsGroup( 'mouseUniforms' ).addUniform(
  58. new Vector2Uniform( 'pointer', pointer )
  59. );
  60. const computeBindings = [
  61. particleBuffer,
  62. velocityBuffer,
  63. pointerGroup
  64. ];
  65. const computeShader = /* glsl */`#version 450
  66. #define PARTICLE_NUM ${particleNum}
  67. #define PARTICLE_SIZE ${particleSize}
  68. #define ROOM_SIZE 1.0
  69. #define POINTER_SIZE 0.1
  70. // Limitation for now: the order should be the same as bindings order
  71. layout(set = 0, binding = 0) buffer Particle {
  72. float particle[ PARTICLE_NUM * PARTICLE_SIZE ];
  73. } particle;
  74. layout(set = 0, binding = 1) buffer Velocity {
  75. float velocity[ PARTICLE_NUM * PARTICLE_SIZE ];
  76. } velocity;
  77. layout(set = 0, binding = 2) uniform MouseUniforms {
  78. vec2 pointer;
  79. } mouseUniforms;
  80. void main() {
  81. uint index = gl_GlobalInvocationID.x;
  82. if ( index >= PARTICLE_NUM ) { return; }
  83. vec3 position = vec3(
  84. particle.particle[ index * 3 + 0 ] + velocity.velocity[ index * 3 + 0 ],
  85. particle.particle[ index * 3 + 1 ] + velocity.velocity[ index * 3 + 1 ],
  86. particle.particle[ index * 3 + 2 ] + velocity.velocity[ index * 3 + 2 ]
  87. );
  88. if ( abs( position.x ) >= ROOM_SIZE ) {
  89. velocity.velocity[ index * 3 + 0 ] = - velocity.velocity[ index * 3 + 0 ];
  90. }
  91. if ( abs( position.y ) >= ROOM_SIZE ) {
  92. velocity.velocity[ index * 3 + 1 ] = - velocity.velocity[ index * 3 + 1 ];
  93. }
  94. if ( abs( position.z ) >= ROOM_SIZE ) {
  95. velocity.velocity[ index * 3 + 2 ] = - velocity.velocity[ index * 3 + 2 ];
  96. }
  97. float dx = mouseUniforms.pointer.x - position.x;
  98. float dy = mouseUniforms.pointer.y - position.y;
  99. float distanceFromPointer = sqrt( dx * dx + dy * dy );
  100. if ( distanceFromPointer <= POINTER_SIZE ) {
  101. position.x = 0.0;
  102. position.y = 0.0;
  103. position.z = 0.0;
  104. }
  105. particle.particle[ index * 3 + 0 ] = position.x;
  106. particle.particle[ index * 3 + 1 ] = position.y;
  107. particle.particle[ index * 3 + 2 ] = position.z;
  108. }
  109. `;
  110. computeParams.push( {
  111. num: particleNum,
  112. shader: computeShader,
  113. bindings: computeBindings
  114. } );
  115. // Use a compute shader to animate the point cloud's vertex data.
  116. const pointsGeometry = new THREE.BufferGeometry().setAttribute(
  117. 'position', particleBuffer.attribute
  118. );
  119. const pointsMaterial = new THREE.PointsMaterial();
  120. pointsMaterial.colorNode = new OperatorNode( '+', new PositionNode(), new ColorNode( new THREE.Color( 0x0000FF ) ) );
  121. const mesh = new THREE.Points( pointsGeometry, pointsMaterial );
  122. scene.add( mesh );
  123. renderer = new WebGPURenderer();
  124. renderer.setPixelRatio( window.devicePixelRatio );
  125. renderer.setSize( window.innerWidth, window.innerHeight );
  126. document.body.appendChild( renderer.domElement );
  127. window.addEventListener( 'resize', onWindowResize );
  128. window.addEventListener( 'mousemove', onMouseMove );
  129. return renderer.init();
  130. }
  131. function onWindowResize() {
  132. camera.updateProjectionMatrix();
  133. renderer.setSize( window.innerWidth, window.innerHeight );
  134. }
  135. function onMouseMove( event ) {
  136. const x = event.clientX;
  137. const y = event.clientY;
  138. const width = window.innerWidth;
  139. const height = window.innerHeight;
  140. pointer.set(
  141. ( x / width - 0.5 ) * 2.0,
  142. ( - y / height + 0.5 ) * 2.0
  143. );
  144. }
  145. function animate() {
  146. requestAnimationFrame( animate );
  147. renderer.compute( computeParams );
  148. renderer.render( scene, camera );
  149. }
  150. function error( error ) {
  151. console.error( error );
  152. }
  153. </script>
  154. </body>
  155. </html>