-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboids.js
366 lines (316 loc) · 10.1 KB
/
boids.js
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
// Size of canvas. These get updated to fill the whole browser.
let width = 150;
let height = 150;
const numBoids = 100;
const visualRange = 75;
let centeringFactor = 0.005; // adjust velocity by this %
let centeringFactorChangeInterval = 100; // Time interval of anti flocking. After this, the boids again centralise at center of mass
const minDistance = 20; // The distance to stay away from other boids
const avoidFactor = 0.05; // Adjust velocity by this %
const minPredDistance = 100; // Minimum distance from predator to respond
const predAvoidFactor = 2; // How quick the boids respond to predator in range
const matchingFactor = 0.05; // Adjust by this % of average velocity
let matchingFactorWind = 0.1; // Adjust to make boids more/less resistive to wind vector
let placeTendFactor = 0.001; // Factor effecting the velocity vector directing towards a particular coordinate
// let placeTendFactorChangeInterval = 10;
const speedLimit = 15;
const wind = {x: randomBetween(-1,1), y: randomBetween(-1,1) }; // Generate constant wind vector
// const wind = {x: 1, y: 0};
let place = {x: 100, y: 100};
const perchTimeRange = {min: 50, max: 100}; // To randomize the perching time of boids
const DRAW_TRAIL = false;
var boids = [];
// Single predator boid
// TODO: Add multiple predators for complex behaviour
var predBoid = {};
function initBoids() {
for (var i = 0; i < numBoids; i += 1) {
boids[boids.length] = {
x: Math.random() * width,
y: Math.random() * height,
dx: Math.random() * 10 - 7,
dy: Math.random() * 10 - 7,
perching: false,
perch_time: randomBetween(perchTimeRange.min, perchTimeRange.max),
history: [],
pred: false,
};
}
// Predator boid init
predBoid = {
x: Math.random() * width,
y: Math.random() * height,
dx: Math.random() * 10 - 7,
dy: Math.random() * 10 - 7,
history: [],
pred: true,
};
}
// Util function to calculate distance between two given boids
function distance(boid1, boid2) {
return Math.sqrt(
(boid1.x - boid2.x) * (boid1.x - boid2.x) +
(boid1.y - boid2.y) * (boid1.y - boid2.y),
);
}
// Util function to generate randon interger between given numbers
function randomBetween(min, max) {
if (min < 0) {
return Math.floor(min + Math.random() * (Math.abs(min)+max));
}else {
return Math.floor(min + Math.random() * max);
}
}
// Change: Used Schwartzian transform.
function nClosestBoids(boid, n) {
// Make a copy
const sorted = boids.map(b => [distance(boid, b), b]);
// Sort the copy by distance from `boid`
sorted.sort((a, b) => a[0] - b[0]);
// Return the `n` closest
return sorted.slice(1, n + 1).map(obj => obj[1]);
}
// Called initially and whenever the window resizes to update the canvas
// size and width/height variables.
function sizeCanvas() {
const canvas = document.getElementById("boids");
width = window.innerWidth;
height = window.innerHeight;
canvas.width = width;
canvas.height = height;
}
// Constrain a boid to within the window. If it gets too close to an edge,
// nudge it back in and reverse its direction.
function keepWithinBounds(boid) {
const marginX = 80;
const marginY = 80;
const turnFactor = 1;
if (boid.x < marginX) {
boid.dx += turnFactor;
}
if (boid.x > width - marginX) {
boid.dx -= turnFactor
}
if (boid.y < marginY) {
boid.dy += turnFactor;
}
if (boid.y > height - marginY) {
boid.dy -= turnFactor;
}
// Preching behaviour: one in every 3 boids when closer to ground perches
if ((boid.y > height) & randomBetween(1,3) == 2) {
boid.y = height - 30;
boid.perching = true;
}
}
// Find the center of mass of the other boids and adjust velocity slightly to
// point towards the center of mass.
function flyTowardsCenter(boid, factor = centeringFactor) {
let centerX = 0;
let centerY = 0;
let numNeighbors = 0;
for (let otherBoid of boids) {
if (distance(boid, otherBoid) < visualRange) {
centerX += otherBoid.x;
centerY += otherBoid.y;
numNeighbors += 1;
}
}
if (numNeighbors) {
centerX = centerX / numNeighbors;
centerY = centerY / numNeighbors;
boid.dx += (centerX - boid.x) * factor;
boid.dy += (centerY - boid.y) * factor;
}
}
// Move away from other boids that are too close to avoid colliding
function avoidOthers(boid) {
let moveX = 0;
let moveY = 0;
for (let otherBoid of boids) {
if (otherBoid !== boid) {
if (distance(boid, otherBoid) < minDistance) {
moveX += boid.x - otherBoid.x;
moveY += boid.y - otherBoid.y;
}
}
}
boid.dx += moveX * avoidFactor;
boid.dy += moveY * avoidFactor;
}
// Move away from pedator that are close (within minPredDistance) to avoid predation
function avoidPredator(boid) {
let moveX = 0;
let moveY = 0;
if (predBoid !== boid) {
if (distance(boid, predBoid) < minPredDistance) {
moveX += boid.x - predBoid.x;
moveY += boid.y - predBoid.y;
}
}
boid.dx += moveX * predAvoidFactor;
boid.dy += moveY * predAvoidFactor;
}
// Find the average velocity (speed and direction) of the other boids and
// adjust velocity slightly to match.
function matchVelocity(boid) {
let avgDX = 0;
let avgDY = 0;
let numNeighbors = 0;
for (let otherBoid of boids) {
if (distance(boid, otherBoid) < visualRange) {
avgDX += otherBoid.dx;
avgDY += otherBoid.dy;
numNeighbors += 1;
}
}
if (numNeighbors) {
avgDX = avgDX / numNeighbors;
avgDY = avgDY / numNeighbors;
boid.dx += (avgDX - boid.dx) * matchingFactor;
boid.dy += (avgDY - boid.dy) * matchingFactor;
}
}
// Action of a strong wind or current
// This function returns the same value independent of the boid being examined;
// hence the entire flock will have the same push due to the wind.
function matchWind(boid){
boid.dx += wind.x * matchingFactorWind;
boid.dy += wind.y * matchingFactorWind;
}
// Add tendency to move towards a particular coordinate: place{x,y}
function tendToPlace(boid) {
boid.dx += (place.x*(width/150) - boid.x) * placeTendFactor;
boid.dy += (place.y*(height/150) - boid.y) * placeTendFactor;
}
// Speed will naturally vary in flocking behavior, but real animals can't go
// arbitrarily fast.
function limitSpeed(boid) {
const speed = Math.sqrt(boid.dx * boid.dx + boid.dy * boid.dy);
if (speed > speedLimit) {
boid.dx = (boid.dx / speed) * speedLimit;
boid.dy = (boid.dy / speed) * speedLimit;
}
}
function drawBoid(ctx, boid) {
let angle = Math.atan2(boid.dy, boid.dx);
let fillStyle = "#558cf4";
let strokeStyle = "#558cf466";
// angle of boid if perching: pointing up. Also predators don't perch
if (boid.perching && boid.pred == false) {
angle = Math.atan2(-1, 0);
}
//Change color of predator boid
if(boid.pred == true){
fillStyle = "#fc3503";
strokeStyle = "#fc350366";
}
ctx.translate(boid.x, boid.y);
ctx.rotate(angle);
ctx.translate(-boid.x, -boid.y);
ctx.fillStyle = fillStyle;
ctx.beginPath();
ctx.moveTo(boid.x, boid.y);
if(boid.pred == false){
ctx.lineTo(boid.x - 15, boid.y + 5);
ctx.lineTo(boid.x - 15, boid.y - 5);
ctx.lineTo(boid.x, boid.y);
}
else {
ctx.lineTo(boid.x - 20, boid.y + 10);
ctx.lineTo(boid.x - 20, boid.y - 10);
ctx.lineTo(boid.x, boid.y);
}
ctx.fill();
ctx.setTransform(1, 0, 0, 1, 0, 0);
if (DRAW_TRAIL) {
ctx.strokeStyle = strokeStyle;
ctx.beginPath();
ctx.moveTo(boid.history[0][0], boid.history[0][1]);
for (const point of boid.history) {
ctx.lineTo(point[0], point[1]);
}
ctx.stroke();
}
}
// Main animation loop
function animationLoop() {
// Update each boid
for (let boid of boids) {
if (boid.perching){
if (boid.perch_time > 0 && distance(boid, predBoid) > visualRange) { // Don't perch if predator is close
boid.perch_time -= 1;
continue;
}
else {
boid.perching = false;
boid.perch_time = randomBetween(perchTimeRange.min, perchTimeRange.max);
}
}
// Update the velocities according to each rule
flyTowardsCenter(boid);
avoidOthers(boid);
avoidPredator(boid);
matchVelocity(boid);
matchWind(boid);
tendToPlace(boid);
limitSpeed(boid);
keepWithinBounds(boid);
// Update the position based on the current velocity
boid.x += boid.dx;
boid.y += boid.dy;
boid.history.push([boid.x, boid.y])
boid.history = boid.history.slice(-50);
}
// Clear the canvas and redraw all the boids in their current positions
const ctx = document.getElementById("boids").getContext("2d");
ctx.clearRect(0, 0, width, height);
for (let boid of boids) {
drawBoid(ctx, boid);
}
// Calculating behaviour of Predator boid (predBoid)
flyTowardsCenter(predBoid,0.02);
matchWind(predBoid);
limitSpeed(predBoid);
keepWithinBounds(predBoid);
predBoid.x += predBoid.dx;
predBoid.y += predBoid.dy;
predBoid.history.push([predBoid.x, predBoid.y])
predBoid.history = predBoid.history.slice(-50);
drawBoid(ctx, predBoid);
// Change conditions dynamically
// Randomly change the centering factor for real life behaviour
let r = randomBetween(1,100);
// console.log(r);
if (r == 1) {
// console.log(r);
centeringFactor *= -1;
if (centeringFactorChangeInterval > 0) centeringFactorChangeInterval -= 1;
else {
centeringFactor *= -1;
centeringFactorChangeInterval = 100;
}
}
// Dynamic place tendency is causing severe divergent behaviour. So Droped
// TODO: Realistically implement dynamic place tendency
// if ( randomBetween(1,1000) == 50) {
// // console.log(r);
// placeTendFactor *= -0.1;
// if (placeTendFactorChangeInterval > 0) placeTendFactorChangeInterval -= 1;
// else {
// placeTendFactor = 0.001;
// placeTendFactorChangeInterval = 10;
// }
// }
// Schedule the next frame
window.requestAnimationFrame(animationLoop);
}
window.onload = () => {
// Make sure the canvas always fills the whole window
window.addEventListener("resize", sizeCanvas, false);
sizeCanvas();
// Randomly distribute the boids to start
initBoids();
// Schedule the main animation loop
window.requestAnimationFrame(animationLoop);
};