collide-convex 0.5.4

Convex collider implementation for the collide crate
Documentation
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
#![deny(missing_docs)]

//! This crate contains a convex collider, which implements the collide trait from the `collide` crate.

use collide::{Collider, CollisionInfo, Transform, Transformable};
use inner_space::{InnerSpace, VectorSpace};
use scalars::{One, Real, Sqrt, Zero};

fn epsilon<V: VectorSpace>() -> V::Scalar
where
    V::Scalar: Real,
{
    let two = V::Scalar::one() + V::Scalar::one();
    let thousand = {
        let t = two * two * two * two * two;
        t * t
    };
    V::Scalar::one() / (thousand * thousand)
}

/// The convex collider defined as a convex hull around multiple spheres having the same radius.
#[derive(Clone)]
pub struct Convex<V: VectorSpace> {
    /// The radius of the spheres.
    pub rad: V::Scalar,
    /// The positions of the spheres.
    pub points: Box<[V]>,
}

impl<V: VectorSpace> Convex<V> {
    /// Creates a new convex collider.
    pub const fn new(rad: V::Scalar, points: Box<[V]>) -> Self {
        Self { rad, points }
    }

    /// Creates a new convex collider representing a capsule.
    pub fn capsule(rad: V::Scalar, start: V, end: V) -> Self {
        Self {
            rad,
            points: [start, end].into(),
        }
    }

    /// Creates a new convex collider representing a point.
    pub fn point(pos: V) -> Self {
        Self {
            rad: V::Scalar::zero(),
            points: [pos].into(),
        }
    }

    /// Creates a new convex collider representing a line.
    pub fn line(start: V, end: V) -> Self {
        Self {
            rad: V::Scalar::zero(),
            points: [start, end].into(),
        }
    }

    /// Creates a new convex collider representing a sphere.
    pub fn sphere(pos: V, rad: V::Scalar) -> Self {
        Self {
            rad,
            points: [pos].into(),
        }
    }
}

pub(crate) fn origin_offset<V: Copy + InnerSpace>(vertices: &[V]) -> V {
    let Some(&first) = vertices.first() else {
        return V::zero();
    };

    let mut ortho: Vec<V> = Vec::new();
    for &vertex in &vertices[1..] {
        let mut edge = vertex - first;
        for basis in &ortho {
            let mag2 = basis.magnitude2();
            if !mag2.is_zero() {
                edge = edge - *basis * (edge.dot(basis) / mag2);
            }
        }
        if !edge.is_zero() {
            ortho.push(edge);
        }
    }

    let mut result = first;
    for basis in &ortho {
        let mag2 = basis.magnitude2();
        if !mag2.is_zero() {
            result = result - *basis * (result.dot(basis) / mag2);
        }
    }
    result
}

fn is_projection_inside<V: Copy + InnerSpace>(offset: V, simplex: &[V]) -> bool {
    if simplex.len() <= 1 {
        return true;
    }
    let n = simplex.len();
    for i in 0..n {
        let face: Vec<V> = (0..n).filter(|&j| j != i).map(|j| simplex[j]).collect();
        let face_offset = origin_offset(&face);
        let toward_vertex = simplex[i] - face_offset;
        let toward_projection = offset - face_offset;
        if toward_vertex.dot(&toward_projection) < V::Scalar::zero() {
            return false;
        }
    }
    true
}

pub(crate) fn closest_subsimplex<V: Copy + InnerSpace>(points: &[V]) -> (Vec<V>, V) {
    let n = points.len();
    let last_bit = 1u32 << (n - 1);
    let mut best: Option<(u32, V, V::Scalar)> = None;

    for mask in 1u32..(1u32 << n) {
        if mask & last_bit == 0 {
            continue;
        }

        let subset: Vec<V> = (0..n)
            .filter(|&i| mask & (1 << i) != 0)
            .map(|i| points[i])
            .collect();

        let offset = origin_offset(&subset);

        if !is_projection_inside(offset, &subset) {
            continue;
        }

        let mag2 = offset.magnitude2();
        if best.as_ref().is_some_and(|(_, _, m)| mag2 >= *m) {
            continue;
        }

        best = Some((mask, offset, mag2));
    }

    let (mask, offset, _) =
        best.unwrap_or_else(|| (last_bit, points[n - 1], points[n - 1].magnitude2()));
    let subset = (0..n)
        .filter(|&i| mask & (1 << i) != 0)
        .map(|i| points[i])
        .collect();
    (subset, offset)
}

