webgpu_compute_birds.html 15 KB

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