phys-collision 2.0.1-beta.0

Provides collision detection ability
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
463
464
465
466
467
468
469
470
471
472
473
474
475
// Copyright (C) 2020-2025 phys-collision authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use glam_det::Point3;
use strum_macros::EnumCount as EnumCountMacro;

use super::ConvexHull;
use crate::ray::{Raycast, RaycastHitResult};
use crate::shapes::container::{ComplexShapeId as ConvexHullId, ComplexShapeId};
use crate::shapes::{Capsule, Cuboid, Cylinder, InfinitePlane, ShapeContainer, Sphere};
use crate::traits::{ContainsPoint, ContainsResult, Expansion, SignedDistanceToPoint};
use crate::{Aabb3, ComputeAabb3, ComputeVolume, Ray};

/// 3D shape types enum
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, EnumCountMacro, strum_macros::AsRefStr)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Shape {
    Cuboid(Cuboid),
    Sphere(Sphere),
    Capsule(Capsule),
    Cylinder(Cylinder),
    ConvexHull(ConvexHullId),
    InfinitePlane(InfinitePlane),
    Custom {
        plugin_id: u64,
        complex_shape_id: ComplexShapeId,
    },
}

macro_rules! impl_shape_from_types {
    ($($type:ident),*) => {
        $(
            impl From<$type> for Shape {
                #[inline]
                fn from(shape: $type) -> Self {
                    Self::$type(shape)
                }
            }
        )*
    };
}

impl_shape_from_types!(Cuboid, Sphere, Capsule, Cylinder, InfinitePlane);

#[derive(Clone, Copy)]
pub struct ShapeRef<'a> {
    pub value: Shape,
    pub container: &'a ShapeContainer,
}

impl<'a> ShapeRef<'a> {
    #[must_use]
    pub fn compute_aabb(&self) -> Aabb3 {
        match &self.value {
            Shape::Cuboid(s) => s.compute_aabb(),
            Shape::Sphere(s) => s.compute_aabb(),
            Shape::Capsule(s) => s.compute_aabb(),
            Shape::InfinitePlane(s) => s.compute_aabb(),
            Shape::Cylinder(s) => s.compute_aabb(),
            Shape::ConvexHull(id) => self
                .container
                .get_shape_set_by_id(ConvexHull::PLUGIN_ID)
                .compute_aabb(*id),
            Shape::Custom {
                plugin_id,
                complex_shape_id,
            } => self
                .container
                .get_shape_set_by_id(*plugin_id)
                .compute_aabb(*complex_shape_id),
        }
    }

    #[must_use]
    pub fn max_radius_and_max_angular_expansion(&self) -> (f32, f32) {
        match &self.value {
            Shape::Cuboid(s) => s.max_radius_and_max_angular_expansion(),
            Shape::Sphere(s) => s.max_radius_and_max_angular_expansion(),
            Shape::Capsule(s) => s.max_radius_and_max_angular_expansion(),
            Shape::InfinitePlane(s) => s.max_radius_and_max_angular_expansion(),
            Shape::Cylinder(s) => s.max_radius_and_max_angular_expansion(),
            Shape::ConvexHull(id) => self
                .container
                .get_shape_set_by_id(ConvexHull::PLUGIN_ID)
                .max_radius_and_max_angular_expansion(*id),
            Shape::Custom {
                plugin_id,
                complex_shape_id,
            } => self
                .container
                .get_shape_set_by_id(*plugin_id)
                .max_radius_and_max_angular_expansion(*complex_shape_id),
        }
    }

    #[inline]
    #[must_use]
    pub fn raycast(
        &self,
        local_ray: Ray,
        max_distance: f32,
        discard_inside_hit: bool,
    ) -> Option<RaycastHitResult> {
        match &self.value {
            Shape::Cuboid(s) => s.raycast(local_ray, max_distance, discard_inside_hit),
            Shape::Sphere(s) => s.raycast(local_ray, max_distance, discard_inside_hit),
            Shape::Capsule(s) => s.raycast(local_ray, max_distance, discard_inside_hit),
            Shape::InfinitePlane(s) => s.raycast(local_ray, max_distance, discard_inside_hit),
            Shape::Cylinder(s) => s.raycast(local_ray, max_distance, discard_inside_hit),
            Shape::ConvexHull(id) => self
                .container
                .get_shape_set_by_id(ConvexHull::PLUGIN_ID)
                .raycast(*id, local_ray, max_distance, discard_inside_hit),
            Shape::Custom {
                plugin_id,
                complex_shape_id,
            } => self.container.get_shape_set_by_id(*plugin_id).raycast(
                *complex_shape_id,
                local_ray,
                max_distance,
                discard_inside_hit,
            ),
        }
    }

