webgpu_compute_birds.html 16 KB

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