webgpu_compute_birds.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - compute - flocking</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. <style>
  9. body {
  10. background-color: #fff;
  11. color: #444;
  12. }
  13. a {
  14. color:#08f;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">
  20. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - webgpu compute birds<br/>
  21. Move mouse to disturb birds.
  22. </div>
  23. <script type="importmap">
  24. {
  25. "imports": {
  26. "three": "../build/three.webgpu.js",
  27. "three/webgpu": "../build/three.webgpu.js",
  28. "three/tsl": "../build/three.tsl.js",
  29. "three/addons/": "./jsm/",
  30. "stats-gl": "https://cdn.jsdelivr.net/npm/stats-gl@3.6.0/dist/main.js"
  31. }
  32. }
  33. </script>
  34. <script type="module">
  35. import * as THREE from 'three/webgpu';
  36. import { uniform, varying, vec4, add, sub, max, dot, sin, mat3, uint, negate, instancedArray, cameraProjectionMatrix, cameraViewMatrix, positionLocal, modelWorldMatrix, sqrt, property, float, Fn, If, cos, Loop, Continue, normalize, instanceIndex, length, vertexIndex } from 'three/tsl';
  37. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  38. import Stats from 'stats-gl';
  39. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  40. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  41. let container, stats;
  42. let camera, scene, renderer;
  43. let last = performance.now();
  44. let pointer, raycaster;
  45. let computeVelocity, computePosition, effectController;
  46. const BIRDS = 16384;
  47. const SPEED_LIMIT = 9.0;
  48. const BOUNDS = 800, BOUNDS_HALF = BOUNDS / 2;
  49. // Custom Geometry - using 3 triangles each. No normals currently.
  50. class BirdGeometry extends THREE.BufferGeometry {
  51. constructor() {
  52. super();
  53. const points = 3 * 3;
  54. const vertices = new THREE.BufferAttribute( new Float32Array( points * 3 ), 3 );
  55. this.setAttribute( 'position', vertices );
  56. let v = 0;
  57. function verts_push() {
  58. for ( let i = 0; i < arguments.length; i ++ ) {
  59. vertices.array[ v ++ ] = arguments[ i ];
  60. }
  61. }
  62. const wingsSpan = 20;
  63. // Body
  64. verts_push(
  65. 0, 0, - 20,
  66. 0, - 8, 10,
  67. 0, 0, 30
  68. );
  69. // Left Wing
  70. verts_push(
  71. 0, 0, - 15,
  72. - wingsSpan, 0, 5,
  73. 0, 0, 15
  74. );
  75. // Right Wing
  76. verts_push(
  77. 0, 0, 15,
  78. wingsSpan, 0, 5,
  79. 0, 0, - 15
  80. );
  81. this.scale( 0.2, 0.2, 0.2 );
  82. }
  83. }
  84. // TODO: Fix example with WebGL backend
  85. if ( WebGPU.isAvailable() === false ) {
  86. document.body.appendChild( WebGPU.getErrorMessage() );
  87. throw new Error( 'No WebGPU support' );
  88. }
  89. function init() {
  90. container = document.createElement( 'div' );
  91. document.body.appendChild( container );
  92. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 5000 );
  93. camera.position.z = 1000;
  94. scene = new THREE.Scene();
  95. scene.fog = new THREE.Fog( 0xffffff, 700, 3000 );
  96. // Pointer
  97. pointer = new THREE.Vector2();
  98. raycaster = new THREE.Raycaster();
  99. // Sky
  100. const geometry = new THREE.IcosahedronGeometry( 1, 6 );
  101. const material = new THREE.MeshBasicNodeMaterial( {
  102. // Use vertex positions to create atmosphere colors
  103. colorNode: varying(
  104. vec4(
  105. sub( 0.25, positionLocal.y ),
  106. sub( - 0.25, positionLocal.y ),
  107. add( 1.5, positionLocal.y ),
  108. 1.0
  109. )
  110. ),
  111. side: THREE.BackSide
  112. } );
  113. const mesh = new THREE.Mesh( geometry, material );
  114. mesh.rotation.z = 0.75;
  115. mesh.scale.setScalar( 1200 );
  116. scene.add( mesh );
  117. //
  118. renderer = new THREE.WebGPURenderer( { antialias: true, forceWebGL: false } );
  119. renderer.setPixelRatio( window.devicePixelRatio );
  120. renderer.setSize( window.innerWidth, window.innerHeight );
  121. renderer.setAnimationLoop( animate );
  122. renderer.toneMapping = THREE.NeutralToneMapping;
  123. container.appendChild( renderer.domElement );
  124. const controls = new OrbitControls( camera );
  125. controls.connect( renderer.domElement );
  126. // Initialize position, velocity, and phase values
  127. const positionArray = new Float32Array( BIRDS * 3 );
  128. const velocityArray = new Float32Array( BIRDS * 3 );
  129. const phaseArray = new Float32Array( BIRDS );
  130. for ( let i = 0; i < BIRDS; i ++ ) {
  131. const posX = Math.random() * BOUNDS - BOUNDS_HALF;
  132. const posY = Math.random() * BOUNDS - BOUNDS_HALF;
  133. const posZ = Math.random() * BOUNDS - BOUNDS_HALF;
  134. positionArray[ i * 3 + 0 ] = posX;
  135. positionArray[ i * 3 + 1 ] = posY;
  136. positionArray[ i * 3 + 2 ] = posZ;
  137. const velX = Math.random() - 0.5;
  138. const velY = Math.random() - 0.5;
  139. const velZ = Math.random() - 0.5;
  140. velocityArray[ i * 3 + 0 ] = velX * 10;
  141. velocityArray[ i * 3 + 1 ] = velY * 10;
  142. velocityArray[ i * 3 + 2 ] = velZ * 10;
  143. phaseArray[ i ] = 1;
  144. }
  145. // Labels applied to storage nodes and uniform nodes are reflected within the shader output,
  146. // and are useful for debugging purposes.
  147. const positionStorage = instancedArray( positionArray, 'vec3' ).setName( 'positionStorage' );
  148. const velocityStorage = instancedArray( velocityArray, 'vec3' ).setName( 'velocityStorage' );
  149. const phaseStorage = instancedArray( phaseArray, 'float' ).setName( 'phaseStorage' );
  150. // The Pixel Buffer Object (PBO) is required to get the GPU computed data in the WebGL2 fallback.
  151. positionStorage.setPBO( true );
  152. velocityStorage.setPBO( true );
  153. phaseStorage.setPBO( true );
  154. // Define Uniforms. Uniforms only need to be defined once rather than per shader.
  155. effectController = {
  156. separation: uniform( 15.0 ).setName( 'separation' ),
  157. alignment: uniform( 20.0 ).setName( 'alignment' ),
  158. cohesion: uniform( 20.0 ).setName( 'cohesion' ),
  159. freedom: uniform( 0.75 ).setName( 'freedom' ),
  160. now: uniform( 0.0 ),
  161. deltaTime: uniform( 0.0 ).setName( 'deltaTime' ),
  162. rayOrigin: uniform( new THREE.Vector3() ).setName( 'rayOrigin' ),
  163. rayDirection: uniform( new THREE.Vector3() ).setName( 'rayDirection' )
  164. };
  165. // Create geometry
  166. const birdGeometry = new BirdGeometry();
  167. const birdMaterial = new THREE.NodeMaterial();
  168. // Animate bird mesh within vertex shader, then apply position offset to vertices.
  169. const birdVertexTSL = Fn( () => {
  170. const position = positionLocal.toVar();
  171. const newPhase = phaseStorage.element( instanceIndex ).toVar();
  172. const newVelocity = normalize( velocityStorage.element( instanceIndex ) ).toVar();
  173. If( vertexIndex.equal( 4 ).or( vertexIndex.equal( 7 ) ), () => {
  174. // flap wings
  175. position.y = sin( newPhase ).mul( 5.0 );
  176. } );
  177. const newPosition = modelWorldMatrix.mul( position );
  178. newVelocity.z.mulAssign( - 1.0 );
  179. const xz = length( newVelocity.xz );
  180. const xyz = float( 1.0 );
  181. const x = sqrt( ( newVelocity.y.mul( newVelocity.y ) ).oneMinus() );
  182. const cosry = newVelocity.x.div( xz ).toVar();
  183. const sinry = newVelocity.z.div( xz ).toVar();
  184. const cosrz = x.div( xyz );
  185. const sinrz = newVelocity.y.div( xyz ).toVar();
  186. // Nodes must be negated with negate(). Using '-', their values will resolve to NaN.
  187. const maty = mat3(
  188. cosry, 0, negate( sinry ),
  189. 0, 1, 0,
  190. sinry, 0, cosry
  191. );
  192. const matz = mat3(
  193. cosrz, sinrz, 0,
  194. negate( sinrz ), cosrz, 0,
  195. 0, 0, 1
  196. );
  197. const finalVert = maty.mul( matz ).mul( newPosition );
  198. finalVert.addAssign( positionStorage.element( instanceIndex ) );
  199. return cameraProjectionMatrix.mul( cameraViewMatrix ).mul( finalVert );
  200. } );
  201. birdMaterial.vertexNode = birdVertexTSL();
  202. birdMaterial.side = THREE.DoubleSide;
  203. const birdMesh = new THREE.InstancedMesh( birdGeometry, birdMaterial, BIRDS );
  204. birdMesh.rotation.y = Math.PI / 2;
  205. birdMesh.matrixAutoUpdate = false;
  206. birdMesh.frustumCulled = false;
  207. birdMesh.updateMatrix();
  208. // Define GPU Compute shaders.
  209. // Shaders are computationally identical to their GLSL counterparts outside of texture destructuring.
  210. computeVelocity = Fn( () => {
  211. // Define consts
  212. const PI = float( 3.141592653589793 );
  213. const PI_2 = PI.mul( 2.0 );
  214. const limit = property( 'float', 'limit' ).assign( SPEED_LIMIT );
  215. // Destructure uniforms
  216. const { alignment, separation, cohesion, deltaTime, rayOrigin, rayDirection } = effectController;
  217. const zoneRadius = separation.add( alignment ).add( cohesion ).toConst();
  218. const separationThresh = separation.div( zoneRadius ).toConst();
  219. const alignmentThresh = ( separation.add( alignment ) ).div( zoneRadius ).toConst();
  220. const zoneRadiusSq = zoneRadius.mul( zoneRadius ).toConst();
  221. // Cache current bird's position and velocity outside the loop
  222. const birdIndex = instanceIndex.toConst( 'birdIndex' );
  223. const position = positionStorage.element( birdIndex ).toVar();
  224. const velocity = velocityStorage.element( birdIndex ).toVar();
  225. // Add influence of pointer position to velocity using cached position
  226. const directionToRay = rayOrigin.sub( position ).toConst();
  227. const projectionLength = dot( directionToRay, rayDirection ).toConst();
  228. const closestPoint = rayOrigin.sub( rayDirection.mul( projectionLength ) ).toConst();
  229. const directionToClosestPoint = closestPoint.sub( position ).toConst();
  230. const distanceToClosestPoint = length( directionToClosestPoint ).toConst();
  231. const distanceToClosestPointSq = distanceToClosestPoint.mul( distanceToClosestPoint ).toConst();
  232. const rayRadius = float( 150.0 ).toConst();
  233. const rayRadiusSq = rayRadius.mul( rayRadius ).toConst();
  234. If( distanceToClosestPointSq.lessThan( rayRadiusSq ), () => {
  235. const velocityAdjust = ( distanceToClosestPointSq.div( rayRadiusSq ).sub( 1.0 ) ).mul( deltaTime ).mul( 100.0 );
  236. velocity.addAssign( normalize( directionToClosestPoint ).mul( velocityAdjust ) );
  237. limit.addAssign( 5.0 );
  238. } );
  239. // Attract flocks to center
  240. const dirToCenter = position.toVar();
  241. dirToCenter.y.mulAssign( 2.5 );
  242. velocity.subAssign( normalize( dirToCenter ).mul( deltaTime ).mul( 5.0 ) );
  243. Loop( { start: uint( 0 ), end: uint( BIRDS ), type: 'uint', condition: '<' }, ( { i } ) => {
  244. If( i.equal( birdIndex ), () => {
  245. Continue();
  246. } );
  247. // Cache bird's position and velocity
  248. const birdPosition = positionStorage.element( i );
  249. const dirToBird = birdPosition.sub( position );
  250. const distToBird = length( dirToBird );
  251. If( distToBird.lessThan( 0.0001 ), () => {
  252. Continue();
  253. } );
  254. const distToBirdSq = distToBird.mul( distToBird );
  255. // Don't apply any changes to velocity if changes if the bird is outsize the zone's radius.
  256. If( distToBirdSq.greaterThan( zoneRadiusSq ), () => {
  257. Continue();
  258. } );
  259. // Determine which threshold the bird is flying within and adjust its velocity accordingly
  260. const percent = distToBirdSq.div( zoneRadiusSq );
  261. If( percent.lessThan( separationThresh ), () => {
  262. // Separation - Move apart for comfort
  263. const velocityAdjust = ( separationThresh.div( percent ).sub( 1.0 ) ).mul( deltaTime );
  264. velocity.subAssign( normalize( dirToBird ).mul( velocityAdjust ) );
  265. } ).ElseIf( percent.lessThan( alignmentThresh ), () => {
  266. // Alignment - fly the same direction
  267. const threshDelta = alignmentThresh.sub( separationThresh );
  268. const adjustedPercent = ( percent.sub( separationThresh ) ).div( threshDelta );
  269. const birdVelocity = velocityStorage.element( i );
  270. const cosRange = cos( adjustedPercent.mul( PI_2 ) );
  271. const cosRangeAdjust = float( 0.5 ).sub( cosRange.mul( 0.5 ) ).add( 0.5 );
  272. const velocityAdjust = cosRangeAdjust.mul( deltaTime );
  273. velocity.addAssign( normalize( birdVelocity ).mul( velocityAdjust ) );
  274. } ).Else( () => {
  275. // Attraction / Cohesion - move closer
  276. const threshDelta = alignmentThresh.oneMinus();
  277. const adjustedPercent = threshDelta.equal( 0.0 ).select( 1.0, ( percent.sub( alignmentThresh ) ).div( threshDelta ) );
  278. const cosRange = cos( adjustedPercent.mul( PI_2 ) );
  279. const adj1 = cosRange.mul( - 0.5 );
  280. const adj2 = adj1.add( 0.5 );
  281. const adj3 = float( 0.5 ).sub( adj2 );
  282. const velocityAdjust = adj3.mul( deltaTime );
  283. velocity.addAssign( normalize( dirToBird ).mul( velocityAdjust ) );
  284. } );
  285. } );
  286. If( length( velocity ).greaterThan( limit ), () => {
  287. velocity.assign( normalize( velocity ).mul( limit ) );
  288. } );
  289. // Write back the final velocity to storage
  290. velocityStorage.element( birdIndex ).assign( velocity );
  291. } )().compute( BIRDS );
  292. computePosition = Fn( () => {
  293. const { deltaTime } = effectController;
  294. positionStorage.element( instanceIndex ).addAssign( velocityStorage.element( instanceIndex ).mul( deltaTime ).mul( 15.0 ) );
  295. const velocity = velocityStorage.element( instanceIndex );
  296. const phase = phaseStorage.element( instanceIndex );
  297. const modValue = phase.add( deltaTime ).add( length( velocity.xz ).mul( deltaTime ).mul( 3.0 ) ).add( max( velocity.y, 0.0 ).mul( deltaTime ).mul( 6.0 ) );
  298. phaseStorage.element( instanceIndex ).assign( modValue.mod( 62.83 ) );
  299. } )().compute( BIRDS );
  300. scene.add( birdMesh );
  301. stats = new Stats( {
  302. precision: 3,
  303. horizontal: false,
  304. trackGPU: true,
  305. trackCPT: true
  306. } );
  307. stats.init( renderer );
  308. container.appendChild( stats.dom );
  309. container.style.touchAction = 'none';
  310. container.addEventListener( 'pointermove', onPointerMove );
  311. window.addEventListener( 'resize', onWindowResize );
  312. const gui = new GUI();
  313. gui.add( effectController.separation, 'value', 0.0, 100.0, 1.0 ).name( 'Separation' );
  314. gui.add( effectController.alignment, 'value', 0.0, 100, 0.001 ).name( 'Alignment ' );
  315. gui.add( effectController.cohesion, 'value', 0.0, 100, 0.025 ).name( 'Cohesion' );
  316. gui.close();
  317. }
  318. function onWindowResize() {
  319. camera.aspect = window.innerWidth / window.innerHeight;
  320. camera.updateProjectionMatrix();
  321. renderer.setSize( window.innerWidth, window.innerHeight );
  322. }
  323. function onPointerMove( event ) {
  324. if ( event.isPrimary === false ) return;
  325. pointer.x = ( event.clientX / window.innerWidth ) * 2.0 - 1.0;
  326. pointer.y = 1.0 - ( event.clientY / window.innerHeight ) * 2.0;
  327. }
  328. function animate() {
  329. render();
  330. renderer.resolveTimestampsAsync();
  331. stats.update();
  332. }
  333. function render() {
  334. const now = performance.now();
  335. let deltaTime = ( now - last ) / 1000;
  336. if ( deltaTime > 1 ) deltaTime = 1; // safety cap on large deltas
  337. last = now;
  338. raycaster.setFromCamera( pointer, camera );
  339. effectController.now.value = now;
  340. effectController.deltaTime.value = deltaTime;
  341. effectController.rayOrigin.value.copy( raycaster.ray.origin );
  342. effectController.rayDirection.value.copy( raycaster.ray.direction );
  343. renderer.compute( computeVelocity );
  344. renderer.compute( computePosition );
  345. renderer.resolveTimestampsAsync( THREE.TimestampQuery.COMPUTE );
  346. renderer.render( scene, camera );
  347. // Move pointer away so we only affect birds when moving the mouse
  348. pointer.y = 10;
  349. }
  350. init();
  351. </script>
  352. </body>
  353. </html>
粤ICP备19079148号