webgl_gpgpu_birds.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - gpgpu - 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. <meta property="og:title" content="three.js webgl - gpgpu - flocking">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgl_gpgpu_birds.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgl_gpgpu_birds.jpg">
  11. <link type="text/css" rel="stylesheet" href="main.css">
  12. <style>
  13. body {
  14. background-color: #fff;
  15. color: #444;
  16. }
  17. a {
  18. color:#08f;
  19. }
  20. </style>
  21. </head>
  22. <body>
  23. <div id="info">
  24. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - webgl gpgpu birds<br/>
  25. Move mouse to disturb birds.
  26. </div>
  27. <!--
  28. TODO: If you're reading this, you may wish to improve this example by
  29. - Create a better shading for the birds?
  30. -->
  31. <!-- shader for bird's position -->
  32. <script id="fragmentShaderPosition" type="x-shader/x-fragment">
  33. uniform float time;
  34. uniform float delta;
  35. void main() {
  36. vec2 uv = gl_FragCoord.xy / resolution.xy;
  37. vec4 tmpPos = texture2D( texturePosition, uv );
  38. vec3 position = tmpPos.xyz;
  39. vec3 velocity = texture2D( textureVelocity, uv ).xyz;
  40. float phase = tmpPos.w;
  41. phase = mod( ( phase + delta +
  42. length( velocity.xz ) * delta * 3. +
  43. max( velocity.y, 0.0 ) * delta * 6. ), 62.83 );
  44. gl_FragColor = vec4( position + velocity * delta * 15. , phase );
  45. }
  46. </script>
  47. <!-- shader for bird's velocity -->
  48. <script id="fragmentShaderVelocity" type="x-shader/x-fragment">
  49. uniform float time;
  50. uniform float testing;
  51. uniform float delta; // about 0.016
  52. uniform float separationDistance; // 20
  53. uniform float alignmentDistance; // 40
  54. uniform float cohesionDistance; //
  55. uniform float freedomFactor;
  56. uniform vec3 predator;
  57. const float width = resolution.x;
  58. const float height = resolution.y;
  59. const float PI = 3.141592653589793;
  60. const float PI_2 = PI * 2.0;
  61. // const float VISION = PI * 0.55;
  62. float zoneRadius = 40.0;
  63. float zoneRadiusSquared = 1600.0;
  64. float separationThresh = 0.45;
  65. float alignmentThresh = 0.65;
  66. const float UPPER_BOUNDS = BOUNDS;
  67. const float LOWER_BOUNDS = -UPPER_BOUNDS;
  68. const float SPEED_LIMIT = 9.0;
  69. float rand( vec2 co ){
  70. return fract( sin( dot( co.xy, vec2(12.9898,78.233) ) ) * 43758.5453 );
  71. }
  72. void main() {
  73. zoneRadius = separationDistance + alignmentDistance + cohesionDistance;
  74. separationThresh = separationDistance / zoneRadius;
  75. alignmentThresh = ( separationDistance + alignmentDistance ) / zoneRadius;
  76. zoneRadiusSquared = zoneRadius * zoneRadius;
  77. vec2 uv = gl_FragCoord.xy / resolution.xy;
  78. vec3 birdPosition, birdVelocity;
  79. vec3 selfPosition = texture2D( texturePosition, uv ).xyz;
  80. vec3 selfVelocity = texture2D( textureVelocity, uv ).xyz;
  81. float dist;
  82. vec3 dir; // direction
  83. float distSquared;
  84. float separationSquared = separationDistance * separationDistance;
  85. float cohesionSquared = cohesionDistance * cohesionDistance;
  86. float f;
  87. float percent;
  88. vec3 velocity = selfVelocity;
  89. float limit = SPEED_LIMIT;
  90. dir = predator * UPPER_BOUNDS - selfPosition;
  91. dir.z = 0.;
  92. // dir.z *= 0.6;
  93. dist = length( dir );
  94. distSquared = dist * dist;
  95. float preyRadius = 150.0;
  96. float preyRadiusSq = preyRadius * preyRadius;
  97. // move birds away from predator
  98. if ( dist < preyRadius ) {
  99. f = ( distSquared / preyRadiusSq - 1.0 ) * delta * 100.;
  100. velocity += normalize( dir ) * f;
  101. limit += 5.0;
  102. }
  103. // if (testing == 0.0) {}
  104. // if ( rand( uv + time ) < freedomFactor ) {}
  105. // Attract flocks to the center
  106. vec3 central = vec3( 0., 0., 0. );
  107. dir = selfPosition - central;
  108. dist = length( dir );
  109. dir.y *= 2.5;
  110. velocity -= normalize( dir ) * delta * 5.;
  111. for ( float y = 0.0; y < height; y++ ) {
  112. for ( float x = 0.0; x < width; x++ ) {
  113. vec2 ref = vec2( x + 0.5, y + 0.5 ) / resolution.xy;
  114. birdPosition = texture2D( texturePosition, ref ).xyz;
  115. dir = birdPosition - selfPosition;
  116. dist = length( dir );
  117. if ( dist < 0.0001 ) continue;
  118. distSquared = dist * dist;
  119. if ( distSquared > zoneRadiusSquared ) continue;
  120. percent = distSquared / zoneRadiusSquared;
  121. if ( percent < separationThresh ) { // low
  122. // Separation - Move apart for comfort
  123. f = ( separationThresh / percent - 1.0 ) * delta;
  124. velocity -= normalize( dir ) * f;
  125. } else if ( percent < alignmentThresh ) { // high
  126. // Alignment - fly the same direction
  127. float threshDelta = alignmentThresh - separationThresh;
  128. float adjustedPercent = ( percent - separationThresh ) / threshDelta;
  129. birdVelocity = texture2D( textureVelocity, ref ).xyz;
  130. f = ( 0.5 - cos( adjustedPercent * PI_2 ) * 0.5 + 0.5 ) * delta;
  131. velocity += normalize( birdVelocity ) * f;
  132. } else {
  133. // Attraction / Cohesion - move closer
  134. float threshDelta = 1.0 - alignmentThresh;
  135. float adjustedPercent;
  136. if( threshDelta == 0. ) adjustedPercent = 1.;
  137. else adjustedPercent = ( percent - alignmentThresh ) / threshDelta;
  138. f = ( 0.5 - ( cos( adjustedPercent * PI_2 ) * -0.5 + 0.5 ) ) * delta;
  139. velocity += normalize( dir ) * f;
  140. }
  141. }
  142. }
  143. // this make tends to fly around than down or up
  144. // if (velocity.y > 0.) velocity.y *= (1. - 0.2 * delta);
  145. // Speed Limits
  146. if ( length( velocity ) > limit ) {
  147. velocity = normalize( velocity ) * limit;
  148. }
  149. gl_FragColor = vec4( velocity, 1.0 );
  150. }
  151. </script>
  152. <script type="x-shader/x-vertex" id="birdVS">
  153. attribute vec2 reference;
  154. attribute float birdVertex;
  155. attribute vec3 birdColor;
  156. uniform sampler2D texturePosition;
  157. uniform sampler2D textureVelocity;
  158. varying vec4 vColor;
  159. varying float z;
  160. uniform float time;
  161. void main() {
  162. vec4 tmpPos = texture2D( texturePosition, reference );
  163. vec3 pos = tmpPos.xyz;
  164. vec3 velocity = normalize(texture2D( textureVelocity, reference ).xyz);
  165. vec3 newPosition = position;
  166. if ( birdVertex == 4.0 || birdVertex == 7.0 ) {
  167. // flap wings
  168. newPosition.y = sin( tmpPos.w ) * 5.;
  169. }
  170. newPosition = mat3( modelMatrix ) * newPosition;
  171. velocity.z *= -1.;
  172. float xz = length( velocity.xz );
  173. float xyz = 1.;
  174. float x = sqrt( 1. - velocity.y * velocity.y );
  175. float cosry = velocity.x / xz;
  176. float sinry = velocity.z / xz;
  177. float cosrz = x / xyz;
  178. float sinrz = velocity.y / xyz;
  179. mat3 maty = mat3(
  180. cosry, 0, -sinry,
  181. 0 , 1, 0 ,
  182. sinry, 0, cosry
  183. );
  184. mat3 matz = mat3(
  185. cosrz , sinrz, 0,
  186. -sinrz, cosrz, 0,
  187. 0 , 0 , 1
  188. );
  189. newPosition = maty * matz * newPosition;
  190. newPosition += pos;
  191. z = newPosition.z;
  192. vColor = vec4( birdColor, 1.0 );
  193. gl_Position = projectionMatrix * viewMatrix * vec4( newPosition, 1.0 );
  194. }
  195. </script>
  196. <!-- bird geometry shader -->
  197. <script type="x-shader/x-fragment" id="birdFS">
  198. varying vec4 vColor;
  199. varying float z;
  200. uniform vec3 color;
  201. void main() {
  202. // Fake colors for now
  203. float z2 = 0.2 + ( 1000. - z ) / 1000. * vColor.x;
  204. gl_FragColor = vec4( z2, z2, z2, 1. );
  205. }
  206. </script>
  207. <script type="importmap">
  208. {
  209. "imports": {
  210. "three": "../build/three.module.js",
  211. "three/addons/": "./jsm/"
  212. }
  213. }
  214. </script>
  215. <script type="module">
  216. import * as THREE from 'three';
  217. import Stats from 'three/addons/libs/stats.module.js';
  218. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  219. import { GPUComputationRenderer } from 'three/addons/misc/GPUComputationRenderer.js';
  220. /* TEXTURE WIDTH FOR SIMULATION */
  221. const WIDTH = 32;
  222. const BIRDS = WIDTH * WIDTH;
  223. // Custom Geometry - using 3 triangles each. No UVs, no normals currently.
  224. class BirdGeometry extends THREE.BufferGeometry {
  225. constructor() {
  226. super();
  227. const trianglesPerBird = 3;
  228. const triangles = BIRDS * trianglesPerBird;
  229. const points = triangles * 3;
  230. const vertices = new THREE.BufferAttribute( new Float32Array( points * 3 ), 3 );
  231. const birdColors = new THREE.BufferAttribute( new Float32Array( points * 3 ), 3 );
  232. const references = new THREE.BufferAttribute( new Float32Array( points * 2 ), 2 );
  233. const birdVertex = new THREE.BufferAttribute( new Float32Array( points ), 1 );
  234. this.setAttribute( 'position', vertices );
  235. this.setAttribute( 'birdColor', birdColors );
  236. this.setAttribute( 'reference', references );
  237. this.setAttribute( 'birdVertex', birdVertex );
  238. // this.setAttribute( 'normal', new Float32Array( points * 3 ), 3 );
  239. let v = 0;
  240. function verts_push() {
  241. for ( let i = 0; i < arguments.length; i ++ ) {
  242. vertices.array[ v ++ ] = arguments[ i ];
  243. }
  244. }
  245. const wingsSpan = 20;
  246. for ( let f = 0; f < BIRDS; f ++ ) {
  247. // Body
  248. verts_push(
  249. 0, - 0, - 20,
  250. 0, 4, - 20,
  251. 0, 0, 30
  252. );
  253. // Wings
  254. verts_push(
  255. 0, 0, - 15,
  256. - wingsSpan, 0, 0,
  257. 0, 0, 15
  258. );
  259. verts_push(
  260. 0, 0, 15,
  261. wingsSpan, 0, 0,
  262. 0, 0, - 15
  263. );
  264. }
  265. for ( let v = 0; v < triangles * 3; v ++ ) {
  266. const triangleIndex = ~ ~ ( v / 3 );
  267. const birdIndex = ~ ~ ( triangleIndex / trianglesPerBird );
  268. const x = ( birdIndex % WIDTH ) / WIDTH;
  269. const y = ~ ~ ( birdIndex / WIDTH ) / WIDTH;
  270. const c = new THREE.Color(
  271. 0x666666 +
  272. ~ ~ ( v / 9 ) / BIRDS * 0x666666
  273. );
  274. birdColors.array[ v * 3 + 0 ] = c.r;
  275. birdColors.array[ v * 3 + 1 ] = c.g;
  276. birdColors.array[ v * 3 + 2 ] = c.b;
  277. references.array[ v * 2 ] = x;
  278. references.array[ v * 2 + 1 ] = y;
  279. birdVertex.array[ v ] = v % 9;
  280. }
  281. this.scale( 0.2, 0.2, 0.2 );
  282. }
  283. }
  284. //
  285. let container, stats;
  286. let camera, scene, renderer;
  287. let mouseX = 0, mouseY = 0;
  288. let windowHalfX = window.innerWidth / 2;
  289. let windowHalfY = window.innerHeight / 2;
  290. const BOUNDS = 800, BOUNDS_HALF = BOUNDS / 2;
  291. let last = performance.now();
  292. let gpuCompute;
  293. let velocityVariable;
  294. let positionVariable;
  295. let positionUniforms;
  296. let velocityUniforms;
  297. let birdUniforms;
  298. init();
  299. function init() {
  300. container = document.createElement( 'div' );
  301. document.body.appendChild( container );
  302. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  303. camera.position.z = 350;
  304. scene = new THREE.Scene();
  305. scene.background = new THREE.Color( 0xffffff );
  306. scene.fog = new THREE.Fog( 0xffffff, 100, 1000 );
  307. renderer = new THREE.WebGLRenderer();
  308. renderer.setPixelRatio( window.devicePixelRatio );
  309. renderer.setSize( window.innerWidth, window.innerHeight );
  310. renderer.setAnimationLoop( animate );
  311. container.appendChild( renderer.domElement );
  312. initComputeRenderer();
  313. stats = new Stats();
  314. container.appendChild( stats.dom );
  315. container.style.touchAction = 'none';
  316. container.addEventListener( 'pointermove', onPointerMove );
  317. //
  318. window.addEventListener( 'resize', onWindowResize );
  319. const gui = new GUI();
  320. const effectController = {
  321. separation: 20.0,
  322. alignment: 20.0,
  323. cohesion: 20.0,
  324. freedom: 0.75
  325. };
  326. const valuesChanger = function () {
  327. velocityUniforms[ 'separationDistance' ].value = effectController.separation;
  328. velocityUniforms[ 'alignmentDistance' ].value = effectController.alignment;
  329. velocityUniforms[ 'cohesionDistance' ].value = effectController.cohesion;
  330. velocityUniforms[ 'freedomFactor' ].value = effectController.freedom;
  331. };
  332. valuesChanger();
  333. gui.add( effectController, 'separation', 0.0, 100.0, 1.0 ).onChange( valuesChanger );
  334. gui.add( effectController, 'alignment', 0.0, 100, 0.001 ).onChange( valuesChanger );
  335. gui.add( effectController, 'cohesion', 0.0, 100, 0.025 ).onChange( valuesChanger );
  336. gui.close();
  337. initBirds();
  338. }
  339. function initComputeRenderer() {
  340. gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );
  341. const dtPosition = gpuCompute.createTexture();
  342. const dtVelocity = gpuCompute.createTexture();
  343. fillPositionTexture( dtPosition );
  344. fillVelocityTexture( dtVelocity );
  345. velocityVariable = gpuCompute.addVariable( 'textureVelocity', document.getElementById( 'fragmentShaderVelocity' ).textContent, dtVelocity );
  346. positionVariable = gpuCompute.addVariable( 'texturePosition', document.getElementById( 'fragmentShaderPosition' ).textContent, dtPosition );
  347. gpuCompute.setVariableDependencies( velocityVariable, [ positionVariable, velocityVariable ] );
  348. gpuCompute.setVariableDependencies( positionVariable, [ positionVariable, velocityVariable ] );
  349. positionUniforms = positionVariable.material.uniforms;
  350. velocityUniforms = velocityVariable.material.uniforms;
  351. positionUniforms[ 'time' ] = { value: 0.0 };
  352. positionUniforms[ 'delta' ] = { value: 0.0 };
  353. velocityUniforms[ 'time' ] = { value: 1.0 };
  354. velocityUniforms[ 'delta' ] = { value: 0.0 };
  355. velocityUniforms[ 'testing' ] = { value: 1.0 };
  356. velocityUniforms[ 'separationDistance' ] = { value: 1.0 };
  357. velocityUniforms[ 'alignmentDistance' ] = { value: 1.0 };
  358. velocityUniforms[ 'cohesionDistance' ] = { value: 1.0 };
  359. velocityUniforms[ 'freedomFactor' ] = { value: 1.0 };
  360. velocityUniforms[ 'predator' ] = { value: new THREE.Vector3() };
  361. velocityVariable.material.defines.BOUNDS = BOUNDS.toFixed( 2 );
  362. velocityVariable.wrapS = THREE.RepeatWrapping;
  363. velocityVariable.wrapT = THREE.RepeatWrapping;
  364. positionVariable.wrapS = THREE.RepeatWrapping;
  365. positionVariable.wrapT = THREE.RepeatWrapping;
  366. const error = gpuCompute.init();
  367. if ( error !== null ) {
  368. console.error( error );
  369. }
  370. }
  371. function initBirds() {
  372. const geometry = new BirdGeometry();
  373. // For Vertex and Fragment
  374. birdUniforms = {
  375. 'color': { value: new THREE.Color( 0xff2200 ) },
  376. 'texturePosition': { value: null },
  377. 'textureVelocity': { value: null },
  378. 'time': { value: 1.0 },
  379. 'delta': { value: 0.0 }
  380. };
  381. // THREE.ShaderMaterial
  382. const material = new THREE.ShaderMaterial( {
  383. uniforms: birdUniforms,
  384. vertexShader: document.getElementById( 'birdVS' ).textContent,
  385. fragmentShader: document.getElementById( 'birdFS' ).textContent,
  386. side: THREE.DoubleSide
  387. } );
  388. const birdMesh = new THREE.Mesh( geometry, material );
  389. birdMesh.rotation.y = Math.PI / 2;
  390. birdMesh.matrixAutoUpdate = false;
  391. birdMesh.updateMatrix();
  392. scene.add( birdMesh );
  393. }
  394. function fillPositionTexture( texture ) {
  395. const theArray = texture.image.data;
  396. for ( let k = 0, kl = theArray.length; k < kl; k += 4 ) {
  397. const x = Math.random() * BOUNDS - BOUNDS_HALF;
  398. const y = Math.random() * BOUNDS - BOUNDS_HALF;
  399. const z = Math.random() * BOUNDS - BOUNDS_HALF;
  400. theArray[ k + 0 ] = x;
  401. theArray[ k + 1 ] = y;
  402. theArray[ k + 2 ] = z;
  403. theArray[ k + 3 ] = 1;
  404. }
  405. }
  406. function fillVelocityTexture( texture ) {
  407. const theArray = texture.image.data;
  408. for ( let k = 0, kl = theArray.length; k < kl; k += 4 ) {
  409. const x = Math.random() - 0.5;
  410. const y = Math.random() - 0.5;
  411. const z = Math.random() - 0.5;
  412. theArray[ k + 0 ] = x * 10;
  413. theArray[ k + 1 ] = y * 10;
  414. theArray[ k + 2 ] = z * 10;
  415. theArray[ k + 3 ] = 1;
  416. }
  417. }
  418. function onWindowResize() {
  419. windowHalfX = window.innerWidth / 2;
  420. windowHalfY = window.innerHeight / 2;
  421. camera.aspect = window.innerWidth / window.innerHeight;
  422. camera.updateProjectionMatrix();
  423. renderer.setSize( window.innerWidth, window.innerHeight );
  424. }
  425. function onPointerMove( event ) {
  426. if ( event.isPrimary === false ) return;
  427. mouseX = event.clientX - windowHalfX;
  428. mouseY = event.clientY - windowHalfY;
  429. }
  430. //
  431. function animate() {
  432. render();
  433. stats.update();
  434. }
  435. function render() {
  436. const now = performance.now();
  437. let delta = ( now - last ) / 1000;
  438. if ( delta > 1 ) delta = 1; // safety cap on large deltas
  439. last = now;
  440. positionUniforms[ 'time' ].value = now;
  441. positionUniforms[ 'delta' ].value = delta;
  442. velocityUniforms[ 'time' ].value = now;
  443. velocityUniforms[ 'delta' ].value = delta;
  444. birdUniforms[ 'time' ].value = now;
  445. birdUniforms[ 'delta' ].value = delta;
  446. velocityUniforms[ 'predator' ].value.set( 0.5 * mouseX / windowHalfX, - 0.5 * mouseY / windowHalfY, 0 );
  447. mouseX = 10000;
  448. mouseY = 10000;
  449. gpuCompute.compute();
  450. birdUniforms[ 'texturePosition' ].value = gpuCompute.getCurrentRenderTarget( positionVariable ).texture;
  451. birdUniforms[ 'textureVelocity' ].value = gpuCompute.getCurrentRenderTarget( velocityVariable ).texture;
  452. renderer.render( scene, camera );
  453. }
  454. </script>
  455. </body>
  456. </html>
粤ICP备19079148号