    #[inline]
    #[must_use]
    pub fn contains_point(&self, local_point: Point3) -> ContainsResult {
        self.contains_point_with_threshold(local_point, f32::EPSILON)
    }

    /// # Panics
    /// Panics if the convex hull id is invalid.
    ///
    /// Panics if self is a mesh shape.
    #[inline]
    #[must_use]
    pub fn contains_point_with_threshold(
        &self,
        local_point: Point3,
        threshold: f32,
    ) -> ContainsResult {
        match &self.value {
            Shape::Cuboid(s) => s.contains_point_with_threshold(local_point, threshold),
            Shape::Sphere(s) => s.contains_point_with_threshold(local_point, threshold),
            Shape::Capsule(s) => s.contains_point_with_threshold(local_point, threshold),
            Shape::InfinitePlane(s) => s.contains_point_with_threshold(local_point, threshold),
            Shape::Cylinder(s) => s.contains_point_with_threshold(local_point, threshold),
            Shape::ConvexHull(id) => {
                // TODO: test coverage for this line in issue #1428
                self.container
                    .get_shape_set_by_id(ConvexHull::PLUGIN_ID)
                    .contains_point_with_threshold(*id, local_point, threshold)
            }

            Shape::Custom {
                plugin_id,
                complex_shape_id,
            } => self
                .container
                .get_shape_set_by_id(*plugin_id)
                .contains_point_with_threshold(*complex_shape_id, local_point, threshold),
        }
    }

    /// # Panics
    /// Panics if self is a convex hull shape.
    ///
    /// Panics if self is a mesh shape.
    #[inline]
    #[must_use]
    pub fn signed_distance_to_point(&self, local_point: Point3) -> f32 {
        match &self.value {
            Shape::Cuboid(s) => s.signed_distance_to_point(local_point),
            Shape::Sphere(s) => s.signed_distance_to_point(local_point),
            Shape::Capsule(s) => s.signed_distance_to_point(local_point),
            Shape::InfinitePlane(s) => s.signed_distance_to_point(local_point),
            Shape::Cylinder(s) => s.signed_distance_to_point(local_point),
            Shape::ConvexHull(_id) => {
                todo!("issue #1433");
            }

            Shape::Custom {
                plugin_id,
                complex_shape_id,
            } => self
                .container
                .get_shape_set_by_id(*plugin_id)
                .signed_distance_to_point(*complex_shape_id, local_point),
        }
    }
}

impl Shape {
    /// Create a new cuboid shape.
    /// # Arguments
    /// * 'x' - The x dimension of the cuboid.
    /// * 'y' - The y dimension of the cuboid.
    /// * 'z' - The z dimension of the cuboid.
    #[inline]
    #[must_use]
    pub fn new_cuboid(x: f32, y: f32, z: f32) -> Self {
        Self::Cuboid(Cuboid::new_xyz(x, y, z))
    }

    /// Create a new sphere shape.
    /// # Arguments
    /// * `radius` - The radius of the sphere.
    /// # Panics
    /// Panics if the radius is less than or equal to 0.
    #[inline]
    #[must_use]
    pub fn new_sphere(radius: f32) -> Self {
        Self::Sphere(Sphere::new(radius))
    }

    /// Create a new capsule shape.
    /// # Arguments
    /// * `half_height` - The half height of the capsule. Not including the radius.
    /// * `radius` - The radius of the capsule.
    /// # Panics
    /// Panics if the `radius` is less than 0.
    /// Panics if the `half_height` is less than or equal to 0.
    #[inline]
    #[must_use]
    pub fn new_capsule(half_height: f32, radius: f32) -> Self {
        Self::Capsule(Capsule::new(half_height, radius))
    }

    /// Create a new cylinder shape.
    /// # Arguments
    /// * `half_height` - The half height of the cylinder
    /// * `radius` - The radius of the cylinder.
    /// # Panics
    /// Panics if the `radius` is less than or equal to 0.
    /// Panics if the `half_height` is less than or equal to 0.
    #[inline]
    #[must_use]
    pub fn new_cylinder(half_height: f32, radius: f32) -> Self {
        Self::Cylinder(Cylinder::new(half_height, radius))
    }

