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
use std::hash::Hash;
/// Reflects the index in the input list of particles.
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct ParticleIndex(usize);
impl From<ParticleIndex> for usize {
fn from(index: ParticleIndex) -> Self {
index.0
}
}
impl From<usize> for ParticleIndex {
fn from(index: usize) -> Self {
Self(index)
}
}
#[derive(Clone, Debug)]
pub struct Particle {
pub x: f64,
pub y: f64,
pub vx: f64,
pub vy: f64,
pub index: ParticleIndex,
// The following fields signal that a node is fixed in a certain direction.
// TODO(grtlr): Move this to a separate `Vec` in the simulation to improve the memory layout.
pub fx: Option<f64>,
pub fy: Option<f64>,
}
impl Particle {
pub fn new(index: impl Into<ParticleIndex>, x: f64, y: f64) -> Self {
Self {
x,
y,
vx: 0.0,
vy: 0.0,
fx: None,
fy: None,
index: index.into(),
}
}
pub fn with_fixed_x(mut self) -> Self {
self.fx = Some(self.x);
self
}
pub fn with_fixed_y(mut self) -> Self {
self.fx = Some(self.x);
self
}
/// Applies the velocity to the vectors, while respecting fixed positions.
pub(crate) fn apply_velocities(&mut self, velocity_decay: f64) {
if let Some(fx) = self.fx {
self.x = fx;
self.vx = 0.0;
} else {
// TODO: This is a somewhat hacky way to prevent particles from
// moving too far and therefore overflowing the quadtree.
self.x += self.vx.clamp(i32::MIN as f64, i32::MAX as f64);
self.vx *= velocity_decay;
}
if let Some(fy) = self.fy {
self.y = fy;
self.vy = 0.0;
} else {
// TODO: This is a somewhat hacky way to prevent particles from
// moving too far and therefore overflowing the quadtree.
self.y += self.vy.clamp(i32::MIN as f64, i32::MAX as f64);
self.vy *= velocity_decay;
}
}
}