webgpu_compute_birds.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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/tsl": "../build/three.webgpu.js",
  28. "three/addons/": "./jsm/"
  29. }
  30. }
  31. </script>
  32. <script type="module">
  33. import * as THREE from 'three';
  34. import { uniform, varyingProperty, vec4, max, sin, mat3, uint, negate, cameraProjectionMatrix, cameraViewMatrix, positionLocal, modelWorldMatrix, sqrt, attribute, property, float, storage, storageObject, Fn, If, cos, Loop, Continue, normalize, instanceIndex, length } from 'three/tsl';
  35. import Stats from 'three/addons/libs/stats.module.js';
  36. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  37. let container, stats;
  38. let camera, scene, renderer;
  39. let mouseX = 0, mouseY = 0;
  40. let windowHalfX = window.innerWidth / 2, windowHalfY = window.innerHeight / 2;
  41. let last = performance.now();
  42. let computeVelocity, computePosition, effectController;
  43. const BIRDS = 16384;
  44. const SPEED_LIMIT = 9.0;
  45. const BOUNDS = 800, BOUNDS_HALF = BOUNDS / 2;
  46. const UPPER_BOUNDS = BOUNDS;
  47. // Custom Geometry - using 3 triangles each. No normals currently.
  48. class BirdGeometry extends THREE.BufferGeometry {
  49. constructor() {
  50. super();
  51. const trianglesPerBird = 3;
  52. const triangles = BIRDS * trianglesPerBird;
  53. const points = triangles * 3;
  54. const vertices = new THREE.BufferAttribute( new Float32Array( points * 3 ), 3 );
  55. const references = new THREE.BufferAttribute( new Uint32Array( points ), 1 );
  56. const birdVertex = new THREE.BufferAttribute( new Uint32Array( points ), 1 );
  57. this.setAttribute( 'position', vertices );
  58. this.setAttribute( 'reference', references );
  59. this.setAttribute( 'birdVertex', birdVertex );
  60. let v = 0;
  61. function verts_push() {
  62. for ( let i = 0; i < arguments.length; i ++ ) {
  63. vertices.array[ v ++ ] = arguments[ i ];
  64. }
  65. }
  66. const wingsSpan = 20;
  67. for ( let f = 0; f < BIRDS; f ++ ) {
  68. // Body
  69. verts_push(
  70. 0, - 0, - 20,
  71. 0, 4, - 20,
  72. 0, 0, 30
  73. );
  74. // Wings
  75. verts_push(
  76. 0, 0, - 15,
  77. - wingsSpan, 0, 0,
  78. 0, 0, 15
  79. );
  80. verts_push(
  81. 0, 0, 15,
  82. wingsSpan, 0, 0,
  83. 0, 0, - 15
  84. );
  85. }
  86. for ( let v = 0; v < triangles * 3; v ++ ) {
  87. const triangleIndex = ~ ~ ( v / 3 );
  88. const birdIndex = ~ ~ ( triangleIndex / trianglesPerBird );
  89. references.array[ v ] = birdIndex;
  90. birdVertex.array[ v ] = v % 9;
  91. }
  92. this.scale( 0.2, 0.2, 0.2 );
  93. }
  94. }
  95. function init() {
  96. container = document.createElement( 'div' );
  97. document.body.appendChild( container );
  98. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 3000 );
  99. camera.position.z = 1000;
  100. scene = new THREE.Scene();
  101. scene.fog = new THREE.Fog( 0xffffff, 500, 3000 );
  102. // Sky
  103. const light = new THREE.HemisphereLight( 0x0000ff, 0xffbb00, 3 );
  104. light.position.x = - 1;
  105. light.position.z = - 1;
  106. scene.add( light );
  107. const geometry = new THREE.IcosahedronGeometry( 1000, 6 );
  108. const material = new THREE.MeshStandardMaterial( { side: THREE.BackSide } );
  109. scene.add( new THREE.Mesh( geometry, material ) );
  110. renderer = new THREE.WebGPURenderer( { antialiasing: true } );
  111. renderer.setPixelRatio( window.devicePixelRatio );
  112. renderer.setSize( window.innerWidth, window.innerHeight );
  113. renderer.setAnimationLoop( animate );
  114. renderer.toneMapping = THREE.NeutralToneMapping;
  115. container.appendChild( renderer.domElement );
  116. // Initialize position, velocity, and phase values
  117. const positionArray = new Float32Array( BIRDS * 3 );
  118. const velocityArray = new Float32Array( BIRDS * 3 );
  119. const phaseArray = new Float32Array( BIRDS );
  120. for ( let i = 0; i < BIRDS; i ++ ) {
  121. const posX = Math.random() * BOUNDS - BOUNDS_HALF;
  122. const posY = Math.random() * BOUNDS - BOUNDS_HALF;
  123. const posZ = Math.random() * BOUNDS - BOUNDS_HALF;
  124. positionArray[ i * 3 + 0 ] = posX;
  125. positionArray[ i * 3 + 1 ] = posY;
  126. positionArray[ i * 3 + 2 ] = posZ;
  127. const velX = Math.random() - 0.5;
  128. const velY = Math.random() - 0.5;
  129. const velZ = Math.random() - 0.5;
  130. velocityArray[ i * 3 + 0 ] = velX * 10;
  131. velocityArray[ i * 3 + 1 ] = velY * 10;
  132. velocityArray[ i * 3 + 2 ] = velZ * 10;
  133. phaseArray[ i ] = 1;
  134. }
  135. // Create storage buffer attributes.
  136. const positionBufferAttribute = new THREE.StorageBufferAttribute( positionArray, 3 );
  137. const velocityBufferAttribute = new THREE.StorageBufferAttribute( velocityArray, 3 );
  138. const phaseBufferAttribute = new THREE.StorageBufferAttribute( phaseArray, 1 );
  139. // Labels applied to storage nodes and uniform nodes are reflected within the shader output,
  140. // and are useful for debugging purposes.
  141. // Access storage buffer attribute data from within shaders with a StorageNode.
  142. const positionStorage = storage( positionBufferAttribute, 'vec3', positionBufferAttribute.count ).label( 'positionStorage' );
  143. const velocityStorage = storage( velocityBufferAttribute, 'vec3', velocityBufferAttribute.count ).label( 'velocityStorage' );
  144. const phaseStorage = storage( phaseBufferAttribute, 'float', phaseBufferAttribute.count ).label( 'phaseStorage' );
  145. // Create read-only storage nodes. Storage nodes can only be accessed outside of compute shaders in a read-only state.
  146. const positionRead = storageObject( positionBufferAttribute, 'vec3', positionBufferAttribute.count ).toReadOnly();
  147. const velocityRead = storageObject( velocityBufferAttribute, 'vec3', velocityBufferAttribute.count ).toReadOnly();
  148. const phaseRead = storageObject( phaseBufferAttribute, 'float', phaseBufferAttribute.count ).toReadOnly();
  149. // Define Uniforms. Uniforms only need to be defined once rather than per shader.
  150. effectController = {
  151. separation: uniform( 15.0 ).label( 'separation' ),
  152. alignment: uniform( 20.0 ).label( 'alignment' ),
  153. cohesion: uniform( 20.0 ).label( 'cohesion' ),
  154. freedom: uniform( 0.75 ).label( 'freedom' ),
  155. now: uniform( 0.0 ),
  156. deltaTime: uniform( 0.0 ).label( 'deltaTime' ),
  157. predator: uniform( new THREE.Vector3() ).label( 'predator' ),
  158. };
  159. // Create geometry
  160. const birdGeometry = new BirdGeometry();
  161. const birdMaterial = new THREE.NodeMaterial();
  162. // Animate bird mesh within vertex shader, then apply position offset to vertices.
  163. const birdVertexTSL = Fn( () => {
  164. const reference = attribute( 'reference' );
  165. const birdVertex = attribute( 'birdVertex' );
  166. const position = positionLocal.toVar();
  167. const newPhase = phaseRead.element( reference ).toVar();
  168. const newVelocity = normalize( velocityRead.element( reference ) ).toVar();
  169. If( birdVertex.equal( 4 ).or( birdVertex.equal( 7 ) ), () => {
  170. // flap wings
  171. position.y = sin( newPhase ).mul( 5.0 );
  172. } );
  173. const newPosition = modelWorldMatrix.mul( position );
  174. newVelocity.z.mulAssign( - 1.0 );
  175. const xz = length( newVelocity.xz );
  176. const xyz = float( 1.0 );
  177. const x = sqrt( ( newVelocity.y.mul( newVelocity.y ) ).oneMinus() );
  178. const cosry = newVelocity.x.div( xz ).toVar();
  179. const sinry = newVelocity.z.div( xz ).toVar();
  180. const cosrz = x.div( xyz );
  181. const sinrz = newVelocity.y.div( xyz ).toVar();
  182. // Nodes must be negated with negate(). Using '-', their values will resolve to NaN.
  183. const maty = mat3(
  184. cosry, 0, negate( sinry ),
  185. 0, 1, 0,
  186. sinry, 0, cosry
  187. );
  188. const matz = mat3(
  189. cosrz, sinrz, 0,
  190. negate( sinrz ), cosrz, 0,
  191. 0, 0, 1
  192. );
  193. const finalVert = maty.mul( matz ).mul( newPosition );
  194. finalVert.addAssign( positionRead.element( reference ) );
  195. return cameraProjectionMatrix.mul( cameraViewMatrix ).mul( finalVert );
  196. } );
  197. birdMaterial.vertexNode = birdVertexTSL();
  198. birdMaterial.side = THREE.DoubleSide;
  199. const birdMesh = new THREE.Mesh( birdGeometry, birdMaterial );
  200. birdMesh.rotation.y = Math.PI / 2;
  201. birdMesh.matrixAutoUpdate = false;
  202. birdMesh.updateMatrix();
  203. // Define GPU Compute shaders.
  204. // Shaders are computationally identical to their GLSL counterparts outside of texture destructuring.
  205. computeVelocity = Fn( () => {
  206. // Define consts
  207. const PI = float( 3.141592653589793 );
  208. const PI_2 = PI.mul( 2.0 );
  209. const limit = property( 'float', 'limit' ).assign( SPEED_LIMIT );
  210. // Destructure uniforms
  211. const { alignment, separation, cohesion, predator, deltaTime } = effectController;
  212. const zoneRadius = separation.add( alignment ).add( cohesion );
  213. const separationThresh = separation.div( zoneRadius );
  214. const alignmentThresh = ( separation.add( alignment ) ).div( zoneRadius );
  215. const zoneRadiusSq = zoneRadius.mul( zoneRadius );
  216. const position = positionStorage.element( instanceIndex );
  217. const velocity = velocityStorage.element( instanceIndex );
  218. // Add influence of mouse position to velocity.
  219. const dirToPredator = predator.mul( UPPER_BOUNDS ).sub( position );
  220. dirToPredator.z.assign( 0.0 );
  221. const distToPredator = length( dirToPredator );
  222. const distToPreadatorSq = distToPredator.mul( distToPredator );
  223. const preyRadius = float( 150.0 );
  224. const preyRadiusSq = preyRadius.mul( preyRadius );
  225. // Move birds away from predator if they are within the predator's area.
  226. If( distToPredator.lessThan( preyRadius ), () => {
  227. // Scale bird velocity inversely with distance from prey radius center.
  228. const velocityAdjust = ( distToPreadatorSq.div( preyRadiusSq ).sub( 1.0 ) ).mul( deltaTime ).mul( 100.0 );
  229. velocity.addAssign( normalize( dirToPredator ).mul( velocityAdjust ) );
  230. limit.addAssign( 5.0 );
  231. } );
  232. // Attract flocks to center
  233. const dirToCenter = position.toVar();
  234. dirToCenter.y.mulAssign( 2.5 );
  235. velocity.subAssign( normalize( dirToCenter ).mul( deltaTime ).mul( 5.0 ) );
  236. Loop( { start: uint( 0 ), end: uint( BIRDS ), type: 'uint', condition: '<' }, ( { i } ) => {
  237. const birdPosition = positionStorage.element( i );
  238. const dirToBird = birdPosition.sub( position );
  239. const distToBird = length( dirToBird );
  240. // Don't apply any changes to velocity if the distance to this bird is negligable.
  241. If( distToBird.lessThan( 0.0001 ), () => {
  242. Continue();
  243. } );
  244. const distToBirdSq = distToBird.mul( distToBird );
  245. // Don't apply any changes to velocity if changes if the bird is outsize the zone's radius.
  246. If( distToBirdSq.greaterThan( zoneRadiusSq ), () => {
  247. Continue();
  248. } );
  249. // Determine which threshold the bird is flying within and adjust its velocity accordingly
  250. const percent = distToBirdSq.div( zoneRadiusSq );
  251. If( percent.lessThan( separationThresh ), () => {
  252. // Separation - Move apart for comfort
  253. const velocityAdjust = ( separationThresh.div( percent ).sub( 1.0 ) ).mul( deltaTime );
  254. velocity.subAssign( normalize( dirToBird ).mul( velocityAdjust ) );
  255. } ).ElseIf( percent.lessThan( alignmentThresh ), () => {
  256. // Alignment - fly the same direction
  257. const threshDelta = alignmentThresh.sub( separationThresh );
  258. const adjustedPercent = ( percent.sub( separationThresh ) ).div( threshDelta );
  259. const birdVelocity = velocityStorage.element( i );
  260. const cosRange = cos( adjustedPercent.mul( PI_2 ) );
  261. const cosRangeAdjust = float( 0.5 ).sub( cosRange.mul( 0.5 ) ).add( 0.5 );
  262. const velocityAdjust = cosRangeAdjust.mul( deltaTime );
  263. velocity.addAssign( normalize( birdVelocity ).mul( velocityAdjust ) );
  264. } ).Else( () => {
  265. // Attraction / Cohesion - move closer
  266. const threshDelta = alignmentThresh.oneMinus();
  267. const adjustedPercent = threshDelta.equal( 0.0 ).select( 1.0, ( percent.sub( alignmentThresh ) ).div( threshDelta ) );
  268. const cosRange = cos( adjustedPercent.mul( PI_2 ) );
  269. const adj1 = cosRange.mul( - 0.5 );
  270. const adj2 = adj1.add( 0.5 );
  271. const adj3 = float( 0.5 ).sub( adj2 );
  272. const velocityAdjust = adj3.mul( deltaTime );
  273. velocity.addAssign( normalize( dirToBird ).mul( velocityAdjust ) );
  274. } );
  275. } );
  276. If( length( velocity ).greaterThan( limit ), () => {
  277. velocity.assign( normalize( velocity ).mul( limit ) );
  278. } );
  279. } )().compute( BIRDS );
  280. computePosition = Fn( () => {
  281. const { deltaTime } = effectController;
  282. positionStorage.element( instanceIndex ).addAssign( velocityStorage.element( instanceIndex ).mul( deltaTime ).mul( 15.0 ) );
  283. const velocity = velocityStorage.element( instanceIndex );
  284. const phase = phaseStorage.element( instanceIndex );
  285. 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 ) );
  286. phaseStorage.element( instanceIndex ).assign( modValue.mod( 62.83 ) );
  287. } )().compute( BIRDS );
  288. scene.add( birdMesh );
  289. stats = new Stats();
  290. container.appendChild( stats.dom );
  291. container.style.touchAction = 'none';
  292. container.addEventListener( 'pointermove', onPointerMove );
  293. window.addEventListener( 'resize', onWindowResize );
  294. const gui = new GUI();
  295. gui.add( effectController.separation, 'value', 0.0, 100.0, 1.0 ).name( 'Separation' );
  296. gui.add( effectController.alignment, 'value', 0.0, 100, 0.001 ).name( 'Alignment ' );
  297. gui.add( effectController.cohesion, 'value', 0.0, 100, 0.025 ).name( 'Cohesion' );
  298. gui.close();
  299. }
  300. function onWindowResize() {
  301. windowHalfX = window.innerWidth / 2;
  302. windowHalfY = window.innerHeight / 2;
  303. camera.aspect = window.innerWidth / window.innerHeight;
  304. camera.updateProjectionMatrix();
  305. renderer.setSize( window.innerWidth, window.innerHeight );
  306. }
  307. function onPointerMove( event ) {
  308. if ( event.isPrimary === false ) return;
  309. mouseX = event.clientX - windowHalfX;
  310. mouseY = event.clientY - windowHalfY;
  311. }
  312. function animate() {
  313. render();
  314. stats.update();
  315. }
  316. function render() {
  317. const now = performance.now();
  318. let deltaTime = ( now - last ) / 1000;
  319. if ( deltaTime > 1 ) deltaTime = 1; // safety cap on large deltas
  320. last = now;
  321. effectController.now.value = now;
  322. effectController.deltaTime.value = deltaTime;
  323. effectController.predator.value.set( 0.5 * mouseX / windowHalfX, - 0.5 * mouseY / windowHalfY, 0 );
  324. mouseX = 10000;
  325. mouseY = 10000;
  326. renderer.compute( computeVelocity );
  327. renderer.compute( computePosition );
  328. renderer.render( scene, camera );
  329. }
  330. init();
  331. </script>
  332. </body>
  333. </html>
粤ICP备19079148号