-
Notifications
You must be signed in to change notification settings - Fork 0
/
rules.cpp
102 lines (85 loc) · 2.61 KB
/
rules.cpp
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
#include "boid.hpp"
#include <iostream>
// It would have been good to construct a new modDouble variable maybe
double mod(double const& num, double const& modulo)
{
if (!cfg.isTorusSpace()) {
return num;
} else {
if (std::abs(num) > std::abs(std::abs(num) - modulo)) {
if (num >= 0) {
return num - modulo;
} else {
return num + modulo;
}
} else {
return num;
}
}
}
std::pair<double, double> separation(Boid const& current,
std::set<Boid*> const& neighbors)
{
double separationX = 0.0;
double separationY = 0.0;
for (const auto& neighbor : neighbors) {
if (neighbor == ¤t)
continue;
double distanceX = mod(neighbor->get_x() - current.get_x(),
cfg.getXSpace()[1] - cfg.getXSpace()[0]);
double distanceY = mod(neighbor->get_y() - current.get_y(),
cfg.getYSpace()[1] - cfg.getYSpace()[0]);
double distance = current.distance(*neighbor);
if (distance < cfg.getDS()) {
separationX -= cfg.getS() * distanceX;
separationY -= cfg.getS() * distanceY;
}
}
return {separationX, separationY};
}
std::pair<double, double> alignment(Boid const& current,
std::set<Boid*> const& neighbors)
{
double avgVx = 0.0;
double avgVy = 0.0;
int count = 0;
for (const auto& neighbor : neighbors) {
// As for now I update neighbors with lazyUpdateNeighbors it shouldn't
// contain itself in the neighbors but to make sure even for later
if (neighbor == ¤t)
continue;
avgVx += neighbor->get_vx();
avgVy += neighbor->get_vy();
count++;
}
if (count > 0) {
avgVx /= count;
avgVy /= count;
}
double alignmentX = cfg.getA() * (avgVx - current.get_vx());
double alignmentY = cfg.getA() * (avgVy - current.get_vy());
return {alignmentX, alignmentY};
}
std::pair<double, double> cohesion(Boid const& current,
std::set<Boid*> const& neighbors)
{
double centerX = 0.0;
double centerY = 0.0;
int count = 0;
for (const auto& neighbor : neighbors) {
if (neighbor == ¤t)
continue;
centerX += mod(neighbor->get_x() - current.get_x(),
cfg.getXSpace()[1] - cfg.getXSpace()[0]);
centerY += mod(neighbor->get_y() - current.get_y(),
cfg.getYSpace()[1] - cfg.getYSpace()[0]);
count++;
}
if (count > 0) {
centerX /= count;
centerY /= count;
}
double cohesionX = cfg.getC() * centerX;
double cohesionY = cfg.getC() * centerY;
return {cohesionX, cohesionY};
}