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
use slab::{Iter, IterMut, Slab};
use na::Real;
use crate::world::ColliderWorld;
use crate::object::{Body, Ground};
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct BodyHandle(usize);
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct BodyPartHandle(pub BodyHandle, pub usize);
impl BodyHandle {
#[inline]
pub fn ground() -> Self {
BodyHandle(usize::max_value())
}
#[inline]
pub fn is_ground(&self) -> bool {
self.0 == usize::max_value()
}
}
impl BodyPartHandle {
pub fn ground() -> Self {
BodyPartHandle(BodyHandle::ground(), 0)
}
pub fn is_ground(&self) -> bool {
self.0.is_ground()
}
}
pub trait BodyDesc<N: Real> {
type Body: Body<N>;
fn build_with_handle(&self, cworld: &mut ColliderWorld<N>, handle: BodyHandle) -> Self::Body;
}
pub struct BodySet<N: Real> {
ground: Ground<N>,
bodies: Slab<Box<Body<N>>>,
}
impl<N: Real> BodySet<N> {
pub fn new() -> Self {
BodySet {
ground: Ground::new(),
bodies: Slab::new(),
}
}
pub fn len(&self) -> usize {
self.bodies.len()
}
pub fn add_body<B: BodyDesc<N>>(&mut self, desc: &B, cworld: &mut ColliderWorld<N>) -> &mut B::Body {
let b_entry = self.bodies.vacant_entry();
let b_id = b_entry.key();
let handle = BodyHandle(b_id);
let body = desc.build_with_handle(cworld, handle);
b_entry.insert(Box::new(body)).downcast_mut::<B::Body>().expect("Body construction failed with type mismatch.")
}
pub fn remove_body(&mut self, body: BodyHandle) {
if !body.is_ground() {
let _ = self.bodies.remove(body.0);
}
}
#[inline]
pub fn contains(&self, handle: BodyHandle) -> bool {
handle.is_ground() || self.bodies.contains(handle.0)
}
#[inline]
pub fn body(&self, handle: BodyHandle) -> Option<&Body<N>> {
if handle.is_ground() {
Some(&self.ground)
} else {
self.bodies.get(handle.0).map(|b| &**b)
}
}
#[inline]
pub fn body_mut(&mut self, handle: BodyHandle) -> Option<&mut Body<N>> {
if handle.is_ground() {
Some(&mut self.ground)
} else {
self.bodies.get_mut(handle.0).map(|b| &mut **b)
}
}
#[inline]
pub fn bodies(&self) -> impl Iterator<Item = &Body<N>> {
self.bodies.iter().map(|e| &**e.1)
}
#[inline]
pub fn bodies_mut(&mut self) -> impl Iterator<Item = &mut Body<N>> {
self.bodies.iter_mut().map(|e| &mut **e.1)
}
}
pub type Bodies<'a, N> = Iter<'a, Box<Body<N>>>;
pub type BodiesMut<'a, N> = IterMut<'a, Box<Body<N>>>;