webgl_gpgpu_birds_gltf.html 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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. <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> - webgl gpgpu birds + GLTF mesh<br/>
  21. Flamingo by <a href="https://mirada.com/" target="_blank" rel="noopener">mirada</a> from <a href="http://www.ro.me/" target="_blank" rel="noopener">rome</a><br/>
  22. Move mouse to disturb birds.
  23. </div>
  24. <!-- shader for bird's position -->
  25. <script id="fragmentShaderPosition" type="x-shader/x-fragment">
  26. uniform float time;
  27. uniform float delta;
  28. void main() {
  29. vec2 uv = gl_FragCoord.xy / resolution.xy;
  30. vec4 tmpPos = texture2D( texturePosition, uv );
  31. vec3 position = tmpPos.xyz;
  32. vec3 velocity = texture2D( textureVelocity, uv ).xyz;
  33. float phase = tmpPos.w;
  34. phase = mod( ( phase + delta +
  35. length( velocity.xz ) * delta * 3. +
  36. max( velocity.y, 0.0 ) * delta * 6. ), 62.83 );
  37. gl_FragColor = vec4( position + velocity * delta * 15. , phase );
  38. }
  39. </script>
  40. <!-- shader for bird's velocity -->
  41. <script id="fragmentShaderVelocity" type="x-shader/x-fragment">
  42. uniform float time;
  43. uniform float testing;
  44. uniform float delta; // about 0.016
  45. uniform float separationDistance; // 20
  46. uniform float alignmentDistance; // 40
  47. uniform float cohesionDistance; //
  48. uniform float freedomFactor;
  49. uniform vec3 predator;
  50. const float width = resolution.x;
  51. const float height = resolution.y;
  52. const float PI = 3.141592653589793;
  53. const float PI_2 = PI * 2.0;
  54. // const float VISION = PI * 0.55;
  55. float zoneRadius = 40.0;
  56. float zoneRadiusSquared = 1600.0;
  57. float separationThresh = 0.45;
  58. float alignmentThresh = 0.65;
  59. const float UPPER_BOUNDS = BOUNDS;
  60. const float LOWER_BOUNDS = -UPPER_BOUNDS;
  61. const float SPEED_LIMIT = 9.0;
  62. float rand( vec2 co ){
  63. return fract( sin( dot( co.xy, vec2(12.9898,78.233) ) ) * 43758.5453 );
  64. }
  65. void main() {
  66. zoneRadius = separationDistance + alignmentDistance + cohesionDistance;
  67. separationThresh = separationDistance / zoneRadius;
  68. alignmentThresh = ( separationDistance + alignmentDistance ) / zoneRadius;
  69. zoneRadiusSquared = zoneRadius * zoneRadius;
  70. vec2 uv = gl_FragCoord.xy / resolution.xy;
  71. vec3 birdPosition, birdVelocity;
  72. vec3 selfPosition = texture2D( texturePosition, uv ).xyz;
  73. vec3 selfVelocity = texture2D( textureVelocity, uv ).xyz;
  74. float dist;
  75. vec3 dir; // direction
  76. float distSquared;
  77. float separationSquared = separationDistance * separationDistance;
  78. float cohesionSquared = cohesionDistance * cohesionDistance;
  79. float f;
  80. float percent;
  81. vec3 velocity = selfVelocity;
  82. float limit = SPEED_LIMIT;
  83. dir = predator * UPPER_BOUNDS - selfPosition;
  84. dir.z = 0.;
  85. // dir.z *= 0.6;
  86. dist = length( dir );
  87. distSquared = dist * dist;
  88. float preyRadius = 150.0;
  89. float preyRadiusSq = preyRadius * preyRadius;
  90. // move birds away from predator
  91. if ( dist < preyRadius ) {
  92. f = ( distSquared / preyRadiusSq - 1.0 ) * delta * 100.;
  93. velocity += normalize( dir ) * f;
  94. limit += 5.0;
  95. }
  96. // if (testing == 0.0) {}
  97. // if ( rand( uv + time ) < freedomFactor ) {}
  98. // Attract flocks to the center
  99. vec3 central = vec3( 0., 0., 0. );
  100. dir = selfPosition - central;
  101. dist = length( dir );
  102. dir.y *= 2.5;
  103. velocity -= normalize( dir ) * delta * 5.;
  104. for ( float y = 0.0; y < height; y++ ) {
  105. for ( float x = 0.0; x < width; x++ ) {
  106. vec2 ref = vec2( x + 0.5, y + 0.5 ) / resolution.xy;
  107. birdPosition = texture2D( texturePosition, ref ).xyz;
  108. dir = birdPosition - selfPosition;
  109. dist = length( dir );
  110. if ( dist < 0.0001 ) continue;
  111. distSquared = dist * dist;
  112. if ( distSquared > zoneRadiusSquared ) continue;
  113. percent = distSquared / zoneRadiusSquared;
  114. if ( percent < separationThresh ) { // low
  115. // Separation - Move apart for comfort
  116. f = ( separationThresh / percent - 1.0 ) * delta;
  117. velocity -= normalize( dir ) * f;
  118. } else if ( percent < alignmentThresh ) { // high
  119. // Alignment - fly the same direction
  120. float threshDelta = alignmentThresh - separationThresh;
  121. float adjustedPercent = ( percent - separationThresh ) / threshDelta;
  122. birdVelocity = texture2D( textureVelocity, ref ).xyz;
  123. f = ( 0.5 - cos( adjustedPercent * PI_2 ) * 0.5 + 0.5 ) * delta;
  124. velocity += normalize( birdVelocity ) * f;
  125. } else {
  126. // Attraction / Cohesion - move closer
  127. float threshDelta = 1.0 - alignmentThresh;
  128. float adjustedPercent;
  129. if( threshDelta == 0. ) adjustedPercent = 1.;
  130. else adjustedPercent = ( percent - alignmentThresh ) / threshDelta;
  131. f = ( 0.5 - ( cos( adjustedPercent * PI_2 ) * -0.5 + 0.5 ) ) * delta;
  132. velocity += normalize( dir ) * f;
  133. }
  134. }
  135. }
  136. // this make tends to fly around than down or up
  137. // if (velocity.y > 0.) velocity.y *= (1. - 0.2 * delta);
  138. // Speed Limits
  139. if ( length( velocity ) > limit ) {
  140. velocity = normalize( velocity ) * limit;
  141. }
  142. gl_FragColor = vec4( velocity, 1.0 );
  143. }
  144. </script>
  145. <script type="importmap">
  146. {
  147. "imports": {
  148. "three": "../build/three.module.js",
  149. "three/addons/": "./jsm/"
  150. }
  151. }
  152. </script>
  153. <script type="module">
  154. import * as THREE from 'three';
  155. import Stats from 'three/addons/libs/stats.module.js';
  156. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  157. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  158. import { GPUComputationRenderer } from 'three/addons/misc/GPUComputationRenderer.js';
  159. /* TEXTURE WIDTH FOR SIMULATION */
  160. const WIDTH = 64;
  161. const BIRDS = WIDTH * WIDTH;
  162. /* BAKE ANIMATION INTO TEXTURE and CREATE GEOMETRY FROM BASE MODEL */
  163. const BirdGeometry = new THREE.BufferGeometry();
  164. let textureAnimation, durationAnimation, birdMesh, materialShader, indicesPerBird;
  165. function nextPowerOf2( n ) {
  166. return Math.pow( 2, Math.ceil( Math.log( n ) / Math.log( 2 ) ) );
  167. }
  168. const gltfs = [ 'models/gltf/Parrot.glb', 'models/gltf/Flamingo.glb' ];
  169. const colors = [ 0xccFFFF, 0xffdeff ];
  170. const sizes = [ 0.2, 0.1 ];
  171. const selectModel = Math.floor( Math.random() * gltfs.length );
  172. new GLTFLoader().load( gltfs[ selectModel ], function ( gltf ) {
  173. const animations = gltf.animations;
  174. durationAnimation = Math.round( animations[ 0 ].duration * 60 );
  175. const birdGeo = gltf.scene.children[ 0 ].geometry;
  176. const morphAttributes = birdGeo.morphAttributes.position;
  177. const tHeight = nextPowerOf2( durationAnimation );
  178. const tWidth = nextPowerOf2( birdGeo.getAttribute( 'position' ).count );
  179. indicesPerBird = birdGeo.index.count;
  180. const tData = new Float32Array( 4 * tWidth * tHeight );
  181. for ( let i = 0; i < tWidth; i ++ ) {
  182. for ( let j = 0; j < tHeight; j ++ ) {
  183. const offset = j * tWidth * 4;
  184. const curMorph = Math.floor( j / durationAnimation * morphAttributes.length );
  185. const nextMorph = ( Math.floor( j / durationAnimation * morphAttributes.length ) + 1 ) % morphAttributes.length;
  186. const lerpAmount = j / durationAnimation * morphAttributes.length % 1;
  187. if ( j < durationAnimation ) {
  188. let d0, d1;
  189. d0 = morphAttributes[ curMorph ].array[ i * 3 ];
  190. d1 = morphAttributes[ nextMorph ].array[ i * 3 ];
  191. if ( d0 !== undefined && d1 !== undefined ) tData[ offset + i * 4 ] = THREE.MathUtils.lerp( d0, d1, lerpAmount );
  192. d0 = morphAttributes[ curMorph ].array[ i * 3 + 1 ];
  193. d1 = morphAttributes[ nextMorph ].array[ i * 3 + 1 ];
  194. if ( d0 !== undefined && d1 !== undefined ) tData[ offset + i * 4 + 1 ] = THREE.MathUtils.lerp( d0, d1, lerpAmount );
  195. d0 = morphAttributes[ curMorph ].array[ i * 3 + 2 ];
  196. d1 = morphAttributes[ nextMorph ].array[ i * 3 + 2 ];
  197. if ( d0 !== undefined && d1 !== undefined ) tData[ offset + i * 4 + 2 ] = THREE.MathUtils.lerp( d0, d1, lerpAmount );
  198. tData[ offset + i * 4 + 3 ] = 1;
  199. }
  200. }
  201. }
  202. textureAnimation = new THREE.DataTexture( tData, tWidth, tHeight, THREE.RGBAFormat, THREE.FloatType );
  203. textureAnimation.needsUpdate = true;
  204. const vertices = [], color = [], reference = [], seeds = [], indices = [];
  205. const totalVertices = birdGeo.getAttribute( 'position' ).count * 3 * BIRDS;
  206. for ( let i = 0; i < totalVertices; i ++ ) {
  207. const bIndex = i % ( birdGeo.getAttribute( 'position' ).count * 3 );
  208. vertices.push( birdGeo.getAttribute( 'position' ).array[ bIndex ] );
  209. color.push( birdGeo.getAttribute( 'color' ).array[ bIndex ] );
  210. }
  211. let r = Math.random();
  212. for ( let i = 0; i < birdGeo.getAttribute( 'position' ).count * BIRDS; i ++ ) {
  213. const bIndex = i % ( birdGeo.getAttribute( 'position' ).count );
  214. const bird = Math.floor( i / birdGeo.getAttribute( 'position' ).count );
  215. if ( bIndex == 0 ) r = Math.random();
  216. const j = ~ ~ bird;
  217. const x = ( j % WIDTH ) / WIDTH;
  218. const y = ~ ~ ( j / WIDTH ) / WIDTH;
  219. reference.push( x, y, bIndex / tWidth, durationAnimation / tHeight );
  220. seeds.push( bird, r, Math.random(), Math.random() );
  221. }
  222. for ( let i = 0; i < birdGeo.index.array.length * BIRDS; i ++ ) {
  223. const offset = Math.floor( i / birdGeo.index.array.length ) * ( birdGeo.getAttribute( 'position' ).count );
  224. indices.push( birdGeo.index.array[ i % birdGeo.index.array.length ] + offset );
  225. }
  226. BirdGeometry.setAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
  227. BirdGeometry.setAttribute( 'birdColor', new THREE.BufferAttribute( new Float32Array( color ), 3 ) );
  228. BirdGeometry.setAttribute( 'color', new THREE.BufferAttribute( new Float32Array( color ), 3 ) );
  229. BirdGeometry.setAttribute( 'reference', new THREE.BufferAttribute( new Float32Array( reference ), 4 ) );
  230. BirdGeometry.setAttribute( 'seeds', new THREE.BufferAttribute( new Float32Array( seeds ), 4 ) );
  231. BirdGeometry.setIndex( indices );
  232. init();
  233. } );
  234. let container, stats;
  235. let camera, scene, renderer;
  236. let mouseX = 0, mouseY = 0;
  237. let windowHalfX = window.innerWidth / 2;
  238. let windowHalfY = window.innerHeight / 2;
  239. const BOUNDS = 800, BOUNDS_HALF = BOUNDS / 2;
  240. let last = performance.now();
  241. let gpuCompute;
  242. let velocityVariable;
  243. let positionVariable;
  244. let positionUniforms;
  245. let velocityUniforms;
  246. function init() {
  247. container = document.createElement( 'div' );
  248. document.body.appendChild( container );
  249. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  250. camera.position.z = 350;
  251. scene = new THREE.Scene();
  252. scene.background = new THREE.Color( colors[ selectModel ] );
  253. scene.fog = new THREE.Fog( colors[ selectModel ], 100, 1000 );
  254. // LIGHTS
  255. const hemiLight = new THREE.HemisphereLight( colors[ selectModel ], 0xffffff, 4.5 );
  256. hemiLight.color.setHSL( 0.6, 1, 0.6, THREE.SRGBColorSpace );
  257. hemiLight.groundColor.setHSL( 0.095, 1, 0.75, THREE.SRGBColorSpace );
  258. hemiLight.position.set( 0, 50, 0 );
  259. scene.add( hemiLight );
  260. const dirLight = new THREE.DirectionalLight( 0x00CED1, 2.0 );
  261. dirLight.color.setHSL( 0.1, 1, 0.95, THREE.SRGBColorSpace );
  262. dirLight.position.set( - 1, 1.75, 1 );
  263. dirLight.position.multiplyScalar( 30 );
  264. scene.add( dirLight );
  265. renderer = new THREE.WebGLRenderer( { antialias: true } );
  266. renderer.setPixelRatio( window.devicePixelRatio );
  267. renderer.setSize( window.innerWidth, window.innerHeight );
  268. renderer.setAnimationLoop( animate );
  269. container.appendChild( renderer.domElement );
  270. initComputeRenderer();
  271. stats = new Stats();
  272. container.appendChild( stats.dom );
  273. container.style.touchAction = 'none';
  274. container.addEventListener( 'pointermove', onPointerMove );
  275. window.addEventListener( 'resize', onWindowResize );
  276. const gui = new GUI();
  277. const effectController = {
  278. separation: 20.0,
  279. alignment: 20.0,
  280. cohesion: 20.0,
  281. freedom: 0.75,
  282. size: sizes[ selectModel ],
  283. count: Math.floor( BIRDS / 4 )
  284. };
  285. const valuesChanger = function () {
  286. velocityUniforms[ 'separationDistance' ].value = effectController.separation;
  287. velocityUniforms[ 'alignmentDistance' ].value = effectController.alignment;
  288. velocityUniforms[ 'cohesionDistance' ].value = effectController.cohesion;
  289. velocityUniforms[ 'freedomFactor' ].value = effectController.freedom;
  290. if ( materialShader ) materialShader.uniforms[ 'size' ].value = effectController.size;
  291. BirdGeometry.setDrawRange( 0, indicesPerBird * effectController.count );
  292. };
  293. valuesChanger();
  294. gui.add( effectController, 'separation', 0.0, 100.0, 1.0 ).onChange( valuesChanger );
  295. gui.add( effectController, 'alignment', 0.0, 100, 0.001 ).onChange( valuesChanger );
  296. gui.add( effectController, 'cohesion', 0.0, 100, 0.025 ).onChange( valuesChanger );
  297. gui.add( effectController, 'size', 0, 1, 0.01 ).onChange( valuesChanger );
  298. gui.add( effectController, 'count', 0, BIRDS, 1 ).onChange( valuesChanger );
  299. gui.close();
  300. initBirds( effectController );
  301. }
  302. function initComputeRenderer() {
  303. gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );
  304. const dtPosition = gpuCompute.createTexture();
  305. const dtVelocity = gpuCompute.createTexture();
  306. fillPositionTexture( dtPosition );
  307. fillVelocityTexture( dtVelocity );
  308. velocityVariable = gpuCompute.addVariable( 'textureVelocity', document.getElementById( 'fragmentShaderVelocity' ).textContent, dtVelocity );
  309. positionVariable = gpuCompute.addVariable( 'texturePosition', document.getElementById( 'fragmentShaderPosition' ).textContent, dtPosition );
  310. gpuCompute.setVariableDependencies( velocityVariable, [ positionVariable, velocityVariable ] );
  311. gpuCompute.setVariableDependencies( positionVariable, [ positionVariable, velocityVariable ] );
  312. positionUniforms = positionVariable.material.uniforms;
  313. velocityUniforms = velocityVariable.material.uniforms;
  314. positionUniforms[ 'time' ] = { value: 0.0 };
  315. positionUniforms[ 'delta' ] = { value: 0.0 };
  316. velocityUniforms[ 'time' ] = { value: 1.0 };
  317. velocityUniforms[ 'delta' ] = { value: 0.0 };
  318. velocityUniforms[ 'testing' ] = { value: 1.0 };
  319. velocityUniforms[ 'separationDistance' ] = { value: 1.0 };
  320. velocityUniforms[ 'alignmentDistance' ] = { value: 1.0 };
  321. velocityUniforms[ 'cohesionDistance' ] = { value: 1.0 };
  322. velocityUniforms[ 'freedomFactor' ] = { value: 1.0 };
  323. velocityUniforms[ 'predator' ] = { value: new THREE.Vector3() };
  324. velocityVariable.material.defines.BOUNDS = BOUNDS.toFixed( 2 );
  325. velocityVariable.wrapS = THREE.RepeatWrapping;
  326. velocityVariable.wrapT = THREE.RepeatWrapping;
  327. positionVariable.wrapS = THREE.RepeatWrapping;
  328. positionVariable.wrapT = THREE.RepeatWrapping;
  329. const error = gpuCompute.init();
  330. if ( error !== null ) {
  331. console.error( error );
  332. }
  333. }
  334. function initBirds( effectController ) {
  335. const geometry = BirdGeometry;
  336. const m = new THREE.MeshStandardMaterial( {
  337. vertexColors: true,
  338. flatShading: true,
  339. roughness: 1,
  340. metalness: 0
  341. } );
  342. m.onBeforeCompile = ( shader ) => {
  343. shader.uniforms.texturePosition = { value: null };
  344. shader.uniforms.textureVelocity = { value: null };
  345. shader.uniforms.textureAnimation = { value: textureAnimation };
  346. shader.uniforms.time = { value: 1.0 };
  347. shader.uniforms.size = { value: effectController.size };
  348. shader.uniforms.delta = { value: 0.0 };
  349. let token = '#define STANDARD';
  350. let insert = /* glsl */`
  351. attribute vec4 reference;
  352. attribute vec4 seeds;
  353. attribute vec3 birdColor;
  354. uniform sampler2D texturePosition;
  355. uniform sampler2D textureVelocity;
  356. uniform sampler2D textureAnimation;
  357. uniform float size;
  358. uniform float time;
  359. `;
  360. shader.vertexShader = shader.vertexShader.replace( token, token + insert );
  361. token = '#include <begin_vertex>';
  362. insert = /* glsl */`
  363. vec4 tmpPos = texture2D( texturePosition, reference.xy );
  364. vec3 pos = tmpPos.xyz;
  365. vec3 velocity = normalize(texture2D( textureVelocity, reference.xy ).xyz);
  366. vec3 aniPos = texture2D( textureAnimation, vec2( reference.z, mod( time + ( seeds.x ) * ( ( 0.0004 + seeds.y / 10000.0) + normalize( velocity ) / 20000.0 ), reference.w ) ) ).xyz;
  367. vec3 newPosition = position;
  368. newPosition = mat3( modelMatrix ) * ( newPosition + aniPos );
  369. newPosition *= size + seeds.y * size * 0.2;
  370. velocity.z *= -1.;
  371. float xz = length( velocity.xz );
  372. float xyz = 1.;
  373. float x = sqrt( 1. - velocity.y * velocity.y );
  374. float cosry = velocity.x / xz;
  375. float sinry = velocity.z / xz;
  376. float cosrz = x / xyz;
  377. float sinrz = velocity.y / xyz;
  378. mat3 maty = mat3( cosry, 0, -sinry, 0 , 1, 0 , sinry, 0, cosry );
  379. mat3 matz = mat3( cosrz , sinrz, 0, -sinrz, cosrz, 0, 0 , 0 , 1 );
  380. newPosition = maty * matz * newPosition;
  381. newPosition += pos;
  382. vec3 transformed = vec3( newPosition );
  383. `;
  384. shader.vertexShader = shader.vertexShader.replace( token, insert );
  385. materialShader = shader;
  386. };
  387. birdMesh = new THREE.Mesh( geometry, m );
  388. birdMesh.rotation.y = Math.PI / 2;
  389. birdMesh.castShadow = true;
  390. birdMesh.receiveShadow = true;
  391. scene.add( birdMesh );
  392. }
  393. function fillPositionTexture( texture ) {
  394. const theArray = texture.image.data;
  395. for ( let k = 0, kl = theArray.length; k < kl; k += 4 ) {
  396. const x = Math.random() * BOUNDS - BOUNDS_HALF;
  397. const y = Math.random() * BOUNDS - BOUNDS_HALF;
  398. const z = Math.random() * BOUNDS - BOUNDS_HALF;
  399. theArray[ k + 0 ] = x;
  400. theArray[ k + 1 ] = y;
  401. theArray[ k + 2 ] = z;
  402. theArray[ k + 3 ] = 1;
  403. }
  404. }
  405. function fillVelocityTexture( texture ) {
  406. const theArray = texture.image.data;
  407. for ( let k = 0, kl = theArray.length; k < kl; k += 4 ) {
  408. const x = Math.random() - 0.5;
  409. const y = Math.random() - 0.5;
  410. const z = Math.random() - 0.5;
  411. theArray[ k + 0 ] = x * 10;
  412. theArray[ k + 1 ] = y * 10;
  413. theArray[ k + 2 ] = z * 10;
  414. theArray[ k + 3 ] = 1;
  415. }
  416. }
  417. function onWindowResize() {
  418. windowHalfX = window.innerWidth / 2;
  419. windowHalfY = window.innerHeight / 2;
  420. camera.aspect = window.innerWidth / window.innerHeight;
  421. camera.updateProjectionMatrix();
  422. renderer.setSize( window.innerWidth, window.innerHeight );
  423. }
  424. function onPointerMove( event ) {
  425. if ( event.isPrimary === false ) return;
  426. mouseX = event.clientX - windowHalfX;
  427. mouseY = event.clientY - windowHalfY;
  428. }
  429. //
  430. function animate() {
  431. render();
  432. stats.update();
  433. }
  434. function render() {
  435. const now = performance.now();
  436. let delta = ( now - last ) / 1000;
  437. if ( delta > 1 ) delta = 1; // safety cap on large deltas
  438. last = now;
  439. positionUniforms[ 'time' ].value = now;
  440. positionUniforms[ 'delta' ].value = delta;
  441. velocityUniforms[ 'time' ].value = now;
  442. velocityUniforms[ 'delta' ].value = delta;
  443. if ( materialShader ) materialShader.uniforms[ 'time' ].value = now / 1000;
  444. if ( materialShader ) materialShader.uniforms[ 'delta' ].value = delta;
  445. velocityUniforms[ 'predator' ].value.set( 0.5 * mouseX / windowHalfX, - 0.5 * mouseY / windowHalfY, 0 );
  446. mouseX = 10000;
  447. mouseY = 10000;
  448. gpuCompute.compute();
  449. if ( materialShader ) materialShader.uniforms[ 'texturePosition' ].value = gpuCompute.getCurrentRenderTarget( positionVariable ).texture;
  450. if ( materialShader ) materialShader.uniforms[ 'textureVelocity' ].value = gpuCompute.getCurrentRenderTarget( velocityVariable ).texture;
  451. renderer.render( scene, camera );
  452. }
  453. </script>
  454. </body>
  455. </html>
粤ICP备19079148号