fn epa<V: Copy + InnerSpace>(initial_simplex: &[V], support: impl Fn(V) -> V) -> V
where
    V::Scalar: Real,
{
    if initial_simplex.len() <= 2 {
        return epa_closest_initial_face(initial_simplex);
    }

    let mut vertices: Vec<V> = initial_simplex.to_vec();
    let vertex_count = vertices.len();

    let mut faces: Vec<Vec<usize>> = (0..vertex_count)
        .map(|skip| (0..vertex_count).filter(|&i| i != skip).collect())
        .collect();

    let mut result = epa_closest_initial_face(initial_simplex);

    for _ in 0..64 {
        let Some((_, offset, distance)) = epa_find_closest_face(&vertices, &faces) else {
            break;
        };

        if distance.is_zero() {
            continue;
        }

        result = offset;

        let new_point = support(offset);

        let new_projection = new_point.dot(&offset);
        let tolerance = epsilon::<V>().sqrt();
        if new_projection - distance <= tolerance * distance {
            break;
        }

        let eps = epsilon::<V>();
        if vertices
            .iter()
            .any(|&vertex| (vertex - new_point).magnitude2() <= eps)
        {
            break;
        }

        let new_index = vertices.len();
        vertices.push(new_point);

        let visible: Vec<bool> = faces
            .iter()
            .map(|face| {
                let points: Vec<V> = face.iter().map(|&i| vertices[i]).collect();
                let face_offset = origin_offset(&points);
                if face_offset.magnitude2().is_zero() {
                    return false;
                }
                (new_point - vertices[face[0]]).dot(&face_offset) > V::Scalar::zero()
            })
            .collect();

        let mut ridges: Vec<Vec<usize>> = Vec::new();
        for (face_index, face) in faces.iter().enumerate() {
            if !visible[face_index] {
                continue;
            }
            for skip in 0..face.len() {
                let mut ridge: Vec<usize> = face
                    .iter()
                    .enumerate()
                    .filter(|&(j, _)| j != skip)
                    .map(|(_, &vertex)| vertex)
                    .collect();
                ridge.sort_unstable();
                ridges.push(ridge);
            }
        }

        let horizon: Vec<Vec<usize>> = ridges
            .iter()
            .filter(|ridge| ridges.iter().filter(|other| other == ridge).count() == 1)
            .cloned()
            .collect();

        faces = faces
            .into_iter()
            .enumerate()
            .filter(|(index, _)| !visible[*index])
            .map(|(_, face)| face)
            .collect();

        for ridge in horizon {
            let mut face = ridge;
            face.push(new_index);
            faces.push(face);
        }

        if faces.is_empty() {
            break;
        }
    }

    result
}

fn epa_find_closest_face<V: Copy + InnerSpace>(
    vertices: &[V],
    faces: &[Vec<usize>],
) -> Option<(usize, V, V::Scalar)> {
    let mut best: Option<(usize, V, V::Scalar)> = None;

    for (index, face) in faces.iter().enumerate() {
        let points: Vec<V> = face.iter().map(|&i| vertices[i]).collect();
        let offset = origin_offset(&points);

        if !is_projection_inside(offset, &points) {
            continue;
        }

        let distance = offset.magnitude2();
        if distance.is_zero() {
            continue;
        }
        if best.as_ref().is_some_and(|(_, _, d)| distance >= *d) {
            continue;
        }

        best = Some((index, offset, distance));
    }

    best
}

fn epa_closest_initial_face<V: Copy + InnerSpace>(simplex: &[V]) -> V {
    let mut best: Option<(V::Scalar, V)> = None;
    for skip in 0..simplex.len() {
        let face: Vec<V> = (0..simplex.len())
            .filter(|&j| j != skip)
            .map(|j| simplex[j])
            .collect();
        if face.is_empty() {
            continue;
        }
        let offset = origin_offset(&face);
        let magnitude = offset.magnitude2();
        if magnitude.is_zero() {
            continue;
        }
        if best.as_ref().is_some_and(|(m, _)| magnitude >= *m) {
            continue;
        }
        best = Some((magnitude, offset));
    }
    best.map_or_else(V::zero, |(_, offset)| offset)
}

