webgl_gpgpu_birds.html 18 KB

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