    /// Create a new infinite plane shape.
    /// NOTE: The infinite plane is always facing the positive y direction in actor's local space.
    #[inline]
    #[must_use]
    pub fn new_infinite_plane() -> Self {
        Self::InfinitePlane(InfinitePlane::default())
    }

    /// Create a new convex hull shape.
    /// # Arguments
    /// * `convex_hull_id` - The id of the convex hull in the shape container.
    #[inline]
    #[must_use]
    pub fn new_convex_hull(convex_hull_id: ConvexHullId) -> Self {
        Self::ConvexHull(convex_hull_id)
    }
}

impl Shape {
    #[inline]
    #[must_use]
    pub fn into_shape_ref(self, container: &ShapeContainer) -> ShapeRef<'_> {
        ShapeRef {
            value: self,
            container,
        }
    }
}

impl ComputeVolume for Shape {
    #[inline]
    fn compute_volume(&self) -> f32 {
        match self {
            Self::InfinitePlane(_) => 0.0,
            Self::Cuboid(shape) => shape.compute_volume(),
            Self::Sphere(shape) => shape.compute_volume(),
            Self::Cylinder(shape) => shape.compute_volume(),
            Self::Capsule(shape) => shape.compute_volume(),
            _ => {
                panic!("Not supported on complex shape. use ShapeRef::volume instead");
            }
        }
    }
}