enum Side {
    Inside,
    Outside,
}

impl<V: Copy + InnerSpace> Convex<V>
where
    V::Scalar: Real,
{
    fn support(&self, other: &Self, dir: V) -> V {
        let mut found: Option<V> = None;
        for &point in &self.points {
            for &other_point in &other.points {
                let diff = other_point - point;
                if found.is_some_and(|found| diff.dot(&dir) <= found.dot(&dir)) {
                    continue;
                }
                found = Some(diff);
            }
        }

        found.unwrap_or_else(V::zero)
    }

    fn offset(&self, other: &Self) -> (V, Side) {
        let isd = other.points[0] - self.points[0];
        if isd.is_zero() {
            return (V::zero(), Side::Outside);
        }
        let initial = self.support(other, isd);
        let mut simplex = vec![initial];
        let mut dir = -initial;

        for _ in 0..64 {
            let new_point = self.support(other, dir);

            if simplex.contains(&new_point) {
                break;
            }

            simplex.push(new_point);
            let (sub, offset) = closest_subsimplex(&simplex);

            let inside = if offset.is_zero() {
                true
            } else if sub.len() == simplex.len() {
                let scale = simplex
                    .iter()
                    .copied()
                    .map(|v| v.magnitude2())
                    .fold(V::Scalar::zero(), |a, b| if a > b { a } else { b });
                let eps = epsilon::<V>();
                offset.magnitude2() <= scale * eps * eps
            } else {
                false
            };
            if inside {
                let mut expanded = sub;
                'expand: for &self_point in &self.points {
                    for &other_point in &other.points {
                        let diff = other_point - self_point;
                        if expanded.contains(&diff) {
                            continue;
                        }
                        expanded.push(diff);
                        let (new_sub, new_offset) = closest_subsimplex(&expanded);
                        if new_offset.is_zero() {
                            expanded = new_sub;
                            if expanded.len() > 2 {
                                break 'expand;
                            }
                        } else {
                            expanded.pop();
                        }
                    }
                }
                let result = epa(&expanded, |direction| self.support(other, direction));
                return (result, Side::Inside);
            }

            simplex = sub;
            dir = -offset;
        }

        (origin_offset(&simplex), Side::Outside)
    }
}

impl<V: Copy + InnerSpace, T: Transform<V>> Transformable<T> for Convex<V> {
    fn transformed(&self, transform: &T) -> Self {
        Self {
            rad: self.rad,
            points: self
                .points
                .iter()
                .map(|&p| transform.apply_point(p))
                .collect(),
        }
    }
}

#[cfg(feature = "sphere")]
mod bounding_sphere;

#[cfg(feature = "ray")]
mod ray;

impl<V: Copy + InnerSpace> Collider for Convex<V>
where
    V::Scalar: Real,
{
    type Vector = V;

    fn collision_info(&self, other: &Self) -> Option<CollisionInfo<Self::Vector>> {
        let (offset, side) = self.offset(other);
        let mag2 = offset.magnitude2();
        let rad = self.rad + other.rad;
        match side {
            Side::Inside => {
                if mag2.is_zero() {
                    return Some(CollisionInfo {
                        self_contact: V::zero(),
                        other_contact: V::zero(),
                        vector: V::zero(),
                    });
                }
                let mag = mag2.sqrt();
                let dir = offset / mag;
                Some(CollisionInfo {
                    self_contact: V::zero(),
                    other_contact: V::zero(),
                    vector: dir * (mag + rad),
                })
            }
            Side::Outside => {
                if mag2 > rad * rad {
                    return None;
                }
                if mag2.is_zero() {
                    return Some(CollisionInfo {
                        self_contact: V::zero(),
                        other_contact: V::zero(),
                        vector: V::zero(),
                    });
                }
                let mag = mag2.sqrt();
                let dir = offset / mag;
                Some(CollisionInfo {
                    self_contact: V::zero(),
                    other_contact: V::zero(),
                    vector: dir * (mag - rad),
                })
            }
        }
    }
}