-
Notifications
You must be signed in to change notification settings - Fork 34
/
index.html
580 lines (457 loc) · 18.6 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
<!DOCTYPE html>
<html lang="en">
<head>
<title>Flocking Simulation</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<!-- Place this tag in your head or just before your close body tag. -->
<script async defer src="https://buttons.github.io/buttons.js"></script>
<style>
body {
margin: 0px;
overflow: hidden;
cursor: pointer;
}
</style>
</head>
<body>
<div style="position: relative;"><center><b>Use Scroll to Zoom In/Out | Click+drag to move in 3D</b></center></div>
<div style="position: relative;"><center>
<a class="github-button" href="https://github.com/techcentaur/Starling-Simulation" data-icon="octicon-star" aria-label="Star techcentaur/Starling-Simulation on GitHub">Star</a>
<a class="github-button" href="https://github.com/techcentaur/Starling-Simulation/fork" data-icon="octicon-repo-forked" aria-label="Fork techcentaur/Starling-Simulation on GitHub">Fork</a>
<a class="github-button" href="https://github.com/techcentaur" aria-label="Follow @techcentaur on GitHub">Follow @techcentaur</a>
</center></div>
<div style="position: relative;">
<center><a href="https://github.com/techcentaur/Starling-Simulation">View on GitHub</a></center>
</div>
<div id="info" style="margin-top: -6%;">
<span id="birds"></span>
</div>
<script src="js-libs/three.js"></script>
<script src="js-libs/Detector.js"></script>
<script src="js-libs/stats.min.js"></script>
<script src="js-libs/dat.gui.min.js"></script>
<script src="js-libs/GPUComputationRenderer.js"></script>
<script src="js-libs/FirstPersonControls.js"></script>
<script src="js-libs/OrbitControls.js"></script>
<script src="js-libs/KeyboardState.js"></script>
<!-- fragment shader for bird's position -->
<script id="BoidPositionFragmentShader" >
uniform float clock;
uniform float del_change;
void main() {
vec2 textcoordi = gl_FragCoord.xy / resolution.xy;
vec4 temp_position = texture2D( PositionTexture, textcoordi );
vec3 position = temp_position.xyz;
vec3 velocity = texture2D( VeloctiyTexture, textcoordi ).xyz;
float wcoordinate = temp_position.w;
wcoordinate = mod( ( wcoordinate + del_change*2.0 +
length(velocity.xz) * del_change * 3. +
max(velocity.y, 0.0) * del_change * 6. ), 50.0 );
gl_FragColor = vec4( position + velocity * del_change * 15. , wcoordinate );}
</script>
<!-- fragment shader for bird's velocity -->
<script id="BoidVelocityFragmentShader">
uniform float clock;
uniform float testing;
uniform float del_change;
uniform float seperation_distance;
uniform float alignment_distance;
uniform float cohesion_distance;
uniform float freedom_distance;
uniform vec3 predator;
const float width = resolution.x;
const float height = resolution.y;
const float PI = 3.14159;
const float PI_2 = PI * 2.0;
float zoneRadius = 35.0;
float zoneRadiusSquared = zoneRadius*zoneRadius;
float separationThresh = 0.5;
float alignmentThresh = 1.0;
const float UPPER_bounds = bounds;
const float LOWER_bounds = -UPPER_bounds;
const float SPEED_LIMIT = 10.0;
void main() {
zoneRadius = seperation_distance + alignment_distance + cohesion_distance;
separationThresh = seperation_distance / zoneRadius;
alignmentThresh = ( seperation_distance + alignment_distance ) / zoneRadius;
zoneRadiusSquared = zoneRadius * zoneRadius;
vec2 textcoordi = gl_FragCoord.xy / resolution.xy;
vec3 birdPosition, birdVelocity;
vec3 selfPosition = texture2D( PositionTexture, textcoordi ).xyz;
vec3 selfVelocity = texture2D( VeloctiyTexture, textcoordi ).xyz;
float dist;
vec3 dir;
float distSquared;
float seperationSquared = seperation_distance * seperation_distance;
float cohesionSquared = cohesion_distance * cohesion_distance;
float f;
float percent;
vec3 velocity = selfVelocity;
float limit = SPEED_LIMIT;
dir = predator * UPPER_bounds - selfPosition;
dir.z = 0.;
dist = length( dir );
distSquared = dist * dist;
float preyRadius = 50.0;
float preyRadiusSq = preyRadius * preyRadius;
if (dist < preyRadius) {
f = ( distSquared / preyRadiusSq ) * del_change * 160.;
velocity += normalize(dir) * f;
limit += 5.0;}
vec3 central = vec3( 0., 0., 0. );
dir = selfPosition - central;
dist = length( dir );
dir.y *= 2.5;
velocity -= normalize( dir ) * del_change * 6.;
for (float y=0.0;y<height;y++) {
for (float x=0.0;x<width;x++) {
vec2 ref = vec2( x + 0.6, y + 0.6 ) / resolution.xy;
birdPosition = texture2D( PositionTexture, ref ).xyz;
dir = birdPosition - selfPosition;
dist = length(dir);
if (dist < 0.0001) continue;
distSquared = dist * dist;
if (distSquared > zoneRadiusSquared ) continue;
percent = distSquared / zoneRadiusSquared;
if ( percent < separationThresh ) {
// Separation
f = (separationThresh / percent - 1.0) * del_change;
velocity -= normalize(dir) * f;
} else if ( percent < alignmentThresh ) {
// Alignment
float threshold = alignmentThresh - separationThresh;
float adjustedPercent = ( percent - separationThresh ) / threshold;
birdVelocity = texture2D( VeloctiyTexture, ref ).xyz;
f = ( 0.5 - cos( adjustedPercent * PI_2 ) * 0.5 + 0.5 ) * del_change;
velocity += normalize(birdVelocity) * f;
} else {
// Attraction
float threshold = 1.0 - alignmentThresh;
float adjustedPercent = ( percent - alignmentThresh ) / threshold;
f = ( 0.5 - ( cos( adjustedPercent * PI_2 ) * -0.5 + 0.5 ) ) * del_change;
velocity += normalize(dir) * f;
}
}
}
if ( length( velocity ) > limit ) {
velocity = normalize( velocity ) * limit;
}
gl_FragColor = vec4( velocity, 1.0 );
}
</script>
<!-- fragment shader for bird's geometry-->
<script id="BoidGeometryFragmentShader">
varying vec4 vertex_color;
varying float zcoordi;
void main() {
float z = 0.2 + ( 1000. - zcoordi ) / 1000. * vertex_color.x;
gl_FragColor = vec4( z, z, z, 1. );}
</script>
<!-- vertex shader for bird's vertex -->
<script id="BoidVertexShader">
uniform float clock;
attribute vec2 reference;
attribute float birdVertex;
attribute vec3 birdColor;
uniform sampler2D PositionTexture;
uniform sampler2D VeloctiyTexture;
varying vec4 vertex_color;
varying float zcoordi;
void main() {
vec4 temp_position = texture2D( PositionTexture, reference );
vec3 pos = temp_position.xyz;
vec3 velocity = normalize(texture2D( VeloctiyTexture, reference ).xyz);
vec3 newPosition = position;
if ( birdVertex == 4.0 || birdVertex == 7.0 ){ newPosition.y = sin( temp_position.w ) * 5.;}
newPosition = mat3( modelMatrix ) * newPosition;
velocity.z *= -1.;
float xz = length( velocity.xz );
float xyz = 1.;
float x = sqrt( 1. - velocity.y * velocity.y );
float cosry = velocity.x / xz;
float sinry = velocity.z / xz;
float cosrz = x / xyz;
float sinrz = velocity.y / xyz;
mat3 maty = mat3( cosry, 0, -sinry, 0 , 1, 0 ,sinry, 0, cosry);
mat3 matz = mat3( cosrz , sinrz, 0, -sinrz, cosrz, 0, 0, 0, 1);
newPosition = maty * matz * newPosition;
newPosition += pos;
zcoordi = newPosition.z;
vertex_color = vec4( birdColor, 1.0 );
gl_Position = projectionMatrix * viewMatrix * vec4( newPosition, 1.0 );
}
</script>
<!-- Main script -->
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var hash = document.location.hash.substr( 1 );
if (hash) hash = parseInt(hash, 0);
var argumentHash = hash || 32;
var birds = argumentHash * argumentHash;
THREE.BirdGeometry = function () {
var triangles = birds * 3;
var points = triangles * 3;
THREE.BufferGeometry.call( this );
var vertices = new THREE.BufferAttribute( new Float32Array( points * 3 ), 3 );
var birdColors = new THREE.BufferAttribute( new Float32Array( points * 3 ), 3 );
var references = new THREE.BufferAttribute( new Float32Array( points * 2 ), 2 );
var birdVertex = new THREE.BufferAttribute( new Float32Array( points ), 1 );
this.addAttribute( 'position', vertices );
this.addAttribute( 'birdColor', birdColors );
this.addAttribute( 'reference', references );
this.addAttribute( 'birdVertex', birdVertex );
var v = 0;
function vertex_append() {
for (var i=0; i < arguments.length; i++) {
vertices.array[v++] = arguments[i];
}
}
for (var f = 0; f<birds; f++ ) {
vertex_append(
0, -0, -6,
0, 1, -15,
0, 0, 8);
vertex_append(
0, 0, -4,
-6, 0, 0,
0, 0, 4);
vertex_append(
0, 0, 4,
6, 0, 0,
0, 0, -4);
}
for( var v = 0; v < triangles * 3; v++ ) {
var i = ~~(v / 3);
var x = (i % argumentHash) / argumentHash;
var y = ~~(i / argumentHash) / argumentHash;
var c = new THREE.Color(0x000000);
birdColors.array[v*3+0] = c.r;
birdColors.array[v*3+1] = c.g;
birdColors.array[v*3+2] = c.b;
references.array[v*2] = x;
references.array[v*2+1] = y;
birdVertex.array[v] = v % 9;
}
this.scale( 0.35, 0.35, 0.35 );
};
THREE.BirdGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
var half_resolution_windowX = window.innerWidth / 2;
var half_resolution_windowY = window.innerHeight / 2;
var bounds = 500, bounds_HALF = bounds / 2;
document.getElementById('birds').innerText = birds;
function change(n) {
location.hash = n;
location.reload();
return false;
}
var last = performance.now();
var gpu_allocation;
var velocity_variable;
var position_variable;
var uniform_position;
var uniform_velocity;
var uniform_bird;
var container, stats;
var camera, scene, renderer, geometry, i, h, color;
var mouseX = 0, mouseY = 0;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x87ceeb);
scene.fog = new THREE.Fog( 0x87ceeb, 100, 1000 );
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setClearColor(0x66C2FF);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMapEnabled= true;
renderer.shadowMapSoft = true;
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.addEventListener( 'change', render );
camera.position.x = 600;
camera.position.y = 600;
camera.position.z = 600;
camera.lookAt(scene.position);
guiControls = new function(){
this.rotationX = 0.0;
this.rotationY = 0.0;
this.rotationZ = 0.0;
this.lightX = 19;
this.lightY = 47;
this.lightZ = 19;
this.intensity = 2.5;
this.distance = 373;
this.angle = 1.6;
this.exponent = 38;
this.shadowCameraNear = 34;
this.shadowCameraFar = 2635;
this.shadowCameraFov = 68;
this.shadowCameraVisible=false;
this.shadowMapWidth=512;
this.shadowMapHeight=512;
this.shadowBias=0.00;
this.shadowDarkness=0.11;
}
spotLight = new THREE.SpotLight(0xffffff);
spotLight.castShadow = true;
spotLight.position.set (20, 35, 40);
spotLight.intensity = guiControls.intensity;
spotLight.distance = guiControls.distance;
spotLight.angle = guiControls.angle;
spotLight.exponent = guiControls.exponent;
spotLight.shadowCameraNear = guiControls.shadowCameraNear;
spotLight.shadowCameraFar = guiControls.shadowCameraFar;
spotLight.shadowCameraFov = guiControls.shadowCameraFov;
spotLight.shadowCameraVisible = guiControls.shadowCameraVisible;
spotLight.shadowBias = guiControls.shadowBias;
spotLight.shadowDarkness = guiControls.shadowDarkness;
scene.add(spotLight);
container.appendChild( renderer.domElement );
initComputeRenderer();
stats = new Stats();
container.appendChild( stats.dom );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
document.addEventListener( 'touchstart', onDocumentTouchStart, false );
document.addEventListener( 'touchmove', onDocumentTouchMove, false );
// var gui = new dat.GUI();
var controller_variables = { seperation: 20.0, alignment: 30.0, cohesion: 20.0, freedom: 0.3 };
var new_values_update = function() {
uniform_velocity.seperation_distance.value = controller_variables.seperation;
uniform_velocity.alignment_distance.value = controller_variables.alignment;
uniform_velocity.cohesion_distance.value = controller_variables.cohesion;
uniform_velocity.freedom_distance.value = controller_variables.freedom;
};
new_values_update();
// gui.add( controller_variables, "seperation", 0.0, 100.0, 1.0 ).onChange( new_values_update );
// gui.add( controller_variables, "alignment", 0.0, 100, 0.001 ).onChange( new_values_update );
// gui.add( controller_variables, "cohesion", 0.0, 100, 0.025 ).onChange( new_values_update );
// gui.close();
initBirds();
}
function initComputeRenderer() {
gpu_allocation = new GPUComputationRenderer( argumentHash, argumentHash, renderer );
var dtPosition = gpu_allocation.createTexture();
var dtVelocity = gpu_allocation.createTexture();
fillPositionTexture( dtPosition );
fillVelocityTexture( dtVelocity );
velocity_variable = gpu_allocation.addVariable( "VeloctiyTexture", document.getElementById( 'BoidVelocityFragmentShader' ).textContent, dtVelocity );
position_variable = gpu_allocation.addVariable( "PositionTexture", document.getElementById( 'BoidPositionFragmentShader' ).textContent, dtPosition );
gpu_allocation.setVariableDependencies( velocity_variable, [ position_variable, velocity_variable ] );
gpu_allocation.setVariableDependencies( position_variable, [ position_variable, velocity_variable ] );
uniform_position = position_variable.material.uniforms;
uniform_velocity = velocity_variable.material.uniforms;
uniform_position.clock = { value: 0.0 };
uniform_position.del_change = { value: 0.0 };
uniform_velocity.clock = { value: 1.0 };
uniform_velocity.del_change = { value: 0.0 };
uniform_velocity.testing = { value: 1.0 };
uniform_velocity.seperation_distance = { value: 1.0 };
uniform_velocity.alignment_distance = { value: 1.0 };
uniform_velocity.cohesion_distance = { value: 1.0 };
uniform_velocity.freedom_distance = { value: 1.0 };
uniform_velocity.predator = { value: new THREE.Vector3() };
velocity_variable.material.defines.bounds = bounds.toFixed( 2 );
velocity_variable.wrapS = THREE.RepeatWrapping;
velocity_variable.wrapT = THREE.RepeatWrapping;
position_variable.wrapS = THREE.RepeatWrapping;
position_variable.wrapT = THREE.RepeatWrapping;
var error = gpu_allocation.init();
if ( error !== null ) {
console.error( error );
}
}
function initBirds() {
var geometry = new THREE.BirdGeometry();
// For Vertex and Fragment
uniform_bird = {
color: { value: new THREE.Color( 0xff2200 ) },
PositionTexture: { value: null },
VeloctiyTexture: { value: null },
clock: { value: 1.0 },
del_change: { value: 0.0 }
};
// ShaderMaterial
var material = new THREE.ShaderMaterial( {
uniforms: uniform_bird,
vertexShader: document.getElementById( 'BoidVertexShader' ).textContent,
fragmentShader: document.getElementById( 'BoidGeometryFragmentShader' ).textContent,
side: THREE.DoubleSide
});
var birdMesh = new THREE.Mesh( geometry, material );
birdMesh.rotation.y = Math.PI / 2;
birdMesh.matrixAutoUpdate = false;
birdMesh.updateMatrix();
scene.add(birdMesh);
}
function fillPositionTexture( texture ) {
var theArray = texture.image.data;
for ( var k = 0, kl = theArray.length; k < kl; k += 4 ) {
var x = Math.random() * 100 ;
var y = Math.random() * 100;
var z = Math.random() * 100;
theArray[ k + 0 ] = x;
theArray[ k + 1 ] = y;
theArray[ k + 2 ] = z;
theArray[ k + 3 ] = 1;
}
}
function fillVelocityTexture( texture ) {
var theArray = texture.image.data;
for ( var k = 0, kl = theArray.length; k < kl; k += 4 ) {
var x = Math.random() - 0.5;
var y = Math.random() - 0.5;
var z = Math.random() - 0.5;
theArray[ k + 0 ] = x * 10;
theArray[ k + 1 ] = y * 10;
theArray[ k + 2 ] = z * 10;
theArray[ k + 3 ] = 1;
}
}
function onDocumentMouseMove( event ) {
mouseX = event.clientX - half_resolution_windowX;
mouseY = event.clientY - half_resolution_windowY;
}
function onDocumentTouchStart( event ) {
if ( event.touches.length === 1 ) {
event.preventDefault();
mouseX = event.touches[ 0 ].pageX - half_resolution_windowX;
mouseY = event.touches[ 0 ].pageY - half_resolution_windowY;
}
}
function onDocumentTouchMove( event ) {
if ( event.touches.length === 1 ) {
event.preventDefault();
mouseX = event.touches[ 0 ].pageX - half_resolution_windowX;
mouseY = event.touches[ 0 ].pageY - half_resolution_windowY;
}
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
var now = performance.now();
var del_change = (now - last) / 1000;
if (del_change > 1) del_change = 1; // safety cap on large del_changes
last = now;
uniform_position.clock.value = now;
uniform_position.del_change.value = del_change;
uniform_velocity.clock.value = now;
uniform_velocity.del_change.value = del_change;
uniform_bird.clock.value = now;
uniform_bird.del_change.value = del_change;
uniform_velocity.predator.value.set( 0.5 * mouseX / half_resolution_windowX, - 0.5 * mouseY / half_resolution_windowY, 0 );
mouseX = 10000;
mouseY = 10000;
gpu_allocation.compute();
uniform_bird.PositionTexture.value = gpu_allocation.getCurrentRenderTarget( position_variable ).texture;
uniform_bird.VeloctiyTexture.value = gpu_allocation.getCurrentRenderTarget( velocity_variable ).texture;
renderer.render( scene, camera );
}
</script>
</body>
</html>