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
#![warn(missing_docs)]

//! # tahga::pursuit::boids::boid
//!
//! The boid module implements a single boid in the boids flocking algorithm

use nannou::color::Alpha;
use nannou::prelude::*;

/// A [`Boid`] is a single member of a flock
#[derive(Clone, Debug)]
pub struct Boid {
    /// The unique id for this boid
    id: u32,
    /// The current position
    pub position: Vec2,
    /// The current velocity
    pub velocity: Vec2,
    /// The color of this boid
    pub color: Alpha<Hsl, f32>,
    /// The range at which this boid can see other boids
    pub visual_range: f32,
    /// The max speed of this boid
    pub max_speed: f32,
    /// Not currently used
    pub max_affect: f32,
    /// Not currently used
    pub border: f32,
    /// A record of past positions
    pub path: Vec<Vec2>,
}

impl Boid {
    /// Create a new [`Boid`] instance
    ///
    /// # Arguments
    ///
    /// `id` - A unique id for this [`Boid`]
    ///
    /// `position` - The current position
    ///
    /// `velocity` - The current velocity
    ///
    /// # Examples
    ///
    /// ```
    /// use nannou::prelude::*;
    /// use tahga::pursuit::boids::boid::Boid;
    /// let b = Boid::new(0, vec2(0., 0.), vec2(10., 10.));
    /// assert_eq!(b.visual_range, 75.);
    /// assert_eq!(b.max_speed, 15.);
    /// assert_eq!(b.max_affect, 0.8);
    /// ```
    ///
    pub fn new(id: u32, position: Vec2, velocity: Vec2) -> Self {
        Boid {
            id,
            position,
            velocity,
            color: hsla(0.0, 1., 0.0, 1.0),
            visual_range: 75.,
            max_speed: 15.,
            max_affect: 0.8,
            border: 15.,
            path: Vec::new(),
        }
    }

    /// Set a single color for a [`Boid`] and return a new instance
    ///
    /// This is intended to be chained with new() in a builder pattern
    ///
    /// # Arguments
    ///
    /// `color`: The color to use
    ///
    /// # Examples
    ///
    /// ```
    /// use nannou::prelude::*;
    /// use tahga::pursuit::boids::boid::Boid;
    /// let b = Boid::new(0, vec2(0., 0.), vec2(10., 10.)).color(hsla(0.7,0.5,0.1,0.3));
    ///  let c = b.color.into_components();
    /// assert_eq!(c.1, 0.5);
    /// ```
    ///
    pub fn color(mut self, color: Alpha<Hsl, f32>) -> Self {
        self.color = color;

        self
    }

    /// Set the visual_range for a [`Boid`]
    ///
    /// This is intended to be chained with new() in a builder pattern
    ///
    /// # Arguments
    ///
    /// `visual_range`: the new visual_range
    ///
    /// # Examples
    ///
    /// ```
    /// use nannou::prelude::*;
    /// use tahga::pursuit::boids::boid::Boid;
    /// let b = Boid::new(0, vec2(0., 0.), vec2(10., 10.)).visual_range(10.);
    /// assert_eq!(b.visual_range, 10.);
    /// ```
    ///
    pub fn visual_range(mut self, visual_range: f32) -> Self {
        self.visual_range = visual_range;

        self
    }

    /// Set the max_speed for a [`Boid`]
    ///
    /// This is intended to be chained with new() in a builder pattern
    ///
    /// # Arguments
    ///
    /// `max_speed`: the new max_speed
    ///
    /// # Examples
    ///
    /// ```
    /// use nannou::prelude::*;
    /// use tahga::pursuit::boids::boid::Boid;
    /// let b = Boid::new(0, vec2(0., 0.), vec2(10., 10.)).max_speed(10.);
    /// assert_eq!(b.max_speed, 10.);
    /// ```
    ///
    pub fn max_speed(mut self, max_speed: f32) -> Self {
        self.max_speed = max_speed;

        self
    }

