webgpu_compute_birds.html 16 KB

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