impl<'a> ComputeVolume for ShapeRef<'a> {
    #[inline]
    fn compute_volume(&self) -> f32 {
        match self.value {
            Shape::InfinitePlane(_) => 0.0,
            Shape::Cuboid(shape) => shape.compute_volume(),
            Shape::Sphere(shape) => shape.compute_volume(),
            Shape::Cylinder(shape) => shape.compute_volume(),
            Shape::Capsule(shape) => shape.compute_volume(),
            Shape::ConvexHull(id) => self
                .container
                .get_shape_set_by_id(ConvexHull::PLUGIN_ID)
                .compute_volume(id),

            Shape::Custom {
                plugin_id,
                complex_shape_id,
            } => self
                .container
                .get_shape_set_by_id(plugin_id)
                .compute_volume(complex_shape_id),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::f32::consts::PI;

    use approx_det::assert_relative_eq;
    use glam_det::*;
    use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure};

    use crate::ray::RaycastHitResult;
    use crate::{
        Capsule, ComputeVolume, ConvexHull, Cuboid, CuboidExt, Cylinder, InfinitePlane, Ray, Shape,
        ShapeContainer, Sphere,
    };
    wasm_bindgen_test_configure!(run_in_browser);
    #[test]
    #[wasm_bindgen_test]
    fn test_expansion() {
        let _ = env_logger::builder().is_test(true).try_init();

        let mut container = ShapeContainer::default();
        let cuboid = Shape::Cuboid(crate::Cuboid::new_xyz(1.0, 2.0, 3.0));
        let cuboid_ref = cuboid.into_shape_ref(&container);
        let _ = cuboid_ref.max_radius_and_max_angular_expansion();
        let sphere = Shape::Sphere(Sphere::new(1.0));
        let sphere_ref = sphere.into_shape_ref(&container);
        let _ = sphere_ref.max_radius_and_max_angular_expansion();
        let capsule = Shape::Capsule(crate::Capsule::new(1.0, 2.0));
        let capsule_ref = capsule.into_shape_ref(&container);
        let _ = capsule_ref.max_radius_and_max_angular_expansion();
        let cylinder = Shape::Cylinder(crate::Cylinder::new(1.0, 2.0));
        let cylinder_ref = cylinder.into_shape_ref(&container);
        let _ = cylinder_ref.max_radius_and_max_angular_expansion();
        let convex_hull = Shape::ConvexHull(container.add(ConvexHull::new_unchecked(&[
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(1.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(1.0, 1.0, 1.0),
        ])));
        let convex_hull_ref = convex_hull.into_shape_ref(&container);
        let _ = convex_hull_ref.max_radius_and_max_angular_expansion();
        let infinite_plane = Shape::InfinitePlane(crate::InfinitePlane::default());
        let infinite_plane_ref = infinite_plane.into_shape_ref(&container);
        let _ = infinite_plane_ref.max_radius_and_max_angular_expansion();
    }

    #[test]
    #[wasm_bindgen_test]
    fn test_shape_volume() {
        let _ = env_logger::builder().is_test(true).try_init();

        let shape: Shape = Shape::Cuboid(Cuboid::new(vec3(1.0, 2.0, 3.0)));
        assert_relative_eq!(shape.compute_volume(), 6.0);

        let shape: Shape = Shape::Cylinder(Cylinder::new(1.0, 2.0));
        assert_relative_eq!(shape.compute_volume(), 8.0 * PI);

        let shape: Shape = Shape::Capsule(Capsule::new(1.0, 2.0));
        assert_relative_eq!(shape.compute_volume(), 32.0 * PI / 3.0 + 8.0 * PI);

        let shape: Shape = Shape::Sphere(Sphere::new(1.0));
        assert_relative_eq!(shape.compute_volume(), 4.188_790_3);

        let shape: Shape = Shape::InfinitePlane(InfinitePlane::default());
        assert_relative_eq!(shape.compute_volume(), 0.0);
    }

    #[test]
    fn test_shape_new() {
        let shape = Shape::new_cuboid(1.0, 2.0, 3.0);
        #[allow(clippy::float_cmp)]
        if let Shape::Cuboid(cuboid) = shape {
            assert_eq!(cuboid.length(), [1.0, 2.0, 3.0]);
        } else {
            panic!("Expected a cuboid shape");
        }

        let shape = Shape::new_sphere(1.0);
        if let Shape::Sphere(sphere) = shape {
            assert_relative_eq!(sphere.radius(), 1.0, epsilon = f32::EPSILON);
        } else {
            panic!("Expected a sphere shape");
        }

        let shape = Shape::new_capsule(2.0, 1.0);
        if let Shape::Capsule(capsule) = shape {
            assert_relative_eq!(capsule.radius(), 1.0, epsilon = f32::EPSILON);
            assert_relative_eq!(capsule.half_height(), 2.0, epsilon = f32::EPSILON);
        } else {
            panic!("Expected a capsule shape");
        }

        let shape = Shape::new_cylinder(2.0, 1.0);
        if let Shape::Cylinder(cylinder) = shape {
            assert_relative_eq!(cylinder.radius(), 1.0, epsilon = f32::EPSILON);
            assert_relative_eq!(cylinder.half_height(), 2.0, epsilon = f32::EPSILON);
        } else {
            panic!("Expected a cylinder shape");
        }

        let shape = Shape::new_infinite_plane();

        if let Shape::InfinitePlane(_) = shape {
        } else {
            panic!("Expected an infinite plane shape");
        }

        let mut container = ShapeContainer::default();

        let convex_hull_id = container.add(ConvexHull::new_unchecked(&[
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(1.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(1.0, 1.0, 1.0),
        ]));
        let shape = Shape::new_convex_hull(convex_hull_id);
        if let Shape::ConvexHull(id) = shape {
            assert_eq!(id, convex_hull_id);
        } else {
            panic!("Expected a convex hull shape");
        }
    }

    #[test]
    #[wasm_bindgen_test]
    fn test_convex_hull_raycast() {
        let _ = env_logger::builder().is_test(true).try_init();

        let cuboid = Cuboid::new(Vec3::ONE * 2.0);
        let vertice_indexs = 0..8_usize;
        let vertices: Vec<Point3> = vertice_indexs
            .into_iter()
            .map(|i| cuboid.get_vertex(i))
            .collect();
        let convex_hull = ConvexHull::new_unchecked(&vertices);

        let mut shape_batches = ShapeContainer::default();
        let id = shape_batches.add(convex_hull);
        assert!(shape_batches.get::<ConvexHull>(id).is_some());
        let shape = Shape::ConvexHull(id);
        let shape_ref = shape.into_shape_ref(&shape_batches);
        let ray = Ray::new_with_vec3([0.0, 0.0, 1.0], [0.0, 0.0, 1.0]);
        assert_eq!(shape_ref.raycast(ray, 10.0, true), None);
        assert_eq!(
            shape_ref.raycast(ray, 10.0, false),
            Some(RaycastHitResult {
                distance: 0.0,
                normal: -ray.direction,
            })
        );
    }
}