    /// Set the max_affect for a [`Boid`]
    ///
    /// This is intended to be chained with new() in a builder pattern
    ///
    /// # Arguments
    ///
    /// `max_affect`: the new max_affect
    ///
    /// # Examples
    ///
    /// ```
    /// use nannou::prelude::*;
    /// use tahga::pursuit::boids::boid::Boid;
    /// let b = Boid::new(0, vec2(0., 0.), vec2(10., 10.)).max_affect(10.);
    /// assert_eq!(b.max_affect, 10.);
    /// ```
    ///
    pub fn max_affect(mut self, max_affect: f32) -> Self {
        self.max_affect = max_affect;

        self
    }

    /// Set the border for a [`Boid`]
    ///
    /// This is intended to be chained with new() in a builder pattern
    ///
    /// # Arguments
    ///
    /// `border`: the new border
    ///
    /// # Examples
    ///
    /// ```
    /// use nannou::prelude::*;
    /// use tahga::pursuit::boids::boid::Boid;
    /// let b = Boid::new(0, vec2(0., 0.), vec2(10., 10.)).border(10.);
    /// assert_eq!(b.border, 10.);
    /// ```
    ///
    pub fn border(mut self, border: f32) -> Self {
        self.border = border;

        self
    }

    /// Update the position and velocity of a [`Boid`]
    ///
    /// `boids` - A reference to the Vec of all boids
    ///
    /// `rect` - The canvas rectangle
    ///
    pub fn update(&mut self, boids: &Vec<Boid>, rect: &Rect) {
        self.cohere(boids);
        self.align(boids);
        self.separate(boids);
        self.obey_speed_limit();
        self.stay_in_bounds(rect);

        self.path.push(self.position);
        if self.path.len() > 10 {
            self.path.remove(0);
        }
        self.position += self.velocity;
    }

    fn separate(&mut self, boids: &Vec<Boid>) {
        let min_distance = 20.;
        let avoidance_factor = 0.05;
        let mut acc = Vec2::ZERO;

        for other in boids {
            if self.id == other.id { continue; }
            let distance = self.position.distance(other.position);
            if distance > min_distance { continue; }
            acc += self.position - other.position;
        }

        self.velocity += acc * avoidance_factor;
    }

    fn align(&mut self, boids: &Vec<Boid>) {
        let mut avg = Vec2::ZERO;
        let alignment_factor = 0.05;
        let mut neighbors = 0;

        for other in boids {
            if self.id == other.id { continue; }
            if self.position.distance(other.position) > self.visual_range { continue; }
            avg += other.velocity;
            neighbors += 1;
        }
        if neighbors > 0 {
            avg /= neighbors as f32;
            self.velocity += (avg - self.velocity) * alignment_factor;
        }
    }

    fn cohere(&mut self, boids: &Vec<Boid>) {
        let mut center = Vec2::ZERO;
        let centering_factor = 0.005;
        let mut neighbors = 0;

        for other in boids {
            if self.id == other.id { continue; }
            if self.position.distance(other.position) > self.visual_range { continue; }
            center += other.position;
            neighbors += 1;
        }
        if neighbors > 0 {
            center /= neighbors as f32;
            self.velocity += (center - self.position) * centering_factor;
        }
    }

    fn obey_speed_limit(&mut self) {
        let speed = (self.velocity.x * self.velocity.x + self.velocity.y * self.velocity.y).sqrt();
        if speed > self.max_speed {
            self.velocity.x = (self.velocity.x / speed) * self.max_speed;
            self.velocity.y = (self.velocity.y / speed) * self.max_speed;
        }
    }

    fn stay_in_bounds(&mut self, rect: &Rect) {
        let margin = 100.;
        let turn = 1.;

        if self.position.x < rect.left() + margin {
            self.velocity.x += turn;
        }
        if self.position.x > rect.right() - margin {
            self.velocity.x -= turn;
        }
        if self.position.y < rect.bottom() + margin {
            self.velocity.y += turn;
        }
        if self.position.y > rect.top() - margin {
            self.velocity.y -= turn;
        }
    }
}