The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
parry's voxel ray hits along the lattice's planes, fixed at the source; the world's own ray walk goes (#34)
Yujia0a89089aa051
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 1b1091d..7a92788 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -4457,9 +4457,11 @@ benchmark level. The order follows the dependencies; a step that meets a furthera face between two cells is held by the cell the point falls in, else the nearest solid neighbour.- (c2) Vehicles and ropes: the ray-cast vehicle (Rapier's `DynamicRayCastVehicleController`; the comparison in`out/web-probe/step10/c-vehicle-compare.md`: steady, 250-300 times cheaper than a car of wheel joints, as- deterministic); ropes as `RopeJoint` and a drawn curve (they do not collide: they pass through walls). Waits on- the user's decision on parry's voxel ray, which misses 8-22 % of rays starting on a lattice plane (the wheels'- rays go through it).+ deterministic); ropes as `RopeJoint` and a drawn curve (they do not collide: they pass through walls). Before it:+ parry's voxel ray, which missed 8-22 % of rays starting on a lattice plane (the wheels' rays go through it), is+ fixed at the source (the user's decision, 2026-11-12: `renderer/third_party/parry3d`, its chunk walk only; the+ world's own walk removed, every ray through Rapier's query; branch `parry-voxel-ray`); and a CPU comparison of+ single-ray wheels against shape-cast wheels on debris and narrow gaps (to be scoped).- (d) Acceptance: the benchmark level played through as a game, every line of `docs/VOXEL.md`'s benchmark measured.## Known issuesdiff --git a/docs/VOXEL.md b/docs/VOXEL.mdindex 2541b4d..4d6fa37 100644--- a/docs/VOXEL.md+++ b/docs/VOXEL.md@@ -760,13 +760,13 @@ of their own). Each place in `packages/voxel/src/explosions.ts` points here.### Where the engine works round its dependenciesEach is a way round a fault or a gap of Rapier 0.36.1, parry 0.31.1, glamx 0.3.1 or rayon 1.12, in our code (no-crate is patched but glamx, in `renderer/third_party`). When a new release comes, this says what can go.+crate is patched but glamx and parry3d, in `renderer/third_party`). When a new release comes, this says what can go.| What | Way round | Where | It can go when | How to tell || --- | --- | --- | --- | --- || The parallel step can hang: Rapier joins its deferred BVH pass with a blocking `recv` on a pool worker, and rayon does not promise another worker takes the job (ROADMAP § 6 step 8) | the wait for a step injects an empty job into the pool every 0.5 ms (`THREERT_PHYSICS_KICK=off` waits without) | `renderer/src/physics.rs` `in_pool` | Rapier joins that pass without blocking a worker (or runs it inline) | `cargo run --release --example physics_fuzz -- --runs 0 --stress 10000000` with `THREERT_PHYSICS_KICK=off`: no hang (today it hangs within 10⁵–10⁶ steps); then delete `in_pool`'s kick || A ball on voxels panics the solver ("stale ContactRef manifold ordinal"): parry's voxels-ball contact keeps no workspace, so Rapier takes the pair for a simple one | the pair goes through parry's general voxels-shape function (a query dispatcher) | `renderer/physics-core/src/world.rs` `VoxelsWithBalls` | parry's voxels-ball contact keeps a workspace (or Rapier stops deciding by it) | take the dispatcher out and run `check::cases` (its voxel kind), `voxel_worlds_never_panic` (20,000 worlds, ignored: `-- --ignored`) and `random_calls_on_voxel_shapes_never_panic`: none panics |-| parry's ray misses voxels when it lies on a lattice plane and runs along it | the world walks the cells itself (Amanatides–Woo) | `world.rs` `voxel_ray`, `shape_ray` | parry's ray cast on `Voxels` hits along lattice planes | `rays_at_voxel_shapes` with parry's ray in place of `voxel_ray` (it compares with brute force) |+| parry's ray misses voxels when it lies on a lattice plane and runs along it (8-22 % of rays straight down on a plane: a solid cell's box is asked for the hit again, and a ray in its face's plane grazes it) | **fixed at the source**: parry's chunk walk takes a solid cell as hit where the ray entered it (2026-11-12; the world's own walk is gone, every ray goes through Rapier's query) | `renderer/third_party/parry3d` (`PATCH.md`: `ray_voxels.rs` only), `[patch.crates-io]` in the three manifests | a parry release has the fix (upstream report: `out/upstream/parry-voxel-ray/DRAFT.md`, not sent) and Rapier uses it | delete the copy and its patch lines; `rays_at_voxel_shapes` (brute force, the lattice's planes, 0 misses) and the recorded hashes hold || parry's `Voxels::voxels()` leaves cells out: it takes its range from the shape's box in metres, and f32 rounding can drop a layer (one cell at (-1000, 9, -673) of 0.1 m is listed as none; found by the fuzz, a body's count 29 short) | the world lists a shape's cells over its exact `domain()` (`voxels_in_range`) | `world.rs` `listed` | `Voxels::voxels()` takes its range as `domain()` does (from voxel centres) | `every_voxel_is_listed` with `voxels()` in place of `listed` || A voxel shape edited where it sits (`shape_mut`) leaves stale recycled contacts on pairs that do not move | `edit_voxels` takes the collider out and puts it back under the same id | `world.rs` `Physics::edit_voxels` | Rapier refreshes a collider's manifolds when its shape is edited in place | `voxel_shapes_are_edited` and the voxel fuzz with the edit done through `shape_mut` || glamx's eigen decomposition calls the platform's `acos` / `cos` when `std` is in the crate graph: other bits natively than in wasm32 | the three calls through `simba`'s libm, by name | `renderer/third_party/glamx` (`PATCH.md`), `[patch.crates-io]` in both manifests | a glamx release has the fix (dimforge/glamx #9, #10) and Rapier uses it | delete the copy and the patch tables; `tools/physics-determinism.ts` (its "std in the crate graph" run) and the recorded hashes hold |diff --git a/renderer/Cargo.lock b/renderer/Cargo.lockindex 40d9a0d..00cf6a6 100644--- a/renderer/Cargo.lock+++ b/renderer/Cargo.lock@@ -1654,8 +1654,6 @@ dependencies = [[[package]]name = "parry3d"version = "0.31.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7b626edc0b497dba4bdf6e1e0797895294ed9f61dac2bd28cb5d34d37ad2ca7e"dependencies = ["approx","arrayvec",diff --git a/renderer/Cargo.toml b/renderer/Cargo.tomlindex 23b35bd..304a02a 100644--- a/renderer/Cargo.toml+++ b/renderer/Cargo.toml@@ -71,3 +71,4 @@ opt-level = 2# (src/physics.rs `the_renderers_physics_steps_to_the_recorded_bits` fails without it).[patch.crates-io]glamx = { path = "third_party/glamx" }+parry3d = { path = "third_party/parry3d" }diff --git a/renderer/physics-core/Cargo.lock b/renderer/physics-core/Cargo.lockindex 8637b7a..de1d43f 100644--- a/renderer/physics-core/Cargo.lock+++ b/renderer/physics-core/Cargo.lock@@ -332,8 +332,6 @@ dependencies = [[[package]]name = "parry3d"version = "0.31.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7b626edc0b497dba4bdf6e1e0797895294ed9f61dac2bd28cb5d34d37ad2ca7e"dependencies = ["approx","arrayvec",diff --git a/renderer/physics-core/Cargo.toml b/renderer/physics-core/Cargo.tomlindex 3662b87..d6999b9 100644--- a/renderer/physics-core/Cargo.toml+++ b/renderer/physics-core/Cargo.toml@@ -55,3 +55,4 @@ name = "voxel_shapes"# steps `check::script` and `check::cases` to the recorded hashes, which is what shows a patch left out (PATCH.md).[patch.crates-io]glamx = { path = "../third_party/glamx" }+parry3d = { path = "../third_party/parry3d" }diff --git a/renderer/physics-core/src/world.rs b/renderer/physics-core/src/world.rsindex 8c16ac3..03e5da3 100644--- a/renderer/physics-core/src/world.rs+++ b/renderer/physics-core/src/world.rs@@ -444,13 +444,6 @@ mod dispatch {}}-/// A ray against a voxel shape placed at `at`, the cells walked one by one (Amanatides and Woo): the distance to the-/// first solid cell within `max` and the normal of the face it is entered by (a ray that starts in a solid cell: 0,-/// and against the ray). Parry's own (ray_voxels.rs) tests each cell's box with the ray and takes the next cell by-/// the box's bounds, both in floating point: **a ray that lies on a plane of the lattice and runs along it misses-/// every cell** (straight down at x = 1.5 onto cells of 0.1 m, which is where a game asks for the ground). Here a-/// point belongs to the cell its coordinates floor to, the cell is stepped as an integer, and a cell that is solid-/// is a hit./// Every cell of a voxel shape. Not parry's `Voxels::voxels()`: it takes its range from the shape's box in metres, and/// f32's rounding can leave the lowest layer out (found by the fuzz: a body spanning -100.8 m .. 0.1 m listed 29 cells/// fewer than it holds, all of its lowest z row, at -67.3 m). `domain()` rounds from a voxel's centre, exactly.@@ -459,83 +452,6 @@ fn listed(v: &rapier3d::parry::shape::Voxels) -> impl Iterator<Item = rapier3d::v.voxels_in_range(d[0], d[1])}-fn voxel_ray(v: &rapier3d::parry::shape::Voxels, at: &Pose, ray: &Ray, max: f32) -> Option<(f32, Vector)> {- let size = v.voxel_size().x;- let (o, d) = (at.inverse_transform_point(ray.origin).to_array(), at.inverse_transform_vector(ray.dir).to_array());- let [lo, hi] = v.domain();- let (lo, hi) = (lo.to_array(), hi.to_array());- // The stretch of the ray inside the box of the shape's cells.- let (mut t0, mut t1, mut entered) = (0.0f32, max, 3usize);- for a in 0..3 {- let (min, max) = (lo[a] as f32 * size, hi[a] as f32 * size);- if d[a] == 0.0 {- if o[a] < min || o[a] >= max {- return None;- }- continue;- }- let (ta, tb) = ((min - o[a]) / d[a], (max - o[a]) / d[a]);- let (near, far) = (ta.min(tb), ta.max(tb));- if near > t0 {- (t0, entered) = (near, a);- }- t1 = t1.min(far);- }- if !(t0 <= t1) {- return None;- }- // The cell the ray is in there, held inside the box (it enters on a face, to rounding).- let mut cell = [0i32; 3];- for a in 0..3 {- cell[a] = (((o[a] + d[a] * t0) / size).floor() as i32).clamp(lo[a], hi[a] - 1);- }- let normal = |axis: usize| {- let mut n = [0.0f32; 3];- if axis < 3 {- n[axis] = if d[axis] > 0.0 { -1.0 } else { 1.0 };- at.transform_vector(Vector::new(n[0], n[1], n[2]))- } else {- -ray.dir.normalize_or_zero()- }- };- let mut t = t0;- let mut axis = entered;- // (At most every cell of the box's three sides: the walk leaves the box.)- loop {- if v.voxel_state(IVector::new(cell[0], cell[1], cell[2])).is_some_and(|s| !s.is_empty()) {- return Some((t, normal(axis)));- }- // The next lattice plane on each axis; the nearest is crossed (the lower axis first when they are equal).- let mut next = (f32::INFINITY, 3usize);- for a in 0..3 {- if d[a] != 0.0 {- let plane = (cell[a] + (d[a] > 0.0) as i32) as f32 * size;- let ta = ((plane - o[a]) / d[a]).max(t);- if ta < next.0 {- next = (ta, a);- }- }- }- if next.1 == 3 || next.0 > t1 {- return None;- }- (t, axis) = next;- cell[axis] += if d[axis] > 0.0 { 1 } else { -1 };- if cell[axis] < lo[axis] || cell[axis] >= hi[axis] {- return None;- }- }-}--/// A ray against a collider's shape placed at `at` (the collider's pose, or where a fresh one is): the distance and-/// the normal. Parry's answer, but for a voxel shape (`voxel_ray`).-fn shape_ray(c: &Collider, at: &Pose, ray: &Ray, max: f32) -> Option<(f32, Vector)> {- match c.shape().as_voxels() {- Some(v) => voxel_ray(v, at, ray, max),- None => c.shape().cast_ray_and_get_normal(at, ray, max, true).map(|i| (i.time_of_impact, i.normal)),- }-}-/// A number's bits as the hash takes them: one NaN for all (the platforms make NaNs of different bits, ffc00000/// natively and 7fc00000 in wasm32).pub(crate) fn hash_bits(x: f32) -> u32 {@@ -554,8 +470,6 @@ pub struct Physics {/// Each collider with its shape's data (`Shape::data`), and their sum.colliders: BTreeMap<ColliderId, (ColliderHandle, usize)>,shape_data: usize,- /// The voxel colliders there are: rays are cast at them here (`voxel_ray`), not by the broad phase's query.- voxel_colliders: std::collections::BTreeSet<ColliderId>,joints: BTreeMap<JointId, ImpulseJointHandle>,/// Per joint: its kind (what `set_joint` may change), and for a hinge the centre of its limits (rad) by which its/// first frame is turned (`add_joint`).@@ -596,7 +510,6 @@ impl Physics {bodies: BTreeMap::new(),colliders: BTreeMap::new(),shape_data: 0,- voxel_colliders: Default::default(),joints: BTreeMap::new(),joint_kinds: BTreeMap::new(),kinematic: Default::default(),@@ -671,7 +584,6 @@ impl Physics {self.world.remove_body_with_colliders(h, true);for c in &gone {self.fresh.remove(c);- self.voxel_colliders.remove(c);if let Some((_, data)) = self.colliders.remove(c) {self.shape_data -= data;}@@ -718,9 +630,6 @@ impl Physics {self.colliders.insert(id, (h, data));self.shape_data += data;self.fresh.insert(id);- if matches!(d.shape, Shape::Voxels { .. } | Shape::SharedVoxels(_)) {- self.voxel_colliders.insert(id);- }Ok(id)}@@ -729,7 +638,6 @@ impl Physics {self.world.remove_collider(h);self.shape_data -= data;self.fresh.remove(&id);- self.voxel_colliders.remove(&id);}}@@ -1022,7 +930,6 @@ impl Physics {self.colliders.remove(&id);self.shape_data -= data;self.fresh.remove(&id);- self.voxel_colliders.remove(&id);return if left == 0 { Ok(0) } else { Err(format!("physics: a voxel shape holds at most {MAX_VOXELS} cells (the collider is gone)")) };}let h = self.world.insert_collider(c, parent);@@ -1042,10 +949,10 @@ impl Physics {/// A shape several colliders share is counted once.pub fn voxel_bytes(&self) -> usize {let mut seen = std::collections::BTreeSet::new();- self.voxel_colliders- .iter()- .filter_map(|id| {- let shape = self.world.colliders.get(self.colliders.get(id)?.0)?.shared_shape();+ self.colliders+ .values()+ .filter_map(|&(h, _)| {+ let shape = self.world.colliders.get(h)?.shared_shape();let first = seen.insert(std::sync::Arc::as_ptr(&shape.0) as *const () as usize);shape.as_voxels().filter(|_| first).map(|v| v.total_memory_size())})@@ -1379,11 +1286,11 @@ impl Physics {/// whose colliders the ray passes through (the one that casts it).pub fn cast_ray(&self, origin: [f32; 3], direction: [f32; 3], max: f32, skip: Option<BodyId>) -> Result<Option<Hit>, String> {let Some((ray, max)) = Self::ray(origin, direction, max)? else { return Ok(None) };- let settled = |_: ColliderHandle, c: &Collider| !self.fresh.contains(&(c.user_data as u32)) && c.shape().as_voxels().is_none();+ let settled = |_: ColliderHandle, c: &Collider| !self.fresh.contains(&(c.user_data as u32));let mut best = self.world.cast_ray_and_get_normal(&ray, max, true, self.filter(skip, &settled)).and_then(|(h, i)| self.hit(h, i.time_of_impact, ray.point_at(i.time_of_impact), i.normal));- for (h, c, at) in self.fresh(skip).chain(self.voxels_on(&ray, max, skip)) {- if let Some((t, n)) = shape_ray(c, &at, &ray, max) {- best = Self::nearer(best, self.hit(h, t, ray.point_at(t), n));+ for (h, c, at) in self.fresh(skip) {+ if let Some(i) = c.shape().cast_ray_and_get_normal(&at, &ray, max, true) {+ best = Self::nearer(best, self.hit(h, i.time_of_impact, ray.point_at(i.time_of_impact), i.normal));}}Ok(best)@@ -1392,11 +1299,11 @@ impl Physics {/// Every collider a ray passes through within `max` metres, nearest first, at most `limit` of them.pub fn cast_ray_all(&self, origin: [f32; 3], direction: [f32; 3], max: f32, skip: Option<BodyId>, limit: usize) -> Result<Vec<Hit>, String> {let Some((ray, max)) = Self::ray(origin, direction, max)? else { return Ok(vec![]) };- let settled = |_: ColliderHandle, c: &Collider| !self.fresh.contains(&(c.user_data as u32)) && c.shape().as_voxels().is_none();+ let settled = |_: ColliderHandle, c: &Collider| !self.fresh.contains(&(c.user_data as u32));let mut hits: Vec<Hit> = self.world.intersect_ray(ray, max, true, self.filter(skip, &settled)).filter_map(|(h, _, i)| self.hit(h, i.time_of_impact, ray.point_at(i.time_of_impact), i.normal)).collect();- for (h, c, at) in self.fresh(skip).chain(self.voxels_on(&ray, max, skip)) {- if let Some((t, n)) = shape_ray(c, &at, &ray, max) {- hits.extend(self.hit(h, t, ray.point_at(t), n));+ for (h, c, at) in self.fresh(skip) {+ if let Some(i) = c.shape().cast_ray_and_get_normal(&at, &ray, max, true) {+ hits.extend(self.hit(h, i.time_of_impact, ray.point_at(i.time_of_impact), i.normal));}}// (Equal distances in collider order: the same answer on every machine.)@@ -1405,21 +1312,6 @@ impl Physics {Ok(hits)}- /// The settled voxel colliders whose boxes a ray passes within `max` (the broad phase's tree; not `skip`'s), each- /// where it is: the rays' own test of them (`voxel_ray`). None in a world without voxel shapes.- fn voxels_on<'a>(&'a self, ray: &'a Ray, max: f32, skip: Option<BodyId>) -> impl Iterator<Item = (ColliderHandle, &'a Collider, Pose)> + 'a {- let skip = skip.and_then(|b| self.bodies.get(&b)).copied();- let any = !self.voxel_colliders.is_empty();- let tree = self.world.query_pipeline().bvh;- tree.leaves(move |node: &rapier3d::parry::partitioning::BvhNode| any && node.aabb().intersects_local_ray(ray, max)).filter_map(move |leaf| {- let (c, h) = self.world.colliders.get_unknown_gen(leaf)?;- if !c.is_enabled() || c.shape().as_voxels().is_none() || self.fresh.contains(&(c.user_data as u32)) || (skip.is_some() && c.parent() == skip) {- return None;- }- Some((h, c, *c.position()))- })- }-/// A query's ray and reach (cut to `MAX_QUERY_DISTANCE`); None for a reach of 0 or less (it meets nothing).fn ray(origin: [f32; 3], direction: [f32; 3], max: f32) -> Result<Option<(Ray, f32)>, String> {within(&origin, MAX_COORD, "a query's origin")?;@@ -1446,8 +1338,8 @@ impl Physics {Some(&h) => QueryFilter::default().exclude_rigid_body(h),None => QueryFilter::default(),};- // (Nothing fresh, as after every tick, and no voxel shape: the plain filter.)- if self.fresh.is_empty() && self.voxel_colliders.is_empty() {+ // (Nothing fresh, as after every tick: the plain filter.)+ if self.fresh.is_empty() {f} else {f.predicate(settled)@@ -2150,8 +2042,13 @@ mod tests {assert!(p.take_faults().is_empty());}- /// A ray at a voxel shape meets what testing every solid cell's box finds, for random rays at a turned shape; and- /// a ray that lies on a plane of the lattice and runs along it meets the cells (parry's own walk misses them all).+ /// Parry's ray at voxel shapes (its walk patched in third_party/parry3d: PATCH.md), through the world's query as+ /// game code casts it, against testing every solid cell's box: random rays at a turned shape (towards it, from+ /// inside it, anywhere); straight down onto a slab with x, z or both on the lattice's planes or both mid-cell+ /// (4,000 each: unpatched, parry missed 8-22 % of the first three); along a plane between two layers and in the top+ /// face's plane; along the lattice's edges and through its vertices; a shape far out at negative coordinates; a+ /// shape edited. Every hit at the brute-force distance (0.1 mm; 1 mm 500 m out), its normal a unit vector against the ray (none+ /// from inside a cell, as for every shape); every miss a miss.#[test]fn rays_at_voxel_shapes() {use rapier3d::parry::query::RayCast;@@ -2162,58 +2059,152 @@ mod tests {seed ^= seed << 17;(seed >> 40) as f32 / 16_777_216.0};- let cells: Vec<[i32; 3]> = block([-6, -3, -5], [7, 4, 6]).into_iter().filter(|_| rnd() < 0.3).collect();- let voxels = rapier3d::parry::shape::Voxels::new(Vector::splat(0.25), &cells.iter().map(|c| IVector::new(c[0], c[1], c[2])).collect::<Vec<_>>());- let at = pose([0.3, -0.2, 0.1], [0.2, -0.4, 0.1, 0.9]).unwrap();- let (mut hits, mut misses) = (0, 0);- for _ in 0..4000 {- let o = Vector::new(rnd() * 8.0 - 4.0, rnd() * 8.0 - 4.0, rnd() * 8.0 - 4.0);- // (Towards the shape, about the origin, or anywhere.)- let to = Vector::new(rnd() - 0.5, rnd() - 0.5, rnd() - 0.5) * if rnd() < 0.7 { 3.0 } else { 30.0 };- let d = (to - o).normalize();- let ray = Ray::new(o, d);- let max = 1.0 + rnd() * 8.0;- let brute = cells+ // The world with one voxel collider, settled into the broad phase (a step), and the brute force on its cells.+ let world = |size: f32, cells: &[[i32; 3]], at: [f32; 3], rot: [f32; 4]| {+ let mut p = Physics::default();+ let c = p.add_collider(None, &ColliderDesc { position: at, rotation: rot, ..ColliderDesc::new(Shape::Voxels { size, cells: cells.to_vec() }) }).unwrap();+ run(&mut p, 1);+ (p, c)+ };+ let brute = |size: f32, cells: &[[i32; 3]], at: &Pose, ray: &Ray, max: f32| {+ cells.iter().filter_map(|c| {- let centre = at.transform_point(Vector::new(c[0] as f32 + 0.5, c[1] as f32 + 0.5, c[2] as f32 + 0.5) * 0.25);- Cuboid::new(Vector::splat(0.125)).cast_ray(&Pose::from_parts(centre, at.rotation), &ray, max, true)+ let centre = at.transform_point(Vector::new(c[0] as f32 + 0.5, c[1] as f32 + 0.5, c[2] as f32 + 0.5) * size);+ Cuboid::new(Vector::splat(size * 0.5)).cast_ray(&Pose::from_parts(centre, at.rotation), ray, max, true)})- .fold(f32::INFINITY, f32::min);- match voxel_ray(&voxels, &at, &ray, max) {- Some((t, n)) => {- assert!((t - brute).abs() < 1e-4, "{t} for {brute}: from {o:?} along {d:?}");- assert!((n.length() - 1.0).abs() < 1e-4 && (t == 0.0 || n.dot(d) < 1e-4), "{n:?}");- hits += 1;+ .fold(f32::INFINITY, f32::min)+ };+ // (Within 0.1 mm; 1 mm 500 m out, where an f32 is 30 um apart and a ray along an axis it barely moves on divides+ // that.)+ let check = |p: &Physics, want: f32, ray: &Ray, max: f32, what: &str| -> bool {+ let tol = if ray.origin.length() > 100.0 { 1e-3 } else { 1e-4 };+ let o = ray.origin.to_array();+ match p.cast_ray(o, ray.dir.to_array(), max, None).unwrap() {+ Some(h) => {+ let n = Vector::from(h.normal);+ assert!((h.distance - want).abs() < tol, "{what}: {} for {want}: from {o:?} along {:?}", h.distance, ray.dir);+ assert!(if h.distance == 0.0 { n == Vector::ZERO || (n.length() - 1.0).abs() < 1e-4 } else { (n.length() - 1.0).abs() < 1e-4 && n.dot(ray.dir) <= 1e-4 }, "{what}: normal {n:?} from {o:?} along {:?}", ray.dir);+ true}None => {- assert!(brute == f32::INFINITY, "missed a cell at {brute}: from {o:?} along {d:?}");- misses += 1;+ assert!(want == f32::INFINITY, "{what}: missed a cell at {want}: from {o:?} along {:?}", ray.dir);+ false}}+ };+ // Random rays at a turned shape.+ let cells: Vec<[i32; 3]> = block([-6, -3, -5], [7, 4, 6]).into_iter().filter(|_| rnd() < 0.3).collect();+ let (at, rot) = ([0.3, -0.2, 0.1], [0.2, -0.4, 0.1, 0.9]);+ let (p, _) = world(0.25, &cells, at, rot);+ let pose_ = pose(at, rot).unwrap();+ let (mut hits, mut misses) = (0, 0);+ for k in 0..4000 {+ // (From anywhere about it, or from inside one of its cells.)+ let o = if k % 4 == 3 {+ let c = cells[(rnd() * cells.len() as f32) as usize % cells.len()];+ pose_.transform_point(Vector::new(c[0] as f32 + rnd(), c[1] as f32 + rnd(), c[2] as f32 + rnd()) * 0.25)+ } else {+ Vector::new(rnd() * 8.0 - 4.0, rnd() * 8.0 - 4.0, rnd() * 8.0 - 4.0)+ };+ let to = Vector::new(rnd() - 0.5, rnd() - 0.5, rnd() - 0.5) * if rnd() < 0.7 { 3.0 } else { 30.0 };+ let ray = Ray::new(o, (to - o).normalize());+ let max = 1.0 + rnd() * 8.0;+ if check(&p, brute(0.25, &cells, &pose_, &ray, max), &ray, max, "random") {+ hits += 1;+ } else {+ misses += 1;+ }+ }+ assert!(hits > 1500 && misses > 800, "{hits} hits, {misses} misses");+ // Straight down onto a slab of 0.1 m cells (40 x 3 x 40 from the origin's corner at -2 m), the four ways.+ let slab = block([-20, 0, -20], [20, 3, 20]);+ let (p, _) = world(0.1, &slab, [0.0; 3], [0.0, 0.0, 0.0, 1.0]);+ for (way, (xs, zs)) in [("x on a plane", (true, false)), ("x and z on planes", (true, true)), ("z on a plane", (false, true)), ("both mid-cell", (false, false))] {+ for _ in 0..4000 {+ let at = |plane: bool, r: f32| ((r * 38.0) as i32 - 19) as f32 * 0.1 + if plane { 0.0 } else { 0.05 };+ let ray = Ray::new(Vector::new(at(xs, rnd()), 5.0, at(zs, rnd())), Vector::new(0.0, -1.0, 0.0));+ assert!(check(&p, 4.7, &ray, 10.0, way), "{way}: missed");+ }}- assert!(hits > 800 && misses > 800, "{hits} hits, {misses} misses");- // On the lattice's planes, along them: a slab of cells of 0.1 m from above at every corner of its cells.- let slab = rapier3d::parry::shape::Voxels::new(Vector::splat(0.1), &block([-20, 0, -20], [20, 3, 20]).iter().map(|c| IVector::new(c[0], c[1], c[2])).collect::<Vec<_>>());+ // Along planes: between the two upper layers (it belongs to the upper, solid: met at the slab's side); in the+ // top face's plane (above the cells: nothing); along edges (two planes at once); through vertices; on the+ // chunks' faces (every 0.8 m: among the four ways above too) and the shape's own. (The+ // distances here are exact, by hand: brute force on the cells' boxes misses some of these by rounding.)+ let s2 = std::f32::consts::SQRT_2;let still = Pose::identity();- let mut parry_missed = 0;+ for (o, d, want) in [+ ([-5.0, 0.2, 0.05], [1.0, 0.0, 0.0], Some(3.0)),+ ([-5.0, 0.3, 0.05], [1.0, 0.0, 0.0], None),+ ([-5.0, 0.2, 0.3], [1.0, 0.0, 0.0], Some(3.0)),+ ([0.5, 0.1, -5.0], [0.0, 0.0, 1.0], Some(3.0)),+ ([-5.0, 0.3, 0.3], [1.0, 0.0, 0.0], None),+ ([3.0, 0.1, 3.0], [-1.0, 0.0, -1.0], Some(s2)),+ ([-0.7, 1.0, -0.7], [1.0, -1.0, 1.0], Some(0.7 * 3f32.sqrt())),+ ([1.3, 2.3, -0.4], [-0.5, -1.0, 0.0], Some(5f32.sqrt())),+ // On the shape's own faces (its box's, and the collider's in the broad phase): the lower one is its cells',+ // the upper one the empty cells' beyond.+ ([-2.0, 5.0, 0.05], [0.0, -1.0, 0.0], Some(4.7)),+ ([2.0, 5.0, 0.05], [0.0, -1.0, 0.0], None),+ ([0.05, 5.0, -2.0], [0.0, -1.0, 0.0], Some(4.7)),+ ([-2.0, 5.0, -2.0], [0.0, -1.0, 0.0], Some(4.7)),+ ] {+ let ray = Ray::new(Vector::from(o), Vector::from(d).normalize());+ check(&p, want.unwrap_or(f32::INFINITY), &ray, 20.0, "along planes, edges, vertices");+ }+ assert!(p.cast_ray([-5.0, 0.3, 0.05], [1.0, 0.0, 0.0], 20.0, None).unwrap().is_none(), "the top face's plane is above the cells");+ let h = p.cast_ray([-5.0, 0.2, 0.05], [1.0, 0.0, 0.0], 20.0, None).unwrap().unwrap();+ assert!((h.distance - 3.0).abs() < 1e-5 && h.normal == [-1.0, 0.0, 0.0], "{h:?}");+ // From inside a cell: at once, no normal (as every shape answers from inside). Also from a point on one of+ // the lattice's planes inside the slab, along that plane (the cell it floors into is solid; its box, centre+ // +- half a cell, may round off the plane and graze), every plane and direction of a grid of them.+ let h = p.cast_ray([0.05, 0.15, 0.05], [0.0, 1.0, 0.0], 20.0, None).unwrap().unwrap();+ assert!(h.distance == 0.0 && h.normal == [0.0; 3], "{h:?}");for x in -19..19 {- for z in -19..19 {- let ray = Ray::new(Vector::new(x as f32 * 0.1, 5.0, z as f32 * 0.1), Vector::new(0.0, -1.0, 0.0));- let (t, n) = voxel_ray(&slab, &still, &ray, 10.0).unwrap_or_else(|| panic!("a ray down at ({x}, {z}) x 0.1 m misses the slab"));- assert!((t - 4.7).abs() < 1e-4 && n.y == 1.0, "{t} {n:?}");- parry_missed += slab.cast_ray(&still, &ray, 10.0, true).is_none() as u32;+ for (o, d) in [([x as f32 * 0.1, 0.15, 0.05], [0.0, 0.0, 1.0]), ([x as f32 * 0.1, 0.15, 0.05], [0.0, 1.0, 0.0]), ([0.05, 0.1, x as f32 * 0.1], [1.0, 0.0, 0.0]), ([x as f32 * 0.1, 0.2, x as f32 * 0.1 + 0.05], [0.0, 0.0, -1.0])] {+ let h = p.cast_ray(o, d, 20.0, None).unwrap();+ assert!(h.is_some_and(|h| h.distance == 0.0), "from {o:?} along {d:?}, inside the slab: {h:?}");}}- // (Why the walk is here. If parry mends its own, this count falls to 0 and the walk can go.)- assert!(parry_missed > 0, "parry's ray meets them all now");- // Along the top face, in it: nothing above the cells is met; one cell lower the first cell is.- assert!(voxel_ray(&slab, &still, &Ray::new(Vector::new(-5.0, 0.3, 0.05), Vector::new(1.0, 0.0, 0.0)), 20.0).is_none());- let (t, n) = voxel_ray(&slab, &still, &Ray::new(Vector::new(-5.0, 0.2, 0.05), Vector::new(1.0, 0.0, 0.0)), 20.0).unwrap();- assert!((t - 3.0).abs() < 1e-5 && n.x == -1.0);- // From inside a cell: at once, against the ray.- let (t, n) = voxel_ray(&slab, &still, &Ray::new(Vector::new(0.05, 0.15, 0.05), Vector::new(0.0, 1.0, 0.0)), 20.0).unwrap();- assert!(t == 0.0 && n.y == -1.0);+ // Far out at negative coordinates (chunks of negative keys: parry's listing once lost a row there). Straight+ // down on planes or mid-cell: the column the ray's x and z floor into, met at its highest solid cell's top (by+ // this rule, not the cells' boxes: at 500 m a box's centre +- half its size and the plane k x size round apart+ // by an ulp); oblique from anywhere: brute force.+ let far: Vec<[i32; 3]> = block([-5013, -2, -4021], [-4987, 1, -3995]).into_iter().filter(|_| rnd() < 0.6).collect();+ let (p, _) = world(0.1, &far, [0.0; 3], [0.0, 0.0, 0.0, 1.0]);+ for k in 0..2000 {+ if k % 5 == 0 {+ let o = Vector::new(-501.2 + rnd() * 2.4, 3.0, -402.0 + rnd() * 2.4);+ let ray = Ray::new(o, Vector::new(rnd() - 0.5, -1.0, rnd() - 0.5).normalize());+ check(&p, brute(0.1, &far, &still, &ray, 10.0), &ray, 10.0, "far, negative, oblique");+ continue;+ }+ let x = ((-5012.0 + rnd() * 24.0) as i32) as f32 * 0.1 + if k % 2 == 0 { 0.0 } else { 0.05 };+ let z = ((-4020.0 + rnd() * 24.0) as i32) as f32 * 0.1 + if k % 3 == 0 { 0.0 } else { 0.05 };+ let (cx, cz) = ((x / 0.1).floor() as i32, (z / 0.1).floor() as i32);+ let top = far.iter().filter(|c| c[0] == cx && c[2] == cz).map(|c| c[1] + 1).max();+ let ray = Ray::new(Vector::new(x, 3.0, z), Vector::new(0.0, -1.0, 0.0));+ check(&p, top.map_or(f32::INFINITY, |t| 3.0 - t as f32 * 0.1), &ray, 10.0, "far, negative, straight down");+ }+ // Edited: a pit carved and a column added; rays on planes and mid-cell find what is there now (the column+ // their x and z floor into, as above).+ let (mut p, c) = world(0.1, &slab, [0.0; 3], [0.0, 0.0, 0.0, 1.0]);+ let pit = block([-3, 1, -3], [3, 3, 3]);+ let column = block([5, 3, 5], [7, 10, 7]);+ p.edit_voxels(c, &pit, &column).unwrap();+ let now: Vec<[i32; 3]> = slab.iter().filter(|c| !pit.contains(c)).chain(column.iter()).copied().collect();+ for k in 0..2000 {+ let x = ((rnd() * 20.0) as i32 - 10) as f32 * 0.1 + if k % 2 == 0 { 0.0 } else { 0.05 };+ let z = ((rnd() * 20.0) as i32 - 10) as f32 * 0.1 + if k % 3 == 0 { 0.0 } else { 0.05 };+ let (cx, cz) = ((x / 0.1).floor() as i32, (z / 0.1).floor() as i32);+ let top = now.iter().filter(|c| c[0] == cx && c[2] == cz).map(|c| c[1] + 1).max();+ let ray = Ray::new(Vector::new(x, 5.0, z), Vector::new(0.0, -1.0, 0.0));+ check(&p, top.map_or(f32::INFINITY, |t| 5.0 - t as f32 * 0.1), &ray, 10.0, "edited");+ }+ // Parry's own `cast_ray` on the shape gives the same as the world's query (no walk of the world's own).+ let shape = rapier3d::parry::shape::Voxels::new(Vector::splat(0.1), &slab.iter().map(|c| IVector::new(c[0], c[1], c[2])).collect::<Vec<_>>());+ let ray = Ray::new(Vector::new(1.5, 5.0, -0.3), Vector::new(0.0, -1.0, 0.0));+ assert!((shape.cast_ray(&still, &ray, 10.0, true).unwrap() - 4.7).abs() < 1e-5);}/// Colliders that share one voxel shape: its memory is counted once; an edit of one gives that one cells of itsdiff --git a/renderer/third_party/parry3d/Cargo.toml b/renderer/third_party/parry3d/Cargo.tomlnew file mode 100644index 0000000..e2a0795--- /dev/null+++ b/renderer/third_party/parry3d/Cargo.toml@@ -0,0 +1,268 @@+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO+#+# When uploading crates to the registry Cargo will automatically+# "normalize" Cargo.toml files for maximal compatibility+# with all versions of Cargo and also rewrite `path` dependencies+# to registry (e.g., crates.io) dependencies.+#+# If you are reading this file be aware that the original Cargo.toml+# will likely look very different (and much more reasonable).+# See Cargo.toml.orig for the original contents.++[package]+edition = "2021"+name = "parry3d"+version = "0.31.1"+authors = ["Sébastien Crozet <[email protected]>"]+build = false+autolib = false+autobins = false+autoexamples = false+autotests = false+autobenches = false+description = "3 dimensional collision detection library in Rust."+homepage = "https://parry.rs"+documentation = "https://parry.rs/docs"+readme = "README.md"+keywords = [+ "collision",+ "geometry",+ "distance",+ "ray",+ "convex",+]+categories = [+ "science",+ "game-development",+ "mathematics",+ "wasm",+]+license = "Apache-2.0"+repository = "https://github.com/dimforge/parry"++[package.metadata.docs.rs]+rustdoc-args = [+ "-Zunstable-options",+ "--generate-link-to-definition",+]+cargo-args = [+ "-Zunstable-options",+ "-Zrustdoc-scrape-examples",+]+features = ["wavefront"]++[badges.maintenance]+status = "actively-developed"++[features]+alloc = [+ "hashbrown",+ "smallvec",+ "downcast-rs",+ "rstar",+ "glamx/approx",+]+bytemuck-serialize = [+ "bytemuck",+ "glamx/bytemuck",+]+default = [+ "required-features",+ "std",+ "spade",+]+dim3 = []+encase = [+ "dep:encase",+ "glamx/encase",+]+enhanced-determinism = [+ "simba/libm_force",+ "indexmap",+ "glamx/libm",+ "glamx/scalar-math",+]+f32 = []+improved_fixed_point_support = []+parallel = ["rayon"]+required-features = [+ "dim3",+ "f32",+]+rkyv = [+ "dep:rkyv",+ "glamx/rkyv",+]+serde-serialize = [+ "serde",+ "serde_arrays",+ "glamx/serde",+ "bitflags/serde",+ "hashbrown?/serde",+ "spade?/serde",+]+simd8 = []+spade = [+ "dep:spade",+ "alloc",+]+std = [+ "glamx/std",+ "slab",+ "simba/std",+ "arrayvec/std",+ "spade?/std",+ "thiserror/std",+ "ena",+]+wavefront = ["obj"]++[lib]+name = "parry3d"+path = "src/lib.rs"+required-features = ["required-features"]++[dependencies.approx]+version = "0.5"+default-features = false++[dependencies.arrayvec]+version = "0.7"+default-features = false++[dependencies.bitflags]+version = "2.3"++[dependencies.bytemuck]+version = "1"+features = ["derive"]+optional = true++[dependencies.downcast-rs]+version = "2"+features = ["sync"]+optional = true+default-features = false++[dependencies.either]+version = "1"+default-features = false++[dependencies.ena]+version = "0.14.3"+optional = true+default-features = false++[dependencies.encase]+version = "0.12"+optional = true++[dependencies.foldhash]+version = "0.2"+default-features = false++[dependencies.glamx]+version = "0.3"+features = [+ "nostd-libm",+ "i32",+]+default-features = false++[dependencies.hashbrown]+version = "0.17"+features = ["default-hasher"]+optional = true+default-features = false++[dependencies.indexmap]+version = "2"+features = ["serde"]+optional = true++[dependencies.log]+version = "0.4"++[dependencies.num-derive]+version = "0.5"++[dependencies.num-traits]+version = "0.2"+default-features = false++[dependencies.obj]+version = "0.10.2"+optional = true++[dependencies.ordered-float]+version = "5"+default-features = false++[dependencies.rayon]+version = "1"+optional = true++[dependencies.rkyv]+version = "0.8"+features = [+ "bytecheck",+ "alloc",+]+optional = true+default-features = false++[dependencies.rstar]+version = "0.13.0"+optional = true++[dependencies.serde]+version = "1.0"+features = [+ "derive",+ "rc",+]+optional = true++[dependencies.serde_arrays]+version = "0.2"+optional = true++[dependencies.simba]+version = "0.10.1"+features = ["wide"]+default-features = false++[dependencies.slab]+version = "0.4"+optional = true++[dependencies.smallvec]+version = "1"+optional = true++[dependencies.spade]+version = "2.15"+optional = true+default-features = false++[dependencies.static_assertions]+version = "1"++[dependencies.thiserror]+version = "2"+default-features = false++[lints.clippy]+alloc_instead_of_core = "warn"+std_instead_of_alloc = "warn"+std_instead_of_core = "warn"++[lints.rust.unexpected_cfgs]+level = "warn"+priority = 0+check-cfg = [+ 'cfg(feature, values("dim2", "dim3", "f32", "f64"))',+ 'cfg(feature, values("wavefront"))',+ 'cfg(feature, values("encase"))',+ 'cfg(target_arch, values("spirv"))',+]diff --git a/renderer/third_party/parry3d/LICENSE b/renderer/third_party/parry3d/LICENSEnew file mode 100644index 0000000..97f4383--- /dev/null+++ b/renderer/third_party/parry3d/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright 2020 Sébastien Crozet++ 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.diff --git a/renderer/third_party/parry3d/PATCH.md b/renderer/third_party/parry3d/PATCH.mdnew file mode 100644index 0000000..228310a--- /dev/null+++ b/renderer/third_party/parry3d/PATCH.md@@ -0,0 +1,79 @@+# parry3d 0.31.1, patched for ThreeRT++This is parry3d 0.31.1 from crates.io (Apache-2.0: `LICENSE`, taken from the upstream repository, since the crate+does not ship it) with one change, in `src/query/ray/ray_voxels.rs` (`impl RayCast for VoxelsChunkRef`), and a lint+allowed. Only what the crate needs to build is here: its `src`, its `README.md`, and its `Cargo.toml` without the+examples, tests, benches and dev-dependencies (they are not in this copy). `renderer/Cargo.toml`,+`renderer/physics-core/Cargo.toml` and `renderer/web/Cargo.toml` use it through `[patch.crates-io]`.++## Why++A ray cast at a voxel shape misses its cells when it lies on a plane of the lattice and runs along it: straight+down at x = 1.5 m onto cells of 0.1 m, which is where a game asks for the ground (a vehicle's wheels, a character's+feet, a click). Through Rapier's query pipeline, 4,000 rays straight down at a slab missed 320 with x on a plane,+872 with x and z on planes and 600 with z on a plane (0 mid-cell; measured for ThreeRT's vehicle comparison,+2026-11-12).++The walk over a chunk's cells reached the right solid cell, then asked that cell's box for the hit again+(`aabb.cast_local_ray_and_get_normal`). A ray in one of the box's face planes grazes the box: depending on the+rounding of the box's bounds (`voxel_aabb`: centre plus or minus half a cell) it answered none. The walk then went+on to the next cell, left the chunk and reported a miss.++ThreeRT had worked round it with a walk of its own over every voxel collider (`voxel_ray` in physics-core). That+walk is gone with this patch: every ray now goes through Rapier's query.++## What++In `VoxelsChunkRef::cast_local_ray_and_get_normal` (the chunk level, `impl RayCast for Voxels`, is unchanged):++- The ray is clipped to the chunk's box, whose bounds are the lattice planes `key * voxel_size`. The walk keeps the+ axis it entered by.+- A solid cell is a hit where the ray entered it, on the face it crossed:+ - the normal points against the ray along that axis;+ - the feature is `Face(axis)` or `Face(axis + 3)`, as the box reports;+ - on a tie between axes, the lower axis is taken (the box reported `-dir` on an exact edge).+- A ray that starts in a solid cell (the one its origin floors into) is, cast `solid`, a hit at 0 with no normal, as+ every shape answers from inside; the cell's box is not asked (it may round off a plane the origin lies on and+ graze: found by Bugbot on the first draft). Only the hollow cast still asks that box where the ray leaves it.+- The next cell is the one across the nearest lattice plane ahead, computed from the integer key. The walk never+ steps back behind where the ray already is.+- A ray running along the planes of an axis belongs to the cells its coordinate floors into, the same rule as+ `voxel_at_point`. On a plane between two chunks it belongs to the upper one. Both chunks decide this from one+ floor, so exactly one of them takes the ray.++The chunk level needed no change. The `Bvh` tests the chunks' boxes inclusively, so rays in a chunk's face plane+reach both chunks, and the walk above decides which one takes them. The test rays include rays on the chunks' faces+(every 8 cells) and on the shape's own faces.++Also, `src/lib.rs` allows unused imports: as a path dependency, the crate's warnings show.++Not touched: contacts (`VoxelsWithBalls`, the dispatcher), shape casts and point queries. They do not call this+function.++## Checks++- physics-core `rays_at_voxel_shapes`, through the world's query. It compares against testing every solid cell's+ box, or against the floor rule where the boxes' own rounding is the question:+ - random rays at a turned shape, including rays from inside its cells;+ - 4,000 rays straight down each with x on a plane, x and z on planes, z on a plane, and both mid-cell: 0 misses+ (unpatched, the first group already fails);+ - rays along planes, edges and vertices, and on the chunks' and the shape's faces;+ - a shape far out at negative coordinates;+ - an edited shape.+- Against the walk it replaces, over 48,000 rays (four scenes):+ - every answer is the same: distance to six decimals, normal exactly;+ - the only difference is the 2,090 rays that start inside a cell: distance 0 in both, normal zero here against+ `-dir` before.+- Time (one release build on an M-series Mac): 1.1 to 1.7 times the old walk's. A turned shape takes 206-214 ns a+ ray against 184-192; a slab, 281-295 ns against 164-187.+- The recorded hashes (`physics_core::check`, the voxel bodies' script) and `tools/physics-determinism.ts` are+ unchanged.++## Upstream++The report is drafted in `out/upstream/parry-voxel-ray/DRAFT.md` (minimal repro, cause, this patch). It has not+been sent.++**Delete this copy and the three `[patch.crates-io]` lines once a parry release answers rays on lattice planes and+Rapier uses it.** `rays_at_voxel_shapes` (0 misses on the planes, brute force everywhere else) and the recorded+hashes say whether the release behaves the same.diff --git a/renderer/third_party/parry3d/README.md b/renderer/third_party/parry3d/README.mdnew file mode 100644index 0000000..7a8c5e5--- /dev/null+++ b/renderer/third_party/parry3d/README.md@@ -0,0 +1,37 @@+<p align="center">+ <img src="https://parry.rs/img/logo_parry.svg" alt="crates.io" height="200px">+</p>+<p align="center">+ <a href="https://discord.gg/vt9DJSW">+ <img src="https://img.shields.io/discord/507548572338880513.svg?logo=discord&colorB=7289DA">+ </a>+ <a href="https://crates.io/crates/parry2d">+ <img src="https://img.shields.io/crates/v/parry2d.svg?style=flat-square" alt="crates.io">+ </a>+ <a href="https://crates.io/crates/parry3d">+ <img src="https://img.shields.io/crates/v/parry3d.svg?style=flat-square" alt="crates.io">+ </a>+</p>++-----++<p align = "center">+ <strong>+ <a href="http://docs.rs/parry2d">2D Documentation</a> | <a href="http://docs.rs/parry3d">3D Documentation</a> | <a href="http://parry.rs">User Guide</a>+ </strong>+</p>++-----++## What is Parry?++**Parry** is a set 2 and 3-dimensional geometric and collision detection libraries.+These libraries are `parry2d`, `parry3d`, `parry2d-f64`, and `parry3d-f64`. They are written with the Rust+programming language, by the [Dimforge](https://dimforge.com) organization. It is forever free+and open-source! We regularly give updates about our progress on [our blog](https://www.dimforge.com/blog).++## Resources and discussions+- [Dimforge](https://dimforge.com): See all the open-source projects we are working on! Follow our announcements+ on our [blog](https://www.dimforge.com/blog).+- [User guide](https://www.parry.rs/docs/): (WIP) Learn to use Parry in your project by reading the official User Guide.+- [Discord](https://discord.gg/vt9DJSW): Come chat with us, get help, suggest features, on Discord!diff --git a/renderer/third_party/parry3d/src/bounding_volume/aabb.rs b/renderer/third_party/parry3d/src/bounding_volume/aabb.rsnew file mode 100644index 0000000..69231f4--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/aabb.rs@@ -0,0 +1,1031 @@+//! Axis Aligned Bounding Box.++use crate::bounding_volume::{BoundingSphere, BoundingVolume};+use crate::math::{Pose, Real, Vector, VectorExt, DIM, TWO_DIM};+use crate::shape::{Cuboid, SupportMap};+use crate::utils::PoseOps;+use arrayvec::ArrayVec;+use num::Bounded;++use crate::query::{Ray, RayCast};++/// An Axis-Aligned Bounding Box (AABB).+///+/// An AABB is the simplest bounding volume, defined by its minimum and maximum corners.+/// It's called "axis-aligned" because its edges are always parallel to the coordinate axes+/// (X, Y, and Z in 3D), making it very fast to test and compute.+///+/// # Structure+///+/// - **mins**: The point with the smallest coordinates on each axis (bottom-left-back corner)+/// - **maxs**: The point with the largest coordinates on each axis (top-right-front corner)+/// - **Invariant**: `mins.x ≤ maxs.x`, `mins.y ≤ maxs.y` (and `mins.z ≤ maxs.z` in 3D)+///+/// # Properties+///+/// - **Axis-aligned**: Edges always parallel to coordinate axes+/// - **Conservative**: May be larger than the actual shape for rotated objects+/// - **Fast**: Intersection tests are very cheap (just coordinate comparisons)+/// - **Hierarchical**: Perfect for spatial data structures (BVH, quadtree, octree)+///+/// # Use Cases+///+/// AABBs are fundamental to collision detection and are used for:+///+/// - **Broad-phase collision detection**: Quickly eliminate distant object pairs+/// - **Spatial partitioning**: Building BVHs, quadtrees, and octrees+/// - **View frustum culling**: Determining what's visible+/// - **Ray tracing acceleration**: Quickly rejecting non-intersecting rays+/// - **Bounding volume for any shape**: Every shape can compute its AABB+///+/// # Performance+///+/// AABBs are the fastest bounding volume for:+/// - Intersection tests: O(1) with just 6 comparisons (3D)+/// - Merging: O(1) with component-wise min/max+/// - Contains test: O(1) with coordinate comparisons+///+/// # Limitations+///+/// - **Rotation invariance**: Must be recomputed when objects rotate+/// - **Tightness**: May waste space for rotated or complex shapes+/// - **No orientation**: Cannot represent oriented bounding boxes (OBB)+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::math::Vector;+///+/// // Create an AABB for a unit cube centered at origin+/// let mins = Vector::new(-0.5, -0.5, -0.5);+/// let maxs = Vector::new(0.5, 0.5, 0.5);+/// let aabb = Aabb::new(mins, maxs);+///+/// // Check if a point is inside+/// let point = Vector::ZERO;+/// assert!(aabb.contains_local_point(point));+///+/// // Get center and extents+/// assert_eq!(aabb.center(), Vector::ZERO);+/// assert_eq!(aabb.extents().x, 1.0); // Full width+/// assert_eq!(aabb.half_extents().x, 0.5); // Half width+/// # }+/// ```+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::math::Vector;+///+/// // Create from a set of points+/// let points = vec![+/// Vector::new(1.0, 2.0, 3.0),+/// Vector::new(-1.0, 4.0, 2.0),+/// Vector::new(0.0, 0.0, 5.0),+/// ];+/// let aabb = Aabb::from_points(points);+///+/// // The AABB encloses all points+/// assert_eq!(aabb.mins, Vector::new(-1.0, 0.0, 2.0));+/// assert_eq!(aabb.maxs, Vector::new(1.0, 4.0, 5.0));+/// # }+/// ```+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Debug, PartialEq, Copy, Clone)]+#[repr(C)]+pub struct Aabb {+ /// The point with minimum coordinates (bottom-left-back corner).+ ///+ /// Each component (`x`, `y`, `z`) should be less than or equal to the+ /// corresponding component in `maxs`.+ pub mins: Vector,++ /// The point with maximum coordinates (top-right-front corner).+ ///+ /// Each component (`x`, `y`, `z`) should be greater than or equal to the+ /// corresponding component in `mins`.+ pub maxs: Vector,+}++impl Aabb {+ /// The vertex indices of each edge of this `Aabb`.+ ///+ /// This gives, for each edge of this `Aabb`, the indices of its+ /// vertices when taken from the `self.vertices()` array.+ /// Here is how the faces are numbered, assuming+ /// a right-handed coordinate system:+ ///+ /// ```text+ /// y 3 - 2+ /// | 7 − 6 |+ /// ___ x | | 1 (the zero is below 3 and on the left of 1,+ /// / 4 - 5 hidden by the 4-5-6-7 face.)+ /// z+ /// ```+ #[cfg(feature = "dim3")]+ pub const EDGES_VERTEX_IDS: [(usize, usize); 12] = [+ (0, 1),+ (1, 2),+ (3, 2),+ (0, 3),+ (4, 5),+ (5, 6),+ (7, 6),+ (4, 7),+ (0, 4),+ (1, 5),+ (2, 6),+ (3, 7),+ ];++ /// The vertex indices of each face of this `Aabb`.+ ///+ /// This gives, for each face of this `Aabb`, the indices of its+ /// vertices when taken from the `self.vertices()` array.+ /// Here is how the faces are numbered, assuming+ /// a right-handed coordinate system:+ ///+ /// ```text+ /// y 3 - 2+ /// | 7 − 6 |+ /// ___ x | | 1 (the zero is below 3 and on the left of 1,+ /// / 4 - 5 hidden by the 4-5-6-7 face.)+ /// z+ /// ```+ #[cfg(feature = "dim3")]+ pub const FACES_VERTEX_IDS: [(usize, usize, usize, usize); 6] = [+ // Face with normal +X+ (1, 2, 6, 5),+ // Face with normal -X+ (0, 3, 7, 4),+ // Face with normal +Y+ (2, 3, 7, 6),+ // Face with normal -Y+ (1, 0, 4, 5),+ // Face with normal +Z+ (4, 5, 6, 7),+ // Face with normal -Z+ (0, 1, 2, 3),+ ];++ /// The vertex indices of each face of this `Aabb`.+ ///+ /// This gives, for each face of this `Aabb`, the indices of its+ /// vertices when taken from the `self.vertices()` array.+ /// Here is how the faces are numbered, assuming+ /// a right-handed coordinate system:+ ///+ /// ```text+ /// y 3 - 2+ /// | | |+ /// ___ x 0 - 1+ /// ```+ #[cfg(feature = "dim2")]+ pub const FACES_VERTEX_IDS: [(usize, usize); 4] = [+ // Face with normal +X+ (1, 2),+ // Face with normal -X+ (3, 0),+ // Face with normal +Y+ (2, 3),+ // Face with normal -Y+ (0, 1),+ ];++ /// Creates a new AABB from its minimum and maximum corners.+ ///+ /// # Arguments+ ///+ /// * `mins` - The point with the smallest coordinates on each axis+ /// * `maxs` - The point with the largest coordinates on each axis+ ///+ /// # Invariant+ ///+ /// Each component of `mins` should be ≤ the corresponding component of `maxs`.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// // Create a 2x2x2 cube centered at origin+ /// let aabb = Aabb::new(+ /// Vector::new(-1.0, -1.0, -1.0),+ /// Vector::new(1.0, 1.0, 1.0)+ /// );+ ///+ /// assert_eq!(aabb.center(), Vector::ZERO);+ /// assert_eq!(aabb.extents(), Vector::new(2.0, 2.0, 2.0));+ /// # }+ /// ```+ #[inline]+ pub fn new(mins: Vector, maxs: Vector) -> Aabb {+ Aabb { mins, maxs }+ }++ /// Creates an invalid AABB with inverted bounds.+ ///+ /// The resulting AABB has `mins` set to maximum values and `maxs` set to+ /// minimum values. This is useful as an initial value for AABB merging+ /// algorithms (similar to starting a min operation with infinity).+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::{Aabb, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let mut aabb = Aabb::new_invalid();+ ///+ /// // Merge with actual points to build proper AABB+ /// aabb.merge(&Aabb::new(Vector::new(1.0, 2.0, 3.0), Vector::new(1.0, 2.0, 3.0)));+ /// aabb.merge(&Aabb::new(Vector::new(-1.0, 0.0, 2.0), Vector::new(-1.0, 0.0, 2.0)));+ ///+ /// // Now contains the merged bounds+ /// assert_eq!(aabb.mins, Vector::new(-1.0, 0.0, 2.0));+ /// assert_eq!(aabb.maxs, Vector::new(1.0, 2.0, 3.0));+ /// # }+ /// ```+ #[inline]+ pub fn new_invalid() -> Self {+ Self::new(+ Vector::splat(Real::max_value()),+ Vector::splat(-Real::max_value()),+ )+ }++ /// Creates a new AABB from its center and half-extents.+ ///+ /// This is often more intuitive than specifying min and max corners.+ ///+ /// # Arguments+ ///+ /// * `center` - The center point of the AABB+ /// * `half_extents` - Half the dimensions along each axis+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// // Create a 10x6x8 box centered at (5, 0, 0)+ /// let aabb = Aabb::from_half_extents(+ /// Vector::new(5.0, 0.0, 0.0),+ /// Vector::new(5.0, 3.0, 4.0)+ /// );+ ///+ /// assert_eq!(aabb.mins, Vector::new(0.0, -3.0, -4.0));+ /// assert_eq!(aabb.maxs, Vector::new(10.0, 3.0, 4.0));+ /// assert_eq!(aabb.center(), Vector::new(5.0, 0.0, 0.0));+ /// # }+ /// ```+ #[inline]+ pub fn from_half_extents(center: Vector, half_extents: Vector) -> Self {+ Self::new(center - half_extents, center + half_extents)+ }++ /// Creates a new AABB that tightly encloses a set of points (references).+ ///+ /// Computes the minimum and maximum coordinates across all points.+ ///+ /// # Arguments+ ///+ /// * `pts` - An iterator over point references+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let points = vec![+ /// Vector::new(1.0, 2.0, 3.0),+ /// Vector::new(-1.0, 4.0, 2.0),+ /// Vector::new(0.0, 0.0, 5.0),+ /// ];+ ///+ /// let aabb = Aabb::from_points_ref(&points);+ /// assert_eq!(aabb.mins, Vector::new(-1.0, 0.0, 2.0));+ /// assert_eq!(aabb.maxs, Vector::new(1.0, 4.0, 5.0));+ /// # }+ /// ```+ pub fn from_points_ref<'a, I>(pts: I) -> Self+ where+ I: IntoIterator<Item = &'a Vector>,+ {+ super::aabb_utils::local_point_cloud_aabb(pts.into_iter().copied())+ }++ /// Creates a new AABB that tightly encloses a set of points (values).+ ///+ /// Computes the minimum and maximum coordinates across all points.+ ///+ /// # Arguments+ ///+ /// * `pts` - An iterator over point values+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabb = Aabb::from_points(vec![+ /// Vector::new(1.0, 2.0, 3.0),+ /// Vector::new(-1.0, 4.0, 2.0),+ /// Vector::new(0.0, 0.0, 5.0),+ /// ]);+ ///+ /// assert_eq!(aabb.mins, Vector::new(-1.0, 0.0, 2.0));+ /// assert_eq!(aabb.maxs, Vector::new(1.0, 4.0, 5.0));+ /// # }+ /// ```+ pub fn from_points<I>(pts: I) -> Self+ where+ I: IntoIterator<Item = Vector>,+ {+ super::aabb_utils::local_point_cloud_aabb(pts)+ }++ /// Returns the center point of this AABB.+ ///+ /// The center is the midpoint between `mins` and `maxs`.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabb = Aabb::new(+ /// Vector::new(-2.0, -3.0, -4.0),+ /// Vector::new(2.0, 3.0, 4.0)+ /// );+ ///+ /// assert_eq!(aabb.center(), Vector::ZERO);+ /// # }+ /// ```+ #[inline]+ pub fn center(&self) -> Vector {+ self.mins.midpoint(self.maxs)+ }++ /// Returns the half-extents of this AABB.+ ///+ /// Half-extents are half the dimensions along each axis.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabb = Aabb::new(+ /// Vector::new(-5.0, -3.0, -2.0),+ /// Vector::new(5.0, 3.0, 2.0)+ /// );+ ///+ /// let half = aabb.half_extents();+ /// assert_eq!(half, Vector::new(5.0, 3.0, 2.0));+ ///+ /// // Full dimensions are 2 * half_extents+ /// let full = aabb.extents();+ /// assert_eq!(full, Vector::new(10.0, 6.0, 4.0));+ /// # }+ /// ```+ #[inline]+ pub fn half_extents(&self) -> Vector {+ let half: Real = 0.5;+ (self.maxs - self.mins) * half+ }++ /// Returns the volume of this AABB.+ ///+ /// - **2D**: Returns the area (width × height)+ /// - **3D**: Returns the volume (width × height × depth)+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// // A 2x3x4 box+ /// let aabb = Aabb::new(+ /// Vector::ZERO,+ /// Vector::new(2.0, 3.0, 4.0)+ /// );+ ///+ /// assert_eq!(aabb.volume(), 24.0); // 2 * 3 * 4+ /// # }+ /// ```+ #[inline]+ pub fn volume(&self) -> Real {+ let extents = self.extents();+ #[cfg(feature = "dim2")]+ return extents.x * extents.y;+ #[cfg(feature = "dim3")]+ return extents.x * extents.y * extents.z;+ }++ /// In 3D, returns the half-area. In 2D returns the half-perimeter of the AABB.+ pub fn half_area_or_perimeter(&self) -> Real {+ #[cfg(feature = "dim2")]+ return self.half_perimeter();+ #[cfg(feature = "dim3")]+ return self.half_area();+ }++ /// The half perimeter of this `Aabb`.+ #[cfg(feature = "dim2")]+ pub fn half_perimeter(&self) -> Real {+ let extents = self.extents();+ extents.x + extents.y+ }++ /// The half area of this `Aabb`.+ #[cfg(feature = "dim3")]+ pub fn half_area(&self) -> Real {+ let extents = self.extents();+ extents.x * (extents.y + extents.z) + extents.y * extents.z+ }++ /// The extents of this `Aabb`.+ #[inline]+ pub fn extents(&self) -> Vector {+ self.maxs - self.mins+ }++ /// Enlarges this `Aabb` so it also contains the point `pt`.+ pub fn take_point(&mut self, pt: Vector) {+ self.mins = self.mins.min(pt);+ self.maxs = self.maxs.max(pt);+ }++ /// Computes the `Aabb` bounding `self` transformed by `m`.+ #[inline]+ pub fn transform_by(&self, m: &Pose) -> Self {+ let ls_center = self.center();+ let center = m * ls_center;+ let ws_half_extents = m.absolute_transform_vector(self.half_extents());++ Aabb::new(center + (-ws_half_extents), center + ws_half_extents)+ }++ /// Computes the Aabb bounding `self` translated by `translation`.+ #[inline]+ pub fn translated(mut self, translation: Vector) -> Self {+ self.mins += translation;+ self.maxs += translation;+ self+ }++ #[inline]+ pub fn scaled(self, scale: Vector) -> Self {+ let a = self.mins * scale;+ let b = self.maxs * scale;+ Self {+ mins: a.min(b),+ maxs: a.max(b),+ }+ }++ /// Returns an AABB with the same center as `self` but with extents scaled by `scale`.+ ///+ /// # Parameters+ /// - `scale`: the scaling factor. It can be non-uniform and/or negative. The AABB being+ /// symmetric wrt. its center, a negative scale value has the same effect as scaling+ /// by its absolute value.+ #[inline]+ #[must_use]+ pub fn scaled_wrt_center(self, scale: Vector) -> Self {+ let center = self.center();+ // Multiply the extents by the scale. Negative scaling might modify the half-extent+ // sign, so we take the absolute value. The AABB being symmetric that absolute value+ // is valid.+ let half_extents = self.half_extents() * scale.abs();+ Self::from_half_extents(center, half_extents)+ }++ /// The smallest bounding sphere containing this `Aabb`.+ #[inline]+ pub fn bounding_sphere(&self) -> BoundingSphere {+ let center = self.center();+ let radius = self.mins.distance(self.maxs) * 0.5;+ BoundingSphere::new(center, radius)+ }++ /// Does this AABB contains a point expressed in the same coordinate frame as `self`?+ #[inline]+ pub fn contains_local_point(&self, point: Vector) -> bool {+ for i in 0..DIM {+ if point.vget(i) < self.mins.vget(i) || point.vget(i) > self.maxs.vget(i) {+ return false;+ }+ }++ true+ }++ /// Computes the distance between the origin and this AABB.+ pub fn distance_to_origin(&self) -> Real {+ self.mins.max(-self.maxs).max(Vector::ZERO).length()+ }++ /// Does this AABB intersects an AABB `aabb2` moving at velocity `vel12` relative to `self`?+ #[inline]+ pub fn intersects_moving_aabb(&self, aabb2: &Self, vel12: Vector) -> bool {+ // Minkowski sum.+ let msum = Aabb {+ mins: self.mins - aabb2.maxs,+ maxs: self.maxs - aabb2.mins,+ };+ let ray = Ray::new(Vector::ZERO, vel12);++ msum.intersects_local_ray(&ray, 1.0)+ }++ /// Computes the intersection of this `Aabb` and another one.+ pub fn intersection(&self, other: &Aabb) -> Option<Aabb> {+ let result = Aabb {+ mins: self.mins.max(other.mins),+ maxs: self.maxs.min(other.maxs),+ };++ for i in 0..DIM {+ if result.mins.vget(i) > result.maxs.vget(i) {+ return None;+ }+ }++ Some(result)+ }++ /// Computes two AABBs for the intersection between two translated and rotated AABBs.+ ///+ /// This method returns two AABBs: the first is expressed in the local-space of `self`,+ /// and the second is expressed in the local-space of `aabb2`.+ pub fn aligned_intersections(&self, pos12: &Pose, aabb2: &Self) -> Option<(Aabb, Aabb)> {+ let pos21 = pos12.inverse();++ let aabb2_1 = aabb2.transform_by(pos12);+ let inter1_1 = self.intersection(&aabb2_1)?;+ let inter1_2 = inter1_1.transform_by(&pos21);++ let aabb1_2 = self.transform_by(&pos21);+ let inter2_2 = aabb2.intersection(&aabb1_2)?;+ let inter2_1 = inter2_2.transform_by(pos12);++ Some((+ inter1_1.intersection(&inter2_1)?,+ inter1_2.intersection(&inter2_2)?,+ ))+ }++ /// Returns the difference between this `Aabb` and `rhs`.+ ///+ /// Removing another `Aabb` from `self` will result in zero, one, or up to 4 (in 2D) or 8 (in 3D)+ /// new smaller Aabbs.+ pub fn difference(&self, rhs: &Aabb) -> ArrayVec<Self, TWO_DIM> {+ self.difference_with_cut_sequence(rhs).0+ }++ /// Returns the difference between this `Aabb` and `rhs`.+ ///+ /// Removing another `Aabb` from `self` will result in zero, one, or up to 4 (in 2D) or 8 (in 3D)+ /// new smaller Aabbs.+ ///+ /// # Return+ /// This returns a pair where the first item are the new Aabbs and the second item is+ /// the sequence of cuts applied to `self` to obtain the new Aabbs. Each cut is performed+ /// along one axis identified by `-1, -2, -3` for `-X, -Y, -Z` and `1, 2, 3` for `+X, +Y, +Z`, and+ /// the plane’s bias.+ ///+ /// The cuts are applied sequentially. For example, if `result.1[0]` contains `1`, then it means+ /// that `result.0[0]` is equal to the piece of `self` lying in the negative half-space delimited+ /// by the plane with outward normal `+X`. Then, the other piece of `self` generated by this cut+ /// (i.e. the piece of `self` lying in the positive half-space delimited by the plane with outward+ /// normal `+X`) is the one that will be affected by the next cut.+ ///+ /// The returned cut sequence will be empty if the aabbs are disjoint.+ pub fn difference_with_cut_sequence(+ &self,+ rhs: &Aabb,+ ) -> (ArrayVec<Self, TWO_DIM>, ArrayVec<(i8, Real), TWO_DIM>) {+ let mut result = ArrayVec::new();+ let mut cut_sequence = ArrayVec::new();++ // NOTE: special case when the boxes are disjoint.+ // This isn’t exactly the same as `!self.intersects(rhs)`+ // because of the equality.+ for i in 0..DIM {+ if self.mins.vget(i) >= rhs.maxs.vget(i) || self.maxs.vget(i) <= rhs.mins.vget(i) {+ result.push(*self);+ return (result, cut_sequence);+ }+ }++ let mut rest = *self;++ for i in 0..DIM {+ if rhs.mins.vget(i) > rest.mins.vget(i) {+ let mut fragment = rest;+ fragment.maxs.vset(i, rhs.mins.vget(i));+ rest.mins.vset(i, rhs.mins.vget(i));+ result.push(fragment);+ cut_sequence.push((i as i8 + 1, rhs.mins.vget(i)));+ }++ if rhs.maxs.vget(i) < rest.maxs.vget(i) {+ let mut fragment = rest;+ fragment.mins.vset(i, rhs.maxs.vget(i));+ rest.maxs.vset(i, rhs.maxs.vget(i));+ result.push(fragment);+ cut_sequence.push((-(i as i8 + 1), -rhs.maxs.vget(i)));+ }+ }++ (result, cut_sequence)+ }++ /// Computes the vertices of this `Aabb`.+ ///+ /// The vertices are given in the following order in a right-handed coordinate system:+ /// ```text+ /// y 3 - 2+ /// | | |+ /// ___ x 0 - 1+ /// ```+ #[inline]+ #[cfg(feature = "dim2")]+ pub fn vertices(&self) -> [Vector; 4] {+ [+ Vector::new(self.mins.x, self.mins.y),+ Vector::new(self.maxs.x, self.mins.y),+ Vector::new(self.maxs.x, self.maxs.y),+ Vector::new(self.mins.x, self.maxs.y),+ ]+ }++ /// Computes the vertices of this `Aabb`.+ ///+ /// The vertices are given in the following order, in a right-handed coordinate system:+ /// ```text+ /// y 3 - 2+ /// | 7 − 6 |+ /// ___ x | | 1 (the zero is below 3 and on the left of 1,+ /// / 4 - 5 hidden by the 4-5-6-7 face.)+ /// z+ /// ```+ #[inline]+ #[cfg(feature = "dim3")]+ pub fn vertices(&self) -> [Vector; 8] {+ [+ Vector::new(self.mins.x, self.mins.y, self.mins.z),+ Vector::new(self.maxs.x, self.mins.y, self.mins.z),+ Vector::new(self.maxs.x, self.maxs.y, self.mins.z),+ Vector::new(self.mins.x, self.maxs.y, self.mins.z),+ Vector::new(self.mins.x, self.mins.y, self.maxs.z),+ Vector::new(self.maxs.x, self.mins.y, self.maxs.z),+ Vector::new(self.maxs.x, self.maxs.y, self.maxs.z),+ Vector::new(self.mins.x, self.maxs.y, self.maxs.z),+ ]+ }++ /// Splits this `Aabb` at its center, into four parts (as in a quad-tree).+ #[inline]+ #[cfg(feature = "dim2")]+ pub fn split_at_center(&self) -> [Aabb; 4] {+ let center = self.center();++ [+ Aabb::new(self.mins, center),+ Aabb::new(+ Vector::new(center.x, self.mins.y),+ Vector::new(self.maxs.x, center.y),+ ),+ Aabb::new(center, self.maxs),+ Aabb::new(+ Vector::new(self.mins.x, center.y),+ Vector::new(center.x, self.maxs.y),+ ),+ ]+ }++ /// Splits this `Aabb` at its center, into eight parts (as in an octree).+ #[inline]+ #[cfg(feature = "dim3")]+ pub fn split_at_center(&self) -> [Aabb; 8] {+ let center = self.center();++ [+ Aabb::new(+ Vector::new(self.mins.x, self.mins.y, self.mins.z),+ Vector::new(center.x, center.y, center.z),+ ),+ Aabb::new(+ Vector::new(center.x, self.mins.y, self.mins.z),+ Vector::new(self.maxs.x, center.y, center.z),+ ),+ Aabb::new(+ Vector::new(center.x, center.y, self.mins.z),+ Vector::new(self.maxs.x, self.maxs.y, center.z),+ ),+ Aabb::new(+ Vector::new(self.mins.x, center.y, self.mins.z),+ Vector::new(center.x, self.maxs.y, center.z),+ ),+ Aabb::new(+ Vector::new(self.mins.x, self.mins.y, center.z),+ Vector::new(center.x, center.y, self.maxs.z),+ ),+ Aabb::new(+ Vector::new(center.x, self.mins.y, center.z),+ Vector::new(self.maxs.x, center.y, self.maxs.z),+ ),+ Aabb::new(+ Vector::new(center.x, center.y, center.z),+ Vector::new(self.maxs.x, self.maxs.y, self.maxs.z),+ ),+ Aabb::new(+ Vector::new(self.mins.x, center.y, center.z),+ Vector::new(center.x, self.maxs.y, self.maxs.z),+ ),+ ]+ }++ /// Enlarges this AABB on each side by the given `half_extents`.+ #[must_use]+ pub fn add_half_extents(&self, half_extents: Vector) -> Self {+ Self {+ mins: self.mins - half_extents,+ maxs: self.maxs + half_extents,+ }+ }++ /// Projects every point of `Aabb` on an arbitrary axis.+ pub fn project_on_axis(&self, axis: Vector) -> (Real, Real) {+ let cuboid = Cuboid::new(self.half_extents());+ let shift = cuboid.local_support_point_toward(axis).dot(axis).abs();+ let center = self.center().dot(axis);+ (center - shift, center + shift)+ }++ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ pub fn intersects_spiral(+ &self,+ point: Vector,+ spiral_center: Vector,+ axis: Vector,+ linvel: Vector,+ angvel: Real,+ ) -> bool {+ use crate::math::{Matrix2, Vector2};+ use crate::utils::WBasis;+ use crate::utils::{Interval, IntervalFunction};+ use alloc::vec;++ struct SpiralPlaneDistance {+ spiral_center: Vector,+ tangents: [Vector; 2],+ linvel: Vector,+ angvel: Real,+ point: Vector2,+ plane: Vector,+ bias: Real,+ }++ impl SpiralPlaneDistance {+ fn spiral_pt_at(&self, t: Real) -> Vector {+ let angle = t * self.angvel;++ // NOTE: we construct the rotation matrix explicitly here instead+ // of using `Rotation2::new()` because we will use similar+ // formulas on the interval methods.+ let (sin, cos) = <Real as simba::scalar::ComplexField>::sin_cos(angle);+ // Mat2 in column-major: first column is [cos, sin], second is [-sin, cos]+ let rotmat = Matrix2::from_cols(Vector2::new(cos, sin), Vector2::new(-sin, cos));++ let rotated_pt = rotmat * self.point;+ let shift = self.tangents[0] * rotated_pt.x + self.tangents[1] * rotated_pt.y;+ self.spiral_center + self.linvel * t + shift+ }+ }++ impl IntervalFunction<Real> for SpiralPlaneDistance {+ fn eval(&self, t: Real) -> Real {+ let point_pos = self.spiral_pt_at(t);+ point_pos.dot(self.plane) - self.bias+ }++ fn eval_interval(&self, t: Interval<Real>) -> Interval<Real> {+ // This is the same as `self.eval` except that `t` is an interval.+ let angle = t * self.angvel;+ let (sin, cos) = angle.sin_cos();++ // Compute rotated point manually with interval arithmetic+ let rotated_pt_x =+ cos * Interval::splat(self.point.x) - sin * Interval::splat(self.point.y);+ let rotated_pt_y =+ sin * Interval::splat(self.point.x) + cos * Interval::splat(self.point.y);++ let shift_x = Interval::splat(self.tangents[0].x) * rotated_pt_x+ + Interval::splat(self.tangents[1].x) * rotated_pt_y;+ let shift_y = Interval::splat(self.tangents[0].y) * rotated_pt_x+ + Interval::splat(self.tangents[1].y) * rotated_pt_y;+ let shift_z = Interval::splat(self.tangents[0].z) * rotated_pt_x+ + Interval::splat(self.tangents[1].z) * rotated_pt_y;++ let point_pos_x = Interval::splat(self.spiral_center.x)+ + Interval::splat(self.linvel.x) * t+ + shift_x;+ let point_pos_y = Interval::splat(self.spiral_center.y)+ + Interval::splat(self.linvel.y) * t+ + shift_y;+ let point_pos_z = Interval::splat(self.spiral_center.z)+ + Interval::splat(self.linvel.z) * t+ + shift_z;++ point_pos_x * Interval::splat(self.plane.x)+ + point_pos_y * Interval::splat(self.plane.y)+ + point_pos_z * Interval::splat(self.plane.z)+ - Interval::splat(self.bias)+ }++ fn eval_interval_gradient(&self, t: Interval<Real>) -> Interval<Real> {+ let angle = t * self.angvel;+ let (sin, cos) = angle.sin_cos();+ let angvel_interval = Interval::splat(self.angvel);++ // Derivative of rotation matrix applied to point+ let rotated_pt_x = (-sin * angvel_interval) * Interval::splat(self.point.x)+ - (cos * angvel_interval) * Interval::splat(self.point.y);+ let rotated_pt_y = (cos * angvel_interval) * Interval::splat(self.point.x)+ + (-sin * angvel_interval) * Interval::splat(self.point.y);++ let shift_x = Interval::splat(self.tangents[0].x) * rotated_pt_x+ + Interval::splat(self.tangents[1].x) * rotated_pt_y;+ let shift_y = Interval::splat(self.tangents[0].y) * rotated_pt_x+ + Interval::splat(self.tangents[1].y) * rotated_pt_y;+ let shift_z = Interval::splat(self.tangents[0].z) * rotated_pt_x+ + Interval::splat(self.tangents[1].z) * rotated_pt_y;++ let point_vel_x = shift_x + Interval::splat(self.linvel.x);+ let point_vel_y = shift_y + Interval::splat(self.linvel.y);+ let point_vel_z = shift_z + Interval::splat(self.linvel.z);++ point_vel_x * Interval::splat(self.plane.x)+ + point_vel_y * Interval::splat(self.plane.y)+ + point_vel_z * Interval::splat(self.plane.z)+ }+ }++ let tangents = axis.orthonormal_basis();+ let dpos = point - spiral_center;+ #[cfg(feature = "f32")]+ let spiral_point = glamx::Vec2::new(dpos.dot(tangents[0]), dpos.dot(tangents[1]));+ #[cfg(feature = "f64")]+ let spiral_point = glamx::DVec2::new(dpos.dot(tangents[0]), dpos.dot(tangents[1]));+ let mut distance_fn = SpiralPlaneDistance {+ spiral_center,+ tangents,+ linvel,+ angvel,+ point: spiral_point,+ plane: Vector::X,+ bias: 0.0,+ };++ // Check the 8 planar faces of the Aabb.+ let mut roots = vec![];+ let mut candidates = vec![];++ let planes = [+ (-self.mins.x, -Vector::X, 0),+ (self.maxs.x, Vector::X, 0),+ (-self.mins.y, -Vector::Y, 1),+ (self.maxs.y, Vector::Y, 1),+ (-self.mins.z, -Vector::Z, 2),+ (self.maxs.z, Vector::Z, 2),+ ];++ let range = self.project_on_axis(axis);+ let range_bias = spiral_center.dot(axis);+ let interval = Interval::sort(range.0, range.1) - range_bias;++ for (bias, axis, i) in &planes {+ distance_fn.plane = *axis;+ distance_fn.bias = *bias;++ crate::utils::find_root_intervals_to(+ &distance_fn,+ interval,+ 1.0e-5,+ 1.0e-5,+ 100,+ &mut roots,+ &mut candidates,+ );++ for root in roots.drain(..) {+ let point = distance_fn.spiral_pt_at(root.midpoint());+ let (j, k) = ((i + 1) % 3, (i + 2) % 3);+ if point.vget(j) >= self.mins.vget(j)+ && point.vget(j) <= self.maxs.vget(j)+ && point.vget(k) >= self.mins.vget(k)+ && point.vget(k) <= self.maxs.vget(k)+ {+ return true;+ }+ }+ }++ false+ }+}++impl BoundingVolume for Aabb {+ #[inline]+ fn center(&self) -> Vector {+ self.center()+ }++ #[inline]+ fn intersects(&self, other: &Aabb) -> bool {+ (self.mins.cmple(other.maxs) & self.maxs.cmpge(other.mins)).all()+ }++ #[inline]+ fn contains(&self, other: &Aabb) -> bool {+ (self.mins.cmple(other.mins) & self.maxs.cmpge(other.maxs)).all()+ }++ #[inline]+ fn merge(&mut self, other: &Aabb) {+ self.mins = self.mins.min(other.mins);+ self.maxs = self.maxs.max(other.maxs);+ }++ #[inline]+ fn merged(&self, other: &Aabb) -> Aabb {+ Aabb {+ mins: self.mins.min(other.mins),+ maxs: self.maxs.max(other.maxs),+ }+ }++ #[inline]+ fn loosen(&mut self, amount: Real) {+ assert!(amount >= 0.0, "The loosening margin must be non-negative.");+ self.mins += Vector::splat(-amount);+ self.maxs += Vector::splat(amount);+ }++ #[inline]+ fn loosened(&self, amount: Real) -> Aabb {+ assert!(amount >= 0.0, "The loosening margin must be non-negative.");+ Aabb {+ mins: self.mins + Vector::splat(-amount),+ maxs: self.maxs + Vector::splat(amount),+ }+ }++ #[inline]+ fn tighten(&mut self, amount: Real) {+ assert!(amount >= 0.0, "The tightening margin must be non-negative.");+ self.mins += Vector::splat(amount);+ self.maxs += Vector::splat(-amount);+ assert!(+ self.mins.cmple(self.maxs).all(),+ "The tightening margin is to large."+ );+ }++ #[inline]+ fn tightened(&self, amount: Real) -> Aabb {+ assert!(amount >= 0.0, "The tightening margin must be non-negative.");++ Aabb::new(+ self.mins + Vector::splat(amount),+ self.maxs + Vector::splat(-amount),+ )+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/aabb_ball.rs b/renderer/third_party/parry3d/src/bounding_volume/aabb_ball.rsnew file mode 100644index 0000000..c06aada--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/aabb_ball.rs@@ -0,0 +1,34 @@+use crate::bounding_volume::Aabb;+use crate::math::{Pose, Real, Vector};+use crate::shape::Ball;++/// Computes the Axis-Aligned Bounding Box of a ball transformed by `center`.+#[inline]+pub fn ball_aabb(center: Vector, radius: Real) -> Aabb {+ Aabb::new(+ center + Vector::splat(-radius),+ center + Vector::splat(radius),+ )+}++/// Computes the Axis-Aligned Bounding Box of a ball.+#[inline]+pub fn local_ball_aabb(radius: Real) -> Aabb {+ let half_extents = Vector::splat(radius);++ Aabb::new(-half_extents, half_extents)+}++impl Ball {+ /// Computes the world-space [`Aabb`] of this ball transformed by `pos`.+ #[inline]+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ ball_aabb(pos.translation, self.radius)+ }++ /// Computes the local-space [`Aabb`] of this ball.+ #[inline]+ pub fn local_aabb(&self) -> Aabb {+ local_ball_aabb(self.radius)+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/aabb_capsule.rs b/renderer/third_party/parry3d/src/bounding_volume/aabb_capsule.rsnew file mode 100644index 0000000..ed68b61--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/aabb_capsule.rs@@ -0,0 +1,21 @@+use crate::bounding_volume::Aabb;+use crate::math::{Pose, Vector};+use crate::shape::Capsule;++impl Capsule {+ /// The axis-aligned bounding box of this capsule.+ #[inline]+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ self.transform_by(pos).local_aabb()+ }++ /// The axis-aligned bounding box of this capsule.+ #[inline]+ pub fn local_aabb(&self) -> Aabb {+ let a = self.segment.a;+ let b = self.segment.b;+ let mins = a.min(b) - Vector::splat(self.radius);+ let maxs = a.max(b) + Vector::splat(self.radius);+ Aabb::new(mins, maxs)+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/aabb_convex_polygon.rs b/renderer/third_party/parry3d/src/bounding_volume/aabb_convex_polygon.rsnew file mode 100644index 0000000..8021a76--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/aabb_convex_polygon.rs@@ -0,0 +1,17 @@+use crate::bounding_volume::Aabb;+use crate::math::Pose;+use crate::shape::ConvexPolygon;++impl ConvexPolygon {+ /// Computes the world-space [`Aabb`] of this convex polygon, transformed by `pos`.+ #[inline]+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ super::details::point_cloud_aabb_ref(pos, self.points())+ }++ /// Computes the local-space [`Aabb`] of this convex polygon.+ #[inline]+ pub fn local_aabb(&self) -> Aabb {+ super::details::local_point_cloud_aabb_ref(self.points())+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/aabb_convex_polyhedron.rs b/renderer/third_party/parry3d/src/bounding_volume/aabb_convex_polyhedron.rsnew file mode 100644index 0000000..aafa893--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/aabb_convex_polyhedron.rs@@ -0,0 +1,17 @@+use crate::bounding_volume::Aabb;+use crate::math::Pose;+use crate::shape::ConvexPolyhedron;++impl ConvexPolyhedron {+ /// Computes the world-space [`Aabb`] of this convex polyhedron, transformed by `pos`.+ #[inline]+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ super::details::point_cloud_aabb_ref(pos, self.points())+ }++ /// Computes the local-space [`Aabb`] of this convex polyhedron.+ #[inline]+ pub fn local_aabb(&self) -> Aabb {+ super::details::local_point_cloud_aabb_ref(self.points())+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/aabb_cuboid.rs b/renderer/third_party/parry3d/src/bounding_volume/aabb_cuboid.rsnew file mode 100644index 0000000..aea1096--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/aabb_cuboid.rs@@ -0,0 +1,21 @@+use crate::bounding_volume::Aabb;+use crate::math::Pose;+use crate::shape::Cuboid;+use crate::utils::PoseOps;++impl Cuboid {+ /// Computes the world-space [`Aabb`] of this cuboid, transformed by `pos`.+ #[inline]+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ let center = pos.translation;+ let ws_half_extents = pos.absolute_transform_vector(self.half_extents);++ Aabb::from_half_extents(center, ws_half_extents)+ }++ /// Computes the local-space [`Aabb`] of this cuboid.+ #[inline]+ pub fn local_aabb(&self) -> Aabb {+ Aabb::new(-self.half_extents, self.half_extents)+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/aabb_halfspace.rs b/renderer/third_party/parry3d/src/bounding_volume/aabb_halfspace.rsnew file mode 100644index 0000000..43434ee--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/aabb_halfspace.rs@@ -0,0 +1,20 @@+use crate::bounding_volume::Aabb;+use crate::math::{Pose, Vector};+use crate::shape::HalfSpace;++impl HalfSpace {+ /// Computes the world-space [`Aabb`] of this half-space.+ #[inline]+ pub fn aabb(&self, _pos: &Pose) -> Aabb {+ self.local_aabb()+ }++ /// Computes the local-space [`Aabb`] of this half-space.+ #[inline]+ pub fn local_aabb(&self) -> Aabb {+ // We divide by 2.0 so that we can still make some operations with it (like loosening)+ // without breaking the box.+ let max = Vector::MAX * 0.5;+ Aabb::new(-max, max)+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/aabb_heightfield.rs b/renderer/third_party/parry3d/src/bounding_volume/aabb_heightfield.rsnew file mode 100644index 0000000..0baf8e6--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/aabb_heightfield.rs@@ -0,0 +1,17 @@+use crate::bounding_volume::Aabb;+use crate::math::Pose;+use crate::shape::HeightField;++impl HeightField {+ /// Computes the world-space [`Aabb`] of this heightfield, transformed by `pos`.+ #[inline]+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ self.root_aabb().transform_by(pos)+ }++ /// Computes the local-space [`Aabb`] of this heightfield.+ #[inline]+ pub fn local_aabb(&self) -> Aabb {+ *self.root_aabb()+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/aabb_support_map.rs b/renderer/third_party/parry3d/src/bounding_volume/aabb_support_map.rsnew file mode 100644index 0000000..0af1e2a--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/aabb_support_map.rs@@ -0,0 +1,50 @@+use crate::bounding_volume;+use crate::bounding_volume::Aabb;+use crate::math::Pose;+use crate::shape::Segment;+#[cfg(feature = "dim3")]+use crate::shape::{Cone, Cylinder};++#[cfg(feature = "dim3")]+impl Cone {+ /// Computes the world-space [`Aabb`] of this cone, transformed by `pos`.+ #[inline]+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ bounding_volume::details::support_map_aabb(pos, self)+ }++ /// Computes the local-space [`Aabb`] of this cone.+ #[inline]+ pub fn local_aabb(&self) -> Aabb {+ bounding_volume::details::local_support_map_aabb(self)+ }+}++#[cfg(feature = "dim3")]+impl Cylinder {+ /// Computes the world-space [`Aabb`] of this cylinder, transformed by `pos`.+ #[inline]+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ bounding_volume::details::support_map_aabb(pos, self)+ }++ /// Computes the local-space [`Aabb`] of this cylinder.+ #[inline]+ pub fn local_aabb(&self) -> Aabb {+ bounding_volume::details::local_support_map_aabb(self)+ }+}++impl Segment {+ /// Computes the world-space [`Aabb`] of this segment, transformed by `pos`.+ #[inline]+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ self.transformed(pos).local_aabb()+ }++ /// Computes the local-space [`Aabb`] of this segment.+ #[inline]+ pub fn local_aabb(&self) -> Aabb {+ bounding_volume::details::local_support_map_aabb(self)+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/aabb_triangle.rs b/renderer/third_party/parry3d/src/bounding_volume/aabb_triangle.rsnew file mode 100644index 0000000..59ca41c--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/aabb_triangle.rs@@ -0,0 +1,61 @@+use crate::{+ bounding_volume::Aabb,+ math::{Pose, Vector},+ shape::Triangle,+};++impl Triangle {+ /// Computes the world-space [`Aabb`] of this triangle, transformed by `pos`.+ #[inline]+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ self.transformed(pos).local_aabb()+ }++ /// Computes the local-space [`Aabb`] of this triangle.+ #[inline]+ pub fn local_aabb(&self) -> Aabb {+ let a = self.a;+ let b = self.b;+ let c = self.c;++ let mut min = Vector::ZERO;+ let mut max = Vector::ZERO;++ for_each_dim! {+ min[ii] = a[ii].min(b[ii]).min(c[ii]);+ max[ii] = a[ii].max(b[ii]).max(c[ii]);+ }++ Aabb::new(min, max)+ }+}++#[cfg(test)]+#[cfg(feature = "dim3")]+mod test {+ use crate::{+ bounding_volume::details::support_map_aabb,+ math::{Pose, Real, Rotation, Vector},+ shape::Triangle,+ };+ use core::f64::consts::FRAC_PI_2;++ #[test]+ fn triangle_aabb_matches_support_map_aabb() {+ let t = Triangle::new(+ Vector::new(0.3, -0.1, 0.2),+ Vector::new(-0.7, 1.0, 0.0),+ Vector::new(-0.7, 1.5, 0.0),+ );++ let m = Pose::from_parts(+ Vector::new(-0.2, 5.0, 0.2),+ Rotation::from_euler(glamx::EulerRot::XYZ, 0.0, FRAC_PI_2 as Real, 0.0),+ );++ assert_eq!(t.aabb(&m), support_map_aabb(&m, &t));++ // TODO: also test local Aabb once support maps have a local Aabb+ // function too+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/aabb_utils.rs b/renderer/third_party/parry3d/src/bounding_volume/aabb_utils.rsnew file mode 100644index 0000000..ff0db7f--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/aabb_utils.rs@@ -0,0 +1,115 @@+use core::iter::IntoIterator;++use crate::bounding_volume::Aabb;+use crate::math::VectorExt;+use crate::math::{Pose, Vector, DIM};+use crate::shape::SupportMap;++/// Computes the [`Aabb`] of an [support mapped shape](SupportMap).+#[cfg(feature = "dim3")]+pub fn support_map_aabb<G>(m: &Pose, i: &G) -> Aabb+where+ G: SupportMap,+{+ let mut min = Vector::ZERO;+ let mut max = Vector::ZERO;+ let mut basis = Vector::ZERO;++ for d in 0..DIM {+ // TODO: this could be further improved iterating on `m`'s columns, and passing+ // Id as the transformation matrix.+ basis.vset(d, 1.0);+ max.vset(d, i.support_point(m, basis).vget(d));++ basis.vset(d, -1.0);+ min.vset(d, i.support_point(m, basis).vget(d));++ basis.vset(d, 0.0);+ }++ Aabb::new(min, max)+}++/// Computes the [`Aabb`] of an [support mapped shape](SupportMap).+pub fn local_support_map_aabb<G>(i: &G) -> Aabb+where+ G: SupportMap,+{+ let mut min = Vector::ZERO;+ let mut max = Vector::ZERO;+ let mut basis = Vector::ZERO;++ for d in 0..DIM {+ // TODO: this could be further improved iterating on `m`'s columns, and passing+ // Id as the transformation matrix.+ basis.vset(d, 1.0);+ max.vset(d, i.local_support_point(basis).vget(d));++ basis.vset(d, -1.0);+ min.vset(d, i.local_support_point(basis).vget(d));++ basis.vset(d, 0.0);+ }++ Aabb::new(min, max)+}++/// Computes the [`Aabb`] of a set of point references transformed by `m`.+pub fn point_cloud_aabb_ref<'a, I>(m: &Pose, pts: I) -> Aabb+where+ I: IntoIterator<Item = &'a Vector>,+{+ point_cloud_aabb(m, pts.into_iter().copied())+}++/// Computes the [`Aabb`] of a set of points transformed by `m`.+pub fn point_cloud_aabb<I>(m: &Pose, pts: I) -> Aabb+where+ I: IntoIterator<Item = Vector>,+{+ let mut it = pts.into_iter();++ let p0 = it.next().expect(+ "Vector cloud Aabb construction: the input iterator should yield at least one point.",+ );+ let wp0 = m * p0;+ let mut min: Vector = wp0;+ let mut max: Vector = wp0;++ for pt in it {+ let wpt = m * pt;+ min = min.min(wpt);+ max = max.max(wpt);+ }++ Aabb::new(min, max)+}++/// Computes the [`Aabb`] of a set of points.+pub fn local_point_cloud_aabb_ref<'a, I>(pts: I) -> Aabb+where+ I: IntoIterator<Item = &'a Vector>,+{+ local_point_cloud_aabb(pts.into_iter().copied())+}++/// Computes the [`Aabb`] of a set of points.+pub fn local_point_cloud_aabb<I>(pts: I) -> Aabb+where+ I: IntoIterator<Item = Vector>,+{+ let mut it = pts.into_iter();++ let p0 = it.next().expect(+ "Vector cloud Aabb construction: the input iterator should yield at least one point.",+ );+ let mut min: Vector = p0;+ let mut max: Vector = p0;++ for pt in it {+ min = min.min(pt);+ max = max.max(pt);+ }++ Aabb::new(min, max)+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/aabb_voxels.rs b/renderer/third_party/parry3d/src/bounding_volume/aabb_voxels.rsnew file mode 100644index 0000000..881ef8a--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/aabb_voxels.rs@@ -0,0 +1,17 @@+use crate::bounding_volume::Aabb;+use crate::math::Pose;+use crate::shape::Voxels;++impl Voxels {+ /// Computes the world-space Aabb of this set of voxels, transformed by `pos`.+ #[inline]+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ self.chunk_bvh().root_aabb().transform_by(pos)+ }++ /// Computes the local-space Aabb of this set of voxels.+ #[inline]+ pub fn local_aabb(&self) -> Aabb {+ self.chunk_bvh().root_aabb()+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere.rsnew file mode 100644index 0000000..173b9fa--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere.rs@@ -0,0 +1,590 @@+//! Bounding sphere.++use crate::bounding_volume::BoundingVolume;+use crate::math::{Pose, Real, Vector};++/// A Bounding Sphere.+///+/// A bounding sphere is a spherical bounding volume defined by a center point and a radius.+/// Unlike an AABB, a bounding sphere is rotation-invariant, meaning it doesn't need to be+/// recomputed when an object rotates.+///+/// # Structure+///+/// - **center**: The center point of the sphere+/// - **radius**: The distance from the center to any point on the sphere's surface+///+/// # Properties+///+/// - **Rotation-invariant**: Remains valid under rotation transformations+/// - **Simple**: Only 4 values (3D: x, y, z, radius; 2D: x, y, radius)+/// - **Conservative**: Often larger than the actual shape, especially for elongated objects+/// - **Fast intersection tests**: Only requires distance comparison+///+/// # Use Cases+///+/// Bounding spheres are useful for:+///+/// - **Rotating objects**: No recomputation needed when objects rotate+/// - **Broad-phase culling**: Quick rejection of distant object pairs+/// - **View frustum culling**: Simple sphere-frustum tests+/// - **Level of detail (LOD)**: Distance-based detail switching+/// - **Physics simulations**: Fast bounds checking for moving/rotating bodies+///+/// # Performance+///+/// - **Intersection test**: O(1) - Single distance comparison+/// - **Rotation**: O(1) - Only center needs transformation+/// - **Contains test**: O(1) - Distance plus radius comparison+///+/// # Comparison to AABB+///+/// **When to use BoundingSphere:**+/// - Objects rotate frequently+/// - Objects are roughly spherical or evenly distributed+/// - Memory is tight (fewer values to store)+/// - Rotation-invariant bounds are required+///+/// **When to use AABB:**+/// - Objects are axis-aligned or rarely rotate+/// - Objects are elongated or box-like+/// - Tighter bounds are critical+/// - Building spatial hierarchies (BVH, octree)+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::bounding_volume::BoundingSphere;+/// use parry3d::math::Vector;+///+/// // Create a bounding sphere with center at origin and radius 2.0+/// let sphere = BoundingSphere::new(Vector::ZERO, 2.0);+///+/// // Check basic properties+/// assert_eq!(sphere.center(), Vector::ZERO);+/// assert_eq!(sphere.radius(), 2.0);+///+/// // Test if a point is within the sphere+/// let point = Vector::new(1.0, 1.0, 0.0);+/// let distance = (point - sphere.center()).length();+/// assert!(distance <= sphere.radius());+/// # }+/// ```+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::bounding_volume::BoundingSphere;+/// use parry3d::math::Vector;+///+/// // Create a sphere and translate it+/// let sphere = BoundingSphere::new(Vector::new(1.0, 2.0, 3.0), 1.5);+/// let translation = Vector::new(5.0, 0.0, 0.0);+/// let moved = sphere.translated(translation);+///+/// assert_eq!(moved.center(), Vector::new(6.0, 2.0, 3.0));+/// assert_eq!(moved.radius(), 1.5); // Radius unchanged by translation+/// # }+/// ```+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::bounding_volume::{BoundingSphere, BoundingVolume};+/// use parry3d::math::Vector;+///+/// // Merge two bounding spheres+/// let sphere1 = BoundingSphere::new(Vector::ZERO, 1.0);+/// let sphere2 = BoundingSphere::new(Vector::new(4.0, 0.0, 0.0), 1.0);+///+/// let merged = sphere1.merged(&sphere2);+/// // The merged sphere contains both original spheres.+/// // Note: due to floating-point rounding, containment may fail by a tiny margin+/// // for some inputs; apply `BoundingVolume::loosened` if strict containment matters.+/// assert!(merged.contains(&sphere1));+/// assert!(merged.contains(&sphere2));+/// # }+/// ```+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Debug, PartialEq, Copy, Clone)]+#[repr(C)]+pub struct BoundingSphere {+ /// The center point of the bounding sphere.+ pub center: Vector,++ /// The radius of the bounding sphere.+ ///+ /// This is the distance from the center to any point on the sphere's surface.+ /// All points within the bounded object should satisfy: distance(point, center) <= radius+ pub radius: Real,+}++impl BoundingSphere {+ /// Creates a new bounding sphere from a center point and radius.+ ///+ /// # Arguments+ ///+ /// * `center` - The center point of the sphere+ /// * `radius` - The radius of the sphere (must be non-negative)+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::BoundingSphere;+ /// use parry3d::math::Vector;+ ///+ /// // Create a sphere centered at (1, 2, 3) with radius 5.0+ /// let sphere = BoundingSphere::new(+ /// Vector::new(1.0, 2.0, 3.0),+ /// 5.0+ /// );+ ///+ /// assert_eq!(sphere.center(), Vector::new(1.0, 2.0, 3.0));+ /// assert_eq!(sphere.radius(), 5.0);+ /// # }+ /// ```+ pub fn new(center: Vector, radius: Real) -> BoundingSphere {+ BoundingSphere { center, radius }+ }++ /// Returns a reference to the center point of this bounding sphere.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::BoundingSphere;+ /// use parry3d::math::Vector;+ ///+ /// let sphere = BoundingSphere::new(Vector::new(1.0, 2.0, 3.0), 5.0);+ /// let center = sphere.center();+ ///+ /// assert_eq!(center, Vector::new(1.0, 2.0, 3.0));+ /// # }+ /// ```+ #[inline]+ pub fn center(&self) -> Vector {+ self.center+ }++ /// Returns the radius of this bounding sphere.+ ///+ /// The radius is the distance from the center to any point on the sphere's surface.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::BoundingSphere;+ /// use parry3d::math::Vector;+ ///+ /// let sphere = BoundingSphere::new(Vector::ZERO, 10.0);+ ///+ /// assert_eq!(sphere.radius(), 10.0);+ /// # }+ /// ```+ #[inline]+ pub fn radius(&self) -> Real {+ self.radius+ }++ /// Transforms this bounding sphere by the given isometry.+ ///+ /// For a bounding sphere, only the center point is affected by the transformation.+ /// The radius remains unchanged because spheres are rotation-invariant and isometries+ /// preserve distances.+ ///+ /// # Arguments+ ///+ /// * `m` - The isometry (rigid transformation) to apply+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::BoundingSphere;+ /// use parry3d::math::{Vector, Pose, Rotation};+ ///+ /// let sphere = BoundingSphere::new(Vector::new(1.0, 0.0, 0.0), 2.0);+ ///+ /// // Create a transformation: translate by (5, 0, 0) and rotate 90 degrees around Z+ /// let translation = Vector::new(5.0, 0.0, 0.0);+ /// let rotation = Rotation::from_rotation_z(std::f32::consts::FRAC_PI_2);+ /// let transform = Pose::from_parts(translation, rotation);+ ///+ /// let transformed = sphere.transform_by(&transform);+ ///+ /// // The center is transformed+ /// assert!((transformed.center() - Vector::new(5.0, 1.0, 0.0)).length() < 1e-5);+ /// // The radius is unchanged+ /// assert_eq!(transformed.radius(), 2.0);+ /// # }+ /// ```+ #[inline]+ pub fn transform_by(&self, m: &Pose) -> BoundingSphere {+ BoundingSphere::new(m * self.center, self.radius)+ }++ /// Translates this bounding sphere by the given vector.+ ///+ /// This is equivalent to `transform_by` with a pure translation, but more efficient+ /// as it doesn't involve rotation.+ ///+ /// # Arguments+ ///+ /// * `translation` - The translation vector to add to the center+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::BoundingSphere;+ /// use parry3d::math::Vector;+ ///+ /// let sphere = BoundingSphere::new(Vector::ZERO, 1.0);+ /// let translation = Vector::new(10.0, 5.0, -3.0);+ ///+ /// let moved = sphere.translated(translation);+ ///+ /// assert_eq!(moved.center(), Vector::new(10.0, 5.0, -3.0));+ /// assert_eq!(moved.radius(), 1.0); // Radius unchanged+ /// # }+ /// ```+ #[inline]+ pub fn translated(&self, translation: Vector) -> BoundingSphere {+ BoundingSphere::new(self.center + translation, self.radius)+ }+}++impl BoundingVolume for BoundingSphere {+ /// Returns the center point of this bounding sphere.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::{BoundingSphere, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let sphere = BoundingSphere::new(Vector::new(1.0, 2.0, 3.0), 5.0);+ ///+ /// // BoundingVolume::center() returns a Vector by value+ /// assert_eq!(BoundingVolume::center(&sphere), Vector::new(1.0, 2.0, 3.0));+ /// # }+ /// ```+ #[inline]+ fn center(&self) -> Vector {+ self.center()+ }++ /// Tests if this bounding sphere intersects another bounding sphere.+ ///+ /// Two spheres intersect if the distance between their centers is less than or equal+ /// to the sum of their radii.+ ///+ /// # Arguments+ ///+ /// * `other` - The other bounding sphere to test against+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::{BoundingSphere, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let sphere1 = BoundingSphere::new(Vector::ZERO, 2.0);+ /// let sphere2 = BoundingSphere::new(Vector::new(3.0, 0.0, 0.0), 2.0);+ /// let sphere3 = BoundingSphere::new(Vector::new(10.0, 0.0, 0.0), 1.0);+ ///+ /// assert!(sphere1.intersects(&sphere2)); // Distance 3.0 <= sum of radii 4.0+ /// assert!(!sphere1.intersects(&sphere3)); // Distance 10.0 > sum of radii 3.0+ /// # }+ /// ```+ #[inline]+ fn intersects(&self, other: &BoundingSphere) -> bool {+ // TODO: refactor that with the code from narrow_phase::ball_ball::collide(...) ?+ let delta_pos = other.center - self.center;+ let distance_squared = delta_pos.length_squared();+ let sum_radius = self.radius + other.radius;++ distance_squared <= sum_radius * sum_radius+ }++ /// Tests if this bounding sphere fully contains another bounding sphere.+ ///+ /// A sphere fully contains another sphere if the distance between their centers+ /// plus the other's radius is less than or equal to this sphere's radius.+ ///+ /// # Arguments+ ///+ /// * `other` - The other bounding sphere to test+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::{BoundingSphere, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let large = BoundingSphere::new(Vector::ZERO, 10.0);+ /// let small = BoundingSphere::new(Vector::new(2.0, 0.0, 0.0), 1.0);+ /// let outside = BoundingSphere::new(Vector::new(15.0, 0.0, 0.0), 2.0);+ ///+ /// assert!(large.contains(&small)); // Small sphere is inside large sphere+ /// assert!(!large.contains(&outside)); // Outside sphere extends beyond large sphere+ /// assert!(!small.contains(&large)); // Small cannot contain large+ /// # }+ /// ```+ #[inline]+ fn contains(&self, other: &BoundingSphere) -> bool {+ let delta_pos = other.center - self.center;+ let distance = delta_pos.length();++ distance + other.radius <= self.radius+ }++ /// Merges this bounding sphere with another in-place.+ ///+ /// After this operation, this sphere will be the smallest sphere that contains+ /// both the original sphere and the other sphere.+ ///+ /// Note that due to floating-point rounding, [`contains`](BoundingVolume::contains)+ /// is not guaranteed to return `true` for the two input spheres afterwards: the+ /// result can be off by a tiny margin. Use [`loosened`](BoundingVolume::loosened)+ /// with a small margin if strict containment is required.+ ///+ /// # Arguments+ ///+ /// * `other` - The other bounding sphere to merge with+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::{BoundingSphere, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let mut sphere1 = BoundingSphere::new(Vector::ZERO, 1.0);+ /// let sphere2 = BoundingSphere::new(Vector::new(4.0, 0.0, 0.0), 1.0);+ ///+ /// sphere1.merge(&sphere2);+ ///+ /// // The merged sphere now contains both original spheres+ /// assert!(sphere1.contains(&BoundingSphere::new(Vector::ZERO, 1.0)));+ /// assert!(sphere1.contains(&sphere2));+ /// # }+ /// ```+ #[inline]+ fn merge(&mut self, other: &BoundingSphere) {+ let dir = other.center() - self.center();+ let (dir, length) = dir.normalize_and_length();++ if length == 0.0 {+ if other.radius > self.radius {+ self.radius = other.radius+ }+ } else {+ let s_center_dir = self.center.dot(dir);+ let o_center_dir = other.center.dot(dir);++ let right = if s_center_dir + self.radius > o_center_dir + other.radius {+ self.center + dir * self.radius+ } else {+ other.center + dir * other.radius+ };++ let left = if -s_center_dir + self.radius > -o_center_dir + other.radius {+ self.center - dir * self.radius+ } else {+ other.center - dir * other.radius+ };++ self.center = left.midpoint(right);+ self.radius = right.distance(self.center);+ }+ }++ /// Returns a new bounding sphere that is the merge of this sphere and another.+ ///+ /// The returned sphere is the smallest sphere that contains both input spheres.+ /// This is the non-mutating version of `merge`.+ ///+ /// Note that due to floating-point rounding, [`contains`](BoundingVolume::contains)+ /// is not guaranteed to return `true` for the two input spheres: the result can be+ /// off by a tiny margin. Use [`loosened`](BoundingVolume::loosened) with a small+ /// margin if strict containment is required.+ ///+ /// # Arguments+ ///+ /// * `other` - The other bounding sphere to merge with+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::{BoundingSphere, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let sphere1 = BoundingSphere::new(Vector::ZERO, 1.0);+ /// let sphere2 = BoundingSphere::new(Vector::new(4.0, 0.0, 0.0), 1.0);+ ///+ /// let merged = sphere1.merged(&sphere2);+ ///+ /// // Original spheres are unchanged+ /// assert_eq!(sphere1.radius(), 1.0);+ /// // Merged sphere contains both+ /// assert!(merged.contains(&sphere1));+ /// assert!(merged.contains(&sphere2));+ /// # }+ /// ```+ #[inline]+ fn merged(&self, other: &BoundingSphere) -> BoundingSphere {+ let mut res = *self;++ res.merge(other);++ res+ }++ /// Increases the radius of this bounding sphere by the given amount in-place.+ ///+ /// This creates a larger sphere with the same center. Useful for adding safety margins+ /// or creating conservative bounds.+ ///+ /// # Arguments+ ///+ /// * `amount` - The amount to increase the radius (must be non-negative)+ ///+ /// # Panics+ ///+ /// Panics if `amount` is negative.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::{BoundingSphere, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let mut sphere = BoundingSphere::new(Vector::ZERO, 5.0);+ /// sphere.loosen(2.0);+ ///+ /// assert_eq!(sphere.radius(), 7.0);+ /// assert_eq!(sphere.center(), Vector::ZERO); // Center unchanged+ /// # }+ /// ```+ #[inline]+ fn loosen(&mut self, amount: Real) {+ assert!(amount >= 0.0, "The loosening margin must be non-negative.");+ self.radius += amount+ }++ /// Returns a new bounding sphere with increased radius.+ ///+ /// This is the non-mutating version of `loosen`. The returned sphere has the same+ /// center but a larger radius.+ ///+ /// # Arguments+ ///+ /// * `amount` - The amount to increase the radius (must be non-negative)+ ///+ /// # Panics+ ///+ /// Panics if `amount` is negative.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::{BoundingSphere, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let sphere = BoundingSphere::new(Vector::ZERO, 5.0);+ /// let larger = sphere.loosened(3.0);+ ///+ /// assert_eq!(sphere.radius(), 5.0); // Original unchanged+ /// assert_eq!(larger.radius(), 8.0);+ /// assert_eq!(larger.center(), Vector::ZERO);+ /// # }+ /// ```+ #[inline]+ fn loosened(&self, amount: Real) -> BoundingSphere {+ assert!(amount >= 0.0, "The loosening margin must be non-negative.");+ BoundingSphere::new(self.center, self.radius + amount)+ }++ /// Decreases the radius of this bounding sphere by the given amount in-place.+ ///+ /// This creates a smaller sphere with the same center. Useful for conservative+ /// collision detection or creating inner bounds.+ ///+ /// # Arguments+ ///+ /// * `amount` - The amount to decrease the radius (must be non-negative and ≤ radius)+ ///+ /// # Panics+ ///+ /// Panics if `amount` is negative or greater than the current radius.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::{BoundingSphere, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let mut sphere = BoundingSphere::new(Vector::ZERO, 10.0);+ /// sphere.tighten(3.0);+ ///+ /// assert_eq!(sphere.radius(), 7.0);+ /// assert_eq!(sphere.center(), Vector::ZERO); // Center unchanged+ /// # }+ /// ```+ #[inline]+ fn tighten(&mut self, amount: Real) {+ assert!(amount >= 0.0, "The tightening margin must be non-negative.");+ assert!(amount <= self.radius, "The tightening margin is to large.");+ self.radius -= amount+ }++ /// Returns a new bounding sphere with decreased radius.+ ///+ /// This is the non-mutating version of `tighten`. The returned sphere has the same+ /// center but a smaller radius.+ ///+ /// # Arguments+ ///+ /// * `amount` - The amount to decrease the radius (must be non-negative and ≤ radius)+ ///+ /// # Panics+ ///+ /// Panics if `amount` is negative or greater than the current radius.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::bounding_volume::{BoundingSphere, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let sphere = BoundingSphere::new(Vector::ZERO, 10.0);+ /// let smaller = sphere.tightened(4.0);+ ///+ /// assert_eq!(sphere.radius(), 10.0); // Original unchanged+ /// assert_eq!(smaller.radius(), 6.0);+ /// assert_eq!(smaller.center(), Vector::ZERO);+ /// # }+ /// ```+ #[inline]+ fn tightened(&self, amount: Real) -> BoundingSphere {+ assert!(amount >= 0.0, "The tightening margin must be non-negative.");+ assert!(amount <= self.radius, "The tightening margin is to large.");+ BoundingSphere::new(self.center, self.radius - amount)+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_ball.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_ball.rsnew file mode 100644index 0000000..dd6263b--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_ball.rs@@ -0,0 +1,18 @@+use crate::bounding_volume::BoundingSphere;+use crate::math::{Pose, Vector};+use crate::shape::Ball;++impl Ball {+ /// Computes the world-space bounding sphere of this ball, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ let bv: BoundingSphere = self.local_bounding_sphere();+ bv.transform_by(pos)+ }++ /// Computes the local-space Aabb of this ball.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ BoundingSphere::new(Vector::ZERO, self.radius)+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_capsule.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_capsule.rsnew file mode 100644index 0000000..ec2d42c--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_capsule.rs@@ -0,0 +1,18 @@+use crate::bounding_volume::BoundingSphere;+use crate::math::Pose;+use crate::shape::Capsule;++impl Capsule {+ /// Computes the world-space bounding sphere of this capsule, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ self.local_bounding_sphere().transform_by(pos)+ }++ /// Computes the world-space bounding sphere of this capsule.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ let radius = self.radius + self.half_height();+ BoundingSphere::new(self.center(), radius)+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_cone.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_cone.rsnew file mode 100644index 0000000..e83dda9--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_cone.rs@@ -0,0 +1,22 @@+use crate::bounding_volume::BoundingSphere;+use crate::math::{ComplexField, Pose, Real, Vector};+use crate::shape::Cone;++impl Cone {+ /// Computes the world-space bounding sphere of this cone, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ let bv: BoundingSphere = self.local_bounding_sphere();+ bv.transform_by(pos)+ }++ /// Computes the local-space bounding sphere of this cone.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ let radius = <Real as ComplexField>::sqrt(+ self.radius * self.radius + self.half_height * self.half_height,+ );++ BoundingSphere::new(Vector::ZERO, radius)+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_convex.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_convex.rsnew file mode 100644index 0000000..a02ce55--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_convex.rs@@ -0,0 +1,19 @@+use crate::bounding_volume;+use crate::bounding_volume::BoundingSphere;+use crate::math::Pose;+use crate::shape::ConvexPolyhedron;++impl ConvexPolyhedron {+ /// Computes the world-space bounding sphere of this convex polyhedron, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ let bv: BoundingSphere = self.local_bounding_sphere();+ bv.transform_by(pos)+ }++ /// Computes the local-space bounding sphere of this convex polyhedron.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ bounding_volume::details::point_cloud_bounding_sphere(self.points())+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_convex_polygon.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_convex_polygon.rsnew file mode 100644index 0000000..0fbedd7--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_convex_polygon.rs@@ -0,0 +1,19 @@+use crate::bounding_volume;+use crate::bounding_volume::BoundingSphere;+use crate::math::Pose;+use crate::shape::ConvexPolygon;++impl ConvexPolygon {+ /// Computes the world-space bounding sphere of this convex polygon, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ let bv: BoundingSphere = self.local_bounding_sphere();+ bv.transform_by(pos)+ }++ /// Computes the local-space bounding sphere of this convex polygon.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ bounding_volume::details::point_cloud_bounding_sphere(self.points())+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_cuboid.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_cuboid.rsnew file mode 100644index 0000000..02f9db9--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_cuboid.rs@@ -0,0 +1,19 @@+use crate::bounding_volume::BoundingSphere;+use crate::math::{Pose, Vector};+use crate::shape::Cuboid;++impl Cuboid {+ /// Computes the world-space bounding sphere of this cuboid, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ let bv: BoundingSphere = self.local_bounding_sphere();+ bv.transform_by(pos)+ }++ /// Computes the local-space bounding sphere of this cuboid.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ let radius = self.half_extents.length();+ BoundingSphere::new(Vector::ZERO, radius)+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_cylinder.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_cylinder.rsnew file mode 100644index 0000000..9fd1d05--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_cylinder.rs@@ -0,0 +1,22 @@+use crate::bounding_volume::BoundingSphere;+use crate::math::{ComplexField, Pose, Real, Vector};+use crate::shape::Cylinder;++impl Cylinder {+ /// Computes the world-space bounding sphere of this cylinder, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ let bv: BoundingSphere = self.local_bounding_sphere();+ bv.transform_by(pos)+ }++ /// Computes the local-space bounding sphere of this cylinder.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ let radius = <Real as ComplexField>::sqrt(+ self.radius * self.radius + self.half_height * self.half_height,+ );++ BoundingSphere::new(Vector::ZERO, radius)+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_halfspace.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_halfspace.rsnew file mode 100644index 0000000..626772e--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_halfspace.rs@@ -0,0 +1,22 @@+use crate::bounding_volume::BoundingSphere;+use crate::math::{Pose, Real, Vector};+use crate::shape::HalfSpace;++use num::Bounded;++impl HalfSpace {+ /// Computes the world-space bounding sphere of this half-space, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ let bv: BoundingSphere = self.local_bounding_sphere();+ bv.transform_by(pos)+ }++ /// Computes the local-space bounding sphere of this half-space.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ let radius = Real::max_value();++ BoundingSphere::new(Vector::ZERO, radius)+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_heightfield.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_heightfield.rsnew file mode 100644index 0000000..9dd3294--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_heightfield.rs@@ -0,0 +1,17 @@+use crate::bounding_volume::BoundingSphere;+use crate::math::Pose;+use crate::shape::HeightField;++impl HeightField {+ /// Computes the world-space bounding sphere of this height-field, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ self.local_aabb().bounding_sphere().transform_by(pos)+ }++ /// Computes the local-space bounding sphere of this height-field.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ self.local_aabb().bounding_sphere()+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_polyline.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_polyline.rsnew file mode 100644index 0000000..1c24672--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_polyline.rs@@ -0,0 +1,17 @@+use crate::bounding_volume::BoundingSphere;+use crate::math::Pose;+use crate::shape::Polyline;++impl Polyline {+ /// Computes the world-space bounding sphere of this polyline, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ self.local_aabb().bounding_sphere().transform_by(pos)+ }++ /// Computes the local-space bounding sphere of this polyline.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ self.local_aabb().bounding_sphere()+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_segment.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_segment.rsnew file mode 100644index 0000000..d9de1f7--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_segment.rs@@ -0,0 +1,20 @@+use crate::bounding_volume;+use crate::bounding_volume::BoundingSphere;+use crate::math::Pose;+use crate::shape::Segment;++impl Segment {+ /// Computes the world-space bounding sphere of this segment, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ let bv: BoundingSphere = self.local_bounding_sphere();+ bv.transform_by(pos)+ }++ /// Computes the local-space bounding sphere of this segment.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ let pts = [self.a, self.b];+ bounding_volume::details::point_cloud_bounding_sphere(&pts[..])+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_triangle.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_triangle.rsnew file mode 100644index 0000000..2cbc1dc--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_triangle.rs@@ -0,0 +1,20 @@+use crate::bounding_volume;+use crate::bounding_volume::BoundingSphere;+use crate::math::Pose;+use crate::shape::Triangle;++impl Triangle {+ /// Computes the world-space bounding sphere of this triangle, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ let bv: BoundingSphere = self.local_bounding_sphere();+ bv.transform_by(pos)+ }++ /// Computes the local-space bounding sphere of this triangle.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ let pts = [self.a, self.b, self.c];+ bounding_volume::details::point_cloud_bounding_sphere(&pts[..])+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_trimesh.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_trimesh.rsnew file mode 100644index 0000000..211e554--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_trimesh.rs@@ -0,0 +1,17 @@+use crate::bounding_volume::BoundingSphere;+use crate::math::Pose;+use crate::shape::TriMesh;++impl TriMesh {+ /// Computes the world-space bounding sphere of this triangle mesh, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ self.local_aabb().bounding_sphere().transform_by(pos)+ }++ /// Computes the local-space bounding sphere of this triangle mesh.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ self.local_aabb().bounding_sphere()+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_utils.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_utils.rsnew file mode 100644index 0000000..bd1b049--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_utils.rs@@ -0,0 +1,25 @@+use crate::math::{ComplexField, Real, Vector};+use crate::utils;++use super::BoundingSphere;++/// Computes the bounding sphere of a set of point, given its center.+#[inline]+pub fn point_cloud_bounding_sphere_with_center(pts: &[Vector], center: Vector) -> BoundingSphere {+ let mut sqradius = 0.0;++ for pt in pts.iter() {+ let dist_sq = pt.distance_squared(center);++ if dist_sq > sqradius {+ sqradius = dist_sq+ }+ }+ BoundingSphere::new(center, <Real as ComplexField>::sqrt(sqradius))+}++/// Computes a bounding sphere of the specified set of point.+#[inline]+pub fn point_cloud_bounding_sphere(pts: &[Vector]) -> BoundingSphere {+ point_cloud_bounding_sphere_with_center(pts, utils::center(pts))+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_voxels.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_voxels.rsnew file mode 100644index 0000000..bef3c8b--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_sphere_voxels.rs@@ -0,0 +1,17 @@+use crate::bounding_volume::BoundingSphere;+use crate::math::Pose;+use crate::shape::Voxels;++impl Voxels {+ /// Computes the world-space bounding sphere of this set of voxels, transformed by `pos`.+ #[inline]+ pub fn bounding_sphere(&self, pos: &Pose) -> BoundingSphere {+ self.local_aabb().bounding_sphere().transform_by(pos)+ }++ /// Computes the local-space bounding sphere of this set of voxels.+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ self.local_aabb().bounding_sphere()+ }+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/bounding_volume.rs b/renderer/third_party/parry3d/src/bounding_volume/bounding_volume.rsnew file mode 100644index 0000000..1d4ab22--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/bounding_volume.rs@@ -0,0 +1,45 @@+use crate::math::{Real, Vector};++/// Trait of bounding volumes.+///+/// Bounding volumes are coarse approximations of shapes. It usually have constant time+/// intersection, inclusion test. Two bounding volume must also be mergeable into a bigger bounding+/// volume.+pub trait BoundingVolume {+ // TODO: keep that ? What about non-spacial bounding volumes (e.g. bounding cones, curvature+ // bounds, etc.) ?+ /// Returns a point inside of this bounding volume. This is ideally its center.+ fn center(&self) -> Vector;++ /// Checks if this bounding volume intersect with another one.+ fn intersects(&self, _: &Self) -> bool;++ /// Checks if this bounding volume contains another one.+ fn contains(&self, _: &Self) -> bool;++ /// Merges this bounding volume with another one. The merge is done in-place.+ ///+ /// Due to floating-point rounding, the merged volume is not guaranteed to strictly+ /// [`contain`](Self::contains) both input volumes. Use [`loosened`](Self::loosened)+ /// with a small margin if strict containment is required.+ fn merge(&mut self, _: &Self);++ /// Merges this bounding volume with another one.+ ///+ /// Due to floating-point rounding, the merged volume is not guaranteed to strictly+ /// [`contain`](Self::contains) both input volumes. Use [`loosened`](Self::loosened)+ /// with a small margin if strict containment is required.+ fn merged(&self, _: &Self) -> Self;++ /// Enlarges this bounding volume.+ fn loosen(&mut self, _: Real);++ /// Creates a new, enlarged version, of this bounding volume.+ fn loosened(&self, _: Real) -> Self;++ /// Tighten this bounding volume.+ fn tighten(&mut self, _: Real);++ /// Creates a new, tightened version, of this bounding volume.+ fn tightened(&self, _: Real) -> Self;+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/mod.rs b/renderer/third_party/parry3d/src/bounding_volume/mod.rsnew file mode 100644index 0000000..a379ff0--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/mod.rs@@ -0,0 +1,75 @@+//! Bounding volumes.++#[doc(inline)]+pub use crate::bounding_volume::aabb::Aabb;++// pub use crate::bounding_volume::simd_aabb::SimdAabb;++#[doc(inline)]+pub use crate::bounding_volume::bounding_sphere::BoundingSphere;+#[doc(inline)]+pub use crate::bounding_volume::bounding_volume::BoundingVolume;++#[doc(hidden)]+pub mod bounding_volume;++#[doc(hidden)]+pub mod aabb;+mod aabb_ball;+#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+mod aabb_convex_polygon;+#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+mod aabb_convex_polyhedron;+mod aabb_cuboid;+mod aabb_halfspace;+#[cfg(feature = "alloc")]+mod aabb_heightfield;+mod aabb_support_map;+mod aabb_triangle;+mod aabb_utils;++mod aabb_capsule;+#[cfg(feature = "alloc")]+mod aabb_voxels;+#[doc(hidden)]+pub mod bounding_sphere;+mod bounding_sphere_ball;+mod bounding_sphere_capsule;+#[cfg(feature = "dim3")]+mod bounding_sphere_cone;+#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+mod bounding_sphere_convex;+#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+mod bounding_sphere_convex_polygon;+mod bounding_sphere_cuboid;+#[cfg(feature = "dim3")]+mod bounding_sphere_cylinder;+mod bounding_sphere_halfspace;+#[cfg(feature = "alloc")]+mod bounding_sphere_heightfield;+#[cfg(feature = "alloc")]+mod bounding_sphere_polyline;+mod bounding_sphere_segment;+mod bounding_sphere_triangle;+#[cfg(feature = "alloc")]+mod bounding_sphere_trimesh;+mod bounding_sphere_utils;+#[cfg(feature = "alloc")]+mod bounding_sphere_voxels;++// mod simd_aabb;++/// Free functions for some special cases of bounding-volume computation.+pub mod details {+ #[cfg(feature = "dim3")]+ pub use super::aabb_utils::support_map_aabb;+ pub use super::aabb_utils::{+ local_point_cloud_aabb, local_point_cloud_aabb_ref, local_support_map_aabb,+ point_cloud_aabb, point_cloud_aabb_ref,+ };+ pub use super::bounding_sphere_utils::point_cloud_bounding_sphere;+}diff --git a/renderer/third_party/parry3d/src/bounding_volume/simd_aabb.rs b/renderer/third_party/parry3d/src/bounding_volume/simd_aabb.rsnew file mode 100644index 0000000..6217957--- /dev/null+++ b/renderer/third_party/parry3d/src/bounding_volume/simd_aabb.rs@@ -0,0 +1,351 @@+use crate::bounding_volume::Aabb;+use crate::math::{Pose, Real, SimdBool, SimdReal, Vector, Vector, DIM, SIMD_WIDTH};+use crate::query::SimdRay;+use crate::utils::{self, PoseOps};+use num::{One, Zero};+use simba::simd::{SimdPartialOrd, SimdValue};++/// Four Aabb represented as a single SoA Aabb with SIMD components.+#[derive(Debug, Copy, Clone)]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize),+)]+pub struct SimdAabb {+ /// The min coordinates of the Aabbs.+ pub mins: Vector<SimdReal>,+ /// The max coordinates the Aabbs.+ pub maxs: Vector<SimdReal>,+}++#[cfg(feature = "serde-serialize")]+impl serde::Serialize for SimdAabb {+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: serde::Serializer,+ {+ use serde::ser::SerializeStruct;++ let mins: Vector<[Real; SIMD_WIDTH]> =+ Vector::from(self.mins.map(|e| array![|ii| e.extract(ii); SIMD_WIDTH]));+ let maxs: Vector<[Real; SIMD_WIDTH]> =+ Vector::from(self.maxs.map(|e| array![|ii| e.extract(ii); SIMD_WIDTH]));++ let mut simd_aabb = serializer.serialize_struct("SimdAabb", 2)?;+ simd_aabb.serialize_field("mins", &mins)?;+ simd_aabb.serialize_field("maxs", &maxs)?;+ simd_aabb.end()+ }+}++#[cfg(feature = "serde-serialize")]+impl<'de> serde::Deserialize<'de> for SimdAabb {+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>+ where+ D: serde::Deserializer<'de>,+ {+ struct Visitor {}++ #[derive(Deserialize)]+ #[serde(field_identifier, rename_all = "lowercase")]+ enum Field {+ Mins,+ Maxs,+ }++ impl<'de> serde::de::Visitor<'de> for Visitor {+ type Value = SimdAabb;+ fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {+ write!(+ formatter,+ "two arrays containing at least {} floats",+ SIMD_WIDTH * DIM * 2+ )+ }++ fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>+ where+ A: serde::de::MapAccess<'de>,+ {+ let mut mins: Option<Vector<[Real; SIMD_WIDTH]>> = None;+ let mut maxs: Option<Vector<[Real; SIMD_WIDTH]>> = None;++ while let Some(key) = map.next_key()? {+ match key {+ Field::Mins => {+ if mins.is_some() {+ return Err(serde::de::Error::duplicate_field("mins"));+ }+ mins = Some(map.next_value()?);+ }+ Field::Maxs => {+ if maxs.is_some() {+ return Err(serde::de::Error::duplicate_field("maxs"));+ }+ maxs = Some(map.next_value()?);+ }+ }+ }++ let mins = mins.ok_or_else(|| serde::de::Error::missing_field("mins"))?;+ let maxs = maxs.ok_or_else(|| serde::de::Error::missing_field("maxs"))?;+ let mins = mins.map(SimdReal::from);+ let maxs = maxs.map(SimdReal::from);+ Ok(SimdAabb { mins, maxs })+ }++ fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>+ where+ A: serde::de::SeqAccess<'de>,+ {+ let mins: Vector<[Real; SIMD_WIDTH]> = seq+ .next_element()?+ .ok_or_else(|| serde::de::Error::invalid_length(0, &self))?;+ let maxs: Vector<[Real; SIMD_WIDTH]> = seq+ .next_element()?+ .ok_or_else(|| serde::de::Error::invalid_length(1, &self))?;+ let mins = mins.map(SimdReal::from);+ let maxs = maxs.map(SimdReal::from);+ Ok(SimdAabb { mins, maxs })+ }+ }++ deserializer.deserialize_struct("SimdAabb", &["mins", "maxs"], Visitor {})+ }+}++impl SimdAabb {+ /// An invalid Aabb.+ pub fn new_invalid() -> Self {+ Self::splat(Aabb::new_invalid())+ }++ /// Builds an SIMD aabb composed of four identical aabbs.+ pub fn splat(aabb: Aabb) -> Self {+ Self {+ mins: Vector::splat(aabb.mins),+ maxs: Vector::splat(aabb.maxs),+ }+ }++ /// The center of all the Aabbs represented by `self`.+ pub fn center(&self) -> Vector<SimdReal> {+ Vector::from((self.mins + self.maxs) * SimdReal::splat(0.5))+ }++ /// The half-extents of all the Aabbs represented by `self`.+ pub fn half_extents(&self) -> Vector<SimdReal> {+ (self.maxs - self.mins) * SimdReal::splat(0.5)+ }++ /// The radius of all the Aabbs represented by `self`.+ pub fn radius(&self) -> SimdReal {+ (self.maxs - self.mins).length()+ }++ /// Return the Aabb of the `self` transformed by the given isometry.+ pub fn transform_by(&self, transform: &Pose<SimdReal>) -> Self {+ let ls_center = self.center();+ let center = transform * ls_center;+ let ws_half_extents = transform.absolute_transform_vector(&self.half_extents());+ Self {+ mins: center + (-ws_half_extents),+ maxs: center + ws_half_extents,+ }+ }++ /// Returns a scaled version of this Aabb.+ #[inline]+ pub fn scaled(self, scale: Vector<SimdReal>) -> Self {+ let a = self.mins * (scale);+ let b = self.maxs * (scale);+ Self {+ mins: a.min(b).into(),+ maxs: a.max(b).into(),+ }+ }++ /// Enlarges this bounding volume by the given margin.+ pub fn loosen(&mut self, margin: SimdReal) {+ self.mins -= Vector::splat(margin);+ self.maxs += Vector::splat(margin);+ }++ /// Dilate all the Aabbs represented by `self` by their extents multiplied+ /// by the given scale `factor`.+ pub fn dilate_by_factor(&mut self, factor: SimdReal) {+ // If some of the Aabbs on this SimdAabb are invalid,+ // don't, dilate them.+ let is_valid = self.mins.x.simd_le(self.maxs.x);+ let factor = factor.select(is_valid, SimdReal::zero());++ // NOTE: we multiply each by factor instead of doing+ // (maxs - mins) * factor. That's to avoid overflows (and+ // therefore NaNs if this SimdAabb contains some invalid+ // Aabbs initialised with Real::MAX+ let dilation = self.maxs * factor - self.mins * factor;+ self.mins -= dilation;+ self.maxs += dilation;+ }++ /// Replace the `i-th` Aabb of this SIMD AAAB by the given value.+ pub fn replace(&mut self, i: usize, aabb: Aabb) {+ self.mins.replace(i, aabb.mins);+ self.maxs.replace(i, aabb.maxs);+ }++ /// Casts a ray on all the Aabbs represented by `self`.+ pub fn cast_local_ray(+ &self,+ ray: &SimdRay,+ max_time_of_impact: SimdReal,+ ) -> (SimdBool, SimdReal) {+ let zero = SimdReal::zero();+ let one = SimdReal::one();+ let infinity = SimdReal::splat(Real::MAX);++ let mut hit = SimdBool::splat(true);+ let mut tmin = SimdReal::zero();+ let mut tmax = max_time_of_impact;++ // TODO: could this be optimized more considering we really just need a boolean answer?+ for i in 0usize..DIM {+ let is_not_zero = ray.dir[i].simd_ne(zero);+ let is_zero_test =+ ray.origin[i].simd_ge(self.mins[i]) & ray.origin[i].simd_le(self.maxs[i]);+ let is_not_zero_test = {+ let denom = one / ray.dir[i];+ let mut inter_with_near_plane =+ ((self.mins[i] - ray.origin[i]) * denom).select(is_not_zero, -infinity);+ let mut inter_with_far_plane =+ ((self.maxs[i] - ray.origin[i]) * denom).select(is_not_zero, infinity);++ let gt = inter_with_near_plane.simd_gt(inter_with_far_plane);+ utils::simd_swap(gt, &mut inter_with_near_plane, &mut inter_with_far_plane);++ tmin = tmin.simd_max(inter_with_near_plane);+ tmax = tmax.simd_min(inter_with_far_plane);++ tmin.simd_le(tmax)+ };++ hit = hit & is_not_zero_test.select(is_not_zero, is_zero_test);+ }++ (hit, tmin)+ }++ /// Computes the distances between a point and all the Aabbs represented by `self`.+ pub fn distance_to_local_point(&self, point: Vector<SimdReal>) -> SimdReal {+ let mins_point = self.mins - point;+ let point_maxs = point - self.maxs;+ let shift = mins_point.max(point_maxs).max(Vector::ZERO);+ shift.length()+ }++ /// Computes the distances between the origin and all the Aabbs represented by `self`.+ pub fn distance_to_origin(&self) -> SimdReal {+ self.mins.max(-self.maxs).max(Vector::ZERO).length()+ }++ /// Check which Aabb represented by `self` contains the given `point`.+ pub fn contains_local_point(&self, point: Vector<SimdReal>) -> SimdBool {+ #[cfg(feature = "dim2")]+ return self.mins.x.simd_le(point.x)+ & self.mins.y.simd_le(point.y)+ & self.maxs.x.simd_ge(point.x)+ & self.maxs.y.simd_ge(point.y);++ #[cfg(feature = "dim3")]+ return self.mins.x.simd_le(point.x)+ & self.mins.y.simd_le(point.y)+ & self.mins.z.simd_le(point.z)+ & self.maxs.x.simd_ge(point.x)+ & self.maxs.y.simd_ge(point.y)+ & self.maxs.z.simd_ge(point.z);+ }++ /// Lanewise check which Aabb represented by `self` contains the given set of `other` aabbs.+ /// The check is performed lane-wise.+ #[cfg(feature = "dim2")]+ pub fn contains(&self, other: &SimdAabb) -> SimdBool {+ self.mins.x.simd_le(other.mins.x)+ & self.mins.y.simd_le(other.mins.y)+ & self.maxs.x.simd_ge(other.maxs.x)+ & self.maxs.y.simd_ge(other.maxs.y)+ }++ /// Lanewise check which Aabb represented by `self` contains the given set of `other` aabbs.+ /// The check is performed lane-wise.+ #[cfg(feature = "dim3")]+ pub fn contains(&self, other: &SimdAabb) -> SimdBool {+ self.mins.x.simd_le(other.mins.x)+ & self.mins.y.simd_le(other.mins.y)+ & self.mins.z.simd_le(other.mins.z)+ & self.maxs.x.simd_ge(other.maxs.x)+ & self.maxs.y.simd_ge(other.maxs.y)+ & self.maxs.z.simd_ge(other.maxs.z)+ }++ /// Lanewise check which Aabb represented by `self` intersects the given set of `other` aabbs.+ /// The check is performed lane-wise.+ #[cfg(feature = "dim2")]+ pub fn intersects(&self, other: &SimdAabb) -> SimdBool {+ self.mins.x.simd_le(other.maxs.x)+ & other.mins.x.simd_le(self.maxs.x)+ & self.mins.y.simd_le(other.maxs.y)+ & other.mins.y.simd_le(self.maxs.y)+ }++ /// Check which Aabb represented by `self` contains the given set of `other` aabbs.+ /// The check is performed lane-wise.+ #[cfg(feature = "dim3")]+ pub fn intersects(&self, other: &SimdAabb) -> SimdBool {+ self.mins.x.simd_le(other.maxs.x)+ & other.mins.x.simd_le(self.maxs.x)+ & self.mins.y.simd_le(other.maxs.y)+ & other.mins.y.simd_le(self.maxs.y)+ & self.mins.z.simd_le(other.maxs.z)+ & other.mins.z.simd_le(self.maxs.z)+ }++ /// Checks intersections between all the lanes combination between `self` and `other`.+ ///+ /// The result is an array such that `result[i].extract(j)` contains the intersection+ /// result between `self.extract(i)` and `other.extract(j)`.+ pub fn intersects_permutations(&self, other: &SimdAabb) -> [SimdBool; SIMD_WIDTH] {+ let mut result = [SimdBool::splat(false); SIMD_WIDTH];+ for (ii, result) in result.iter_mut().enumerate() {+ // TODO: use SIMD-accelerated shuffling?+ let extracted = SimdAabb::splat(self.extract(ii));+ *result = extracted.intersects(other);+ }++ result+ }++ /// Merge all the Aabb represented by `self` into a single one.+ pub fn to_merged_aabb(&self) -> Aabb {+ Aabb::new(+ self.mins.map(|e| e.simd_horizontal_min()).into(),+ self.maxs.map(|e| e.simd_horizontal_max()).into(),+ )+ }++ /// Extracts the Aabb stored in the given SIMD lane of the SIMD Aabb:+ pub fn extract(&self, lane: usize) -> Aabb {+ Aabb::new(self.mins.extract(lane), self.maxs.extract(lane))+ }+}++impl From<[Aabb; SIMD_WIDTH]> for SimdAabb {+ fn from(aabbs: [Aabb; SIMD_WIDTH]) -> Self {+ let mins = array![|ii| aabbs[ii].mins; SIMD_WIDTH];+ let maxs = array![|ii| aabbs[ii].maxs; SIMD_WIDTH];++ SimdAabb {+ mins: Vector::from(mins),+ maxs: Vector::from(maxs),+ }+ }+}diff --git a/renderer/third_party/parry3d/src/lib.rs b/renderer/third_party/parry3d/src/lib.rsnew file mode 100644index 0000000..eae587f--- /dev/null+++ b/renderer/third_party/parry3d/src/lib.rs@@ -0,0 +1,111 @@+/*!+parry+========++**parry** is a 2 and 3-dimensional geometric library written with+the rust programming language.++*/++#![deny(non_camel_case_types)]+#![deny(unused_parens)]+#![deny(non_upper_case_globals)]+#![deny(unused_results)]+#![deny(unused_qualifications)]+#![warn(missing_docs)]+#![allow(unused_imports)] // ThreeRT: as a path dependency its warnings show (PATCH.md); upstream warns.+#![allow(missing_copy_implementations)]+#![allow(clippy::too_many_arguments)] // Maybe revisit this one later.+#![allow(clippy::module_inception)]+#![allow(clippy::manual_range_contains)] // This usually makes it way more verbose that it could be.+#![allow(clippy::type_complexity)] // Complains about closures that are fairly simple.+#![cfg_attr(feature = "dim2", doc(html_root_url = "https://docs.rs/parry2d"))]+#![cfg_attr(feature = "dim3", doc(html_root_url = "https://docs.rs/parry3d"))]+#![no_std]++#[cfg(all(feature = "simd8", feature = "enhanced-determinism"))]+core::compile_error!(+ "8-lanes SIMD cannot be enabled when the `enhanced-determinism` feature is also enabled because it breaks cross-platform determinism."+);++#[allow(unused_macros)]+macro_rules! array(+ ($callback: expr; SIMD_WIDTH) => {+ {+ #[inline(always)]+ #[allow(dead_code)]+ fn create_arr<T>(callback: impl FnMut(usize) -> T) -> [T; SIMD_WIDTH] {+ // Width-agnostic: `N` is inferred from the `[T; SIMD_WIDTH]` return type,+ // so this covers the 1-, 4-, and 8-lane builds alike.+ core::array::from_fn(callback)+ }++ create_arr($callback)+ }+ }+);++#[cfg(feature = "std")]+extern crate std;++#[cfg(feature = "alloc")]+#[cfg_attr(test, macro_use)]+extern crate alloc;++#[cfg(feature = "serde")]+#[macro_use]+extern crate serde;+#[macro_use]+extern crate approx;+extern crate num_traits as num;++pub extern crate either;+pub extern crate glamx;+pub extern crate simba;++#[macro_use]+mod macros;++pub mod bounding_volume;+pub mod mass_properties;+pub mod math;+pub mod partitioning;+pub mod query;+pub mod shape;+#[cfg(feature = "alloc")]+pub mod transformation;+pub mod utils;++mod simd {+ // The `wide` types fall back to scalar code on targets without SIMD, so+ // they are always used, whatever the platform.++ // 8-lane SIMD (f32 only; simba has no `WideF64x8`). Opt-in via `simd8`.+ // Requires an AVX-enabled target (`RUSTFLAGS="-C target-feature=+avx2,+fma"`+ // or `-C target-cpu=native`) for the compiler to actually emit 256-bit+ // instructions; otherwise it runs (correctly) as two 128-bit halves.+ #[cfg(all(feature = "simd8", feature = "f32"))]+ pub use simba::simd::{WideBoolF32x8 as SimdBool, WideF32x8 as SimdReal};++ // 4-lane SIMD (default width).+ #[cfg(all(not(feature = "simd8"), feature = "f32"))]+ pub use simba::simd::{WideBoolF32x4 as SimdBool, WideF32x4 as SimdReal};++ // f64 stays 4-lane regardless of `simd8` (no 8-lane f64 type in simba).+ #[cfg(feature = "f64")]+ pub use simba::simd::{WideBoolF64x4 as SimdBool, WideF64x4 as SimdReal};++ /// The number of lanes of a SIMD number.+ #[cfg(all(feature = "simd8", feature = "f32"))]+ pub const SIMD_WIDTH: usize = 8;+ /// SIMD_WIDTH - 1+ #[cfg(all(feature = "simd8", feature = "f32"))]+ pub const SIMD_LAST_INDEX: usize = 7;++ /// The number of lanes of a SIMD number.+ #[cfg(not(all(feature = "simd8", feature = "f32")))]+ pub const SIMD_WIDTH: usize = 4;+ /// SIMD_WIDTH - 1+ #[cfg(not(all(feature = "simd8", feature = "f32")))]+ pub const SIMD_LAST_INDEX: usize = 3;+}diff --git a/renderer/third_party/parry3d/src/macros.rs b/renderer/third_party/parry3d/src/macros.rsnew file mode 100644index 0000000..5f54ef4--- /dev/null+++ b/renderer/third_party/parry3d/src/macros.rs@@ -0,0 +1,94 @@+/// Inner implementation of [`for_each_dim!`]. A tt-muncher that replaces every+/// occurrence of the sentinel `[ii]` in the token stream with `.$f` (i.e. `.x`,+/// `.y`, or `.z`) for the current dimension.+#[doc(hidden)]+macro_rules! for_each_dim_inner {+ // Base case: no more input tokens, emit accumulated output.+ ($f:ident [$($out:tt)*]) => { $($out)* };++ // Match the [ii] sentinel and replace with .field_name.+ ($f:ident [$($out:tt)*] [ii] $($rest:tt)*) => {+ for_each_dim_inner!($f [$($out)* . $f] $($rest)*)+ };++ // Recurse into `{ }` delimited groups.+ ($f:ident [$($out:tt)*] { $($inner:tt)* } $($rest:tt)*) => {+ for_each_dim_inner!($f [$($out)* { for_each_dim_inner!($f [] $($inner)*) }] $($rest)*)+ };++ // Recurse into `( )` delimited groups.+ ($f:ident [$($out:tt)*] ( $($inner:tt)* ) $($rest:tt)*) => {+ for_each_dim_inner!($f [$($out)* ( for_each_dim_inner!($f [] $($inner)*) )] $($rest)*)+ };++ // Recurse into `[ ]` delimited groups (general case, NOT [ii]).+ ($f:ident [$($out:tt)*] [ $($inner:tt)* ] $($rest:tt)*) => {+ for_each_dim_inner!($f [$($out)* [ for_each_dim_inner!($f [] $($inner)*) ]] $($rest)*)+ };++ // Pass through any other token unchanged.+ ($f:ident [$($out:tt)*] $other:tt $($rest:tt)*) => {+ for_each_dim_inner!($f [$($out)* $other] $($rest)*)+ };+}++/// Unrolls a loop over spatial dimensions (2 or 3 depending on features),+/// replacing occurrences of the sentinel `[ii]` with direct field access+/// (`.x`, `.y`, `.z`) on glam vectors. This avoids bracket indexing which+/// is not supported on SPIR-V targets.+///+/// # Usage+///+/// Basic form — every `[ii]` in the body is replaced with `.x`, `.y`, `.z`+/// in successive unrolled iterations:+/// ```ignore+/// for_each_dim! {+/// min[ii] = a[ii].min(b[ii]);+/// }+/// // Expands to:+/// // min.x = a.x.min(b.x);+/// // min.y = a.y.min(b.y);+/// // min.z = a.z.min(b.z); // only in 3D+/// ```+///+/// With a dimension index (provided as a `const usize`):+/// ```ignore+/// for_each_dim! { i =>+/// if mask & (1 << i) != 0 {+/// result[ii] = -result[ii];+/// }+/// }+/// ```+///+/// # Limitations+///+/// - The sentinel `[ii]` is replaced **everywhere** it appears in the body,+/// so avoid using `[ii]` for other purposes inside the macro.+macro_rules! for_each_dim {+ ($i:ident => $($body:tt)*) => {{+ #[cfg(feature = "dim2")]+ {+ { const $i: usize = 0; for_each_dim_inner!(x [] $($body)*); }+ { const $i: usize = 1; for_each_dim_inner!(y [] $($body)*); }+ }+ #[cfg(feature = "dim3")]+ {+ { const $i: usize = 0; for_each_dim_inner!(x [] $($body)*); }+ { const $i: usize = 1; for_each_dim_inner!(y [] $($body)*); }+ { const $i: usize = 2; for_each_dim_inner!(z [] $($body)*); }+ }+ }};+ ($($body:tt)*) => {{+ #[cfg(feature = "dim2")]+ {+ for_each_dim_inner!(x [] $($body)*);+ for_each_dim_inner!(y [] $($body)*);+ }+ #[cfg(feature = "dim3")]+ {+ for_each_dim_inner!(x [] $($body)*);+ for_each_dim_inner!(y [] $($body)*);+ for_each_dim_inner!(z [] $($body)*);+ }+ }};+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mass_properties.rs b/renderer/third_party/parry3d/src/mass_properties/mass_properties.rsnew file mode 100644index 0000000..f6738d3--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mass_properties.rs@@ -0,0 +1,789 @@+use crate::math::{AngVector, AngularInertia, Pose, Real, Rotation, Vector};+#[cfg(feature = "dim3")]+use crate::math::{MatExt, Matrix, VectorExt};+use crate::utils;+use core::ops::{Add, AddAssign, Sub, SubAssign};+use num::Zero;++#[cfg_attr(feature = "f32", expect(clippy::unnecessary_cast))]+const EPSILON: Real = f32::EPSILON as Real;++#[derive(Copy, Clone, Debug, Default, PartialEq)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+/// The mass properties of a rigid body.+///+/// Mass properties define how an object responds to forces and torques in physics+/// simulation. They include the mass, center of mass, and angular inertia (resistance+/// to rotation).+///+/// # Fields+///+/// - **local_com**: Center of mass in the shape's local coordinate system+/// - **inv_mass**: Inverse mass (1/mass). Zero = infinite mass (immovable)+/// - **inv_principal_inertia**: Inverse angular inertia along principal axes+/// - **principal_inertia_local_frame** (3D only): Rotation to principal inertia axes+///+/// # Why Inverse Values?+///+/// Physics engines store inverse mass and inertia because:+/// - Infinite mass/inertia (immovable objects) = zero inverse+/// - Avoids division in the simulation loop (multiply by inverse instead)+/// - More numerically stable for very heavy objects+///+/// # Angular Inertia+///+/// Angular inertia (moment of inertia) describes resistance to rotation:+/// - **Higher values**: Harder to spin (like a heavy wheel)+/// - **Lower values**: Easier to spin (like a light rod)+/// - **Different per axis**: Objects resist rotation differently around different axes+///+/// # Principal Inertia+///+/// The inertia tensor is diagonalized to principal axes:+/// - Rotation around principal axes is independent+/// - Simplifies physics calculations+/// - In 2D: Only one axis (perpendicular to the plane)+/// - In 3D: Three orthogonal axes+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::mass_properties::MassProperties;+/// use parry3d::shape::{Ball, Shape};+/// use parry3d::math::Vector;+///+/// // Compute mass properties for a unit ball with density 1.0+/// let ball = Ball::new(1.0);+/// let props = ball.mass_properties(1.0);+///+/// // Mass of a unit sphere with density 1.0+/// let mass = props.mass();+/// println!("Mass: {}", mass);+///+/// // Center of mass (at origin for a ball)+/// assert_eq!(props.local_com, Vector::ZERO);+///+/// // For simulation, use inverse values+/// if props.inv_mass > 0.0 {+/// // Object has finite mass - can be moved+/// println!("Can apply forces");+/// } else {+/// // Object has infinite mass - immovable (like terrain)+/// println!("Static/kinematic object");+/// }+/// # }+/// ```+///+/// # Combining Mass Properties+///+/// Mass properties can be added to create compound objects:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::mass_properties::MassProperties;+/// use parry3d::shape::{Ball, Cuboid, Shape};+/// use parry3d::math::Vector;+///+/// let ball = Ball::new(1.0);+/// let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+///+/// let ball_props = ball.mass_properties(1.0);+/// let cuboid_props = cuboid.mass_properties(1.0);+///+/// // Combined properties (ball + cuboid)+/// let combined = ball_props + cuboid_props;+///+/// // Total mass is sum of individual masses+/// let total_mass = combined.mass();+/// println!("Combined mass: {}", total_mass);+/// # }+/// ```+pub struct MassProperties {+ /// The center of mass in local (shape-relative) coordinates.+ ///+ /// This is the balance point of the object. For symmetric shapes, it's typically+ /// at the geometric center. All angular inertia calculations are relative to this point.+ pub local_com: Vector,++ /// The inverse of the mass (1 / mass).+ ///+ /// - **Positive value**: Normal object with finite mass+ /// - **Zero**: Infinite mass (immovable/static object)+ ///+ /// To get the actual mass, use `mass()` method or compute `1.0 / inv_mass`.+ pub inv_mass: Real,++ /// The inverse of the principal angular inertia values.+ ///+ /// These are the angular inertia values along the principal inertia axes:+ /// - **2D**: Single scalar value (rotation around perpendicular axis)+ /// - **3D**: Vector of three values (rotation around X, Y, Z principal axes)+ ///+ /// Angular inertia relative to the center of mass (`local_com`).+ /// Zero components indicate infinite inertia (no rotation) along that axis.+ pub inv_principal_inertia: AngVector,++ #[cfg(feature = "dim3")]+ /// The rotation from local coordinates to principal inertia axes (3D only).+ ///+ /// This rotation aligns the object's coordinate system with its principal+ /// axes of inertia, where the inertia tensor is diagonal.+ pub principal_inertia_local_frame: Rotation,+}++impl MassProperties {+ /// Creates mass properties from center of mass, mass, and angular inertia (2D).+ ///+ /// # Arguments+ ///+ /// * `local_com` - Center of mass in local coordinates+ /// * `mass` - The mass (positive value, use 0.0 for infinite mass)+ /// * `principal_inertia` - Angular inertia around the perpendicular axis+ ///+ /// # Example (2D)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::mass_properties::MassProperties;+ /// use parry2d::math::Vector;+ ///+ /// // Create mass properties for a 10kg object+ /// let props = MassProperties::new(+ /// Vector::ZERO, // Centered at origin+ /// 10.0, // 10kg mass+ /// 5.0 // Angular inertia+ /// );+ ///+ /// assert_eq!(props.mass(), 10.0);+ /// assert_eq!(props.inv_mass, 0.1); // 1/10+ /// # }+ /// ```+ #[cfg(feature = "dim2")]+ pub fn new(local_com: Vector, mass: Real, principal_inertia: Real) -> Self {+ let inv_mass = utils::inv(mass);+ let inv_principal_inertia = utils::inv(principal_inertia);+ Self {+ local_com,+ inv_mass,+ inv_principal_inertia,+ }+ }++ /// Initializes the mass properties from the given center-of-mass, mass, and principal angular inertia.+ ///+ /// The center-of-mass is specified in the local-space of the rigid-body.+ /// The principal angular inertia are the angular inertia along the coordinate axes in the local-space+ /// of the rigid-body.+ #[cfg(feature = "dim3")]+ pub fn new(local_com: Vector, mass: Real, principal_inertia: AngVector) -> Self {+ Self::with_principal_inertia_frame(local_com, mass, principal_inertia, Rotation::IDENTITY)+ }++ /// Initializes the mass properties from the given center-of-mass, mass, and principal angular inertia.+ ///+ /// The center-of-mass is specified in the local-space of the rigid-body.+ /// The principal angular inertia are the angular inertia along the coordinate axes defined by+ /// the `principal_inertia_local_frame` expressed in the local-space of the rigid-body.+ #[cfg(feature = "dim3")]+ pub fn with_principal_inertia_frame(+ local_com: Vector,+ mass: Real,+ principal_inertia: AngVector,+ principal_inertia_local_frame: Rotation,+ ) -> Self {+ let inv_mass = utils::inv(mass);+ let inv_principal_inertia = principal_inertia.map(utils::inv);+ Self {+ local_com,+ inv_mass,+ inv_principal_inertia,+ principal_inertia_local_frame,+ }+ }++ /// Initialize a new `MassProperties` from a given center-of-mass, mass, and angular inertia matrix.+ ///+ /// The angular inertia matrix will be diagonalized in order to extract the principal inertia+ /// values and principal inertia frame.+ #[cfg(feature = "dim3")]+ pub fn with_inertia_matrix(local_com: Vector, mass: Real, inertia: Matrix) -> Self {+ let mut eigen = inertia.symmetric_eigen();+ if eigen.eigenvectors.determinant() < 0.0 {+ eigen.eigenvectors.swap_cols(1, 2);+ eigen.eigenvalues.as_mut().swap(1, 2);+ }+ let eigenvectors = eigen.eigenvectors;+ let principal_inertia_local_frame = Rotation::from_mat3(&eigenvectors).normalize();++ // Drop negative eigenvalues.+ let principal_inertia = eigen.eigenvalues.map(|e| e.max(0.0));++ Self::with_principal_inertia_frame(+ local_com,+ mass,+ principal_inertia,+ principal_inertia_local_frame,+ )+ }++ /// The mass.+ pub fn mass(&self) -> Real {+ utils::inv(self.inv_mass)+ }++ /// The angular inertia along the principal inertia axes and center of mass of the rigid-body.+ pub fn principal_inertia(&self) -> AngVector {+ #[cfg(feature = "dim2")]+ return utils::inv(self.inv_principal_inertia);+ #[cfg(feature = "dim3")]+ return self.inv_principal_inertia.map(utils::inv);+ }++ /// The world-space center of mass of the rigid-body.+ pub fn world_com(&self, pos: &Pose) -> Vector {+ pos * self.local_com+ }++ #[cfg(feature = "dim2")]+ /// The world-space inverse angular inertia tensor of the rigid-body.+ pub fn world_inv_inertia(&self, _rot: &Rotation) -> AngularInertia {+ self.inv_principal_inertia+ }++ #[cfg(feature = "dim3")]+ /// The world-space inverse angular inertia tensor of the rigid-body.+ pub fn world_inv_inertia(&self, rot: &Rotation) -> AngularInertia {+ if self.inv_principal_inertia != Vector::ZERO {+ let mut lhs = Matrix::from_quat(rot * self.principal_inertia_local_frame);+ let rhs = lhs.transpose();+ lhs.x_axis *= self.inv_principal_inertia.x;+ lhs.y_axis *= self.inv_principal_inertia.y;+ lhs.z_axis *= self.inv_principal_inertia.z;+ let inertia = lhs * rhs;+ AngularInertia::from_sdp_matrix(inertia)+ } else {+ AngularInertia::zero()+ }+ }++ #[cfg(feature = "dim3")]+ /// Reconstructs the inverse angular inertia tensor of the rigid body from its principal inertia values and axes.+ pub fn reconstruct_inverse_inertia_matrix(&self) -> Matrix {+ let inv_principal_inertia = self.inv_principal_inertia;+ let rot_mat = Matrix::from_quat(self.principal_inertia_local_frame);+ let inv_rot_mat = Matrix::from_quat(self.principal_inertia_local_frame.inverse());++ rot_mat * Matrix::from_diagonal(inv_principal_inertia) * inv_rot_mat+ }++ #[cfg(feature = "dim3")]+ /// Reconstructs the angular inertia tensor of the rigid body from its principal inertia values and axes.+ pub fn reconstruct_inertia_matrix(&self) -> Matrix {+ let principal_inertia = self.inv_principal_inertia.map(utils::inv);+ let rot_mat = Matrix::from_quat(self.principal_inertia_local_frame);+ let inv_rot_mat = Matrix::from_quat(self.principal_inertia_local_frame.inverse());+ rot_mat * Matrix::from_diagonal(principal_inertia) * inv_rot_mat+ }++ #[cfg(feature = "dim2")]+ pub(crate) fn construct_shifted_inertia_matrix(&self, shift: Vector) -> Real {+ let i = utils::inv(self.inv_principal_inertia);++ if self.inv_mass != 0.0 {+ let mass = 1.0 / self.inv_mass;+ i + shift.length_squared() * mass+ } else {+ i+ }+ }++ #[cfg(feature = "dim3")]+ pub(crate) fn construct_shifted_inertia_matrix(&self, shift: Vector) -> Matrix {+ let matrix = self.reconstruct_inertia_matrix();++ if self.inv_mass != 0.0 {+ let mass = 1.0 / self.inv_mass;+ let diag = shift.length_squared();+ let diagm = Matrix::from_diagonal(Vector::splat(diag));+ matrix + (diagm - shift.kronecker(shift)) * mass+ } else {+ matrix+ }+ }++ /// Transform each element of the mass properties.+ pub fn transform_by(&self, m: &Pose) -> Self {+ // NOTE: we don't apply the parallel axis theorem here+ // because the center of mass is also transformed.+ Self {+ local_com: m * self.local_com,+ inv_mass: self.inv_mass,+ inv_principal_inertia: self.inv_principal_inertia,+ #[cfg(feature = "dim3")]+ principal_inertia_local_frame: m.rotation * self.principal_inertia_local_frame,+ }+ }++ /// Changes the mass on these mass-properties.+ ///+ /// The `adjust_angular_inertia` argument should always be `true`, unless+ /// there are some specific reasons not to do so. Setting this to `true`+ /// will automatically adjust the angular inertia of `self` to account+ /// for the mass change (i.e. it will multiply the angular inertia by+ /// `new_mass / prev_mass`). Setting it to `false` will not change the+ /// current angular inertia.+ pub fn set_mass(&mut self, new_mass: Real, adjust_angular_inertia: bool) {+ let new_inv_mass = utils::inv(new_mass);++ if adjust_angular_inertia {+ let curr_mass = utils::inv(self.inv_mass);+ self.inv_principal_inertia *= new_inv_mass * curr_mass;+ }++ self.inv_mass = new_inv_mass;+ }+}++impl Zero for MassProperties {+ fn zero() -> Self {+ Self {+ inv_mass: 0.0,+ #[cfg(feature = "dim2")]+ inv_principal_inertia: 0.0,+ #[cfg(feature = "dim3")]+ inv_principal_inertia: Vector::ZERO,+ #[cfg(feature = "dim3")]+ principal_inertia_local_frame: Rotation::IDENTITY,+ local_com: Vector::ZERO,+ }+ }++ fn is_zero(&self) -> bool {+ *self == Self::zero()+ }+}++impl Sub<MassProperties> for MassProperties {+ type Output = Self;++ #[cfg(feature = "dim2")]+ fn sub(self, other: MassProperties) -> Self {+ if self.is_zero() || other.is_zero() {+ return self;+ }++ let m1 = utils::inv(self.inv_mass);+ let m2 = utils::inv(other.inv_mass);++ let mut new_mass = m1 - m2;++ if new_mass < EPSILON {+ // Account for small numerical errors.+ new_mass = 0.0;+ }++ let inv_mass = utils::inv(new_mass);++ let local_com = (self.local_com * m1 - other.local_com * m2) * inv_mass;+ let i1 = self.construct_shifted_inertia_matrix(local_com - self.local_com);+ let i2 = other.construct_shifted_inertia_matrix(local_com - other.local_com);+ let mut inertia = i1 - i2;++ if inertia < EPSILON {+ // Account for small numerical errors.+ inertia = 0.0;+ }++ // NOTE: we drop the negative eigenvalues that may result from subtraction rounding errors.+ let inv_principal_inertia = utils::inv(inertia);++ Self {+ local_com,+ inv_mass,+ inv_principal_inertia,+ }+ }++ #[cfg(feature = "dim3")]+ fn sub(self, other: MassProperties) -> Self {+ if self.is_zero() || other.is_zero() {+ return self;+ }++ let m1 = utils::inv(self.inv_mass);+ let m2 = utils::inv(other.inv_mass);+ let mut new_mass = m1 - m2;++ if new_mass < EPSILON {+ new_mass = 0.0;+ }++ let inv_mass = utils::inv(new_mass);+ let local_com = (self.local_com * m1 - other.local_com * m2) * inv_mass;+ let i1 = self.construct_shifted_inertia_matrix(local_com - self.local_com);+ let i2 = other.construct_shifted_inertia_matrix(local_com - other.local_com);+ let inertia = i1 - i2;+ Self::with_inertia_matrix(local_com, new_mass, inertia)+ }+}++impl SubAssign<MassProperties> for MassProperties {+ fn sub_assign(&mut self, rhs: MassProperties) {+ *self = *self - rhs+ }+}++impl Add<MassProperties> for MassProperties {+ type Output = Self;++ #[cfg(feature = "dim2")]+ fn add(self, other: MassProperties) -> Self {+ if self.is_zero() {+ return other;+ } else if other.is_zero() {+ return self;+ }++ let m1 = utils::inv(self.inv_mass);+ let m2 = utils::inv(other.inv_mass);+ let inv_mass = utils::inv(m1 + m2);+ let local_com = (self.local_com * m1 + other.local_com * m2) * inv_mass;+ let i1 = self.construct_shifted_inertia_matrix(local_com - self.local_com);+ let i2 = other.construct_shifted_inertia_matrix(local_com - other.local_com);+ let inertia = i1 + i2;+ let inv_principal_inertia = utils::inv(inertia);++ Self {+ local_com,+ inv_mass,+ inv_principal_inertia,+ }+ }++ #[cfg(feature = "dim3")]+ fn add(self, other: MassProperties) -> Self {+ if self.is_zero() {+ return other;+ } else if other.is_zero() {+ return self;+ }++ let m1 = utils::inv(self.inv_mass);+ let m2 = utils::inv(other.inv_mass);+ let inv_mass = utils::inv(m1 + m2);+ let local_com = (self.local_com * m1 + other.local_com * m2) * inv_mass;+ let i1 = self.construct_shifted_inertia_matrix(local_com - self.local_com);+ let i2 = other.construct_shifted_inertia_matrix(local_com - other.local_com);+ let inertia = i1 + i2;++ Self::with_inertia_matrix(local_com, m1 + m2, inertia)+ }+}++impl AddAssign<MassProperties> for MassProperties {+ fn add_assign(&mut self, rhs: MassProperties) {+ *self = *self + rhs+ }+}++#[cfg(feature = "alloc")]+impl core::iter::Sum<MassProperties> for MassProperties {+ #[cfg(feature = "dim2")]+ fn sum<I>(iter: I) -> Self+ where+ I: Iterator<Item = Self>,+ {+ use alloc::vec::Vec;++ let mut total_mass = 0.0;+ let mut total_com = Vector::ZERO;+ let mut total_inertia = 0.0;+ // TODO: avoid this allocation.+ // This is needed because we iterate twice.+ let mut all_props = Vec::new();++ for props in iter {+ let mass = utils::inv(props.inv_mass);+ total_mass += mass;+ total_com += props.local_com * mass;+ all_props.push(props);+ }++ if total_mass > 0.0 {+ total_com /= total_mass;+ }++ for props in all_props {+ total_inertia += props.construct_shifted_inertia_matrix(total_com - props.local_com);+ }++ Self {+ local_com: total_com,+ inv_mass: utils::inv(total_mass),+ inv_principal_inertia: utils::inv(total_inertia),+ }+ }++ #[cfg(feature = "dim3")]+ fn sum<I>(iter: I) -> Self+ where+ I: Iterator<Item = Self>,+ {+ use alloc::vec::Vec;++ let mut total_mass = 0.0;+ let mut total_com = Vector::ZERO;+ let mut total_inertia = Matrix::ZERO;+ // TODO: avoid this allocation.+ // This is needed because we iterate twice.+ let mut all_props = Vec::new();++ for props in iter {+ let mass = utils::inv(props.inv_mass);+ total_mass += mass;+ total_com += props.local_com * mass;+ all_props.push(props);+ }++ if total_mass > 0.0 {+ total_com /= total_mass;+ }++ let total_com = total_com;+ for props in all_props {+ total_inertia += props.construct_shifted_inertia_matrix(total_com - props.local_com);+ }++ Self::with_inertia_matrix(total_com, total_mass, total_inertia)+ }+}++impl approx::AbsDiffEq for MassProperties {+ type Epsilon = Real;+ fn default_epsilon() -> Self::Epsilon {+ Real::default_epsilon()+ }++ fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {+ #[cfg(feature = "dim2")]+ let inertia_is_ok = self+ .inv_principal_inertia+ .abs_diff_eq(&other.inv_principal_inertia, epsilon);++ #[cfg(feature = "dim3")]+ let inertia_is_ok = self+ .reconstruct_inverse_inertia_matrix()+ .abs_diff_eq(other.reconstruct_inverse_inertia_matrix(), epsilon);++ inertia_is_ok+ && self.local_com.abs_diff_eq(other.local_com, epsilon)+ && self.inv_mass.abs_diff_eq(&other.inv_mass, epsilon)+ }+}++#[cfg(feature = "alloc")] // TODO: this is a workaround because the `approx` feature of `glam` cannot be enabled on spirv targets.+impl approx::RelativeEq for MassProperties {+ fn default_max_relative() -> Self::Epsilon {+ Real::default_max_relative()+ }++ fn relative_eq(+ &self,+ other: &Self,+ epsilon: Self::Epsilon,+ max_relative: Self::Epsilon,+ ) -> bool {+ #[cfg(feature = "dim2")]+ let inertia_is_ok = self.inv_principal_inertia.relative_eq(+ &other.inv_principal_inertia,+ epsilon,+ max_relative,+ );++ // Compare either the inertia matrix or its inverse, whichever is most precise.+ #[cfg(feature = "dim3")]+ let inertia_is_ok = self.reconstruct_inverse_inertia_matrix().relative_eq(+ &other.reconstruct_inverse_inertia_matrix(),+ epsilon,+ max_relative,+ ) || self.reconstruct_inertia_matrix().relative_eq(+ &other.reconstruct_inertia_matrix(),+ epsilon,+ max_relative,+ );++ inertia_is_ok+ && self+ .local_com+ .relative_eq(&other.local_com, epsilon, max_relative)+ && self+ .inv_mass+ .relative_eq(&other.inv_mass, epsilon, max_relative)+ }+}++#[cfg(test)]+mod test {+ use super::MassProperties;+ #[cfg(feature = "dim3")]+ use crate::math::Rotation;+ use crate::math::{AngVector, Vector};+ use crate::shape::{Ball, Capsule, Shape};+ use approx::assert_relative_eq;+ use num::Zero;++ #[test]+ fn mass_properties_add_partial_zero() {+ let m1 = MassProperties {+ local_com: Vector::ZERO,+ inv_mass: 2.0,+ #[cfg(feature = "dim2")]+ inv_principal_inertia: 0.0,+ #[cfg(feature = "dim3")]+ inv_principal_inertia: Vector::ZERO,+ #[cfg(feature = "dim3")]+ principal_inertia_local_frame: Rotation::IDENTITY,+ };+ let m2 = MassProperties {+ local_com: Vector::ZERO,+ inv_mass: 0.0,+ #[cfg(feature = "dim2")]+ inv_principal_inertia: 1.0,+ #[cfg(feature = "dim3")]+ inv_principal_inertia: Vector::new(3.0, 2.0, 1.0),+ #[cfg(feature = "dim3")]+ principal_inertia_local_frame: Rotation::IDENTITY,+ };+ let result = MassProperties {+ local_com: Vector::ZERO,+ inv_mass: 2.0,+ #[cfg(feature = "dim2")]+ inv_principal_inertia: 1.0,+ #[cfg(feature = "dim3")]+ inv_principal_inertia: Vector::new(3.0, 2.0, 1.0),+ #[cfg(feature = "dim3")]+ // TODO: ideally this should be IDENTITY, but glam’s conversion from matrix+ // to quaternion returns this instead. This is OK for the cube test+ // due to its symmetry though this needs a closer look.+ principal_inertia_local_frame: Rotation::from_xyzw(1.0, 0.0, 0.0, 0.0),+ };++ assert_eq!(m1 + m2, result);+ assert_eq!(m2 + m1, result);+ }++ #[test]+ fn mass_properties_add_sub() {+ // Check that addition and subtraction of mass properties behave as expected.+ let c1 = Capsule::new_x(1.0, 2.0);+ let c2 = Capsule::new_y(3.0, 4.0);+ let c3 = Ball::new(2.0);++ let m1 = c1.mass_properties(1.0);+ let m2 = c2.mass_properties(1.0);+ let m3 = c3.mass_properties(1.0);+ let m1m2m3 = m1 + m2 + m3;++ assert_relative_eq!(m1 + m2, m2 + m1, epsilon = 1.0e-6);+ assert_relative_eq!(m1m2m3 - m1, m2 + m3, epsilon = 1.0e-6);+ assert_relative_eq!(m1m2m3 - m2, m1 + m3, epsilon = 1.0e-6);+ assert_relative_eq!(m1m2m3 - m3, m1 + m2, epsilon = 1.0e-6);+ assert_relative_eq!(m1m2m3 - (m1 + m2), m3, epsilon = 1.0e-5);+ assert_relative_eq!(m1m2m3 - (m1 + m3), m2, epsilon = 1.0e-6);+ assert_relative_eq!(m1m2m3 - (m2 + m3), m1, epsilon = 1.0e-6);+ assert_relative_eq!(m1m2m3 - m1 - m2, m3, epsilon = 1.0e-5);+ assert_relative_eq!(m1m2m3 - m1 - m3, m2, epsilon = 1.0e-6);+ assert_relative_eq!(m1m2m3 - m2 - m3, m1, epsilon = 1.0e-6);+ assert_relative_eq!(m1m2m3 - m2 - m3, m1, epsilon = 1.0e-6);++ // NOTE: converting the inverse inertia matrices don't work well here because+ // tiny inertia value originating from the subtraction can result in a non-zero+ // (but large) inverse.+ assert_relative_eq!(+ (((m1m2m3 - m1) - m2) - m3).principal_inertia(),+ AngVector::default(),+ epsilon = 1.0e-2+ );+ assert_relative_eq!((((m1m2m3 - m1) - m2) - m3).mass(), 0.0, epsilon = 1.0e-6);+ }++ #[test]+ #[cfg(feature = "alloc")]+ fn mass_properties_compound() {+ use crate::{+ math::{Pose, Vector},+ shape::{Compound, Cuboid, SharedShape},+ };++ // Compute the mass properties of a compound shape made of three 1x1x1 cuboids.+ let shape = Cuboid::new(Vector::splat(0.5));+ let mp = shape.mass_properties(1.0);+ let iso2 = Pose::from_parts(Vector::Y.into(), Default::default());+ let iso3 = Pose::from_parts((-Vector::Y).into(), Default::default());++ // Test sum shifted result through `MassProperties::add`+ let sum = [mp, mp.transform_by(&iso2), mp.transform_by(&iso3)]+ .into_iter()+ .sum::<MassProperties>();++ // Test compound through `MassProperties::from_compound`+ let compound_shape = Compound::new(vec![+ (+ Pose::from_parts(Vector::default().into(), Default::default()),+ SharedShape::new(shape),+ ),+ (iso2, SharedShape::new(shape)),+ (iso3, SharedShape::new(shape)),+ ]);+ let mp_compound = compound_shape.mass_properties(1.0);++ // Check that the mass properties of the compound shape match the mass properties+ // of a single 1x3x1 cuboid.+ #[cfg(feature = "dim2")]+ let expected = Cuboid::new(Vector::new(1.5, 0.5)).mass_properties(1.0);+ #[cfg(feature = "dim3")]+ let expected = Cuboid::new(Vector::new(1.5, 0.5, 0.5)).mass_properties(1.0);++ // Sum shifted+ assert_relative_eq!(sum.local_com, expected.local_com, epsilon = 1.0e-6);+ assert_relative_eq!(sum.inv_mass, expected.inv_mass, epsilon = 1.0e-6);+ #[cfg(feature = "dim3")]+ assert!(sum+ .inv_principal_inertia+ .abs_diff_eq(expected.inv_principal_inertia, 1.0e-6));+ #[cfg(feature = "dim2")]+ assert_relative_eq!(+ sum.inv_principal_inertia,+ expected.inv_principal_inertia,+ epsilon = 1.0e-6+ );++ // Compound+ assert_relative_eq!(mp_compound.local_com, expected.local_com, epsilon = 1.0e-6);+ assert_relative_eq!(mp_compound.inv_mass, expected.inv_mass, epsilon = 1.0e-6);+ #[cfg(feature = "dim3")]+ assert!(mp_compound+ .inv_principal_inertia+ .abs_diff_eq(expected.inv_principal_inertia, 1.0e-6));+ #[cfg(feature = "dim2")]+ assert_relative_eq!(+ mp_compound.inv_principal_inertia,+ expected.inv_principal_inertia,+ epsilon = 1.0e-6+ );+ }++ #[test]+ #[cfg(feature = "alloc")]+ fn mass_properties_sum_no_nan() {+ let mp: MassProperties = [MassProperties::zero()].iter().copied().sum();+ assert!(!mp.local_com.x.is_nan() && !mp.local_com.y.is_nan());+ #[cfg(feature = "dim3")]+ assert!(!mp.local_com.z.is_nan());+ }+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mass_properties_ball.rs b/renderer/third_party/parry3d/src/mass_properties/mass_properties_ball.rsnew file mode 100644index 0000000..8a07185--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mass_properties_ball.rs@@ -0,0 +1,115 @@+use crate::mass_properties::MassProperties;+use crate::math::{PrincipalAngularInertia, Real, RealField, Vector};++impl MassProperties {+ pub(crate) fn ball_volume_unit_angular_inertia(+ radius: Real,+ ) -> (Real, PrincipalAngularInertia) {+ #[cfg(feature = "dim2")]+ {+ let volume = Real::pi() * radius * radius;+ let i = radius * radius / 2.0;+ (volume, i)+ }+ #[cfg(feature = "dim3")]+ {+ let volume = Real::pi() * radius * radius * radius * 4.0 / 3.0;+ let i = radius * radius * 2.0 / 5.0;++ (volume, Vector::splat(i))+ }+ }++ /// Computes the mass properties of a ball (sphere in 3D, circle in 2D).+ ///+ /// A ball is a perfectly round geometric shape defined by its radius. This function+ /// calculates the physical properties needed for physics simulation, including mass,+ /// center of mass, and angular inertia (resistance to rotation).+ ///+ /// # Arguments+ ///+ /// * `density` - The material density (mass per unit volume/area). Higher values make heavier objects.+ /// - In 3D: units are typically kg/m³ (e.g., water = 1000, steel = 7850)+ /// - In 2D: units are typically kg/m² (mass per unit area)+ /// * `radius` - The radius of the ball (distance from center to surface)+ ///+ /// # Returns+ ///+ /// A `MassProperties` struct containing:+ /// - **mass**: Total mass calculated from volume and density+ /// - **local_com**: Center of mass at the origin (balls are perfectly symmetric)+ /// - **inv_principal_inertia**: Inverse angular inertia (resistance to spinning)+ ///+ /// # Physics Background+ ///+ /// Balls have uniform density and perfect symmetry, which means:+ /// - The center of mass is at the geometric center (origin)+ /// - All rotational axes have the same angular inertia (isotropic)+ /// - In 3D: moment of inertia = (2/5) * mass * radius²+ /// - In 2D: moment of inertia = (1/2) * mass * radius²+ ///+ /// # Example (3D)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::math::Vector;+ ///+ /// // Create mass properties for a 0.5m radius ball with density 1000 kg/m³ (water density)+ /// let radius = 0.5;+ /// let density = 1000.0;+ /// let ball_props = MassProperties::from_ball(density, radius);+ ///+ /// // Volume of sphere: (4/3) * π * r³ = 0.524 m³+ /// // Mass: volume * density = 524 kg+ /// let mass = ball_props.mass();+ /// assert!((mass - 523.6).abs() < 1.0); // Approximately 524 kg+ ///+ /// // Center of mass is at the origin for symmetric shapes+ /// assert_eq!(ball_props.local_com, Vector::ZERO);+ ///+ /// // Check if object can be moved (finite mass)+ /// assert!(ball_props.inv_mass > 0.0, "Ball has finite mass and can move");+ /// # }+ /// ```+ ///+ /// # Example (2D)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::mass_properties::MassProperties;+ /// use parry2d::math::Vector;+ ///+ /// // Create a circular disc with 1.0m radius and density 100 kg/m²+ /// let radius = 1.0;+ /// let density = 100.0;+ /// let circle_props = MassProperties::from_ball(density, radius);+ ///+ /// // Area of circle: π * r² = 3.14 m²+ /// // Mass: area * density = 314 kg+ /// let mass = circle_props.mass();+ /// assert!((mass - 314.159).abs() < 0.1); // Approximately 314 kg+ ///+ /// println!("Circle mass: {:.2} kg", mass);+ /// println!("Moment of inertia: {:.2}", circle_props.principal_inertia());+ /// # }+ /// ```+ ///+ /// # Use Cases+ ///+ /// - **Sports balls**: Soccer balls, basketballs, bowling balls+ /// - **Planets and celestial bodies**: Spherical approximations+ /// - **Particles**: Vector-like objects with rotational inertia+ /// - **Wheels and gears**: Cylindrical objects in 2D simulations+ ///+ /// # Performance Note+ ///+ /// This is a very fast computation (constant time) as it only involves basic arithmetic+ /// with the radius and density. Balls are the simplest shape for collision detection+ /// and physics simulation.+ pub fn from_ball(density: Real, radius: Real) -> Self {+ let (vol, unit_i) = Self::ball_volume_unit_angular_inertia(radius);+ let mass = vol * density;+ Self::new(Vector::ZERO, mass, unit_i * mass)+ }+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mass_properties_capsule.rs b/renderer/third_party/parry3d/src/mass_properties/mass_properties_capsule.rsnew file mode 100644index 0000000..4bf2fb0--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mass_properties_capsule.rs@@ -0,0 +1,158 @@+use crate::mass_properties::MassProperties;+use crate::math::{Real, Vector};+#[cfg(feature = "dim3")]+use crate::shape::Capsule;++impl MassProperties {+ /// Computes the mass properties of a capsule (pill-shaped object).+ ///+ /// A capsule is a cylinder with hemispherical caps on both ends. It's defined by two+ /// endpoint centers (a line segment) and a radius. Capsules are commonly used for+ /// character controllers and elongated objects because they provide smooth collision+ /// handling without sharp edges.+ ///+ /// # Arguments+ ///+ /// * `density` - The material density (mass per unit volume/area). Higher values make heavier objects.+ /// - In 3D: units are typically kg/m³+ /// - In 2D: units are typically kg/m² (mass per unit area)+ /// * `a` - First endpoint of the capsule's central axis (center of first hemisphere)+ /// * `b` - Second endpoint of the capsule's central axis (center of second hemisphere)+ /// * `radius` - The radius of the capsule (distance from the axis to the surface)+ ///+ /// # Returns+ ///+ /// A `MassProperties` struct containing:+ /// - **mass**: Total mass calculated from volume and density+ /// - **local_com**: Center of mass at the midpoint between `a` and `b`+ /// - **inv_principal_inertia**: Inverse angular inertia (varies by axis)+ /// - **principal_inertia_local_frame** (3D only): Rotation aligning capsule axis with Y+ ///+ /// # Physics Background+ ///+ /// A capsule consists of:+ /// - A cylindrical body connecting the two endpoints+ /// - Two hemispherical caps (which together form one complete sphere)+ /// - The total length is: `distance(a, b) + 2 * radius`+ /// - Mass and inertia are computed by combining cylinder + sphere components+ ///+ /// # Example (3D) - Character Controller+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::math::Vector;+ ///+ /// // Create a capsule for a standing character (height ~2m, radius 0.3m)+ /// // Endpoints at (0, 0, 0) and (0, 2, 0) form vertical capsule+ /// let a = Vector::ZERO;+ /// let b = Vector::new(0.0, 2.0, 0.0);+ /// let radius = 0.3;+ /// let density = 985.0; // Similar to human body density+ ///+ /// let character_props = MassProperties::from_capsule(density, a, b, radius);+ ///+ /// // Center of mass is at the midpoint+ /// let expected_com = Vector::new(0.0, 1.0, 0.0);+ /// assert!((character_props.local_com - expected_com).length() < 0.01);+ ///+ /// let mass = character_props.mass();+ /// println!("Character mass: {:.2} kg", mass); // Approximately 70-80 kg+ ///+ /// // Inertia is higher around horizontal axes (harder to tip over)+ /// let inertia = character_props.principal_inertia();+ /// println!("Inertia X: {:.2}, Y: {:.2}, Z: {:.2}", inertia.x, inertia.y, inertia.z);+ /// # }+ /// ```+ ///+ /// # Example (3D) - Horizontal Capsule (Lying Down)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::math::Vector;+ ///+ /// // Create a horizontal capsule along the X-axis+ /// let a = Vector::new(-1.0, 0.0, 0.0);+ /// let b = Vector::new(1.0, 0.0, 0.0);+ /// let radius = 0.5;+ /// let density = 1000.0;+ ///+ /// let capsule_props = MassProperties::from_capsule(density, a, b, radius);+ ///+ /// // Center of mass at midpoint (origin)+ /// assert_eq!(capsule_props.local_com, Vector::ZERO);+ ///+ /// // Total length = distance + 2*radius = 2.0 + 1.0 = 3.0 meters+ /// println!("Mass: {:.2} kg", capsule_props.mass());+ /// # }+ /// ```+ ///+ /// # Example (2D) - Stadium Shape+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::mass_properties::MassProperties;+ /// use parry2d::math::Vector;+ ///+ /// // Create a horizontal 2D capsule (stadium/discorectangle shape)+ /// let a = Vector::new(-2.0, 0.0);+ /// let b = Vector::new(2.0, 0.0);+ /// let radius = 1.0;+ /// let density = 100.0; // kg/m²+ ///+ /// let stadium_props = MassProperties::from_capsule(density, a, b, radius);+ ///+ /// println!("Stadium mass: {:.2} kg", stadium_props.mass());+ /// println!("Moment of inertia: {:.2}", stadium_props.principal_inertia());+ /// # }+ /// ```+ ///+ /// # Use Cases+ ///+ /// - **Character controllers**: Humanoid characters, NPCs+ /// - **Vehicles**: Simplified car or boat bodies+ /// - **Projectiles**: Bullets, missiles, arrows+ /// - **Limbs**: Arms, legs in ragdoll physics+ /// - **Cylinders with rounded ends**: Pipes, rods, poles+ ///+ /// # Common Mistakes+ ///+ /// - **Total length confusion**: The visual length is `distance(a, b) + 2 * radius`,+ /// not just `distance(a, b)`. The hemispheres add extra length.+ /// - **Endpoint placement**: Vectors `a` and `b` are centers of the hemispherical caps,+ /// not the extreme ends of the capsule.+ ///+ /// # Performance Note+ ///+ /// Capsules are very efficient for collision detection (almost as fast as spheres)+ /// and provide smooth rolling behavior. They're preferred over cylinders for+ /// dynamic objects that need to move smoothly.+ pub fn from_capsule(density: Real, a: Vector, b: Vector, radius: Real) -> Self {+ let half_height = (b - a).length() / 2.0;+ let (cyl_vol, cyl_unit_i) = Self::cylinder_y_volume_unit_inertia(half_height, radius);+ let (ball_vol, ball_unit_i) = Self::ball_volume_unit_angular_inertia(radius);+ let cap_vol = cyl_vol + ball_vol;+ let cap_mass = cap_vol * density;+ let mut cap_i = (cyl_unit_i * cyl_vol + ball_unit_i * ball_vol) * density;+ let local_com = a.midpoint(b);++ #[cfg(feature = "dim2")]+ {+ let h = half_height * 2.0;+ let extra = (h * h * 0.25 + h * radius * 3.0 / 8.0) * ball_vol * density;+ cap_i += extra;+ Self::new(local_com, cap_mass, cap_i)+ }++ #[cfg(feature = "dim3")]+ {+ let h = half_height * 2.0;+ let extra = (h * h * 0.25 + h * radius * 3.0 / 8.0) * ball_vol * density;+ cap_i.x += extra;+ cap_i.z += extra;+ let local_frame = Capsule::new(a, b, radius).rotation_wrt_y();+ Self::with_principal_inertia_frame(local_com, cap_mass, cap_i, local_frame)+ }+ }+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mass_properties_compound.rs b/renderer/third_party/parry3d/src/mass_properties/mass_properties_compound.rsnew file mode 100644index 0000000..0f0eeb0--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mass_properties_compound.rs@@ -0,0 +1,166 @@+use crate::mass_properties::MassProperties;+use crate::math::{Pose, Real};+use crate::shape::SharedShape;++impl MassProperties {+ /// Computes the mass properties of a compound shape (combination of multiple shapes).+ ///+ /// A compound shape is a collection of sub-shapes, each with its own position and+ /// orientation. This function computes the mass properties of each sub-shape,+ /// transforms them to their local positions, and combines them using the parallel+ /// axis theorem to get the total mass properties.+ ///+ /// # Arguments+ ///+ /// * `density` - The material density applied to all sub-shapes+ /// - In 3D: kg/m³ (mass per unit volume)+ /// - In 2D: kg/m² (mass per unit area)+ /// * `shapes` - Array of (position, shape) pairs+ /// - Each shape has an `Pose` (position + rotation)+ /// - Shapes can be any type implementing the `Shape` trait+ ///+ /// # Returns+ ///+ /// A `MassProperties` struct containing:+ /// - **mass**: Sum of all sub-shape masses+ /// - **local_com**: Combined center of mass (mass-weighted average)+ /// - **inv_principal_inertia**: Combined angular inertia+ ///+ /// # Physics Background+ ///+ /// The parallel axis theorem is used to shift inertia tensors:+ /// - Each shape's mass properties are computed in its local frame+ /// - Properties are transformed to the compound's coordinate system+ /// - Center of mass is the mass-weighted average of all sub-shapes+ /// - Angular inertia accounts for both local rotation and offset from COM+ ///+ /// # Example (3D) - Dumbbell+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::shape::{Ball, SharedShape};+ /// use parry3d::math::{Pose, Vector};+ ///+ /// // Create a dumbbell: two balls connected by a bar+ /// let ball = SharedShape::new(Ball::new(0.5));+ /// let bar = SharedShape::new(parry3d::shape::Cuboid::new(Vector::new(0.1, 1.0, 0.1)));+ ///+ /// let shapes = vec![+ /// (Pose::translation(0.0, -1.0, 0.0), ball.clone()), // Left ball+ /// (Pose::identity(), bar), // Center bar+ /// (Pose::translation(0.0, 1.0, 0.0), ball), // Right ball+ /// ];+ ///+ /// let density = 1000.0;+ /// let dumbbell_props = MassProperties::from_compound(density, &shapes);+ ///+ /// println!("Dumbbell mass: {:.2} kg", dumbbell_props.mass());+ /// println!("Center of mass: {:?}", dumbbell_props.local_com);+ ///+ /// // Dumbbell has high inertia around X and Z (hard to spin end-over-end)+ /// // but low inertia around Y (easy to spin along the bar)+ /// let inertia = dumbbell_props.principal_inertia();+ /// println!("Inertia: X={:.3}, Y={:.3}, Z={:.3}", inertia.x, inertia.y, inertia.z);+ /// # }+ /// ```+ ///+ /// # Example (2D) - Table+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::mass_properties::MassProperties;+ /// use parry2d::shape::{Cuboid, SharedShape};+ /// use parry2d::math::{Pose, Vector};+ ///+ /// // Create a simple table: top surface + legs+ /// let top = SharedShape::new(Cuboid::new(Vector::new(2.0, 0.1))); // Wide, thin top+ /// let leg = SharedShape::new(Cuboid::new(Vector::new(0.1, 0.5))); // Narrow, tall leg+ ///+ /// let shapes = vec![+ /// (Pose::translation(0.0, 0.6), top), // Table top+ /// (Pose::translation(-1.5, 0.0), leg.clone()), // Left leg+ /// (Pose::translation(1.5, 0.0), leg), // Right leg+ /// ];+ ///+ /// let density = 500.0; // Wood+ /// let table_props = MassProperties::from_compound(density, &shapes);+ ///+ /// println!("Table mass: {:.2} kg", table_props.mass());+ /// # }+ /// ```+ ///+ /// # Example (3D) - Robot Arm+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::shape::{Capsule, Cuboid, SharedShape};+ /// use parry3d::math::{Pose, Vector};+ ///+ /// // Simple robot arm with multiple segments+ /// let base = SharedShape::new(Cuboid::new(Vector::new(0.3, 0.2, 0.3)));+ /// let upper_arm = SharedShape::new(Capsule::new(+ /// Vector::ZERO,+ /// Vector::new(0.0, 1.0, 0.0),+ /// 0.1+ /// ));+ /// let forearm = SharedShape::new(Capsule::new(+ /// Vector::ZERO,+ /// Vector::new(0.0, 0.8, 0.0),+ /// 0.08+ /// ));+ ///+ /// let shapes = vec![+ /// (Pose::identity(), base),+ /// (Pose::translation(0.0, 0.2, 0.0), upper_arm),+ /// (Pose::translation(0.0, 1.2, 0.0), forearm),+ /// ];+ ///+ /// let density = 2700.0; // Aluminum+ /// let arm_props = MassProperties::from_compound(density, &shapes);+ ///+ /// println!("Robot arm mass: {:.2} kg", arm_props.mass());+ /// println!("Arm center of mass: {:?}", arm_props.local_com);+ /// # }+ /// ```+ ///+ /// # Use Cases+ ///+ /// - **Complex objects**: Multi-part objects (tables, chairs, vehicles)+ /// - **Articulated bodies**: Robot arms, character skeletons+ /// - **Assemblies**: Combining simple shapes into complex forms+ /// - **Non-convex shapes**: Convex decomposition results+ /// - **Hierarchical structures**: Nested compound shapes+ ///+ /// # Different Densities+ ///+ /// To use different densities for different parts:+ ///+ /// ```ignore+ /// // Compute each part separately with its own density+ /// let heavy_part = ball_shape.mass_properties(5000.0).transform_by(&pos1);+ /// let light_part = cuboid_shape.mass_properties(100.0).transform_by(&pos2);+ ///+ /// // Combine manually+ /// let total = heavy_part + light_part;+ /// ```+ ///+ /// # Performance Note+ ///+ /// The computation time is O(n) where n is the number of sub-shapes. Each shape's+ /// mass properties are computed once and then combined. This is efficient even for+ /// large numbers of shapes.+ ///+ /// # See Also+ ///+ /// - `MassProperties::transform_by()`: Transform mass properties to a new frame+ /// - `Add` trait: Combine mass properties with `+` operator+ /// - `Sum` trait: Sum an iterator of mass properties+ pub fn from_compound(density: Real, shapes: &[(Pose, SharedShape)]) -> Self {+ shapes+ .iter()+ .map(|s| s.1.mass_properties(density).transform_by(&s.0))+ .sum()+ }+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mass_properties_cone.rs b/renderer/third_party/parry3d/src/mass_properties/mass_properties_cone.rsnew file mode 100644index 0000000..4a94819--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mass_properties_cone.rs@@ -0,0 +1,181 @@+use crate::mass_properties::MassProperties;+use crate::math::{PrincipalAngularInertia, Real, RealField, Rotation, Vector};++impl MassProperties {+ pub(crate) fn cone_y_volume_unit_inertia(+ half_height: Real,+ radius: Real,+ ) -> (Real, PrincipalAngularInertia) {+ let volume = radius * radius * Real::pi() * half_height * 2.0 / 3.0;+ let sq_radius = radius * radius;+ let sq_height = half_height * half_height * 4.0;+ let off_principal = sq_radius * 3.0 / 20.0 + sq_height * 3.0 / 80.0;+ let principal = sq_radius * 3.0 / 10.0;++ (volume, Vector::new(off_principal, principal, off_principal))+ }++ /// Computes the mass properties of a cone (3D only).+ ///+ /// A cone is a 3D shape with a circular base and a point (apex) at the top, aligned+ /// along the Y-axis. The base is at y = -half_height, the apex is at y = +half_height,+ /// and the center of the base is at the origin.+ ///+ /// # Arguments+ ///+ /// * `density` - The material density in kg/m³ (mass per unit volume)+ /// * `half_height` - Half the total height of the cone (center to apex/base)+ /// * `radius` - The radius of the circular base+ ///+ /// # Returns+ ///+ /// A `MassProperties` struct containing:+ /// - **mass**: Total mass calculated from volume and density+ /// - **local_com**: Center of mass at `(0, -half_height/2, 0)` - shifted toward the base+ /// - **inv_principal_inertia**: Inverse angular inertia (varies by axis)+ /// - **principal_inertia_local_frame**: Identity rotation (aligned with Y-axis)+ ///+ /// # Physics Background+ ///+ /// Cones have unique mass distribution due to tapering shape:+ /// - Volume = (1/3) × π × radius² × height+ /// - Center of mass is NOT at the geometric center+ /// - Center of mass is located 1/4 of the height from the base (toward the base)+ /// - The wider base contains more mass than the narrow top+ /// - Angular inertia around Y-axis (spinning): I_y = (3/10) × mass × radius²+ /// - Angular inertia around X/Z axes: includes both base radius and height terms+ ///+ /// # Example - Traffic Cone+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::math::Vector;+ ///+ /// // Standard traffic cone: 70cm tall, 30cm base diameter+ /// // Made of flexible plastic, density ~950 kg/m³+ /// let half_height = 0.35; // 70cm / 2 = 35cm+ /// let radius = 0.15; // 30cm / 2 = 15cm+ /// let density = 950.0;+ ///+ /// let cone_props = MassProperties::from_cone(density, half_height, radius);+ ///+ /// let mass = cone_props.mass();+ /// println!("Traffic cone mass: {:.3} kg", mass); // About 1-2 kg+ ///+ /// // Center of mass is shifted toward the base (negative Y)+ /// let com_y = cone_props.local_com.y;+ /// println!("Center of mass Y: {:.3} m", com_y);+ /// assert!(com_y < 0.0, "COM should be below origin, toward the base");+ /// assert!((com_y - (-half_height / 2.0)).abs() < 0.01);+ /// # }+ /// ```+ ///+ /// # Example - Ice Cream Cone+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ ///+ /// // Small ice cream cone (wafer): 12cm tall, 5cm diameter+ /// let half_height = 0.06; // 6cm+ /// let radius = 0.025; // 2.5cm+ /// let density = 400.0; // Wafer is light and porous+ ///+ /// let wafer_props = MassProperties::from_cone(density, half_height, radius);+ ///+ /// // Volume = (1/3) × π × (0.025)² × 0.12 ≈ 0.0000785 m³+ /// let mass = wafer_props.mass();+ /// println!("Wafer mass: {:.1} grams", mass * 1000.0); // About 30 grams+ /// # }+ /// ```+ ///+ /// # Example - Center of Mass Position+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ ///+ /// // Demonstrate that COM is 1/4 height from base+ /// let half_height = 2.0;+ /// let radius = 1.0;+ /// let density = 1000.0;+ ///+ /// let cone_props = MassProperties::from_cone(density, half_height, radius);+ ///+ /// // Base is at y = -2.0, apex is at y = +2.0+ /// // COM should be at y = -2.0 + (4.0 / 4.0) = -1.0+ /// // Or equivalently: y = -half_height / 2 = -1.0+ /// let expected_com_y = -half_height / 2.0;+ /// assert!((cone_props.local_com.y - expected_com_y).abs() < 0.001);+ /// println!("Base at: {}", -half_height);+ /// println!("Apex at: {}", half_height);+ /// println!("COM at: {:.3}", cone_props.local_com.y);+ /// # }+ /// ```+ ///+ /// # Example - Cone vs Cylinder Comparison+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ ///+ /// let half_height = 1.0;+ /// let radius = 0.5;+ /// let density = 1000.0;+ ///+ /// let cone = MassProperties::from_cone(density, half_height, radius);+ /// let cylinder = MassProperties::from_cylinder(density, half_height, radius);+ ///+ /// // Cone has 1/3 the volume of a cylinder with same dimensions+ /// println!("Cone mass: {:.2} kg", cone.mass());+ /// println!("Cylinder mass: {:.2} kg", cylinder.mass());+ /// assert!((cylinder.mass() / cone.mass() - 3.0).abs() < 0.1);+ ///+ /// // Cone's COM is offset, cylinder's is at origin+ /// println!("Cone COM Y: {:.3}", cone.local_com.y);+ /// println!("Cylinder COM Y: {:.3}", cylinder.local_com.y);+ /// # }+ /// ```+ ///+ /// # Use Cases+ ///+ /// - **Traffic cones**: Road safety markers+ /// - **Funnels**: Pouring devices+ /// - **Party hats**: Conical decorations+ /// - **Volcanic mountains**: Natural cone-shaped terrain+ /// - **Rocket noses**: Aerodynamic cone shapes+ /// - **Drills and bits**: Conical tool tips+ ///+ /// # Important Notes+ ///+ /// - **Orientation**: Cone points upward (+Y), base is downward (-Y)+ /// - **Asymmetric COM**: Unlike cylinder or ball, center of mass is NOT at origin+ /// - **Volume**: Remember it's only 1/3 of an equivalent cylinder's volume+ /// - **Base position**: The base center is at the origin, not the geometric center+ ///+ /// # Common Mistakes+ ///+ /// - **Expecting COM at origin**: The center of mass is shifted toward the base by+ /// `half_height/2` in the negative Y direction+ /// - **Confusing orientation**: The apex points in +Y direction, base faces -Y+ /// - **Volume estimation**: Cone volume is much smaller than you might expect+ /// (only 1/3 of a cylinder with the same dimensions)+ ///+ /// # Performance Note+ ///+ /// Cone collision detection is moderately expensive due to the tapered shape and+ /// curved surface. For simpler simulations, consider using a cylinder or compound+ /// shape approximation.+ pub fn from_cone(density: Real, half_height: Real, radius: Real) -> Self {+ let (cyl_vol, cyl_unit_i) = Self::cone_y_volume_unit_inertia(half_height, radius);+ let cyl_mass = cyl_vol * density;++ Self::with_principal_inertia_frame(+ Vector::new(0.0, -half_height / 2.0, 0.0),+ cyl_mass,+ cyl_unit_i * cyl_mass,+ Rotation::IDENTITY,+ )+ }+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mass_properties_convex_polygon.rs b/renderer/third_party/parry3d/src/mass_properties/mass_properties_convex_polygon.rsnew file mode 100644index 0000000..5f510e1--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mass_properties_convex_polygon.rs@@ -0,0 +1,188 @@+use crate::mass_properties::MassProperties;+use crate::math::{Real, Vector};+use crate::shape::Triangle;++impl MassProperties {+ /// Computes the mass properties of a convex polygon (2D only).+ ///+ /// A convex polygon is a 2D shape where all interior angles are less than 180 degrees+ /// and all vertices point outward. This function decomposes the polygon into triangles+ /// from the center of mass and sums their mass properties.+ ///+ /// # Arguments+ ///+ /// * `density` - The material density in kg/m² (mass per unit area)+ /// * `vertices` - A slice of points defining the polygon vertices+ /// - Must form a convex shape+ /// - Vertices should be ordered counter-clockwise+ /// - At least 3 vertices required+ ///+ /// # Returns+ ///+ /// A `MassProperties` struct containing:+ /// - **mass**: Total mass calculated from area and density+ /// - **local_com**: Center of mass (weighted average of triangle centroids)+ /// - **inv_principal_inertia**: Inverse angular inertia (scalar in 2D)+ ///+ /// # Physics Background+ ///+ /// The algorithm:+ /// 1. Computes the geometric center of all vertices+ /// 2. Creates triangles from the center to each edge+ /// 3. Calculates area and inertia for each triangle+ /// 4. Combines results using weighted averages+ ///+ /// # Example - Pentagon+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::mass_properties::MassProperties;+ /// use parry2d::math::Vector;+ /// use std::f32::consts::PI;+ ///+ /// // Create a regular pentagon with radius 1.0+ /// let mut vertices = Vec::new();+ /// for i in 0..5 {+ /// let angle = (i as f32) * 2.0 * PI / 5.0;+ /// vertices.push(Vector::new(angle.cos(), angle.sin()));+ /// }+ ///+ /// let density = 100.0;+ /// let pentagon_props = MassProperties::from_convex_polygon(density, &vertices);+ ///+ /// println!("Pentagon mass: {:.2} kg", pentagon_props.mass());+ /// println!("Center of mass: {:?}", pentagon_props.local_com);+ ///+ /// // For a regular polygon centered at origin, COM should be near origin+ /// assert!(pentagon_props.local_com.length() < 0.01);+ /// # }+ /// ```+ ///+ /// # Example - Trapezoid+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::mass_properties::MassProperties;+ /// use parry2d::math::Vector;+ ///+ /// // Create a trapezoid (4 vertices)+ /// let vertices = vec![+ /// Vector::ZERO, // Bottom left+ /// Vector::new(4.0, 0.0), // Bottom right+ /// Vector::new(3.0, 2.0), // Top right+ /// Vector::new(1.0, 2.0), // Top left+ /// ];+ ///+ /// let density = 50.0;+ /// let trap_props = MassProperties::from_convex_polygon(density, &vertices);+ ///+ /// // Area of trapezoid = ((b1 + b2) / 2) × h = ((4 + 2) / 2) × 2 = 6 m²+ /// // Mass = area × density = 300 kg+ /// let mass = trap_props.mass();+ /// println!("Trapezoid mass: {:.2} kg", mass);+ /// # }+ /// ```+ ///+ /// # Example - Custom Convex Shape+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::mass_properties::MassProperties;+ /// use parry2d::math::Vector;+ ///+ /// // Arbitrary convex polygon+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(2.0, 0.0),+ /// Vector::new(3.0, 1.0),+ /// Vector::new(2.0, 2.5),+ /// Vector::new(0.0, 2.0),+ /// ];+ ///+ /// let density = 200.0;+ /// let props = MassProperties::from_convex_polygon(density, &vertices);+ ///+ /// println!("Custom polygon mass: {:.2} kg", props.mass());+ /// println!("Moment of inertia: {:.2}", props.principal_inertia());+ /// # }+ /// ```+ ///+ /// # Use Cases+ ///+ /// - **Custom 2D shapes**: Game objects with specific geometry+ /// - **Simplified collision**: Convex approximations of complex shapes+ /// - **Platforms**: Angled or irregular platforms in 2D games+ /// - **Polygonal wheels**: Multi-sided rotating objects+ /// - **Terrain segments**: Ground pieces with varying slopes+ ///+ /// # Important Requirements+ ///+ /// - **Must be convex**: Non-convex (concave) polygons will produce incorrect results+ /// - **Vertex ordering**: Counter-clockwise order is conventional but either works+ /// - **Minimum vertices**: At least 3 vertices (forms a triangle)+ /// - **No self-intersection**: Vertices must not cross each other+ ///+ /// # For Non-Convex Shapes+ ///+ /// If your polygon is concave (not convex):+ /// 1. Use convex decomposition algorithms to break it into convex parts+ /// 2. Compute mass properties for each convex part+ /// 3. Combine using `from_compound()` or by summing MassProperties+ ///+ /// Alternatively, use `from_trimesh()` with a triangulated version of the shape.+ ///+ /// # Performance Note+ ///+ /// Computation time is O(n) where n is the number of vertices. The polygon is+ /// decomposed into n triangles, each processed independently.+ pub fn from_convex_polygon(density: Real, vertices: &[Vector]) -> MassProperties {+ let (area, com) = convex_polygon_area_and_center_of_mass(vertices);++ if area == 0.0 {+ return MassProperties::new(com, 0.0, 0.0);+ }++ let mut itot = 0.0;++ let mut iterpeek = vertices.iter().peekable();+ let first_element = *iterpeek.peek().unwrap(); // store first element to close the cycle in the end with unwrap_or+ while let Some(elem) = iterpeek.next() {+ let triangle = Triangle::new(com, *elem, **iterpeek.peek().unwrap_or(&first_element));+ let area = triangle.area();+ let ipart = triangle.unit_angular_inertia();+ itot += ipart * area;+ }++ Self::new(com, area * density, itot * density)+ }+}++/// Computes the area and center-of-mass of a convex polygon.+pub fn convex_polygon_area_and_center_of_mass(convex_polygon: &[Vector]) -> (Real, Vector) {+ let mut geometric_center = convex_polygon.iter().fold(Vector::ZERO, |e1, e2| e1 + e2);+ geometric_center /= convex_polygon.len() as Real;+ let mut res = Vector::ZERO;+ let mut areasum = 0.0;++ let mut iterpeek = convex_polygon.iter().peekable();+ let first_element = *iterpeek.peek().unwrap(); // Stores first element to close the cycle in the end with unwrap_or.+ while let Some(elem) = iterpeek.next() {+ let (a, b, c) = (+ elem,+ iterpeek.peek().unwrap_or(&first_element),+ &geometric_center,+ );+ let area = Triangle::new(*a, **b, *c).area();+ let center = (*a + **b + *c) / 3.0;++ res += center * area;+ areasum += area;+ }++ if areasum == 0.0 {+ (areasum, geometric_center)+ } else {+ res /= areasum;+ (areasum, res)+ }+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mass_properties_convex_polyhedron.rs b/renderer/third_party/parry3d/src/mass_properties/mass_properties_convex_polyhedron.rsnew file mode 100644index 0000000..5af7aac--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mass_properties_convex_polyhedron.rs@@ -0,0 +1,128 @@+use crate::mass_properties::MassProperties;+use crate::math::{Real, Vector, DIM};++impl MassProperties {+ /// Computes the mass properties of a convex polyhedron (3D) or polygon (2D).+ ///+ /// A convex polyhedron is a 3D solid where all faces are flat and all vertices point+ /// outward. This is a convenience function that delegates to `from_trimesh()`, which+ /// handles the actual computation by treating the polyhedron as a triangle mesh.+ ///+ /// # Arguments+ ///+ /// * `density` - The material density+ /// - In 3D: kg/m³ (mass per unit volume)+ /// - In 2D: kg/m² (mass per unit area)+ /// * `vertices` - Array of vertex positions defining the polyhedron+ /// * `indices` - Array of triangle indices+ /// - In 3D: Each element is `[u32; 3]` indexing into vertices array+ /// - In 2D: Each element is `[u32; 2]` for line segments+ ///+ /// # Returns+ ///+ /// A `MassProperties` struct containing:+ /// - **mass**: Total mass calculated from volume/area and density+ /// - **local_com**: Center of mass (volume-weighted centroid)+ /// - **inv_principal_inertia**: Inverse angular inertia tensor+ ///+ /// # Example (3D) - Tetrahedron+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::math::Vector;+ ///+ /// // Create a regular tetrahedron (4 vertices, 4 triangular faces)+ /// let vertices = vec![+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 1.0),+ /// Vector::ZERO,+ /// ];+ ///+ /// let indices = vec![+ /// [0, 1, 2], // Face 1+ /// [0, 1, 3], // Face 2+ /// [0, 2, 3], // Face 3+ /// [1, 2, 3], // Face 4+ /// ];+ ///+ /// let density = 1000.0;+ /// let tetra_props = MassProperties::from_convex_polyhedron(density, &vertices, &indices);+ ///+ /// println!("Tetrahedron mass: {:.4} kg", tetra_props.mass());+ /// println!("Center of mass: {:?}", tetra_props.local_com);+ /// # }+ /// ```+ ///+ /// # Example (3D) - Octahedron+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::math::Vector;+ ///+ /// // Regular octahedron (6 vertices, 8 triangular faces)+ /// let vertices = vec![+ /// Vector::new(1.0, 0.0, 0.0), // +X+ /// Vector::new(-1.0, 0.0, 0.0), // -X+ /// Vector::new(0.0, 1.0, 0.0), // +Y+ /// Vector::new(0.0, -1.0, 0.0), // -Y+ /// Vector::new(0.0, 0.0, 1.0), // +Z+ /// Vector::new(0.0, 0.0, -1.0), // -Z+ /// ];+ ///+ /// let indices = vec![+ /// [0, 2, 4], [0, 4, 3], [0, 3, 5], [0, 5, 2], // Right hemisphere+ /// [1, 4, 2], [1, 3, 4], [1, 5, 3], [1, 2, 5], // Left hemisphere+ /// ];+ ///+ /// let density = 800.0;+ /// let octa_props = MassProperties::from_convex_polyhedron(density, &vertices, &indices);+ ///+ /// println!("Octahedron mass: {:.2} kg", octa_props.mass());+ /// # }+ /// ```+ ///+ /// # Use Cases+ ///+ /// - **Custom 3D shapes**: Game objects with specific polyhedral geometry+ /// - **Crystalline structures**: Geometric solids (tetrahedra, octahedra, dodecahedra)+ /// - **Simplified models**: Convex approximations of complex shapes+ /// - **Gems and jewels**: Faceted objects+ /// - **Dice**: Polyhedral game dice (d4, d6, d8, d12, d20)+ ///+ /// # Requirements+ ///+ /// - **Must be convex**: All faces must be flat and point outward+ /// - **Closed mesh**: Triangles must form a watertight volume+ /// - **Consistent winding**: Triangle vertices should follow consistent order+ /// (counter-clockwise when viewed from outside)+ /// - **Valid indices**: All index values must be < vertices.len()+ ///+ /// # Convex vs Non-Convex+ ///+ /// This function assumes the shape is convex. For non-convex (concave) meshes:+ /// - The result may be incorrect+ /// - Consider using `from_compound()` with a convex decomposition+ /// - Or use `from_trimesh()` directly (handles both convex and concave)+ ///+ /// # Implementation Note+ ///+ /// This function is a thin wrapper around `from_trimesh()`. Both produce identical+ /// results. Use `from_convex_polyhedron()` when you know the shape is convex to+ /// make intent clear in code.+ ///+ /// # See Also+ ///+ /// - `from_trimesh()`: For general triangle meshes (convex or concave)+ /// - `from_convex_polygon()`: For 2D convex polygons+ /// - `from_compound()`: For combining multiple convex shapes+ pub fn from_convex_polyhedron(+ density: Real,+ vertices: &[Vector],+ indices: &[[u32; DIM]],+ ) -> MassProperties {+ Self::from_trimesh(density, vertices, indices)+ }+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mass_properties_cuboid.rs b/renderer/third_party/parry3d/src/mass_properties/mass_properties_cuboid.rsnew file mode 100644index 0000000..3f17022--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mass_properties_cuboid.rs@@ -0,0 +1,155 @@+use crate::mass_properties::MassProperties;+use crate::math::{PrincipalAngularInertia, Real, Vector};++impl MassProperties {+ pub(crate) fn cuboid_volume_unit_inertia(+ half_extents: Vector,+ ) -> (Real, PrincipalAngularInertia) {+ #[cfg(feature = "dim2")]+ {+ let volume = half_extents.x * half_extents.y * 4.0;+ let ix = (half_extents.x * half_extents.x) / 3.0;+ let iy = (half_extents.y * half_extents.y) / 3.0;++ (volume, ix + iy)+ }++ #[cfg(feature = "dim3")]+ {+ let volume = half_extents.x * half_extents.y * half_extents.z * 8.0;+ let ix = (half_extents.x * half_extents.x) / 3.0;+ let iy = (half_extents.y * half_extents.y) / 3.0;+ let iz = (half_extents.z * half_extents.z) / 3.0;++ (volume, Vector::new(iy + iz, ix + iz, ix + iy))+ }+ }++ /// Computes the mass properties of a cuboid (box in 3D, rectangle in 2D).+ ///+ /// A cuboid is a box-shaped object with three dimensions (or two in 2D), where each+ /// dimension can have a different size. The cuboid is centered at the origin, and+ /// `half_extents` define the distance from the center to each face.+ ///+ /// # Arguments+ ///+ /// * `density` - The material density (mass per unit volume/area). Higher values make heavier objects.+ /// - In 3D: units are typically kg/m³ (e.g., wood = 500-900, concrete = 2400)+ /// - In 2D: units are typically kg/m² (mass per unit area)+ /// * `half_extents` - Half the size along each axis (center to face distance).+ /// - In 3D: `Vector::new(hx, hy, hz)` creates a box with dimensions 2hx × 2hy × 2hz+ /// - In 2D: `Vector::new(hx, hy)` creates a rectangle with dimensions 2hx × 2hy+ ///+ /// # Returns+ ///+ /// A `MassProperties` struct containing:+ /// - **mass**: Total mass calculated from volume and density+ /// - **local_com**: Center of mass at the origin (cuboids are symmetric)+ /// - **inv_principal_inertia**: Inverse angular inertia along each axis+ ///+ /// # Physics Background+ ///+ /// Cuboids have axis-aligned mass distribution:+ /// - Center of mass is at the geometric center (origin)+ /// - Angular inertia varies per axis based on dimensions+ /// - Longer dimensions increase inertia around perpendicular axes+ /// - In 3D, each axis has different inertia: I_x depends on y and z extents, etc.+ ///+ /// # Example (3D) - Wooden Crate+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::math::Vector;+ ///+ /// // Create a wooden crate: 2m × 1m × 1m (half_extents = 1.0, 0.5, 0.5)+ /// // Wood density: approximately 600 kg/m³+ /// let half_extents = Vector::new(1.0, 0.5, 0.5);+ /// let density = 600.0;+ /// let crate_props = MassProperties::from_cuboid(density, half_extents);+ ///+ /// // Volume = (2 * 1.0) × (2 * 0.5) × (2 * 0.5) = 2 m³+ /// // Mass = volume × density = 1200 kg+ /// let mass = crate_props.mass();+ /// assert!((mass - 1200.0).abs() < 0.1);+ ///+ /// // Longer dimension (x-axis) means higher inertia around y and z axes+ /// let inertia = crate_props.principal_inertia();+ /// println!("Inertia around x-axis: {:.2}", inertia.x); // Lowest (easier to spin around length)+ /// println!("Inertia around y-axis: {:.2}", inertia.y); // Higher+ /// println!("Inertia around z-axis: {:.2}", inertia.z); // Higher+ ///+ /// // Center of mass is at the origin+ /// assert_eq!(crate_props.local_com, Vector::ZERO);+ /// # }+ /// ```+ ///+ /// # Example (3D) - Cube+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::math::Vector;+ ///+ /// // Create a 1m × 1m × 1m cube (half_extents = 0.5 on all axes)+ /// let half_extents = Vector::new(0.5, 0.5, 0.5);+ /// let density = 1000.0; // Water density+ /// let cube_props = MassProperties::from_cuboid(density, half_extents);+ ///+ /// // Volume = 1 m³, Mass = 1000 kg+ /// assert!((cube_props.mass() - 1000.0).abs() < 0.1);+ ///+ /// // For a cube, all axes have equal inertia (symmetric)+ /// let inertia = cube_props.principal_inertia();+ /// assert!((inertia.x - inertia.y).abs() < 0.01);+ /// assert!((inertia.y - inertia.z).abs() < 0.01);+ /// # }+ /// ```+ ///+ /// # Example (2D) - Rectangular Platform+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::mass_properties::MassProperties;+ /// use parry2d::math::Vector;+ ///+ /// // Create a 4m × 2m rectangular platform (half_extents = 2.0, 1.0)+ /// let half_extents = Vector::new(2.0, 1.0);+ /// let density = 500.0; // kg/m²+ /// let platform_props = MassProperties::from_cuboid(density, half_extents);+ ///+ /// // Area = (2 * 2.0) × (2 * 1.0) = 8 m²+ /// // Mass = area × density = 4000 kg+ /// let mass = platform_props.mass();+ /// assert!((mass - 4000.0).abs() < 0.1);+ ///+ /// println!("Platform mass: {:.2} kg", mass);+ /// println!("Moment of inertia: {:.2}", platform_props.principal_inertia());+ /// # }+ /// ```+ ///+ /// # Use Cases+ ///+ /// - **Boxes and crates**: Storage containers, shipping boxes+ /// - **Building blocks**: Walls, floors, platforms+ /// - **Vehicles**: Simplified car or truck bodies+ /// - **Furniture**: Tables, chairs, cabinets+ /// - **Terrain**: Rectangular ground segments+ ///+ /// # Common Mistakes+ ///+ /// - **Wrong dimensions**: Remember that `half_extents` are HALF the total size.+ /// For a 2m × 2m × 2m box, use `Vector::new(1.0, 1.0, 1.0)`, not `(2.0, 2.0, 2.0)`+ /// - **Unit confusion**: Ensure density units match your distance units+ /// (kg/m³ with meters, kg/cm³ with centimeters, etc.)+ ///+ /// # Performance Note+ ///+ /// This is a very fast computation (constant time). Cuboids are the second simplest+ /// shape after balls and are highly efficient for collision detection.+ pub fn from_cuboid(density: Real, half_extents: Vector) -> Self {+ let (vol, unit_i) = Self::cuboid_volume_unit_inertia(half_extents);+ let mass = vol * density;+ Self::new(Vector::ZERO, mass, unit_i * mass)+ }+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mass_properties_cylinder.rs b/renderer/third_party/parry3d/src/mass_properties/mass_properties_cylinder.rsnew file mode 100644index 0000000..53e7802--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mass_properties_cylinder.rs@@ -0,0 +1,180 @@+use crate::mass_properties::MassProperties;+use crate::math::{PrincipalAngularInertia, Real, Vector};+#[cfg(feature = "dim3")]+use crate::math::{RealField, Rotation};++impl MassProperties {+ pub(crate) fn cylinder_y_volume_unit_inertia(+ half_height: Real,+ radius: Real,+ ) -> (Real, PrincipalAngularInertia) {+ #[cfg(feature = "dim2")]+ {+ Self::cuboid_volume_unit_inertia(Vector::new(radius, half_height))+ }++ #[cfg(feature = "dim3")]+ {+ let volume = half_height * radius * radius * Real::pi() * 2.0;+ let sq_radius = radius * radius;+ let sq_height = half_height * half_height * 4.0;+ let off_principal = (sq_radius * 3.0 + sq_height) / 12.0;++ let inertia = Vector::new(off_principal, sq_radius / 2.0, off_principal);+ (volume, inertia)+ }+ }++ /// Computes the mass properties of a cylinder (3D only).+ ///+ /// A cylinder is a 3D shape with circular cross-section and flat ends, aligned along+ /// the Y-axis and centered at the origin. Unlike a capsule, a cylinder has sharp edges+ /// at the top and bottom.+ ///+ /// **Note**: In 2D, this function is used internally but cylinders don't exist as a+ /// distinct 2D shape (rectangles are used instead).+ ///+ /// # Arguments+ ///+ /// * `density` - The material density in kg/m³ (e.g., aluminum = 2700, plastic = 950)+ /// * `half_height` - Half the total height of the cylinder (center to top/bottom)+ /// * `radius` - The radius of the circular cross-section+ ///+ /// # Returns+ ///+ /// A `MassProperties` struct containing:+ /// - **mass**: Total mass calculated from volume and density+ /// - **local_com**: Center of mass at the origin (cylinders are symmetric)+ /// - **inv_principal_inertia**: Inverse angular inertia (different for each axis)+ /// - **principal_inertia_local_frame**: Identity rotation (aligned with Y-axis)+ ///+ /// # Physics Background+ ///+ /// Cylinders have rotational symmetry around the Y-axis:+ /// - Volume = π × radius² × height+ /// - Center of mass is at the geometric center (origin)+ /// - Angular inertia around Y-axis (spinning like a top): I_y = (1/2) × mass × radius²+ /// - Angular inertia around X/Z axes (tipping over): I_x = I_z = (1/12) × mass × (3×radius² + height²)+ /// - Easier to spin around the central axis than to tip over+ ///+ /// # Example - Aluminum Can+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::math::Vector;+ ///+ /// // Standard soda can: 12.3cm tall, 6.6cm diameter+ /// // Aluminum density: ~2700 kg/m³+ /// let half_height = 0.0615; // 6.15 cm in meters+ /// let radius = 0.033; // 3.3 cm in meters+ /// let density = 2700.0;+ ///+ /// let can_props = MassProperties::from_cylinder(density, half_height, radius);+ ///+ /// let mass = can_props.mass();+ /// println!("Can mass: {:.2} kg", mass); // Approximately 0.15 kg (150 grams)+ ///+ /// // Center of mass at origin+ /// assert_eq!(can_props.local_com, Vector::ZERO);+ ///+ /// // Check inertia differences+ /// let inertia = can_props.principal_inertia();+ /// println!("Spin inertia (Y): {:.6}", inertia.y); // Low (easy to spin)+ /// println!("Tip inertia (X): {:.6}", inertia.x); // Higher (harder to tip)+ /// assert!(inertia.y < inertia.x); // Easier to spin than tip+ /// # }+ /// ```+ ///+ /// # Example - Concrete Column+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ ///+ /// // Concrete support column: 3m tall, 0.5m diameter+ /// // Concrete density: ~2400 kg/m³+ /// let half_height = 1.5; // 3m / 2+ /// let radius = 0.25; // 0.5m / 2+ /// let density = 2400.0;+ ///+ /// let column_props = MassProperties::from_cylinder(density, half_height, radius);+ ///+ /// // Volume = π × (0.25)² × 3 = 0.589 m³+ /// // Mass = 0.589 × 2400 = 1414 kg+ /// let mass = column_props.mass();+ /// assert!((mass - 1414.0).abs() < 10.0);+ ///+ /// println!("Column mass: {:.0} kg", mass);+ /// # }+ /// ```+ ///+ /// # Example - Comparing Cylinder vs Capsule+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::math::Vector;+ ///+ /// let half_height = 1.0;+ /// let radius = 0.5;+ /// let density = 1000.0;+ ///+ /// // Cylinder has flat ends (sharp edges)+ /// let cylinder = MassProperties::from_cylinder(density, half_height, radius);+ ///+ /// // Capsule has rounded ends (smooth)+ /// let a = Vector::new(0.0, -half_height, 0.0);+ /// let b = Vector::new(0.0, half_height, 0.0);+ /// let capsule = MassProperties::from_capsule(density, a, b, radius);+ ///+ /// // Capsule has more mass due to hemispherical caps+ /// println!("Cylinder mass: {:.2} kg", cylinder.mass());+ /// println!("Capsule mass: {:.2} kg", capsule.mass());+ /// assert!(capsule.mass() > cylinder.mass());+ /// # }+ /// ```+ ///+ /// # Use Cases+ ///+ /// - **Structural elements**: Columns, pillars, posts+ /// - **Containers**: Cans, drums, barrels, tanks+ /// - **Mechanical parts**: Shafts, pistons, rollers+ /// - **Tree trunks**: Natural cylindrical objects+ /// - **Wheels**: When viewed from the side (use with proper orientation)+ ///+ /// # Cylinder vs Capsule+ ///+ /// **Use Cylinder when**:+ /// - Sharp edges are acceptable or desired+ /// - Object is truly flat-ended (cans, pipes)+ /// - Static/kinematic objects (don't need smooth rolling)+ ///+ /// **Use Capsule when**:+ /// - Smooth collision response is needed+ /// - Object needs to roll or slide smoothly+ /// - Character controllers or dynamic objects+ ///+ /// # Common Mistakes+ ///+ /// - **Wrong axis**: Cylinders are aligned with Y-axis by default. Use+ /// `transform_by()` or create with proper orientation if you need X or Z alignment.+ /// - **Half height confusion**: Total height is `2 × half_height`, not just `half_height`+ ///+ /// # Performance Note+ ///+ /// Cylinder collision detection is more expensive than capsules due to sharp edges,+ /// but still reasonably efficient. For dynamic objects, prefer capsules.+ #[cfg(feature = "dim3")]+ pub fn from_cylinder(density: Real, half_height: Real, radius: Real) -> Self {+ let (cyl_vol, cyl_unit_i) = Self::cylinder_y_volume_unit_inertia(half_height, radius);+ let cyl_mass = cyl_vol * density;++ Self::with_principal_inertia_frame(+ Vector::ZERO,+ cyl_mass,+ cyl_unit_i * cyl_mass,+ Rotation::IDENTITY,+ )+ }+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mass_properties_triangle.rs b/renderer/third_party/parry3d/src/mass_properties/mass_properties_triangle.rsnew file mode 100644index 0000000..67ec48b--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mass_properties_triangle.rs@@ -0,0 +1,183 @@+use crate::mass_properties::MassProperties;+use crate::math::{Real, Vector};+use crate::shape::Triangle;++impl MassProperties {+ /// Computes the mass properties of a triangle.+ ///+ /// A triangle is the simplest polygon, defined by three vertices. In 2D, this represents+ /// a filled triangular region. In 3D, this represents a flat triangular surface with+ /// negligible thickness (useful for thin sheets or as building blocks for meshes).+ ///+ /// # Arguments+ ///+ /// * `density` - The material density (mass per unit area in both 2D and 3D)+ /// - Units are typically kg/m² (surface density)+ /// - For 3D triangles, this represents the density of a thin sheet+ /// * `a`, `b`, `c` - The three vertices of the triangle+ ///+ /// # Returns+ ///+ /// A `MassProperties` struct containing:+ /// - **mass**: Total mass calculated from area and density+ /// - **local_com**: Center of mass at the centroid (average of three vertices)+ /// - **inv_principal_inertia**: Inverse angular inertia+ ///+ /// # Physics Background+ ///+ /// Triangles have specific geometric properties:+ /// - Area (2D): Using cross product of edge vectors+ /// - Area (3D): Same formula, treating triangle as flat surface+ /// - Center of mass: Always at centroid = (a + b + c) / 3+ /// - Angular inertia: Depends on vertex positions relative to centroid+ /// - Degenerate cases: Zero-area triangles (collinear points) return zero mass+ ///+ /// # Example (2D) - Right Triangle+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::mass_properties::MassProperties;+ /// use parry2d::math::Vector;+ ///+ /// // Create a right triangle with legs of 3m and 4m+ /// let a = Vector::ZERO;+ /// let b = Vector::new(3.0, 0.0);+ /// let c = Vector::new(0.0, 4.0);+ /// let density = 100.0; // kg/m²+ ///+ /// let triangle_props = MassProperties::from_triangle(density, a, b, c);+ ///+ /// // Area = (1/2) × base × height = (1/2) × 3 × 4 = 6 m²+ /// // Mass = area × density = 600 kg+ /// let mass = triangle_props.mass();+ /// assert!((mass - 600.0).abs() < 0.1);+ ///+ /// // Center of mass at centroid: (0+3+0)/3, (0+0+4)/3 = (1, 1.333)+ /// let com = triangle_props.local_com;+ /// assert!((com.x - 1.0).abs() < 0.01);+ /// assert!((com.y - 4.0/3.0).abs() < 0.01);+ ///+ /// println!("Triangle mass: {:.2} kg", mass);+ /// println!("Center of mass: ({:.2}, {:.2})", com.x, com.y);+ /// # }+ /// ```+ ///+ /// # Example (2D) - Equilateral Triangle+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::mass_properties::MassProperties;+ /// use parry2d::math::Vector;+ ///+ /// // Equilateral triangle with side length 2m+ /// let side = 2.0;+ /// let height = side * (3.0_f32.sqrt() / 2.0);+ ///+ /// let a = Vector::ZERO;+ /// let b = Vector::new(side, 0.0);+ /// let c = Vector::new(side / 2.0, height);+ /// let density = 50.0;+ ///+ /// let tri_props = MassProperties::from_triangle(density, a, b, c);+ ///+ /// // For equilateral triangle: Area = (side² × √3) / 4+ /// let expected_area = side * side * 3.0_f32.sqrt() / 4.0;+ /// let mass = tri_props.mass();+ /// assert!((mass - expected_area * density).abs() < 0.1);+ ///+ /// println!("Equilateral triangle mass: {:.2} kg", mass);+ /// # }+ /// ```+ ///+ /// # Example (3D) - Triangle as Thin Sheet+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::math::Vector;+ ///+ /// // Triangle in 3D space (e.g., a metal plate or sail)+ /// let a = Vector::ZERO;+ /// let b = Vector::new(2.0, 0.0, 0.0);+ /// let c = Vector::new(1.0, 2.0, 0.0);+ /// let density = 200.0; // kg/m² (sheet metal)+ ///+ /// let plate_props = MassProperties::from_triangle(density, a, b, c);+ ///+ /// // Area = 2 m² (base=2, height=2, area=(1/2)×2×2=2)+ /// // Mass = 400 kg+ /// let mass = plate_props.mass();+ /// assert!((mass - 400.0).abs() < 0.1);+ ///+ /// println!("Metal plate mass: {:.2} kg", mass);+ /// # }+ /// ```+ ///+ /// # Example - Degenerate Triangle (Collinear Vectors)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::mass_properties::MassProperties;+ /// use parry2d::math::Vector;+ ///+ /// // Three points on a line (no area)+ /// let a = Vector::ZERO;+ /// let b = Vector::new(1.0, 1.0);+ /// let c = Vector::new(2.0, 2.0);+ /// let density = 100.0;+ ///+ /// let degenerate = MassProperties::from_triangle(density, a, b, c);+ ///+ /// // Zero area means zero mass+ /// assert_eq!(degenerate.mass(), 0.0);+ /// println!("Degenerate triangle has zero mass");+ /// # }+ /// ```+ ///+ /// # Use Cases+ ///+ /// - **Mesh building blocks**: Triangles are the basis for triangle meshes+ /// - **Thin surfaces**: Sails, flags, sheets of material+ /// - **Terrain patches**: Small triangular ground segments+ /// - **Simple shapes**: Quick prototyping with basic geometry+ /// - **2D games**: Triangular platforms, obstacles, or decorations+ ///+ /// # Vertex Order+ ///+ /// - The order of vertices (a, b, c) matters for orientation+ /// - Counter-clockwise order is conventional in 2D+ /// - In 3D, vertex order determines the normal direction (right-hand rule)+ /// - However, for mass properties, the orientation doesn't affect the result+ ///+ /// # Common Use with Meshes+ ///+ /// For complex shapes, use `from_trimesh()` instead, which handles multiple triangles:+ ///+ /// ```ignore+ /// // For a single triangle, use from_triangle+ /// let props = MassProperties::from_triangle(density, &a, &b, &c);+ ///+ /// // For multiple triangles, use from_trimesh+ /// let vertices = vec![a, b, c, d, e, f];+ /// let indices = vec![[0, 1, 2], [3, 4, 5]];+ /// let mesh_props = MassProperties::from_trimesh(density, &vertices, &indices);+ /// ```+ ///+ /// # Performance Note+ ///+ /// Computing triangle mass properties is very fast (constant time) and involves+ /// only basic geometric calculations (area, centroid, and moment of inertia).+ pub fn from_triangle(density: Real, a: Vector, b: Vector, c: Vector) -> MassProperties {+ let triangle = Triangle::new(a, b, c);+ let area = triangle.area();+ let com = triangle.center();++ if area == 0.0 {+ return MassProperties::new(com, 0.0, 0.0);+ }++ let ipart = triangle.unit_angular_inertia();++ Self::new(com, area * density, ipart * area * density)+ }+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mass_properties_trimesh2d.rs b/renderer/third_party/parry3d/src/mass_properties/mass_properties_trimesh2d.rsnew file mode 100644index 0000000..f3a4ec1--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mass_properties_trimesh2d.rs@@ -0,0 +1,219 @@+use crate::mass_properties::MassProperties;+use crate::math::{Real, Vector};+use crate::shape::Triangle;++impl MassProperties {+ /// Computes the mass properties of a triangle mesh.+ ///+ /// A triangle mesh (trimesh) is a collection of triangles that together form a+ /// 2D or 3D shape. This function works for both convex and non-convex (concave)+ /// meshes. It decomposes the mesh into individual triangles, computes each+ /// triangle's mass properties, and combines them.+ ///+ /// # Arguments+ ///+ /// * `density` - The material density+ /// - In 3D: kg/m³ (mass per unit volume) - treats mesh as a solid volume+ /// - In 2D: kg/m² (mass per unit area) - treats mesh as a flat surface+ /// * `vertices` - Array of vertex positions (points in space)+ /// * `indices` - Array of triangle indices, each element is `[u32; 3]`+ /// - Each triplet references three vertices forming a triangle+ /// - Indices must be valid: all values < vertices.len()+ ///+ /// # Returns+ ///+ /// A `MassProperties` struct containing:+ /// - **mass**: Total mass of all triangles combined+ /// - **local_com**: Center of mass (area/volume weighted)+ /// - **inv_principal_inertia**: Combined angular inertia+ ///+ /// # Physics Background+ ///+ /// For each triangle:+ /// 1. Compute area (2D) or volume contribution (3D)+ /// 2. Find center of mass (centroid)+ /// 3. Calculate moment of inertia+ /// 4. Use parallel axis theorem to shift to common reference frame+ /// 5. Sum all contributions+ ///+ /// # Example (2D) - L-Shape+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::mass_properties::MassProperties;+ /// use parry2d::math::Vector;+ ///+ /// // Create an L-shaped mesh from two rectangles (4 triangles)+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(2.0, 0.0),+ /// Vector::new(2.0, 1.0),+ /// Vector::new(1.0, 1.0),+ /// Vector::new(1.0, 3.0),+ /// Vector::new(0.0, 3.0),+ /// ];+ ///+ /// let indices = vec![+ /// [0, 1, 2], // Bottom rectangle (triangle 1)+ /// [0, 2, 3], // Bottom rectangle (triangle 2)+ /// [0, 3, 4], // Vertical part (triangle 1)+ /// [0, 4, 5], // Vertical part (triangle 2)+ /// ];+ ///+ /// let density = 100.0;+ /// let l_shape_props = MassProperties::from_trimesh(density, &vertices, &indices);+ ///+ /// println!("L-shape mass: {:.2} kg", l_shape_props.mass());+ /// println!("Center of mass: {:?}", l_shape_props.local_com);+ /// # }+ /// ```+ ///+ /// # Example (3D) - Pyramid+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::math::Vector;+ ///+ /// // Square pyramid: 4 vertices at base + 1 apex+ /// let vertices = vec![+ /// Vector::new(-1.0, 0.0, -1.0), // Base corner 1+ /// Vector::new(1.0, 0.0, -1.0), // Base corner 2+ /// Vector::new(1.0, 0.0, 1.0), // Base corner 3+ /// Vector::new(-1.0, 0.0, 1.0), // Base corner 4+ /// Vector::new(0.0, 2.0, 0.0), // Apex+ /// ];+ ///+ /// let indices = vec![+ /// [0, 1, 4], // Side face 1+ /// [1, 2, 4], // Side face 2+ /// [2, 3, 4], // Side face 3+ /// [3, 0, 4], // Side face 4+ /// [0, 2, 1], // Base (triangle 1)+ /// [0, 3, 2], // Base (triangle 2)+ /// ];+ ///+ /// let density = 1000.0;+ /// let pyramid_props = MassProperties::from_trimesh(density, &vertices, &indices);+ ///+ /// println!("Pyramid mass: {:.2} kg", pyramid_props.mass());+ /// println!("Center of mass: {:?}", pyramid_props.local_com);+ /// # }+ /// ```+ ///+ /// # Example (3D) - Loading from File+ ///+ /// ```ignore+ /// # {+ /// use parry3d::mass_properties::MassProperties;+ ///+ /// // Assume you've loaded a mesh from an OBJ file+ /// let mesh = load_obj_file("complex_model.obj");+ /// let vertices = mesh.vertices;+ /// let indices = mesh.indices;+ ///+ /// let density = 2700.0; // Aluminum+ /// let props = MassProperties::from_trimesh(density, &vertices, &indices);+ ///+ /// println!("Model mass: {:.2} kg", props.mass());+ /// # }+ /// ```+ ///+ /// # Use Cases+ ///+ /// - **Complex 3D models**: Characters, vehicles, buildings+ /// - **Terrain**: Height-mapped ground, caves, landscapes+ /// - **Custom shapes**: Anything representable as triangles+ /// - **Imported models**: Meshes from modeling software (Blender, Maya, etc.)+ /// - **Non-convex objects**: Concave shapes that can't use simpler primitives+ ///+ /// # Mesh Quality Considerations+ ///+ /// - **Watertight meshes** (3D): For accurate volume/mass, mesh should be closed+ /// - Open meshes may give incorrect results+ /// - Check for holes, gaps, or missing faces+ /// - **Triangle orientation**: Consistent winding order improves accuracy+ /// - Counter-clockwise from outside (right-hand rule)+ /// - **Degenerate triangles**: Zero-area triangles are automatically handled (skipped)+ /// - **Overlapping triangles**: Can cause incorrect results; ensure clean mesh+ ///+ /// # Performance+ ///+ /// Computation time is O(n) where n is the number of triangles. For large meshes+ /// (thousands of triangles), this can take noticeable time. Consider:+ /// - Using simpler primitive approximations when possible+ /// - Pre-computing mass properties and caching results+ /// - Simplifying meshes for physics (use low-poly collision mesh)+ ///+ /// # Trimesh vs Simpler Shapes+ ///+ /// For better performance and accuracy, use primitive shapes when possible:+ /// - Ball, Cuboid, Cylinder: Much faster and more accurate+ /// - Capsule: Better for elongated objects+ /// - Compound: Combine multiple primitives+ ///+ /// Use trimesh only when the shape is truly complex and can't be approximated.+ ///+ /// # See Also+ ///+ /// - `from_convex_polyhedron()`: Alias for convex meshes+ /// - `from_triangle()`: For single triangles+ /// - `from_compound()`: Combine multiple simpler shapes+ pub fn from_trimesh(+ density: Real,+ vertices: &[Vector],+ indices: &[[u32; 3]],+ ) -> MassProperties {+ let (area, com) = trimesh_area_and_center_of_mass(vertices, indices);++ if area == 0.0 {+ return MassProperties::new(com, 0.0, 0.0);+ }++ let mut itot = 0.0;++ for idx in indices {+ let triangle = Triangle::new(+ vertices[idx[0] as usize],+ vertices[idx[1] as usize],+ vertices[idx[2] as usize],+ );++ // TODO: is the parallel axis theorem correctly applied here?+ let area = triangle.area();+ let ipart = triangle.unit_angular_inertia();+ itot += ipart * area;+ }++ Self::new(com, area * density, itot * density)+ }+}++/// Computes the area and center-of-mass of a triangle-mesh.+pub fn trimesh_area_and_center_of_mass(+ vertices: &[Vector],+ indices: &[[u32; 3]],+) -> (Real, Vector) {+ let mut res = Vector::ZERO;+ let mut areasum = 0.0;++ for idx in indices {+ let triangle = Triangle::new(+ vertices[idx[0] as usize],+ vertices[idx[1] as usize],+ vertices[idx[2] as usize],+ );+ let area = triangle.area();+ let center = triangle.center();++ res += center * area;+ areasum += area;+ }++ if areasum == 0.0 {+ (areasum, res)+ } else {+ res /= areasum;+ (areasum, res)+ }+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mass_properties_trimesh3d.rs b/renderer/third_party/parry3d/src/mass_properties/mass_properties_trimesh3d.rsnew file mode 100644index 0000000..0dfb7bd--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mass_properties_trimesh3d.rs@@ -0,0 +1,342 @@+use crate::mass_properties::MassProperties;+use crate::math::{Matrix, Real, Vector, DIM};+use crate::shape::Tetrahedron;+use num::Zero;++impl MassProperties {+ /// Computes the mass properties of a triangle mesh.+ pub fn from_trimesh(+ density: Real,+ vertices: &[Vector],+ indices: &[[u32; DIM]],+ ) -> MassProperties {+ let (volume, com) = trimesh_signed_volume_and_center_of_mass(vertices, indices);++ if volume.is_zero() {+ return MassProperties::zero();+ }++ let mut itot = Matrix::ZERO;++ for t in indices {+ let p2 = vertices[t[0] as usize];+ let p3 = vertices[t[1] as usize];+ let p4 = vertices[t[2] as usize];++ let vol = Tetrahedron::new(com, p2, p3, p4).signed_volume();+ let ipart = tetrahedron_unit_inertia_tensor_wrt_point(com, com, p2, p3, p4);++ itot += ipart * vol;+ }++ let sign = volume.signum();+ Self::with_inertia_matrix(com, volume * density * sign, itot * density * sign)+ }+}++/// Computes the unit inertia tensor of a tetrahedron, with regard to the given `point`.+pub fn tetrahedron_unit_inertia_tensor_wrt_point(+ point: Vector,+ p1: Vector,+ p2: Vector,+ p3: Vector,+ p4: Vector,+) -> Matrix {+ let p1 = p1 - point;+ let p2 = p2 - point;+ let p3 = p3 - point;+ let p4 = p4 - point;++ // Just for readability.+ let x1 = p1.x;+ let y1 = p1.y;+ let z1 = p1.z;+ let x2 = p2.x;+ let y2 = p2.y;+ let z2 = p2.z;+ let x3 = p3.x;+ let y3 = p3.y;+ let z3 = p3.z;+ let x4 = p4.x;+ let y4 = p4.y;+ let z4 = p4.z;++ let diag_x = x1 * x1+ + x1 * x2+ + x2 * x2+ + x1 * x3+ + x2 * x3+ + x3 * x3+ + x1 * x4+ + x2 * x4+ + x3 * x4+ + x4 * x4;+ let diag_y = y1 * y1+ + y1 * y2+ + y2 * y2+ + y1 * y3+ + y2 * y3+ + y3 * y3+ + y1 * y4+ + y2 * y4+ + y3 * y4+ + y4 * y4;+ let diag_z = z1 * z1+ + z1 * z2+ + z2 * z2+ + z1 * z3+ + z2 * z3+ + z3 * z3+ + z1 * z4+ + z2 * z4+ + z3 * z4+ + z4 * z4;++ let a0 = (diag_y + diag_z) * 0.1;+ let b0 = (diag_z + diag_x) * 0.1;+ let c0 = (diag_x + diag_y) * 0.1;++ let a1 = (y1 * z1 * 2.0+ + y2 * z1+ + y3 * z1+ + y4 * z1+ + y1 * z2+ + y2 * z2 * 2.0+ + y3 * z2+ + y4 * z2+ + y1 * z3+ + y2 * z3+ + y3 * z3 * 2.0+ + y4 * z3+ + y1 * z4+ + y2 * z4+ + y3 * z4+ + y4 * z4 * 2.0)+ * 0.05;+ let b1 = (x1 * z1 * 2.0+ + x2 * z1+ + x3 * z1+ + x4 * z1+ + x1 * z2+ + x2 * z2 * 2.0+ + x3 * z2+ + x4 * z2+ + x1 * z3+ + x2 * z3+ + x3 * z3 * 2.0+ + x4 * z3+ + x1 * z4+ + x2 * z4+ + x3 * z4+ + x4 * z4 * 2.0)+ * 0.05;+ let c1 = (x1 * y1 * 2.0+ + x2 * y1+ + x3 * y1+ + x4 * y1+ + x1 * y2+ + x2 * y2 * 2.0+ + x3 * y2+ + x4 * y2+ + x1 * y3+ + x2 * y3+ + x3 * y3 * 2.0+ + x4 * y3+ + x1 * y4+ + x2 * y4+ + x3 * y4+ + x4 * y4 * 2.0)+ * 0.05;++ Matrix::from_cols_array(&[a0, -c1, -b1, -c1, b0, -a1, -b1, -a1, c0])+}++/// Computes the volume and center-of-mass of a mesh.+pub fn trimesh_signed_volume_and_center_of_mass(+ vertices: &[Vector],+ indices: &[[u32; DIM]],+) -> (Real, Vector) {+ let geometric_center = crate::utils::center(vertices);++ let mut res = Vector::ZERO;+ let mut vol = 0.0;++ for t in indices {+ let p2 = vertices[t[0] as usize];+ let p3 = vertices[t[1] as usize];+ let p4 = vertices[t[2] as usize];++ let volume = Tetrahedron::new(geometric_center, p2, p3, p4).signed_volume();+ let center = Tetrahedron::new(geometric_center, p2, p3, p4).center();++ res += center * volume;+ vol += volume;+ }++ if vol.is_zero() {+ (vol, geometric_center)+ } else {+ (vol, res / vol)+ }+}++#[cfg(test)]+mod test {+ use crate::math::{Pose, Rotation, Vector, VectorExt};+ use crate::{+ mass_properties::MassProperties,+ shape::{Ball, Capsule, Cone, Cuboid, Cylinder, Shape},+ };+ use std::dbg;++ fn assert_same_principal_inertias(mprops1: &MassProperties, mprops2: &MassProperties) {+ for k in 0..3 {+ let i1 = mprops1.principal_inertia_local_frame+ * (mprops1.principal_inertia()+ * (mprops1.principal_inertia_local_frame.inverse() * Vector::ith(k, 1.0)));+ let i2 = mprops2.principal_inertia_local_frame+ * (mprops2.principal_inertia()+ * (mprops2.principal_inertia_local_frame.inverse() * Vector::ith(k, 1.0)));+ assert!(i1.abs_diff_eq(i2, 0.5))+ }+ }++ #[test]+ fn cuboid_as_trimesh_mprops() {+ let cuboid = Cuboid::new(Vector::new(1.0, 2.0, 3.0));++ use crate::shape::Shape;+ let orig_mprops = cuboid.mass_properties(1.0);+ dbg!(orig_mprops.principal_inertia());++ let mut trimesh = cuboid.to_trimesh();+ let mprops = MassProperties::from_trimesh(1.0, &trimesh.0, &trimesh.1);+ assert_relative_eq!(mprops.mass(), 48.0, epsilon = 1.0e-4);+ assert!(+ (mprops.principal_inertia_local_frame * mprops.principal_inertia())+ .abs()+ .abs_diff_eq(Vector::new(208.0, 160.0, 80.0), 1.0e-4)+ );++ // Check after shifting the trimesh off the origin.+ trimesh+ .0+ .iter_mut()+ .for_each(|pt| *pt += Vector::new(30.0, 20.0, 10.0));+ let mprops = MassProperties::from_trimesh(1.0, &trimesh.0, &trimesh.1);+ assert_relative_eq!(mprops.mass(), 48.0, epsilon = 1.0e-4);+ assert!(+ (mprops.principal_inertia_local_frame * mprops.principal_inertia())+ .abs()+ .abs_diff_eq(Vector::new(208.0, 160.0, 80.0), 1.0e-4)+ );+ }++ #[test]+ fn primitives_as_trimesh_mprops() {+ let primitives = (+ Cuboid::new(Vector::new(1.0, 2.0, 3.0)),+ Capsule::new_y(2.0, 1.0),+ Cone::new(2.0, 1.0),+ Cylinder::new(2.0, 1.0),+ Ball::new(2.0),+ );+ let mut meshes = [+ primitives.0.to_trimesh(),+ primitives.1.to_trimesh(100, 100),+ primitives.2.to_trimesh(100),+ primitives.3.to_trimesh(100),+ primitives.4.to_trimesh(100, 100),+ ];+ let shapes = [+ &primitives.0 as &dyn Shape,+ &primitives.1 as &dyn Shape,+ &primitives.2 as &dyn Shape,+ &primitives.3 as &dyn Shape,+ &primitives.4 as &dyn Shape,+ ];++ for (shape, mesh) in shapes.iter().zip(meshes.iter_mut()) {+ let shape_mprops = shape.mass_properties(2.0);+ let mesh_mprops = MassProperties::from_trimesh(2.0, &mesh.0, &mesh.1);+ assert_relative_eq!(shape_mprops.mass(), mesh_mprops.mass(), epsilon = 1.0e-1);+ assert_same_principal_inertias(&shape_mprops, &mesh_mprops);+ assert_relative_eq!(+ shape_mprops.local_com,+ mesh_mprops.local_com,+ epsilon = 1.0e-3+ );++ // Now try with a shifted mesh.+ let shift = Vector::new(33.0, 22.0, 11.0);+ mesh.0.iter_mut().for_each(|pt| *pt += shift);++ let mesh_mprops = MassProperties::from_trimesh(2.0, &mesh.0, &mesh.1);++ assert_relative_eq!(shape_mprops.mass(), mesh_mprops.mass(), epsilon = 1.0e-1);+ assert_same_principal_inertias(&shape_mprops, &mesh_mprops);+ assert_relative_eq!(+ shape_mprops.local_com + shift, // The mesh is shifted, so its center-of-mass is shifted too.+ mesh_mprops.local_com,+ epsilon = 1.0e-3+ );+ }+ }++ // Regression test for https://github.com/dimforge/parry/pull/331+ //+ // We compare the angular inertia tensor of a rotated & translated Cuboid, with the+ // inertia tensor of the same cuboid represented as a `TriMesh` with rotated & translated+ // vertices.+ #[test]+ fn rotated_inertia_tensor() {+ let cuboid = Cuboid::new(Vector::new(3.0, 2.0, 1.0));+ let density = 1.0;++ // Compute mass properties with a translated and rotated cuboid.+ let pose = Pose::new(Vector::new(5.0, 2.0, 3.0), Vector::new(0.6, 0.7, 0.8));+ let mprops = cuboid.mass_properties(density);++ // Compute mass properties with a manually transformed cuboid.+ let mut vertices = cuboid.to_trimesh().0;+ let trimesh_origin_mprops =+ MassProperties::from_trimesh(density, &vertices, &cuboid.to_trimesh().1);+ vertices.iter_mut().for_each(|v| *v = pose * *v);+ let trimesh_transformed_mprops =+ MassProperties::from_trimesh(density, &vertices, &cuboid.to_trimesh().1);++ // Compare the mass properties.+ assert_relative_eq!(+ mprops.mass(),+ trimesh_origin_mprops.mass(),+ epsilon = 1.0e-4+ );+ assert_relative_eq!(+ mprops.mass(),+ trimesh_transformed_mprops.mass(),+ epsilon = 1.0e-4+ );+ // compare local_com+ assert_relative_eq!(+ pose * mprops.local_com,+ trimesh_transformed_mprops.local_com,+ epsilon = 1.0e-4+ );+ assert_relative_eq!(+ pose * trimesh_origin_mprops.local_com,+ trimesh_transformed_mprops.local_com,+ epsilon = 1.0e-4+ );+ assert!(trimesh_origin_mprops+ .principal_inertia()+ .abs_diff_eq(mprops.principal_inertia(), 1.0e-4));+ let w1 = trimesh_origin_mprops.world_inv_inertia(&pose.rotation);+ let w2 = trimesh_transformed_mprops.world_inv_inertia(&Rotation::IDENTITY);+ assert_relative_eq!(w1.m11, w2.m11, epsilon = 1.0e-7);+ assert_relative_eq!(w1.m12, w2.m12, epsilon = 1.0e-7);+ assert_relative_eq!(w1.m13, w2.m13, epsilon = 1.0e-7);+ assert_relative_eq!(w1.m22, w2.m22, epsilon = 1.0e-7);+ assert_relative_eq!(w1.m23, w2.m23, epsilon = 1.0e-7);+ assert_relative_eq!(w1.m33, w2.m33, epsilon = 1.0e-7);+ }+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mass_properties_voxels.rs b/renderer/third_party/parry3d/src/mass_properties/mass_properties_voxels.rsnew file mode 100644index 0000000..e08b907--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mass_properties_voxels.rs@@ -0,0 +1,206 @@+use crate::mass_properties::MassProperties;+#[cfg(feature = "dim3")]+use crate::math::Matrix;+use crate::math::{Real, Vector};+use crate::shape::Voxels;++impl MassProperties {+ /// Computes the mass properties of a voxel grid.+ ///+ /// Voxels (volumetric pixels) represent a 3D shape as a grid of small cubes. This+ /// function treats each non-empty voxel as a small cuboid and combines their mass+ /// properties. It's useful for volumetric data, destructible terrain, or shapes that+ /// are difficult to represent with traditional geometry.+ ///+ /// # Arguments+ ///+ /// * `density` - The material density+ /// - In 3D: kg/m³ (mass per unit volume)+ /// - In 2D: kg/m² (mass per unit area)+ /// * `voxels` - A `Voxels` structure containing the voxel grid+ /// - Each voxel is a small cube/square of uniform size+ /// - Voxels can be empty or filled+ /// - Since v0.25.0, uses sparse storage internally for efficiency+ ///+ /// # Returns+ ///+ /// A `MassProperties` struct containing:+ /// - **mass**: Total mass of all non-empty voxels+ /// - **local_com**: Center of mass (weighted average of voxel centers)+ /// - **inv_principal_inertia**: Combined angular inertia+ ///+ /// # Physics Background+ ///+ /// The algorithm:+ /// 1. Compute mass properties of a single voxel (small cuboid)+ /// 2. For each non-empty voxel, shift its mass properties to its position+ /// 3. Sum all contributions using parallel axis theorem+ /// 4. Empty voxels contribute nothing (zero mass)+ ///+ /// # Example (3D) - Simple Voxel Object+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// // Create a 3×3×3 voxel grid with 1m voxels+ /// let voxel_size = Vector::new(1.0, 1.0, 1.0);+ ///+ /// // Fill some voxels to create an L-shape+ /// let voxels = &[+ /// IVector::new(0, 0, 0), // Bottom bar+ /// IVector::new(1, 0, 0),+ /// IVector::new(2, 0, 0),+ /// IVector::new(0, 1, 0), // Vertical part+ /// IVector::new(0, 2, 0),+ /// ];+ /// let voxels = Voxels::new(voxel_size, voxels);+ ///+ /// let density = 1000.0; // Water density+ /// let voxel_props = MassProperties::from_voxels(density, &voxels);+ ///+ /// // 5 voxels × 1m³ each × 1000 kg/m³ = 5000 kg+ /// println!("Voxel object mass: {:.2} kg", voxel_props.mass());+ /// println!("Center of mass: {:?}", voxel_props.local_com);+ /// # }+ /// ```+ ///+ /// # Example (3D) - Destructible Terrain+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// // Create a chunk of destructible terrain+ /// let voxel_size = Vector::new(0.5, 0.5, 0.5); // 50cm voxels+ /// let mut voxels = vec![];+ ///+ /// // Fill a 4×4×4 solid block+ /// for x in 0..4 {+ /// for y in 0..4 {+ /// for z in 0..4 {+ /// voxels.push(IVector::new(x, y, z));+ /// }+ /// }+ /// }+ ///+ /// let mut terrain = Voxels::new(voxel_size, &voxels);+ ///+ /// let density = 2400.0; // Concrete+ /// let terrain_props = MassProperties::from_voxels(density, &terrain);+ ///+ /// println!("Terrain chunk mass: {:.2} kg", terrain_props.mass());+ /// # }+ /// ```+ ///+ /// # Example - Sparse Voxel Grid (Efficient)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::mass_properties::MassProperties;+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// // Large sparse grid (only stores filled voxels since v0.25.0)+ /// let voxel_size = Vector::new(0.1, 0.1, 0.1);+ ///+ /// // Scatter some voxels in a large space (efficient with sparse storage)+ /// let voxels = &[+ /// IVector::new(0, 0, 0),+ /// IVector::new(100, 50, 75),+ /// IVector::new(-50, 200, -30),+ /// ];+ /// let voxels = Voxels::new(voxel_size, voxels);+ /// let density = 1000.0;+ /// let props = MassProperties::from_voxels(density, &voxels);+ ///+ /// // Only 3 voxels contribute to mass+ /// println!("Sparse voxel mass: {:.4} kg", props.mass());+ /// # }+ /// ```+ ///+ /// # Use Cases+ ///+ /// - **Destructible terrain**: Voxel-based environments (Minecraft-style)+ /// - **Medical imaging**: CT scans, MRI data volumetric analysis+ /// - **Procedural generation**: Voxel-based world generation+ /// - **Simulation**: Granular materials, fluids represented as voxels+ /// - **Dynamic shapes**: Objects that change shape at runtime+ /// - **Complex geometry**: Shapes difficult to represent with meshes+ ///+ /// # Performance Considerations+ ///+ /// - **Sparse storage** (v0.25.0+): Only filled voxels consume memory+ /// - **Computation time**: O(n) where n = number of filled voxels+ /// - **For large grids**: Prefer coarser voxel sizes when possible+ /// - **Memory usage**: Each voxel stores position and state+ /// - **Alternative**: For static shapes, consider using triangle meshes+ ///+ /// # Voxel Size Trade-offs+ ///+ /// **Smaller voxels**:+ /// - More accurate representation of curved surfaces+ /// - More voxels = longer computation time+ /// - Higher memory usage (more voxels to store)+ ///+ /// **Larger voxels**:+ /// - Faster computation+ /// - Less memory+ /// - Blockier appearance (lower resolution)+ ///+ /// # Accuracy Notes+ ///+ /// - Voxel representation is an approximation of the true shape+ /// - Smooth curves become staircase patterns+ /// - Mass properties accuracy depends on voxel resolution+ /// - For exact results with smooth shapes, use primitive shapes or meshes+ ///+ /// # Empty vs Filled Voxels+ ///+ /// - Only non-empty voxels contribute to mass+ /// - Empty voxels are ignored (zero mass, no inertia)+ /// - The voxel state is checked using `vox.state.is_empty()`+ ///+ /// # See Also+ ///+ /// - `Voxels::new()`: Create a new voxel grid+ /// - `Voxels::set_voxel()`: Add or remove voxels+ /// - `from_trimesh()`: Alternative for precise shapes+ /// - `from_compound()`: Combine multiple shapes efficiently+ pub fn from_voxels(density: Real, voxels: &Voxels) -> Self {+ let mut com = Vector::ZERO;+ let mut num_not_empty = 0;+ #[cfg(feature = "dim2")]+ let mut angular_inertia = 0.0;+ #[cfg(feature = "dim3")]+ let mut angular_inertia = Matrix::ZERO;+ let block_ref_mprops = MassProperties::from_cuboid(density, voxels.voxel_size() / 2.0);++ for vox in voxels.voxels() {+ if !vox.state.is_empty() {+ com += vox.center;+ num_not_empty += 1;+ }+ }++ com /= num_not_empty as Real;++ for vox in voxels.voxels() {+ if !vox.state.is_empty() {+ angular_inertia +=+ block_ref_mprops.construct_shifted_inertia_matrix(vox.center - com);+ }+ }++ let mass = block_ref_mprops.mass() * num_not_empty as Real;++ #[cfg(feature = "dim2")]+ return Self::new(com, mass, angular_inertia);+ #[cfg(feature = "dim3")]+ return Self::with_inertia_matrix(com, mass, angular_inertia);+ }+}diff --git a/renderer/third_party/parry3d/src/mass_properties/mod.rs b/renderer/third_party/parry3d/src/mass_properties/mod.rsnew file mode 100644index 0000000..6f8dd77--- /dev/null+++ b/renderer/third_party/parry3d/src/mass_properties/mod.rs@@ -0,0 +1,45 @@+//! Mass properties (mass, inertia, center-of-mass) of shapes.++pub use self::mass_properties::MassProperties;++mod mass_properties;+mod mass_properties_ball;+mod mass_properties_capsule;+#[cfg(feature = "alloc")]+mod mass_properties_compound;+#[cfg(feature = "dim3")]+mod mass_properties_cone;+#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+mod mass_properties_convex_polygon;+#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+mod mass_properties_convex_polyhedron;+mod mass_properties_cuboid;+mod mass_properties_cylinder;+#[cfg(feature = "dim2")]+mod mass_properties_triangle;+#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+mod mass_properties_trimesh2d;+#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+mod mass_properties_trimesh3d;++#[cfg(feature = "alloc")]+mod mass_properties_voxels;++/// Free functions for some special-cases of mass-properties computation.+pub mod details {+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ pub use super::mass_properties_convex_polygon::convex_polygon_area_and_center_of_mass;+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ pub use super::mass_properties_trimesh2d::trimesh_area_and_center_of_mass;+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ pub use super::mass_properties_trimesh3d::{+ tetrahedron_unit_inertia_tensor_wrt_point, trimesh_signed_volume_and_center_of_mass,+ };+}diff --git a/renderer/third_party/parry3d/src/math/mod.rs b/renderer/third_party/parry3d/src/math/mod.rsnew file mode 100644index 0000000..fcb3819--- /dev/null+++ b/renderer/third_party/parry3d/src/math/mod.rs@@ -0,0 +1,314 @@+//! Math types and utilities for parry, wrapping glam types.++mod vector_ext;++/// The scalar type used throughout this crate.+#[cfg(feature = "f64")]+pub use f64 as Real;+#[cfg(feature = "f64")]+pub use i64 as Int;++/// The scalar type used throughout this crate.+#[cfg(feature = "f32")]+pub use f32 as Real;+#[cfg(feature = "f32")]+pub use i32 as Int;++// Re-export ComplexField and RealField from simba for math operations+pub use simba::scalar::{ComplexField, RealField};++pub use vector_ext::*;++// Re-export SIMD types from parent module+pub use crate::simd::*;++// Re-export types from glamx based on precision+#[cfg(feature = "f64")]+pub use glamx::{+ DPose2 as Pose2, DPose3 as Pose3, DRot2 as Rot2, DRot3 as Rot3,+ DSymmetricEigen2 as SymmetricEigen2, DSymmetricEigen3 as SymmetricEigen3, MatExt,+};+#[cfg(feature = "f32")]+pub use glamx::{MatExt, Pose2, Pose3, Rot2, Rot3, SymmetricEigen2, SymmetricEigen3};++// Re-export glam types used directly+#[cfg(feature = "f64")]+pub use glamx::{+ DMat2 as Mat2, DMat3 as Mat3, DVec2 as Vec2, DVec3 as Vec3, DVec3 as Vec3A, DVec4 as Vec4,+};+#[cfg(feature = "f32")]+pub use glamx::{Mat2, Mat3, Vec2, Vec3, Vec3A, Vec4};++/// The default tolerance used for geometric operations.+pub const DEFAULT_EPSILON: Real = Real::EPSILON;++/// The dimension of the space.+#[cfg(feature = "dim2")]+pub const DIM: usize = 2;+/// The dimension of the space.+#[cfg(feature = "dim3")]+pub const DIM: usize = 3;++/// The dimension of the space multiplied by two.+pub const TWO_DIM: usize = DIM * 2;++// ==================== DIMENSION-DEPENDENT TYPE ALIASES ====================++// --- 3D Type Aliases ---++#[cfg(feature = "dim3")]+mod dim3_types {+ use super::*;+ #[cfg(feature = "f64")]+ use glamx::{DMat3, DVec3};++ /// The vector type.+ #[cfg(feature = "f32")]+ pub type Vector = Vec3;+ /// The vector type.+ #[cfg(feature = "f64")]+ pub type Vector = DVec3;++ /// The integer vector type.+ #[cfg(feature = "f32")]+ pub type IVector = glamx::IVec3;+ /// The integer vector type.+ #[cfg(feature = "f64")]+ pub type IVector = glamx::I64Vec3;++ /// The angular vector type.+ #[cfg(feature = "f32")]+ pub type AngVector = Vec3;+ /// The angular vector type.+ #[cfg(feature = "f64")]+ pub type AngVector = DVec3;++ /// The matrix type.+ #[cfg(feature = "f32")]+ pub type Matrix = Mat3;+ /// The matrix type.+ #[cfg(feature = "f64")]+ pub type Matrix = DMat3;++ /// The transformation matrix type (pose = rotation + translation).+ pub type Pose = Pose3;++ /// The rotation type.+ pub type Rotation = Rot3;++ /// The orientation type.+ #[cfg(feature = "f32")]+ pub type Orientation = Vec3;+ /// The orientation type.+ #[cfg(feature = "f64")]+ pub type Orientation = DVec3;++ /// A vector with a dimension equal to the maximum number of degrees of freedom of a rigid body.+ #[cfg(feature = "f32")]+ pub type SpatialVector = [f32; 6];+ /// A vector with a dimension equal to the maximum number of degrees of freedom of a rigid body.+ #[cfg(feature = "f64")]+ pub type SpatialVector = [f64; 6];++ /// The angular inertia of a rigid body.+ pub type AngularInertia = crate::utils::SdpMatrix3<Real>;++ /// The principal angular inertia of a rigid body.+ #[cfg(feature = "f32")]+ pub type PrincipalAngularInertia = Vec3;+ /// The principal angular inertia of a rigid body.+ #[cfg(feature = "f64")]+ pub type PrincipalAngularInertia = DVec3;++ /// A matrix that represent the cross product with a given vector.+ #[cfg(feature = "f32")]+ pub type CrossMatrix = Mat3;+ /// A matrix that represent the cross product with a given vector.+ #[cfg(feature = "f64")]+ pub type CrossMatrix = DMat3;++ /// A 3D symmetric-definite-positive matrix.+ pub type SdpMatrix = crate::utils::SdpMatrix3<Real>;++ /// The result of eigendecomposition of a symmetric matrix.+ #[cfg(feature = "f32")]+ pub type SymmetricEigen = SymmetricEigen3;+ /// The result of eigendecomposition of a symmetric matrix.+ #[cfg(feature = "f64")]+ pub type SymmetricEigen = glamx::DSymmetricEigen3;+}++#[cfg(feature = "dim3")]+pub use dim3_types::*;++// --- 2D Type Aliases ---++#[cfg(feature = "dim2")]+mod dim2_types {+ use super::*;+ #[cfg(feature = "f64")]+ use glamx::{DMat2, DVec2, DVec3};++ /// The vector type.+ #[cfg(feature = "f32")]+ pub type Vector = Vec2;+ /// The vector type.+ #[cfg(feature = "f64")]+ pub type Vector = DVec2;++ /// The integer vector type.+ #[cfg(feature = "f32")]+ pub type IVector = glamx::IVec2;+ /// The integer vector type.+ #[cfg(feature = "f64")]+ pub type IVector = glamx::I64Vec2;++ /// The angular vector type (scalar for 2D).+ pub type AngVector = Real;++ /// The matrix type.+ #[cfg(feature = "f32")]+ pub type Matrix = Mat2;+ /// The matrix type.+ #[cfg(feature = "f64")]+ pub type Matrix = DMat2;++ /// The transformation matrix type (pose = rotation + translation).+ pub type Pose = Pose2;++ /// The rotation type.+ pub type Rotation = Rot2;++ /// The orientation type (scalar angle for 2D).+ pub type Orientation = Real;++ /// A vector with a dimension equal to the maximum number of degrees of freedom of a rigid body.+ #[cfg(feature = "f32")]+ pub type SpatialVector = Vec3;+ /// A vector with a dimension equal to the maximum number of degrees of freedom of a rigid body.+ #[cfg(feature = "f64")]+ pub type SpatialVector = DVec3;++ /// The angular inertia of a rigid body (scalar for 2D).+ pub type AngularInertia = Real;++ /// The principal angular inertia of a rigid body (scalar for 2D).+ pub type PrincipalAngularInertia = Real;++ /// A matrix that represent the cross product with a given vector.+ #[cfg(feature = "f32")]+ pub type CrossMatrix = Vec2;+ /// A matrix that represent the cross product with a given vector.+ #[cfg(feature = "f64")]+ pub type CrossMatrix = DVec2;++ /// A 2D symmetric-definite-positive matrix.+ pub type SdpMatrix = crate::utils::SdpMatrix2<Real>;++ /// The result of eigendecomposition of a symmetric matrix.+ #[cfg(feature = "f32")]+ pub type SymmetricEigen = SymmetricEigen2;+ /// The result of eigendecomposition of a symmetric matrix.+ #[cfg(feature = "f64")]+ pub type SymmetricEigen = glamx::DSymmetricEigen2;+}++#[cfg(feature = "dim2")]+pub use dim2_types::*;++// ==================== ORTHONORMAL BASIS COMPUTATION ====================++/// Computes an orthonormal basis for the subspace orthogonal to the given vectors.+/// Calls the callback `f` with each basis vector.+///+/// For 3D: given 1 vector, produces 2 orthonormal vectors perpendicular to it.+#[cfg(feature = "dim3")]+pub fn orthonormal_subspace_basis<F>(vs: &[Vector], mut f: F)+where+ F: FnMut(Vector) -> bool,+{+ if vs.is_empty() {+ return;+ }++ // Normalize the input vector+ let v = vs[0].normalize_or_zero();++ if v == Vector::ZERO {+ return;+ }++ // Find a vector that's not parallel to v+ let orth = if v.x.abs() > v.z.abs() {+ Vector::new(-v.y, v.x, 0.0)+ } else {+ Vector::new(0.0, -v.z, v.y)+ };++ // First orthonormal vector+ let orth1 = orth.normalize();+ if !f(orth1) {+ return;+ }++ // Second orthonormal vector (cross product)+ let orth2 = v.cross(orth1);+ let _ = f(orth2);+}++// ==================== 2D TYPES FOR 3D CONTEXTS ====================+// These are needed for algorithms like spiral intersection that use 2D math in 3D contexts.++/// A 2D vector type for use in any dimension context.+pub type Vector2 = Vec2;++/// A 2x2 matrix type for use in any dimension context.+pub type Matrix2 = Mat2;++/// A 3D vector type for use in any dimension context.+pub type Vector3 = Vec3;++/// A 3x3 matrix type for use in any dimension context.+pub type Matrix3 = Mat3;++/// Converts an integer vector to a floating-point vector.+#[cfg(all(feature = "dim2", feature = "f32"))]+pub fn ivect_to_vect(p: IVector) -> Vector {+ p.as_vec2()+}+/// Converts an integer vector to a floating-point vector.+#[cfg(all(feature = "dim2", feature = "f64"))]+pub fn ivect_to_vect(p: IVector) -> Vector {+ p.as_dvec2()+}+/// Converts an integer vector to a floating-point vector.+#[cfg(all(feature = "dim3", feature = "f32"))]+pub fn ivect_to_vect(p: IVector) -> Vector {+ p.as_vec3()+}+/// Converts an integer vector to a floating-point vector.+#[cfg(all(feature = "dim3", feature = "f64"))]+pub fn ivect_to_vect(p: IVector) -> Vector {+ p.as_dvec3()+}++/// Converts a floating-point vector to an integer vector.+#[cfg(all(feature = "dim2", feature = "f32"))]+pub fn vect_to_ivect(p: Vector) -> IVector {+ p.as_ivec2()+}+/// Converts a floating-point vector to an integer vector.+#[cfg(all(feature = "dim2", feature = "f64"))]+pub fn vect_to_ivect(p: Vector) -> IVector {+ p.as_i64vec2()+}+/// Converts a floating-point vector to an integer vector.+#[cfg(all(feature = "dim3", feature = "f32"))]+pub fn vect_to_ivect(p: Vector) -> IVector {+ p.as_ivec3()+}+/// Converts a floating-point vector to an integer vector.+#[cfg(all(feature = "dim3", feature = "f64"))]+pub fn vect_to_ivect(p: Vector) -> IVector {+ p.as_i64vec3()+}diff --git a/renderer/third_party/parry3d/src/math/vector_ext.rs b/renderer/third_party/parry3d/src/math/vector_ext.rsnew file mode 100644index 0000000..61aae97--- /dev/null+++ b/renderer/third_party/parry3d/src/math/vector_ext.rs@@ -0,0 +1,154 @@+//! Vector extension trait for glam types.++use crate::math::{IVector, Int, Matrix, Real, Vector};++#[cfg(not(feature = "std"))]+use simba::scalar::ComplexField;++/// Extension trait for glam vector types to provide additional functionality.+pub trait VectorExt: Sized + Copy {+ /// Creates a vector with the i-th component set to `val` and all others to zero.+ fn ith(i: usize, val: Real) -> Self;++ /// Computes the angle between two vectors in radians.+ fn angle(self, other: Self) -> Real;++ /// Computes the kronecker product between two vectors.+ fn kronecker(self, other: Self) -> Matrix;++ /// Gets the i-th component of the vector by index.+ ///+ /// This is a SPIR-V compatible replacement for bracket indexing (`v[i]`),+ /// which is not supported on glam types when targeting SPIR-V.+ fn vget(&self, i: usize) -> Real;++ /// Sets the i-th component of the vector by index.+ ///+ /// This is a SPIR-V compatible replacement for bracket indexing (`v[i] = val`),+ /// which is not supported on glam types when targeting SPIR-V.+ fn vset(&mut self, i: usize, val: Real);+}++impl VectorExt for Vector {+ #[inline]+ #[cfg(feature = "dim2")]+ fn ith(i: usize, val: Real) -> Self {+ match i {+ 0 => Self::new(val, 0.0),+ 1 => Self::new(0.0, val),+ _ => Self::ZERO,+ }+ }++ #[inline]+ #[cfg(feature = "dim3")]+ fn ith(i: usize, val: Real) -> Self {+ match i {+ 0 => Self::new(val, 0.0, 0.0),+ 1 => Self::new(0.0, val, 0.0),+ 2 => Self::new(0.0, 0.0, val),+ _ => Self::ZERO,+ }+ }++ #[inline]+ fn angle(self, other: Self) -> Real {+ let dot = self.dot(other);+ let len_self = self.length();+ let len_other = other.length();+ if len_self > 0.0 && len_other > 0.0 {+ (dot / (len_self * len_other)).clamp(-1.0, 1.0).acos()+ } else {+ 0.0+ }+ }++ #[inline]+ #[cfg(feature = "dim2")]+ fn kronecker(self, other: Self) -> Matrix {+ Matrix::from_cols(self * other.x, self * other.y)+ }++ #[inline]+ #[cfg(feature = "dim3")]+ fn kronecker(self, other: Self) -> Matrix {+ Matrix::from_cols(self * other.x, self * other.y, self * other.z)+ }++ #[inline]+ fn vget(&self, i: usize) -> Real {+ #[cfg(target_arch = "spirv")]+ return match i {+ 0 => self.x,+ 1 => self.y,+ #[cfg(feature = "dim3")]+ 2 => self.z,+ _ => panic!("Index out of bounds for 2D vector: {i}"),+ };+ #[cfg(not(target_arch = "spirv"))]+ {+ self[i]+ }+ }++ #[inline]+ fn vset(&mut self, i: usize, val: Real) {+ #[cfg(target_arch = "spirv")]+ match i {+ 0 => self.x = val,+ 1 => self.y = val,+ #[cfg(feature = "dim3")]+ 2 => self.z = val,+ _ => panic!("Index out of bounds for 2D vector: {i}"),+ };+ #[cfg(not(target_arch = "spirv"))]+ {+ self[i] = val;+ }+ }+}++/// Extension trait for integer vector types with index-based component access.+///+/// Provides SPIR-V compatible replacement for bracket indexing on glam integer vectors.+pub trait IVectorExt: Sized + Copy {+ /// Gets the i-th component of the integer vector by index.+ fn ivget(&self, i: usize) -> Int;++ /// Sets the i-th component of the integer vector by index.+ fn ivset(&mut self, i: usize, val: Int);+}++impl IVectorExt for IVector {+ #[inline]+ fn ivget(&self, i: usize) -> Int {+ #[cfg(target_arch = "spirv")]+ return match i {+ 0 => self.x,+ 1 => self.y,+ #[cfg(feature = "dim3")]+ 2 => self.z,+ _ => panic!("Index out of bounds for 2D integer vector: {i}"),+ };+ #[cfg(not(target_arch = "spirv"))]+ {+ self[i]+ }+ }++ #[inline]+ fn ivset(&mut self, i: usize, val: Int) {+ #[cfg(target_arch = "spirv")]+ match i {+ 0 => self.x = val,+ 1 => self.y = val,+ #[cfg(feature = "dim3")]+ 2 => self.z = val,+ _ => panic!("Index out of bounds for 2D integer vector: {i}"),+ }+ #[cfg(not(target_arch = "spirv"))]+ {+ self[i] = val;+ }+ }+}diff --git a/renderer/third_party/parry3d/src/partitioning/bvh/bvh_binned_build.rs b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_binned_build.rsnew file mode 100644index 0000000..e2251ec--- /dev/null+++ b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_binned_build.rs@@ -0,0 +1,200 @@+use super::bvh_tree::{BvhBuildStrategy, BvhNodeIndex, BvhNodeWide};+use super::{Bvh, BvhNode, BvhWorkspace};+use crate::bounding_volume::{Aabb, BoundingVolume};+use crate::math::{Real, VectorExt};++impl Bvh {+ /// Fully rebuilds this BVH using the given strategy.+ ///+ /// This rebuilds a BVH with the same leaves, but different intermediate nodes and depth using+ /// the specified building strategy.+ pub fn rebuild(&mut self, workspace: &mut BvhWorkspace, strategy: BvhBuildStrategy) {+ if self.nodes.len() < 2 {+ // Nothing to rebuild if the tree is empty or only contains the root.+ // This takes care of the case where we have a partial root too.+ return;+ }++ workspace.rebuild_leaves.clear();+ for node in self.nodes.iter() {+ if node.left.is_leaf() {+ workspace.rebuild_leaves.push(node.left);+ }+ if node.right.is_leaf() {+ workspace.rebuild_leaves.push(node.right);+ }+ }++ self.nodes.clear();+ self.parents.clear();+ self.free_wide_nodes.clear();+ self.nodes.push(BvhNodeWide::zeros());+ self.parents.push(BvhNodeIndex::default());++ match strategy {+ BvhBuildStrategy::Binned => self.rebuild_range_binned(0, &mut workspace.rebuild_leaves),+ BvhBuildStrategy::Ploc => self.rebuild_range_ploc(0, &mut workspace.rebuild_leaves),+ }+ }++ pub(crate) fn rebuild_range_binned(&mut self, target_node_id: u32, leaves: &mut [BvhNode]) {+ // PERF: calculate an optimal bin count dynamically based on the number of leaves to split?+ // The paper suggests (4 + 2 * sqrt(num_leaves).floor()).min(16)+ const NUM_BINS: usize = 8;+ const BIN_EPSILON: Real = 1.0e-5;++ let mut bins = [BvhBin::default(); NUM_BINS];++ assert!(leaves.len() > 1);++ let centroid_aabb = Aabb::from_points(leaves.iter().map(|node| node.center()));+ let bins_axis = centroid_aabb.extents().max_position();+ let bins_range = [+ centroid_aabb.mins.vget(bins_axis),+ centroid_aabb.maxs.vget(bins_axis),+ ];++ // Compute bins characteristics.+ let k1 = NUM_BINS as Real * (1.0 - BIN_EPSILON) / (bins_range[1] - bins_range[0]);+ let k0 = bins_range[0];+ // NOTE: the clamp guards against degenerate leaf AABBs, whose non-finite or very+ // large coordinates would push the bin index outside [0, NUM_BINS - 1]+ // (`as usize` saturates).+ let bin_id_unclamped = |center: Real| (k1 * (center - k0)) as usize;+ for leaf in &*leaves {+ let bin_id = bin_id_unclamped(leaf.center().vget(bins_axis)).min(NUM_BINS - 1);+ let bin = &mut bins[bin_id];+ bin.aabb.merge(&leaf.aabb());+ bin.leaf_count += 1;+ }++ // Select the best splitting plane (there are NUM_BINS - 1 splitting planes) based on SAH.+ let mut right_merges = bins;+ let mut right_acc = bins[NUM_BINS - 1];++ for i in 1..NUM_BINS - 1 {+ right_acc.aabb.merge(&right_merges[NUM_BINS - 1 - i].aabb);+ right_acc.leaf_count += &right_merges[NUM_BINS - 1 - i].leaf_count;+ right_merges[NUM_BINS - 1 - i] = right_acc;+ }++ let mut best_cost = Real::MAX;+ let mut best_plane = 0;+ let mut left_merge = bins[0];+ let mut best_leaf_count = bins[0].leaf_count;++ for i in 0..NUM_BINS - 1 {+ let right = &right_merges[i + 1];++ let cost = left_merge.aabb.volume() * left_merge.leaf_count as Real+ + right.aabb.volume() * right.leaf_count as Real;+ if cost < best_cost {+ best_cost = cost;+ best_plane = i;+ best_leaf_count = left_merge.leaf_count;+ }++ left_merge.aabb.merge(&bins[i + 1].aabb);+ left_merge.leaf_count += bins[i + 1].leaf_count;+ }++ // With the splitting plane selected, sort & split the leaves in place.+ let mut mid = best_leaf_count as usize;++ // In degenerate cases where all the node end up on the same bin,+ // just split the range in two.+ if mid == 0 || mid == leaves.len() {+ mid = leaves.len() / 2;+ } else {+ // Sort in-place.+ // TODO PERF: try with using teh leaves_tmp instead of in-place sorting.+ let bin = |leaves: &mut [BvhNode], id: usize| {+ let node = &leaves[id];+ bin_id_unclamped(node.center().vget(bins_axis)).min(NUM_BINS - 1)+ };++ let mut left_id = 0;+ let mut right_id = mid;++ 'outer: while left_id != mid && right_id != leaves.len() {+ while bin(leaves, left_id) <= best_plane {+ left_id += 1;++ if left_id == mid {+ break 'outer;+ }+ }++ while bin(leaves, right_id) > best_plane {+ right_id += 1;++ if right_id == leaves.len() {+ break 'outer;+ }+ }++ leaves.swap(left_id, right_id);+ left_id += 1;+ right_id += 1;+ }+ }++ // Recurse.+ let (left_leaves, right_leaves) = leaves.split_at_mut(mid);++ assert!(!left_leaves.is_empty() && !right_leaves.is_empty());++ // Recurse.+ if left_leaves.len() == 1 {+ let target = &mut self.nodes[target_node_id as usize];+ target.left = left_leaves[0];++ if target.left.is_leaf() {+ self.leaf_node_indices[target.left.children as usize] =+ BvhNodeIndex::left(target_node_id);+ } else {+ self.parents[target.left.children as usize] = BvhNodeIndex::left(target_node_id);+ }+ } else {+ let left_id = self.nodes.len() as u32;+ self.nodes.push(BvhNodeWide::zeros());+ self.parents.push(BvhNodeIndex::left(target_node_id));+ self.rebuild_range_binned(left_id, left_leaves);+ self.nodes[target_node_id as usize].left = self.nodes[left_id as usize].merged(left_id);+ }++ if right_leaves.len() == 1 {+ let target = &mut self.nodes[target_node_id as usize];+ target.right = right_leaves[0];++ if target.right.is_leaf() {+ self.leaf_node_indices[target.right.children as usize] =+ BvhNodeIndex::right(target_node_id);+ } else {+ self.parents[target.right.children as usize] = BvhNodeIndex::right(target_node_id);+ }+ } else {+ let right_id = self.nodes.len() as u32;+ self.nodes.push(BvhNodeWide::zeros());+ self.parents.push(BvhNodeIndex::right(target_node_id));+ self.rebuild_range_binned(right_id, right_leaves);+ self.nodes[target_node_id as usize].right =+ self.nodes[right_id as usize].merged(right_id);+ }+ }+}++#[derive(Copy, Clone, Debug)]+struct BvhBin {+ aabb: Aabb,+ leaf_count: u32,+}++impl Default for BvhBin {+ fn default() -> Self {+ Self {+ aabb: Aabb::new_invalid(),+ leaf_count: 0,+ }+ }+}diff --git a/renderer/third_party/parry3d/src/partitioning/bvh/bvh_insert.rs b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_insert.rsnew file mode 100644index 0000000..e0b9ae6--- /dev/null+++ b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_insert.rs@@ -0,0 +1,730 @@+use super::bvh_tree::{BvhNodeIndex, BvhNodeWide};+use super::BvhNode;+use crate::bounding_volume::{Aabb, BoundingVolume};+use crate::math::{Real, Vector};+use crate::partitioning::Bvh;+use alloc::vec;+#[cfg(feature = "parallel")]+use alloc::vec::Vec;++/// Result of a leaf update through [`Bvh::insert_or_update_partially`] or+/// [`Bvh::insert_with_change_detection`].+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub enum BvhLeafUpdateStatus {+ /// The leaf already existed and its stored (fattened) AABB still contains the new+ /// AABB: the tree was left completely untouched.+ Unchanged,+ /// The leaf already existed and its stored AABB was rewritten in place (with+ /// [`Bvh::insert_or_update_partially`], its ancestors might no longer enclose it+ /// until the next refit).+ UpdatedInPlace,+ /// The leaf didn't exist yet and was inserted (the tree topology changed).+ Inserted,+}++impl Bvh {+ /// Inserts a new leaf into the BVH or updates an existing one.+ ///+ /// If a leaf with the given `leaf_index` already exists in the tree, its AABB is updated+ /// to the new value and the tree's internal nodes are adjusted to maintain correctness.+ /// If the leaf doesn't exist, it's inserted into an optimal position based on the+ /// Surface Area Heuristic (SAH).+ ///+ /// This operation automatically propagates AABB changes up the tree to maintain the+ /// invariant that each internal node's AABB encloses all its descendants. For better+ /// performance when updating many leaves, consider using [`insert_or_update_partially`]+ /// followed by a single [`refit`] call.+ ///+ /// # Arguments+ ///+ /// * `aabb` - The Axis-Aligned Bounding Box for this leaf+ /// * `leaf_index` - A unique identifier for this leaf (typically an object ID)+ ///+ /// # Performance+ ///+ /// - **Insert new leaf**: O(log n) average, O(n) worst case+ /// - **Update existing leaf**: O(log n) for propagation up the tree+ ///+ /// # Examples+ ///+ /// ## Adding new objects+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::Bvh;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let mut bvh = Bvh::new();+ ///+ /// // Insert objects with custom IDs+ /// bvh.insert(Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)), 100);+ /// bvh.insert(Aabb::new(Vector::new(5.0, 0.0, 0.0), Vector::new(6.0, 1.0, 1.0)), 200);+ /// bvh.insert(Aabb::new(Vector::new(10.0, 0.0, 0.0), Vector::new(11.0, 1.0, 1.0)), 300);+ ///+ /// assert_eq!(bvh.leaf_count(), 3);+ /// # }+ /// ```+ ///+ /// ## Updating object positions+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::Bvh;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let mut bvh = Bvh::new();+ ///+ /// // Insert an object+ /// bvh.insert(Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)), 42);+ ///+ /// // Simulate the object moving - just insert with the same ID+ /// bvh.insert(Aabb::new(Vector::new(5.0, 0.0, 0.0), Vector::new(6.0, 1.0, 1.0)), 42);+ ///+ /// // The BVH still has only 1 leaf, but at the new position+ /// assert_eq!(bvh.leaf_count(), 1);+ /// # }+ /// ```+ ///+ /// ## Bulk updates with better performance+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhWorkspace};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let mut bvh = Bvh::new();+ /// let mut workspace = BvhWorkspace::default();+ ///+ /// // Add initial objects+ /// for i in 0..100 {+ /// let aabb = Aabb::new(+ /// Vector::new(i as f32, 0.0, 0.0),+ /// Vector::new(i as f32 + 1.0, 1.0, 1.0)+ /// );+ /// bvh.insert(aabb, i);+ /// }+ ///+ /// // For better performance on bulk updates, use insert_or_update_partially+ /// // then refit once at the end+ /// for i in 0..100 {+ /// let aabb = Aabb::new(+ /// Vector::new(i as f32 + 0.1, 0.0, 0.0),+ /// Vector::new(i as f32 + 1.1, 1.0, 1.0)+ /// );+ /// bvh.insert_or_update_partially(aabb, i, 0.0);+ /// }+ /// bvh.refit(&mut workspace); // Update tree in one pass+ /// # }+ /// ```+ ///+ /// # Notes+ ///+ /// - Leaf indices can be any `u32` value - they don't need to be contiguous+ /// - The same leaf index can only exist once in the tree+ /// - For dynamic scenes, call this every frame for moving objects+ /// - Consider calling [`refit`] or [`optimize_incremental`] periodically for best+ /// query performance+ ///+ /// # See Also+ ///+ /// - [`insert_with_change_detection`](Self::insert_with_change_detection) - Insert with+ /// margin for motion prediction+ /// - [`insert_or_update_partially`](Self::insert_or_update_partially) - Insert without+ /// propagation (faster for bulk updates)+ /// - [`remove`](Self::remove) - Remove a leaf from the tree+ /// - [`refit`](Self::refit) - Update tree after bulk modifications+ ///+ /// [`insert_or_update_partially`]: Self::insert_or_update_partially+ /// [`refit`]: Self::refit+ /// [`optimize_incremental`]: Self::optimize_incremental+ pub fn insert(&mut self, aabb: Aabb, leaf_index: u32) {+ let _ = self.insert_with_change_detection(aabb, leaf_index, 0.0);+ }++ /// Inserts a leaf into this BVH, or updates it if already exists.+ ///+ /// If the `aabb` is already contained by the existing leaf node AABB, nothing is modified.+ /// Otherwise, the aabb being effectively inserted is equal to `aabb` enlarged by the+ /// `change_detection_margin`.+ pub fn insert_with_change_detection(+ &mut self,+ aabb: Aabb,+ leaf_index: u32,+ change_detection_margin: Real,+ ) -> BvhLeafUpdateStatus {+ if let Some(leaf) = self.leaf_node_indices.get(leaf_index as usize) {+ let node = &mut self.nodes[*leaf];++ if change_detection_margin > 0.0 {+ if !node.contains_aabb(&aabb) {+ node.mins = aabb.mins - Vector::splat(change_detection_margin);+ node.maxs = aabb.maxs + Vector::splat(change_detection_margin);+ node.data.set_change_pending();+ } else {+ // No change detected, no propagation needed.+ return BvhLeafUpdateStatus::Unchanged;+ }+ } else {+ node.mins = aabb.mins;+ node.maxs = aabb.maxs;+ }++ // Propagate up.+ // TODO: maybe we should offer multiple propagation strategy.+ // The one we currently implement simply stops as soon as a+ // parent node contains the given `aabb`, but it won’t try+ // to make the parent AABBs smaller even if we could.+ // There could be two additional strategies that are slower but would leave the+ // tree in a tighter state:+ // - Make the parent smaller if possible by merging the aabb with+ // the sibling.+ // - In addition to merging with the sibling, we could apply bottom-up+ // tree rotations to optimize part of the tree on our way up to the+ // root.+ let wide_node_id = leaf.decompose().0;+ if wide_node_id == 0 {+ // Already at the root, no propagation possible.+ return BvhLeafUpdateStatus::UpdatedInPlace;+ }++ let mut parent = self.parents[wide_node_id];+ loop {+ let node = &mut self.nodes[parent];+ if node.contains_aabb(&aabb) {+ // No more propagation needed, the parent is big enough.+ break;+ }++ node.mins = node.mins.min(aabb.mins);+ node.maxs = node.maxs.max(aabb.maxs);++ let wide_node_id = parent.decompose().0;+ if wide_node_id == 0 {+ break;+ }++ parent = self.parents[wide_node_id];+ }++ BvhLeafUpdateStatus::UpdatedInPlace+ } else {+ self.insert_new_unchecked(aabb, leaf_index);+ BvhLeafUpdateStatus::Inserted+ }+ }++ /// Either inserts a node on this tree, or, if it already exists, updates its associated bounding+ /// but doesn’t update its ascendant nodes.+ ///+ /// This method is primarily designed to be called for inserting new nodes or updating existing+ /// ones, and then running a [`Bvh::refit`]. Until [`Bvh::refit`] or [`Bvh::refit_without_opt`]+ /// is called, the BVH will effectively be left in an invalid state where some internal nodes+ /// might no longer enclose their children.+ ///+ /// For an alternative that inserts a node while also making sure all its ascendants are+ /// up to date, see [`Bvh::insert`].+ pub fn insert_or_update_partially(+ &mut self,+ aabb: Aabb,+ leaf_index: u32,+ change_detection_margin: Real,+ ) -> BvhLeafUpdateStatus {+ match self.update_partially_if_present(aabb, leaf_index, change_detection_margin) {+ Some(status) => status,+ None => {+ self.insert_new_unchecked(aabb, leaf_index);+ BvhLeafUpdateStatus::Inserted+ }+ }+ }++ /// [`Self::insert_or_update_partially`] restricted to leaves already in the tree:+ /// returns `None`, leaving the tree untouched, when `leaf_index` has no leaf yet.+ ///+ /// Lets a caller apply every in-place update before any structural insertion — the+ /// order `insert_or_update_batch_partially_parallel` imposes, since its updates+ /// run concurrently — without paying a second lookup to find out which updates are+ /// insertions.+ pub fn update_partially_if_present(+ &mut self,+ aabb: Aabb,+ leaf_index: u32,+ change_detection_margin: Real,+ ) -> Option<BvhLeafUpdateStatus> {+ let leaf = *self.leaf_node_indices.get(leaf_index as usize)?;+ let node = &mut self.nodes[leaf];++ if change_detection_margin > 0.0 {+ if !node.contains_aabb(&aabb) {+ node.mins = aabb.mins - Vector::splat(change_detection_margin);+ node.maxs = aabb.maxs + Vector::splat(change_detection_margin);+ node.data.set_change_pending();+ Some(BvhLeafUpdateStatus::UpdatedInPlace)+ } else {+ // The new AABB is still inside the leaf's fat AABB: the tree+ // is left untouched.+ Some(BvhLeafUpdateStatus::Unchanged)+ }+ } else {+ node.mins = aabb.mins;+ node.maxs = aabb.maxs;+ Some(BvhLeafUpdateStatus::UpdatedInPlace)+ }+ }++ /// Batch, parallel version of [`Self::insert_or_update_partially`].+ ///+ /// Applies every update whose leaf already exists in parallel (existing+ /// leaves are updated in place: distinct leaf indices map to distinct+ /// [`BvhNode`]s, so the writes are disjoint — two sibling leaves share a+ /// wide node but occupy its two disjoint halves), then inserts the new+ /// leaves sequentially. `statuses` is filled with one entry per update, in+ /// order.+ ///+ /// Like [`Self::insert_or_update_partially`], the ascendants of updated+ /// leaves are **not** updated: the tree must be refitted (e.g.+ /// [`Bvh::refit`]) before the next query for its results to be exact.+ ///+ /// # Panics+ ///+ /// May panic (or leave arbitrary leaf AABBs, but no memory unsafety beyond+ /// a torn AABB) if the same leaf index appears twice in `updates`.+ #[cfg(feature = "parallel")]+ pub fn insert_or_update_batch_partially_parallel(+ &mut self,+ updates: &[(Aabb, u32, Real)],+ statuses: &mut Vec<BvhLeafUpdateStatus>,+ ) {+ use rayon::prelude::*;++ statuses.clear();+ statuses.resize(updates.len(), BvhLeafUpdateStatus::Unchanged);++ // Phase 1 (parallel): in-place updates of the existing leaves.+ struct NodesPtr(*mut BvhNodeWide);+ unsafe impl Sync for NodesPtr {}+ let nodes = &NodesPtr(self.nodes.0.as_mut_ptr());+ let leaf_node_indices = &self.leaf_node_indices;++ updates.par_iter().zip(statuses.par_iter_mut()).for_each(+ move |((aabb, leaf_index, change_detection_margin), status)| {+ let Some(leaf) = leaf_node_indices.get(*leaf_index as usize) else {+ // Structural change: deferred to the sequential phase below.+ *status = BvhLeafUpdateStatus::Inserted;+ return;+ };+ let (wide_id, is_right) = leaf.decompose();+ // SAFETY: distinct leaf indices map to distinct (wide, side)+ // slots, i.e. disjoint `BvhNode`s; `leaf_node_indices`+ // is only read during this phase.+ let wide = unsafe { &mut *nodes.0.add(wide_id) };+ let node = if is_right {+ &mut wide.right+ } else {+ &mut wide.left+ };++ if *change_detection_margin > 0.0 {+ if !node.contains_aabb(aabb) {+ node.mins = aabb.mins - Vector::splat(*change_detection_margin);+ node.maxs = aabb.maxs + Vector::splat(*change_detection_margin);+ node.data.set_change_pending();+ *status = BvhLeafUpdateStatus::UpdatedInPlace;+ } else {+ // The new AABB is still inside the leaf's fat AABB: the+ // tree is left untouched.+ *status = BvhLeafUpdateStatus::Unchanged;+ }+ } else {+ node.mins = aabb.mins;+ node.maxs = aabb.maxs;+ *status = BvhLeafUpdateStatus::UpdatedInPlace;+ }+ },+ );++ // Phase 2 (sequential): structural insertions.+ for (update, status) in updates.iter().zip(statuses.iter()) {+ if *status == BvhLeafUpdateStatus::Inserted {+ self.insert_new_unchecked(update.0, update.1);+ }+ }+ }++ /// Inserts a new leaf into this BVH without checking if it already exists.+ fn insert_new_unchecked(&mut self, aabb: Aabb, leaf_index: u32) {+ let _ = self+ .leaf_node_indices+ .insert(leaf_index as usize, BvhNodeIndex::default());+ let leaf_index_mut = &mut self.leaf_node_indices[leaf_index as usize];++ // If the tree is empty, create the root.+ if self.nodes.is_empty() {+ self.nodes.push(BvhNodeWide {+ left: BvhNode::leaf(aabb, leaf_index),+ right: BvhNode::zeros(),+ });+ self.parents.push(BvhNodeIndex::default());+ *leaf_index_mut = BvhNodeIndex::left(0);+ return;+ }++ // If we have a root, but it is partial, just complete it.+ if self.nodes[0].right.leaf_count() == 0 {+ self.nodes[0].right = BvhNode::leaf(aabb, leaf_index);+ *leaf_index_mut = BvhNodeIndex::right(0);+ return;+ }++ // General case: traverse the tree to find room for the new leaf.+ let mut curr_id = 0u32;+ let mut path_taken = vec![];++ const APPLY_ROTATIONS_DOWN: bool = true;+ const APPLY_ROTATIONS_UP: bool = false;++ loop {+ if APPLY_ROTATIONS_UP {+ path_taken.push(curr_id);+ }++ if APPLY_ROTATIONS_DOWN {+ self.maybe_apply_rotation(curr_id);+ }++ let curr_node = &self.nodes[curr_id as usize];++ // Need to determine the best side to insert our node.+ let left = &curr_node.left;+ let right = &curr_node.right;++ let left_merged_aabb = left.aabb().merged(&aabb);+ let right_merged_aabb = right.aabb().merged(&aabb);++ let left_merged_vol = left_merged_aabb.volume();+ let right_merged_vol = right_merged_aabb.volume();+ let left_vol = left.aabb().volume();+ let right_vol = right.aabb().volume();+ let left_count = left.leaf_count();+ let right_count = right.leaf_count();++ // NOTE: when calculating the SAH cost, we don’t care about dividing by the+ // parent’s volume since both compared costs use the same factor so+ // ignoring it doesn’t affect the comparison.+ let left_cost =+ left_merged_vol * (left_count + 1) as Real + right_vol * right_count as Real;+ let right_cost =+ right_merged_vol * (right_count + 1) as Real + left_vol * left_count as Real;++ // Insert into the branch with lowest post-insertion SAH cost.+ // If the costs are equal, just pick the branch with the smallest leaf count.+ if left_cost < right_cost || (left_cost == right_cost && left_count < right_count) {+ // Insert left. The `left` node will become an internal node.+ // We create a new wide leaf containing the current and new leaves and+ // attach it to `left`.+ if left.is_leaf() {+ let wide_node = BvhNodeWide {+ left: *left,+ right: BvhNode::leaf(aabb, leaf_index),+ };+ let new_leaf_id = self.alloc_wide_node(wide_node, BvhNodeIndex::left(curr_id));++ let left = &mut self.nodes[curr_id as usize].left;+ self.leaf_node_indices[left.children as usize] =+ BvhNodeIndex::left(new_leaf_id as u32);+ self.leaf_node_indices[leaf_index as usize] =+ BvhNodeIndex::right(new_leaf_id as u32);++ left.children = new_leaf_id as u32;+ left.data.add_leaf_count(1);+ left.mins = left.mins.min(aabb.mins);+ left.maxs = left.maxs.max(aabb.maxs);+ break;+ } else {+ let left = &mut self.nodes[curr_id as usize].left;+ curr_id = left.children;+ left.data.add_leaf_count(1);+ left.mins = left.mins.min(aabb.mins);+ left.maxs = left.maxs.max(aabb.maxs);+ }+ } else {+ // Insert right. The `right` node will become an internal node.+ // We create a new wide leaf containing the current and new leaves and+ // attach it to `right`.+ if right.is_leaf() {+ let new_node = BvhNodeWide {+ left: BvhNode::leaf(aabb, leaf_index),+ right: *right,+ };+ let new_leaf_id = self.alloc_wide_node(new_node, BvhNodeIndex::right(curr_id));++ let right = &mut self.nodes[curr_id as usize].right;+ self.leaf_node_indices[leaf_index as usize] =+ BvhNodeIndex::left(new_leaf_id as u32);+ self.leaf_node_indices[right.children as usize] =+ BvhNodeIndex::right(new_leaf_id as u32);++ right.children = new_leaf_id as u32;+ right.data.add_leaf_count(1);+ right.mins = right.mins.min(aabb.mins);+ right.maxs = right.maxs.max(aabb.maxs);+ break;+ } else {+ let right = &mut self.nodes[curr_id as usize].right;+ curr_id = right.children;+ right.data.add_leaf_count(1);+ right.mins = right.mins.min(aabb.mins);+ right.maxs = right.maxs.max(aabb.maxs);+ }+ }+ }++ if APPLY_ROTATIONS_UP {+ while let Some(node) = path_taken.pop() {+ self.maybe_apply_rotation(node);+ }+ }+ }++ /// Allocates a slot for a new wide node, preferring slots orphaned by earlier+ /// leaf removals over growing the node array.+ fn alloc_wide_node(&mut self, node: BvhNodeWide, parent: BvhNodeIndex) -> usize {+ if let Some(free) = self.free_wide_nodes.pop() {+ self.nodes[free as usize] = node;+ self.parents[free as usize] = parent;+ free as usize+ } else {+ let id = self.nodes.len();+ self.nodes.push(node);+ self.parents.push(parent);+ id+ }+ }++ /// Updates the leaf AABB like [`Self::insert_with_change_detection`], but+ /// relocates the leaf through a removal + SAH re-insertion whenever its fattened+ /// AABB must actually change.+ ///+ /// Unlike the in-place update of [`Self::insert_with_change_detection`] (which+ /// keeps the leaf's tree position and only enlarges its ancestors), the+ /// re-insertion picks a fresh position by SAH descent — including rotations —+ /// so a stream of such updates keeps the tree quality high on its own, without+ /// requiring periodic [`Self::optimize_incremental`] passes. The freed wide-node+ /// slot is recycled by the re-insertion itself, so the node array doesn't grow.+ ///+ /// This is the preferred update path when only a small fraction of the leaves+ /// move (the per-leaf cost is an O(log n) descent instead of O(1)); for bulk+ /// updates, prefer in-place updates followed by a refit and periodic+ /// optimization.+ ///+ /// Compatible with [`Self::refit_partial`] under the same rules as insertions.+ pub fn reinsert_or_update_with_change_detection(+ &mut self,+ aabb: Aabb,+ leaf_index: u32,+ change_detection_margin: Real,+ ) -> BvhLeafUpdateStatus {+ match self.reinsert_or_update_if_present(aabb, leaf_index, change_detection_margin) {+ Some(status) => status,+ None => {+ self.insert_new_unchecked(aabb, leaf_index);+ BvhLeafUpdateStatus::Inserted+ }+ }+ }++ /// [`Self::reinsert_or_update_with_change_detection`] restricted to leaves already in+ /// the tree: returns `None`, leaving the tree untouched, when `leaf_index` has no leaf+ /// yet. See [`Self::update_partially_if_present`].+ pub fn reinsert_or_update_if_present(+ &mut self,+ aabb: Aabb,+ leaf_index: u32,+ change_detection_margin: Real,+ ) -> Option<BvhLeafUpdateStatus> {+ let leaf = *self.leaf_node_indices.get(leaf_index as usize)?;+ if self.nodes[leaf].contains_aabb(&aabb) {+ return Some(BvhLeafUpdateStatus::Unchanged);+ }++ self.remove(leaf_index);+ let fat_aabb = Aabb {+ mins: aabb.mins - Vector::splat(change_detection_margin),+ maxs: aabb.maxs + Vector::splat(change_detection_margin),+ };+ // The new leaf is created with a pending change flag, exactly like an+ // in-place update that escaped its previous fattened AABB.+ self.insert_new_unchecked(fat_aabb, leaf_index);+ Some(BvhLeafUpdateStatus::UpdatedInPlace)+ }++ // Applies a tree rotation at the given `node` if this improves the SAH metric at that node.+ fn maybe_apply_rotation(&mut self, node_id: u32) {+ let node = self.nodes[node_id as usize];+ let left = &node.left;+ let right = &node.right;++ let curr_score =+ left.volume() * left.leaf_count() as Real + right.volume() * right.leaf_count() as Real;++ macro_rules! eval_costs {+ ($left: ident, $right: ident) => {+ if !$left.is_leaf() {+ let children = self.nodes[$left.children as usize];+ let left_child = &children.left;+ let right_child = &children.right;++ // New SAH score after transforming [{left_child, right_child}, right]+ // into [left_child, {right_child, right}].+ let new_score1 = left_child.volume() * left_child.leaf_count() as Real+ + right_child.merged_volume($right)+ * (right_child.leaf_count() + $right.leaf_count()) as Real;++ // New SAH score after transforming [{left_child, right_child}, right]+ // into [right_child, {left_child, right}].+ let new_score2 = right_child.volume() * right_child.leaf_count() as Real+ + left_child.merged_volume($right)+ * (left_child.leaf_count() + $right.leaf_count()) as Real;++ if new_score1 < new_score2 {+ (new_score1 - curr_score, true)+ } else {+ (new_score2 - curr_score, false)+ }+ } else {+ (Real::MAX, false)+ }+ };+ }++ // Because of the rotation some leaves might have changed location.+ // This a helper to update the `leaf_data` map accordingly.+ macro_rules! set_leaf_data {+ ($leaf_data_id: ident, $node_id: ident, $left_or_right: expr) => {+ self.leaf_node_indices[$leaf_data_id as usize] =+ BvhNodeIndex::new($node_id, $left_or_right);+ };+ }++ // For right rotation.+ let (rotation_score0, left_child_moves_up0) = eval_costs!(left, right);+ // For left rotation.+ let (rotation_score1, left_child_moves_up1) = eval_costs!(right, left);++ if rotation_score0 < 0.0 || rotation_score1 < 0.0 {+ // At least one of the rotations is worth it, apply the one with+ // the best impact on SAH scoring.+ if rotation_score0 < rotation_score1 {+ // Apply RIGHT rotation.+ let children_id = left.children;+ let children = self.nodes[children_id as usize];+ let left_child = &children.left;+ let right_child = &children.right;++ let right_is_leaf = right.is_leaf();+ let left_child_is_leaf = left_child.is_leaf();+ let right_child_is_leaf = right_child.is_leaf();++ let right_leaf_data = right.children;+ let left_child_leaf_data = left_child.children;+ let right_child_leaf_data = right_child.children;++ self.parents[children_id as usize] = BvhNodeIndex::right(node_id);++ if left_child_moves_up0 {+ // The left child moves into `left`, and `right` takes it place.+ self.nodes[node_id as usize].left = *left_child;+ self.nodes[children_id as usize].left = *right;+ self.nodes[node_id as usize].right =+ self.nodes[children_id as usize].merged(children_id);++ if left_child_is_leaf {+ self.leaf_node_indices[left_child_leaf_data as usize] =+ BvhNodeIndex::left(node_id);+ } else {+ self.parents[left_child_leaf_data as usize] = BvhNodeIndex::left(node_id);+ }+ if right_is_leaf {+ self.leaf_node_indices[right_leaf_data as usize] =+ BvhNodeIndex::left(children_id);+ } else {+ self.parents[right_leaf_data as usize] = BvhNodeIndex::left(children_id);+ }+ } else {+ // The right child moves into `left`, and `right` takes it place.+ self.nodes[node_id as usize].left = *right_child;+ self.nodes[children_id as usize].right = *right;+ self.nodes[node_id as usize].right =+ self.nodes[children_id as usize].merged(children_id);+ if right_child_is_leaf {+ self.leaf_node_indices[right_child_leaf_data as usize] =+ BvhNodeIndex::left(node_id);+ } else {+ self.parents[right_child_leaf_data as usize] = BvhNodeIndex::left(node_id);+ }+ if right_is_leaf {+ self.leaf_node_indices[right_leaf_data as usize] =+ BvhNodeIndex::right(children_id);+ } else {+ self.parents[right_leaf_data as usize] = BvhNodeIndex::right(children_id);+ }+ }+ } else {+ // Apply LEFT rotation.+ let children_id = right.children;+ let children = self.nodes[children_id as usize];+ let left_child = &children.left;+ let right_child = &children.right;++ let left_is_leaf = left.is_leaf();+ let left_child_is_leaf = left_child.is_leaf();+ let right_child_is_leaf = right_child.is_leaf();++ let left_leaf_data = left.children;+ let left_child_leaf_data = left_child.children;+ let right_child_leaf_data = right_child.children;++ self.parents[children_id as usize] = BvhNodeIndex::left(node_id);++ if left_child_moves_up1 {+ // The left child moves into `right`, and `left` takes it place.+ self.nodes[node_id as usize].right = *left_child;+ self.nodes[children_id as usize].left = *left;+ self.nodes[node_id as usize].left =+ self.nodes[children_id as usize].merged(children_id);+ if left_child_is_leaf {+ self.leaf_node_indices[left_child_leaf_data as usize] =+ BvhNodeIndex::right(node_id);+ } else {+ self.parents[left_child_leaf_data as usize] = BvhNodeIndex::right(node_id);+ }+ if left_is_leaf {+ self.leaf_node_indices[left_leaf_data as usize] =+ BvhNodeIndex::left(children_id);+ } else {+ self.parents[left_leaf_data as usize] = BvhNodeIndex::left(children_id);+ }+ } else {+ // The right child moves into `right`, and `left` takes it place.+ self.nodes[node_id as usize].right = *right_child;+ self.nodes[children_id as usize].right = *left;+ self.nodes[node_id as usize].left =+ self.nodes[children_id as usize].merged(children_id);+ if right_child_is_leaf {+ set_leaf_data!(right_child_leaf_data, node_id, BvhNodeIndex::RIGHT);+ } else {+ self.parents[right_child_leaf_data as usize] = BvhNodeIndex::right(node_id);+ }+ if left_is_leaf {+ set_leaf_data!(left_leaf_data, children_id, BvhNodeIndex::RIGHT);+ } else {+ self.parents[left_leaf_data as usize] = BvhNodeIndex::right(children_id);+ }+ }+ }+ }+ }+}diff --git a/renderer/third_party/parry3d/src/partitioning/bvh/bvh_optimize.rs b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_optimize.rsnew file mode 100644index 0000000..38c798e--- /dev/null+++ b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_optimize.rs@@ -0,0 +1,578 @@+use super::{Bvh, BvhWorkspace};+use crate::math::Real;+use core::cmp::Ordering;+use ordered_float::OrderedFloat;++#[cfg(not(feature = "std"))]+use crate::math::ComplexField; // For `round` and `sqrt` in no-std+alloc builds.++impl Bvh {+ fn optimization_config(&self, frame_index: u32) -> OptimizationConfig {+ const TARGET_REBUILD_NODE_PERCENTAGE: u32 = 5;+ let num_leaves = self.nodes[0].leaf_count();+ let num_optimized_leaves = (num_leaves * TARGET_REBUILD_NODE_PERCENTAGE).div_ceil(100);++ let num_leaves_sqrt = (num_leaves as Real).sqrt();+ let root_mode = if frame_index.is_multiple_of(2) {+ RootOptimizationMode::Skip+ } else if (frame_index / 2).is_multiple_of(16) {+ RootOptimizationMode::BreadthFirst+ } else {+ RootOptimizationMode::PriorityQueue+ };++ let target_root_node_count = num_leaves_sqrt.ceil();+ let target_subtree_leaf_count = (num_leaves_sqrt * 4.0).ceil();+ let root_refinement_cost = target_root_node_count * target_root_node_count.log2()+ / (target_subtree_leaf_count * target_subtree_leaf_count.log2());+ let mut target_optimized_subtree_count =+ (num_optimized_leaves as Real / target_subtree_leaf_count - root_refinement_cost)+ .round()+ .max(0.0) as usize;++ if root_mode == RootOptimizationMode::Skip {+ target_optimized_subtree_count = target_optimized_subtree_count.max(1)+ }++ OptimizationConfig {+ target_root_node_count: target_root_node_count as usize,+ target_subtree_leaf_count: target_subtree_leaf_count as usize,+ target_optimized_subtree_count,+ root_mode,+ }+ }++ /// Incrementally improves tree quality after dynamic updates.+ ///+ /// This method performs one step of tree optimization by rebuilding small portions of+ /// the BVH to maintain good query performance. As objects move around, the tree's structure+ /// can become suboptimal even after refitting. This method gradually fixes these issues+ /// without the cost of rebuilding the entire tree.+ ///+ /// # What It Does+ ///+ /// Each call optimizes:+ /// - A small percentage of the tree (typically ~5% of leaves)+ /// - The root region (periodically)+ /// - Subtrees that have degraded the most+ ///+ /// The optimization is **incremental** - it's designed to be called repeatedly (e.g.,+ /// every few frames) to continuously maintain tree quality without large frame-time spikes.+ ///+ /// # When to Use+ ///+ /// Call `optimize_incremental`:+ /// - Every 5-10 frames for highly dynamic scenes+ /// - After many [`insert`] and [`remove`] operations+ /// - When query performance degrades over time+ /// - In physics engines, once per simulation step+ ///+ /// **Don't call this**:+ /// - Every frame (too frequent - diminishing returns)+ /// - For static scenes (not needed)+ /// - Immediately after [`from_leaves`] (tree is already optimal)+ ///+ /// # Arguments+ ///+ /// * `workspace` - A reusable workspace to avoid allocations. The same workspace+ /// can be shared across multiple BVH operations.+ ///+ /// # Performance+ ///+ /// - **Time**: O(k log k) where k is the number of leaves optimized (~5% of total)+ /// - **Target**: <1ms for trees with 10,000 leaves (on modern hardware)+ /// - Spreads optimization cost over many frames+ /// - Much cheaper than full rebuild (O(n log n))+ ///+ /// # Examples+ ///+ /// ## In a game loop+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhWorkspace};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let mut bvh = Bvh::new();+ /// let mut workspace = BvhWorkspace::default();+ ///+ /// // Add initial objects+ /// for i in 0..1000 {+ /// let aabb = Aabb::new(+ /// Vector::new(i as f32, 0.0, 0.0),+ /// Vector::new(i as f32 + 1.0, 1.0, 1.0)+ /// );+ /// bvh.insert(aabb, i);+ /// }+ ///+ /// // Game loop+ /// for frame in 0..1000 {+ /// // Update object positions every frame+ /// for i in 0..1000 {+ /// let time = frame as f32 * 0.016;+ /// let offset = (time * (i as f32 + 1.0)).sin() * 5.0;+ /// let aabb = Aabb::new(+ /// Vector::new(i as f32 + offset, 0.0, 0.0),+ /// Vector::new(i as f32 + offset + 1.0, 1.0, 1.0)+ /// );+ /// bvh.insert_or_update_partially(aabb, i, 0.0);+ /// }+ ///+ /// // Update AABBs every frame (fast)+ /// bvh.refit(&mut workspace);+ ///+ /// // Optimize tree quality every 5 frames (slower but important)+ /// if frame % 5 == 0 {+ /// bvh.optimize_incremental(&mut workspace);+ /// }+ ///+ /// // Perform queries (ray casts, collision detection, etc.)+ /// }+ /// # }+ /// ```+ ///+ /// ## Physics engine broad-phase+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhWorkspace};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let mut bvh = Bvh::new();+ /// let mut workspace = BvhWorkspace::default();+ ///+ /// // Simulation loop+ /// for step in 0..100 {+ /// // Physics update: integrate velocities, forces, etc.+ /// // Update BVH with new rigid body positions+ /// for body_id in 0..100 {+ /// let aabb = get_body_aabb(body_id);+ /// bvh.insert_or_update_partially(aabb, body_id, 0.0);+ /// }+ ///+ /// // Refit tree for new positions+ /// bvh.refit(&mut workspace);+ ///+ /// // Optimize tree quality once per step+ /// bvh.optimize_incremental(&mut workspace);+ ///+ /// // Broad-phase collision detection+ /// // let pairs = find_overlapping_pairs(&bvh);+ /// // ...+ /// }+ ///+ /// # fn get_body_aabb(id: u32) -> Aabb {+ /// # Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0))+ /// # }+ /// # }+ /// ```+ ///+ /// ## After many insertions/removals+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhWorkspace};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let mut bvh = Bvh::new();+ /// let mut workspace = BvhWorkspace::default();+ ///+ /// // Dynamically add many objects over time+ /// for i in 0..1000 {+ /// let aabb = Aabb::new(+ /// Vector::new(i as f32, 0.0, 0.0),+ /// Vector::new(i as f32 + 1.0, 1.0, 1.0)+ /// );+ /// bvh.insert(aabb, i);+ ///+ /// // Periodically optimize while building+ /// if i % 100 == 0 && i > 0 {+ /// bvh.optimize_incremental(&mut workspace);+ /// }+ /// }+ ///+ /// // Tree is now well-optimized despite incremental construction+ /// # }+ /// ```+ ///+ /// # How It Works+ ///+ /// The method uses a sophisticated strategy:+ ///+ /// 1. **Subtree Selection**: Identifies small subtrees that would benefit most from rebuilding+ /// 2. **Local Rebuild**: Rebuilds selected subtrees using the binned construction algorithm+ /// 3. **Root Optimization**: Periodically optimizes the top levels of the tree+ /// 4. **Rotation**: Tracks changes and rotates subtrees incrementally+ ///+ /// The optimization rotates through different parts of the tree on successive calls,+ /// ensuring the entire tree is eventually optimized.+ ///+ /// # Comparison with Full Rebuild+ ///+ /// | Operation | Time | When to Use |+ /// |-----------|------|-------------|+ /// | `optimize_incremental` | O(k log k), k ≈ 5% of n | Every few frames in dynamic scenes |+ /// | `from_leaves` (rebuild) | O(n log n) | When tree is very poor or scene is static |+ ///+ /// # Notes+ ///+ /// - State persists across calls - each call continues from where the last left off+ /// - Call frequency can be adjusted based on performance budget+ /// - Complementary to [`refit`] - use both for best results+ /// - The workspace stores optimization state between calls+ ///+ /// # See Also+ ///+ /// - [`refit`](Bvh::refit) - Update AABBs after leaf movements (call more frequently)+ /// - [`from_leaves`](Bvh::from_leaves) - Full rebuild (for major scene changes)+ /// - [`BvhWorkspace`] - Reusable workspace for operations+ ///+ /// [`insert`]: Bvh::insert+ /// [`remove`]: Bvh::remove+ /// [`from_leaves`]: Bvh::from_leaves+ /// [`refit`]: Bvh::refit+ pub fn optimize_incremental(&mut self, workspace: &mut BvhWorkspace) {+ if self.nodes.is_empty() {+ return;+ }++ workspace.rebuild_leaves.clear();+ self.optimization.rebuild_frame_index =+ self.optimization.rebuild_frame_index.overflowing_add(1).0;+ let config = self.optimization_config(self.optimization.rebuild_frame_index);++ /*+ * Subtree optimizations.+ */+ // let t0 = core::time::Instant::now();+ let num_leaves = self.nodes[0].leaf_count();+ let mut start_index = self.optimization.rebuild_start_index;++ // println!("Max candidate leaf count = {}", max_candidate_leaf_count);+ self.find_optimization_roots(+ workspace,+ 0,+ &mut start_index,+ config.target_optimized_subtree_count as u32,+ 0,+ config.target_subtree_leaf_count as u32,+ );++ if start_index >= num_leaves {+ start_index = 0;+ // TODO: if we hit the end of the tree, wrap back at the beginning+ // to reach the target subtree count.+ }++ self.optimization.rebuild_start_index = start_index;++ // println!(+ // "Num refinement candidates: {}, list: {:?}",+ // workspace.optimization_roots.len(),+ // workspace.optimization_roots+ // );++ /*+ * Root optimization.+ */+ workspace.rebuild_leaves.clear();++ // let t0 = core::time::Instant::now();+ match config.root_mode {+ RootOptimizationMode::BreadthFirst => self+ .find_root_optimization_pseudo_leaves_breadth_first(+ workspace,+ config.target_root_node_count,+ ),+ RootOptimizationMode::PriorityQueue => self+ .find_root_optimization_pseudo_leaves_pqueue(+ workspace,+ config.target_root_node_count,+ ),+ RootOptimizationMode::Skip => {}+ }++ if !workspace.rebuild_leaves.is_empty() {+ self.rebuild_range_binned(0, &mut workspace.rebuild_leaves);+ }+ // println!("Root optimization: {}", t0.elapsed().as_secs_f32() * 1000.0);++ /*+ * Subtree leaf optimizations.+ */+ for i in 0..workspace.optimization_roots.len() {+ let subtree_root_id = workspace.optimization_roots[i];+ workspace.rebuild_leaves.clear();+ self.collect_leaves(workspace, subtree_root_id);++ // let t1 = core::time::Instant::now();+ self.rebuild_range_binned(subtree_root_id, &mut workspace.rebuild_leaves);+ // println!(+ // "Optimized leaves: {}, time: {}",+ // workspace.rebuild_leaves.len(),+ // t1.elapsed().as_secs_f32() * 1000.0+ // );+ }++ // println!(+ // "Leaf optimization: {}, optimization roots: {}, config: {:?}",+ // t0.elapsed().as_secs_f32() * 1000.0,+ // workspace.optimization_roots.len(),+ // config+ // );+ workspace.optimization_roots.clear();+ }++ fn collect_leaves(&self, workspace: &mut BvhWorkspace, subtree_root: u32) {+ let node = &self.nodes[subtree_root as usize];+ let left = &node.left;+ let right = &node.right;++ if left.is_leaf() {+ workspace.rebuild_leaves.push(*left);+ } else {+ self.collect_leaves(workspace, left.children);+ }++ if right.is_leaf() {+ workspace.rebuild_leaves.push(*right);+ } else {+ self.collect_leaves(workspace, right.children);+ }+ }++ fn find_root_optimization_pseudo_leaves_breadth_first(+ &mut self,+ workspace: &mut BvhWorkspace,+ target_count: usize,+ ) {+ if self.nodes.len() < 2 {+ return;+ }++ workspace.dequeue.push_back(0);++ while workspace.dequeue.len() + workspace.rebuild_leaves.len() < target_count {+ let Some(curr_node) = workspace.dequeue.pop_front() else {+ break;+ };++ let node = &self.nodes[curr_node as usize];+ let left = &node.left;+ let right = &node.right;++ if left.is_leaf() || left.data.is_change_pending() {+ workspace.rebuild_leaves.push(*left);+ } else {+ workspace.dequeue.push_back(left.children);+ }++ if right.is_leaf() || right.data.is_change_pending() {+ workspace.rebuild_leaves.push(*right);+ } else {+ workspace.dequeue.push_back(right.children);+ }+ }++ for id in workspace.dequeue.drain(..) {+ let node = &self.nodes[id as usize];+ workspace.rebuild_leaves.push(node.left);+ workspace.rebuild_leaves.push(node.right);+ }+ }++ fn find_root_optimization_pseudo_leaves_pqueue(+ &mut self,+ workspace: &mut BvhWorkspace,+ target_count: usize,+ ) {+ if self.nodes.len() < 2 {+ return;+ }++ workspace.queue.push(BvhOptimizationHeapEntry {+ score: OrderedFloat(Real::MAX),+ id: 0,+ });++ while workspace.queue.len() + workspace.rebuild_leaves.len() < target_count {+ let Some(curr_node) = workspace.queue.pop() else {+ break;+ };++ let node = &self.nodes[curr_node.id as usize];+ let left = &node.left;+ let right = &node.right;++ if left.is_leaf() || left.data.is_change_pending() {+ workspace.rebuild_leaves.push(*left);+ } else {+ let children = self.nodes[left.children as usize];+ let left_score = children.left.volume() * children.left.leaf_count() as Real+ + children.right.volume() * children.right.leaf_count() as Real;+ workspace.queue.push(BvhOptimizationHeapEntry {+ score: OrderedFloat(left_score),+ id: left.children,+ });+ }++ if right.is_leaf() || right.data.is_change_pending() {+ workspace.rebuild_leaves.push(*right);+ } else {+ let children = self.nodes[right.children as usize];+ let right_score = children.left.volume() * children.left.leaf_count() as Real+ + children.right.volume() * children.right.leaf_count() as Real;+ workspace.queue.push(BvhOptimizationHeapEntry {+ score: OrderedFloat(right_score),+ id: right.children,+ });+ }+ }++ for id in workspace.queue.as_slice() {+ let node = &self.nodes[id.id as usize];+ workspace.rebuild_leaves.push(node.left);+ workspace.rebuild_leaves.push(node.right);+ }+ workspace.queue.clear();+ }++ fn find_optimization_roots(+ &mut self,+ workspace: &mut BvhWorkspace,+ curr_node: u32,+ start_index: &mut u32,+ max_optimization_roots: u32,+ mut leaf_count_before: u32,+ max_candidate_leaf_count: u32,+ ) {+ if workspace.optimization_roots.len() == max_optimization_roots as usize {+ // We reached the desired number of collected leaves. Just exit.+ return;+ }++ let node = &mut self.nodes[curr_node as usize];+ let left = &mut node.left;+ let left_leaf_count = left.leaf_count();+ let left_children = left.children;++ if leaf_count_before + left_leaf_count > *start_index {+ // Traverse the left children.+ if left_leaf_count < max_candidate_leaf_count {+ // If the node doesn’t have at least the leaves, it can’t be rebalanced.+ if left_leaf_count > 2 {+ // Mark the optimization root so that the root pseudo-leaf+ // extraction knows not to cross this node.+ // This won’t disturb bvtt traversal because refit will get+ // rid of this flag.+ left.data.set_change_pending();+ workspace.optimization_roots.push(left_children);+ *start_index += left_leaf_count;+ }+ } else {+ // This node has too many leaves. Recurse.+ self.find_optimization_roots(+ workspace,+ left_children,+ start_index,+ max_optimization_roots,+ leaf_count_before,+ max_candidate_leaf_count,+ );+ }+ }++ leaf_count_before += left_leaf_count;++ if workspace.optimization_roots.len() == max_optimization_roots as usize {+ // We reached the desired number of collected leaves. Just exit.+ return;+ }++ let node = &mut self.nodes[curr_node as usize];+ let right = &mut node.right;+ let right_leaf_count = right.leaf_count();+ let right_children = right.children;++ if leaf_count_before + right_leaf_count > *start_index {+ // Traverse the right children.+ if right_leaf_count < max_candidate_leaf_count {+ if right_leaf_count > 2 {+ // Mark the optimization root so that the root pseudo-leaf+ // extraction knows not to cross this node.+ // This won’t disturb bvtt traversal because refit will get+ // rid of this flag.+ right.data.set_change_pending();+ workspace.optimization_roots.push(right_children);+ *start_index += right_leaf_count;+ }+ } else {+ self.find_optimization_roots(+ workspace,+ right_children,+ start_index,+ max_optimization_roots,+ leaf_count_before,+ max_candidate_leaf_count,+ );+ }+ }+ }+}++/// The optimization state used by `Bvh::optimize_incremental`.+/// This allows each call to `optimize_incremental` to continue from where the last one left off.+#[derive(Clone, Debug, Default)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+pub(super) struct BvhIncrementalOptimizationState {+ pub(super) rebuild_frame_index: u32,+ pub(super) rebuild_start_index: u32,+}++#[derive(Copy, Clone, PartialEq, Eq, Debug)]+enum RootOptimizationMode {+ PriorityQueue,+ BreadthFirst,+ Skip,+}++#[derive(Copy, Clone, PartialEq, Eq, Debug)]+struct OptimizationConfig {+ target_root_node_count: usize,+ target_subtree_leaf_count: usize,+ target_optimized_subtree_count: usize,+ root_mode: RootOptimizationMode,+}++#[derive(Copy, Clone, Debug)]+pub struct BvhOptimizationHeapEntry {+ score: OrderedFloat<Real>,+ id: u32,+}++impl PartialOrd for BvhOptimizationHeapEntry {+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {+ Some(self.cmp(other))+ }+}++impl Ord for BvhOptimizationHeapEntry {+ fn cmp(&self, other: &Self) -> Ordering {+ self.score.cmp(&other.score)+ }+}++impl PartialEq for BvhOptimizationHeapEntry {+ fn eq(&self, other: &Self) -> bool {+ self.score == other.score+ }+}++impl Eq for BvhOptimizationHeapEntry {}diff --git a/renderer/third_party/parry3d/src/partitioning/bvh/bvh_ploc_build.rs b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_ploc_build.rsnew file mode 100644index 0000000..228cfe6--- /dev/null+++ b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_ploc_build.rs@@ -0,0 +1,94 @@+use super::bvh_tree::{BvhNodeIndex, BvhNodeWide};+use super::BvhNode;+use crate::bounding_volume::{Aabb, BoundingVolume};+use crate::math::Real;+use crate::partitioning::Bvh;+use crate::utils::morton;+use alloc::{vec, vec::Vec};++impl Bvh {+ pub(crate) fn rebuild_range_ploc(&mut self, target_node_id: u32, leaves: &mut Vec<BvhNode>) {+ // Compute the centroids aabb.+ let aabb = Aabb::from_points(leaves.iter().map(|l| l.center()));+ let inv_extents = aabb.extents().map(|e| 1.0 / e);++ // Sort the leaves.+ leaves.sort_by_cached_key(|node| {+ let center = (node.center() - aabb.mins) * (inv_extents);+ morton::morton_encode_u64_unorm(center)+ });++ // Build all the levels.+ const SEARCH_RADIUS: usize = 16;+ let mut merge_candidates = vec![usize::MAX; leaves.len()];+ let mut next_leaves = Vec::with_capacity(leaves.len());++ while leaves.len() > 1 {+ // Find merge candidates.+ for i in 0..leaves.len() {+ let mut best_sah = Real::MAX;+ let mut best_candidate = usize::MAX;+ for k in i.saturating_sub(SEARCH_RADIUS)..=(i + SEARCH_RADIUS).min(leaves.len() - 1)+ {+ if k != i {+ let node_i = &leaves[i];+ let node_k = &leaves[k];+ let sah = node_i+ .aabb()+ .merged(&node_k.aabb())+ .half_area_or_perimeter();+ if sah < best_sah {+ best_sah = sah;+ best_candidate = k;+ }+ }+ }+ merge_candidates[i] = best_candidate;+ }++ // Group nodes with matching merge candidates.+ for i in 0..leaves.len() {+ let k = merge_candidates[i];+ if merge_candidates[k] == i {+ if i > k {+ continue;+ }++ // Merge nodes k and i:+ let left = leaves[i];+ let right = leaves[k];+ let wide_node = BvhNodeWide { left, right };++ let id = if leaves.len() == 2 {+ self.nodes[target_node_id as usize] = wide_node;+ target_node_id+ } else {+ let id = self.nodes.len() as u32;+ let parent = wide_node.merged(id);+ self.nodes.push(wide_node);+ self.parents.push(BvhNodeIndex::default()); // Will be set when the parent is created.+ next_leaves.push(parent);+ id+ };++ if left.is_leaf() {+ self.leaf_node_indices[left.children as usize] = BvhNodeIndex::left(id);+ } else {+ self.parents[left.children as usize] = BvhNodeIndex::left(id);+ }+ if right.is_leaf() {+ self.leaf_node_indices[right.children as usize] = BvhNodeIndex::right(id);+ } else {+ self.parents[right.children as usize] = BvhNodeIndex::right(id);+ }+ } else {+ next_leaves.push(leaves[i]);+ }+ }++ // Swap for next step.+ core::mem::swap(leaves, &mut next_leaves);+ next_leaves.clear();+ }+ }+}diff --git a/renderer/third_party/parry3d/src/partitioning/bvh/bvh_queries.rs b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_queries.rsnew file mode 100644index 0000000..065e05c--- /dev/null+++ b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_queries.rs@@ -0,0 +1,319 @@+use super::{Bvh, BvhNode};+use crate::bounding_volume::Aabb;+use crate::math::Real;+use crate::math::Vector;+use crate::query::PointProjection;+use crate::query::{PointQuery, Ray};+use crate::shape::FeatureId;++#[cfg(all(feature = "dim3", feature = "f32"))]+pub(super) struct SimdInvRay {+ // TODO: we need to use `glam` here instead of `wide` because `wide` is lacking+ // operations for getting the min/max vector element.+ // We can switch back to `wide` once it's supported.+ pub origin: glamx::Vec3A,+ pub inv_dir: glamx::Vec3A,+}++#[cfg(all(feature = "dim3", feature = "f32"))]+impl From<Ray> for SimdInvRay {+ fn from(ray: Ray) -> Self {+ let inv_dir = ray.dir.map(|r| {+ if r.abs() < Real::EPSILON {+ r.signum() / Real::EPSILON+ } else {+ 1.0 / r+ }+ });+ Self {+ origin: glamx::Vec3A::from([ray.origin.x, ray.origin.y, ray.origin.z]),+ inv_dir: glamx::Vec3A::from([inv_dir.x, inv_dir.y, inv_dir.z]),+ }+ }+}++impl Bvh {+ /// Returns an iterator over all leaves whose AABBs intersect the given AABB.+ ///+ /// This efficiently finds all objects in the scene that potentially overlap with a+ /// query region. It's commonly used for:+ /// - Finding objects in a specific area+ /// - Broad-phase collision detection (find candidate pairs)+ /// - Spatial queries (what's near this position?)+ /// - Frustum culling (what's in the camera's view?)+ ///+ /// The iterator returns leaf indices corresponding to objects that were added to the BVH.+ ///+ /// # Arguments+ ///+ /// * `aabb` - The axis-aligned bounding box to test for intersections+ ///+ /// # Returns+ ///+ /// An iterator yielding `u32` leaf indices for all leaves whose AABBs intersect the+ /// query AABB. The iteration order is depth-first through the tree.+ ///+ /// # Performance+ ///+ /// - **Time**: O(log n) average case with good spatial locality+ /// - **Worst case**: O(n) if the query AABB is very large+ /// - Efficiently prunes entire subtrees that don't intersect+ /// - Zero allocations+ ///+ /// # Examples+ ///+ /// ## Find objects in a region+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// // Create a scene with objects+ /// let objects = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(5.0, 0.0, 0.0), Vector::new(6.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(10.0, 0.0, 0.0), Vector::new(11.0, 1.0, 1.0)),+ /// ];+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &objects);+ ///+ /// // Query: which objects are near the origin?+ /// let query_region = Aabb::new(+ /// Vector::new(-1.0, -1.0, -1.0),+ /// Vector::new(2.0, 2.0, 2.0)+ /// );+ ///+ /// for leaf_id in bvh.intersect_aabb(&query_region) {+ /// println!("Object {} is in the query region", leaf_id);+ /// // You can now test the actual geometry of objects[leaf_id]+ /// }+ /// # }+ /// ```+ ///+ /// ## Broad-phase collision detection+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let objects = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(0.5, 0.0, 0.0), Vector::new(1.5, 1.0, 1.0)), // Overlaps first+ /// Aabb::new(Vector::new(10.0, 0.0, 0.0), Vector::new(11.0, 1.0, 1.0)), // Far away+ /// ];+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &objects);+ ///+ /// // Find potential collision pairs+ /// let mut collision_pairs = Vec::new();+ ///+ /// for (i, aabb) in objects.iter().enumerate() {+ /// for leaf_id in bvh.intersect_aabb(aabb) {+ /// if leaf_id as usize > i { // Avoid duplicate pairs+ /// collision_pairs.push((i as u32, leaf_id));+ /// }+ /// }+ /// }+ ///+ /// // collision_pairs now contains potential collision pairs+ /// // Next step: narrow-phase test actual geometry+ /// # }+ /// ```+ ///+ /// ## Frustum culling for rendering+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let scene_objects = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(100.0, 0.0, 0.0), Vector::new(101.0, 1.0, 1.0)), // Far away+ /// ];+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &scene_objects);+ ///+ /// // Camera frustum as an AABB (simplified - real frustums are more complex)+ /// let camera_frustum = Aabb::new(+ /// Vector::new(-10.0, -10.0, -10.0),+ /// Vector::new(10.0, 10.0, 10.0)+ /// );+ ///+ /// let mut visible_objects = Vec::new();+ /// for leaf_id in bvh.intersect_aabb(&camera_frustum) {+ /// visible_objects.push(leaf_id);+ /// }+ ///+ /// // Only render visible_objects - massive performance win!+ /// assert_eq!(visible_objects.len(), 2); // Far object culled+ /// # }+ /// ```+ ///+ /// ## Finding neighbors for an object+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::{Aabb, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let objects = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(1.5, 0.0, 0.0), Vector::new(2.5, 1.0, 1.0)),+ /// Aabb::new(Vector::new(100.0, 0.0, 0.0), Vector::new(101.0, 1.0, 1.0)),+ /// ];+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &objects);+ ///+ /// // Expand an object's AABB to find nearby objects+ /// let search_radius = 2.0;+ /// let expanded = objects[0].loosened(search_radius);+ ///+ /// let mut neighbors = Vec::new();+ /// for leaf_id in bvh.intersect_aabb(&expanded) {+ /// if leaf_id != 0 { // Don't include the object itself+ /// neighbors.push(leaf_id);+ /// }+ /// }+ ///+ /// // neighbors contains objects within search_radius of object 0+ /// # }+ /// ```+ ///+ /// # Notes+ ///+ /// - This only tests AABB-AABB intersection, which is conservative (may have false positives)+ /// - For exact collision detection, test actual geometry after getting candidates+ /// - The iterator is lazy - work is only done as you consume items+ /// - Empty queries (no intersections) are very fast due to early pruning+ ///+ /// # See Also+ ///+ /// - [`cast_ray`](Self::cast_ray) - Ray casting queries+ /// - [`project_point`](Self::project_point) - Find closest point+ /// - [`traverse`](Self::traverse) - Custom traversal logic+ /// - [`leaves`](Self::leaves) - General leaf iteration with predicate+ pub fn intersect_aabb<'a>(&'a self, aabb: &'a Aabb) -> impl Iterator<Item = u32> + 'a {+ // The query as a node: the node-vs-node test is the SIMD one (same inclusive semantics).+ let query = BvhNode::leaf(*aabb, 0);+ self.leaves(move |node: &BvhNode| node.intersects(&query))+ }++ /// Projects a point on this BVH using the provided leaf projection function.+ ///+ /// The `primitive_check` delegates the point-projection task to an external function that+ /// is assumed to map a leaf index to an actual geometry to project on. The `Real` argument+ /// given to that closure is the distance to the closest point found so far (or is equal to+ /// `max_distance` if no projection was found so far).+ pub fn project_point(+ &self,+ point: Vector,+ max_distance: Real,+ primitive_check: impl Fn(u32, Real) -> Option<PointProjection>,+ ) -> Option<(u32, (Real, PointProjection))> {+ self.find_best(+ max_distance,+ |node: &BvhNode, _| node.aabb().distance_to_local_point(point, true),+ |primitive, _| {+ let proj = primitive_check(primitive, max_distance)?;+ Some((proj.point.distance(point), proj))+ },+ )+ }++ /// Projects a point on this BVH using the provided leaf projection function.+ ///+ /// Also returns the feature the point was projected on.+ ///+ /// The `primitive_check` delegates the point-projection task to an external function that+ /// is assumed to map a leaf index to an actual geometry to project on. The `Real` argument+ /// given to that closure is the distance to the closest point found so far (or is equal to+ /// `max_distance` if no projection was found so far).+ pub fn project_point_and_get_feature(+ &self,+ point: Vector,+ max_distance: Real,+ primitive_check: impl Fn(u32, Real) -> Option<(PointProjection, FeatureId)>,+ ) -> Option<(u32, (Real, (PointProjection, FeatureId)))> {+ self.find_best(+ max_distance,+ |node: &BvhNode, _| node.aabb().distance_to_local_point(point, true),+ |primitive, _| {+ let proj = primitive_check(primitive, max_distance)?;+ Some((proj.0.point.distance(point), proj))+ },+ )+ }++ /// Casts a ray on this BVH using the provided leaf ray-cast function.+ ///+ /// The `primitive_check` delegates the ray-casting task to an external function that+ /// is assumed to map a leaf index to an actual geometry to cast a ray on. The `Real` argument+ /// given to that closure is the distance to the closest ray hit found so far (or is equal to+ /// `max_time_of_impact` if no projection was found so far).+ #[cfg(not(all(feature = "dim3", feature = "f32")))]+ pub fn cast_ray(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ primitive_check: impl Fn(u32, Real) -> Option<Real>,+ ) -> Option<(u32, Real)> {+ self.find_best(+ max_time_of_impact,+ |node: &BvhNode, best_so_far| node.cast_ray(ray, best_so_far),+ primitive_check,+ )+ }++ /// Casts a ray on this BVH using the provided leaf ray-cast function.+ ///+ /// The `primitive_check` delegates the ray-casting task to an external function that+ /// is assumed to map a leaf index to an actual geometry to cast a ray on. The `Real` argument+ /// given to that closure is the distance to the closest ray hit found so far (or is equal to+ /// `max_time_of_impact` if no projection was found so far).+ #[cfg(all(feature = "dim3", feature = "f32"))]+ pub fn cast_ray(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ primitive_check: impl Fn(u32, Real) -> Option<Real>,+ ) -> Option<(u32, Real)> {+ // The commented code below relies on depth-first traversal instead of+ // depth first. Interesting to compare both approaches (the best-first is+ // expected to be consistently faster though).+ //+ // let simd_inv_ray = SimdInvRay::from(*ray);+ // let mut best_primitive = u32::MAX;+ // let mut best_toi = Real::MAX;+ // self.traverse(|node: &BvhNode| {+ // if node.cast_inv_ray_simd(&simd_inv_ray) >= best_toi {+ // return TraversalAction::Prune;+ // }+ //+ // if let Some(primitive) = node.leaf_data() {+ // let toi = primitive_check(primitive as u32, best_toi);+ // if toi < best_toi {+ // best_primitive = primitive as u32;+ // best_toi = toi;+ // }+ // }+ //+ // TraversalAction::Continue+ // });+ // (best_primitive, best_toi)++ let simd_inv_ray = SimdInvRay::from(*ray);+ self.find_best(+ max_time_of_impact,+ |node: &BvhNode, _best_so_far| node.cast_inv_ray_simd(&simd_inv_ray),+ primitive_check,+ )+ }+}diff --git a/renderer/third_party/parry3d/src/partitioning/bvh/bvh_refit.rs b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_refit.rsnew file mode 100644index 0000000..d62c32a--- /dev/null+++ b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_refit.rs@@ -0,0 +1,766 @@+use super::bvh_tree::{BvhNodeIndex, BvhNodeVec, BvhNodeWide};+use super::{Bvh, BvhNode, BvhWorkspace};+use crate::utils::VecMap;+use alloc::vec::Vec;++/// Raw pointers to the refit buffers, shared across parallel refit tasks.+///+/// Safety: tasks write disjoint index ranges (see `refit_recurse_parallel`).+#[cfg(feature = "parallel")]+#[derive(Copy, Clone)]+struct RefitPtrs {+ target: *mut BvhNodeVec,+ leaf_data: *mut VecMap<BvhNodeIndex>,+ parents: *mut Vec<BvhNodeIndex>,+}++#[cfg(feature = "parallel")]+unsafe impl Send for RefitPtrs {}+#[cfg(feature = "parallel")]+unsafe impl Sync for RefitPtrs {}++impl Bvh {+ /// Updates the BVH's internal node AABBs after leaf changes.+ ///+ /// Refitting ensures that every internal node's AABB tightly encloses the AABBs of its+ /// children. This operation is essential after updating leaf positions with+ /// [`insert_or_update_partially`] and is much faster than rebuilding the entire tree.+ ///+ /// In addition to updating AABBs, this method:+ /// - Reorders nodes in depth-first order for better cache locality during queries+ /// - Ensures leaf counts on each node are correct+ /// - Propagates change flags from leaves to ancestors (for change detection)+ ///+ /// # When to Use+ ///+ /// Call `refit` after:+ /// - Bulk updates with [`insert_or_update_partially`]+ /// - Any operation that modifies leaf AABBs without updating ancestor nodes+ /// - When you want to optimize tree layout for better query performance+ ///+ /// **Don't call `refit` after**:+ /// - Regular [`insert`] calls (they already update ancestors)+ /// - [`remove`] calls (they already maintain tree validity)+ ///+ /// # Arguments+ ///+ /// * `workspace` - A reusable workspace to avoid allocations. Can be shared across+ /// multiple BVH operations for better performance.+ ///+ /// # Performance+ ///+ /// - **Time**: O(n) where n is the number of nodes+ /// - **Space**: O(n) temporary storage in workspace+ /// - Much faster than rebuilding the tree from scratch+ /// - Essential for maintaining good query performance in dynamic scenes+ ///+ /// # Examples+ ///+ /// ## After bulk updates+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhWorkspace};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let mut bvh = Bvh::new();+ /// let mut workspace = BvhWorkspace::default();+ ///+ /// // Insert initial objects+ /// for i in 0..100 {+ /// let aabb = Aabb::new(+ /// Vector::new(i as f32, 0.0, 0.0),+ /// Vector::new(i as f32 + 1.0, 1.0, 1.0)+ /// );+ /// bvh.insert(aabb, i);+ /// }+ ///+ /// // Update all objects without tree propagation (faster)+ /// for i in 0..100 {+ /// let offset = 0.1;+ /// let aabb = Aabb::new(+ /// Vector::new(i as f32 + offset, 0.0, 0.0),+ /// Vector::new(i as f32 + 1.0 + offset, 1.0, 1.0)+ /// );+ /// bvh.insert_or_update_partially(aabb, i, 0.0);+ /// }+ ///+ /// // Now update the tree in one efficient pass+ /// bvh.refit(&mut workspace);+ /// # }+ /// ```+ ///+ /// ## In a game loop+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhWorkspace};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let mut bvh = Bvh::new();+ /// let mut workspace = BvhWorkspace::default();+ ///+ /// // Game initialization - add objects+ /// for i in 0..1000 {+ /// let aabb = Aabb::new(+ /// Vector::new(i as f32, 0.0, 0.0),+ /// Vector::new(i as f32 + 1.0, 1.0, 1.0)+ /// );+ /// bvh.insert(aabb, i);+ /// }+ ///+ /// // Game loop - update objects each frame+ /// for frame in 0..100 {+ /// // Update physics, AI, etc.+ /// for i in 0..1000 {+ /// let time = frame as f32 * 0.016; // ~60 FPS+ /// let pos = time.sin() * 10.0;+ /// let aabb = Aabb::new(+ /// Vector::new(i as f32 + pos, 0.0, 0.0),+ /// Vector::new(i as f32 + pos + 1.0, 1.0, 1.0)+ /// );+ /// bvh.insert_or_update_partially(aabb, i, 0.0);+ /// }+ ///+ /// // Refit once per frame for all updates+ /// bvh.refit(&mut workspace);+ ///+ /// // Now perform collision detection queries...+ /// }+ /// # }+ /// ```+ ///+ /// ## With change detection margin+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhWorkspace};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let mut bvh = Bvh::new();+ /// let mut workspace = BvhWorkspace::default();+ ///+ /// // Add an object+ /// let aabb = Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0));+ /// bvh.insert(aabb, 0);+ ///+ /// // Update with a margin - tree won't update if movement is small+ /// let margin = 0.5;+ /// let new_aabb = Aabb::new(Vector::new(0.1, 0.0, 0.0), Vector::new(1.1, 1.0, 1.0));+ /// bvh.insert_or_update_partially(new_aabb, 0, margin);+ ///+ /// // Refit propagates the change detection flags+ /// bvh.refit(&mut workspace);+ /// # }+ /// ```+ ///+ /// # Comparison with `refit_without_opt`+ ///+ /// This method reorganizes the tree in memory for better cache performance.+ /// If you only need to update AABBs without reordering, use [`refit_without_opt`](Self::refit_without_opt)+ /// which is faster but doesn't improve memory layout.+ ///+ /// # Notes+ ///+ /// - Reuses the provided `workspace` to avoid allocations+ /// - Safe to call even if no leaves were modified (just reorganizes tree)+ /// - Does not change the tree's topology, only AABBs and layout+ /// - Call this before [`optimize_incremental`] for best results+ ///+ /// # See Also+ ///+ /// - [`insert_or_update_partially`](Bvh::insert_or_update_partially) - Update leaves+ /// without propagation+ /// - [`refit_without_opt`](Self::refit_without_opt) - Faster refit without memory+ /// reorganization+ /// - [`optimize_incremental`](Bvh::optimize_incremental) - Improve tree quality+ /// - [`BvhWorkspace`] - Reusable workspace for operations+ ///+ /// [`insert_or_update_partially`]: Bvh::insert_or_update_partially+ /// [`insert`]: Bvh::insert+ /// [`remove`]: Bvh::remove+ /// [`optimize_incremental`]: Bvh::optimize_incremental+ pub fn refit(&mut self, workspace: &mut BvhWorkspace) {+ Self::refit_buffers::<true>(+ &mut self.nodes,+ &mut workspace.refit_tmp,+ &mut self.leaf_node_indices,+ &mut self.parents,+ );++ // Swap the old nodes with the refitted ones.+ core::mem::swap(&mut self.nodes, &mut workspace.refit_tmp);+ // The refit rebuilt the node array in depth-first order, dropping the+ // orphaned slots the free list pointed to.+ self.free_wide_nodes.clear();+ }++ /// Same as [`Self::refit`], but processes independent subtrees in parallel.+ ///+ /// The result is identical to [`Self::refit`] (same node layout, same flags);+ /// only the work distribution differs.+ #[cfg(feature = "parallel")]+ pub fn refit_parallel(&mut self, workspace: &mut BvhWorkspace) {+ Self::refit_buffers_parallel::<true>(+ &mut self.nodes,+ &mut workspace.refit_tmp,+ &mut self.leaf_node_indices,+ &mut self.parents,+ );++ // Swap the old nodes with the refitted ones.+ core::mem::swap(&mut self.nodes, &mut workspace.refit_tmp);+ // The refit rebuilt the node array in depth-first order, dropping the+ // orphaned slots the free list pointed to.+ self.free_wide_nodes.clear();+ }++ #[cfg(feature = "parallel")]+ fn refit_buffers_parallel<const RESOLVE: bool>(+ source: &mut BvhNodeVec,+ target: &mut BvhNodeVec,+ leaf_data: &mut VecMap<BvhNodeIndex>,+ parents: &mut Vec<BvhNodeIndex>,+ ) {+ // Subtrees below this leaf count are refitted sequentially.+ const SEQ_LEAF_THRESHOLD: u32 = 2048;+ // Bounds the number of spawned tasks to 2^MAX_SPLIT_DEPTH.+ const MAX_SPLIT_DEPTH: u32 = 6;++ if source.is_empty() || source[0].leaf_count() <= SEQ_LEAF_THRESHOLD.max(2) {+ return Self::refit_buffers::<RESOLVE>(source, target, leaf_data, parents);+ }++ target.resize(+ source.len(),+ BvhNodeWide {+ left: BvhNode::zeros(),+ right: BvhNode::zeros(),+ },+ );+ parents.resize(source.len(), BvhNodeIndex::default());++ let ptrs = RefitPtrs {+ target: target as *mut BvhNodeVec,+ leaf_data: leaf_data as *mut VecMap<BvhNodeIndex>,+ parents: parents as *mut Vec<BvhNodeIndex>,+ };++ // Mirror of `refit_buffers`' root special case, with the sequential target-id+ // counter replaced by offsets computed from the subtree leaf counts: the+ // depth-first layout of a subtree with `n` leaves spans exactly `n - 1` wide+ // nodes.+ let root = source[0];+ let left_size = if root.left.is_leaf() {+ 0+ } else {+ root.left.leaf_count() - 1+ };+ let right_size = if root.right.is_leaf() {+ 0+ } else {+ root.right.leaf_count() - 1+ };+ let final_len = (1 + left_size + right_size) as usize;++ let _ = rayon::join(+ || {+ // SAFETY: this task writes only to target slots [1, 1 + left_size),+ // entry target[0].left, and the leaf data of leaves of the+ // left subtree — all disjoint from the other task.+ let target = unsafe { &mut *ptrs.target };+ if !root.left.is_leaf() {+ Self::refit_recurse_parallel::<RESOLVE>(+ source,+ ptrs,+ root.left.children,+ 1,+ BvhNodeIndex::left(0),+ MAX_SPLIT_DEPTH,+ SEQ_LEAF_THRESHOLD,+ );+ } else {+ target[0].left = root.left;+ if RESOLVE {+ target[0].left.data.resolve_pending_change();+ }+ }+ },+ || {+ // SAFETY: see the other task; slots [1 + left_size, final_len) and+ // entry target[0].right.+ let target = unsafe { &mut *ptrs.target };+ if !root.right.is_leaf() {+ Self::refit_recurse_parallel::<RESOLVE>(+ source,+ ptrs,+ root.right.children,+ 1 + left_size,+ BvhNodeIndex::right(0),+ MAX_SPLIT_DEPTH,+ SEQ_LEAF_THRESHOLD,+ );+ } else {+ target[0].right = root.right;+ if RESOLVE {+ target[0].right.data.resolve_pending_change();+ }+ }+ },+ );++ source.truncate(final_len);+ target.truncate(final_len);+ parents.truncate(final_len);+ }++ /// Recursive parallel counterpart of `refit_recurse`.+ ///+ /// `target_id` is the depth-first slot this subtree's root occupies (its left+ /// child subtree starts at `target_id + 1`, its right child subtree right after+ /// the left one, whose extent is known from its leaf count).+ #[cfg(feature = "parallel")]+ fn refit_recurse_parallel<const RESOLVE: bool>(+ source: &BvhNodeVec,+ ptrs: RefitPtrs,+ source_id: u32,+ target_id: u32,+ parent: BvhNodeIndex,+ depth: u32,+ seq_leaf_threshold: u32,+ ) {+ let node = source[source_id as usize];+ let leaf_count = node.left.leaf_count() + node.right.leaf_count();++ if depth == 0 || leaf_count <= seq_leaf_threshold {+ //++ // SAFETY: the sequential refit of this subtree only touches the target+ // slots [target_id, target_id + leaf_count - 1), its parent entry,+ // and its own leaves' data: all disjoint from the other tasks.+ let target = unsafe { &mut *ptrs.target };+ let leaf_data = unsafe { &mut *ptrs.leaf_data };+ let parents = unsafe { &mut *ptrs.parents };+ let mut counter = target_id;+ Self::refit_recurse::<RESOLVE>(+ source,+ target,+ leaf_data,+ parents,+ source_id,+ &mut counter,+ parent,+ );+ debug_assert_eq!(counter, target_id + leaf_count - 1);+ return;+ }++ let left_size = if node.left.is_leaf() {+ 0+ } else {+ node.left.leaf_count() - 1+ };++ let _ = rayon::join(+ || {+ let target = unsafe { &mut *ptrs.target };+ let leaf_data = unsafe { &mut *ptrs.leaf_data };+ if !node.left.is_leaf() {+ Self::refit_recurse_parallel::<RESOLVE>(+ source,+ ptrs,+ node.left.children,+ target_id + 1,+ BvhNodeIndex::left(target_id),+ depth - 1,+ seq_leaf_threshold,+ );+ } else {+ target[target_id as usize].left = node.left;+ if RESOLVE {+ target[target_id as usize]+ .left+ .data+ .resolve_pending_change();+ }+ leaf_data[node.left.children as usize] = BvhNodeIndex::left(target_id);+ }+ },+ || {+ let target = unsafe { &mut *ptrs.target };+ let leaf_data = unsafe { &mut *ptrs.leaf_data };+ if !node.right.is_leaf() {+ Self::refit_recurse_parallel::<RESOLVE>(+ source,+ ptrs,+ node.right.children,+ target_id + 1 + left_size,+ BvhNodeIndex::right(target_id),+ depth - 1,+ seq_leaf_threshold,+ );+ } else {+ target[target_id as usize].right = node.right;+ if RESOLVE {+ target[target_id as usize]+ .right+ .data+ .resolve_pending_change();+ }+ leaf_data[node.right.children as usize] = BvhNodeIndex::right(target_id);+ }+ },+ );++ // Both children of this wide node are now written: compute the summary entry+ // in the parent, like the tail of `refit_recurse`.+ let target = unsafe { &mut *ptrs.target };+ let parents = unsafe { &mut *ptrs.parents };+ let merged = target[target_id as usize]+ .left+ .merged(&target[target_id as usize].right, target_id);+ target[parent] = merged;+ parents[target_id as usize] = parent;+ }++ /// Same as [`Self::refit`], but leaves every change-detection flag untouched.+ ///+ /// Use this to make the tree valid for queries after a batch of+ /// [`Self::insert_or_update_partially`] without consuming the pending change+ /// flags: a later flag-resolving [`Self::refit`] (or+ /// [`Self::refit_partial`]) will promote them as if this call never happened.+ pub fn refit_without_resolve(&mut self, workspace: &mut BvhWorkspace) {+ Self::refit_buffers::<false>(+ &mut self.nodes,+ &mut workspace.refit_tmp,+ &mut self.leaf_node_indices,+ &mut self.parents,+ );+ core::mem::swap(&mut self.nodes, &mut workspace.refit_tmp);+ // The refit rebuilt the node array in depth-first order, dropping the+ // orphaned slots the free list pointed to.+ self.free_wide_nodes.clear();+ }++ /// Parallel version of [`Self::refit_without_resolve`].+ #[cfg(feature = "parallel")]+ pub fn refit_without_resolve_parallel(&mut self, workspace: &mut BvhWorkspace) {+ Self::refit_buffers_parallel::<false>(+ &mut self.nodes,+ &mut workspace.refit_tmp,+ &mut self.leaf_node_indices,+ &mut self.parents,+ );+ core::mem::swap(&mut self.nodes, &mut workspace.refit_tmp);+ // The refit rebuilt the node array in depth-first order, dropping the+ // orphaned slots the free list pointed to.+ self.free_wide_nodes.clear();+ }++ pub(super) fn refit_buffers<const RESOLVE: bool>(+ source: &mut BvhNodeVec,+ target: &mut BvhNodeVec,+ leaf_data: &mut VecMap<BvhNodeIndex>,+ parents: &mut Vec<BvhNodeIndex>,+ ) {+ if source.is_empty() {+ target.clear();+ parents.clear();+ } else if source[0].leaf_count() <= 2 {+ // No actual refit to apply, just copy the root wide node.+ target.clear();+ parents.clear();+ target.push(source[0]);+ if RESOLVE {+ target[0].left.data.resolve_pending_change();+ if target[0].right.leaf_count() > 0 {+ target[0].right.data.resolve_pending_change();+ }+ }+ parents.push(BvhNodeIndex::default());+ } else if !source.is_empty() && source[0].leaf_count() > 2 {+ target.resize(+ source.len(),+ BvhNodeWide {+ left: BvhNode::zeros(),+ right: BvhNode::zeros(),+ },+ );++ let mut len = 1;++ // Start with a special case for the root then recurse.+ let left_child_id = source[0].left.children;+ let right_child_id = source[0].right.children;++ if !source[0].left.is_leaf() {+ Self::refit_recurse::<RESOLVE>(+ source,+ target,+ leaf_data,+ parents,+ left_child_id,+ &mut len,+ BvhNodeIndex::left(0),+ );+ } else {+ target[0].left = source[0].left;+ if RESOLVE {+ target[0].left.data.resolve_pending_change();+ }++ // NOTE: updating the leaf_data shouldn’t be needed here since the root+ // is always at 0.+ // *self.leaf_data.get_mut_unknown_gen(left_child_id).unwrap() = BvhNodeIndex::left(0);+ }++ if !source[0].right.is_leaf() {+ Self::refit_recurse::<RESOLVE>(+ source,+ target,+ leaf_data,+ parents,+ right_child_id,+ &mut len,+ BvhNodeIndex::right(0),+ );+ } else {+ target[0].right = source[0].right;+ if RESOLVE {+ target[0].right.data.resolve_pending_change();+ }+ // NOTE: updating the leaf_data shouldn’t be needed here since the root+ // is always at 0.+ // *self.leaf_data.get_mut_unknown_gen(right_child_id).unwrap() = BvhNodeIndex::right(0);+ }++ source.truncate(len as usize);+ target.truncate(len as usize);+ parents.truncate(len as usize);+ }+ }++ fn refit_recurse<const RESOLVE: bool>(+ source: &BvhNodeVec,+ target: &mut BvhNodeVec,+ leaf_data: &mut VecMap<BvhNodeIndex>,+ parents: &mut [BvhNodeIndex],+ source_id: u32,+ target_id_mut: &mut u32,+ parent: BvhNodeIndex,+ ) {+ let target_id = *target_id_mut;+ *target_id_mut += 1;++ let node = &source[source_id as usize];+ let left_is_leaf = node.left.is_leaf();+ let right_is_leaf = node.right.is_leaf();+ let left_source_id = node.left.children;+ let right_source_id = node.right.children;++ if !left_is_leaf {+ Self::refit_recurse::<RESOLVE>(+ source,+ target,+ leaf_data,+ parents,+ left_source_id,+ target_id_mut,+ BvhNodeIndex::left(target_id),+ );+ } else {+ let node = &source[source_id as usize];+ target[target_id as usize].left = node.left;+ if RESOLVE {+ target[target_id as usize]+ .left+ .data+ .resolve_pending_change();+ }+ leaf_data[node.left.children as usize] = BvhNodeIndex::left(target_id);+ }++ if !right_is_leaf {+ Self::refit_recurse::<RESOLVE>(+ source,+ target,+ leaf_data,+ parents,+ right_source_id,+ target_id_mut,+ BvhNodeIndex::right(target_id),+ );+ } else {+ let node = &source[source_id as usize];+ target[target_id as usize].right = node.right;+ if RESOLVE {+ target[target_id as usize]+ .right+ .data+ .resolve_pending_change();+ }+ leaf_data[node.right.children as usize] = BvhNodeIndex::right(target_id);+ }++ let node = &target[target_id as usize];+ target[parent] = node.left.merged(&node.right, target_id);+ parents[target_id as usize] = parent;+ }++ /// Incrementally refits the tree after a small number of leaf updates or+ /// insertions.+ ///+ /// This is a faster alternative to [`Self::refit`] valid only if, since the last+ /// refit, the only tree modifications were calls to+ /// [`Self::insert_or_update_partially`], [`Self::insert`],+ /// [`Self::insert_with_change_detection`], or+ /// [`Self::reinsert_or_update_with_change_detection`] (in-place updates,+ /// insertions, or removal-based relocations of leaves). In particular, no leaf+ /// was removed without being re-inserted in the same batch, and no optimization+ /// ran. Otherwise, call [`Self::refit`] instead.+ ///+ /// Insertions are safe here because `insert_new_unchecked` keeps the tree+ /// geometrically valid on its own (it enlarges the ancestor AABBs and increments+ /// their leaf counts during its descent) and creates the new leaf with a pending+ /// change flag. Any transient change-flag state it leaves behind (the pending+ /// flag inherited by the wide node that used to hold the insertion sibling, the+ /// raw-merged flags written by its SAH rotations) lies on the inserted leaf's+ /// ancestor path, which the walk below rewrites all the way to the root — see+ /// `refit_path`.+ ///+ /// [`BvhLeafUpdateStatus::Inserted`]: super::BvhLeafUpdateStatus::Inserted+ ///+ /// `previously_changed` must contain (a superset of) the leaves whose change flag+ /// was set by the previous refit: their change flag gets cleared. `newly_changed`+ /// must contain (a superset of) the leaves updated in-place or inserted since the+ /// last refit: their change flag gets set if their fat AABB actually changed+ /// (inserted leaves always count as changed).+ ///+ /// Unlike [`Self::refit`], this runs in `O(changed * tree_height)` instead of+ /// `O(node_count)`, but doesn't reorder nodes in memory.+ pub fn refit_partial(&mut self, previously_changed: &[u32], newly_changed: &[u32]) {+ // First resolve the change flags of every impacted leaf, and only then walk+ // their ancestor paths. Walking while some leaves still hold an unresolved+ // pending flag would propagate that transient state into internal nodes+ // (a pending internal node reads as "unchanged" during traversals).+ for leaf in previously_changed {+ let Some(leaf_node_id) = self.leaf_node_indices.get(*leaf as usize).copied() else {+ continue;+ };+ let data = &mut self.nodes[leaf_node_id].data;++ // Clear the flag of leaves that were changed at the previous refit and+ // didn't move since. Leaves that moved again (pending) are promoted by+ // the next loop instead.+ if !data.is_change_pending() && data.is_changed() {+ data.resolve_pending_change();+ }+ }++ for leaf in newly_changed {+ let Some(leaf_node_id) = self.leaf_node_indices.get(*leaf as usize).copied() else {+ continue;+ };+ let data = &mut self.nodes[leaf_node_id].data;++ // Promote pending leaves to CHANGED. Leaves whose update stayed within+ // the change-detection margin have no flag to update.+ if data.is_change_pending() {+ data.resolve_pending_change();+ }+ }++ for leaf in previously_changed.iter().chain(newly_changed) {+ let Some(leaf_node_id) = self.leaf_node_indices.get(*leaf as usize).copied() else {+ continue;+ };+ self.refit_path(leaf_node_id);+ }+ }++ /// Propagates AABB and change-flag updates from the given node up to the root.+ ///+ /// The walk deliberately does NOT stop early when an ancestor's recomputed value+ /// matches its stored one: leaf insertions can leave transient change-flag state+ /// (pending flags inherited by the wide node that used to hold the insertion+ /// sibling, raw-merged flags written by the insertion's SAH rotations) anywhere+ /// on the inserted leaf's ancestor path. Walking the whole path rewrites every+ /// ancestor with an exact, normalized recomputation, which is what keeps the+ /// internal change flags exactly equal to the OR of their descendant leaves'+ /// flags. An early-out could strand a stale pending flag above the break point,+ /// and a pending internal node reads as "unchanged" during change-detection+ /// traversals — hiding every changed leaf underneath. The full walk costs+ /// O(tree height) per changed leaf, which is fine in the small-change regime+ /// partial refits are meant for.+ fn refit_path(&mut self, node: BvhNodeIndex) {+ let (mut wide_id, _) = node.decompose();++ while wide_id != 0 {+ let parent = self.parents[wide_id];+ let wide = &self.nodes[wide_id];+ let mut recomputed = wide.left.merged(&wide.right, wide_id as u32);+ recomputed.data.normalize_change_flag();++ self.nodes[parent] = recomputed;+ (wide_id, _) = parent.decompose();+ }+ }++ /// Similar to [`Self::refit`] but without any optimization of the internal node storage layout.+ ///+ /// This can be faster than [`Self::refit`] but doesn’t reorder node to be more cache-efficient+ /// on tree traversals.+ pub fn refit_without_opt(&mut self) {+ if self.leaf_count() > 2 {+ let root = &self.nodes[0];+ let left = root.left.children;+ let right = root.right.children;+ let left_is_leaf = root.left.is_leaf();+ let right_is_leaf = root.right.is_leaf();++ if !left_is_leaf {+ self.recurse_refit_without_opt(left, BvhNodeIndex::left(0));+ }+ if !right_is_leaf {+ self.recurse_refit_without_opt(right, BvhNodeIndex::right(0));+ }+ }+ }++ fn recurse_refit_without_opt(&mut self, node_id: u32, parent: BvhNodeIndex) {+ let node = &self.nodes[node_id as usize];+ let left = &node.left;+ let right = &node.right;+ let left_is_leaf = left.is_leaf();+ let right_is_leaf = right.is_leaf();+ let left_children = left.children;+ let right_children = right.children;++ if !left_is_leaf {+ self.recurse_refit_without_opt(left_children, BvhNodeIndex::left(node_id));+ } else {+ self.nodes[node_id as usize]+ .left+ .data+ .resolve_pending_change();+ }+ if !right_is_leaf {+ self.recurse_refit_without_opt(right_children, BvhNodeIndex::right(node_id));+ } else {+ self.nodes[node_id as usize]+ .right+ .data+ .resolve_pending_change();+ }++ let node = &self.nodes[node_id as usize];+ let left = &node.left;+ let right = &node.right;+ let merged = left.merged(right, node_id);++ self.nodes[parent] = merged;+ }+}diff --git a/renderer/third_party/parry3d/src/partitioning/bvh/bvh_tests.rs b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_tests.rsnew file mode 100644index 0000000..d4e7d3b--- /dev/null+++ b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_tests.rs@@ -0,0 +1,460 @@+use crate::bounding_volume::Aabb;+use crate::math::{Real, Vector};+use crate::partitioning::{+ Bvh, BvhBuildStrategy, BvhNode, BvhNodeIndex, BvhWorkspace, TraversalAction,+};++fn make_test_aabb(i: usize) -> Aabb {+ Aabb::from_half_extents(Vector::splat(i as Real).into(), Vector::splat(1.0))+}++#[test]+fn test_leaves_iteration() {+ let leaves = [+ make_test_aabb(0), // mins at (0,0,0) - should pass+ make_test_aabb(5), // mins at (5,5,5) - should be filtered out+ ];+ let bvh = Bvh::from_leaves(BvhBuildStrategy::Binned, &leaves);++ // Only allow nodes with mins.x <= 3.0 (should only pass leaf 0)+ let check = |node: &BvhNode| -> bool { node.mins.x <= 3.0 };++ let mut found_invalid_leaf = false;+ for leaf_index in bvh.leaves(check) {+ if leaf_index == 1 {+ // This is the leaf that should be filtered out+ found_invalid_leaf = true;+ break;+ }+ }++ if found_invalid_leaf {+ panic!("Leaves iterator returned an invalid leaf");+ }+}++#[test]+fn test_traverse_indexed() {+ // Empty tree: callback must never fire, regardless of `subtree` being `None`.+ let empty = Bvh::new();+ empty.traverse_indexed(None, |_, _| {+ panic!("callback should not be called on an empty BVH");+ });++ // Single-leaf tree exercises the partial-root branch when starting from the root.+ let single = Bvh::from_leaves(BvhBuildStrategy::Binned, &[make_test_aabb(0)]);+ let mut single_visited = std::vec::Vec::new();+ single.traverse_indexed(None, |node, idx| {+ single_visited.push((idx, node.leaf_data()));+ TraversalAction::Continue+ });+ assert_eq!(single_visited.len(), 1);+ assert_eq!(single_visited[0].0, BvhNodeIndex::left(0));+ assert_eq!(single_visited[0].1, Some(0));++ // Multi-leaf tree: traversing from the root must visit every leaf, and the+ // index passed to the callback must round-trip through `bvh.nodes`.+ let leaves: std::vec::Vec<_> = (0..16).map(make_test_aabb).collect();+ let bvh = Bvh::from_leaves(BvhBuildStrategy::Binned, &leaves);++ let mut seen_leaves = std::vec::Vec::new();+ let mut traverse_indexed_calls = std::vec::Vec::new();+ bvh.traverse_indexed(None, |node, idx| {+ // Every reported index must point to the same node we just received.+ let by_idx: &BvhNode = &bvh.nodes[idx];+ assert!(core::ptr::eq(by_idx, node));++ traverse_indexed_calls.push(idx);+ if let Some(data) = node.leaf_data() {+ seen_leaves.push(data);+ }+ TraversalAction::Continue+ });+ seen_leaves.sort();+ assert_eq!(seen_leaves, (0..16).collect::<std::vec::Vec<_>>());++ // `traverse_indexed(None, ...)` must visit exactly the same nodes (in the same+ // order) as `traverse`.+ let mut traverse_nodes: std::vec::Vec<*const BvhNode> = std::vec::Vec::new();+ bvh.traverse(|node| {+ traverse_nodes.push(node as *const _);+ TraversalAction::Continue+ });+ let indexed_nodes: std::vec::Vec<*const BvhNode> = traverse_indexed_calls+ .iter()+ .map(|idx| &bvh.nodes[*idx] as *const _)+ .collect();+ assert_eq!(traverse_nodes, indexed_nodes);++ // Starting from a specific subtree must only visit that subtree (the start+ // node and its descendants), and every reported leaf must belong to it.+ let subtree_root_idx = BvhNodeIndex::left(0);+ let mut subtree_leaves = std::vec::Vec::new();+ let mut subtree_visited = std::vec::Vec::new();+ bvh.traverse_indexed(Some(subtree_root_idx), |node, idx| {+ subtree_visited.push(idx);+ if let Some(data) = node.leaf_data() {+ subtree_leaves.push(data);+ }+ TraversalAction::Continue+ });+ assert_eq!(subtree_visited[0], subtree_root_idx);+ // The subtree's leaves must be a non-empty strict subset of the full set.+ assert!(!subtree_leaves.is_empty());+ assert!(subtree_leaves.len() < 16);+ for leaf in &subtree_leaves {+ assert!(seen_leaves.contains(leaf));+ }+ // Leaf count reported by the subtree's root must match the visited leaves.+ assert_eq!(+ bvh.nodes[subtree_root_idx].leaf_count() as usize,+ subtree_leaves.len()+ );++ // Starting from a leaf node visits exactly that leaf.+ let leaf_idx = *traverse_indexed_calls+ .iter()+ .find(|idx| bvh.nodes[**idx].is_leaf())+ .expect("the tree must contain at least one leaf");+ let mut leaf_only = std::vec::Vec::new();+ bvh.traverse_indexed(Some(leaf_idx), |node, idx| {+ leaf_only.push((idx, node.leaf_data()));+ TraversalAction::Continue+ });+ assert_eq!(leaf_only.len(), 1);+ assert_eq!(leaf_only[0].0, leaf_idx);+ assert!(leaf_only[0].1.is_some());++ // `Prune` at the start node must visit it once and stop.+ let mut prune_visits = 0;+ bvh.traverse_indexed(Some(BvhNodeIndex::left(0)), |_, _| {+ prune_visits += 1;+ TraversalAction::Prune+ });+ assert_eq!(prune_visits, 1);++ // `EarlyExit` at the start node must visit it once and stop.+ let mut exit_visits = 0;+ bvh.traverse_indexed(Some(BvhNodeIndex::left(0)), |_, _| {+ exit_visits += 1;+ TraversalAction::EarlyExit+ });+ assert_eq!(exit_visits, 1);++ // `EarlyExit` partway through must short-circuit the full traversal.+ let mut early = 0;+ bvh.traverse_indexed(None, |_, _| {+ early += 1;+ if early >= 3 {+ TraversalAction::EarlyExit+ } else {+ TraversalAction::Continue+ }+ });+ assert_eq!(early, 3);+}++#[test]+fn bvh_build_and_removal() {+ // Check various combination of building pattern and removal pattern.+ // The tree validity is asserted at every step.+ #[derive(Copy, Clone, Debug)]+ enum BuildPattern {+ Ploc,+ Binned,+ Insert,+ }++ #[derive(Copy, Clone, Debug)]+ enum RemovalPattern {+ InOrder,+ RevOrder,+ EvenOdd,+ }++ for build_pattern in [+ BuildPattern::Ploc,+ BuildPattern::Binned,+ BuildPattern::Insert,+ ] {+ for removal_pattern in [+ RemovalPattern::InOrder,+ RemovalPattern::RevOrder,+ RemovalPattern::EvenOdd,+ ] {+ for len in 1..=100 {+ std::println!(+ "Testing build: {:?}, removal: {:?}, len: {}",+ build_pattern,+ removal_pattern,+ len+ );+ let leaves: std::vec::Vec<_> = (0..len).map(make_test_aabb).collect();++ let mut bvh = match build_pattern {+ BuildPattern::Binned => Bvh::from_leaves(BvhBuildStrategy::Binned, &leaves),+ BuildPattern::Ploc => Bvh::from_leaves(BvhBuildStrategy::Ploc, &leaves),+ BuildPattern::Insert => {+ let mut bvh = Bvh::new();+ for i in 0..len {+ bvh.insert(make_test_aabb(i), i as u32);+ bvh.assert_well_formed();+ }+ bvh+ }+ };++ for _ in 0..3 {+ bvh.assert_well_formed();++ match removal_pattern {+ RemovalPattern::InOrder => {+ // Remove in insertion order.+ for i in 0..len {+ bvh.remove(i as u32);+ bvh.assert_well_formed();+ }+ }+ RemovalPattern::RevOrder => {+ // Remove in reverse insertion order.+ for i in (0..len).rev() {+ bvh.remove(i as u32);+ bvh.assert_well_formed();+ }+ }+ RemovalPattern::EvenOdd => {+ // Remove even indices first, then odd.+ for i in (0..len).filter(|i| i % 2 == 0) {+ bvh.remove(i as u32);+ bvh.assert_well_formed();+ }+ for i in (0..len).filter(|i| i % 2 != 0) {+ bvh.remove(i as u32);+ bvh.assert_well_formed();+ }+ }+ }++ // Re-insert everything.+ for (i, leaf) in leaves.iter().enumerate() {+ bvh.insert(*leaf, i as u32);+ }+ }+ }+ }+ }+}++#[test]+fn bvh_remove_to_partial_root_then_optimize() {+ // Regression test for the bug reported in #409 where `Bvh::remove` would leave orphaned+ // wide nodes in `self.nodes`/`self.parents` after reducing the tree to a+ // partial root (a single surviving leaf at node 0). Earlier removals on a+ // tree with more than one wide node would intentionally leave orphans for+ // the next `refit` to compact, but if a partial root was created before+ // any refit, those orphans remained reachable from `self.nodes` and+ // `optimize_incremental` would walk them as if they were live, crashing+ // on the corrupt structure.+ //+ // We pick enough leaves to ensure at least one orphan-leaving removal+ // (`wide_node_index != 0`) before the final partial-root removal.+ let leaves: std::vec::Vec<_> = (0..10).map(make_test_aabb).collect();+ let mut bvh = Bvh::from_leaves(BvhBuildStrategy::Binned, &leaves);++ // Remove all but the last leaf, without ever calling refit in between.+ for i in 0..(leaves.len() as u32 - 1) {+ bvh.remove(i);+ }++ // After the final remove, the tree should be a partial root with exactly+ // one surviving leaf, and no orphaned wide nodes left over.+ assert_eq!(bvh.leaf_count(), 1);++ // Without the fix this call walks the orphan-laden tree as if it were+ // live and ends up corrupting/crashing on the partial root.+ let mut workspace = BvhWorkspace::default();+ bvh.optimize_incremental(&mut workspace);++ assert_eq!(bvh.nodes.len(), 1);+ assert_eq!(bvh.parents.len(), 1);+ bvh.assert_well_formed();+}++#[cfg(feature = "parallel")]+#[cfg(all(feature = "dim3", feature = "f32"))]+mod parallel_batch_update {+ use crate::bounding_volume::Aabb;+ use crate::math::Vector;+ use crate::partitioning::{Bvh, BvhLeafUpdateStatus, BvhWorkspace};+ use alloc::vec::Vec;++ /// The parallel batch leaf update must behave exactly like the sequential+ /// per-leaf `insert_or_update_partially` calls (statuses and final tree).+ #[test]+ fn batch_partial_update_matches_sequential() {+ let aabb = |i: usize, offset: f32| {+ Aabb::new(+ Vector::new(i as f32 + offset, 0.0, 0.0).into(),+ Vector::new(i as f32 + offset + 1.0, 1.0, 1.0).into(),+ )+ };++ let mut seq = Bvh::new();+ let mut par = Bvh::new();+ for i in 0..1000 {+ seq.insert(aabb(i, 0.0), i as u32);+ par.insert(aabb(i, 0.0), i as u32);+ }+ // Fatten every leaf so the batch below exercises the within-margin+ // (`Unchanged`) path too.+ for i in 0..1000 {+ let _ = seq.insert_or_update_partially(aabb(i, 2.5), i as u32, 0.5);+ let _ = par.insert_or_update_partially(aabb(i, 2.5), i as u32, 0.5);+ }++ // A mix of: moved-beyond-margin leaves, moved-within-margin leaves, and+ // brand new leaves.+ let updates: Vec<(Aabb, u32, f32)> = (0..1500)+ .map(|i| {+ let offset = if i % 3 == 0 { 2.51 } else { 5.0 };+ (aabb(i, offset), i as u32, 0.1)+ })+ .collect();++ let seq_statuses: Vec<BvhLeafUpdateStatus> = updates+ .iter()+ .map(|(aabb, leaf, margin)| seq.insert_or_update_partially(*aabb, *leaf, *margin))+ .collect();++ let mut par_statuses = Vec::new();+ par.insert_or_update_batch_partially_parallel(&updates, &mut par_statuses);++ assert_eq!(seq_statuses, par_statuses);+ assert!(seq_statuses.contains(&BvhLeafUpdateStatus::Unchanged));+ assert!(seq_statuses.contains(&BvhLeafUpdateStatus::UpdatedInPlace));+ assert!(seq_statuses.contains(&BvhLeafUpdateStatus::Inserted));++ let mut w1 = BvhWorkspace::default();+ let mut w2 = BvhWorkspace::default();+ seq.refit(&mut w1);+ par.refit(&mut w2);+ for i in 0..1500u32 {+ assert_eq!(+ seq.leaf_node(i).map(|n| n.aabb()),+ par.leaf_node(i).map(|n| n.aabb()),+ "leaf {i} differs between sequential and parallel updates"+ );+ }+ }+}++/// The contracts rapier's `parallel`-off ≡ `parallel`-on guarantee rests on: when rapier+/// picks the parallel variant of one of these passes, it must get the exact result the+/// sequential one would have produced — otherwise a build with the feature and a build+/// without it are two different simulations.+#[cfg(feature = "parallel")]+#[cfg(all(feature = "dim3", feature = "f32"))]+mod parallel_matches_sequential {+ use crate::bounding_volume::Aabb;+ use crate::math::Vector;+ use crate::partitioning::{Bvh, BvhWorkspace};+ use alloc::vec::Vec;++ /// 17^3, past `refit_buffers_parallel`'s `SEQ_LEAF_THRESHOLD` so the parallel refit+ /// really splits instead of delegating to the sequential one.+ const SIDE: u32 = 17;+ const LEAVES: u32 = SIDE * SIDE * SIDE;++ /// A jittered grid whose cells overlap their neighbours: the tree needs real internal+ /// structure, and the traversal real pairs, for the comparisons to mean anything.+ fn scene() -> Bvh {+ let mut bvh = Bvh::new();+ for i in 0..LEAVES {+ let (x, y, z) = (i % SIDE, (i / SIDE) % SIDE, i / (SIDE * SIDE));+ let jitter = (i % 7) as f32 * 0.03;+ let mins = Vector::new(x as f32, y as f32, z as f32) * 1.0+ + Vector::new(jitter, jitter * 0.5, jitter * 0.25);+ bvh.insert(+ Aabb::new(mins.into(), (mins + Vector::new(1.5, 1.5, 1.5)).into()),+ i,+ );+ }+ bvh+ }++ /// Compares the node arrays themselves, not just the leaf AABBs: the refit rebuilds+ /// them in depth-first order, and that order decides the traversal order downstream.+ fn assert_same_nodes(seq: &Bvh, par: &Bvh) {+ assert_eq!(+ seq.nodes.len(),+ par.nodes.len(),+ "node array lengths differ after refit"+ );+ for (i, (a, b)) in seq.nodes.iter().zip(par.nodes.iter()).enumerate() {+ for (side, a, b) in [("left", &a.left, &b.left), ("right", &a.right, &b.right)] {+ assert_eq!(a.aabb(), b.aabb(), "node {i} ({side}) aabb differs");+ assert_eq!(+ a.leaf_count(),+ b.leaf_count(),+ "node {i} ({side}) leaf count differs"+ );+ assert_eq!(+ a.is_leaf(),+ b.is_leaf(),+ "node {i} ({side}) leafness differs"+ );+ }+ }+ for i in 0..LEAVES {+ assert_eq!(+ seq.leaf_node(i).map(|n| n.aabb()),+ par.leaf_node(i).map(|n| n.aabb()),+ "leaf {i} differs after refit"+ );+ }+ }++ /// [`Bvh::refit_parallel`] documents that "only the work distribution differs".+ #[test]+ fn refit_parallel_matches_sequential() {+ let (mut seq, mut par) = (scene(), scene());+ let (mut w1, mut w2) = (BvhWorkspace::default(), BvhWorkspace::default());+ seq.refit(&mut w1);+ par.refit_parallel(&mut w2);+ assert_same_nodes(&seq, &par);+ }++ /// Same, for the flag-preserving refit rapier runs in its deferred optimization pass.+ #[test]+ fn refit_without_resolve_parallel_matches_sequential() {+ let (mut seq, mut par) = (scene(), scene());+ let (mut w1, mut w2) = (BvhWorkspace::default(), BvhWorkspace::default());+ seq.optimize_incremental(&mut w1);+ par.optimize_incremental(&mut w2);+ seq.refit_without_resolve(&mut w1);+ par.refit_without_resolve_parallel(&mut w2);+ assert_same_nodes(&seq, &par);+ }++ /// [`Bvh::traverse_bvtt_single_tree_parallel`] documents that it returns the pairs "in+ /// the exact same order as the calls the sequential traversal would have made".+ #[test]+ fn bvtt_traversal_parallel_matches_sequential() {+ let mut bvh = scene();+ let mut workspace = BvhWorkspace::default();+ bvh.refit(&mut workspace);++ let mut sequential = Vec::new();+ bvh.traverse_bvtt_single_tree::<false>(&mut workspace, &mut |a, b| sequential.push((a, b)));+ let parallel = bvh.traverse_bvtt_single_tree_parallel::<false>();++ assert!(+ !sequential.is_empty(),+ "the scene must actually report pairs"+ );+ assert_eq!(+ sequential, parallel,+ "the parallel BVTT traversal reported a different pair sequence"+ );+ }+}diff --git a/renderer/third_party/parry3d/src/partitioning/bvh/bvh_traverse.rs b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_traverse.rsnew file mode 100644index 0000000..1874833--- /dev/null+++ b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_traverse.rs@@ -0,0 +1,445 @@+use super::BvhNode;+use crate::math::Real;+use crate::partitioning::{Bvh, BvhNodeIndex};+use smallvec::SmallVec;++const TRAVERSAL_STACK_SIZE: usize = 32;++pub struct Leaves<'a, Check: Fn(&BvhNode) -> bool> {+ tree: &'a Bvh,+ next: Option<&'a BvhNode>,+ stack: SmallVec<[&'a BvhNode; TRAVERSAL_STACK_SIZE]>,+ check: Check,+}++impl<'a, Check: Fn(&BvhNode) -> bool> Leaves<'a, Check> {+ pub fn new(tree: &'a Bvh, check: Check) -> Leaves<'a, Check> {+ let mut stack = SmallVec::default();+ let mut next = None;++ if let Some(root) = tree.nodes.first() {+ if check(&root.left) {+ next = Some(&root.left);+ }++ if root.right.leaf_count() > 0 && check(&root.right) {+ stack.push(&root.right);+ }+ }++ Leaves {+ tree,+ next,+ stack,+ check,+ }+ }+}++impl<'a, Check: Fn(&BvhNode) -> bool> Iterator for Leaves<'a, Check> {+ type Item = u32;+ fn next(&mut self) -> Option<Self::Item> {+ loop {+ if self.next.is_none() {+ self.next = self.stack.pop();+ }++ let node = self.next.take()?;++ if node.is_leaf() {+ return Some(node.children);+ }++ let children = &self.tree.nodes[node.children as usize];+ let left = &children.left;+ let right = &children.right;++ if (self.check)(left) {+ self.next = Some(left);+ }++ if (self.check)(right) {+ if self.next.is_none() {+ self.next = Some(right);+ } else {+ self.stack.push(right);+ }+ }+ }+ }+}++/// Cost associated to a BVH leaf during best-first traversal.+pub trait BvhLeafCost {+ /// The cost value associated to the leaf.+ ///+ /// Best-first searches for the leaf with the lowest cost.+ fn cost(&self) -> Real;+}++impl BvhLeafCost for Real {+ #[inline(always)]+ fn cost(&self) -> Real {+ *self+ }+}++impl<T> BvhLeafCost for (Real, T) {+ #[inline(always)]+ fn cost(&self) -> Real {+ self.0+ }+}++impl Bvh {+ /// Iterates through the leaves, in depth-first order.+ ///+ /// The `check_node` closure is called on every traversed node. If it returns `false` then the+ /// node and all its descendants won’t be iterated on. This is useful for pruning whole+ /// sub-trees based on a geometric predicate on the node’s AABB.+ ///+ /// See also the [`Bvh::traverse`] function which is slightly less convenient since it doesn’t+ /// rely on the iterator system, but takes a closure that implements [`FnMut`] instead of [`Fn`].+ pub fn leaves<F: Fn(&BvhNode) -> bool>(&self, check_node: F) -> Leaves<'_, F> {+ Leaves::new(self, check_node)+ }+}++/// Controls the execution flow of [`Bvh::traverse`].+pub enum TraversalAction {+ /// The traversal will continue on the children of the tested node.+ Continue,+ /// The traversal will skip all descendants of the tested node.+ Prune,+ /// The traversal will exit immediately.+ EarlyExit,+}++impl Bvh {+ #[inline(always)]+ pub(crate) fn traversal_stack() -> SmallVec<[u32; 32]> {+ Default::default()+ }++ /// Traverses the BVH in depth-first order with full control over traversal.+ ///+ /// This method provides low-level control over tree traversal. For each node visited,+ /// it calls your closure which can decide whether to continue traversing, prune that+ /// subtree, or exit early.+ ///+ /// # Arguments+ ///+ /// * `check_node` - A mutable closure called for each node. It receives a [`BvhNode`]+ /// and returns a [`TraversalAction`] to control the traversal:+ /// - `Continue`: Visit this node's children (if not a leaf)+ /// - `Prune`: Skip this node's subtree entirely+ /// - `EarlyExit`: Stop traversal immediately+ ///+ /// # Traversal Order+ ///+ /// The tree is traversed in **depth-first** order:+ /// 1. Check current node with `check_node`+ /// 2. If `Continue`, descend into left child first+ /// 3. Then descend into right child+ /// 4. Backtrack when both subtrees are processed+ ///+ /// This order is cache-friendly and matches the tree's memory layout.+ ///+ /// # When to Use+ ///+ /// Use `traverse` when you need:+ /// - **Mutable state** during traversal+ /// - **Early exit** conditions+ /// - **Full control** over pruning decisions+ /// - **Custom query logic** that doesn't fit standard patterns+ ///+ /// For simpler cases, consider:+ /// - [`leaves`](Self::leaves) - Iterator over leaves matching a predicate+ /// - [`intersect_aabb`](Self::intersect_aabb) - Find leaves intersecting an AABB+ /// - [`cast_ray`](Self::cast_ray) - Ray casting queries+ ///+ /// # Performance+ ///+ /// - **Best case**: O(log n) when pruning effectively+ /// - **Worst case**: O(n) when visiting all nodes+ /// - Cache-friendly due to depth-first order+ /// - No allocations beyond a small stack (~32 entries)+ ///+ /// # Examples+ ///+ /// ## Count leaves in a region+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy, TraversalAction};+ /// use parry3d::bounding_volume::{Aabb, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let aabbs = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(5.0, 0.0, 0.0), Vector::new(6.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(10.0, 0.0, 0.0), Vector::new(11.0, 1.0, 1.0)),+ /// ];+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+ ///+ /// let query_region = Aabb::new(+ /// Vector::new(-1.0, -1.0, -1.0),+ /// Vector::new(7.0, 2.0, 2.0)+ /// );+ ///+ /// let mut count = 0;+ /// bvh.traverse(|node| {+ /// if !node.aabb().intersects(&query_region) {+ /// // Prune: this entire subtree is outside the region+ /// return TraversalAction::Prune;+ /// }+ ///+ /// if node.is_leaf() {+ /// count += 1;+ /// }+ ///+ /// TraversalAction::Continue+ /// });+ ///+ /// assert_eq!(count, 2); // First two objects intersect the region+ /// # }+ /// ```+ ///+ /// ## Find first leaf matching a condition+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy, TraversalAction};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabbs = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(5.0, 0.0, 0.0), Vector::new(6.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(10.0, 0.0, 0.0), Vector::new(11.0, 1.0, 1.0)),+ /// ];+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+ ///+ /// let target_point = Vector::new(5.5, 0.5, 0.5);+ /// let mut found_leaf = None;+ ///+ /// bvh.traverse(|node| {+ /// if !node.aabb().contains_local_point(target_point) {+ /// return TraversalAction::Prune;+ /// }+ ///+ /// if let Some(leaf_id) = node.leaf_data() {+ /// found_leaf = Some(leaf_id);+ /// return TraversalAction::EarlyExit; // Found it, stop searching+ /// }+ ///+ /// TraversalAction::Continue+ /// });+ ///+ /// assert_eq!(found_leaf, Some(1));+ /// # }+ /// ```+ ///+ /// ## Collect statistics with mutable state+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy, TraversalAction};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabbs = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(4.0, 0.0, 0.0), Vector::new(5.0, 1.0, 1.0)),+ /// ];+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+ ///+ /// let mut stats = (0, 0); // (num_internal_nodes, num_leaves)+ ///+ /// bvh.traverse(|node| {+ /// if node.is_leaf() {+ /// stats.1 += 1;+ /// } else {+ /// stats.0 += 1;+ /// }+ /// TraversalAction::Continue+ /// });+ ///+ /// assert_eq!(stats.1, 3); // 3 leaves+ /// # }+ /// ```+ ///+ /// # Notes+ ///+ /// - The closure is called for **every** visited node (internal and leaf)+ /// - Pruning a node skips all its descendants+ /// - Use `node.is_leaf()` to distinguish leaves from internal nodes+ /// - Use `node.leaf_data()` to get the leaf's index (returns `None` for internal nodes)+ /// - The traversal uses a small fixed-size stack internally+ ///+ /// # See Also+ ///+ /// - [`leaves`](Self::leaves) - Simpler iterator interface for leaf traversal+ /// - [`intersect_aabb`](Self::intersect_aabb) - Specialized AABB intersection query+ /// - [`cast_ray`](Self::cast_ray) - Ray casting with best-first traversal+ /// - [`TraversalAction`] - Controls traversal flow+ pub fn traverse(&self, mut check_node: impl FnMut(&BvhNode) -> TraversalAction) {+ self.traverse_indexed(None, move |node, _| check_node(node));+ }++ /// Similar to [`Self::traverse`] but starts the traversal with the node at index `subtree`,+ /// and the `check_node` closure is given the node index.+ ///+ /// If `subtree` is `None` the traversal starts at the root of the tree.+ pub fn traverse_indexed(+ &self,+ subtree: Option<BvhNodeIndex>,+ mut check_node: impl FnMut(&BvhNode, BvhNodeIndex) -> TraversalAction,+ ) {+ let mut stack = Self::traversal_stack();+ let mut curr_id = 0;++ if let Some(subtree) = subtree {+ let to_check = &self.nodes[subtree];+ match check_node(to_check, subtree) {+ TraversalAction::Continue => {+ if to_check.is_leaf() {+ return;+ }++ curr_id = to_check.children;+ }+ TraversalAction::Prune | TraversalAction::EarlyExit => return,+ }+ } else {+ // Start at the root.+ if self.nodes.is_empty() {+ return;+ } else if self.nodes[0].right.leaf_count() == 0 {+ // Special case for partial root.+ let _ = check_node(&self.nodes[0].left, BvhNodeIndex::left(0));+ return;+ }+ }++ loop {+ let node = &self.nodes[curr_id as usize];+ let left = &node.left;+ let right = &node.right;+ let go_left = match check_node(left, BvhNodeIndex::left(curr_id)) {+ TraversalAction::Continue => !left.is_leaf(),+ TraversalAction::Prune => false,+ TraversalAction::EarlyExit => return,+ };+ let go_right = match check_node(right, BvhNodeIndex::right(curr_id)) {+ TraversalAction::Continue => !right.is_leaf(),+ TraversalAction::Prune => false,+ TraversalAction::EarlyExit => return,+ };++ match (go_left, go_right) {+ (true, true) => {+ curr_id = left.children;+ stack.push(right.children);+ }+ (true, false) => curr_id = left.children,+ (false, true) => curr_id = right.children,+ (false, false) => {+ let Some(next) = stack.pop() else {+ return;+ };+ curr_id = next;+ }+ }+ }+ }++ /// Find the leaf that minimizes their associated cost.+ pub fn find_best<L: BvhLeafCost>(+ &self,+ max_cost: Real,+ aabb_cost: impl Fn(&BvhNode, Real) -> Real,+ leaf_cost: impl Fn(u32, Real) -> Option<L>,+ ) -> Option<(u32, L)> {+ // A stack with 32 elements should be more than enough in most cases.+ let mut stack = Self::traversal_stack();+ let mut best_val = None;+ let mut best_cost = max_cost;+ let mut best_id = u32::MAX;+ let mut curr_id = 0;++ if self.nodes.is_empty() {+ return None;+ } else if self.nodes[0].right.leaf_count() == 0 {+ // Special case for partial root.+ let leaf = &self.nodes[0].left;+ if aabb_cost(leaf, max_cost) < max_cost {+ let cost = leaf_cost(leaf.children, best_cost)?;+ return (cost.cost() < max_cost).then_some((leaf.children, cost));+ } else {+ return None;+ }+ }++ loop {+ let node = &self.nodes[curr_id as usize];+ let mut left = &node.left;+ let mut right = &node.right;++ let mut left_score = aabb_cost(left, best_cost);+ let mut right_score = aabb_cost(right, best_cost);++ if left_score > right_score {+ core::mem::swap(&mut left_score, &mut right_score);+ core::mem::swap(&mut left, &mut right);+ }++ let mut found_next = false;+ if left_score < best_cost && left_score != Real::MAX {+ if left.is_leaf() {+ if let Some(primitive_val) = leaf_cost(left.children, best_cost) {+ let primitive_score = primitive_val.cost();+ if primitive_score < best_cost {+ best_val = Some(primitive_val);+ best_cost = primitive_score;+ best_id = left.children;+ }+ }+ } else {+ curr_id = left.children;+ found_next = true;+ }+ }++ if right_score < best_cost && right_score != Real::MAX {+ if right.is_leaf() {+ if let Some(primitive_val) = leaf_cost(right.children, best_cost) {+ let primitive_score = primitive_val.cost();+ if primitive_score < best_cost {+ best_val = Some(primitive_val);+ best_cost = primitive_score;+ best_id = right.children;+ }+ }+ } else if found_next {+ stack.push(right.children);+ } else {+ curr_id = right.children;+ found_next = true;+ }+ }++ if !found_next {+ if let Some(next) = stack.pop() {+ curr_id = next;+ } else {+ return best_val.map(|val| (best_id, val));+ }+ }+ }+ }+}diff --git a/renderer/third_party/parry3d/src/partitioning/bvh/bvh_traverse_bvtt.rs b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_traverse_bvtt.rsnew file mode 100644index 0000000..b43ec33--- /dev/null+++ b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_traverse_bvtt.rs@@ -0,0 +1,528 @@+use super::{Bvh, BvhNode, BvhWorkspace};+use alloc::vec::Vec;+use smallvec::SmallVec;++const TRAVERSAL_STACK_SIZE: usize = 32;++impl Bvh {+ /*+ * Traversal of a tree against itself.+ */+ // NOTE PERF: change detection doesn’t make a huge difference in 2D (it can+ // occasionally even make it slower!) Once we support a static/dynamic tree+ // instead of a single tree, we might want to fully disable change detection+ // in 2D.+ /// Traverses the Bounding Volume Test Tree of a tree against itself.+ ///+ /// The closure `f` will be called on each pair of leaf that passed the AABB intersection checks.+ /// If `CHANGE_DETECTION` is `true`, then only pairs of leaves where at least one was detected+ /// as changed during [`Self::insert_or_update_partially`] will be traversed.+ pub fn traverse_bvtt_single_tree<const CHANGE_DETECTION: bool>(+ &self,+ workspace: &mut BvhWorkspace,+ f: &mut impl FnMut(u32, u32),+ ) {+ if self.nodes.is_empty() || self.nodes[0].right.leaf_count() == 0 {+ // Not enough nodes for any overlap.+ return;+ }++ workspace.traversal_stack.clear();+ self.self_intersect_node::<CHANGE_DETECTION>(&mut workspace.traversal_stack, 0, f)+ }++ // Traverses overlaps of a single node with itself.+ // This as special case to:+ // - Ensure we don’t traverse the same branch twice.+ // - Only check the left/right overlap. Left/left and right/right checks trivially pass.+ // TODO: take change detection into account.+ fn self_intersect_node<const CHANGE_DETECTION: bool>(+ &self,+ stack: &mut Vec<u32>,+ id: u32,+ f: &mut impl FnMut(u32, u32),+ ) {+ let node = &self.nodes[id as usize];++ if CHANGE_DETECTION && !node.right.is_changed() && !node.left.is_changed() {+ return;+ }++ let left_right_intersect = node.left.intersects(&node.right);+ let left_child = node.left.children;+ let right_child = node.right.children;+ let left_is_leaf = node.left.is_leaf();+ let right_is_leaf = node.right.is_leaf();++ if (!CHANGE_DETECTION || node.left.is_changed()) && !left_is_leaf {+ self.self_intersect_node::<CHANGE_DETECTION>(stack, left_child, f);+ }++ if (!CHANGE_DETECTION || node.right.is_changed()) && !right_is_leaf {+ self.self_intersect_node::<CHANGE_DETECTION>(stack, right_child, f);+ }++ if left_right_intersect {+ match (left_is_leaf, right_is_leaf) {+ (true, true) => f(left_child, right_child),+ (true, false) => self.traverse_single_subtree::<CHANGE_DETECTION>(+ stack,+ &node.left,+ right_child,+ f,+ ),+ (false, true) => self.traverse_single_subtree::<CHANGE_DETECTION>(+ stack,+ &node.right,+ left_child,+ f,+ ),+ (false, false) => self.traverse_two_branches::<CHANGE_DETECTION>(+ stack,+ left_child,+ right_child,+ f,+ ),+ }+ }+ }++ fn traverse_two_branches<const CHANGE_DETECTION: bool>(+ &self,+ stack: &mut Vec<u32>,+ a: u32,+ b: u32,+ f: &mut impl FnMut(u32, u32),+ ) {+ let node1 = &self.nodes[a as usize];+ let node2 = &self.nodes[b as usize];++ let left1 = &node1.left;+ let right1 = &node1.right;+ let left2 = &node2.left;+ let right2 = &node2.right;++ let left_left = (!CHANGE_DETECTION || left1.is_changed() || left2.is_changed())+ && left1.intersects(left2);+ let left_right = (!CHANGE_DETECTION || left1.is_changed() || right2.is_changed())+ && left1.intersects(right2);+ let right_left = (!CHANGE_DETECTION || right1.is_changed() || left2.is_changed())+ && right1.intersects(left2);+ let right_right = (!CHANGE_DETECTION || right1.is_changed() || right2.is_changed())+ && right1.intersects(right2);++ macro_rules! dispatch(+ ($check: ident, $child_a: ident, $child_b: ident) => {+ if $check {+ match ($child_a.is_leaf(), $child_b.is_leaf()) {+ (true, true) => f($child_a.children, $child_b.children),+ (true, false) => {+ self.traverse_single_subtree::<CHANGE_DETECTION>(stack, $child_a, $child_b.children, f)+ }+ (false, true) => self.traverse_single_subtree::<CHANGE_DETECTION>(+ stack,+ $child_b,+ $child_a.children,+ f,+ ),+ (false, false) => self.traverse_two_branches::<CHANGE_DETECTION>(+ stack,+ $child_a.children,+ $child_b.children,+ f,+ ),+ }+ }+ }+ );++ dispatch!(left_left, left1, left2);+ dispatch!(left_right, left1, right2);+ dispatch!(right_left, right1, left2);+ dispatch!(right_right, right1, right2);+ }++ // Checks overlap between a single node and a subtree.+ fn traverse_single_subtree<const CHANGE_DETECTION: bool>(+ &self,+ stack: &mut Vec<u32>,+ node: &BvhNode,+ subtree: u32,+ f: &mut impl FnMut(u32, u32),+ ) {+ debug_assert!(stack.is_empty());++ // Since this is traversing against a single node it is more efficient to keep the leaf reference+ // around and traverse the branch using a manual stack. Left branches are traversed by the main+ // loop whereas the right branches are pushed to the stack.+ let mut curr_id = subtree;+ let node_changed = node.is_changed();++ loop {+ let curr = &self.nodes[curr_id as usize];+ let left = &curr.left;+ let right = &curr.right;+ let left_check =+ (!CHANGE_DETECTION || node_changed || left.is_changed()) && node.intersects(left);+ let right_check =+ (!CHANGE_DETECTION || node_changed || right.is_changed()) && node.intersects(right);+ let left_is_leaf = left.is_leaf();+ let right_is_leaf = right.is_leaf();+ let mut found_next = false;++ if left_check {+ if left_is_leaf {+ f(node.children, left.children)+ } else {+ curr_id = left.children;+ found_next = true;+ }+ }++ if right_check {+ if right_is_leaf {+ f(node.children, right.children)+ } else if !found_next {+ curr_id = right.children;+ found_next = true;+ } else {+ // We already advanced in curr_id once, push the other+ // branch to the stack.+ stack.push(right.children);+ }+ }++ if !found_next {+ // Pop the stack to find the next candidate.+ if let Some(next_id) = stack.pop() {+ curr_id = next_id;+ } else {+ // Traversal is finished.+ return;+ }+ }+ }+ }++ /// Parallel version of [`Self::traverse_bvtt_single_tree`], returning the reached+ /// leaf pairs instead of invoking a closure.+ ///+ /// The returned pairs are in the exact same order as the calls the sequential+ /// traversal would have made, so both versions are interchangeable, including for+ /// determinism-sensitive callers.+ #[cfg(feature = "parallel")]+ pub fn traverse_bvtt_single_tree_parallel<const CHANGE_DETECTION: bool>(+ &self,+ ) -> Vec<(u32, u32)> {+ if self.nodes.is_empty() || self.nodes[0].right.leaf_count() == 0 {+ // Not enough nodes for any overlap.+ return Vec::new();+ }++ const MAX_SPLIT_DEPTH: u32 = 6;+ self.self_intersect_node_parallel::<CHANGE_DETECTION>(0, MAX_SPLIT_DEPTH)+ }++ /// Task-parallel mirror of `self_intersect_node`: the recursions become tasks and+ /// their results are concatenated in the same order as the sequential recursion.+ #[cfg(feature = "parallel")]+ fn self_intersect_node_parallel<const CHANGE_DETECTION: bool>(+ &self,+ id: u32,+ depth: u32,+ ) -> Vec<(u32, u32)> {+ // Subtrees below this leaf count are traversed sequentially.+ const SEQ_LEAF_THRESHOLD: u32 = 512;++ let node = &self.nodes[id as usize];++ if CHANGE_DETECTION && !node.right.is_changed() && !node.left.is_changed() {+ return Vec::new();+ }++ if depth == 0 || node.left.leaf_count() + node.right.leaf_count() <= SEQ_LEAF_THRESHOLD {+ let mut out = Vec::new();+ let mut stack = Vec::new();+ self.self_intersect_node::<CHANGE_DETECTION>(&mut stack, id, &mut |a, b| {+ out.push((a, b))+ });+ return out;+ }++ let left_right_intersect = node.left.intersects(&node.right);+ let left_child = node.left.children;+ let right_child = node.right.children;+ let left_is_leaf = node.left.is_leaf();+ let right_is_leaf = node.right.is_leaf();++ let (mut left_pairs, (mut right_pairs, mut cross_pairs)) = rayon::join(+ || {+ if (!CHANGE_DETECTION || node.left.is_changed()) && !left_is_leaf {+ self.self_intersect_node_parallel::<CHANGE_DETECTION>(left_child, depth - 1)+ } else {+ Vec::new()+ }+ },+ || {+ rayon::join(+ || {+ if (!CHANGE_DETECTION || node.right.is_changed()) && !right_is_leaf {+ self.self_intersect_node_parallel::<CHANGE_DETECTION>(+ right_child,+ depth - 1,+ )+ } else {+ Vec::new()+ }+ },+ || {+ let mut out = Vec::new();+ if left_right_intersect {+ match (left_is_leaf, right_is_leaf) {+ (true, true) => out.push((left_child, right_child)),+ (true, false) => {+ let mut stack = Vec::new();+ self.traverse_single_subtree::<CHANGE_DETECTION>(+ &mut stack,+ &node.left,+ right_child,+ &mut |a, b| out.push((a, b)),+ );+ }+ (false, true) => {+ let mut stack = Vec::new();+ self.traverse_single_subtree::<CHANGE_DETECTION>(+ &mut stack,+ &node.right,+ left_child,+ &mut |a, b| out.push((a, b)),+ );+ }+ (false, false) => {+ out = self.traverse_two_branches_parallel::<CHANGE_DETECTION>(+ left_child,+ right_child,+ depth - 1,+ );+ }+ }+ }+ out+ },+ )+ },+ );++ left_pairs.append(&mut right_pairs);+ left_pairs.append(&mut cross_pairs);+ left_pairs+ }++ /// Task-parallel mirror of `traverse_two_branches`, preserving its dispatch order+ /// (left/left, left/right, right/left, right/right).+ #[cfg(feature = "parallel")]+ fn traverse_two_branches_parallel<const CHANGE_DETECTION: bool>(+ &self,+ a: u32,+ b: u32,+ depth: u32,+ ) -> Vec<(u32, u32)> {+ const SEQ_LEAF_THRESHOLD: u32 = 512;++ let node1 = &self.nodes[a as usize];+ let node2 = &self.nodes[b as usize];+ let leaf_count = node1.left.leaf_count()+ + node1.right.leaf_count()+ + node2.left.leaf_count()+ + node2.right.leaf_count();++ if depth == 0 || leaf_count <= SEQ_LEAF_THRESHOLD {+ let mut out = Vec::new();+ let mut stack = Vec::new();+ self.traverse_two_branches::<CHANGE_DETECTION>(&mut stack, a, b, &mut |a, b| {+ out.push((a, b))+ });+ return out;+ }++ let dispatch = |child_a: &BvhNode, child_b: &BvhNode, check: bool| -> Vec<(u32, u32)> {+ let mut out = Vec::new();+ if check {+ match (child_a.is_leaf(), child_b.is_leaf()) {+ (true, true) => out.push((child_a.children, child_b.children)),+ (true, false) => {+ let mut stack = Vec::new();+ self.traverse_single_subtree::<CHANGE_DETECTION>(+ &mut stack,+ child_a,+ child_b.children,+ &mut |a, b| out.push((a, b)),+ );+ }+ (false, true) => {+ let mut stack = Vec::new();+ self.traverse_single_subtree::<CHANGE_DETECTION>(+ &mut stack,+ child_b,+ child_a.children,+ &mut |a, b| out.push((a, b)),+ );+ }+ (false, false) => {+ out = self.traverse_two_branches_parallel::<CHANGE_DETECTION>(+ child_a.children,+ child_b.children,+ depth - 1,+ );+ }+ }+ }+ out+ };++ let left1 = &node1.left;+ let right1 = &node1.right;+ let left2 = &node2.left;+ let right2 = &node2.right;++ let left_left = (!CHANGE_DETECTION || left1.is_changed() || left2.is_changed())+ && left1.intersects(left2);+ let left_right = (!CHANGE_DETECTION || left1.is_changed() || right2.is_changed())+ && left1.intersects(right2);+ let right_left = (!CHANGE_DETECTION || right1.is_changed() || left2.is_changed())+ && right1.intersects(left2);+ let right_right = (!CHANGE_DETECTION || right1.is_changed() || right2.is_changed())+ && right1.intersects(right2);++ let ((mut ll, mut lr), (mut rl, mut rr)) = rayon::join(+ || {+ rayon::join(+ || dispatch(left1, left2, left_left),+ || dispatch(left1, right2, left_right),+ )+ },+ || {+ rayon::join(+ || dispatch(right1, left2, right_left),+ || dispatch(right1, right2, right_right),+ )+ },+ );++ ll.append(&mut lr);+ ll.append(&mut rl);+ ll.append(&mut rr);+ ll+ }++ /// Performs a simultaneous traversal of the BVHs `self` and `other`, and yields the pairs+ /// of leaves it reached.+ ///+ /// Any node pairs failing the given `check` will be excluded from the traversal.+ pub fn leaf_pairs<'a, F: Fn(&BvhNode, &BvhNode) -> bool>(+ &'a self,+ other: &'a Self,+ check: F,+ ) -> LeafPairs<'a, F> {+ if let (Some(root1), Some(root2)) = (self.nodes.first(), other.nodes.first()) {+ let mut stack = SmallVec::default();++ if root1.left.leaf_count() > 0 && root2.right.leaf_count() > 0 {+ stack.push((&root1.left, &root2.right));+ // NOTE: we don’t need to push (&root1.left, &root2.left), it is already given as+ // the initial value of `LeafPairs::next`.+ // stack.push((&root1.left, &root2.left))+ }++ if root1.right.leaf_count() > 0 {+ if root2.right.leaf_count() > 0 {+ stack.push((&root1.right, &root2.right));+ }+ stack.push((&root1.right, &root2.left))+ }++ LeafPairs {+ tree1: self,+ tree2: other,+ next: Some((&root1.left, &root2.left)),+ stack,+ check,+ }+ } else {+ LeafPairs {+ tree1: self,+ tree2: other,+ next: None,+ stack: Default::default(),+ check,+ }+ }+ }+}++pub struct LeafPairs<'a, Check: Fn(&BvhNode, &BvhNode) -> bool> {+ tree1: &'a Bvh,+ tree2: &'a Bvh,+ next: Option<(&'a BvhNode, &'a BvhNode)>,+ stack: SmallVec<[(&'a BvhNode, &'a BvhNode); TRAVERSAL_STACK_SIZE]>,+ check: Check,+}++impl<'a, Check: Fn(&BvhNode, &BvhNode) -> bool> Iterator for LeafPairs<'a, Check> {+ type Item = (u32, u32);+ fn next(&mut self) -> Option<Self::Item> {+ loop {+ if self.next.is_none() {+ self.next = self.stack.pop();+ }++ let (node1, node2) = self.next.take()?;++ match (node1.is_leaf(), node2.is_leaf()) {+ (true, true) => return Some((node1.children, node2.children)),+ (true, false) => {+ let child2 = &self.tree2.nodes[node2.children as usize];+ if (self.check)(node1, &child2.left) {+ self.next = Some((node1, &child2.left));+ }+ if (self.check)(node1, &child2.right) {+ if self.next.is_none() {+ self.next = Some((node1, &child2.right));+ } else {+ self.stack.push((node1, &child2.right));+ }+ }+ }+ (false, true) => {+ let child1 = &self.tree1.nodes[node1.children as usize];+ if (self.check)(&child1.left, node2) {+ self.next = Some((&child1.left, node2));+ }+ if (self.check)(&child1.right, node2) {+ if self.next.is_none() {+ self.next = Some((&child1.right, node2));+ } else {+ self.stack.push((&child1.right, node2));+ }+ }+ }+ (false, false) => {+ let child1 = &self.tree1.nodes[node1.children as usize];+ let child2 = &self.tree2.nodes[node2.children as usize];+ if (self.check)(&child1.left, &child2.left) {+ self.stack.push((&child1.left, &child2.left));+ }+ if (self.check)(&child1.right, &child2.left) {+ self.stack.push((&child1.right, &child2.left));+ }+ if (self.check)(&child1.left, &child2.right) {+ self.stack.push((&child1.left, &child2.right));+ }+ if (self.check)(&child1.right, &child2.right) {+ self.stack.push((&child1.right, &child2.right));+ }+ }+ }+ }+ }+}diff --git a/renderer/third_party/parry3d/src/partitioning/bvh/bvh_tree.rs b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_tree.rsnew file mode 100644index 0000000..9fd6907--- /dev/null+++ b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_tree.rs@@ -0,0 +1,2480 @@+use super::bvh_optimize::BvhIncrementalOptimizationState;+use super::BvhOptimizationHeapEntry;+use crate::bounding_volume::{Aabb, BoundingVolume};+use crate::math::{Real, Vector};+use crate::query::{Ray, RayCast};+use crate::utils::VecMap;+use alloc::collections::{BinaryHeap, VecDeque};+use alloc::vec::Vec;+use core::ops::{Deref, DerefMut, Index, IndexMut};++/// The strategy for one-time build of the BVH tree.+///+/// This enum controls which algorithm is used when constructing a BVH from scratch. Different+/// strategies offer different trade-offs between construction speed and final tree quality+/// (measured by ray-casting performance and other query efficiency).+///+/// # Strategy Comparison+///+/// - **Binned**: Fast construction with good overall quality. Best for general-purpose use.+/// - **PLOC**: Slower construction but produces higher quality trees. Best when ray-casting+/// performance is critical and construction time is less important.+///+/// # Performance Notes+///+/// - Neither strategy is currently parallelized, though PLOC is designed to support parallelization.+/// - Tree quality affects query performance: better trees mean fewer node visits during traversals.+/// - For dynamic scenes with frequent updates, choose based on initial construction performance.+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::math::Vector;+///+/// // Create some AABBs for objects in the scene+/// let aabbs = vec![+/// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+/// Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0)),+/// Aabb::new(Vector::new(0.0, 2.0, 0.0), Vector::new(1.0, 3.0, 1.0)),+/// ];+///+/// // Use binned strategy for general purpose (default)+/// let bvh_binned = Bvh::from_leaves(BvhBuildStrategy::Binned, &aabbs);+/// assert_eq!(bvh_binned.leaf_count(), 3);+///+/// // Use PLOC strategy for ray-casting heavy applications+/// let bvh_ploc = Bvh::from_leaves(BvhBuildStrategy::Ploc, &aabbs);+/// assert_eq!(bvh_ploc.leaf_count(), 3);+/// # }+/// ```+///+/// # See Also+///+/// - [`Bvh::from_leaves`] - Construct a BVH using a specific strategy+/// - [`Bvh::from_iter`] - Construct a BVH from an iterator+#[derive(Default, Clone, Debug, Copy, PartialEq, Eq)]+pub enum BvhBuildStrategy {+ /// The tree is built using the binned strategy.+ ///+ /// This implements the strategy from "On fast Construction of SAH-based Bounding Volume Hierarchies"+ /// by Ingo Wald. It uses binning to quickly approximate the Surface Area Heuristic (SAH) cost+ /// function, resulting in fast construction times with good tree quality.+ ///+ /// **Recommended for**: General-purpose usage, dynamic scenes, initial prototyping.+ #[default]+ Binned,+ /// The tree is built using the Locally-Ordered Clustering technique.+ ///+ /// This implements the strategy from "Parallel Locally-Ordered Clustering for Bounding Volume+ /// Hierarchy Construction" by Meister and Bittner. It produces higher quality trees at the cost+ /// of slower construction. The algorithm is designed for parallelization but the current+ /// implementation is sequential.+ ///+ /// **Recommended for**: Ray-casting heavy workloads, static scenes, when query performance+ /// is more important than construction time.+ Ploc,+}++/// Workspace data for various operations on the BVH tree.+///+/// This structure holds temporary buffers and working memory used during BVH operations+/// such as refitting, rebuilding, and optimization. The data inside can be freed at any time+/// without affecting the correctness of BVH results.+///+/// # Purpose+///+/// Many BVH operations require temporary allocations for intermediate results. By reusing+/// the same `BvhWorkspace` across multiple operations, you can significantly reduce allocation+/// overhead and improve performance, especially in performance-critical loops.+///+/// # Usage Pattern+///+/// 1. Create a workspace once (or use [`Default::default()`])+/// 2. Pass it to BVH operations that accept a workspace parameter+/// 3. Reuse the same workspace for subsequent operations+/// 4. The workspace grows to accommodate the largest operation size+///+/// # Memory Management+///+/// - The workspace grows as needed but never automatically shrinks+/// - You can drop and recreate the workspace to free memory+/// - All data is private and managed internally by the BVH+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::partitioning::{Bvh, BvhBuildStrategy, BvhWorkspace};+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::math::Vector;+///+/// let aabbs = vec![+/// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+/// Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0)),+/// ];+///+/// let mut bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+/// let mut workspace = BvhWorkspace::default();+///+/// // Refit the tree after leaf movements+/// bvh.refit(&mut workspace);+///+/// // Reuse the same workspace for optimization+/// bvh.optimize_incremental(&mut workspace);+///+/// // The workspace can be reused across multiple BVH operations+/// # }+/// ```+///+/// # See Also+///+/// - [`Bvh::refit`] - Update AABBs after leaf movement+/// - [`Bvh::optimize_incremental`](Bvh::optimize_incremental) - Incremental tree optimization+#[derive(Clone, Default)]+pub struct BvhWorkspace {+ pub(super) refit_tmp: BvhNodeVec,+ pub(super) rebuild_leaves: Vec<BvhNode>,+ pub(super) optimization_roots: Vec<u32>,+ pub(super) queue: BinaryHeap<BvhOptimizationHeapEntry>,+ pub(super) dequeue: VecDeque<u32>,+ pub(super) traversal_stack: Vec<u32>,+}++/// A piece of data packing state flags as well as leaf counts for a BVH tree node.+#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(transparent)]+pub struct BvhNodeData(u32);+const CHANGED: u32 = 0b01;+const CHANGE_PENDING: u32 = 0b11;++impl BvhNodeData {+ #[inline(always)]+ pub(super) fn with_leaf_count_and_pending_change(leaf_count: u32) -> Self {+ Self(leaf_count | (CHANGE_PENDING << 30))+ }++ #[inline(always)]+ pub(super) fn leaf_count(self) -> u32 {+ self.0 & 0x3fff_ffff+ }++ #[inline(always)]+ pub(super) fn is_changed(self) -> bool {+ self.0 >> 30 == CHANGED+ }++ #[inline(always)]+ pub(super) fn is_change_pending(self) -> bool {+ self.0 >> 30 == CHANGE_PENDING+ }++ #[inline(always)]+ pub(super) fn add_leaf_count(&mut self, added: u32) {+ self.0 += added;+ }++ #[inline(always)]+ pub(super) fn set_change_pending(&mut self) {+ self.0 |= CHANGE_PENDING << 30;+ }++ /// Collapses any change flag (pending or resolved) into the resolved `CHANGED` state.+ ///+ /// Used by partial refitting on internal nodes: a pending flag on an internal node+ /// would otherwise read as "unchanged" (`is_changed() == false`) during traversals.+ #[inline(always)]+ pub(super) fn normalize_change_flag(&mut self) {+ if self.0 >> 30 != 0 {+ *self = Self((self.0 & 0x3fff_ffff) | (CHANGED << 30));+ }+ }++ #[inline(always)]+ pub(super) fn resolve_pending_change(&mut self) {+ if self.is_change_pending() {+ *self = Self((self.0 & 0x3fff_ffff) | (CHANGED << 30));+ } else {+ *self = Self(self.0 & 0x3fff_ffff);+ }+ }++ pub(super) fn merged(self, other: Self) -> Self {+ let leaf_count = self.leaf_count() + other.leaf_count();+ let changed = (self.0 >> 30) | (other.0 >> 30);+ Self(leaf_count | changed << 30)+ }+}++/// A pair of tree nodes forming a 2-wide BVH node.+///+/// The BVH uses a memory layout where nodes are stored in pairs (left and right children)+/// to improve cache coherency and enable SIMD optimizations. This structure represents+/// a single entry in the BVH's node array.+///+/// # Node Validity+///+/// Both `left` and `right` are guaranteed to be valid except for one special case:+/// - **Single leaf tree**: Only `left` is valid, `right` is zeroed+/// - **All other cases**: Both `left` and `right` are valid (tree has at least 2 leaves)+///+/// # Memory Layout+///+/// In 3D with f32 precision and SIMD enabled, this structure is:+/// - **Size**: 64 bytes (cache line aligned)+/// - **Alignment**: 64 bytes (matches typical CPU cache lines)+/// - This alignment improves performance by reducing cache misses+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::math::Vector;+///+/// let aabbs = vec![+/// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+/// Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0)),+/// Aabb::new(Vector::new(4.0, 0.0, 0.0), Vector::new(5.0, 1.0, 1.0)),+/// ];+///+/// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+///+/// // Access the root node's children+/// // The BVH stores nodes as BvhNodeWide pairs internally+/// assert_eq!(bvh.leaf_count(), 3);+/// # }+/// ```+///+/// # See Also+///+/// - [`BvhNode`] - Individual node in the pair+/// - [`Bvh`] - The main BVH structure+#[derive(Copy, Clone, Debug)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+// PERF: the size of this struct is 64 bytes but has a default alignment of 16 (in f32 + 3d + simd mode).+// Forcing an alignment of 64 won’t add padding, and makes aligns it with most cache lines.+#[cfg_attr(all(feature = "dim3", feature = "f32"), repr(align(64)))]+pub struct BvhNodeWide {+ pub(super) left: BvhNode,+ pub(super) right: BvhNode,+}++// NOTE: if this assertion fails with a weird "0 - 1 would overflow" error, it means the equality doesn’t hold.+#[cfg(all(feature = "dim3", feature = "f32"))]+static_assertions::const_assert_eq!(align_of::<BvhNodeWide>(), 64);+#[cfg(all(feature = "dim3", feature = "f32"))]+static_assertions::assert_eq_size!(BvhNodeWide, [u8; 64]);++impl BvhNodeWide {+ /// Creates a new `BvhNodeWide` with both children zeroed out.+ ///+ /// This is primarily used internally during BVH construction and should rarely+ /// be needed in user code.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNodeWide;+ ///+ /// let node_wide = BvhNodeWide::zeros();+ /// assert_eq!(node_wide.leaf_count(), 0);+ /// # }+ /// ```+ #[inline(always)]+ pub fn zeros() -> Self {+ Self {+ left: BvhNode::zeros(),+ right: BvhNode::zeros(),+ }+ }++ /// Returns the two nodes as an array of references.+ ///+ /// This is useful for accessing the left or right node by index (0 or 1 respectively)+ /// instead of by name. Index 0 is the left node, index 1 is the right node.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::{Aabb, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let aabbs = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0)),+ /// ];+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+ /// // The root AABB should contain both leaves+ /// assert!(bvh.root_aabb().contains(&aabbs[0]));+ /// assert!(bvh.root_aabb().contains(&aabbs[1]));+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`as_array_mut`](Self::as_array_mut) - Mutable version+ #[inline(always)]+ pub fn as_array(&self) -> [&BvhNode; 2] {+ [&self.left, &self.right]+ }++ /// Returns the two nodes as an array of mutable references.+ ///+ /// This is useful for modifying the left or right node by index (0 or 1 respectively)+ /// instead of by name. Index 0 is the left node, index 1 is the right node.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNodeWide;+ /// use parry3d::math::Vector;+ ///+ /// let mut node_wide = BvhNodeWide::zeros();+ /// let nodes = node_wide.as_array_mut();+ ///+ /// // Scale both nodes by 2.0+ /// let scale = Vector::splat(2.0);+ /// nodes[0].scale(scale);+ /// nodes[1].scale(scale);+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`as_array`](Self::as_array) - Immutable version+ #[inline(always)]+ pub fn as_array_mut(&mut self) -> [&mut BvhNode; 2] {+ [&mut self.left, &mut self.right]+ }++ /// Merges both child nodes to create their parent node.+ ///+ /// The parent's AABB will be the union of both children's AABBs, and the parent's+ /// leaf count will be the sum of both children's leaf counts. The `my_id` parameter+ /// becomes the parent's `children` field, pointing back to this `BvhNodeWide`.+ ///+ /// # Arguments+ ///+ /// * `my_id` - The index of this `BvhNodeWide` in the BVH's node array+ ///+ /// # Returns+ ///+ /// A new `BvhNode` representing the parent of both children.+ pub fn merged(&self, my_id: u32) -> BvhNode {+ self.left.merged(&self.right, my_id)+ }++ /// Returns the total number of leaves contained in both child nodes.+ ///+ /// This is the sum of the leaf counts of the left and right children. For leaf+ /// nodes, the count is 1. For internal nodes, it's the sum of their descendants.+ ///+ /// # Returns+ ///+ /// The total number of leaves in the subtrees rooted at both children.+ pub fn leaf_count(&self) -> u32 {+ self.left.leaf_count() + self.right.leaf_count()+ }+}++#[repr(C)] // SAFETY: needed to ensure SIMD aabb checks rely on the layout.+#[cfg(all(feature = "dim3", feature = "f32"))]+pub(super) struct BvhNodeSimd {+ mins: glamx::Vec3A,+ maxs: glamx::Vec3A,+}++// SAFETY: compile-time assertions to ensure we can transmute between `BvhNode` and `BvhNodeSimd`.+#[cfg(all(feature = "dim3", feature = "f32"))]+static_assertions::assert_eq_align!(BvhNode, BvhNodeSimd);+#[cfg(all(feature = "dim3", feature = "f32"))]+static_assertions::assert_eq_size!(BvhNode, BvhNodeSimd);++/// A single node (internal or leaf) of a BVH.+///+/// Each node stores an axis-aligned bounding box (AABB) that encompasses all geometry+/// contained within its subtree. A node is either:+/// - **Leaf**: Contains a single piece of geometry (leaf_count == 1)+/// - **Internal**: Contains two child nodes (leaf_count > 1)+///+/// # Structure+///+/// - **AABB**: Stored as separate `mins` and `maxs` points for efficiency+/// - **Children**: For internal nodes, index to a `BvhNodeWide` containing two child nodes.+/// For leaf nodes, this is the user-provided leaf data (typically an index).+/// - **Leaf Count**: Number of leaves in the subtree (1 for leaves, sum of children for internal)+///+/// # Memory Layout+///+/// The structure is carefully laid out for optimal performance:+/// - In 3D with f32: 32 bytes, 16-byte aligned (for SIMD operations)+/// - Fields ordered to enable efficient SIMD AABB tests+/// - The `#[repr(C)]` ensures predictable layout for unsafe optimizations+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::partitioning::BvhNode;+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::math::Vector;+///+/// // Create a leaf node+/// let aabb = Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0));+/// let leaf = BvhNode::leaf(aabb, 42);+///+/// assert!(leaf.is_leaf());+/// assert_eq!(leaf.leaf_data(), Some(42));+/// assert_eq!(leaf.aabb(), aabb);+/// # }+/// ```+///+/// # See Also+///+/// - `BvhNodeWide` - Pair of nodes stored together+/// - [`Bvh`] - The main BVH structure+#[derive(Copy, Clone, Debug, PartialEq)]+#[repr(C)] // SAFETY: needed to ensure SIMD aabb checks rely on the layout.+#[cfg_attr(all(feature = "f32", feature = "dim3"), repr(align(16)))]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+pub struct BvhNode {+ /// Mins coordinates of the node’s bounding volume.+ pub(super) mins: Vector,+ /// Children of this node. A node has either 0 (i.e. it’s a leaf) or 2 children.+ ///+ /// If [`Self::leaf_count`] is 1, then the node has 0 children and is a leaf.+ pub(super) children: u32,+ /// Maxs coordinates of this node’s bounding volume.+ pub(super) maxs: Vector,+ /// Packed data associated to this node (leaf count and flags).+ pub(super) data: BvhNodeData,+}++impl BvhNode {+ #[inline(always)]+ pub(super) fn zeros() -> Self {+ Self {+ mins: Vector::ZERO,+ children: 0,+ maxs: Vector::ZERO,+ data: BvhNodeData(0),+ }+ }++ /// Creates a new leaf node with the given AABB and user data.+ ///+ /// Leaf nodes represent actual geometry in the scene. Each leaf stores:+ /// - The AABB of the geometry it represents+ /// - A user-provided `leaf_data` value (typically an index into your geometry array)+ ///+ /// # Arguments+ ///+ /// * `aabb` - The axis-aligned bounding box for this leaf's geometry+ /// * `leaf_data` - User data associated with this leaf (typically an index or ID)+ ///+ /// # Returns+ ///+ /// A new `BvhNode` representing a leaf with the given properties.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// // Create an AABB for a unit cube+ /// let aabb = Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0));+ ///+ /// // Create a leaf node with index 0+ /// let leaf = BvhNode::leaf(aabb, 0);+ ///+ /// assert!(leaf.is_leaf());+ /// assert_eq!(leaf.leaf_data(), Some(0));+ /// assert_eq!(leaf.aabb(), aabb);+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`is_leaf`](Self::is_leaf) - Check if a node is a leaf+ /// - [`leaf_data`](Self::leaf_data) - Get the leaf data back+ #[inline(always)]+ pub fn leaf(aabb: Aabb, leaf_data: u32) -> BvhNode {+ Self {+ mins: aabb.mins,+ maxs: aabb.maxs,+ children: leaf_data,+ data: BvhNodeData::with_leaf_count_and_pending_change(1),+ }+ }++ /// Returns the user data associated with this leaf node, if it is a leaf.+ ///+ /// For leaf nodes, this returns the `leaf_data` value that was provided when the+ /// leaf was created (typically an index into your geometry array). For internal+ /// nodes, this returns `None`.+ ///+ /// # Returns+ ///+ /// - `Some(leaf_data)` if this is a leaf node+ /// - `None` if this is an internal node+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabb = Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0));+ /// let leaf = BvhNode::leaf(aabb, 42);+ ///+ /// assert_eq!(leaf.leaf_data(), Some(42));+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`leaf`](Self::leaf) - Create a leaf node+ /// - [`is_leaf`](Self::is_leaf) - Check if a node is a leaf+ #[inline(always)]+ pub fn leaf_data(&self) -> Option<u32> {+ self.is_leaf().then_some(self.children)+ }++ /// Returns `true` if this node is a leaf.+ ///+ /// A node is a leaf if its leaf count is exactly 1, meaning it represents a single+ /// piece of geometry rather than a subtree of nodes.+ ///+ /// # Returns+ ///+ /// `true` if this is a leaf node, `false` if it's an internal node.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabb = Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0));+ /// let leaf = BvhNode::leaf(aabb, 0);+ ///+ /// assert!(leaf.is_leaf());+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`leaf_data`](Self::leaf_data) - Get the leaf's user data+ #[inline(always)]+ pub fn is_leaf(&self) -> bool {+ self.leaf_count() == 1+ }++ #[inline(always)]+ pub(super) fn leaf_count(&self) -> u32 {+ self.data.leaf_count()+ }++ #[inline(always)]+ #[cfg(all(feature = "dim3", feature = "f32"))]+ pub(super) fn as_simd(&self) -> &BvhNodeSimd {+ // SAFETY: BvhNode is declared with the alignment+ // and size of two SimdReal.+ unsafe { core::mem::transmute(self) }+ }++ #[inline(always)]+ pub(super) fn merged(&self, other: &Self, children: u32) -> Self {+ Self {+ mins: self.mins.min(other.mins),+ children,+ maxs: self.maxs.max(other.maxs),+ data: self.data.merged(other.data),+ }+ }++ /// Returns the minimum corner of this node's AABB.+ ///+ /// The AABB (axis-aligned bounding box) is defined by two corners: the minimum+ /// corner (with the smallest coordinates on all axes) and the maximum corner.+ ///+ /// # Returns+ ///+ /// A point representing the minimum corner of the AABB.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabb = Aabb::new(Vector::new(1.0, 2.0, 3.0), Vector::new(4.0, 5.0, 6.0));+ /// let node = BvhNode::leaf(aabb, 0);+ ///+ /// assert_eq!(node.mins(), Vector::new(1.0, 2.0, 3.0));+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`maxs`](Self::maxs) - Get the maximum corner+ /// - [`aabb`](Self::aabb) - Get the full AABB+ #[inline]+ pub fn mins(&self) -> Vector {+ self.mins+ }++ /// Returns the maximum corner of this node's AABB.+ ///+ /// The AABB (axis-aligned bounding box) is defined by two corners: the minimum+ /// corner and the maximum corner (with the largest coordinates on all axes).+ ///+ /// # Returns+ ///+ /// A point representing the maximum corner of the AABB.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabb = Aabb::new(Vector::new(1.0, 2.0, 3.0), Vector::new(4.0, 5.0, 6.0));+ /// let node = BvhNode::leaf(aabb, 0);+ ///+ /// assert_eq!(node.maxs(), Vector::new(4.0, 5.0, 6.0));+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`mins`](Self::mins) - Get the minimum corner+ /// - [`aabb`](Self::aabb) - Get the full AABB+ #[inline]+ pub fn maxs(&self) -> Vector {+ self.maxs+ }++ /// Returns this node's AABB as an `Aabb` struct.+ ///+ /// Nodes store their AABBs as separate `mins` and `maxs` points for efficiency.+ /// This method reconstructs the full `Aabb` structure.+ ///+ /// # Returns+ ///+ /// An `Aabb` representing this node's bounding box.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let original_aabb = Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0));+ /// let node = BvhNode::leaf(original_aabb, 0);+ ///+ /// assert_eq!(node.aabb(), original_aabb);+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`mins`](Self::mins) - Get just the minimum corner+ /// - [`maxs`](Self::maxs) - Get just the maximum corner+ #[inline]+ pub fn aabb(&self) -> Aabb {+ Aabb {+ mins: self.mins,+ maxs: self.maxs,+ }+ }++ /// Returns the center point of this node's AABB.+ ///+ /// The center is calculated as the midpoint between the minimum and maximum corners+ /// on all axes: `(mins + maxs) / 2`.+ ///+ /// # Returns+ ///+ /// A point representing the center of the AABB.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabb = Aabb::new(Vector::ZERO, Vector::new(2.0, 4.0, 6.0));+ /// let node = BvhNode::leaf(aabb, 0);+ ///+ /// assert_eq!(node.center(), Vector::new(1.0, 2.0, 3.0));+ /// # }+ /// ```+ #[inline]+ pub fn center(&self) -> Vector {+ self.mins.midpoint(self.maxs)+ }++ /// Returns `true` if this node has been marked as changed.+ ///+ /// The BVH uses change tracking during incremental updates to identify which parts+ /// of the tree need refitting or optimization. This flag is set when a node or its+ /// descendants have been modified.+ ///+ /// # Returns+ ///+ /// `true` if the node is marked as changed, `false` otherwise.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabb = Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0));+ /// let node = BvhNode::leaf(aabb, 0);+ ///+ /// // New leaf nodes are marked as changed (pending change)+ /// // This is used internally for tracking modifications+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`Bvh::refit`] - Uses change tracking to update the tree+ #[inline(always)]+ pub fn is_changed(&self) -> bool {+ self.data.is_changed()+ }++ /// Scales this node's AABB by the given factor.+ ///+ /// Each coordinate of both the minimum and maximum corners is multiplied by the+ /// corresponding component of the scale vector. This is useful when scaling an+ /// entire scene or object.+ ///+ /// # Arguments+ ///+ /// * `scale` - The scale factor to apply (per-axis)+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabb = Aabb::new(Vector::new(1.0, 1.0, 1.0), Vector::new(2.0, 2.0, 2.0));+ /// let mut node = BvhNode::leaf(aabb, 0);+ ///+ /// node.scale(Vector::new(2.0, 2.0, 2.0));+ ///+ /// assert_eq!(node.mins(), Vector::new(2.0, 2.0, 2.0));+ /// assert_eq!(node.maxs(), Vector::new(4.0, 4.0, 4.0));+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`Bvh::scale`] - Scale an entire BVH tree+ #[inline]+ pub fn scale(&mut self, scale: Vector) {+ let new_mins = self.mins * scale;+ let new_maxs = self.maxs * scale;+ // When scale has negative components, mins/maxs swap on those axes.+ // Use component-wise min/max to maintain the AABB invariant (mins <= maxs).+ self.mins = new_mins.min(new_maxs);+ self.maxs = new_mins.max(new_maxs);+ }++ /// Calculates the volume of this node's AABB.+ ///+ /// The volume is the product of the extents on all axes:+ /// - In 2D: width × height (returns area)+ /// - In 3D: width × height × depth (returns volume)+ ///+ /// # Returns+ ///+ /// The volume (or area in 2D) of the AABB.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// // Create a 2×3×4 box+ /// let aabb = Aabb::new(Vector::ZERO, Vector::new(2.0, 3.0, 4.0));+ /// let node = BvhNode::leaf(aabb, 0);+ ///+ /// assert_eq!(node.volume(), 24.0); // 2 * 3 * 4 = 24+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`merged_volume`](Self::merged_volume) - Volume of merged AABBs+ #[inline]+ pub fn volume(&self) -> Real {+ // TODO PERF: simd optimizations?+ let extents = self.maxs - self.mins;+ #[cfg(feature = "dim2")]+ return extents.x * extents.y;+ #[cfg(feature = "dim3")]+ return extents.x * extents.y * extents.z;+ }++ /// Calculates the volume of the AABB that would result from merging this node with another.+ ///+ /// This computes the volume of the smallest AABB that would contain both this node's+ /// AABB and the other node's AABB, without actually creating the merged AABB. This is+ /// useful during BVH construction for evaluating different tree configurations.+ ///+ /// # Arguments+ ///+ /// * `other` - The other node to merge with+ ///+ /// # Returns+ ///+ /// The volume (or area in 2D) of the merged AABB.+ ///+ /// # Performance+ ///+ /// This is more efficient than creating the merged AABB and then computing its volume.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabb1 = Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0));+ /// let aabb2 = Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0));+ ///+ /// let node1 = BvhNode::leaf(aabb1, 0);+ /// let node2 = BvhNode::leaf(aabb2, 1);+ ///+ /// // Merged AABB spans from (0,0,0) to (3,1,1) = 3×1×1 = 3+ /// assert_eq!(node1.merged_volume(&node2), 3.0);+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`volume`](Self::volume) - Volume of a single node+ pub fn merged_volume(&self, other: &Self) -> Real {+ // TODO PERF: simd optimizations?+ let mins = self.mins.min(other.mins);+ let maxs = self.maxs.max(other.maxs);+ let extents = maxs - mins;++ #[cfg(feature = "dim2")]+ return extents.x * extents.y;+ #[cfg(feature = "dim3")]+ return extents.x * extents.y * extents.z;+ }++ /// Tests if this node's AABB intersects another node's AABB.+ ///+ /// Two AABBs intersect if they overlap on all axes. This includes cases where+ /// they only touch at their boundaries.+ ///+ /// # Arguments+ ///+ /// * `other` - The other node to test intersection with+ ///+ /// # Returns+ ///+ /// `true` if the AABBs intersect, `false` otherwise.+ ///+ /// # Performance+ ///+ /// In 3D with f32, this uses vectorized comparisons for improved+ /// performance.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabb1 = Aabb::new(Vector::ZERO, Vector::new(2.0, 2.0, 2.0));+ /// let aabb2 = Aabb::new(Vector::new(1.0, 1.0, 1.0), Vector::new(3.0, 3.0, 3.0));+ /// let aabb3 = Aabb::new(Vector::new(5.0, 5.0, 5.0), Vector::new(6.0, 6.0, 6.0));+ ///+ /// let node1 = BvhNode::leaf(aabb1, 0);+ /// let node2 = BvhNode::leaf(aabb2, 1);+ /// let node3 = BvhNode::leaf(aabb3, 2);+ ///+ /// assert!(node1.intersects(&node2)); // Overlapping+ /// assert!(!node1.intersects(&node3)); // Separated+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`contains`](Self::contains) - Check full containment+ #[cfg(not(all(feature = "dim3", feature = "f32")))]+ pub fn intersects(&self, other: &Self) -> bool {+ self.mins.cmple(other.maxs).all() && self.maxs.cmpge(other.mins).all()+ }++ /// Tests if this node's AABB intersects another node's AABB.+ ///+ /// Two AABBs intersect if they overlap on all axes. This includes cases where+ /// they only touch at their boundaries.+ ///+ /// # Arguments+ ///+ /// * `other` - The other node to test intersection with+ ///+ /// # Returns+ ///+ /// `true` if the AABBs intersect, `false` otherwise.+ ///+ /// # Performance+ ///+ /// This version uses SIMD optimizations for improved performance on supported platforms.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabb1 = Aabb::new(Vector::ZERO, Vector::new(2.0, 2.0, 2.0));+ /// let aabb2 = Aabb::new(Vector::new(1.0, 1.0, 1.0), Vector::new(3.0, 3.0, 3.0));+ /// let aabb3 = Aabb::new(Vector::new(5.0, 5.0, 5.0), Vector::new(6.0, 6.0, 6.0));+ ///+ /// let node1 = BvhNode::leaf(aabb1, 0);+ /// let node2 = BvhNode::leaf(aabb2, 1);+ /// let node3 = BvhNode::leaf(aabb3, 2);+ ///+ /// assert!(node1.intersects(&node2)); // Overlapping+ /// assert!(!node1.intersects(&node3)); // Separated+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`contains`](Self::contains) - Check full containment+ #[cfg(all(feature = "dim3", feature = "f32"))]+ pub fn intersects(&self, other: &Self) -> bool {+ let simd_self = self.as_simd();+ let simd_other = other.as_simd();+ (simd_self.mins.cmple(simd_other.maxs) & simd_self.maxs.cmpge(simd_other.mins)).all()+ }++ /// Tests if this node's AABB fully contains another node's AABB.+ ///+ /// One AABB contains another if the other AABB is completely inside or on the+ /// boundary of this AABB on all axes.+ ///+ /// # Arguments+ ///+ /// * `other` - The other node to test containment of+ ///+ /// # Returns+ ///+ /// `true` if this AABB fully contains the other AABB, `false` otherwise.+ ///+ /// # Performance+ ///+ /// In 3D with f32, this uses vectorized comparisons for improved+ /// performance.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let large = Aabb::new(Vector::ZERO, Vector::new(10.0, 10.0, 10.0));+ /// let small = Aabb::new(Vector::new(2.0, 2.0, 2.0), Vector::new(5.0, 5.0, 5.0));+ ///+ /// let node_large = BvhNode::leaf(large, 0);+ /// let node_small = BvhNode::leaf(small, 1);+ ///+ /// assert!(node_large.contains(&node_small)); // Large contains small+ /// assert!(!node_small.contains(&node_large)); // Small doesn't contain large+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`intersects`](Self::intersects) - Check any overlap+ /// - [`contains_aabb`](Self::contains_aabb) - Contains an `Aabb` directly+ #[cfg(not(all(feature = "dim3", feature = "f32")))]+ pub fn contains(&self, other: &Self) -> bool {+ self.mins.cmple(other.mins).all() && self.maxs.cmpge(other.maxs).all()+ }++ /// Tests if this node's AABB fully contains another node's AABB.+ ///+ /// One AABB contains another if the other AABB is completely inside or on the+ /// boundary of this AABB on all axes.+ ///+ /// # Arguments+ ///+ /// * `other` - The other node to test containment of+ ///+ /// # Returns+ ///+ /// `true` if this AABB fully contains the other AABB, `false` otherwise.+ ///+ /// # Performance+ ///+ /// This version uses SIMD optimizations for improved performance on supported platforms.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let large = Aabb::new(Vector::ZERO, Vector::new(10.0, 10.0, 10.0));+ /// let small = Aabb::new(Vector::new(2.0, 2.0, 2.0), Vector::new(5.0, 5.0, 5.0));+ ///+ /// let node_large = BvhNode::leaf(large, 0);+ /// let node_small = BvhNode::leaf(small, 1);+ ///+ /// assert!(node_large.contains(&node_small)); // Large contains small+ /// assert!(!node_small.contains(&node_large)); // Small doesn't contain large+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`intersects`](Self::intersects) - Check any overlap+ /// - [`contains_aabb`](Self::contains_aabb) - Contains an `Aabb` directly+ #[cfg(all(feature = "dim3", feature = "f32"))]+ pub fn contains(&self, other: &Self) -> bool {+ let simd_self = self.as_simd();+ let simd_other = other.as_simd();+ (simd_self.mins.cmple(simd_other.mins) & simd_self.maxs.cmpge(simd_other.maxs)).all()+ }++ /// Tests if this node's AABB fully contains the given AABB.+ ///+ /// This is similar to [`contains`](Self::contains) but takes an `Aabb` directly+ /// instead of another `BvhNode`.+ ///+ /// # Arguments+ ///+ /// * `other` - The AABB to test containment of+ ///+ /// # Returns+ ///+ /// `true` if this node's AABB fully contains the other AABB, `false` otherwise.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let large = Aabb::new(Vector::ZERO, Vector::new(10.0, 10.0, 10.0));+ /// let small = Aabb::new(Vector::new(2.0, 2.0, 2.0), Vector::new(5.0, 5.0, 5.0));+ ///+ /// let node = BvhNode::leaf(large, 0);+ ///+ /// assert!(node.contains_aabb(&small));+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`contains`](Self::contains) - Contains another `BvhNode`+ pub fn contains_aabb(&self, other: &Aabb) -> bool {+ // TODO PERF: simd optimizations?+ self.mins.cmple(other.mins).all() && self.maxs.cmpge(other.maxs).all()+ }++ /// Casts a ray against this node's AABB.+ ///+ /// Computes the time of impact (parameter `t`) where the ray first intersects+ /// the AABB. The actual hit point is `ray.origin + ray.dir * t`.+ ///+ /// # Arguments+ ///+ /// * `ray` - The ray to cast+ /// * `max_toi` - Maximum time of impact to consider (typically use `f32::MAX` or `f64::MAX`)+ ///+ /// # Returns+ ///+ /// - The time of impact if the ray hits the AABB within `max_toi`+ /// - `Real::MAX` if there is no hit or the hit is beyond `max_toi`+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNode;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::query::Ray;+ /// use parry3d::math::Vector;+ ///+ /// let aabb = Aabb::new(Vector::new(5.0, -1.0, -1.0), Vector::new(6.0, 1.0, 1.0));+ /// let node = BvhNode::leaf(aabb, 0);+ ///+ /// // Ray from origin along X axis+ /// let ray = Ray::new(Vector::ZERO, Vector::new(1.0, 0.0, 0.0));+ ///+ /// let toi = node.cast_ray(&ray, f32::MAX);+ /// assert_eq!(toi, 5.0); // Ray hits at x=5.0+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`Ray`] - Ray structure+ /// - [`Bvh::traverse`] - For traversing the full BVH with ray casts+ pub fn cast_ray(&self, ray: &Ray, max_toi: Real) -> Real {+ self.aabb()+ .cast_local_ray(ray, max_toi, true)+ .unwrap_or(Real::MAX)+ }++ /// Casts a ray on this AABB, with SIMD optimizations.+ ///+ /// Returns `Real::MAX` if there is no hit.+ #[cfg(all(feature = "dim3", feature = "f32"))]+ pub(super) fn cast_inv_ray_simd(&self, ray: &super::bvh_queries::SimdInvRay) -> f32 {+ let simd_self = self.as_simd();+ let t1 = (simd_self.mins - ray.origin) * ray.inv_dir;+ let t2 = (simd_self.maxs - ray.origin) * ray.inv_dir;++ let tmin = t1.min(t2);+ let tmax = t1.max(t2);+ // let tmin = tmin.as_array_ref();+ // let tmax = tmax.as_array_ref();+ let tmin_n = tmin.max_element(); // tmin[0].max(tmin[1].max(tmin[2]));+ let tmax_n = tmax.min_element(); // tmax[0].min(tmax[1].min(tmax[2]));++ if tmax_n >= tmin_n && tmax_n >= 0.0 {+ tmin_n+ } else {+ f32::MAX+ }+ }+}++/// An index identifying a single BVH tree node.+///+/// The BVH stores nodes in pairs (`BvhNodeWide`), where each pair contains a left and+/// right child. This index encodes both which pair and which side (left or right) in a+/// single `usize` value for efficient storage and manipulation.+///+/// # Encoding+///+/// The index is encoded as: `(wide_node_index << 1) | is_right`+/// - The upper bits identify the `BvhNodeWide` (pair of nodes)+/// - The lowest bit indicates left (0) or right (1)+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::partitioning::BvhNodeIndex;+///+/// // Create indices for the left and right children of node pair 5+/// let left = BvhNodeIndex::left(5);+/// let right = BvhNodeIndex::right(5);+///+/// assert_eq!(left.sibling(), right);+/// assert_eq!(right.sibling(), left);+///+/// // Decompose to get the pair index and side+/// let (pair_idx, is_right) = left.decompose();+/// assert_eq!(pair_idx, 5);+/// assert_eq!(is_right, false);+/// # }+/// ```+///+/// # See Also+///+/// - `BvhNodeWide` - The pair of nodes this index points into+/// - [`Bvh`] - The main BVH structure+#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+pub struct BvhNodeIndex(pub usize);++impl BvhNodeIndex {+ pub(super) const LEFT: bool = false;+ pub(super) const RIGHT: bool = true;++ /// Decomposes this index into its components.+ ///+ /// Returns a tuple of `(wide_node_index, is_right)` where:+ /// - `wide_node_index` is the index into the BVH's array of `BvhNodeWide` pairs+ /// - `is_right` is `false` for left child, `true` for right child+ ///+ /// # Returns+ ///+ /// A tuple `(usize, bool)` containing the pair index and side flag.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNodeIndex;+ ///+ /// let left = BvhNodeIndex::left(10);+ /// let (pair_idx, is_right) = left.decompose();+ ///+ /// assert_eq!(pair_idx, 10);+ /// assert_eq!(is_right, false);+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`new`](Self::new) - Construct from components+ #[inline]+ pub fn decompose(self) -> (usize, bool) {+ (self.0 >> 1, (self.0 & 0b01) != 0)+ }++ /// Returns the sibling of this node.+ ///+ /// If this index points to the left child of a pair, returns the right child.+ /// If this index points to the right child, returns the left child.+ ///+ /// # Returns+ ///+ /// The `BvhNodeIndex` of the sibling node.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNodeIndex;+ ///+ /// let left = BvhNodeIndex::left(5);+ /// let right = BvhNodeIndex::right(5);+ ///+ /// assert_eq!(left.sibling(), right);+ /// assert_eq!(right.sibling(), left);+ /// # }+ /// ```+ #[inline]+ pub fn sibling(self) -> Self {+ // Just flip the first bit to switch between left and right child.+ Self(self.0 ^ 0b01)+ }++ /// Creates an index for the left child of a node pair.+ ///+ /// # Arguments+ ///+ /// * `id` - The index of the `BvhNodeWide` pair in the BVH's node array+ ///+ /// # Returns+ ///+ /// A `BvhNodeIndex` pointing to the left child of the specified pair.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNodeIndex;+ ///+ /// let left_child = BvhNodeIndex::left(0);+ /// let (pair_idx, is_right) = left_child.decompose();+ ///+ /// assert_eq!(pair_idx, 0);+ /// assert_eq!(is_right, false);+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`right`](Self::right) - Create index for right child+ /// - [`new`](Self::new) - Create index with explicit side+ #[inline]+ pub fn left(id: u32) -> Self {+ Self::new(id, Self::LEFT)+ }++ /// Creates an index for the right child of a node pair.+ ///+ /// # Arguments+ ///+ /// * `id` - The index of the `BvhNodeWide` pair in the BVH's node array+ ///+ /// # Returns+ ///+ /// A `BvhNodeIndex` pointing to the right child of the specified pair.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNodeIndex;+ ///+ /// let right_child = BvhNodeIndex::right(0);+ /// let (pair_idx, is_right) = right_child.decompose();+ ///+ /// assert_eq!(pair_idx, 0);+ /// assert_eq!(is_right, true);+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`left`](Self::left) - Create index for left child+ /// - [`new`](Self::new) - Create index with explicit side+ #[inline]+ pub fn right(id: u32) -> Self {+ Self::new(id, Self::RIGHT)+ }++ /// Creates a new node index from a pair ID and side flag.+ ///+ /// # Arguments+ ///+ /// * `id` - The index of the `BvhNodeWide` pair in the BVH's node array+ /// * `is_right` - `false` for left child, `true` for right child+ ///+ /// # Returns+ ///+ /// A `BvhNodeIndex` encoding both the pair and the side.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::BvhNodeIndex;+ ///+ /// let left = BvhNodeIndex::new(3, false);+ /// let right = BvhNodeIndex::new(3, true);+ ///+ /// assert_eq!(left, BvhNodeIndex::left(3));+ /// assert_eq!(right, BvhNodeIndex::right(3));+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`left`](Self::left) - Convenience method for left child+ /// - [`right`](Self::right) - Convenience method for right child+ #[inline]+ pub fn new(id: u32, is_right: bool) -> Self {+ Self(((id as usize) << 1) | (is_right as usize))+ }+}++#[derive(Clone, Debug, Default)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+pub(crate) struct BvhNodeVec(pub(crate) Vec<BvhNodeWide>);++impl Deref for BvhNodeVec {+ type Target = Vec<BvhNodeWide>;+ fn deref(&self) -> &Self::Target {+ &self.0+ }+}++impl DerefMut for BvhNodeVec {+ fn deref_mut(&mut self) -> &mut Self::Target {+ &mut self.0+ }+}++impl Index<usize> for BvhNodeVec {+ type Output = BvhNodeWide;++ #[inline(always)]+ fn index(&self, index: usize) -> &Self::Output {+ &self.0[index]+ }+}++impl IndexMut<usize> for BvhNodeVec {+ #[inline(always)]+ fn index_mut(&mut self, index: usize) -> &mut Self::Output {+ &mut self.0[index]+ }+}++impl Index<BvhNodeIndex> for BvhNodeVec {+ type Output = BvhNode;++ #[inline(always)]+ fn index(&self, index: BvhNodeIndex) -> &Self::Output {+ self.0[index.0 >> 1].as_array()[index.0 & 1]+ }+}++impl IndexMut<BvhNodeIndex> for BvhNodeVec {+ #[inline(always)]+ fn index_mut(&mut self, index: BvhNodeIndex) -> &mut Self::Output {+ self.0[index.0 >> 1].as_array_mut()[index.0 & 1]+ }+}++/// A Bounding Volume Hierarchy (BVH) for spatial queries and collision detection.+///+/// A BVH is a tree structure where each node contains an Axis-Aligned Bounding Box (AABB)+/// that encloses all geometry in its subtree. Leaf nodes represent individual objects,+/// while internal nodes partition space hierarchically. This enables efficient spatial+/// queries by allowing entire subtrees to be culled during traversal.+///+/// # What is a BVH and Why Use It?+///+/// A Bounding Volume Hierarchy organizes geometric objects (represented by their AABBs)+/// into a binary tree. Each internal node's AABB bounds the union of its two children's+/// AABBs. This hierarchical structure enables:+///+/// - **Fast spatial queries**: Ray casting, point queries, and AABB intersection tests+/// - **Broad-phase collision detection**: Quickly find potentially colliding pairs+/// - **Efficient culling**: Skip entire branches that don't intersect query regions+///+/// ## Performance Benefits+///+/// Without a BVH, testing N objects against M queries requires O(N × M) tests.+/// With a BVH, this reduces to approximately O(M × log N) for most queries,+/// providing dramatic speedups for scenes with many objects:+///+/// - **1,000 objects**: ~10x faster for ray casting+/// - **10,000 objects**: ~100x faster for ray casting+/// - **Critical for**: Real-time applications (games, physics engines, robotics)+///+/// ## Structure+///+/// The BVH is a binary tree where:+/// - **Leaf nodes**: Contain references to actual geometry (via user-provided indices)+/// - **Internal nodes**: Contain two children and an AABB encompassing both+/// - **Root**: The top-level node encompassing the entire scene+///+/// # Basic Usage - Static Scenes+///+/// For scenes where objects don't move, build the BVH once and query repeatedly:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::math::Vector;+///+/// // Create AABBs for your objects+/// let objects = vec![+/// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+/// Aabb::new(Vector::new(5.0, 0.0, 0.0), Vector::new(6.0, 1.0, 1.0)),+/// Aabb::new(Vector::new(10.0, 0.0, 0.0), Vector::new(11.0, 1.0, 1.0)),+/// ];+///+/// // Build the BVH - the index of each AABB becomes its leaf ID+/// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &objects);+///+/// // Query which objects intersect a region+/// let query_region = Aabb::new(+/// Vector::new(-1.0, -1.0, -1.0),+/// Vector::new(2.0, 2.0, 2.0)+/// );+///+/// for leaf_id in bvh.intersect_aabb(&query_region) {+/// println!("Object {} intersects the query region", leaf_id);+/// // leaf_id corresponds to the index in the original 'objects' vec+/// }+/// # }+/// ```+///+/// # Dynamic Scenes - Adding and Updating Objects+///+/// The BVH supports dynamic scenes where objects move or are added/removed:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::partitioning::{Bvh, BvhWorkspace};+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::math::Vector;+///+/// let mut bvh = Bvh::new();+/// let mut workspace = BvhWorkspace::default();+///+/// // Add objects dynamically with custom IDs+/// bvh.insert(Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)), 100);+/// bvh.insert(Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0)), 200);+///+/// // Update an object's position (by re-inserting with same ID)+/// bvh.insert(Aabb::new(Vector::new(0.5, 0.5, 0.0), Vector::new(1.5, 1.5, 1.0)), 100);+///+/// // Refit the tree after updates for optimal query performance+/// bvh.refit(&mut workspace);+///+/// // Remove an object+/// bvh.remove(200);+/// # }+/// ```+///+/// # Ray Casting Example+///+/// Find the closest object hit by a ray:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::query::{Ray, RayCast};+/// use parry3d::math::Vector;+///+/// let objects = vec![+/// Aabb::new(Vector::new(0.0, 0.0, 5.0), Vector::new(1.0, 1.0, 6.0)),+/// Aabb::new(Vector::new(0.0, 0.0, 10.0), Vector::new(1.0, 1.0, 11.0)),+/// ];+///+/// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &objects);+///+/// // Cast a ray forward along the Z axis+/// let ray = Ray::new(Vector::new(0.5, 0.5, 0.0), Vector::new(0.0, 0.0, 1.0));+/// let max_distance = 100.0;+///+/// // The BVH finds potentially intersecting leaves, then you test actual geometry+/// if let Some((leaf_id, hit_time)) = bvh.cast_ray(&ray, max_distance, |leaf_id, best_hit| {+/// // Test ray against the actual geometry for this leaf+/// // For this example, we test against the AABB itself+/// let aabb = &objects[leaf_id as usize];+/// aabb.cast_local_ray(&ray, best_hit, true)+/// }) {+/// println!("Ray hit object {} at distance {}", leaf_id, hit_time);+/// let hit_point = ray.point_at(hit_time);+/// println!("Hit point: {:?}", hit_point);+/// }+/// # }+/// ```+///+/// # Construction Strategies+///+/// Different build strategies offer trade-offs between build time and query performance:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::math::Vector;+///+/// let aabbs = vec![+/// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+/// Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0)),+/// ];+///+/// // Binned strategy: Fast construction, good quality (recommended default)+/// let bvh_binned = Bvh::from_leaves(BvhBuildStrategy::Binned, &aabbs);+///+/// // PLOC strategy: Slower construction, best quality for ray-casting+/// // Use this for static scenes with heavy query workloads+/// let bvh_ploc = Bvh::from_leaves(BvhBuildStrategy::Ploc, &aabbs);+/// # }+/// ```+///+/// # Maintenance for Dynamic Scenes+///+/// The BVH provides operations to maintain good performance as scenes change:+///+/// ## Refitting+///+/// After objects move, update the tree's AABBs efficiently:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::partitioning::{Bvh, BvhWorkspace};+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::math::Vector;+///+/// let mut bvh = Bvh::new();+/// let mut workspace = BvhWorkspace::default();+///+/// // Insert initial objects+/// bvh.insert(Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)), 0);+/// bvh.insert(Aabb::new(Vector::new(5.0, 0.0, 0.0), Vector::new(6.0, 1.0, 1.0)), 1);+///+/// // Simulate object movement every frame+/// for frame in 0..100 {+/// let offset = frame as f32 * 0.1;+/// bvh.insert(Aabb::new(+/// Vector::new(offset, 0.0, 0.0),+/// Vector::new(1.0 + offset, 1.0, 1.0)+/// ), 0);+///+/// // Refit updates internal AABBs - very fast operation+/// bvh.refit(&mut workspace);+///+/// // Now you can query the BVH with updated positions+/// }+/// # }+/// ```+///+/// ## Incremental Optimization+///+/// For scenes with continuous movement, incrementally improve tree quality:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::partitioning::{Bvh, BvhWorkspace};+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::math::Vector;+///+/// let mut bvh = Bvh::new();+/// let mut workspace = BvhWorkspace::default();+///+/// // Build initial tree+/// for i in 0..1000 {+/// let aabb = Aabb::new(+/// Vector::new(i as f32, 0.0, 0.0),+/// Vector::new(i as f32 + 1.0, 1.0, 1.0)+/// );+/// bvh.insert(aabb, i);+/// }+///+/// // In your update loop:+/// for frame in 0..100 {+/// // Update object positions...+///+/// bvh.refit(&mut workspace);+///+/// // Incrementally optimize tree quality (rebuilds small parts of tree)+/// // Call this every few frames, not every frame+/// if frame % 5 == 0 {+/// bvh.optimize_incremental(&mut workspace);+/// }+/// }+/// # }+/// ```+///+/// # Typical Workflows+///+/// ## Static Scene (Build Once, Query Many Times)+/// 1. Create AABBs for all objects+/// 2. Build BVH with `from_leaves`+/// 3. Query repeatedly (ray casting, intersection tests, etc.)+///+/// ## Dynamic Scene (Objects Move)+/// 1. Build initial BVH or start empty+/// 2. Each frame:+/// - Update positions with `insert`+/// - Call `refit` to update tree AABBs+/// - Perform queries+/// 3. Occasionally call `optimize_incremental` (every 5-10 frames)+///+/// ## Fully Dynamic (Objects Added/Removed)+/// 1. Start with empty BVH+/// 2. Add objects with `insert` as they're created+/// 3. Remove objects with `remove` as they're destroyed+/// 4. Call `refit` after batch updates+/// 5. Call `optimize_incremental` periodically+///+/// # Performance Tips+///+/// - **Reuse `BvhWorkspace`**: Pass the same workspace to multiple operations to avoid+/// allocations+/// - **Batch updates**: Update many leaves, then call `refit` once instead of refitting+/// after each update+/// - **Optimize periodically**: Call `optimize_incremental` every few frames for highly+/// dynamic scenes, not every frame+/// - **Choose right strategy**: Use Binned for most cases, PLOC for static scenes with+/// heavy ray-casting+/// - **Use `insert_or_update_partially`**: For bulk updates followed by a single `refit`+///+/// # Complexity+///+/// - **Construction**: O(n log n) where n is the number of leaves+/// - **Query (average)**: O(log n) for well-balanced trees+/// - **Insert**: O(log n) average+/// - **Remove**: O(log n) average+/// - **Refit**: O(n) but very fast (just updates AABBs)+/// - **Memory**: ~64 bytes per pair of children (3D f32 SIMD), O(n) total+///+/// # See Also+///+/// - [`BvhBuildStrategy`] - Choose construction algorithm (Binned vs PLOC)+/// - [`BvhWorkspace`] - Reusable workspace to avoid allocations+/// - [`BvhNode`] - Individual tree nodes with AABBs+#[derive(Clone, Debug, Default)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+pub struct Bvh {+ pub(super) nodes: BvhNodeVec,+ // Parent indices for elements in `nodes`.+ // We don’t store this in `Self::nodes` since it’s only useful for node removal.+ pub(super) parents: Vec<BvhNodeIndex>,+ pub(super) leaf_node_indices: VecMap<BvhNodeIndex>,+ // NOTE: this cannot be in the workspace as we need this to survive serialization/deserialization+ // to maintain determinism.+ pub(super) optimization: BvhIncrementalOptimizationState,+ // Wide-node slots orphaned by leaf removals, reused by subsequent insertions+ // so remove/insert cycles don't grow the node array unboundedly between+ // compacting refits. The slots are zeroed when freed (a stale leaf copy left+ // in an orphaned slot would be picked up by [`Bvh::rebuild`]'s raw node scan).+ // Compacting refits and rebuilds (which recreate the node array and drop the+ // orphaned slots) clear this list.+ // NOTE: must survive serialization to maintain determinism (the slot reuse+ // order affects the tree topology produced by later insertions).+ #[cfg_attr(feature = "serde-serialize", serde(default))]+ pub(super) free_wide_nodes: Vec<u32>,+}++impl Bvh {+ /// Creates an empty BVH with no leaves.+ ///+ /// This is equivalent to `Bvh::default()` but more explicit. Use this when you plan+ /// to incrementally build the tree using [`insert`](Self::insert), or when you need+ /// an empty placeholder BVH.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::Bvh;+ ///+ /// let bvh = Bvh::new();+ /// assert!(bvh.is_empty());+ /// assert_eq!(bvh.leaf_count(), 0);+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`from_leaves`](Self::from_leaves) - Build from AABBs+ /// - [`from_iter`](Self::from_iter) - Build from an iterator+ pub fn new() -> Self {+ Self::default()+ }++ /// Creates a new BVH from a slice of AABBs.+ ///+ /// Each AABB in the slice becomes a leaf in the BVH. The leaf at index `i` in the slice+ /// will have leaf data `i`, which can be used to identify which object a query result+ /// refers to.+ ///+ /// # Arguments+ ///+ /// * `strategy` - The construction algorithm to use (see [`BvhBuildStrategy`])+ /// * `leaves` - Slice of AABBs, one for each object in the scene+ ///+ /// # Returns+ ///+ /// A new `Bvh` containing all the leaves organized in a tree structure.+ ///+ /// # Performance+ ///+ /// - **Time**: O(n log n) where n is the number of leaves+ /// - **Space**: O(n) additional memory during construction+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabbs = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(4.0, 0.0, 0.0), Vector::new(5.0, 1.0, 1.0)),+ /// ];+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::Binned, &aabbs);+ ///+ /// assert_eq!(bvh.leaf_count(), 3);+ /// // Leaf 0 corresponds to aabbs[0], leaf 1 to aabbs[1], etc.+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`from_iter`](Self::from_iter) - Build from an iterator with custom indices+ /// - [`BvhBuildStrategy`] - Choose construction algorithm+ pub fn from_leaves(strategy: BvhBuildStrategy, leaves: &[Aabb]) -> Self {+ Self::from_iter(strategy, leaves.iter().copied().enumerate())+ }++ /// Creates a new BVH from an iterator of (index, AABB) pairs.+ ///+ /// This is more flexible than [`from_leaves`](Self::from_leaves) as it allows you to+ /// provide custom leaf indices. This is useful when your objects don't have contiguous+ /// indices, or when you want to use sparse IDs.+ ///+ /// # Arguments+ ///+ /// * `strategy` - The construction algorithm to use (see [`BvhBuildStrategy`])+ /// * `leaves` - Iterator yielding `(index, aabb)` pairs+ ///+ /// # Returns+ ///+ /// A new `Bvh` containing all the leaves organized in a tree structure.+ ///+ /// # Notes+ ///+ /// - Indices are stored internally as `u32`, but the iterator accepts `usize` for convenience+ /// - You can use `.enumerate()` directly on an AABB iterator+ /// - Indices larger than `u32::MAX` will overflow+ ///+ /// # Performance+ ///+ /// - **Time**: O(n log n) where n is the number of leaves+ /// - **Space**: O(n) additional memory during construction+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// // Create a BVH with custom indices+ /// let leaves = vec![+ /// (10, Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0))),+ /// (20, Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0))),+ /// (30, Aabb::new(Vector::new(4.0, 0.0, 0.0), Vector::new(5.0, 1.0, 1.0))),+ /// ];+ ///+ /// let bvh = Bvh::from_iter(BvhBuildStrategy::Binned, leaves.into_iter());+ ///+ /// assert_eq!(bvh.leaf_count(), 3);+ /// // Leaf data will be 10, 20, 30 instead of 0, 1, 2+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`from_leaves`](Self::from_leaves) - Simpler version with automatic indices+ /// - [`BvhBuildStrategy`] - Choose construction algorithm+ pub fn from_iter<It>(strategy: BvhBuildStrategy, leaves: It) -> Self+ where+ It: IntoIterator<Item = (usize, Aabb)>,+ {+ let leaves = leaves.into_iter();+ let (capacity_lo, capacity_up) = leaves.size_hint();+ let capacity = capacity_up.unwrap_or(capacity_lo);++ let mut result = Self::new();+ let mut workspace = BvhWorkspace::default();+ workspace.rebuild_leaves.reserve(capacity);+ result.leaf_node_indices.reserve_len(capacity);++ for (leaf_id, leaf_aabb) in leaves {+ workspace+ .rebuild_leaves+ .push(BvhNode::leaf(leaf_aabb, leaf_id as u32));+ let _ = result+ .leaf_node_indices+ .insert(leaf_id, BvhNodeIndex::default());+ }++ // Handle special cases that don’t play well with the rebuilds.+ match workspace.rebuild_leaves.len() {+ 0 => {}+ 1 => {+ result.nodes.push(BvhNodeWide {+ left: workspace.rebuild_leaves[0],+ right: BvhNode::zeros(),+ });+ result.parents.push(BvhNodeIndex::default());+ result.leaf_node_indices[0] = BvhNodeIndex::left(0);+ }+ 2 => {+ result.nodes.push(BvhNodeWide {+ left: workspace.rebuild_leaves[0],+ right: workspace.rebuild_leaves[1],+ });+ result.parents.push(BvhNodeIndex::default());+ result.leaf_node_indices[0] = BvhNodeIndex::left(0);+ result.leaf_node_indices[1] = BvhNodeIndex::right(0);+ }+ _ => {+ result.nodes.reserve(capacity);+ result.parents.reserve(capacity);+ result.parents.clear();+ result.nodes.push(BvhNodeWide::zeros());+ result.parents.push(BvhNodeIndex::default());++ match strategy {+ BvhBuildStrategy::Ploc => {+ result.rebuild_range_ploc(0, &mut workspace.rebuild_leaves)+ }+ BvhBuildStrategy::Binned => {+ result.rebuild_range_binned(0, &mut workspace.rebuild_leaves)+ }+ }++ // Layout in depth-first order.+ result.refit(&mut workspace);+ }+ }++ result+ }++ /// Returns the AABB that bounds all geometry in this BVH.+ ///+ /// This is the AABB of the root node, which encompasses all leaves in the tree.+ /// For an empty BVH, returns an invalid AABB (with mins > maxs).+ ///+ /// # Returns+ ///+ /// An `Aabb` that contains all objects in the BVH.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::{Aabb, BoundingVolume};+ /// use parry3d::math::Vector;+ ///+ /// let aabbs = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(5.0, 0.0, 0.0), Vector::new(6.0, 1.0, 1.0)),+ /// ];+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+ /// let root_aabb = bvh.root_aabb();+ ///+ /// // Root AABB contains both leaves+ /// assert!(root_aabb.contains(&aabbs[0]));+ /// assert!(root_aabb.contains(&aabbs[1]));+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`is_empty`](Self::is_empty) - Check if BVH has no leaves+ pub fn root_aabb(&self) -> Aabb {+ match self.leaf_count() {+ 0 => Aabb::new_invalid(),+ 1 => self.nodes[0].left.aabb(),+ _ => self.nodes[0]+ .left+ .aabb()+ .merged(&self.nodes[0].right.aabb()),+ }+ }++ /// Scales all AABBs in the tree by the given factors.+ ///+ /// Each AABB's coordinates are multiplied by the corresponding scale components, with+ /// mins and maxs swapped on any axis where the scale is negative to preserve the+ /// AABB invariant. This is useful when scaling an entire scene or changing coordinate+ /// systems, including reflections.+ ///+ /// # Arguments+ ///+ /// * `scale` - Per-axis scale factors. Each component must be non-zero.+ ///+ /// # Panics+ ///+ /// Undefined behavior if any scale component is zero (degenerate AABB).+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabbs = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// ];+ ///+ /// let mut bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+ ///+ /// // Scale by 2x on all axes+ /// bvh.scale(Vector::new(2.0, 2.0, 2.0));+ ///+ /// let root = bvh.root_aabb();+ /// assert_eq!(root.maxs, Vector::new(2.0, 2.0, 2.0));+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`BvhNode::scale`] - Scale a single node+ pub fn scale(&mut self, scale: Vector) {+ for node in self.nodes.0.iter_mut() {+ node.left.scale(scale);+ node.right.scale(scale);+ }+ }++ /// Returns `true` if this BVH contains no leaves.+ ///+ /// An empty BVH has no geometry and cannot be queried meaningfully.+ ///+ /// # Returns+ ///+ /// `true` if the BVH is empty, `false` otherwise.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::Bvh;+ ///+ /// let empty_bvh = Bvh::new();+ /// assert!(empty_bvh.is_empty());+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`leaf_count`](Self::leaf_count) - Get the number of leaves+ pub fn is_empty(&self) -> bool {+ self.nodes.is_empty()+ }++ /// Returns a reference to the leaf node with the given index.+ ///+ /// The `leaf_key` is the index that was provided when constructing the BVH+ /// (either the position in the slice for [`from_leaves`](Self::from_leaves),+ /// or the custom index for [`from_iter`](Self::from_iter)).+ ///+ /// # Arguments+ ///+ /// * `leaf_key` - The leaf index to look up+ ///+ /// # Returns+ ///+ /// - `Some(&BvhNode)` if a leaf with that index exists+ /// - `None` if no leaf with that index exists+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabbs = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// ];+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+ ///+ /// // Leaf 0 exists (from aabbs[0])+ /// assert!(bvh.leaf_node(0).is_some());+ ///+ /// // Leaf 1 doesn't exist+ /// assert!(bvh.leaf_node(1).is_none());+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`remove`](Self::remove) - Remove a leaf by index+ pub fn leaf_node(&self, leaf_key: u32) -> Option<&BvhNode> {+ let idx = self.leaf_node_indices.get(leaf_key as usize)?;+ Some(&self.nodes[*idx])+ }++ /// Estimates the total memory usage of this BVH in bytes.+ ///+ /// This includes both the stack size of the `Bvh` struct itself and all+ /// heap-allocated memory (node arrays, parent indices, leaf index maps).+ ///+ /// # Returns+ ///+ /// Approximate memory usage in bytes.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabbs: Vec<_> = (0..100)+ /// .map(|i| {+ /// let f = i as f32;+ /// Aabb::new(Vector::new(f, 0.0, 0.0), Vector::new(f + 1.0, 1.0, 1.0))+ /// })+ /// .collect();+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+ ///+ /// println!("BVH memory usage: {} bytes", bvh.total_memory_size());+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`heap_memory_size`](Self::heap_memory_size) - Only heap-allocated memory+ pub fn total_memory_size(&self) -> usize {+ size_of::<Self>() + self.heap_memory_size()+ }++ /// Estimates the heap-allocated memory usage of this BVH in bytes.+ ///+ /// This only counts dynamically allocated memory (nodes, indices, etc.) and+ /// excludes the stack size of the `Bvh` struct itself.+ ///+ /// # Returns+ ///+ /// Approximate heap memory usage in bytes.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabbs: Vec<_> = (0..100)+ /// .map(|i| {+ /// let f = i as f32;+ /// Aabb::new(Vector::new(f, 0.0, 0.0), Vector::new(f + 1.0, 1.0, 1.0))+ /// })+ /// .collect();+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+ ///+ /// println!("BVH heap memory: {} bytes", bvh.heap_memory_size());+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`total_memory_size`](Self::total_memory_size) - Total memory including stack+ pub fn heap_memory_size(&self) -> usize {+ let Self {+ nodes,+ parents,+ leaf_node_indices,+ optimization: _,+ free_wide_nodes,+ } = self;+ nodes.capacity() * size_of::<BvhNodeWide>()+ + parents.capacity() * size_of::<BvhNodeIndex>()+ + leaf_node_indices.capacity() * size_of::<BvhNodeIndex>()+ + free_wide_nodes.capacity() * size_of::<u32>()+ }++ /// Computes the depth of the subtree rooted at the specified node.+ ///+ /// The depth is the number of levels from the root to the deepest leaf. A single+ /// node has depth 1, a node with two leaf children has depth 2, etc.+ ///+ /// # Arguments+ ///+ /// * `node_id` - The index of the root node of the subtree (use 0 for the entire tree)+ ///+ /// # Returns+ ///+ /// The depth of the subtree, or 0 for an empty tree.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabbs: Vec<_> = (0..4)+ /// .map(|i| {+ /// let f = i as f32;+ /// Aabb::new(Vector::new(f, 0.0, 0.0), Vector::new(f + 1.0, 1.0, 1.0))+ /// })+ /// .collect();+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+ ///+ /// // Get depth of entire tree+ /// let depth = bvh.subtree_depth(0);+ /// assert!(depth >= 2); // At least 2 levels with 4 leaves+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`leaf_count`](Self::leaf_count) - Number of leaves in the tree+ pub fn subtree_depth(&self, node_id: u32) -> u32 {+ if node_id == 0 && self.nodes.is_empty() {+ return 0;+ } else if node_id == 0 && self.nodes.len() == 1 {+ return 1 + (self.nodes[0].right.leaf_count() != 0) as u32;+ }++ let node = &self.nodes[node_id as usize];++ let left_depth = if node.left.is_leaf() {+ 1+ } else {+ self.subtree_depth(node.left.children)+ };++ let right_depth = if node.right.is_leaf() {+ 1+ } else {+ self.subtree_depth(node.right.children)+ };++ left_depth.max(right_depth) + 1+ }++ /// Returns the number of leaves in this BVH.+ ///+ /// Each leaf represents one geometric object that was provided during construction+ /// or added via [`insert`](Self::insert).+ ///+ /// # Returns+ ///+ /// The total number of leaves in the tree.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabbs = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(4.0, 0.0, 0.0), Vector::new(5.0, 1.0, 1.0)),+ /// ];+ ///+ /// let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+ /// assert_eq!(bvh.leaf_count(), 3);+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`is_empty`](Self::is_empty) - Check if the tree has no leaves+ pub fn leaf_count(&self) -> u32 {+ if self.nodes.is_empty() {+ 0+ } else {+ self.nodes[0].leaf_count()+ }+ }++ /// Removes a leaf from the BVH.+ ///+ /// This removes the leaf with the specified index and updates the tree structure+ /// accordingly. The sibling of the removed leaf moves up to take its parent's place,+ /// and all ancestor AABBs and leaf counts are updated.+ ///+ /// # Arguments+ ///+ /// * `leaf_index` - The index of the leaf to remove (the same index used when constructing)+ ///+ /// # Performance+ ///+ /// - **Time**: O(h) where h is the tree height (typically O(log n))+ /// - Updates AABBs and leaf counts for all ancestors of the removed leaf+ /// - For heavily unbalanced trees, consider rebuilding or rebalancing after many removals+ ///+ /// # Notes+ ///+ /// - If the leaf doesn't exist, this is a no-op+ /// - Removing the last leaf results in an empty BVH+ /// - The tree structure remains valid after removal+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::partitioning::{Bvh, BvhBuildStrategy};+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let aabbs = vec![+ /// Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0)),+ /// Aabb::new(Vector::new(4.0, 0.0, 0.0), Vector::new(5.0, 1.0, 1.0)),+ /// ];+ ///+ /// let mut bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs);+ /// assert_eq!(bvh.leaf_count(), 3);+ ///+ /// // Remove the middle leaf+ /// bvh.remove(1);+ /// assert_eq!(bvh.leaf_count(), 2);+ ///+ /// // Leaf 1 no longer exists+ /// assert!(bvh.leaf_node(1).is_none());+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`insert`](Self::insert) - Add a new leaf to the BVH+ /// - [`refit`](Self::refit) - Update AABBs after leaf movements+ /// - [`optimize_incremental`](Self::optimize_incremental) - Improve tree quality+ // TODO: should we make a version that doesn't traverse the parents?+ // If we do, we must be very careful that the leaf counts that become+ // invalid don't break other algorithm… (and, in particular, the root+ // special case that checks if its right element has 0 leaf count).+ pub fn remove(&mut self, leaf_index: u32) {+ if let Some(node_index) = self.leaf_node_indices.remove(leaf_index as usize) {+ if self.leaf_node_indices.is_empty() {+ // We deleted the last leaf! Remove the root.+ self.nodes.clear();+ self.parents.clear();+ self.free_wide_nodes.clear();+ return;+ }++ let sibling = node_index.sibling();+ let (wide_node_index, is_right) = node_index.decompose();++ if wide_node_index == 0 {+ if self.nodes[sibling].is_leaf() {+ // If the sibling is a leaf, we end up with a partial root.+ // There is no parent pointer to update.+ if !is_right {+ // We remove the left leaf. Move the right leaf in its place.+ let moved_index = self.nodes[0].right.children;+ self.nodes[0].left = self.nodes[0].right;+ self.leaf_node_indices[moved_index as usize] = BvhNodeIndex::left(0);+ }++ // Now we can just clear the right leaf.+ self.nodes[0].right = BvhNode::zeros();++ // Clean up orphaned nodes. With a partial root, only node[0] is+ // reachable. Previous removes may have left orphaned wide nodes+ // that were waiting for refit to compact them. If we don't truncate+ // here, the tree appears as a single-leaf tree with unreachable+ // nodes, which corrupts optimize_incremental.+ self.nodes.truncate(1);+ self.parents.truncate(1);+ self.free_wide_nodes.clear();+ } else {+ // The sibling isn’t a leaf. It becomes the new root at index 0.+ let old_sibling_slot = self.nodes[sibling].children;+ self.nodes[0] = self.nodes[old_sibling_slot as usize];+ self.nodes[old_sibling_slot as usize] = BvhNodeWide::zeros();+ self.free_wide_nodes.push(old_sibling_slot);+ // Both parent pointers need to be updated since both nodes moved to the root.+ let new_root = &mut self.nodes[0];+ if new_root.left.is_leaf() {+ self.leaf_node_indices[new_root.left.children as usize] =+ BvhNodeIndex::left(0);+ } else {+ self.parents[new_root.left.children as usize] = BvhNodeIndex::left(0);+ }+ if new_root.right.is_leaf() {+ self.leaf_node_indices[new_root.right.children as usize] =+ BvhNodeIndex::right(0);+ } else {+ self.parents[new_root.right.children as usize] = BvhNodeIndex::right(0);+ }+ }+ } else {+ // The sibling moves to the parent. The affected wide node is no longer accessible,+ // but we can just leave it there, it will get cleaned up at the next refit.+ let parent = self.parents[wide_node_index];+ let sibling = &self.nodes[sibling];++ if sibling.is_leaf() {+ self.leaf_node_indices[sibling.children as usize] = parent;+ } else {+ self.parents[sibling.children as usize] = parent;+ }++ self.nodes[parent] = *sibling;++ // The removed leaf's wide node is now unreachable: zero it (so raw+ // node scans like `Bvh::rebuild` can't pick up its stale leaf+ // copies) and recycle its slot for later insertions.+ self.nodes[wide_node_index] = BvhNodeWide::zeros();+ self.free_wide_nodes.push(wide_node_index as u32);++ // TODO: we could use that propagation as an opportunity to+ // apply some rotations?+ let mut curr = parent.decompose().0;+ while curr != 0 {+ let parent = self.parents[curr];+ self.nodes[parent] = self.nodes[curr].merged(curr as u32);+ curr = parent.decompose().0;+ }+ }+ }+ }++ // pub fn quality_metric(&self) -> Real {+ // let mut metric = 0.0;+ // for i in 0..self.nodes.len() {+ // if !self.nodes[i].is_leaf() {+ // metric += self.sah_cost(i);+ // }+ // }+ // metric+ // }+}diff --git a/renderer/third_party/parry3d/src/partitioning/bvh/bvh_validation.rs b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_validation.rsnew file mode 100644index 0000000..d5bfa9b--- /dev/null+++ b/renderer/third_party/parry3d/src/partitioning/bvh/bvh_validation.rs@@ -0,0 +1,218 @@+use crate::partitioning::bvh::bvh_tree::BvhNodeIndex;+use crate::partitioning::Bvh;+use crate::utils::hashset::HashSet;++impl Bvh {+ /// Counts the number of leaves that can be reached from the node at index `id`.+ ///+ /// This is mostly a utility for debugging.+ pub fn reachable_leaf_count(&self, id: u32) -> u32 {+ if self.nodes.is_empty() {+ 0+ } else if self.nodes[0].right.leaf_count() == 0 {+ (id == 0) as u32+ } else {+ let node = &self.nodes[id as usize];+ let left_count = if node.left.is_leaf() {+ 1+ } else {+ self.reachable_leaf_count(node.left.children)+ };+ let right_count = if node.right.is_leaf() {+ 1+ } else {+ self.reachable_leaf_count(node.right.children)+ };+ left_count + right_count+ }+ }++ /// Counts the number of leaves of `self`, starting with the subtree indexed at+ /// `id`, that are marked as changed.+ ///+ /// This mostly a utility for debugging.+ pub fn changed_leaf_count(&self, id: u32) -> u32 {+ if self.nodes.is_empty() {+ 0+ } else if self.nodes[0].right.leaf_count() == 0 {+ (id == 0 && self.nodes[0].left.data.is_changed()) as u32+ } else {+ let node = &self.nodes[id as usize];+ let left_count = if node.left.is_leaf() {+ node.left.is_changed() as u32+ } else {+ self.changed_leaf_count(node.left.children)+ };+ let right_count = if node.right.is_leaf() {+ node.right.is_changed() as u32+ } else {+ self.changed_leaf_count(node.right.children)+ };+ left_count + right_count+ }+ }++ /// Panics if the tree isn’t well-formed.+ ///+ /// The tree is well-formed if it is topologically correct (internal indices are all valid) and+ /// geometrically correct (node metadata of a parent bound the ones of the children).+ ///+ /// Returns the calculated leaf count.+ pub fn assert_well_formed(&self) {+ if self.is_empty() {+ return;+ } else if self.nodes[0].right.leaf_count() == 0 {+ assert_eq!(self.nodes[0].leaf_count(), 1);+ assert!(self.nodes[0].left.is_leaf());+ return;+ }++ let mut loop_detection = HashSet::default();+ let _ = self.assert_well_formed_recurse(0, &mut loop_detection);+ }++ fn assert_well_formed_recurse(&self, node_id: u32, loop_detection: &mut HashSet<u32>) -> u32 {+ let node = &self.nodes[node_id as usize];++ if !loop_detection.insert(node_id) {+ panic!("Detected loop. Node {} visited twice.", node_id);+ }++ let left_count = if node.left.is_leaf() {+ let leaf_data = self.leaf_node_indices[node.left.children as usize];+ assert_eq!(leaf_data, BvhNodeIndex::left(node_id));+ 1+ } else {+ let calculated_leaf_count =+ self.assert_well_formed_recurse(node.left.children, loop_detection);+ let child = &self.nodes[node.left.children as usize];+ assert_eq!(+ self.parents[node.left.children as usize],+ BvhNodeIndex::left(node_id)+ );+ assert_eq!(+ child.right.is_changed() || child.left.is_changed(),+ node.left.is_changed()+ );+ assert!(node.left.contains(&child.left));+ assert!(node.left.contains(&child.right));+ assert_eq!(+ node.left.leaf_count(),+ child.left.leaf_count() + child.right.leaf_count()+ );+ assert_eq!(node.left.leaf_count(), calculated_leaf_count);+ calculated_leaf_count+ };++ let right_count = if node.right.is_leaf() {+ let leaf_data = self.leaf_node_indices[node.right.children as usize];+ assert_eq!(leaf_data, BvhNodeIndex::right(node_id));+ 1+ } else {+ let calculated_leaf_count =+ self.assert_well_formed_recurse(node.right.children, loop_detection);+ let child = &self.nodes[node.right.children as usize];+ assert_eq!(+ self.parents[node.right.children as usize],+ BvhNodeIndex::right(node_id)+ );+ assert_eq!(+ child.right.is_changed() || child.left.is_changed(),+ node.right.is_changed()+ );+ assert!(node.right.contains(&child.left));+ assert!(node.right.contains(&child.right));+ assert_eq!(+ node.right.leaf_count(),+ child.left.leaf_count() + child.right.leaf_count()+ );+ assert_eq!(calculated_leaf_count, node.right.leaf_count());+ calculated_leaf_count+ };++ left_count + right_count+ }++ /// Similar to [`Self::assert_well_formed`] but doesn’t check the geometry (i.e. it won’t+ /// check that parent AABBs enclose child AABBs).+ ///+ /// This can be useful for checking intermediate states of the tree after topological changes+ /// but before refitting.+ pub fn assert_well_formed_topology_only(&self) {+ let _ = self.assert_well_formed_topology_only_recurse(0);+ }++ fn assert_well_formed_topology_only_recurse(&self, node_id: u32) -> u32 {+ let node = &self.nodes[node_id as usize];++ let left_count = if node.left.is_leaf() {+ assert!(self+ .leaf_node_indices+ .contains_key(node.left.children as usize));+ 1+ } else {+ let calculated_leaf_count =+ self.assert_well_formed_topology_only_recurse(node.left.children);+ let child = &self.nodes[node.left.children as usize];+ assert_eq!(+ self.parents[node.left.children as usize],+ BvhNodeIndex::left(node_id)+ );+ assert_eq!(+ node.left.leaf_count(),+ child.left.leaf_count() + child.right.leaf_count()+ );+ assert_eq!(node.left.leaf_count(), calculated_leaf_count);+ calculated_leaf_count+ };++ let right_count = if node.right.is_leaf() {+ assert!(self+ .leaf_node_indices+ .contains_key(node.right.children as usize));+ 1+ } else {+ let calculated_leaf_count =+ self.assert_well_formed_topology_only_recurse(node.right.children);+ let child = &self.nodes[node.right.children as usize];+ assert_eq!(+ self.parents[node.right.children as usize],+ BvhNodeIndex::right(node_id)+ );+ assert_eq!(+ node.right.leaf_count(),+ child.left.leaf_count() + child.right.leaf_count()+ );+ assert_eq!(calculated_leaf_count, node.right.leaf_count());+ calculated_leaf_count+ };++ left_count + right_count+ }++ /// Panics if the nodes of `self` are not stored in depth-first order on its internal storage.+ ///+ /// Depth-first ordering of `self`’s internals are guaranteed by [`Self::refit`].+ pub fn assert_is_depth_first(&self) {+ if self.is_empty() || self.nodes[0].right.leaf_count() == 0 {+ // Trivially correct and avoids special-cases afterward.+ return;+ }++ let mut stack = alloc::vec![0];+ let mut loop_id = 0;+ while let Some(id) = stack.pop() {+ assert_eq!(loop_id, id);+ loop_id += 1;+ let node = &self.nodes[id as usize];++ if !node.right.is_leaf() {+ stack.push(node.right.children);+ }++ if !node.left.is_leaf() {+ stack.push(node.left.children);+ }+ }+ }+}diff --git a/renderer/third_party/parry3d/src/partitioning/bvh/mod.rs b/renderer/third_party/parry3d/src/partitioning/bvh/mod.rsnew file mode 100644index 0000000..9a917b6--- /dev/null+++ b/renderer/third_party/parry3d/src/partitioning/bvh/mod.rs@@ -0,0 +1,19 @@+pub use bvh_insert::BvhLeafUpdateStatus;+pub use bvh_traverse::{BvhLeafCost, TraversalAction};+pub use bvh_tree::{Bvh, BvhBuildStrategy, BvhNode, BvhNodeIndex, BvhNodeWide, BvhWorkspace};++use bvh_optimize::BvhOptimizationHeapEntry;++mod bvh_binned_build;+mod bvh_insert;+mod bvh_optimize;+mod bvh_ploc_build;+mod bvh_queries;+mod bvh_refit;+mod bvh_traverse;+mod bvh_traverse_bvtt;+mod bvh_tree;+mod bvh_validation;++#[cfg(test)]+mod bvh_tests;diff --git a/renderer/third_party/parry3d/src/partitioning/mod.rs b/renderer/third_party/parry3d/src/partitioning/mod.rsnew file mode 100644index 0000000..12b475e--- /dev/null+++ b/renderer/third_party/parry3d/src/partitioning/mod.rs@@ -0,0 +1,10 @@+//! Spatial partitioning tools.++#[cfg(feature = "alloc")]+pub use self::bvh::{+ Bvh, BvhBuildStrategy, BvhLeafCost, BvhLeafUpdateStatus, BvhNode, BvhNodeIndex, BvhNodeWide,+ BvhWorkspace, TraversalAction,+};++#[cfg(feature = "alloc")]+mod bvh;diff --git a/renderer/third_party/parry3d/src/query/clip/clip_aabb_line.rs b/renderer/third_party/parry3d/src/query/clip/clip_aabb_line.rsnew file mode 100644index 0000000..e561a52--- /dev/null+++ b/renderer/third_party/parry3d/src/query/clip/clip_aabb_line.rs@@ -0,0 +1,219 @@+use crate::bounding_volume::Aabb;+use crate::math::{Real, Vector, VectorExt, DIM};+use crate::query::Ray;+use crate::shape::Segment;+use num::{Bounded, Zero};++impl Aabb {+ /// Computes the intersection of a segment with this Aabb.+ ///+ /// Returns `None` if there is no intersection or if `pa` is invalid (contains `NaN`).+ #[inline]+ pub fn clip_segment(&self, pa: Vector, pb: Vector) -> Option<Segment> {+ let ab = pb - pa;+ clip_aabb_line(self, pa, ab).map(|clip| {+ Segment::new(+ pa + (ab * (clip.0).0.max(0.0)),+ pa + (ab * (clip.1).0.min(1.0)),+ )+ })+ }++ /// Computes the parameters of the two intersection points between a line and this Aabb.+ ///+ /// The parameters are such that the point are given by `orig + dir * parameter`.+ /// Returns `None` if there is no intersection or if `orig` is invalid (contains `NaN`).+ #[inline]+ pub fn clip_line_parameters(&self, orig: Vector, dir: Vector) -> Option<(Real, Real)> {+ clip_aabb_line(self, orig, dir).map(|clip| ((clip.0).0, (clip.1).0))+ }++ /// Computes the intersection segment between a line and this Aabb.+ ///+ /// Returns `None` if there is no intersection or if `orig` is invalid (contains `NaN`).+ #[inline]+ pub fn clip_line(&self, orig: Vector, dir: Vector) -> Option<Segment> {+ clip_aabb_line(self, orig, dir)+ .map(|clip| Segment::new(orig + (dir * (clip.0).0), orig + (dir * (clip.1).0)))+ }++ /// Computes the parameters of the two intersection points between a ray and this Aabb.+ ///+ /// The parameters are such that the point are given by `ray.orig + ray.dir * parameter`.+ /// Returns `None` if there is no intersection or if `ray.orig` is invalid (contains `NaN`).+ #[inline]+ pub fn clip_ray_parameters(&self, ray: &Ray) -> Option<(Real, Real)> {+ self.clip_line_parameters(ray.origin, ray.dir)+ .and_then(|clip| {+ let t0 = clip.0;+ let t1 = clip.1;++ if t1 < 0.0 {+ None+ } else {+ Some((t0.max(0.0), t1))+ }+ })+ }++ /// Computes the intersection segment between a ray and this Aabb.+ ///+ /// Returns `None` if there is no intersection.+ #[inline]+ pub fn clip_ray(&self, ray: &Ray) -> Option<Segment> {+ self.clip_ray_parameters(ray)+ .map(|clip| Segment::new(ray.point_at(clip.0), ray.point_at(clip.1)))+ }+}++/// Computes the segment given by the intersection of a line and an Aabb.+///+/// Returns the two intersections represented as `(t, normal, side)` such that:+/// - `origin + dir * t` gives the intersection points.+/// - `normal` is the face normal at the intersection. This is equal to the zero vector if `dir`+/// is invalid (a zero vector or NaN) and `origin` is inside the AABB.+/// - `side` is the side of the AABB that was hit. This is an integer in [-3, 3] where `1` represents+/// the `+X` axis, `2` the `+Y` axis, etc., and negative values represent the corresponding+/// negative axis. The special value of `0` indicates that the provided `dir` is zero or `NaN`+/// and the line origin is inside the AABB.+pub fn clip_aabb_line(+ aabb: &Aabb,+ origin: Vector,+ dir: Vector,+) -> Option<((Real, Vector, isize), (Real, Vector, isize))> {+ let mut tmax: Real = Bounded::max_value();+ let mut tmin: Real = -tmax;+ let mut near_side = 0;+ let mut far_side = 0;+ let mut near_diag = false;+ let mut far_diag = false;++ for i in 0usize..DIM {+ if dir.vget(i).is_zero() {+ if origin.vget(i) < aabb.mins.vget(i) || origin.vget(i) > aabb.maxs.vget(i) {+ return None;+ }+ } else {+ let denom = 1.0 / dir.vget(i);+ let flip_sides;+ let mut inter_with_near_halfspace = (aabb.mins.vget(i) - origin.vget(i)) * denom;+ let mut inter_with_far_halfspace = (aabb.maxs.vget(i) - origin.vget(i)) * denom;++ if inter_with_near_halfspace > inter_with_far_halfspace {+ flip_sides = true;+ core::mem::swap(+ &mut inter_with_near_halfspace,+ &mut inter_with_far_halfspace,+ )+ } else {+ flip_sides = false;+ }++ if inter_with_near_halfspace > tmin {+ tmin = inter_with_near_halfspace;+ near_side = if flip_sides {+ -(i as isize + 1)+ } else {+ i as isize + 1+ };+ near_diag = false;+ } else if inter_with_near_halfspace == tmin {+ near_diag = true;+ }++ if inter_with_far_halfspace < tmax {+ tmax = inter_with_far_halfspace;+ far_side = if !flip_sides {+ -(i as isize + 1)+ } else {+ i as isize + 1+ };+ far_diag = false;+ } else if inter_with_far_halfspace == tmax {+ far_diag = true;+ }++ if tmax < 0.0 || tmin > tmax {+ return None;+ }+ }+ }++ let near = if near_diag {+ (tmin, -dir.normalize(), near_side)+ } else {+ // If near_side is 0, we are in a special case where `dir` is+ // zero or NaN. Return `Some` only if the ray starts inside the+ // aabb.+ if near_side == 0 {+ let zero = (0.0, Vector::ZERO, 0);+ return aabb.contains_local_point(origin).then_some((zero, zero));+ }++ let mut normal = Vector::ZERO;++ if near_side < 0 {+ normal.vset((-near_side - 1) as usize, 1.0);+ } else {+ normal.vset((near_side - 1) as usize, -1.0);+ }++ (tmin, normal, near_side)+ };++ let far = if far_diag {+ (tmax, -dir.normalize(), far_side)+ } else {+ // If far_side is 0, we are in a special case where `dir` is+ // zero or NaN. Return `Some` only if the ray starts inside the+ // aabb.+ if far_side == 0 {+ let zero = (0.0, Vector::ZERO, 0);+ return aabb.contains_local_point(origin).then_some((zero, zero));+ }++ let mut normal = Vector::ZERO;++ if far_side < 0 {+ normal.vset((-far_side - 1) as usize, -1.0);+ } else {+ normal.vset((far_side - 1) as usize, 1.0);+ }++ (tmax, normal, far_side)+ };++ Some((near, far))+}+#[cfg(test)]+mod test {+ use super::*;++ #[test]+ pub fn clip_empty_aabb_line() {+ assert!(clip_aabb_line(+ &Aabb::new(Vector::ZERO, Vector::ZERO),+ Vector::ZERO,+ Vector::ZERO,+ )+ .is_some());+ assert!(clip_aabb_line(+ &Aabb::new(Vector::splat(1.0).into(), Vector::splat(2.0).into()),+ Vector::ZERO,+ Vector::ZERO,+ )+ .is_none());+ }++ #[test]+ pub fn clip_empty_aabb_segment() {+ let aabb_origin = Aabb::new(Vector::ZERO, Vector::ZERO);+ let aabb_shifted = Aabb::new(Vector::splat(1.0), Vector::splat(2.0));+ assert!(aabb_origin+ .clip_segment(Vector::ZERO, Vector::splat(Real::NAN))+ .is_some());+ assert!(aabb_shifted+ .clip_segment(Vector::ZERO, Vector::splat(Real::NAN))+ .is_none());+ }+}diff --git a/renderer/third_party/parry3d/src/query/clip/clip_aabb_polygon.rs b/renderer/third_party/parry3d/src/query/clip/clip_aabb_polygon.rsnew file mode 100644index 0000000..271483e--- /dev/null+++ b/renderer/third_party/parry3d/src/query/clip/clip_aabb_polygon.rs@@ -0,0 +1,40 @@+use crate::bounding_volume::Aabb;+use crate::math::Vector;+use alloc::vec::Vec;++impl Aabb {+ /// Computes the intersections between this Aabb and the given polygon.+ ///+ /// The results is written into `points` directly. The input points are+ /// assumed to form a convex polygon where all points lie on the same plane.+ /// In order to avoid internal allocations, uses `self.clip_polygon_with_workspace`+ /// instead.+ #[inline]+ pub fn clip_polygon(&self, points: &mut Vec<Vector>) {+ let mut workspace = Vec::new();+ self.clip_polygon_with_workspace(points, &mut workspace)+ }++ /// Computes the intersections between this Aabb and the given polygon.+ ///+ /// The results is written into `points` directly. The input points are+ /// assumed to form a convex polygon where all points lie on the same plane.+ #[inline]+ pub fn clip_polygon_with_workspace(+ &self,+ points: &mut Vec<Vector>,+ workspace: &mut Vec<Vector>,+ ) {+ super::clip_halfspace_polygon(self.mins, -Vector::X, points, workspace);+ super::clip_halfspace_polygon(self.maxs, Vector::X, workspace, points);++ super::clip_halfspace_polygon(self.mins, -Vector::Y, points, workspace);+ super::clip_halfspace_polygon(self.maxs, Vector::Y, workspace, points);++ #[cfg(feature = "dim3")]+ {+ super::clip_halfspace_polygon(self.mins, -Vector::Z, points, workspace);+ super::clip_halfspace_polygon(self.maxs, Vector::Z, workspace, points);+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/clip/clip_halfspace_polygon.rs b/renderer/third_party/parry3d/src/query/clip/clip_halfspace_polygon.rsnew file mode 100644index 0000000..6f823bd--- /dev/null+++ b/renderer/third_party/parry3d/src/query/clip/clip_halfspace_polygon.rs@@ -0,0 +1,57 @@+use crate::math::Vector;+use crate::query::{self, Ray};+use alloc::vec::Vec;++/// Cuts a polygon with the given half-space.+///+/// Given the half-space `center` and outward `normal`,+/// this computes the intersecting between the half-space and+/// the polygon. (Note that a point `pt` is considered as inside of+/// the half-space if `normal.dot((pt - center)) <= 0.0`.+pub fn clip_halfspace_polygon(+ center: Vector,+ normal: Vector,+ polygon: &[Vector],+ result: &mut Vec<Vector>,+) {+ result.clear();++ if polygon.is_empty() {+ return;+ }++ let keep_point = |pt: Vector| (pt - center).dot(normal) <= 0.0;+ let last_pt = polygon.last().unwrap();+ let mut last_keep = keep_point(*last_pt);++ if last_keep {+ result.push(*last_pt);+ }++ for i in 0..polygon.len() {+ let pt = polygon[i];+ let keep = keep_point(pt);++ if keep != last_keep {+ // We crossed the plane, so we need+ // to cut the edge.+ let prev_i = if i == 0 { polygon.len() - 1 } else { i - 1 };+ let prev_pt = polygon[prev_i];+ let ray = Ray::new(prev_pt, pt - prev_pt);++ if let Some(time_of_impact) =+ query::details::ray_toi_with_halfspace(center, normal, &ray)+ {+ if time_of_impact > 0.0 && time_of_impact < 1.0 {+ result.push(ray.origin + ray.dir * time_of_impact)+ }+ }++ last_keep = keep;+ }++ if keep && i != polygon.len() - 1 {+ result.push(pt);+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/clip/clip_segment_segment.rs b/renderer/third_party/parry3d/src/query/clip/clip_segment_segment.rsnew file mode 100644index 0000000..5e9b02d--- /dev/null+++ b/renderer/third_party/parry3d/src/query/clip/clip_segment_segment.rs@@ -0,0 +1,141 @@+use crate::math::Vector;+#[cfg(feature = "dim2")]+use crate::utils;++// Features in clipping points are:+// 0 = First vertex.+// 1 = On the face.+// 2 = Second vertex.+pub type ClippingPoints = (Vector, Vector, usize, usize);++/// Projects two segments on one another towards the direction `normal`,+/// and compute their intersection.+#[cfg(feature = "dim2")]+pub fn clip_segment_segment_with_normal(+ mut seg1: (Vector, Vector),+ mut seg2: (Vector, Vector),+ normal: Vector,+) -> Option<(ClippingPoints, ClippingPoints)> {+ use crate::utils::WBasis;+ let tangent = normal.orthonormal_basis()[0];++ let mut range1 = [seg1.0.dot(tangent), seg1.1.dot(tangent)];+ let mut range2 = [seg2.0.dot(tangent), seg2.1.dot(tangent)];+ let mut features1 = [0, 2];+ let mut features2 = [0, 2];++ if range1[1] < range1[0] {+ range1.swap(0, 1);+ features1.swap(0, 1);+ core::mem::swap(&mut seg1.0, &mut seg1.1);+ }++ if range2[1] < range2[0] {+ range2.swap(0, 1);+ features2.swap(0, 1);+ core::mem::swap(&mut seg2.0, &mut seg2.1);+ }++ if range2[0] > range1[1] || range1[0] > range2[1] {+ // No clip point.+ return None;+ }++ let ca = if range2[0] > range1[0] {+ let bcoord = (range2[0] - range1[0]) * utils::inv(range1[1] - range1[0]);+ let p1 = seg1.0 + (seg1.1 - seg1.0) * bcoord;+ let p2 = seg2.0;++ (p1, p2, 1, features2[0])+ } else {+ let bcoord = (range1[0] - range2[0]) * utils::inv(range2[1] - range2[0]);+ let p1 = seg1.0;+ let p2 = seg2.0 + (seg2.1 - seg2.0) * bcoord;++ (p1, p2, features1[0], 1)+ };++ let cb = if range2[1] < range1[1] {+ let bcoord = (range2[1] - range1[0]) * utils::inv(range1[1] - range1[0]);+ let p1 = seg1.0 + (seg1.1 - seg1.0) * bcoord;+ let p2 = seg2.1;++ (p1, p2, 1, features2[1])+ } else {+ let bcoord = (range1[1] - range2[0]) * utils::inv(range2[1] - range2[0]);+ let p1 = seg1.1;+ let p2 = seg2.0 + (seg2.1 - seg2.0) * bcoord;++ (p1, p2, features1[1], 1)+ };++ Some((ca, cb))+}++/// Projects two segments on one another and compute their intersection.+pub fn clip_segment_segment(+ mut seg1: (Vector, Vector),+ mut seg2: (Vector, Vector),+) -> Option<(ClippingPoints, ClippingPoints)> {+ // NOTE: no need to normalize the tangent.+ let tangent1 = seg1.1 - seg1.0;+ let sqnorm_tangent1 = tangent1.length_squared();++ let mut range1 = [0.0, sqnorm_tangent1];+ let mut range2 = [+ (seg2.0 - seg1.0).dot(tangent1),+ (seg2.1 - seg1.0).dot(tangent1),+ ];+ let mut features1 = [0, 2];+ let mut features2 = [0, 2];++ if range1[1] < range1[0] {+ range1.swap(0, 1);+ features1.swap(0, 1);+ core::mem::swap(&mut seg1.0, &mut seg1.1);+ }++ if range2[1] < range2[0] {+ range2.swap(0, 1);+ features2.swap(0, 1);+ core::mem::swap(&mut seg2.0, &mut seg2.1);+ }++ if range2[0] > range1[1] || range1[0] > range2[1] {+ // No clip point.+ return None;+ }++ let length1 = range1[1] - range1[0];+ let length2 = range2[1] - range2[0];++ let ca = if range2[0] > range1[0] {+ let bcoord = (range2[0] - range1[0]) / length1;+ let p1 = seg1.0 + tangent1 * bcoord;+ let p2 = seg2.0;++ (p1, p2, 1, features2[0])+ } else {+ let bcoord = (range1[0] - range2[0]) / length2;+ let p1 = seg1.0;+ let p2 = seg2.0 + (seg2.1 - seg2.0) * bcoord;++ (p1, p2, features1[0], 1)+ };++ let cb = if range2[1] < range1[1] {+ let bcoord = (range2[1] - range1[0]) / length1;+ let p1 = seg1.0 + tangent1 * bcoord;+ let p2 = seg2.1;++ (p1, p2, 1, features2[1])+ } else {+ let bcoord = (range1[1] - range2[0]) / length2;+ let p1 = seg1.1;+ let p2 = seg2.0 + (seg2.1 - seg2.0) * bcoord;++ (p1, p2, features1[1], 1)+ };++ Some((ca, cb))+}diff --git a/renderer/third_party/parry3d/src/query/clip/mod.rs b/renderer/third_party/parry3d/src/query/clip/mod.rsnew file mode 100644index 0000000..bb3aef0--- /dev/null+++ b/renderer/third_party/parry3d/src/query/clip/mod.rs@@ -0,0 +1,13 @@+pub use self::clip_aabb_line::clip_aabb_line;+#[cfg(feature = "alloc")]+pub use self::clip_halfspace_polygon::clip_halfspace_polygon;+pub use self::clip_segment_segment::clip_segment_segment;+#[cfg(feature = "dim2")]+pub use self::clip_segment_segment::clip_segment_segment_with_normal;++mod clip_aabb_line;+#[cfg(feature = "alloc")]+mod clip_aabb_polygon;+#[cfg(feature = "alloc")]+mod clip_halfspace_polygon;+mod clip_segment_segment;diff --git a/renderer/third_party/parry3d/src/query/closest_points/closest_points.rs b/renderer/third_party/parry3d/src/query/closest_points/closest_points.rsnew file mode 100644index 0000000..92d6042--- /dev/null+++ b/renderer/third_party/parry3d/src/query/closest_points/closest_points.rs@@ -0,0 +1,300 @@+use crate::math::{Pose, Vector};++use core::mem;++/// Result of a closest points query between two shapes.+///+/// This enum represents the outcome of computing closest points between two shapes,+/// taking into account a user-defined maximum search distance. It's useful for+/// proximity-based gameplay mechanics, AI perception systems, and efficient spatial+/// queries where you only care about nearby objects.+///+/// # Variants+///+/// The result depends on the relationship between the shapes and the `max_dist` parameter:+///+/// - **`Intersecting`**: Shapes are overlapping (penetrating or touching)+/// - **`WithinMargin`**: Shapes are separated but within the search distance+/// - **`Disjoint`**: Shapes are too far apart (beyond the search distance)+///+/// # Use Cases+///+/// - **AI perception**: Find nearest enemy within detection range+/// - **Trigger zones**: Detect objects approaching a threshold distance+/// - **LOD systems**: Compute detailed interactions only for nearby objects+/// - **Physics optimization**: Skip expensive computations for distant pairs+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{closest_points, ClosestPoints};+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+///+/// let pos1 = Pose::translation(0.0, 0.0, 0.0);+/// let pos2 = Pose::translation(5.0, 0.0, 0.0);+///+/// // Search for closest points within 10.0 units+/// let result = closest_points(&pos1, &ball1, &pos2, &ball2, 10.0).unwrap();+///+/// match result {+/// ClosestPoints::Intersecting => {+/// println!("Shapes are overlapping!");+/// }+/// ClosestPoints::WithinMargin(pt1, pt2) => {+/// println!("Closest point on shape1: {:?}", pt1);+/// println!("Closest point on shape2: {:?}", pt2);+/// let distance = (pt2 - pt1).length();+/// println!("Distance between shapes: {}", distance);+/// }+/// ClosestPoints::Disjoint => {+/// println!("Shapes are more than 10.0 units apart");+/// }+/// }+/// # }+/// ```+///+/// # See Also+///+/// - [`closest_points`](crate::query::closest_points::closest_points()) - Main function to compute this result+/// - [`distance`](crate::query::distance::distance()) - For just the distance value+/// - [`contact`](crate::query::contact::contact()) - For detailed contact information when intersecting+#[derive(Debug, PartialEq, Clone, Copy)]+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+pub enum ClosestPoints {+ /// The two shapes are intersecting (overlapping or touching).+ ///+ /// When shapes intersect, their closest points are not well-defined, as there+ /// are infinitely many contact points. Use [`contact`](crate::query::contact::contact())+ /// instead to get penetration depth and contact normals.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::{closest_points, ClosestPoints};+ /// use parry3d::shape::Ball;+ /// use parry3d::math::Pose;+ ///+ /// let ball1 = Ball::new(2.0);+ /// let ball2 = Ball::new(2.0);+ ///+ /// // Overlapping balls (centers 3.0 apart, combined radii 4.0)+ /// let pos1 = Pose::translation(0.0, 0.0, 0.0);+ /// let pos2 = Pose::translation(3.0, 0.0, 0.0);+ ///+ /// let result = closest_points(&pos1, &ball1, &pos2, &ball2, 10.0).unwrap();+ /// assert_eq!(result, ClosestPoints::Intersecting);+ /// # }+ /// ```+ Intersecting,++ /// The shapes are separated but within the specified maximum distance.+ ///+ /// Contains the two closest points in world-space coordinates:+ /// - First point: Closest point on the surface of the first shape+ /// - Second point: Closest point on the surface of the second shape+ ///+ /// The distance between the shapes equals the distance between these two points.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::{closest_points, ClosestPoints};+ /// use parry3d::shape::Ball;+ /// use parry3d::math::Pose;+ ///+ /// let ball1 = Ball::new(1.0);+ /// let ball2 = Ball::new(1.0);+ ///+ /// // Balls separated by 3.0 units (centers 5.0 apart, combined radii 2.0)+ /// let pos1 = Pose::translation(0.0, 0.0, 0.0);+ /// let pos2 = Pose::translation(5.0, 0.0, 0.0);+ ///+ /// let result = closest_points(&pos1, &ball1, &pos2, &ball2, 10.0).unwrap();+ ///+ /// if let ClosestPoints::WithinMargin(pt1, pt2) = result {+ /// // Vectors are on the surface, facing each other+ /// assert!((pt1.x - 1.0).abs() < 1e-5); // ball1 surface at x=1.0+ /// assert!((pt2.x - 4.0).abs() < 1e-5); // ball2 surface at x=4.0+ ///+ /// // Distance between points+ /// let dist = (pt2 - pt1).length();+ /// assert!((dist - 3.0).abs() < 1e-5);+ /// } else {+ /// panic!("Expected WithinMargin");+ /// }+ /// # }+ /// ```+ WithinMargin(Vector, Vector),++ /// The shapes are separated by more than the specified maximum distance.+ ///+ /// The actual distance between shapes is unknown (could be much larger than `max_dist`),+ /// and no closest points are computed. This saves computation when you only care+ /// about nearby objects.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::{closest_points, ClosestPoints};+ /// use parry3d::shape::Ball;+ /// use parry3d::math::Pose;+ ///+ /// let ball1 = Ball::new(1.0);+ /// let ball2 = Ball::new(1.0);+ ///+ /// // Balls separated by 8.0 units+ /// let pos1 = Pose::translation(0.0, 0.0, 0.0);+ /// let pos2 = Pose::translation(10.0, 0.0, 0.0);+ ///+ /// // Only search within 5.0 units+ /// let result = closest_points(&pos1, &ball1, &pos2, &ball2, 5.0).unwrap();+ /// assert_eq!(result, ClosestPoints::Disjoint);+ ///+ /// // With larger search distance, we get the points+ /// let result2 = closest_points(&pos1, &ball1, &pos2, &ball2, 10.0).unwrap();+ /// assert!(matches!(result2, ClosestPoints::WithinMargin(_, _)));+ /// # }+ /// ```+ Disjoint,+}++impl ClosestPoints {+ /// Swaps the two closest points in-place.+ ///+ /// This is useful when you need to reverse the perspective of the query result.+ /// If the result is `WithinMargin`, the two points are swapped. For `Intersecting`+ /// and `Disjoint`, this operation has no effect.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::{closest_points, ClosestPoints};+ /// use parry3d::shape::Ball;+ /// use parry3d::math::Pose;+ ///+ /// let ball1 = Ball::new(1.0);+ /// let ball2 = Ball::new(2.0);+ ///+ /// let pos1 = Pose::translation(0.0, 0.0, 0.0);+ /// let pos2 = Pose::translation(5.0, 0.0, 0.0);+ ///+ /// let mut result = closest_points(&pos1, &ball1, &pos2, &ball2, 10.0).unwrap();+ ///+ /// if let ClosestPoints::WithinMargin(pt1_before, pt2_before) = result {+ /// result.flip();+ /// if let ClosestPoints::WithinMargin(pt1_after, pt2_after) = result {+ /// assert_eq!(pt1_before, pt2_after);+ /// assert_eq!(pt2_before, pt1_after);+ /// }+ /// }+ /// # }+ /// ```+ pub fn flip(&mut self) {+ if let ClosestPoints::WithinMargin(ref mut p1, ref mut p2) = *self {+ mem::swap(p1, p2)+ }+ }++ /// Returns a copy with the two closest points swapped.+ ///+ /// This is the non-mutating version of [`flip`](Self::flip). It returns a new+ /// `ClosestPoints` with swapped points if the result is `WithinMargin`, or returns+ /// `self` unchanged for `Intersecting` and `Disjoint`.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::{closest_points, ClosestPoints};+ /// use parry3d::shape::Ball;+ /// use parry3d::math::Pose;+ ///+ /// let ball1 = Ball::new(1.0);+ /// let ball2 = Ball::new(2.0);+ ///+ /// let pos1 = Pose::translation(0.0, 0.0, 0.0);+ /// let pos2 = Pose::translation(5.0, 0.0, 0.0);+ ///+ /// let result = closest_points(&pos1, &ball1, &pos2, &ball2, 10.0).unwrap();+ /// let flipped = result.flipped();+ ///+ /// // Original is unchanged+ /// if let ClosestPoints::WithinMargin(pt1_orig, pt2_orig) = result {+ /// if let ClosestPoints::WithinMargin(pt1_flip, pt2_flip) = flipped {+ /// assert_eq!(pt1_orig, pt2_flip);+ /// assert_eq!(pt2_orig, pt1_flip);+ /// }+ /// }+ /// # }+ /// ```+ #[must_use]+ pub fn flipped(&self) -> Self {+ if let ClosestPoints::WithinMargin(p1, p2) = *self {+ ClosestPoints::WithinMargin(p2, p1)+ } else {+ *self+ }+ }++ /// Transforms the closest points from local space to world space.+ ///+ /// Applies the isometry transformations to convert closest points from their+ /// respective local coordinate frames to world-space coordinates. This is used+ /// internally by the query system.+ ///+ /// - Vector 1 is transformed by `pos1`+ /// - Vector 2 is transformed by `pos2`+ /// - `Intersecting` and `Disjoint` variants are returned unchanged+ ///+ /// # Arguments+ ///+ /// * `pos1` - Transformation for the first shape+ /// * `pos2` - Transformation for the second shape+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::ClosestPoints;+ /// use parry3d::math::{Pose, Vector};+ ///+ /// // Vectors in local space+ /// let local_result = ClosestPoints::WithinMargin(+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(-1.0, 0.0, 0.0),+ /// );+ ///+ /// // Transform to world space+ /// let pos1 = Pose::translation(10.0, 0.0, 0.0);+ /// let pos2 = Pose::translation(20.0, 0.0, 0.0);+ ///+ /// let world_result = local_result.transform_by(&pos1, &pos2);+ ///+ /// if let ClosestPoints::WithinMargin(pt1, pt2) = world_result {+ /// assert!((pt1.x - 11.0).abs() < 1e-5); // 10.0 + 1.0+ /// assert!((pt2.x - 19.0).abs() < 1e-5); // 20.0 + (-1.0)+ /// }+ /// # }+ /// ```+ #[must_use]+ pub fn transform_by(self, pos1: &Pose, pos2: &Pose) -> Self {+ if let ClosestPoints::WithinMargin(p1, p2) = self {+ ClosestPoints::WithinMargin(pos1 * p1, pos2 * p2)+ } else {+ self+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/closest_points/closest_points_ball_ball.rs b/renderer/third_party/parry3d/src/query/closest_points/closest_points_ball_ball.rsnew file mode 100644index 0000000..122d88a--- /dev/null+++ b/renderer/third_party/parry3d/src/query/closest_points/closest_points_ball_ball.rs@@ -0,0 +1,33 @@+use crate::math::{Pose, Real};+use crate::query::ClosestPoints;+use crate::shape::Ball;++/// Closest points between balls.+///+/// Each returned point is expressed on the local-space of the corresponding shape.+#[inline]+pub fn closest_points_ball_ball(pos12: &Pose, b1: &Ball, b2: &Ball, margin: Real) -> ClosestPoints {+ assert!(+ margin >= 0.0,+ "The proximity margin must be positive or null."+ );++ let r1 = b1.radius;+ let r2 = b2.radius;+ let delta_pos = pos12.translation;+ let distance = delta_pos.length();+ let sum_radius = r1 + r2;++ if distance - margin <= sum_radius {+ if distance <= sum_radius {+ ClosestPoints::Intersecting+ } else {+ let normal = delta_pos.normalize();+ let p1 = normal * r1;+ let p2 = pos12.rotation.inverse() * normal * -r2;+ ClosestPoints::WithinMargin(p1, p2)+ }+ } else {+ ClosestPoints::Disjoint+ }+}diff --git a/renderer/third_party/parry3d/src/query/closest_points/closest_points_ball_convex_polyhedron.rs b/renderer/third_party/parry3d/src/query/closest_points/closest_points_ball_convex_polyhedron.rsnew file mode 100644index 0000000..9f9d21f--- /dev/null+++ b/renderer/third_party/parry3d/src/query/closest_points/closest_points_ball_convex_polyhedron.rs@@ -0,0 +1,49 @@+use crate::math::{Pose, Real};+use crate::query::ClosestPoints;+use crate::shape::{Ball, Shape};++/// ClosestPoints between a ball and a convex polyhedron.+///+/// This function panics if the input shape does not implement+/// both the ConvexPolyhedron and PointQuery traits.+#[inline]+pub fn closest_points_ball_convex_polyhedron(+ pos12: &Pose,+ ball1: &Ball,+ shape2: &(impl Shape + ?Sized),+ prediction: Real,+) -> ClosestPoints {+ match crate::query::details::contact_ball_convex_polyhedron(pos12, ball1, shape2, prediction) {+ Some(contact) => {+ if contact.dist <= 0.0 {+ ClosestPoints::Intersecting+ } else {+ ClosestPoints::WithinMargin(contact.point1, contact.point2)+ }+ }+ None => ClosestPoints::Disjoint,+ }+}++/// ClosestPoints between a convex polyhedron and a ball.+///+/// This function panics if the input shape does not implement+/// both the ConvexPolyhedron and PointQuery traits.+#[inline]+pub fn closest_points_convex_polyhedron_ball(+ pos12: &Pose,+ shape1: &(impl Shape + ?Sized),+ ball2: &Ball,+ prediction: Real,+) -> ClosestPoints {+ match crate::query::details::contact_convex_polyhedron_ball(pos12, shape1, ball2, prediction) {+ Some(contact) => {+ if contact.dist <= 0.0 {+ ClosestPoints::Intersecting+ } else {+ ClosestPoints::WithinMargin(contact.point1, contact.point2)+ }+ }+ None => ClosestPoints::Disjoint,+ }+}diff --git a/renderer/third_party/parry3d/src/query/closest_points/closest_points_composite_shape_shape.rs b/renderer/third_party/parry3d/src/query/closest_points/closest_points_composite_shape_shape.rsnew file mode 100644index 0000000..ad909d6--- /dev/null+++ b/renderer/third_party/parry3d/src/query/closest_points/closest_points_composite_shape_shape.rs@@ -0,0 +1,103 @@+use crate::bounding_volume::Aabb;+use crate::math::{Pose, Real};+use crate::partitioning::BvhNode;+use crate::query::{ClosestPoints, QueryDispatcher};+use crate::shape::{CompositeShapeRef, Shape, SubShapeId, TypedCompositeShape};+use crate::utils::PoseOpt;++impl<S: ?Sized + TypedCompositeShape> CompositeShapeRef<'_, S> {+ /// Returns the closest points between `self` and the given `shape2` positioned at+ /// `pose12` relative to `self`.+ ///+ /// Returns the index of the sub-shape of `self` involved in the contact as well as the closest+ /// points information.+ ///+ /// Returns `ClosestPoints::Disjoint` if `self` and `shape2` are separated by a distance larger+ /// than `margin`.+ ///+ /// Returns `None` if no closest point could be calculated (e.g. if the `dispatcher` doesn’t+ /// support the involved shapes at all, or if `self` is empty).+ pub fn closest_points_to_shape<D: ?Sized + QueryDispatcher>(+ &self,+ dispatcher: &D,+ pose12: &Pose,+ shape2: &dyn Shape,+ margin: Real,+ ) -> Option<(SubShapeId, ClosestPoints)> {+ let ls_aabb2 = shape2.compute_aabb(pose12);+ let msum_shift = -ls_aabb2.center();+ let msum_margin = ls_aabb2.half_extents();++ self.0+ .bvh()+ .find_best(+ margin,+ |node: &BvhNode, _| {+ // Compute the minkowski sum of the two Aabbs.+ let msum = Aabb {+ mins: node.mins() + msum_shift - msum_margin,+ maxs: node.maxs() + msum_shift + msum_margin,+ };+ msum.distance_to_origin()+ },+ |part_id, _| {+ self.0+ .map_untyped_part_at(part_id, |part_pos1, part_g1, _| {+ if let Ok(mut pts) = dispatcher.closest_points(+ &part_pos1.inv_mul(pose12),+ part_g1,+ shape2,+ margin,+ ) {+ let cost = match &mut pts {+ ClosestPoints::WithinMargin(p1, p2) => {+ *p1 = part_pos1.transform_point(*p1);+ let p2_1 = pose12 * *p2;+ (*p1 - p2_1).length()+ }+ ClosestPoints::Intersecting => -Real::MAX,+ ClosestPoints::Disjoint => Real::MAX,+ };+ (cost, pts)+ } else {+ (Real::MAX, ClosestPoints::Disjoint)+ }+ })+ },+ )+ .map(|(part_id, (_, pts))| (part_id, pts))+ }+}++/// Closest points between a composite shape and any other shape.+pub fn closest_points_composite_shape_shape<D, G1>(+ dispatcher: &D,+ pos12: &Pose,+ g1: &G1,+ g2: &dyn Shape,+ margin: Real,+) -> ClosestPoints+where+ D: ?Sized + QueryDispatcher,+ G1: ?Sized + TypedCompositeShape,+{+ CompositeShapeRef(g1)+ .closest_points_to_shape(dispatcher, pos12, g2, margin)+ .map(|cp| cp.1)+ .unwrap_or(ClosestPoints::Disjoint)+}++/// Closest points between a shape and a composite shape.+pub fn closest_points_shape_composite_shape<D, G2>(+ dispatcher: &D,+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &G2,+ margin: Real,+) -> ClosestPoints+where+ D: ?Sized + QueryDispatcher,+ G2: ?Sized + TypedCompositeShape,+{+ closest_points_composite_shape_shape(dispatcher, &pos12.inverse(), g2, g1, margin).flipped()+}diff --git a/renderer/third_party/parry3d/src/query/closest_points/closest_points_cuboid_cuboid.rs b/renderer/third_party/parry3d/src/query/closest_points/closest_points_cuboid_cuboid.rsnew file mode 100644index 0000000..b578301--- /dev/null+++ b/renderer/third_party/parry3d/src/query/closest_points/closest_points_cuboid_cuboid.rs@@ -0,0 +1,97 @@+use crate::math::{Pose, Real};+use crate::query::{sat, ClosestPoints, PointQuery};+use crate::shape::{Cuboid, SupportMap};++/// Closest points between two cuboids.+#[inline]+pub fn closest_points_cuboid_cuboid(+ pos12: &Pose,+ cuboid1: &Cuboid,+ cuboid2: &Cuboid,+ margin: Real,+) -> ClosestPoints {+ let pos21 = pos12.inverse();++ let sep1 = sat::cuboid_cuboid_find_local_separating_normal_oneway(cuboid1, cuboid2, pos12);+ if sep1.0 > margin {+ return ClosestPoints::Disjoint;+ }++ let sep2 = sat::cuboid_cuboid_find_local_separating_normal_oneway(cuboid2, cuboid1, &pos21);+ if sep2.0 > margin {+ return ClosestPoints::Disjoint;+ }++ #[cfg(feature = "dim2")]+ let sep3 = (-Real::MAX, crate::math::Vector::Y); // This case does not exist in 2D.+ #[cfg(feature = "dim3")]+ let sep3 = sat::cuboid_cuboid_find_local_separating_edge_twoway(cuboid1, cuboid2, pos12);+ if sep3.0 > margin {+ return ClosestPoints::Disjoint;+ }++ if sep1.0 <= 0.0 && sep2.0 <= 0.0 && sep3.0 <= 0.0 {+ return ClosestPoints::Intersecting;+ }++ // The best separating axis is face-vertex.+ if sep1.0 >= sep2.0 && sep1.0 >= sep3.0 {+ // println!("AA: {:?}", sep1);++ let pt2_1 = cuboid2.support_point(pos12, -sep1.1);+ // Use double-projection to converge to the closest points even in ambiguous cases+ // where both cuboids have some parallel features.+ let proj1 = cuboid1.project_local_point(pt2_1, true);+ let proj2 = cuboid2.project_local_point(pos21 * proj1.point, true);+ let pt2_1 = pos12 * proj2.point;+ if (proj1.point - pt2_1).length_squared() > margin * margin {+ return ClosestPoints::Disjoint;+ } else {+ return ClosestPoints::WithinMargin(proj1.point, proj2.point);+ }+ }++ // The best separating axis is vertex-face.+ if sep2.0 >= sep1.0 && sep2.0 >= sep3.0 {+ // println!("BB: {:?}", sep2);++ // Use double-projection to converge to the closest points even in ambiguous cases+ // where both cuboids have some parallel features.+ let pt1_2 = cuboid1.support_point(&pos21, -sep2.1);+ let proj2 = cuboid2.project_local_point(pt1_2, true);+ let proj1 = cuboid1.project_local_point(pos12 * proj2.point, true);+ let pt1_2 = pos21 * proj1.point;++ if (proj2.point - pt1_2).length_squared() > margin * margin {+ return ClosestPoints::Disjoint;+ } else {+ return ClosestPoints::WithinMargin(proj1.point, proj2.point);+ }+ }++ // The best separating axis is edge-edge.+ #[cfg(feature = "dim3")]+ if sep3.0 >= sep2.0 && sep3.0 >= sep1.0 {+ // println!("AA: {:?}, BB: {:?}, CC: {:?}", sep1, sep2, sep3);++ // To compute the actual distance, we need to compute the closest+ // points between the two edges that generated the separating axis.+ let edge1 = cuboid1.local_support_edge_segment(sep3.1);+ let edge2 = cuboid2.local_support_edge_segment(pos21.rotation * -sep3.1);+ let (_, loc2) = super::closest_points_segment_segment_with_locations(pos12, &edge1, &edge2);++ // Use double-projection to converge to the closest points even in ambiguous cases+ // where both cuboids have some parallel features.+ let pt2_1 = pos12 * edge2.point_at(&loc2);+ let proj1 = cuboid1.project_local_point(pt2_1, true);+ let proj2 = cuboid2.project_local_point(pos21 * proj1.point, true);+ let pt2_1 = pos12 * proj2.point;+ if (proj1.point - pt2_1).length_squared() > margin * margin {+ return ClosestPoints::Disjoint;+ } else {+ return ClosestPoints::WithinMargin(proj1.point, proj2.point);+ }+ }++ unreachable!()+}diff --git a/renderer/third_party/parry3d/src/query/closest_points/closest_points_cuboid_triangle.rs b/renderer/third_party/parry3d/src/query/closest_points/closest_points_cuboid_triangle.rsnew file mode 100644index 0000000..95ef7c8--- /dev/null+++ b/renderer/third_party/parry3d/src/query/closest_points/closest_points_cuboid_triangle.rs@@ -0,0 +1,89 @@+use crate::math::{Pose, Real};+use crate::query::{sat, ClosestPoints, PointQuery};+use crate::shape::{Cuboid, SupportMap, Triangle};++/// Closest points between a cuboid and a triangle.+#[inline]+pub fn closest_points_cuboid_triangle(+ pos12: &Pose,+ cuboid1: &Cuboid,+ triangle2: &Triangle,+ margin: Real,+) -> ClosestPoints {+ let pos21 = pos12.inverse();++ let sep1 =+ sat::cuboid_support_map_find_local_separating_normal_oneway(cuboid1, triangle2, pos12);+ if sep1.0 > margin {+ return ClosestPoints::Disjoint;+ }++ let sep2 = sat::triangle_cuboid_find_local_separating_normal_oneway(triangle2, cuboid1, &pos21);+ if sep2.0 > margin {+ return ClosestPoints::Disjoint;+ }++ #[cfg(feature = "dim2")]+ let sep3 = (-Real::MAX, crate::math::Vector::Y); // This case does not exist in 2D.+ #[cfg(feature = "dim3")]+ let sep3 = sat::cuboid_triangle_find_local_separating_edge_twoway(cuboid1, triangle2, pos12);+ if sep3.0 > margin {+ return ClosestPoints::Disjoint;+ }++ if sep1.0 <= 0.0 && sep2.0 <= 0.0 && sep3.0 <= 0.0 {+ return ClosestPoints::Intersecting;+ }++ // The best separating axis is face-vertex.+ if sep1.0 >= sep2.0 && sep1.0 >= sep3.0 {+ // To compute the closest points, we need to project the support point+ // from triangle2 on the support-face of triangle1. For simplicity, we just+ // project the support point from triangle2 on cuboid1 itself (not just the face).+ let pt2_1 = triangle2.support_point(pos12, -sep1.1);+ let proj1 = cuboid1.project_local_point(pt2_1, true);+ if (proj1.point - pt2_1).length_squared() > margin * margin {+ return ClosestPoints::Disjoint;+ } else {+ return ClosestPoints::WithinMargin(proj1.point, pos21 * pt2_1);+ }+ }++ // The best separating axis is vertex-face.+ if sep2.0 >= sep1.0 && sep2.0 >= sep3.0 {+ // To compute the actual closest points, we need to project the support point+ // from cuboid1 on the support-face of triangle2. For simplicity, we just+ // project the support point from cuboid1 on triangle2 itself (not just the face).+ let pt1_2 = cuboid1.support_point(&pos21, -sep2.1);+ let proj2 = triangle2.project_local_point(pt1_2, true);++ if (proj2.point - pt1_2).length_squared() > margin * margin {+ return ClosestPoints::Disjoint;+ } else {+ return ClosestPoints::WithinMargin(pos12 * pt1_2, proj2.point);+ }+ }++ // The best separating axis is edge-edge.+ #[cfg(feature = "dim3")]+ if sep3.0 >= sep2.0 && sep3.0 >= sep1.0 {+ // To compute the actual distance, we need to compute the closest+ // points between the two edges that generated the separating axis.+ let edge1 = cuboid1.local_support_edge_segment(sep3.1);+ let edge2 = triangle2.local_support_edge_segment(pos21.rotation * -sep3.1);+ return super::closest_points_segment_segment(pos12, &edge1, &edge2, margin);+ }++ unreachable!()+}++/// Closest points between a triangle and a cuboid.+#[inline]+pub fn closest_points_triangle_cuboid(+ pos12: &Pose,+ triangle1: &Triangle,+ cuboid2: &Cuboid,+ margin: Real,+) -> ClosestPoints {+ closest_points_cuboid_triangle(&pos12.inverse(), cuboid2, triangle1, margin).flipped()+}diff --git a/renderer/third_party/parry3d/src/query/closest_points/closest_points_halfspace_support_map.rs b/renderer/third_party/parry3d/src/query/closest_points/closest_points_halfspace_support_map.rsnew file mode 100644index 0000000..563a20e--- /dev/null+++ b/renderer/third_party/parry3d/src/query/closest_points/closest_points_halfspace_support_map.rs@@ -0,0 +1,42 @@+use crate::math::{Pose, Real};+use crate::query::ClosestPoints;+use crate::shape::HalfSpace;+use crate::shape::SupportMap;++/// Closest points between a halfspace and a support-mapped shape (Cuboid, ConvexHull, etc.)+pub fn closest_points_halfspace_support_map<G: ?Sized + SupportMap>(+ pos12: &Pose,+ halfspace: &HalfSpace,+ other: &G,+ margin: Real,+) -> ClosestPoints {+ assert!(+ margin >= 0.0,+ "The proximity margin must be positive or null."+ );++ let deepest = other.support_point(pos12, -halfspace.normal);+ let distance = halfspace.normal.dot(-deepest);++ if distance >= -margin {+ if distance >= 0.0 {+ ClosestPoints::Intersecting+ } else {+ let p1 = deepest + halfspace.normal * distance;+ let p2 = pos12.inverse_transform_point(deepest);+ ClosestPoints::WithinMargin(p1, p2)+ }+ } else {+ ClosestPoints::Disjoint+ }+}++/// Closest points between a support-mapped shape (Cuboid, ConvexHull, etc.) and a halfspace.+pub fn closest_points_support_map_halfspace<G: ?Sized + SupportMap>(+ pos12: &Pose,+ other: &G,+ halfspace: &HalfSpace,+ margin: Real,+) -> ClosestPoints {+ closest_points_halfspace_support_map(&pos12.inverse(), halfspace, other, margin).flipped()+}diff --git a/renderer/third_party/parry3d/src/query/closest_points/closest_points_line_line.rs b/renderer/third_party/parry3d/src/query/closest_points/closest_points_line_line.rsnew file mode 100644index 0000000..5b3e48d--- /dev/null+++ b/renderer/third_party/parry3d/src/query/closest_points/closest_points_line_line.rs@@ -0,0 +1,84 @@+use crate::math::{Real, Vector};++/// Closest points between two lines.+///+/// The result, say `res`, is such that the closest points between both lines are+/// `orig1 + dir1 * res.0` and `orig2 + dir2 * res.1`.+#[inline]+pub fn closest_points_line_line_parameters(+ orig1: Vector,+ dir1: Vector,+ orig2: Vector,+ dir2: Vector,+) -> (Real, Real) {+ let res = closest_points_line_line_parameters_eps(+ orig1,+ dir1,+ orig2,+ dir2,+ crate::math::DEFAULT_EPSILON,+ );+ (res.0, res.1)+}++/// Closest points between two lines with a custom tolerance epsilon.+///+/// The result, say `res`, is such that the closest points between both lines are+/// `orig1 + dir1 * res.0` and `orig2 + dir2 * res.1`. If the lines are parallel+/// then `res.2` is set to `true` and the returned closest points are `orig1` and+/// its projection on the second line.+#[inline]+pub fn closest_points_line_line_parameters_eps(+ orig1: Vector,+ dir1: Vector,+ orig2: Vector,+ dir2: Vector,+ eps: Real,+) -> (Real, Real, bool) {+ // Inspired by RealField-time collision detection by Christer Ericson.+ let r = orig1 - orig2;++ let a = dir1.length_squared();+ let e = dir2.length_squared();+ let f = dir2.dot(r);++ if a <= eps && e <= eps {+ (0.0, 0.0, false)+ } else if a <= eps {+ (0.0, f / e, false)+ } else {+ let c = dir1.dot(r);+ if e <= eps {+ (-c / a, 0.0, false)+ } else {+ let b = dir1.dot(dir2);+ let ae = a * e;+ let bb = b * b;+ let denom = ae - bb;++ // Use absolute and ulps error to test collinearity.+ let parallel = denom <= eps || ulps_eq!(ae, bb);++ let s = if !parallel {+ (b * f - c * e) / denom+ } else {+ 0.0+ };++ (s, (b * s + f) / e, parallel)+ }+ }+}++// TODO: can we re-use this for the segment/segment case?+/// Closest points between two segments.+#[inline]+pub fn closest_points_line_line(+ orig1: Vector,+ dir1: Vector,+ orig2: Vector,+ dir2: Vector,+) -> (Vector, Vector) {+ let (s, t) = closest_points_line_line_parameters(orig1, dir1, orig2, dir2);+ (orig1 + dir1 * s, orig2 + dir2 * t)+}diff --git a/renderer/third_party/parry3d/src/query/closest_points/closest_points_segment_segment.rs b/renderer/third_party/parry3d/src/query/closest_points/closest_points_segment_segment.rsnew file mode 100644index 0000000..d382345--- /dev/null+++ b/renderer/third_party/parry3d/src/query/closest_points/closest_points_segment_segment.rs@@ -0,0 +1,118 @@+use crate::math::{Pose, Real, Vector2};+use crate::query::ClosestPoints;+use crate::shape::{Segment, SegmentPointLocation};++use crate::math::Vector;++/// Closest points between segments.+#[inline]+pub fn closest_points_segment_segment(+ pos12: &Pose,+ seg1: &Segment,+ seg2: &Segment,+ margin: Real,+) -> ClosestPoints {+ let (loc1, loc2) = closest_points_segment_segment_with_locations(pos12, seg1, seg2);+ let p1 = seg1.point_at(&loc1);+ let p2 = seg2.point_at(&loc2);++ if (p1 - (pos12 * p2)).length_squared() <= margin * margin {+ ClosestPoints::WithinMargin(p1, p2)+ } else {+ ClosestPoints::Disjoint+ }+}++// TODO: use this specialized procedure for distance/interference/contact determination as well.+/// Closest points between two segments.+#[inline]+pub fn closest_points_segment_segment_with_locations(+ pos12: &Pose,+ seg1: &Segment,+ seg2: &Segment,+) -> (SegmentPointLocation, SegmentPointLocation) {+ let seg2_1 = seg2.transformed(pos12);+ closest_points_segment_segment_with_locations_nD((&seg1.a, &seg1.b), (&seg2_1.a, &seg2_1.b))+}++macro_rules! impl_closest_points(+ ($Vect: ty, $fname: ident) => {+ /// Segment-segment closest points computation in an arbitrary dimension.+ #[allow(non_snake_case)]+ #[inline]+ pub fn $fname(+ seg1: (&$Vect, &$Vect),+ seg2: (&$Vect, &$Vect),+ ) -> (SegmentPointLocation, SegmentPointLocation) {+ // Inspired by RealField-time collision detection by Christer Ericson.+ let d1 = seg1.1 - seg1.0;+ let d2 = seg2.1 - seg2.0;+ let r = seg1.0 - seg2.0;++ let a = d1.length_squared();+ let e = d2.length_squared();+ let f = d2.dot(r);++ let mut s;+ let mut t;++ let _eps = crate::math::DEFAULT_EPSILON;+ if a <= _eps && e <= _eps {+ s = 0.0;+ t = 0.0;+ } else if a <= _eps {+ s = 0.0;+ t = (f / e).clamp(0.0, 1.0);+ } else {+ let c = d1.dot(r);+ if e <= _eps {+ t = 0.0;+ s = (-c / a).clamp(0.0, 1.0);+ } else {+ let b = d1.dot(d2);+ let ae = a * e;+ let bb = b * b;+ let denom = ae - bb;++ // Use absolute and ulps error to test collinearity.+ if denom > _eps && !ulps_eq!(ae, bb) {+ s = ((b * f - c * e) / denom).clamp(0.0, 1.0);+ } else {+ s = 0.0;+ }++ t = (b * s + f) / e;++ if t < 0.0 {+ t = 0.0;+ s = (-c / a).clamp(0.0, 1.0);+ } else if t > 1.0 {+ t = 1.0;+ s = ((b - c) / a).clamp(0.0, 1.0);+ }+ }+ }++ let loc1 = if s == 0.0 {+ SegmentPointLocation::OnVertex(0)+ } else if s == 1.0 {+ SegmentPointLocation::OnVertex(1)+ } else {+ SegmentPointLocation::OnEdge([1.0 - s, s])+ };++ let loc2 = if t == 0.0 {+ SegmentPointLocation::OnVertex(0)+ } else if t == 1.0 {+ SegmentPointLocation::OnVertex(1)+ } else {+ SegmentPointLocation::OnEdge([1.0 - t, t])+ };++ (loc1, loc2)+ }+ }+);++impl_closest_points!(Vector2, closest_points_segment_segment_2d);+impl_closest_points!(Vector, closest_points_segment_segment_with_locations_nD);diff --git a/renderer/third_party/parry3d/src/query/closest_points/closest_points_shape_shape.rs b/renderer/third_party/parry3d/src/query/closest_points/closest_points_shape_shape.rsnew file mode 100644index 0000000..b886bb4--- /dev/null+++ b/renderer/third_party/parry3d/src/query/closest_points/closest_points_shape_shape.rs@@ -0,0 +1,231 @@+use crate::math::{Pose, Real};+use crate::query::{ClosestPoints, DefaultQueryDispatcher, QueryDispatcher, Unsupported};+use crate::shape::Shape;++/// Computes the pair of closest points between two shapes.+///+/// This query finds the two points on the surfaces of the shapes that are closest+/// to each other, up to a specified maximum distance. It's particularly useful for+/// proximity detection, AI systems, and optimized spatial queries where you only+/// care about nearby objects.+///+/// # Behavior+///+/// The function returns one of three possible results:+///+/// - **`Intersecting`**: Shapes are overlapping (penetrating or touching)+/// - **`WithinMargin`**: Shapes are separated but the distance between them is ≤ `max_dist`+/// - **`Disjoint`**: Shapes are separated by more than `max_dist`+///+/// When shapes are separated and within the margin, the returned points represent+/// the exact locations on each shape's surface that are closest to each other.+///+/// # Maximum Distance Parameter+///+/// The `max_dist` parameter controls how far to search for closest points:+///+/// - **`max_dist = 0.0`**: Only returns points if shapes are touching or intersecting+/// - **`max_dist > 0.0`**: Returns points if separation distance ≤ `max_dist`+/// - **`max_dist = f32::MAX`**: Always computes closest points (no distance limit)+///+/// Using a finite `max_dist` can significantly improve performance by allowing early+/// termination when shapes are far apart.+///+/// # Arguments+///+/// * `pos1` - Position and orientation of the first shape in world space+/// * `g1` - The first shape (can be any shape implementing the `Shape` trait)+/// * `pos2` - Position and orientation of the second shape in world space+/// * `g2` - The second shape (can be any shape implementing the `Shape` trait)+/// * `max_dist` - Maximum separation distance to search for closest points+///+/// # Returns+///+/// * `Ok(ClosestPoints::Intersecting)` - Shapes are overlapping+/// * `Ok(ClosestPoints::WithinMargin(pt1, pt2))` - Closest points in world-space+/// * `Ok(ClosestPoints::Disjoint)` - Shapes are further than `max_dist` apart+/// * `Err(Unsupported)` - This shape pair combination is not supported+///+/// # Performance+///+/// Performance depends on shape types and the `max_dist` parameter:+///+/// - **Ball-Ball**: Very fast (analytical solution)+/// - **Convex-Convex**: Moderate (GJK algorithm)+/// - **Concave shapes**: Slower (requires BVH traversal)+/// - **Finite `max_dist`**: Faster due to early termination when distance exceeds limit+///+/// # Example: Basic Usage+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{closest_points, ClosestPoints};+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+///+/// // Position balls 5 units apart+/// let pos1 = Pose::translation(0.0, 0.0, 0.0);+/// let pos2 = Pose::translation(5.0, 0.0, 0.0);+///+/// // Find closest points (unlimited distance)+/// let result = closest_points(&pos1, &ball1, &pos2, &ball2, f32::MAX).unwrap();+///+/// if let ClosestPoints::WithinMargin(pt1, pt2) = result {+/// // pt1 is at (1.0, 0.0, 0.0) - surface of ball1+/// // pt2 is at (4.0, 0.0, 0.0) - surface of ball2+/// let distance = (pt2 - pt1).length();+/// assert!((distance - 3.0).abs() < 1e-5); // 5.0 - 1.0 - 1.0 = 3.0+/// }+/// # }+/// ```+///+/// # Example: Limited Search Distance+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{closest_points, ClosestPoints};+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+///+/// let pos1 = Pose::translation(0.0, 0.0, 0.0);+/// let pos2 = Pose::translation(10.0, 0.0, 0.0);+///+/// // Only search within 5.0 units+/// let result = closest_points(&pos1, &ball1, &pos2, &ball2, 5.0).unwrap();+///+/// // Shapes are 8.0 units apart (10.0 - 1.0 - 1.0), which exceeds max_dist+/// assert_eq!(result, ClosestPoints::Disjoint);+///+/// // With larger search distance, we get the points+/// let result2 = closest_points(&pos1, &ball1, &pos2, &ball2, 10.0).unwrap();+/// assert!(matches!(result2, ClosestPoints::WithinMargin(_, _)));+/// # }+/// ```+///+/// # Example: Intersecting Shapes+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{closest_points, ClosestPoints};+/// use parry3d::shape::Cuboid;+/// use parry3d::math::{Pose, Vector};+///+/// let box1 = Cuboid::new(Vector::new(2.0, 2.0, 2.0));+/// let box2 = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+///+/// // Position boxes so they overlap+/// let pos1 = Pose::translation(0.0, 0.0, 0.0);+/// let pos2 = Pose::translation(2.0, 0.0, 0.0);+///+/// let result = closest_points(&pos1, &box1, &pos2, &box2, 10.0).unwrap();+///+/// // When shapes intersect, closest points are undefined+/// assert_eq!(result, ClosestPoints::Intersecting);+/// # }+/// ```+///+/// # Example: AI Proximity Detection+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{closest_points, ClosestPoints};+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// // Enemy detection radius+/// let detection_radius = 15.0;+///+/// let player = Ball::new(0.5);+/// let enemy = Ball::new(0.5);+///+/// let player_pos = Pose::translation(0.0, 0.0, 0.0);+/// let enemy_pos = Pose::translation(12.0, 0.0, 0.0);+///+/// let result = closest_points(+/// &player_pos,+/// &player,+/// &enemy_pos,+/// &enemy,+/// detection_radius+/// ).unwrap();+///+/// match result {+/// ClosestPoints::WithinMargin(player_point, enemy_point) => {+/// // Enemy detected! Calculate approach vector+/// let approach_vector = player_point - enemy_point;+/// println!("Enemy approaching from: {:?}", approach_vector.normalize());+/// }+/// ClosestPoints::Disjoint => {+/// println!("Enemy out of detection range");+/// }+/// ClosestPoints::Intersecting => {+/// println!("Enemy contact!");+/// }+/// }+/// # }+/// ```+///+/// # Example: Different Shape Types+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{closest_points, ClosestPoints};+/// use parry3d::shape::{Ball, Cuboid};+/// use parry3d::math::{Pose, Vector};+///+/// let ball = Ball::new(2.0);+/// let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+///+/// let pos_ball = Pose::translation(5.0, 0.0, 0.0);+/// let pos_cuboid = Pose::translation(0.0, 0.0, 0.0);+///+/// let result = closest_points(&pos_ball, &ball, &pos_cuboid, &cuboid, 10.0).unwrap();+///+/// if let ClosestPoints::WithinMargin(pt_ball, pt_cuboid) = result {+/// // pt_ball is on the ball's surface+/// // pt_cuboid is on the cuboid's surface+/// println!("Closest point on ball: {:?}", pt_ball);+/// println!("Closest point on cuboid: {:?}", pt_cuboid);+///+/// // Verify distance+/// let separation = (pt_ball - pt_cuboid).length();+/// println!("Separation distance: {}", separation);+/// }+/// # }+/// ```+///+/// # Comparison with Other Queries+///+/// Choose the right query for your use case:+///+/// | Query | Returns | Use When |+/// |-------|---------|----------|+/// | `closest_points` | Vector locations | You need exact surface points |+/// | [`distance`](crate::query::distance::distance()) | Distance value | You only need the distance |+/// | [`contact`](crate::query::contact::contact()) | Contact info | Shapes are touching/penetrating |+/// | [`intersection_test`](crate::query::intersection_test::intersection_test()) | Boolean | You only need yes/no overlap |+///+/// # See Also+///+/// - [`ClosestPoints`] - The return type with detailed documentation+/// - [`distance`](crate::query::distance::distance()) - For just the distance value+/// - [`contact`](crate::query::contact::contact()) - For penetration depth and contact normals+/// - [`intersection_test`](crate::query::intersection_test::intersection_test()) - For boolean overlap test+pub fn closest_points(+ pos1: &Pose,+ g1: &dyn Shape,+ pos2: &Pose,+ g2: &dyn Shape,+ max_dist: Real,+) -> Result<ClosestPoints, Unsupported> {+ let pos12 = pos1.inv_mul(pos2);+ DefaultQueryDispatcher+ .closest_points(&pos12, g1, g2, max_dist)+ .map(|res| res.transform_by(pos1, pos2))+}diff --git a/renderer/third_party/parry3d/src/query/closest_points/closest_points_support_map_support_map.rs b/renderer/third_party/parry3d/src/query/closest_points/closest_points_support_map_support_map.rsnew file mode 100644index 0000000..0d15133--- /dev/null+++ b/renderer/third_party/parry3d/src/query/closest_points/closest_points_support_map_support_map.rs@@ -0,0 +1,62 @@+use crate::math::{Pose, Real, Vector};+use crate::query::gjk::{self, CsoPoint, GJKResult, VoronoiSimplex};+use crate::query::ClosestPoints;+use crate::shape::SupportMap;++/// Closest points between support-mapped shapes (`Cuboid`, `ConvexHull`, etc.)+pub fn closest_points_support_map_support_map<G1, G2>(+ pos12: &Pose,+ g1: &G1,+ g2: &G2,+ prediction: Real,+) -> ClosestPoints+where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+{+ match closest_points_support_map_support_map_with_params(+ pos12,+ g1,+ g2,+ prediction,+ &mut VoronoiSimplex::new(),+ None,+ ) {+ GJKResult::ClosestPoints(pt1, pt2, _) => {+ ClosestPoints::WithinMargin(pt1, pos12.inverse_transform_point(pt2))+ }+ GJKResult::NoIntersection(_) => ClosestPoints::Disjoint,+ GJKResult::Intersection => ClosestPoints::Intersecting,+ GJKResult::Proximity(_) => unreachable!(),+ }+}++/// Closest points between support-mapped shapes (`Cuboid`, `ConvexHull`, etc.)+///+/// This allows a more fine grained control other the underlying GJK algorigtm.+pub fn closest_points_support_map_support_map_with_params<G1, G2>(+ pos12: &Pose,+ g1: &G1,+ g2: &G2,+ prediction: Real,+ simplex: &mut VoronoiSimplex,+ init_dir: Option<Vector>,+) -> GJKResult+where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+{+ let dir = match init_dir {+ // TODO: or pos12.translation (without the minus sign) ?+ None => -pos12.translation,+ Some(dir) => dir,+ };++ if let Some(dir) = (dir).try_normalize() {+ simplex.reset(CsoPoint::from_shapes(pos12, g1, g2, dir));+ } else {+ simplex.reset(CsoPoint::from_shapes(pos12, g1, g2, Vector::X));+ }++ gjk::closest_points(pos12, g1, g2, prediction, true, simplex)+}diff --git a/renderer/third_party/parry3d/src/query/closest_points/mod.rs b/renderer/third_party/parry3d/src/query/closest_points/mod.rsnew file mode 100644index 0000000..fa962b3--- /dev/null+++ b/renderer/third_party/parry3d/src/query/closest_points/mod.rs@@ -0,0 +1,43 @@+//! Implementation details of the `closest_points` function.++pub use self::closest_points::ClosestPoints;+pub use self::closest_points_ball_ball::closest_points_ball_ball;+pub use self::closest_points_ball_convex_polyhedron::{+ closest_points_ball_convex_polyhedron, closest_points_convex_polyhedron_ball,+};+#[cfg(feature = "alloc")]+pub use self::closest_points_composite_shape_shape::{+ closest_points_composite_shape_shape, closest_points_shape_composite_shape,+};+pub use self::closest_points_cuboid_cuboid::closest_points_cuboid_cuboid;+pub use self::closest_points_cuboid_triangle::{+ closest_points_cuboid_triangle, closest_points_triangle_cuboid,+};+pub use self::closest_points_halfspace_support_map::{+ closest_points_halfspace_support_map, closest_points_support_map_halfspace,+};+pub use self::closest_points_line_line::{+ closest_points_line_line, closest_points_line_line_parameters,+ closest_points_line_line_parameters_eps,+};+pub use self::closest_points_segment_segment::{+ closest_points_segment_segment, closest_points_segment_segment_2d,+ closest_points_segment_segment_with_locations,+ closest_points_segment_segment_with_locations_nD,+};+pub use self::closest_points_shape_shape::closest_points;+pub use self::closest_points_support_map_support_map::closest_points_support_map_support_map;+pub use self::closest_points_support_map_support_map::closest_points_support_map_support_map_with_params;++mod closest_points;+mod closest_points_ball_ball;+mod closest_points_ball_convex_polyhedron;+#[cfg(feature = "alloc")]+mod closest_points_composite_shape_shape;+mod closest_points_cuboid_cuboid;+mod closest_points_cuboid_triangle;+mod closest_points_halfspace_support_map;+mod closest_points_line_line;+mod closest_points_segment_segment;+mod closest_points_shape_shape;+mod closest_points_support_map_support_map;diff --git a/renderer/third_party/parry3d/src/query/contact/contact.rs b/renderer/third_party/parry3d/src/query/contact/contact.rsnew file mode 100644index 0000000..63a2744--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact/contact.rs@@ -0,0 +1,200 @@+use crate::math::{Pose, Real, Vector};+use crate::shape::SubShapeId;+use core::mem;++/// Geometric description of a contact between two shapes.+///+/// A contact represents the point(s) where two shapes touch or penetrate. This structure+/// contains all the information needed to resolve collisions: contact points, surface normals,+/// and penetration depth.+///+/// # Contact States+///+/// A `Contact` can represent different collision states:+///+/// - **Touching** (`dist ≈ 0.0`): Shapes are just barely in contact+/// - **Penetrating** (`dist < 0.0`): Shapes are overlapping (negative distance = penetration depth)+/// - **Separated** (`dist > 0.0`): Shapes are close but not touching (rarely used; see `closest_points` instead)+///+/// # Coordinate Systems+///+/// Contact data can be expressed in different coordinate systems:+///+/// - **World space**: Both shapes' transformations applied; `normal2 = -normal1`+/// - **Local space**: Relative to one shape's coordinate system+///+/// # Use Cases+///+/// - **Physics simulation**: Compute collision response forces+/// - **Collision resolution**: Push objects apart when penetrating+/// - **Trigger detection**: Detect when objects touch without resolving+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::contact;+/// use parry3d::shape::Ball;+/// use parry3d::math::{Pose, Vector};+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+///+/// // Overlapping balls (centers 1.5 units apart, combined radii = 2.0)+/// let pos1 = Pose::translation(0.0, 0.0, 0.0);+/// let pos2 = Pose::translation(1.5, 0.0, 0.0);+///+/// if let Ok(Some(contact)) = contact(&pos1, &ball1, &pos2, &ball2, 0.0) {+/// // Penetration depth (negative distance)+/// assert!(contact.dist < 0.0);+/// println!("Penetration: {}", -contact.dist); // 0.5 units+///+/// // Normal points from shape 1 toward shape 2+/// println!("Normal: {:?}", contact.normal1);+///+/// // Contact points are on each shape's surface+/// println!("Vector on ball1: {:?}", contact.point1);+/// println!("Vector on ball2: {:?}", contact.point2);+/// }+/// # }+/// ```+#[derive(Debug, PartialEq, Copy, Clone)]+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+pub struct Contact {+ /// Position of the contact point on the first shape's surface.+ ///+ /// This is the point on shape 1 that is closest to (or penetrating into) shape 2.+ /// Expressed in the same coordinate system as the contact (world or local space).+ pub point1: Vector,++ /// Position of the contact point on the second shape's surface.+ ///+ /// This is the point on shape 2 that is closest to (or penetrating into) shape 1.+ /// When shapes are penetrating, this point may be inside shape 1.+ pub point2: Vector,++ /// Contact normal pointing outward from the first shape.+ ///+ /// This unit vector points from shape 1 toward shape 2, perpendicular to the+ /// contact surface. Used to compute separation direction and collision response+ /// forces for shape 1.+ pub normal1: Vector,++ /// Contact normal pointing outward from the second shape.+ ///+ /// In world space, this is always equal to `-normal1`. In local space coordinates,+ /// it may differ due to different shape orientations.+ pub normal2: Vector,++ /// Signed distance between the two contact points.+ ///+ /// - **Positive**: Shapes are separated (distance between surfaces)+ /// - **Zero**: Shapes are exactly touching+ /// - **Negative**: Shapes are penetrating (absolute value = penetration depth)+ ///+ /// For collision resolution, use `-dist` as the penetration depth when `dist < 0.0`.+ pub dist: Real,++ /// The sub-shape of the first shape this contact is on.+ ///+ /// Always `0` for a shape with no sub-shapes.+ pub subshape1: SubShapeId,++ /// The sub-shape of the second shape this contact is on.+ ///+ /// Always `0` for a shape with no sub-shapes.+ pub subshape2: SubShapeId,+}++impl Contact {+ /// Creates a new contact with the given parameters.+ ///+ /// # Arguments+ ///+ /// * `point1` - Contact point on the first shape's surface+ /// * `point2` - Contact point on the second shape's surface+ /// * `normal1` - Unit normal pointing outward from shape 1+ /// * `normal2` - Unit normal pointing outward from shape 2+ /// * `dist` - Signed distance (negative = penetration depth)+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::Contact;+ /// use parry3d::math::Vector;+ ///+ /// // Create a contact representing two spheres touching+ /// let point1 = Vector::new(1.0, 0.0, 0.0);+ /// let point2 = Vector::new(2.0, 0.0, 0.0);+ /// let normal1 = Vector::new(1.0, 0.0, 0.0).normalize();+ /// let normal2 = Vector::new(-1.0, 0.0, 0.0).normalize();+ ///+ /// let contact = Contact::new(point1, point2, normal1, normal2, 0.0);+ /// assert_eq!(contact.dist, 0.0); // Touching, not penetrating+ /// # }+ /// ```+ #[inline]+ pub fn new(+ point1: Vector,+ point2: Vector,+ normal1: Vector,+ normal2: Vector,+ dist: Real,+ ) -> Self {+ Contact {+ point1,+ point2,+ normal1,+ normal2,+ dist,+ subshape1: 0,+ subshape2: 0,+ }+ }++ /// Sets the sub-shapes this contact is between.+ #[inline]+ pub fn with_subshapes(mut self, subshape1: SubShapeId, subshape2: SubShapeId) -> Self {+ self.subshape1 = subshape1;+ self.subshape2 = subshape2;+ self+ }+}++impl Contact {+ /// Swaps the points and normals of this contact.+ #[inline]+ pub fn flip(&mut self) {+ mem::swap(&mut self.point1, &mut self.point2);+ mem::swap(&mut self.normal1, &mut self.normal2);+ mem::swap(&mut self.subshape1, &mut self.subshape2);+ }++ /// Returns a new contact containing the swapped points and normals of `self`.+ #[inline]+ pub fn flipped(mut self) -> Self {+ self.flip();+ self+ }++ /// Transform the points and normals from this contact by+ /// the given transformations.+ #[inline]+ pub fn transform_by_mut(&mut self, pos1: &Pose, pos2: &Pose) {+ self.point1 = pos1 * self.point1;+ self.point2 = pos2 * self.point2;+ self.normal1 = pos1.rotation * self.normal1;+ self.normal2 = pos2.rotation * self.normal2;+ }++ /// Transform `self.point1` and `self.normal1` by the `pos`.+ pub fn transform1_by_mut(&mut self, pos: &Pose) {+ self.point1 = pos * self.point1;+ self.normal1 = pos.rotation * self.normal1;+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact/contact_ball_ball.rs b/renderer/third_party/parry3d/src/query/contact/contact_ball_ball.rsnew file mode 100644index 0000000..e365334--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact/contact_ball_ball.rs@@ -0,0 +1,36 @@+use crate::math::{ComplexField, Pose, Real, Vector};+use crate::query::Contact;+use crate::shape::Ball;+use num::Zero;++/// Contact between balls.+#[inline]+pub fn contact_ball_ball(pos12: &Pose, b1: &Ball, b2: &Ball, prediction: Real) -> Option<Contact> {+ let r1 = b1.radius;+ let r2 = b2.radius;+ let center2_1 = pos12.translation;+ let distance_squared = center2_1.length_squared();+ let sum_radius = r1 + r2;+ let sum_radius_with_error = sum_radius + prediction;++ if distance_squared < sum_radius_with_error * sum_radius_with_error {+ let normal1 = if !distance_squared.is_zero() {+ (center2_1).normalize()+ } else {+ Vector::X+ };+ let normal2 = -(pos12.rotation.inverse() * normal1);+ let point1 = normal1 * r1;+ let point2 = normal2 * r2;++ Some(Contact::new(+ point1,+ point2,+ normal1,+ normal2,+ <Real as ComplexField>::sqrt(distance_squared) - sum_radius,+ ))+ } else {+ None+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact/contact_ball_convex_polyhedron.rs b/renderer/third_party/parry3d/src/query/contact/contact_ball_convex_polyhedron.rsnew file mode 100644index 0000000..fdec89a--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact/contact_ball_convex_polyhedron.rs@@ -0,0 +1,60 @@+use crate::math::{Pose, Real, Vector};+use crate::query::Contact;+use crate::shape::{Ball, Shape};++/// Contact between a ball and a convex polyhedron.+///+/// This function panics if the input shape does not implement+/// both the ConvexPolyhedron and PointQuery traits.+#[inline]+pub fn contact_ball_convex_polyhedron(+ pos12: &Pose,+ ball1: &Ball,+ shape2: &(impl Shape + ?Sized),+ prediction: Real,+) -> Option<Contact> {+ contact_convex_polyhedron_ball(&pos12.inverse(), shape2, ball1, prediction).map(|c| c.flipped())+}++/// Contact between a convex polyhedron and a ball.+///+/// This function panics if the input shape does not implement+/// both the ConvexPolyhedron and PointQuery traits.+#[inline]+pub fn contact_convex_polyhedron_ball(+ pos12: &Pose,+ shape1: &(impl Shape + ?Sized),+ ball2: &Ball,+ prediction: Real,+) -> Option<Contact> {+ let center2_1 = pos12.translation;+ let (proj, f1) = shape1.project_local_point_and_get_feature(center2_1);++ let dist;+ let normal1;+ let (dir1, len) = (proj.point - center2_1).normalize_and_length();+ if len >= crate::math::DEFAULT_EPSILON {+ if proj.is_inside {+ dist = -len - ball2.radius;+ normal1 = dir1;+ } else {+ dist = len - ball2.radius;+ normal1 = -dir1;+ }+ } else {+ dist = -ball2.radius;+ normal1 = shape1+ .feature_normal_at_point(proj.subshape, f1, proj.point)+ .or_else(|| (proj.point).try_normalize())+ .unwrap_or(Vector::Y);+ }++ if dist <= prediction {+ let normal2 = pos12.rotation.inverse() * -normal1;+ let point2 = normal2 * ball2.radius;+ let point1 = proj.point;+ return Some(Contact::new(point1, point2, normal1, normal2, dist));+ }++ None+}diff --git a/renderer/third_party/parry3d/src/query/contact/contact_composite_shape_shape.rs b/renderer/third_party/parry3d/src/query/contact/contact_composite_shape_shape.rsnew file mode 100644index 0000000..c82b639--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact/contact_composite_shape_shape.rs@@ -0,0 +1,82 @@+use crate::bounding_volume::BoundingVolume;+use crate::math::{Pose, Real};+use crate::query::{Contact, QueryDispatcher};+use crate::shape::{CompositeShape, CompositeShapeRef, Shape, SubShapeId};+use crate::utils::PoseOpt;++impl<S: ?Sized + CompositeShape> CompositeShapeRef<'_, S> {+ /// Returns the closest/deepest contact between `self` and the given `shape2` positioned at+ /// `pose12` relative to `self`.+ ///+ /// Returns `None` if `self` and `shape2` are separated by a distance larger than+ /// `prediction`. Otherwise returns the index of the sub-shape of `self` the contact is on+ /// alongside the contact, which is left as that sub-shape reported it (its `subshape1` is the+ /// sub-shape's own when it is a composite too, and `subshape2` is `shape2`'s).+ pub fn contact_with_shape<D: ?Sized + QueryDispatcher>(+ &self,+ dispatcher: &D,+ pose12: &Pose,+ shape2: &dyn Shape,+ prediction: Real,+ ) -> Option<(SubShapeId, Contact)> {+ let ls_aabb2 = shape2.compute_aabb(pose12).loosened(prediction);+ let mut result = None::<(SubShapeId, Contact)>;++ for part_id in self.0.bvh().intersect_aabb(&ls_aabb2) {+ self.0.map_part_at(part_id, &mut |part_pos1, part1, _| {+ if let Ok(Some(mut c)) =+ dispatcher.contact(&part_pos1.inv_mul(pose12), part1, shape2, prediction)+ {+ let replace = result.is_none_or(|(_, cbest)| c.dist < cbest.dist);++ if replace {+ if let Some(part_pos1) = part_pos1 {+ c.transform1_by_mut(part_pos1);+ }+ result = Some((part_id, c))+ }+ }+ });+ }++ result+ }+}++/// Best contact between a composite shape (`Mesh`, `Compound`) and any other shape.+pub fn contact_composite_shape_shape<D, G1>(+ dispatcher: &D,+ pose12: &Pose,+ g1: &G1,+ g2: &dyn Shape,+ prediction: Real,+) -> Option<Contact>+where+ D: ?Sized + QueryDispatcher,+ G1: ?Sized + CompositeShape,+{+ // `subshape2` is left as the dispatch set it: `g2` may be a composite too, and only it+ // knows which of its parts answered.+ CompositeShapeRef(g1)+ .contact_with_shape(dispatcher, pose12, g2, prediction)+ .map(|(part_id, mut c)| {+ c.subshape1 = part_id;+ c+ })+}++/// Best contact between a shape and a composite (`Mesh`, `Compound`) shape.+pub fn contact_shape_composite_shape<D, G2>(+ dispatcher: &D,+ pose12: &Pose,+ g1: &dyn Shape,+ g2: &G2,+ prediction: Real,+) -> Option<Contact>+where+ D: ?Sized + QueryDispatcher,+ G2: ?Sized + CompositeShape,+{+ contact_composite_shape_shape(dispatcher, &pose12.inverse(), g2, g1, prediction)+ .map(|c| c.flipped())+}diff --git a/renderer/third_party/parry3d/src/query/contact/contact_cuboid_cuboid.rs b/renderer/third_party/parry3d/src/query/contact/contact_cuboid_cuboid.rsnew file mode 100644index 0000000..e75fbf8--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact/contact_cuboid_cuboid.rs@@ -0,0 +1,119 @@+use crate::math::{Pose, Real};+use crate::query::{sat, Contact, PointQuery};+use crate::shape::{Cuboid, SupportMap};+use approx::AbsDiffEq;++/// Contact between two cuboids.+#[inline]+pub fn contact_cuboid_cuboid(+ pos12: &Pose,+ cuboid1: &Cuboid,+ cuboid2: &Cuboid,+ prediction: Real,+) -> Option<Contact> {+ let pos21 = pos12.inverse();++ let sep1 = sat::cuboid_cuboid_find_local_separating_normal_oneway(cuboid1, cuboid2, pos12);+ if sep1.0 > prediction {+ return None;+ }++ let sep2 = sat::cuboid_cuboid_find_local_separating_normal_oneway(cuboid2, cuboid1, &pos21);+ if sep2.0 > prediction {+ return None;+ }++ #[cfg(feature = "dim2")]+ let sep3 = (-Real::MAX, crate::math::Vector::Y); // This case does not exist in 2D.+ #[cfg(feature = "dim3")]+ let sep3 = sat::cuboid_cuboid_find_local_separating_edge_twoway(cuboid1, cuboid2, pos12);+ if sep3.0 > prediction {+ return None;+ }++ // The best separating axis is face-vertex.+ if sep1.0 >= sep2.0 && sep1.0 >= sep3.0 {+ // To compute the closest points, we need to project the support point+ // from cuboid2 on the support-face of cuboid1. For simplicity, we just+ // project the support point from cuboid2 on cuboid1 itself (not just the face).+ let pt2_1 = cuboid2.support_point(pos12, -sep1.1);+ let proj1 = cuboid1.project_local_point(pt2_1, false);++ let separation = (pt2_1 - proj1.point).dot(sep1.1);+ let (mut normal1, mut dist) = (pt2_1 - proj1.point).normalize_and_length();++ // NOTE: we had to recompute the normal because we can't use+ // the separation vector for the case where we have a vertex-vertex contact.+ if separation < 0.0 || dist <= Real::default_epsilon() {+ // Penetration or contact lying on the boundary exactly.+ normal1 = sep1.1;+ dist = separation;+ }++ if dist > prediction {+ return None;+ }++ return Some(Contact::new(+ proj1.point,+ pos12.inverse_transform_point(pt2_1),+ normal1,+ pos12.rotation.inverse() * -normal1,+ dist,+ ));+ }++ // The best separating axis is vertex-face.+ if sep2.0 >= sep1.0 && sep2.0 >= sep3.0 {+ // To compute the actual closest points, we need to project the support point+ // from cuboid1 on the support-face of cuboid2. For simplicity, we just+ // project the support point from cuboid1 on cuboid2 itself (not just the face).+ let pt1_2 = cuboid1.support_point(&pos21, -sep2.1);+ let proj2 = cuboid2.project_local_point(pt1_2, false);++ let separation = (pt1_2 - proj2.point).dot(sep2.1);+ let (mut normal2, mut dist) = (pt1_2 - proj2.point).normalize_and_length();++ // NOTE: we had to recompute the normal because we can't use+ // the separation vector for the case where we have a vertex-vertex contact.+ if separation < 0.0 || dist <= Real::default_epsilon() {+ // Penetration or contact lying on the boundary exactly.+ normal2 = sep2.1;+ dist = separation;+ }++ if dist > prediction {+ return None;+ }++ return Some(Contact::new(+ pos12 * pt1_2,+ proj2.point,+ pos12.rotation * -normal2,+ normal2,+ dist,+ ));+ }++ // The best separating axis is edge-edge.+ #[cfg(feature = "dim3")]+ if sep3.0 >= sep2.0 && sep3.0 >= sep1.0 {+ use crate::query::{details, ClosestPoints};+ // To compute the actual distance, we need to compute the closest+ // points between the two edges that generated the separating axis.+ let edge1 = cuboid1.local_support_edge_segment(sep3.1);+ let edge2 = cuboid2.local_support_edge_segment(pos21.rotation * -sep3.1);++ match details::closest_points_segment_segment(pos12, &edge1, &edge2, prediction) {+ ClosestPoints::Disjoint => return None,+ ClosestPoints::WithinMargin(a, b) => {+ let normal1 = sep3.1;+ let normal2 = pos12.rotation.inverse() * -normal1;+ return Some(Contact::new(a, b, normal1, normal2, sep3.0));+ }+ ClosestPoints::Intersecting => unreachable!(),+ }+ }++ unreachable!()+}diff --git a/renderer/third_party/parry3d/src/query/contact/contact_halfspace_support_map.rs b/renderer/third_party/parry3d/src/query/contact/contact_halfspace_support_map.rsnew file mode 100644index 0000000..7e82036--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact/contact_halfspace_support_map.rs@@ -0,0 +1,40 @@+use crate::math::{Pose, Real};+use crate::query::Contact;+use crate::shape::{HalfSpace, SupportMap};++/// Contact between a halfspace and a support-mapped shape (Cuboid, ConvexHull, etc.)+pub fn contact_halfspace_support_map<G: ?Sized + SupportMap>(+ pos12: &Pose,+ halfspace: &HalfSpace,+ other: &G,+ prediction: Real,+) -> Option<Contact> {+ let deepest = other.support_point_toward(pos12, -halfspace.normal);+ let distance = halfspace.normal.dot(deepest);++ if distance <= prediction {+ let point1 = deepest - halfspace.normal * distance;+ let point2 = pos12.inverse_transform_point(deepest);+ let normal2 = pos12.rotation.inverse() * -halfspace.normal;++ Some(Contact::new(+ point1,+ point2,+ halfspace.normal,+ normal2,+ distance,+ ))+ } else {+ None+ }+}++/// Contact between a support-mapped shape (Cuboid, ConvexHull, etc.) and a halfspace.+pub fn contact_support_map_halfspace<G: ?Sized + SupportMap>(+ pos12: &Pose,+ other: &G,+ halfspace: &HalfSpace,+ prediction: Real,+) -> Option<Contact> {+ contact_halfspace_support_map(pos12, halfspace, other, prediction).map(|c| c.flipped())+}diff --git a/renderer/third_party/parry3d/src/query/contact/contact_heightfield_shape.rs b/renderer/third_party/parry3d/src/query/contact/contact_heightfield_shape.rsnew file mode 100644index 0000000..b6a7c9f--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact/contact_heightfield_shape.rs@@ -0,0 +1,55 @@+use crate::bounding_volume::BoundingVolume;+use crate::math::{Pose, Real};+use crate::query::{Contact, QueryDispatcher};+use crate::shape::{HeightField, Shape};++/// Best contact between a heightfield and any other shape.+///+/// Tests the elements intersecting `shape2`'s Aabb (loosened by `prediction`) and returns+/// the deepest contact.+pub fn contact_heightfield_shape<D>(+ dispatcher: &D,+ pos12: &Pose,+ heightfield1: &HeightField,+ shape2: &dyn Shape,+ prediction: Real,+) -> Option<Contact>+where+ D: ?Sized + QueryDispatcher,+{+ let aabb2_1 = shape2.compute_aabb(pos12).loosened(prediction.max(0.0));+ let mut result = None::<Contact>;++ heightfield1.map_elements_in_local_aabb(&aabb2_1, &mut |_, elt1| {+ // The elements are already in the heightfield's local frame, so the sub-shape+ // contact needs no transform.+ if let Ok(Some(c)) = dispatcher.contact(pos12, elt1, shape2, prediction) {+ if result.is_none_or(|best| c.dist < best.dist) {+ result = Some(c);+ }+ }+ });++ result+}++/// Best contact between a shape and a heightfield.+pub fn contact_shape_heightfield<D>(+ dispatcher: &D,+ pos12: &Pose,+ shape1: &dyn Shape,+ heightfield2: &HeightField,+ prediction: Real,+) -> Option<Contact>+where+ D: ?Sized + QueryDispatcher,+{+ contact_heightfield_shape(+ dispatcher,+ &pos12.inverse(),+ heightfield2,+ shape1,+ prediction,+ )+ .map(|c| c.flipped())+}diff --git a/renderer/third_party/parry3d/src/query/contact/contact_shape_shape.rs b/renderer/third_party/parry3d/src/query/contact/contact_shape_shape.rsnew file mode 100644index 0000000..aa2201b--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact/contact_shape_shape.rs@@ -0,0 +1,138 @@+use crate::math::{Pose, Real};+use crate::query::{Contact, DefaultQueryDispatcher, QueryDispatcher, Unsupported};+use crate::shape::Shape;++/// Computes contact information between two shapes.+///+/// This function finds a single contact point (or pair of points) where two shapes+/// touch or penetrate. It's one of the most important queries for physics simulation+/// and collision response.+///+/// # Behavior+///+/// The function returns contact data in the following cases:+///+/// - **Penetrating**: Shapes overlap → Returns contact with `dist < 0.0`+/// - **Touching**: Shapes just make contact → Returns contact with `dist ≈ 0.0`+/// - **Nearly touching**: Distance ≤ `prediction` → Returns contact with `dist > 0.0`+/// - **Separated**: Distance > `prediction` → Returns `None`+///+/// # Prediction Distance+///+/// The `prediction` parameter allows detecting contacts before shapes actually touch.+/// This is useful for:+///+/// - **Continuous collision detection**: Predict contacts that will occur soon+/// - **Speculative contacts**: Pre-compute contacts for upcoming frames+/// - **Efficiency**: Avoid re-computing contacts every frame for slow-moving objects+///+/// Use `0.0` for exact contact detection only.+///+/// # Arguments+///+/// * `pos1` - Position and orientation of the first shape in world space+/// * `g1` - The first shape+/// * `pos2` - Position and orientation of the second shape in world space+/// * `g2` - The second shape+/// * `prediction` - Maximum separation distance for contact detection (typically `0.0`)+///+/// # Returns+///+/// * `Ok(Some(contact))` - Contact found (touching, penetrating, or within prediction distance)+/// * `Ok(None)` - No contact (shapes separated by more than `prediction`)+/// * `Err(Unsupported)` - This shape pair combination is not supported+///+/// # Contact Data+///+/// The returned [`Contact`] contains:+/// - `point1`, `point2`: Contact points on each shape's surface (world space)+/// - `normal1`, `normal2`: Surface normals at contact points (world space)+/// - `dist`: Signed distance (negative = penetration depth)+///+/// # Performance+///+/// Performance depends on shape types:+/// - **Convex-Convex**: Fast (GJK/EPA algorithms)+/// - **Concave shapes**: Slower (requires BVH traversal)+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::contact;+/// use parry3d::shape::{Ball, Cuboid};+/// use parry3d::math::{Pose, Vector};+///+/// let ball = Ball::new(1.0);+/// let cuboid = Cuboid::new(Vector::new(2.0, 2.0, 2.0));+///+/// // Position shapes so they're penetrating+/// let pos_ball = Pose::translation(2.5, 0.0, 0.0);+/// let pos_cuboid = Pose::identity();+///+/// // Compute contact (no prediction distance)+/// if let Ok(Some(contact)) = contact(&pos_ball, &ball, &pos_cuboid, &cuboid, 0.0) {+/// // Penetration depth (negative distance)+/// let penetration = -contact.dist;+/// println!("Penetrating by: {} units", penetration);+///+/// // Normal points from ball toward cuboid+/// println!("Separation direction: {:?}", contact.normal1);+///+/// // Use contact to resolve collision:+/// // - Apply impulse along normal1 to separate shapes+/// // - Move shapes apart by penetration depth+/// }+/// # }+/// ```+///+/// # Example with Prediction+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::contact;+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+///+/// // Balls separated by 2.2 units (just outside contact range)+/// let pos1 = Pose::translation(0.0, 0.0, 0.0);+/// let pos2 = Pose::translation(4.2, 0.0, 0.0); // radii sum = 2.0, gap = 2.2+///+/// // Without prediction: no contact+/// assert!(contact(&pos1, &ball1, &pos2, &ball2, 0.0).unwrap().is_none());+///+/// // With prediction of 0.5: still no contact (gap 2.2 > 0.5)+/// assert!(contact(&pos1, &ball1, &pos2, &ball2, 0.5).unwrap().is_none());+///+/// // With prediction of 3.0: contact detected+/// if let Ok(Some(c)) = contact(&pos1, &ball1, &pos2, &ball2, 3.0) {+/// assert!(c.dist > 0.0); // Positive = separated but within prediction+/// assert!(c.dist <= 3.0); // Within prediction distance+/// }+/// # }+/// ```+///+/// # See Also+///+/// - [`distance`](crate::query::distance::distance()) - For just the distance value+/// - [`closest_points`](crate::query::closest_points::closest_points()) - For closest point locations+/// - [`intersection_test`](crate::query::intersection_test::intersection_test()) - For boolean overlap test+pub fn contact(+ pos1: &Pose,+ g1: &dyn Shape,+ pos2: &Pose,+ g2: &dyn Shape,+ prediction: Real,+) -> Result<Option<Contact>, Unsupported> {+ let pos12 = pos1.inv_mul(pos2);+ let mut result = DefaultQueryDispatcher.contact(&pos12, g1, g2, prediction);++ if let Ok(Some(contact)) = &mut result {+ contact.transform_by_mut(pos1, pos2);+ }++ result+}diff --git a/renderer/third_party/parry3d/src/query/contact/contact_support_map_support_map.rs b/renderer/third_party/parry3d/src/query/contact/contact_support_map_support_map.rsnew file mode 100644index 0000000..03d8516--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact/contact_support_map_support_map.rs@@ -0,0 +1,110 @@+use crate::math::{Pose, Real, Vector};+use crate::query::epa::EPA;+use crate::query::gjk::{self, CsoPoint, GJKResult, VoronoiSimplex};+use crate::query::Contact;+use crate::shape::SupportMap;++/// Contact between support-mapped shapes (`Cuboid`, `ConvexHull`, etc.)+pub fn contact_support_map_support_map<G1, G2>(+ pos12: &Pose,+ g1: &G1,+ g2: &G2,+ prediction: Real,+) -> Option<Contact>+where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+{+ let simplex = &mut VoronoiSimplex::new();+ match contact_support_map_support_map_with_params(pos12, g1, g2, prediction, simplex, None) {+ GJKResult::ClosestPoints(point1, point2_1, normal1) => {+ let dist = (point2_1 - point1).dot(normal1);+ let point2 = pos12.inverse_transform_point(point2_1);+ let normal2 = pos12.rotation.inverse() * -normal1;+ Some(Contact::new(point1, point2, normal1, normal2, dist))+ }+ GJKResult::NoIntersection(_) => None,+ GJKResult::Intersection => unreachable!(),+ GJKResult::Proximity(_) => unreachable!(),+ }+}++/// Contact between support-mapped shapes (`Cuboid`, `ConvexHull`, etc.)+///+/// This allows a more fine grained control other the underlying GJK algorigtm.+/// The vector-typed result is the vector that should be passed as `init` for+/// subsequent executions of the algorithm. It is also the contact+/// normal (that points toward the outside of the first solid).+pub fn contact_support_map_support_map_with_params<G1, G2>(+ pos12: &Pose,+ g1: &G1,+ g2: &G2,+ prediction: Real,+ simplex: &mut VoronoiSimplex,+ init_dir: Option<Vector>,+) -> GJKResult+where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+{+ let dir = if let Some(init_dir) = init_dir {+ init_dir+ } else if let Some(init_dir) = (pos12.translation).try_normalize() {+ init_dir+ } else {+ Vector::X+ };++ simplex.reset(CsoPoint::from_shapes(pos12, g1, g2, dir));++ let cpts = gjk::closest_points(pos12, g1, g2, prediction, true, simplex);+ if cpts != GJKResult::Intersection {+ return cpts;+ }++ // The point is inside of the CSO: use the fallback algorithm+ let mut epa = EPA::new();+ if let Some((p1, p2, n)) = epa.closest_points(pos12, g1, g2, simplex) {+ return GJKResult::ClosestPoints(p1, p2, n);+ }++ // Everything failed+ GJKResult::NoIntersection(Vector::X)+}++#[cfg(all(test, feature = "dim2"))]+mod test {+ use crate::bounding_volume::Aabb;+ use crate::math::{Pose, Vector};+ use crate::query::contact;+ use crate::shape::{Cuboid, Segment};++ /// Regression test for <https://github.com/dimforge/parry/issues/415>: a segment overlapping+ /// a cuboid must report a penetrating contact. An absolute tolerance used in EPA's `FaceId`+ /// construction used to spuriously reject valid faces (and make `contact` return `None`) when+ /// using `f64` precision with large coordinates.+ ///+ /// NOTE: this is not in the `tests` directory since we want it for both f32 and f64 versions.+ #[test]+ fn contact_segment_cuboid_issue_415() {+ let segment = Segment {+ a: Vector::new(60.0, 10.0),+ b: Vector::new(10.0, 0.0),+ };+ let aabb = Aabb {+ mins: Vector::new(40.0, -50.0),+ maxs: Vector::new(60.0, 150.0),+ };+ let cuboid = Cuboid::new(aabb.half_extents());+ let pos_cuboid = Pose::from_translation(aabb.center());++ let contact = contact(&Pose::IDENTITY, &segment, &pos_cuboid, &cuboid, 1.0)+ .unwrap()+ .expect("the overlapping segment and cuboid must report a contact");+ assert!(+ contact.dist < 0.0,+ "expected a penetrating contact, got dist = {}",+ contact.dist+ );+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact/mod.rs b/renderer/third_party/parry3d/src/query/contact/mod.rsnew file mode 100644index 0000000..2daacb8--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact/mod.rs@@ -0,0 +1,35 @@+//! Implementation details of the `contact` and `contacts` functions.++pub use self::contact::Contact;+pub use self::contact_ball_ball::contact_ball_ball;+pub use self::contact_ball_convex_polyhedron::{+ contact_ball_convex_polyhedron, contact_convex_polyhedron_ball,+};+#[cfg(feature = "alloc")]+pub use self::contact_composite_shape_shape::{+ contact_composite_shape_shape, contact_shape_composite_shape,+};+pub use self::contact_cuboid_cuboid::contact_cuboid_cuboid;+pub use self::contact_halfspace_support_map::{+ contact_halfspace_support_map, contact_support_map_halfspace,+};+#[cfg(feature = "alloc")]+pub use self::contact_heightfield_shape::{contact_heightfield_shape, contact_shape_heightfield};+pub use self::contact_shape_shape::contact;+#[cfg(feature = "alloc")]+pub use self::contact_support_map_support_map::{+ contact_support_map_support_map, contact_support_map_support_map_with_params,+};++mod contact;+mod contact_ball_ball;+mod contact_ball_convex_polyhedron;+#[cfg(feature = "alloc")]+mod contact_composite_shape_shape;+mod contact_cuboid_cuboid;+mod contact_halfspace_support_map;+#[cfg(feature = "alloc")]+mod contact_heightfield_shape;+mod contact_shape_shape;+#[cfg(feature = "alloc")]+mod contact_support_map_support_map;diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifold.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifold.rsnew file mode 100644index 0000000..dcdfa7a--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifold.rs@@ -0,0 +1,915 @@+use crate::math::{Pose, Real, Vector};+use crate::shape::PackedFeatureId;+#[cfg(feature = "dim3")]+use alloc::vec::Vec;++#[derive(Copy, Clone, Debug)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+/// A single contact point between two shapes.+///+/// A `TrackedContact` represents a single point of contact between two shapes, with enough+/// information to track the contact across multiple frames and identify which geometric+/// features (vertices, edges, faces) are in contact.+///+/// # Understanding Contact Points+///+/// Each contact point consists of:+/// - Two contact positions (one on each shape, in local coordinates)+/// - A distance value (negative = penetrating, positive = separated)+/// - Feature IDs that identify which part of each shape is in contact+/// - Optional user data for tracking contact-specific information+///+/// # Local vs World Space+///+/// Contact points are stored in **local space** (the coordinate system of each shape).+/// This is important because:+/// - Shapes can move and rotate, but local coordinates remain constant+/// - Contact tracking works by comparing feature IDs and local positions+/// - To get world-space positions, transform the local points by the shape's position+///+/// # Distance Convention+///+/// The `dist` field uses the following convention:+/// - `dist < 0.0`: Shapes are penetrating (overlapping). The absolute value is the penetration depth.+/// - `dist == 0.0`: Shapes are exactly touching.+/// - `dist > 0.0`: Shapes are separated. This happens when using contact prediction.+///+/// # Example: Basic Contact Query+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{ContactManifold, TrackedContact};+/// use parry3d::query::details::contact_manifold_ball_ball;+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// // Two balls, one slightly overlapping the other+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+/// let pos12 = Pose::translation(1.5, 0.0, 0.0); // Overlapping by 0.5+///+/// let mut manifold = ContactManifold::<(), ()>::new();+/// contact_manifold_ball_ball(&pos12, &ball1, &ball2, 0.0, &mut manifold);+///+/// if let Some(contact) = manifold.points.first() {+/// println!("Penetration depth: {}", -contact.dist);+/// println!("Contact on ball1 (local): {:?}", contact.local_p1);+/// println!("Contact on ball2 (local): {:?}", contact.local_p2);+/// }+/// # }+/// ```+///+/// # Example: Converting to World Space+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{ContactManifold, TrackedContact};+/// use parry3d::query::details::contact_manifold_ball_ball;+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+///+/// // Position shapes in world space+/// let pos1 = Pose::translation(0.0, 0.0, 0.0);+/// let pos2 = Pose::translation(1.5, 0.0, 0.0);+/// let pos12 = pos1.inverse() * pos2; // Relative position+///+/// let mut manifold = ContactManifold::<(), ()>::new();+/// contact_manifold_ball_ball(&pos12, &ball1, &ball2, 0.0, &mut manifold);+///+/// if let Some(contact) = manifold.points.first() {+/// // Convert local positions to world space+/// let world_p1 = pos1 * contact.local_p1;+/// let world_p2 = pos2 * contact.local_p2;+///+/// println!("Contact in world space:");+/// println!(" On ball1: {:?}", world_p1);+/// println!(" On ball2: {:?}", world_p2);+/// }+/// # }+/// ```+///+/// # Feature IDs+///+/// The `fid1` and `fid2` fields identify which geometric features are in contact:+/// - For a ball: Always the face (surface)+/// - For a box: Could be a vertex, edge, or face+/// - For a triangle: Could be a vertex, edge, or the face+///+/// These IDs are used to track contacts across frames. If the same feature IDs appear+/// in consecutive frames, it's likely the same physical contact point.+pub struct TrackedContact<Data> {+ /// The contact point in the local-space of the first shape.+ ///+ /// This is the point on the first shape's surface (or interior if penetrating)+ /// that is closest to or in contact with the second shape.+ pub local_p1: Vector,++ /// The contact point in the local-space of the second shape.+ ///+ /// This is the point on the second shape's surface (or interior if penetrating)+ /// that is closest to or in contact with the first shape.+ pub local_p2: Vector,++ /// The signed distance between the two contact points.+ ///+ /// - Negative values indicate penetration (shapes are overlapping)+ /// - Positive values indicate separation (used with contact prediction)+ /// - Zero means the shapes are exactly touching+ ///+ /// The magnitude represents the distance along the contact normal.+ pub dist: Real,++ /// The feature ID of the first shape involved in the contact.+ ///+ /// This identifies which geometric feature (vertex, edge, or face) of the first+ /// shape is involved in this contact. Used for contact tracking across frames.+ pub fid1: PackedFeatureId,++ /// The feature ID of the second shape involved in the contact.+ ///+ /// This identifies which geometric feature (vertex, edge, or face) of the second+ /// shape is involved in this contact. Used for contact tracking across frames.+ pub fid2: PackedFeatureId,++ /// User-data associated to this contact.+ ///+ /// This can be used to store any additional information you need to track+ /// per-contact, such as:+ /// - Accumulated impulses for warm-starting in physics solvers+ /// - Contact age or lifetime+ /// - Material properties or friction state+ /// - Custom identifiers or flags+ pub data: Data,+}++impl<Data: Default + Copy> TrackedContact<Data> {+ /// Creates a new tracked contact.+ ///+ /// # Arguments+ ///+ /// * `local_p1` - Contact point on the first shape (in its local space)+ /// * `local_p2` - Contact point on the second shape (in its local space)+ /// * `fid1` - Feature ID of the first shape (which part is in contact)+ /// * `fid2` - Feature ID of the second shape (which part is in contact)+ /// * `dist` - Signed distance between the contact points (negative = penetrating)+ ///+ /// The contact data is initialized to its default value.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::TrackedContact;+ /// use parry3d::shape::PackedFeatureId;+ /// use parry3d::math::Vector;+ ///+ /// let contact = TrackedContact::<()>::new(+ /// Vector::new(1.0, 0.0, 0.0), // Point on shape 1+ /// Vector::new(-1.0, 0.0, 0.0), // Point on shape 2+ /// PackedFeatureId::face(0), // Face 0 of shape 1+ /// PackedFeatureId::face(0), // Face 0 of shape 2+ /// -0.1, // Penetration depth of 0.1+ /// );+ ///+ /// assert_eq!(contact.dist, -0.1);+ /// # }+ /// ```+ pub fn new(+ local_p1: Vector,+ local_p2: Vector,+ fid1: PackedFeatureId,+ fid2: PackedFeatureId,+ dist: Real,+ ) -> Self {+ Self {+ local_p1,+ local_p2,+ fid1,+ fid2,+ dist,+ data: Data::default(),+ }+ }++ /// Creates a new tracked contact where its input may need to be flipped.+ pub fn flipped(+ local_p1: Vector,+ local_p2: Vector,+ fid1: PackedFeatureId,+ fid2: PackedFeatureId,+ dist: Real,+ flipped: bool,+ ) -> Self {+ if !flipped {+ Self::new(local_p1, local_p2, fid1, fid2, dist)+ } else {+ Self::new(local_p2, local_p1, fid2, fid1, dist)+ }+ }++ /// Copy to `self` the geometric information from `contact`.+ pub fn copy_geometry_from(&mut self, contact: Self) {+ self.local_p1 = contact.local_p1;+ self.local_p2 = contact.local_p2;+ self.fid1 = contact.fid1;+ self.fid2 = contact.fid2;+ self.dist = contact.dist;+ }+}++#[derive(Clone, Debug, Default)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+/// A contact manifold between two shapes.+///+/// A `ContactManifold` describes a collection of contact points between two shapes that share+/// the same contact normal and contact kinematics. This is a fundamental data structure for+/// physics simulation, providing stable and persistent contact information across multiple frames.+///+/// # Key Concepts+///+/// ## What is a Contact Manifold?+///+/// Instead of treating each contact point independently, a contact manifold groups together+/// all contact points that share the same properties:+/// - **Same contact normal**: All contacts push the shapes apart in the same direction+/// - **Same contact kinematics**: All contacts describe the same type of interaction+/// - **Coherent geometry**: All contacts belong to the same collision feature pair+///+/// For example, when a box sits on a plane, you get a manifold with 4 contact points (one+/// for each corner of the box touching the plane), all sharing the same upward normal.+///+/// ## Why Use Manifolds?+///+/// Contact manifolds are essential for stable physics simulation:+/// 1. **Stability**: Multiple contact points prevent rotation and provide stable support+/// 2. **Performance**: Grouped contacts can be processed more efficiently+/// 3. **Persistence**: Contact tracking across frames enables warm-starting and reduces jitter+/// 4. **Natural representation**: Matches the physical reality of contact patches+///+/// # Generic Parameters+///+/// - `ManifoldData`: User-defined data associated with the entire manifold+/// - `ContactData`: User-defined data associated with each individual contact point+///+/// Both can be `()` if you don't need to store additional data.+///+/// # Examples+///+/// ## Basic Usage: Two Balls Colliding+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{ContactManifold, TrackedContact};+/// use parry3d::query::details::contact_manifold_ball_ball;+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// // Create two balls+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+///+/// // Position them so they overlap+/// let pos12 = Pose::translation(1.5, 0.0, 0.0); // Overlapping by 0.5+///+/// // Create an empty manifold+/// let mut manifold = ContactManifold::<(), ()>::new();+///+/// // Compute contacts (no prediction distance)+/// contact_manifold_ball_ball(&pos12, &ball1, &ball2, 0.0, &mut manifold);+///+/// // Check the results+/// assert!(!manifold.points.is_empty());+/// println!("Number of contacts: {}", manifold.points.len());+/// println!("Contact normal (local): {:?}", manifold.local_n1);+///+/// if let Some(contact) = manifold.points.first() {+/// println!("Penetration depth: {}", -contact.dist);+/// }+/// # }+/// ```+///+/// ## Contact Prediction+///+/// Contact prediction allows detecting contacts before shapes actually touch,+/// which is useful for continuous collision detection:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::ContactManifold;+/// use parry3d::query::details::contact_manifold_ball_ball;+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+///+/// // Balls are separated by 0.1+/// let pos12 = Pose::translation(2.1, 0.0, 0.0);+///+/// let mut manifold = ContactManifold::<(), ()>::new();+///+/// // With prediction distance of 0.2, we can detect the near-contact+/// let prediction = 0.2;+/// contact_manifold_ball_ball(&pos12, &ball1, &ball2, prediction, &mut manifold);+///+/// if !manifold.points.is_empty() {+/// let contact = &manifold.points[0];+/// println!("Predicted contact distance: {}", contact.dist);+/// assert!(contact.dist > 0.0); // Positive = separated but predicted+/// }+/// # }+/// ```+///+/// ## Efficient Contact Updates with Spatial Coherence+///+/// One of the main benefits of contact manifolds is efficient updates:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::ContactManifold;+/// use parry3d::query::details::contact_manifold_ball_ball;+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+/// let mut manifold = ContactManifold::<(), ()>::new();+///+/// // Frame 1: Initial contact+/// let pos12_frame1 = Pose::translation(1.9, 0.0, 0.0);+/// contact_manifold_ball_ball(&pos12_frame1, &ball1, &ball2, 0.1, &mut manifold);+/// println!("Frame 1: {} contacts", manifold.points.len());+///+/// // Frame 2: Small movement - try to update efficiently+/// let pos12_frame2 = Pose::translation(1.85, 0.0, 0.0);+///+/// if manifold.try_update_contacts(&pos12_frame2) {+/// println!("Successfully updated contacts using spatial coherence");+/// } else {+/// println!("Shapes moved too much, recomputing from scratch");+/// contact_manifold_ball_ball(&pos12_frame2, &ball1, &ball2, 0.1, &mut manifold);+/// }+/// # }+/// ```+///+/// ## Working with Multiple Contacts+///+/// Some shape pairs produce multiple contact points:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::ContactManifold;+/// use parry3d::query::details::contact_manifold_cuboid_cuboid;+/// use parry3d::shape::Cuboid;+/// use parry3d::math::{Pose, Vector};+///+/// // Two boxes+/// let cuboid1 = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+/// let cuboid2 = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+///+/// // One box sitting on top of another+/// let pos12 = Pose::translation(0.0, 1.9, 0.0); // Slight overlap+///+/// let mut manifold = ContactManifold::<(), ()>::new();+/// contact_manifold_cuboid_cuboid(&pos12, &cuboid1, &cuboid2, 0.0, &mut manifold);+///+/// println!("Number of contact points: {}", manifold.points.len());+///+/// // Find the deepest penetration+/// if let Some(deepest) = manifold.find_deepest_contact() {+/// println!("Deepest penetration: {}", -deepest.dist);+/// }+///+/// // Iterate over all contacts+/// for (i, contact) in manifold.points.iter().enumerate() {+/// println!("Contact {}: dist={}, fid1={:?}, fid2={:?}",+/// i, contact.dist, contact.fid1, contact.fid2);+/// }+/// # }+/// ```+///+/// ## Storing Custom Data+///+/// You can attach custom data to both the manifold and individual contacts:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::ContactManifold;+/// use parry3d::query::details::contact_manifold_ball_ball;+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// // Custom data structures+/// #[derive(Clone, Default, Copy)]+/// struct MyManifoldData {+/// collision_id: u32,+/// first_contact_frame: u32,+/// }+///+/// #[derive(Clone, Default, Copy)]+/// struct MyContactData {+/// accumulated_impulse: f32,+/// contact_age: u32,+/// }+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+/// let pos12 = Pose::translation(1.8, 0.0, 0.0);+///+/// // Create manifold with custom data+/// let manifold_data = MyManifoldData {+/// collision_id: 42,+/// first_contact_frame: 100,+/// };+/// let mut manifold: ContactManifold<MyManifoldData, MyContactData> =+/// ContactManifold::with_data(0, 0, manifold_data);+///+/// contact_manifold_ball_ball(&pos12, &ball1, &ball2, 0.0, &mut manifold);+///+/// // Access manifold data+/// println!("Collision ID: {}", manifold.data.collision_id);+///+/// // Set contact-specific data+/// if let Some(contact) = manifold.points.first_mut() {+/// contact.data.accumulated_impulse = 10.0;+/// contact.data.contact_age = 5;+/// }+/// # }+/// ```+///+/// # Contact Normal Convention+///+/// The contact normal (`local_n1` and `local_n2`) points from the first shape toward the+/// second shape. To separate the shapes:+/// - Move shape 1 in the direction of `-local_n1`+/// - Move shape 2 in the direction of `local_n2` (which equals `-local_n1` in world space)+///+/// # Working with Composite Shapes+///+/// When dealing with composite shapes (like triangle meshes or compounds), the manifold+/// tracks which subshapes are involved:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::ContactManifold;+///+/// // For composite shapes, the manifold tracks subshape indices+/// let manifold = ContactManifold::<(), ()>::with_data(+/// 5, // subshape1: 5th subshape of first shape+/// 12, // subshape2: 12th subshape of second shape+/// (), // manifold data+/// );+///+/// println!("Contact between subshape {} and {}",+/// manifold.subshape1, manifold.subshape2);+/// # }+/// ```+pub struct ContactManifold<ManifoldData, ContactData> {+ // NOTE: use a SmallVec instead?+ // And for 2D use an ArrayVec since there will never be more than 2 contacts anyways.+ /// The contacts points.+ #[cfg(feature = "dim2")]+ pub points: arrayvec::ArrayVec<TrackedContact<ContactData>, 2>,+ /// The contacts points.+ #[cfg(feature = "dim3")]+ pub points: Vec<TrackedContact<ContactData>>,+ /// The contact normal of all the contacts of this manifold, expressed in the local space of the first shape.+ pub local_n1: Vector,+ /// The contact normal of all the contacts of this manifold, expressed in the local space of the second shape.+ pub local_n2: Vector,+ /// The first subshape involved in this contact manifold.+ ///+ /// This is zero if the first shape is not a composite shape.+ pub subshape1: u32,+ /// The second subshape involved in this contact manifold.+ ///+ /// This is zero if the second shape is not a composite shape.+ pub subshape2: u32,+ /// If either shape involved is a composite shape, this contains the positions of the+ /// subshapes involved in this contact.+ pub subshape_poses: Option<alloc::boxed::Box<SubshapePoses>>,+ /// Additional tracked data associated to this contact manifold.+ pub data: ManifoldData,+}++/// The positions of the composite-shape subshapes involved in a contact manifold.+#[derive(Clone, Debug, Default)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+pub struct SubshapePoses {+ /// The position of the first shape's subshape, if it is a composite shape.+ pub pos1: Option<Pose>,+ /// The position of the second shape's subshape, if it is a composite shape.+ pub pos2: Option<Pose>,+}++impl<ManifoldData, ContactData> ContactManifold<ManifoldData, ContactData> {+ /// The position of the first shape's subshape involved in this contact, if the first+ /// shape is a composite shape.+ #[inline]+ pub fn subshape_pos1(&self) -> Option<&Pose> {+ self.subshape_poses.as_ref().and_then(|p| p.pos1.as_ref())+ }++ /// The position of the second shape's subshape involved in this contact, if the second+ /// shape is a composite shape.+ #[inline]+ pub fn subshape_pos2(&self) -> Option<&Pose> {+ self.subshape_poses.as_ref().and_then(|p| p.pos2.as_ref())+ }++ /// Sets the position of the first shape's subshape, reusing the existing allocation.+ #[inline]+ pub fn set_subshape_pos1(&mut self, pos: Option<Pose>) {+ match (&mut self.subshape_poses, pos) {+ (Some(poses), pos) => poses.pos1 = pos,+ (slot @ None, Some(pos)) => {+ *slot = Some(alloc::boxed::Box::new(SubshapePoses {+ pos1: Some(pos),+ pos2: None,+ }))+ }+ (None, None) => {}+ }+ }++ /// Sets the position of the second shape's subshape, reusing the existing allocation.+ #[inline]+ pub fn set_subshape_pos2(&mut self, pos: Option<Pose>) {+ match (&mut self.subshape_poses, pos) {+ (Some(poses), pos) => poses.pos2 = pos,+ (slot @ None, Some(pos)) => {+ *slot = Some(alloc::boxed::Box::new(SubshapePoses {+ pos1: None,+ pos2: Some(pos),+ }))+ }+ (None, None) => {}+ }+ }+}++impl<ManifoldData, ContactData: Default + Copy> ContactManifold<ManifoldData, ContactData> {+ /// Create a new empty contact-manifold.+ pub fn new() -> Self+ where+ ManifoldData: Default,+ {+ Self::default()+ }++ /// Create a new empty contact-manifold with the given associated data.+ pub fn with_data(subshape1: u32, subshape2: u32, data: ManifoldData) -> Self {+ Self {+ #[cfg(feature = "dim2")]+ points: arrayvec::ArrayVec::new(),+ #[cfg(feature = "dim3")]+ points: Vec::new(),+ local_n1: Vector::ZERO,+ local_n2: Vector::ZERO,+ subshape1,+ subshape2,+ subshape_poses: None,+ data,+ }+ }++ /// Clones `self` and then remove all contact points from `self`.+ pub fn take(&mut self) -> Self+ where+ ManifoldData: Clone,+ {+ #[cfg(feature = "dim2")]+ let points = self.points.clone();+ #[cfg(feature = "dim3")]+ let points = core::mem::take(&mut self.points);+ self.points.clear();++ ContactManifold {+ points,+ local_n1: self.local_n1,+ local_n2: self.local_n2,+ subshape1: self.subshape1,+ subshape2: self.subshape2,+ subshape_poses: self.subshape_poses.clone(),+ data: self.data.clone(),+ }+ }++ /*+ pub(crate) fn single_manifold<'a, 'b>(+ manifolds: &mut Vec<Self>,+ data: &dyn Fn() -> ManifoldData,+ ) -> &'a mut Self {+ if manifolds.is_empty() {+ let manifold_data = data();+ manifolds.push(ContactManifold::with_data((0, 0), manifold_data));+ }++ &mut manifolds[0]+ }+ */++ /// Returns a slice of all the contact points in this manifold.+ ///+ /// This provides read-only access to all contact points. The contacts are stored+ /// in the order they were added during manifold computation.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::ContactManifold;+ /// use parry3d::query::details::contact_manifold_ball_ball;+ /// use parry3d::shape::Ball;+ /// use parry3d::math::Pose;+ ///+ /// let ball1 = Ball::new(1.0);+ /// let ball2 = Ball::new(1.0);+ /// let pos12 = Pose::translation(1.8, 0.0, 0.0);+ ///+ /// let mut manifold = ContactManifold::<(), ()>::new();+ /// contact_manifold_ball_ball(&pos12, &ball1, &ball2, 0.0, &mut manifold);+ ///+ /// // Access all contacts+ /// for (i, contact) in manifold.contacts().iter().enumerate() {+ /// println!("Contact {}: distance = {}", i, contact.dist);+ /// }+ /// # }+ /// ```+ #[inline]+ pub fn contacts(&self) -> &[TrackedContact<ContactData>] {+ &self.points+ }++ /// Attempts to efficiently update contact points using spatial coherence.+ ///+ /// This method tries to update the contact points based on the new relative position+ /// of the shapes (`pos12`) without recomputing the entire contact manifold. This is+ /// much faster than full recomputation but only works when:+ /// - The shapes haven't moved or rotated too much+ /// - The contact normal hasn't changed significantly+ /// - The contact configuration is still valid+ ///+ /// Returns `true` if the update succeeded, `false` if full recomputation is needed.+ ///+ /// # When to Use This+ ///+ /// Use this method every frame after the initial contact computation. It exploits+ /// temporal coherence in physics simulation where shapes typically move smoothly.+ /// When it returns `false`, fall back to full contact manifold recomputation.+ ///+ /// # Thresholds+ ///+ /// This method uses default thresholds for angle and distance changes. For custom+ /// thresholds, use [`try_update_contacts_eps`](Self::try_update_contacts_eps).+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::ContactManifold;+ /// use parry3d::query::details::contact_manifold_ball_ball;+ /// use parry3d::shape::Ball;+ /// use parry3d::math::Pose;+ ///+ /// let ball1 = Ball::new(1.0);+ /// let ball2 = Ball::new(1.0);+ /// let mut manifold = ContactManifold::<(), ()>::new();+ ///+ /// // Initial computation+ /// let pos12_old = Pose::translation(1.9, 0.0, 0.0);+ /// contact_manifold_ball_ball(&pos12_old, &ball1, &ball2, 0.1, &mut manifold);+ ///+ /// // Next frame: shapes moved slightly+ /// let pos12_new = Pose::translation(1.85, 0.05, 0.0);+ ///+ /// if manifold.try_update_contacts(&pos12_new) {+ /// println!("Updated contacts efficiently!");+ /// } else {+ /// println!("Need to recompute from scratch");+ /// contact_manifold_ball_ball(&pos12_new, &ball1, &ball2, 0.1, &mut manifold);+ /// }+ /// # }+ /// ```+ #[inline]+ pub fn try_update_contacts(&mut self, pos12: &Pose) -> bool {+ // const DOT_THRESHOLD: Real = 0.crate::COS_10_DEGREES;+ // const DOT_THRESHOLD: Real = crate::utils::COS_5_DEGREES;+ const DOT_THRESHOLD: Real = crate::utils::COS_1_DEGREES;+ const DIST_SQ_THRESHOLD: Real = 1.0e-6; // TODO: this should not be hard-coded.+ self.try_update_contacts_eps(pos12, DOT_THRESHOLD, DIST_SQ_THRESHOLD)+ }++ /// Attempts to use spatial coherence to update contacts points, using user-defined tolerances.+ #[inline]+ pub fn try_update_contacts_eps(+ &mut self,+ pos12: &Pose,+ angle_dot_threshold: Real,+ dist_sq_threshold: Real,+ ) -> bool {+ if self.points.is_empty() {+ return false;+ }++ let local_n2 = pos12.rotation * self.local_n2;++ if -self.local_n1.dot(local_n2) < angle_dot_threshold {+ return false;+ }++ for pt in &self.points {+ let local_p2 = pos12 * pt.local_p2;+ let dpt = local_p2 - pt.local_p1;+ let dist = dpt.dot(self.local_n1);++ if dist * pt.dist < 0.0 {+ // We switched between penetrating/non-penetrating.+ // The may result in other contacts to appear.+ return false;+ }+ let new_local_p1 = local_p2 - self.local_n1 * dist;++ if pt.local_p1.distance_squared(new_local_p1) > dist_sq_threshold {+ return false;+ }+ }++ self.update_separations(pos12);++ true+ }++ /// Forces the next contact-manifold computation to recompute this manifold's contact points+ /// instead of reusing them through [`Self::try_update_contacts`]; call it when a shape's+ /// geometry changed with its pose fixed. The points are kept for [`Self::match_contacts`].+ #[inline]+ pub fn mark_shapes_deformed(&mut self) {+ // The coherence check compares the two cached normals; a zero second normal never passes it.+ self.local_n2 = Vector::ZERO;+ }++ /// Refreshes every contact point's separation (`dist`) from the current+ /// relative pose of the two shapes, keeping the contact points (anchors)+ /// frozen at their captured material positions.+ #[inline]+ pub fn update_separations(&mut self, pos12: &Pose) {+ for pt in &mut self.points {+ let local_p2 = pos12 * pt.local_p2;+ pt.dist = (local_p2 - pt.local_p1).dot(self.local_n1);+ }+ }++ /// Transfers contact data from previous frame's contacts to current contacts based on feature IDs.+ ///+ /// This method is crucial for maintaining persistent contact information across frames.+ /// It matches contacts between the old and new manifolds by comparing their feature IDs+ /// (which geometric features are in contact). When a match is found, the user data is+ /// transferred from the old contact to the new one.+ ///+ /// This enables important physics features like:+ /// - **Warm-starting**: Reusing accumulated impulses speeds up constraint solving+ /// - **Contact aging**: Tracking how long a contact has existed+ /// - **Friction state**: Maintaining tangential impulse information+ ///+ /// # When to Use+ ///+ /// Call this method after recomputing the contact manifold, passing the old contact+ /// points from the previous frame. This preserves contact-specific solver state.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::ContactManifold;+ /// use parry3d::query::details::contact_manifold_ball_ball;+ /// use parry3d::shape::Ball;+ /// use parry3d::math::Pose;+ ///+ /// #[derive(Clone, Default, Copy)]+ /// struct MyContactData {+ /// accumulated_impulse: f32,+ /// age: u32,+ /// }+ ///+ /// let ball1 = Ball::new(1.0);+ /// let ball2 = Ball::new(1.0);+ /// let mut manifold = ContactManifold::<(), MyContactData>::new();+ ///+ /// // Frame 1: Compute contacts+ /// let pos12_frame1 = Pose::translation(1.9, 0.0, 0.0);+ /// contact_manifold_ball_ball(&pos12_frame1, &ball1, &ball2, 0.0, &mut manifold);+ ///+ /// // Simulate physics, accumulate impulse+ /// if let Some(contact) = manifold.points.first_mut() {+ /// contact.data.accumulated_impulse = 42.0;+ /// contact.data.age = 1;+ /// }+ ///+ /// // Frame 2: Save old contacts, recompute+ /// let old_contacts = manifold.points.clone();+ /// let pos12_frame2 = Pose::translation(1.85, 0.0, 0.0);+ /// contact_manifold_ball_ball(&pos12_frame2, &ball1, &ball2, 0.0, &mut manifold);+ ///+ /// // Transfer data from old to new based on feature ID matching+ /// manifold.match_contacts(&old_contacts);+ ///+ /// // Data is preserved!+ /// if let Some(contact) = manifold.points.first() {+ /// assert_eq!(contact.data.accumulated_impulse, 42.0);+ /// }+ /// # }+ /// ```+ pub fn match_contacts(&mut self, old_contacts: &[TrackedContact<ContactData>]) {+ for contact in &mut self.points {+ for old_contact in old_contacts {+ if contact.fid1 == old_contact.fid1 && contact.fid2 == old_contact.fid2 {+ // Transfer the tracked data.+ contact.data = old_contact.data;+ }+ }+ }+ }++ /// Copy data associated to contacts from `old_contacts` to the new contacts in `self`+ /// based on matching the contact positions.+ pub fn match_contacts_using_positions(+ &mut self,+ old_contacts: &[TrackedContact<ContactData>],+ dist_threshold: Real,+ ) {+ let sq_threshold = dist_threshold * dist_threshold;+ for contact in &mut self.points {+ for old_contact in old_contacts {+ if contact.local_p1.distance_squared(old_contact.local_p1) < sq_threshold+ && contact.local_p2.distance_squared(old_contact.local_p2) < sq_threshold+ {+ // Transfer the tracked data.+ contact.data = old_contact.data;+ }+ }+ }+ }++ /// Removes all the contacts from `self`.+ pub fn clear(&mut self) {+ self.points.clear();+ }++ /// Finds and returns the contact with the deepest penetration.+ ///+ /// This returns the contact with the smallest (most negative) distance value,+ /// which corresponds to the largest penetration depth. Returns `None` if the+ /// manifold has no contact points.+ ///+ /// # Use Cases+ ///+ /// - Finding the primary contact for simplified physics resolution+ /// - Determining the severity of an overlap for collision response+ /// - Prioritizing contacts in contact reduction algorithms+ /// - Debug visualization of the most significant contact+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::ContactManifold;+ /// use parry3d::query::details::contact_manifold_cuboid_cuboid;+ /// use parry3d::shape::Cuboid;+ /// use parry3d::math::{Pose, Vector};+ ///+ /// let cuboid1 = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+ /// let cuboid2 = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+ ///+ /// // Position with some penetration+ /// let pos12 = Pose::translation(0.0, 1.8, 0.0);+ ///+ /// let mut manifold = ContactManifold::<(), ()>::new();+ /// contact_manifold_cuboid_cuboid(&pos12, &cuboid1, &cuboid2, 0.0, &mut manifold);+ ///+ /// if let Some(deepest) = manifold.find_deepest_contact() {+ /// let penetration_depth = -deepest.dist;+ /// println!("Maximum penetration: {}", penetration_depth);+ /// println!("Deepest contact point (shape 1): {:?}", deepest.local_p1);+ /// }+ /// # }+ /// ```+ pub fn find_deepest_contact(&self) -> Option<&TrackedContact<ContactData>> {+ let mut deepest = self.points.first()?;++ for pt in &self.points {+ if pt.dist < deepest.dist {+ deepest = pt;+ }+ }++ Some(deepest)+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_ball_ball.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_ball_ball.rsnew file mode 100644index 0000000..7733a8d--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_ball_ball.rs@@ -0,0 +1,57 @@+use crate::math::{Pose, Real, Vector};+use crate::query::{ContactManifold, TrackedContact};+use crate::shape::{Ball, PackedFeatureId, Shape};++/// Computes the contact manifold between two balls given as `Shape` trait-objects.+pub fn contact_manifold_ball_ball_shapes<ManifoldData, ContactData: Default + Copy>(+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+) {+ if let (Some(ball1), Some(ball2)) = (shape1.as_ball(), shape2.as_ball()) {+ contact_manifold_ball_ball(pos12, ball1, ball2, prediction, manifold);+ }+}++/// Computes the contact manifold between two balls.+pub fn contact_manifold_ball_ball<ManifoldData, ContactData: Default + Copy>(+ pos12: &Pose,+ ball1: &Ball,+ ball2: &Ball,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+) {+ let radius_a = ball1.radius;+ let radius_b = ball2.radius;++ let dcenter = pos12.translation;+ let center_dist = dcenter.length();+ let dist = center_dist - radius_a - radius_b;++ if dist < prediction {+ let local_n1 = if center_dist != 0.0 {+ dcenter / center_dist+ } else {+ Vector::Y+ };++ let local_n2 = pos12.rotation.inverse() * -local_n1;+ let local_p1 = local_n1 * radius_a;+ let local_p2 = local_n2 * radius_b;+ let fid = PackedFeatureId::face(0);+ let contact = TrackedContact::new(local_p1, local_p2, fid, fid, dist);++ if !manifold.points.is_empty() {+ manifold.points[0].copy_geometry_from(contact);+ } else {+ manifold.points.push(contact);+ }++ manifold.local_n1 = local_n1;+ manifold.local_n2 = local_n2;+ } else {+ manifold.points.clear();+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_capsule_capsule.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_capsule_capsule.rsnew file mode 100644index 0000000..90dea43--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_capsule_capsule.rs@@ -0,0 +1,180 @@+use crate::math::{Pose, Real, Vector};+use crate::query::{ContactManifold, TrackedContact};+#[cfg(feature = "dim2")]+use crate::shape::SegmentPointLocation;+use crate::shape::{Capsule, PackedFeatureId, Shape};+#[cfg(feature = "dim2")]+use approx::AbsDiffEq;++/// Computes the contact manifold between two capsules given as `Shape` trait-objects.+pub fn contact_manifold_capsule_capsule_shapes<ManifoldData, ContactData>(+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+) where+ ContactData: Default + Copy,+{+ if let (Some(capsule1), Some(capsule2)) = (shape1.as_capsule(), shape2.as_capsule()) {+ contact_manifold_capsule_capsule(pos12, capsule1, capsule2, prediction, manifold);+ }+}++/// Computes the contact manifold between two capsules.+#[cfg(feature = "dim2")]+pub fn contact_manifold_capsule_capsule<'a, ManifoldData, ContactData>(+ pos12: &Pose,+ capsule1: &'a Capsule,+ capsule2: &'a Capsule,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+) where+ ContactData: Default + Copy,+{+ let seg1 = capsule1.segment;+ let seg2_1 = capsule2.segment.transformed(pos12);+ let (loc1, loc2) = crate::query::details::closest_points_segment_segment_with_locations_nD(+ (&seg1.a, &seg1.b),+ (&seg2_1.a, &seg2_1.b),+ );++ // We do this clone to perform contact tracking and transfer impulses.+ // TODO: find a more efficient way of doing this.+ let old_manifold_points = manifold.points.clone();+ manifold.clear();++ let fid1 = if let SegmentPointLocation::OnVertex(v1) = loc1 {+ v1 * 2+ } else {+ 1+ };+ let fid2 = if let SegmentPointLocation::OnVertex(v2) = loc2 {+ v2 * 2+ } else {+ 1+ };++ let bcoords1 = loc1.barycentric_coordinates();+ let bcoords2 = loc2.barycentric_coordinates();+ let local_p1 = seg1.a * bcoords1[0] + seg1.b * bcoords1[1];+ let local_p2_1 = seg2_1.a * bcoords2[0] + seg2_1.b * bcoords2[1];++ let local_n1 = (local_p2_1 - local_p1).try_normalize().unwrap_or(Vector::Y);+ let dist = (local_p2_1 - local_p1).dot(local_n1);++ if dist <= prediction + capsule1.radius + capsule2.radius {+ let local_n2 = pos12.rotation.inverse() * -local_n1;+ let local_p2 = pos12.inverse_transform_point(local_p2_1);+ let contact = TrackedContact::new(+ local_p1,+ local_p2,+ PackedFeatureId::face(fid1),+ PackedFeatureId::face(fid2),+ dist,+ );+ manifold.points.push(contact);++ manifold.local_n1 = local_n1;+ manifold.local_n2 = local_n2;+ } else {+ // No contact within tolerance.+ return;+ }++ if let (Some(dir1), Some(dir2)) = (seg1.direction(), seg2_1.direction()) {+ if dir1.dot(dir2).abs() >= crate::utils::COS_FRAC_PI_8+ && dir1.dot(local_n1).abs() < crate::utils::SIN_FRAC_PI_8+ {+ // Capsules axes are almost parallel and are almost perpendicular to the normal.+ // Find a second contact point.+ if let Some((clip_a, clip_b)) = crate::query::details::clip_segment_segment_with_normal(+ (seg1.a, seg1.b),+ (seg2_1.a, seg2_1.b),+ local_n1,+ ) {+ let contact =+ if (clip_a.0 - local_p1).length_squared() > Real::default_epsilon() * 100.0 {+ // Use clip_a as the second contact.+ TrackedContact::new(+ clip_a.0,+ pos12.inverse_transform_point(clip_a.1),+ PackedFeatureId::face(clip_a.2 as u32),+ PackedFeatureId::face(clip_a.3 as u32),+ (clip_a.1 - clip_a.0).dot(local_n1),+ )+ } else {+ // Use clip_b as the second contact.+ TrackedContact::new(+ clip_b.0,+ pos12.inverse_transform_point(clip_b.1),+ PackedFeatureId::face(clip_b.2 as u32),+ PackedFeatureId::face(clip_b.3 as u32),+ (clip_b.1 - clip_b.0).dot(local_n1),+ )+ };++ manifold.points.push(contact);+ }+ }+ }++ for point in &mut manifold.points {+ point.local_p1 += manifold.local_n1 * capsule1.radius;+ point.local_p2 += manifold.local_n2 * capsule2.radius;+ point.dist -= capsule1.radius + capsule2.radius;+ }++ manifold.match_contacts(&old_manifold_points);+}++/// Computes the contact manifold between two capsules.+#[cfg(feature = "dim3")]+pub fn contact_manifold_capsule_capsule<'a, ManifoldData, ContactData>(+ pos12: &Pose,+ capsule1: &'a Capsule,+ capsule2: &'a Capsule,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+) where+ ContactData: Default + Copy,+{+ let seg1 = capsule1.segment;+ let seg2_1 = capsule2.segment.transformed(pos12);+ let (loc1, loc2) =+ crate::query::closest_points::closest_points_segment_segment_with_locations_nD(+ (&seg1.a, &seg1.b),+ (&seg2_1.a, &seg2_1.b),+ );++ let bcoords1 = loc1.barycentric_coordinates();+ let bcoords2 = loc2.barycentric_coordinates();+ let local_p1 = seg1.a * bcoords1[0] + seg1.b * bcoords1[1];+ let local_p2_1 = seg2_1.a * bcoords2[0] + seg2_1.b * bcoords2[1];++ let local_n1 = (local_p2_1 - local_p1).try_normalize().unwrap_or(Vector::Y);+ let dist = (local_p2_1 - local_p1).dot(local_n1) - capsule1.radius - capsule2.radius;++ if dist <= prediction {+ let local_n2 = pos12.rotation.inverse() * -local_n1;+ let fid = PackedFeatureId::face(0);+ let contact = TrackedContact::new(+ local_p1 + local_n1 * capsule1.radius,+ pos12.inverse_transform_point(local_p2_1) + local_n2 * capsule2.radius,+ fid,+ fid,+ dist,+ );++ if !manifold.points.is_empty() {+ manifold.points[0].copy_geometry_from(contact);+ } else {+ manifold.points.push(contact);+ }++ manifold.local_n1 = local_n1;+ manifold.local_n2 = local_n2;+ } else {+ manifold.clear();+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_composite_shape_composite_shape.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_composite_shape_composite_shape.rsnew file mode 100644index 0000000..e6b57a0--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_composite_shape_composite_shape.rs@@ -0,0 +1,204 @@+use alloc::boxed::Box;+use alloc::vec::Vec;++use crate::bounding_volume::BoundingVolume;+use crate::math::{Pose, Real};+use crate::query::contact_manifolds::contact_manifolds_workspace::{+ TypedWorkspaceData, WorkspaceData,+};+use crate::query::contact_manifolds::ContactManifoldsWorkspace;+use crate::query::query_dispatcher::PersistentQueryDispatcher;+use crate::query::ContactManifold;+use crate::shape::CompositeShape;+use crate::utils::hashmap::{Entry, HashMap};+use crate::utils::PoseOpt;++#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Clone)]+struct SubDetector {+ manifold_id: usize,+ timestamp: bool,+}++#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[derive(Clone, Default)]+pub struct CompositeShapeCompositeShapeContactManifoldsWorkspace {+ timestamp: bool,+ sub_detectors: HashMap<(u32, u32), SubDetector>,+}++impl CompositeShapeCompositeShapeContactManifoldsWorkspace {+ pub fn new() -> Self {+ Self::default()+ }+}++fn ensure_workspace_exists(workspace: &mut Option<ContactManifoldsWorkspace>) {+ if workspace+ .as_ref()+ .and_then(|w| {+ w.0.downcast_ref::<CompositeShapeCompositeShapeContactManifoldsWorkspace>()+ })+ .is_some()+ {+ return;+ }++ *workspace = Some(ContactManifoldsWorkspace(Box::new(+ CompositeShapeCompositeShapeContactManifoldsWorkspace::new(),+ )));+}++/// Computes the contact manifolds between two composite shapes.+pub fn contact_manifolds_composite_shape_composite_shape<'a, ManifoldData, ContactData>(+ dispatcher: &dyn PersistentQueryDispatcher<ManifoldData, ContactData>,+ pos12: &Pose,+ mut composite1: &'a dyn CompositeShape,+ mut composite2: &'a dyn CompositeShape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+) where+ ManifoldData: Default + Clone,+ ContactData: Default + Copy,+{+ ensure_workspace_exists(workspace);+ let workspace: &mut CompositeShapeCompositeShapeContactManifoldsWorkspace =+ workspace.as_mut().unwrap().0.downcast_mut().unwrap();+ let new_timestamp = !workspace.timestamp;+ workspace.timestamp = new_timestamp;++ /*+ * Compute interferences.+ */++ let mut bvh1 = composite1.bvh();+ let mut bvh2 = composite2.bvh();++ let mut pos12 = *pos12;+ let mut pos21 = pos12.inverse();++ let mut ls_aabb1 = bvh1.root_aabb();+ let mut ls_aabb2 = bvh2.root_aabb();+ let flipped =+ ls_aabb1.half_extents().length_squared() < ls_aabb2.half_extents().length_squared();++ if flipped {+ core::mem::swap(&mut composite1, &mut composite2);+ core::mem::swap(&mut bvh1, &mut bvh2);+ core::mem::swap(&mut pos12, &mut pos21);+ core::mem::swap(&mut ls_aabb1, &mut ls_aabb2);+ }++ // Traverse bvh1 first.+ let ls_aabb2_1 = ls_aabb2.transform_by(&pos12).loosened(prediction);+ let mut old_manifolds = core::mem::take(manifolds);+ let deformable = composite1.is_deformable() || composite2.is_deformable();++ let mut leaf_fn1 = |leaf1: u32| {+ composite1.map_part_at(leaf1, &mut |part_pos1, part_shape1, normal_constraints1| {+ let pos211 = part_pos1.prepend_to(&pos21); // == pos21 * part_pos1+ let ls_part_aabb1_2 = part_shape1.compute_aabb(&pos211).loosened(prediction);+ let mut leaf_fn2 = |leaf2: u32| {+ composite2.map_part_at(+ leaf2,+ &mut |part_pos2, part_shape2, normal_constraints2| {+ let pos2211 = part_pos2.inv_mul(&pos211);+ let entry_key = if flipped {+ (leaf2, leaf1)+ } else {+ (leaf1, leaf2)+ };++ let sub_detector = match workspace.sub_detectors.entry(entry_key) {+ Entry::Occupied(entry) => {+ let sub_detector = entry.into_mut();+ let manifold = old_manifolds[sub_detector.manifold_id].take();+ sub_detector.manifold_id = manifolds.len();+ sub_detector.timestamp = new_timestamp;+ manifolds.push(manifold);+ sub_detector+ }+ Entry::Vacant(entry) => {+ let sub_detector = SubDetector {+ manifold_id: manifolds.len(),+ timestamp: new_timestamp,+ };++ let mut manifold = ContactManifold::new();++ if flipped {+ manifold.subshape1 = leaf2;+ manifold.subshape2 = leaf1;+ manifold.set_subshape_pos1(part_pos2.copied());+ manifold.set_subshape_pos2(part_pos1.copied());+ } else {+ manifold.subshape1 = leaf1;+ manifold.subshape2 = leaf2;+ manifold.set_subshape_pos1(part_pos1.copied());+ manifold.set_subshape_pos2(part_pos2.copied());+ };++ manifolds.push(manifold);+ entry.insert(sub_detector)+ }+ };++ let manifold = &mut manifolds[sub_detector.manifold_id];+ if deformable {+ manifold.mark_shapes_deformed();+ }++ if flipped {+ let _ = dispatcher.contact_manifold_convex_convex(+ &pos2211,+ part_shape2,+ part_shape1,+ normal_constraints2,+ normal_constraints1,+ prediction,+ manifold,+ );+ } else {+ let _ = dispatcher.contact_manifold_convex_convex(+ &pos2211.inverse(),+ part_shape1,+ part_shape2,+ normal_constraints1,+ normal_constraints2,+ prediction,+ manifold,+ );+ }+ },+ );+ };++ for leaf_id in composite2.bvh().intersect_aabb(&ls_part_aabb1_2) {+ leaf_fn2(leaf_id);+ }+ });+ };++ for leaf_id in composite1.bvh().intersect_aabb(&ls_aabb2_1) {+ leaf_fn1(leaf_id);+ }++ workspace+ .sub_detectors+ .retain(|_, detector| detector.timestamp == new_timestamp)+}++impl WorkspaceData for CompositeShapeCompositeShapeContactManifoldsWorkspace {+ fn as_typed_workspace_data(&self) -> TypedWorkspaceData<'_> {+ TypedWorkspaceData::CompositeShapeCompositeShapeContactManifoldsWorkspace(self)+ }++ fn clone_dyn(&self) -> Box<dyn WorkspaceData> {+ Box::new(self.clone())+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_composite_shape_shape.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_composite_shape_shape.rsnew file mode 100644index 0000000..8d8d78d--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_composite_shape_shape.rs@@ -0,0 +1,208 @@+use alloc::{boxed::Box, vec::Vec};++use crate::bounding_volume::BoundingVolume;+use crate::math::{Pose, Real};+use crate::query::contact_manifolds::contact_manifolds_workspace::{+ TypedWorkspaceData, WorkspaceData,+};+use crate::query::contact_manifolds::ContactManifoldsWorkspace;+use crate::query::query_dispatcher::PersistentQueryDispatcher;+use crate::query::ContactManifold;+use crate::shape::{CompositeShape, Shape};+use crate::utils::hashmap::{Entry, HashMap};+use crate::utils::PoseOpt;++#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Clone)]+struct SubDetector {+ manifold_id: usize,+ timestamp: bool,+}++#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[derive(Clone, Default)]+pub struct CompositeShapeShapeContactManifoldsWorkspace {+ timestamp: bool,+ sub_detectors: HashMap<u32, SubDetector>,+}++impl CompositeShapeShapeContactManifoldsWorkspace {+ pub fn new() -> Self {+ Self::default()+ }+}++fn ensure_workspace_exists(workspace: &mut Option<ContactManifoldsWorkspace>) {+ if workspace+ .as_ref()+ .and_then(|w| {+ w.0.downcast_ref::<CompositeShapeShapeContactManifoldsWorkspace>()+ })+ .is_some()+ {+ return;+ }++ *workspace = Some(ContactManifoldsWorkspace(Box::new(+ CompositeShapeShapeContactManifoldsWorkspace::new(),+ )));+}++/// Leaves reached by the query from which the sub-shape manifolds are computed in parallel+/// (`parallel` feature).+#[cfg(feature = "parallel")]+const PARALLEL_LEAVES: usize = 256;++/// Computes the contact manifolds between a composite shape and an abstract shape.+///+/// The manifolds are in the order of the composite's leaves reached by the query. Under the+/// `parallel` feature, a query reaching many leaves computes their manifolds across threads+/// (same manifolds, same order).+pub fn contact_manifolds_composite_shape_shape<ManifoldData, ContactData>(+ dispatcher: &dyn PersistentQueryDispatcher<ManifoldData, ContactData>,+ pos12: &Pose,+ composite1: &(dyn CompositeShape + Sync),+ shape2: &dyn Shape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+ flipped: bool,+) where+ ManifoldData: Default + Clone + Send + Sync,+ ContactData: Default + Copy + Send + Sync,+{+ ensure_workspace_exists(workspace);+ let workspace: &mut CompositeShapeShapeContactManifoldsWorkspace =+ workspace.as_mut().unwrap().0.downcast_mut().unwrap();+ let new_timestamp = !workspace.timestamp;+ workspace.timestamp = new_timestamp;++ /*+ * Compute interferences.+ */++ let pos12 = *pos12;+ let pos21 = pos12.inverse();+ let deformable = composite1.is_deformable();++ // Traverse bvh1 first.+ let ls_aabb2_1 = shape2.compute_aabb(&pos12).loosened(prediction);+ let mut old_manifolds = core::mem::take(manifolds);++ // The manifold of a leaf: the one kept from the last query, or a fresh one (its sub-shape+ // ids and pose set by the first computation), pushed in leaf order.+ let mut bookkeep =+ |leaf1: u32, manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>| {+ match workspace.sub_detectors.entry(leaf1) {+ Entry::Occupied(entry) => {+ let sub_detector = entry.into_mut();+ let mut manifold = old_manifolds[sub_detector.manifold_id].take();+ sub_detector.manifold_id = manifolds.len();+ sub_detector.timestamp = new_timestamp;+ if deformable {+ manifold.mark_shapes_deformed();+ }+ manifolds.push(manifold);+ false+ }+ Entry::Vacant(entry) => {+ let _ = entry.insert(SubDetector {+ manifold_id: manifolds.len(),+ timestamp: new_timestamp,+ });+ let mut manifold = ContactManifold::new();+ if flipped {+ manifold.subshape1 = 0;+ manifold.subshape2 = leaf1;+ } else {+ manifold.subshape1 = leaf1;+ manifold.subshape2 = 0;+ }+ if deformable {+ manifold.mark_shapes_deformed();+ }+ manifolds.push(manifold);+ true+ }+ }+ };+ // The manifold's sub-shape pose (a fresh manifold) and contacts.+ let compute =+ |leaf1: u32, fresh: bool, manifold: &mut ContactManifold<ManifoldData, ContactData>| {+ composite1.map_part_at(leaf1, &mut |part_pos1, part_shape1, normal_constraints1| {+ if fresh {+ if flipped {+ manifold.set_subshape_pos2(part_pos1.copied());+ } else {+ manifold.set_subshape_pos1(part_pos1.copied());+ }+ }+ if flipped {+ let _ = dispatcher.contact_manifold_convex_convex(+ &part_pos1.prepend_to(&pos21),+ shape2,+ part_shape1,+ None,+ normal_constraints1,+ prediction,+ manifold,+ );+ } else {+ let _ = dispatcher.contact_manifold_convex_convex(+ &part_pos1.inv_mul(&pos12),+ part_shape1,+ shape2,+ normal_constraints1,+ None,+ prediction,+ manifold,+ );+ }+ });+ };++ #[cfg(feature = "parallel")]+ {+ let leaves: Vec<u32> = composite1.bvh().intersect_aabb(&ls_aabb2_1).collect();+ if leaves.len() >= PARALLEL_LEAVES {+ use rayon::prelude::*;+ let fresh: Vec<bool> = leaves+ .iter()+ .map(|&leaf1| bookkeep(leaf1, manifolds))+ .collect();+ manifolds+ .par_iter_mut()+ .zip(leaves.par_iter())+ .zip(fresh.par_iter())+ .for_each(|((manifold, &leaf1), &fresh)| compute(leaf1, fresh, manifold));+ } else {+ for leaf1 in leaves {+ let fresh = bookkeep(leaf1, manifolds);+ compute(leaf1, fresh, manifolds.last_mut().unwrap());+ }+ }+ }+ #[cfg(not(feature = "parallel"))]+ for leaf1 in composite1.bvh().intersect_aabb(&ls_aabb2_1) {+ let fresh = bookkeep(leaf1, manifolds);+ compute(leaf1, fresh, manifolds.last_mut().unwrap());+ }++ workspace+ .sub_detectors+ .retain(|_, detector| detector.timestamp == new_timestamp)+}++impl WorkspaceData for CompositeShapeShapeContactManifoldsWorkspace {+ fn as_typed_workspace_data(&self) -> TypedWorkspaceData<'_> {+ TypedWorkspaceData::CompositeShapeShapeContactManifoldsWorkspace(self)+ }++ fn clone_dyn(&self) -> Box<dyn WorkspaceData> {+ Box::new(self.clone())+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_convex_ball.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_convex_ball.rsnew file mode 100644index 0000000..f58e8d3--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_convex_ball.rs@@ -0,0 +1,145 @@+use crate::math::{Pose, Real, Vector};+use crate::query::contact_manifolds::{NormalConstraints, NormalConstraintsPair};+use crate::query::{ContactManifold, Ray, TrackedContact};+use crate::shape::{Ball, PackedFeatureId, Shape};++/// Computes the contact manifold between a convex shape and a ball, both represented as a `Shape` trait-object.+pub fn contact_manifold_convex_ball_shapes<ManifoldData, ContactData>(+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ normal_constraints1: Option<&dyn NormalConstraints>,+ normal_constraints2: Option<&dyn NormalConstraints>,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+) where+ ContactData: Default + Copy,+{+ if let Some(ball1) = shape1.as_ball() {+ contact_manifold_convex_ball(+ &pos12.inverse(),+ shape2,+ ball1,+ normal_constraints2,+ normal_constraints1,+ prediction,+ manifold,+ true,+ );+ } else if let Some(ball2) = shape2.as_ball() {+ contact_manifold_convex_ball(+ pos12,+ shape1,+ ball2,+ normal_constraints1,+ normal_constraints2,+ prediction,+ manifold,+ false,+ );+ }+}++/// Computes the contact manifold between a convex shape and a ball.+pub fn contact_manifold_convex_ball<'a, ManifoldData, ContactData, S1>(+ pos12: &Pose,+ shape1: &'a S1,+ ball2: &'a Ball,+ normal_constraints1: Option<&dyn NormalConstraints>,+ normal_constraints2: Option<&dyn NormalConstraints>,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+ flipped: bool,+) where+ S1: ?Sized + Shape,+ ContactData: Default + Copy,+{+ let local_p2_1 = pos12.translation;+ let (proj, mut fid1) = shape1.project_local_point_and_get_feature(local_p2_1);+ let mut local_p1 = proj.point;+ let dpos = local_p2_1 - local_p1;++ // local_n1 points from the surface towards our origin if defined, otherwise from the other+ // shape's origin towards our origin if defined, otherwise towards +x+ // NOTE: we used `dpos.normalize_and_length()` here before. But since `normalize_and_length()`+ // multiplying by the reciprocal (1.0 / length) instead of directly dividing by `length`,+ // it can introduce tiny numerical errors that result in drift breaking perfectly verticality+ // of contact normals for, e.g., the 3D spring joint demo in rapier. So we divide ourselves+ // instead.+ let mut dist = dpos.length();+ let mut local_n1 = if dist == 0.0 {+ pos12.translation.normalize_or(Vector::Y)+ } else {+ dpos / dist+ };++ if proj.is_inside {+ local_n1 = -local_n1;+ dist = -dist;+ }++ if dist <= ball2.radius + prediction {+ let mut local_n2 = pos12.rotation.inverse() * -local_n1;+ let uncorrected_local_n2 = local_n2;++ if !(normal_constraints1, normal_constraints2).project_local_normals(+ pos12,+ &mut local_n1,+ &mut local_n2,+ ) {+ // The contact got completely discarded by the normal correction.+ manifold.clear();+ return;+ }++ let local_p2 = local_n2 * ball2.radius;++ // If a correction happened, adjust the contact point on the first body.+ if uncorrected_local_n2 != local_n2 {+ let ray1 = Ray::new(+ pos12.translation,+ if proj.is_inside { local_n1 } else { -local_n1 },+ );++ if let Some(hit) = shape1.cast_local_ray_and_get_normal(&ray1, Real::MAX, false) {+ local_p1 = ray1.point_at(hit.time_of_impact);+ dist = if proj.is_inside {+ -hit.time_of_impact+ } else {+ hit.time_of_impact+ };+ fid1 = hit.feature;+ } else {+ manifold.clear();+ return;+ }+ }++ let contact_point = TrackedContact::flipped(+ local_p1,+ local_p2,+ fid1.into(),+ PackedFeatureId::face(0),+ dist - ball2.radius,+ flipped,+ );++ if manifold.points.len() != 1 {+ manifold.clear();+ manifold.points.push(contact_point);+ } else {+ // Copy only the geometry so we keep the warmstart impulses.+ manifold.points[0].copy_geometry_from(contact_point);+ }++ if flipped {+ manifold.local_n1 = local_n2;+ manifold.local_n2 = local_n1;+ } else {+ manifold.local_n1 = local_n1;+ manifold.local_n2 = local_n2;+ }+ } else {+ manifold.clear();+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_cuboid_capsule.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_cuboid_capsule.rsnew file mode 100644index 0000000..8fd27a8--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_cuboid_capsule.rs@@ -0,0 +1,175 @@+use crate::math::{Pose, Real, Vector};+use crate::query::{sat, ContactManifold};+#[cfg(feature = "dim3")]+use crate::shape::PolygonalFeature;+use crate::shape::{Capsule, Cuboid, Shape};+#[cfg(feature = "dim2")]+use crate::shape::{CuboidFeature, CuboidFeatureFace};++/// Computes the contact manifold between a cuboid and a capsule, both represented as `Shape` trait-objects.+pub fn contact_manifold_cuboid_capsule_shapes<ManifoldData, ContactData>(+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+) where+ ContactData: Default + Copy,+{+ if let (Some(cube1), Some(capsule2)) = (shape1.as_cuboid(), shape2.as_capsule()) {+ contact_manifold_cuboid_capsule(+ pos12,+ &pos12.inverse(),+ cube1,+ capsule2,+ prediction,+ manifold,+ false,+ );+ } else if let (Some(capsule1), Some(cube2)) = (shape1.as_capsule(), shape2.as_cuboid()) {+ contact_manifold_cuboid_capsule(+ &pos12.inverse(),+ pos12,+ cube2,+ capsule1,+ prediction,+ manifold,+ true,+ );+ }+}++/// Computes the contact manifold between a cuboid and a capsule.+pub fn contact_manifold_cuboid_capsule<'a, ManifoldData, ContactData>(+ pos12: &Pose,+ pos21: &Pose,+ cube1: &'a Cuboid,+ capsule2: &'a Capsule,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+ flipped: bool,+) where+ ContactData: Default + Copy,+{+ if (!flipped && manifold.try_update_contacts(&pos12))+ || (flipped && manifold.try_update_contacts(&pos21))+ {+ return;+ }++ let segment2 = capsule2.segment;++ /*+ *+ * Vector-Face cases.+ *+ */+ let sep1 =+ sat::cuboid_support_map_find_local_separating_normal_oneway(cube1, &segment2, &pos12);+ if sep1.0 > prediction + capsule2.radius {+ manifold.clear();+ return;+ }++ #[cfg(feature = "dim3")]+ let sep2 = (-Real::MAX, Vector::X);+ #[cfg(feature = "dim2")]+ let sep2 = sat::segment_cuboid_find_local_separating_normal_oneway(&segment2, cube1, &pos21);+ if sep2.0 > prediction + capsule2.radius {+ manifold.clear();+ return;+ }++ /*+ *+ * Edge-Edge cases.+ *+ */+ #[cfg(feature = "dim2")]+ let sep3 = (-Real::MAX, Vector::X); // This case does not exist in 2D.+ #[cfg(feature = "dim3")]+ let sep3 = sat::cuboid_segment_find_local_separating_edge_twoway(cube1, &segment2, &pos12);+ if sep3.0 > prediction + capsule2.radius {+ manifold.clear();+ return;+ }++ /*+ *+ * Select the best combination of features+ * and get the polygons to clip.+ *+ */+ let mut best_sep = sep1;++ if sep2.0 > sep1.0 && sep2.0 > sep3.0 {+ best_sep = (sep2.0, pos12.rotation * -sep2.1);+ } else if sep3.0 > sep1.0 {+ best_sep = sep3;+ }++ let feature1;+ let feature2;++ #[cfg(feature = "dim2")]+ {+ feature1 = cube1.support_face(best_sep.1);+ feature2 = CuboidFeatureFace::from(segment2);+ }+ #[cfg(feature = "dim3")]+ {+ feature1 = cube1.polyhedron_support_face(best_sep.1);+ feature2 = PolygonalFeature::from(segment2);+ }++ // We do this clone to perform contact tracking and transfer impulses.+ // TODO: find a more efficient way of doing this.+ let old_manifold_points = manifold.points.clone();+ manifold.clear();++ #[cfg(feature = "dim2")]+ CuboidFeature::face_face_contacts(+ pos12,+ &feature1,+ &best_sep.1,+ &feature2,+ prediction + capsule2.radius,+ manifold,+ flipped,+ );++ #[cfg(feature = "dim3")]+ PolygonalFeature::contacts(+ pos12,+ &feature1,+ &best_sep.1,+ &feature2,+ prediction + capsule2.radius,+ manifold,+ flipped,+ );++ // Adjust points to take the radius into account.+ let normal2 = pos21.rotation * -best_sep.1;++ if flipped {+ manifold.local_n1 = normal2;+ manifold.local_n2 = best_sep.1;++ for point in &mut manifold.points {+ point.local_p1 += manifold.local_n1 * capsule2.radius;+ point.dist -= capsule2.radius;+ }+ } else {+ manifold.local_n1 = best_sep.1;+ manifold.local_n2 = normal2;++ for point in &mut manifold.points {+ point.local_p2 += manifold.local_n2 * capsule2.radius;+ point.dist -= capsule2.radius;+ }+ }++ // Transfer impulses.+ manifold.match_contacts(&old_manifold_points);+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_cuboid_cuboid.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_cuboid_cuboid.rsnew file mode 100644index 0000000..5b36bed--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_cuboid_cuboid.rs@@ -0,0 +1,100 @@+#[cfg(feature = "dim2")]+use crate::math::Vector;+use crate::math::{Pose, Real};+use crate::query::{sat, ContactManifold};+use crate::shape::{Cuboid, PolygonalFeature, Shape};++/// Computes the contact manifold between two cuboids represented as `Shape` trait-objects.+pub fn contact_manifold_cuboid_cuboid_shapes<ManifoldData, ContactData: Default + Copy>(+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &dyn Shape,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+) {+ if let (Some(cuboid1), Some(cuboid2)) = (g1.as_cuboid(), g2.as_cuboid()) {+ contact_manifold_cuboid_cuboid(pos12, cuboid1, cuboid2, prediction, manifold);+ }+}++/// Computes the contact manifold between two cuboids.+pub fn contact_manifold_cuboid_cuboid<'a, ManifoldData, ContactData: Default + Copy>(+ pos12: &Pose,+ cuboid1: &'a Cuboid,+ cuboid2: &'a Cuboid,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+) {+ if manifold.try_update_contacts(pos12) {+ return;+ }++ let pos21 = &pos12.inverse();++ /*+ *+ * Vector-Face+ *+ */+ let sep1 = sat::cuboid_cuboid_find_local_separating_normal_oneway(cuboid1, cuboid2, pos12);+ if sep1.0 > prediction {+ manifold.clear();+ return;+ }++ let sep2 = sat::cuboid_cuboid_find_local_separating_normal_oneway(cuboid2, cuboid1, pos21);+ if sep2.0 > prediction {+ manifold.clear();+ return;+ }++ /*+ *+ * Edge-Edge cases+ *+ */+ #[cfg(feature = "dim2")]+ let sep3 = (-Real::MAX, Vector::X); // This case does not exist in 2D.+ #[cfg(feature = "dim3")]+ let sep3 = sat::cuboid_cuboid_find_local_separating_edge_twoway(cuboid1, cuboid2, pos12);+ if sep3.0 > prediction {+ manifold.clear();+ return;+ }++ /*+ *+ * Select the best combination of features+ * and get the polygons to clip.+ *+ */+ let mut best_sep = sep1;++ if sep2.0 > sep1.0 && sep2.0 > sep3.0 {+ best_sep = (sep2.0, pos12.rotation * -sep2.1);+ } else if sep3.0 > sep1.0 {+ best_sep = sep3;+ }++ // We do this clone to perform contact tracking and transfer impulses.+ // TODO: find a more efficient way of doing this.+ let old_manifold_points = manifold.points.clone();+ manifold.clear();++ let local_n2 = pos21.rotation * -best_sep.1;++ // Now the reference feature is from `cuboid1` and the best separation is `best_sep`.+ // Everything must be expressed in the local-space of `cuboid1` for contact clipping.+ let feature1 = cuboid1.support_feature(best_sep.1);+ let feature2 = cuboid2.support_feature(local_n2);++ PolygonalFeature::contacts(+ pos12, pos21, best_sep.1, local_n2, &feature1, &feature2, manifold, false,+ );++ manifold.local_n1 = best_sep.1;+ manifold.local_n2 = local_n2;++ // Transfer impulses.+ manifold.match_contacts(&old_manifold_points);+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_cuboid_triangle.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_cuboid_triangle.rsnew file mode 100644index 0000000..cb1952f--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_cuboid_triangle.rs@@ -0,0 +1,174 @@+#[cfg(feature = "dim2")]+use crate::math::Vector;+use crate::math::{Pose, Real};+use crate::query::contact_manifolds::{NormalConstraints, NormalConstraintsPair};+use crate::query::{sat, ContactManifold};+use crate::shape::PolygonalFeature;+use crate::shape::{Cuboid, Shape, Triangle};++/// Computes the contact manifold between a cuboid and a triangle represented as `Shape` trait-objects.+pub fn contact_manifold_cuboid_triangle_shapes<ManifoldData, ContactData>(+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ normal_constraints1: Option<&dyn NormalConstraints>,+ normal_constraints2: Option<&dyn NormalConstraints>,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+) where+ ContactData: Default + Copy,+{+ if let (Some(cuboid1), Some(triangle2)) = (shape1.as_cuboid(), shape2.as_triangle()) {+ contact_manifold_cuboid_triangle(+ pos12,+ &pos12.inverse(),+ cuboid1,+ triangle2,+ normal_constraints1,+ normal_constraints2,+ prediction,+ manifold,+ false,+ );+ } else if let (Some(triangle1), Some(cuboid2)) = (shape1.as_triangle(), shape2.as_cuboid()) {+ contact_manifold_cuboid_triangle(+ &pos12.inverse(),+ pos12,+ cuboid2,+ triangle1,+ normal_constraints2,+ normal_constraints1,+ prediction,+ manifold,+ true,+ );+ }+}++/// Computes the contact manifold between a cuboid and a triangle.+pub fn contact_manifold_cuboid_triangle<'a, ManifoldData, ContactData>(+ pos12: &Pose,+ pos21: &Pose,+ cuboid1: &'a Cuboid,+ triangle2: &'a Triangle,+ normal_constraints1: Option<&dyn NormalConstraints>,+ normal_constraints2: Option<&dyn NormalConstraints>,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+ flipped: bool,+) where+ ContactData: Default + Copy,+{+ if (!flipped && manifold.try_update_contacts(pos12))+ || (flipped && manifold.try_update_contacts(pos21))+ {+ return;+ }++ /*+ *+ * Vector-Face cases.+ *+ */+ let sep1 =+ sat::cuboid_support_map_find_local_separating_normal_oneway(cuboid1, triangle2, pos12);+ if sep1.0 > prediction {+ manifold.clear();+ return;+ }++ let sep2 = sat::triangle_cuboid_find_local_separating_normal_oneway(triangle2, cuboid1, pos21);+ if sep2.0 > prediction {+ manifold.clear();+ return;+ }++ /*+ *+ * Edge-Edge cases.+ *+ */+ #[cfg(feature = "dim2")]+ let sep3 = (-Real::MAX, Vector::X); // This case does not exist in 2D.+ #[cfg(feature = "dim3")]+ let sep3 = sat::cuboid_triangle_find_local_separating_edge_twoway(cuboid1, triangle2, pos12);+ if sep3.0 > prediction {+ manifold.clear();+ return;+ }++ /*+ *+ * Select the best combination of features+ * and get the polygons to clip.+ *+ */+ let mut normal1 = sep1.1;+ let mut dist = sep1.0;++ if sep2.0 > sep1.0 && sep2.0 > sep3.0 {+ normal1 = pos12.rotation * -sep2.1;+ dist = sep2.0;+ } else if sep3.0 > sep1.0 {+ normal1 = sep3.1;+ dist = sep3.0;+ }++ // Apply any normal constraint to the separating axis.+ let mut normal2 = pos21.rotation * -normal1;++ if !(normal_constraints1, normal_constraints2).project_local_normals(+ pos12,+ &mut normal1,+ &mut normal2,+ ) {+ manifold.clear();+ return; // The contact got completely discarded by normal correction.+ }++ let feature1;+ let feature2;++ #[cfg(feature = "dim2")]+ {+ feature1 = cuboid1.support_face(normal1);+ feature2 = triangle2.support_face(normal2);+ }+ #[cfg(feature = "dim3")]+ {+ feature1 = cuboid1.support_face(normal1);+ feature2 = PolygonalFeature::from(*triangle2);+ }++ // We do this clone to perform contact tracking and transfer impulses.+ // TODO: find a more efficient way of doing this.+ let old_manifold_points = manifold.points.clone();+ manifold.clear();++ PolygonalFeature::contacts(+ pos12, pos21, normal1, normal2, &feature1, &feature2, manifold, flipped,+ );++ if normal_constraints1.is_some() || normal_constraints2.is_some() {+ // HACK: some normal correction can lead to very incorrect penetration+ // depth, e.g., if the other object extends very far toward that direction.+ // This is caused by the locality of the convex/convex check.+ // I haven’t found a good mathematically robust approach to account for+ // that locally, so for now, we eliminate points that are large divergence+ // relative to the unconstrained penetration distance.+ manifold+ .points+ .retain(|pt| dist >= 0.0 || pt.dist >= 0.0 || pt.dist >= dist * 5.0);+ }++ if flipped {+ manifold.local_n1 = normal2;+ manifold.local_n2 = normal1;+ } else {+ manifold.local_n1 = normal1;+ manifold.local_n2 = normal2;+ }++ // Transfer impulses.+ manifold.match_contacts(&old_manifold_points);+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_halfspace_pfm.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_halfspace_pfm.rsnew file mode 100644index 0000000..4c24a53--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_halfspace_pfm.rs@@ -0,0 +1,93 @@+use crate::math::{Pose, Real};+use crate::query::{ContactManifold, TrackedContact};+use crate::shape::{HalfSpace, PackedFeatureId, PolygonalFeature, PolygonalFeatureMap, Shape};++/// Computes the contact manifold between a convex shape and a ball, both represented as a `Shape` trait-object.+pub fn contact_manifold_halfspace_pfm_shapes<ManifoldData, ContactData>(+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+) where+ ContactData: Default + Copy,+{+ if let (Some(halfspace1), Some((pfm2, border_radius2))) =+ (shape1.as_halfspace(), shape2.as_polygonal_feature_map())+ {+ contact_manifold_halfspace_pfm(+ pos12,+ halfspace1,+ pfm2,+ border_radius2,+ prediction,+ manifold,+ false,+ );+ } else if let (Some((pfm1, border_radius1)), Some(halfspace2)) =+ (shape1.as_polygonal_feature_map(), shape2.as_halfspace())+ {+ contact_manifold_halfspace_pfm(+ &pos12.inverse(),+ halfspace2,+ pfm1,+ border_radius1,+ prediction,+ manifold,+ true,+ );+ }+}++/// Computes the contact manifold between a convex shape and a ball.+pub fn contact_manifold_halfspace_pfm<'a, ManifoldData, ContactData, S2>(+ pos12: &Pose,+ halfspace1: &'a HalfSpace,+ pfm2: &'a S2,+ border_radius2: Real,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+ flipped: bool,+) where+ S2: ?Sized + PolygonalFeatureMap,+ ContactData: Default + Copy,+{+ let normal1_2 = pos12.rotation.inverse() * halfspace1.normal;+ let mut feature2 = PolygonalFeature::default();+ pfm2.local_support_feature(-normal1_2, &mut feature2);++ // We do this clone to perform contact tracking and transfer impulses.+ // TODO: find a more efficient way of doing this.+ let old_manifold_points = core::mem::take(&mut manifold.points);++ for i in 0..feature2.num_vertices {+ let vtx2 = feature2.vertices[i];+ let vtx2_1 = pos12 * vtx2;+ let dist_to_plane = vtx2_1.dot(halfspace1.normal);++ if dist_to_plane - border_radius2 <= prediction {+ // Keep this contact point.+ manifold.points.push(TrackedContact::flipped(+ vtx2_1 - halfspace1.normal * dist_to_plane,+ vtx2 - normal1_2 * border_radius2,+ PackedFeatureId::face(0),+ feature2.vids[i],+ dist_to_plane - border_radius2,+ flipped,+ ));+ }+ }++ if flipped {+ manifold.local_n1 = -normal1_2;+ manifold.local_n2 = halfspace1.normal;+ } else {+ manifold.local_n1 = halfspace1.normal;+ manifold.local_n2 = -normal1_2;+ }++ // println!("Found contacts: {}", manifold.points.len());++ // Transfer impulses.+ manifold.match_contacts(&old_manifold_points);+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_heightfield_composite_shape.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_heightfield_composite_shape.rsnew file mode 100644index 0000000..3e1a961--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_heightfield_composite_shape.rs@@ -0,0 +1,182 @@+use alloc::{boxed::Box, vec::Vec};++use crate::bounding_volume::BoundingVolume;+use crate::math::{Pose, Real};+use crate::query::contact_manifolds::contact_manifolds_workspace::{+ TypedWorkspaceData, WorkspaceData,+};+use crate::query::contact_manifolds::{ContactManifoldsWorkspace, NormalConstraints};+use crate::query::query_dispatcher::PersistentQueryDispatcher;+use crate::query::ContactManifold;+#[cfg(feature = "dim2")]+use crate::shape::Capsule;+use crate::shape::{CompositeShape, HeightField, Shape};+use crate::utils::hashmap::{Entry, HashMap};+use crate::utils::PoseOpt;++#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Clone)]+struct SubDetector {+ manifold_id: usize,+ timestamp: bool,+}++#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[derive(Clone, Default)]+pub struct HeightFieldCompositeShapeContactManifoldsWorkspace {+ timestamp: bool,+ sub_detectors: HashMap<(u32, u32), SubDetector>,+}++impl HeightFieldCompositeShapeContactManifoldsWorkspace {+ pub fn new() -> Self {+ Self::default()+ }+}++fn ensure_workspace_exists(workspace: &mut Option<ContactManifoldsWorkspace>) {+ if workspace+ .as_ref()+ .and_then(|w| {+ w.0.downcast_ref::<HeightFieldCompositeShapeContactManifoldsWorkspace>()+ })+ .is_some()+ {+ return;+ }++ *workspace = Some(ContactManifoldsWorkspace(Box::new(+ HeightFieldCompositeShapeContactManifoldsWorkspace::new(),+ )));+}++/// Computes the contact manifold between an heightfield and a composite shape.+pub fn contact_manifolds_heightfield_composite_shape<ManifoldData, ContactData>(+ dispatcher: &dyn PersistentQueryDispatcher<ManifoldData, ContactData>,+ pos12: &Pose,+ pos21: &Pose,+ heightfield1: &HeightField,+ composite2: &dyn CompositeShape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+ flipped: bool,+) where+ ManifoldData: Default + Clone,+ ContactData: Default + Copy,+{+ ensure_workspace_exists(workspace);+ let workspace: &mut HeightFieldCompositeShapeContactManifoldsWorkspace =+ workspace.as_mut().unwrap().0.downcast_mut().unwrap();+ let new_timestamp = !workspace.timestamp;+ workspace.timestamp = new_timestamp;++ /*+ * Compute interferences.+ */+ let bvh2 = composite2.bvh();+ let ls_aabb2_1 = bvh2.root_aabb().transform_by(pos12).loosened(prediction);+ let mut old_manifolds = core::mem::take(manifolds);+ let deformable = composite2.is_deformable();++ heightfield1.map_elements_in_local_aabb(&ls_aabb2_1, &mut |leaf1, part1| {+ #[cfg(feature = "dim2")]+ let sub_shape1 = Capsule::new(part1.a, part1.b, 0.0); // TODO: use a segment instead.+ #[cfg(feature = "dim3")]+ let sub_shape1 = *part1;++ let ls_aabb1_2 = part1.compute_aabb(pos21).loosened(prediction);+ let mut leaf_fn2 = |leaf2: u32| {+ composite2.map_part_at(leaf2, &mut |part_pos2, part_shape2, normal_constraints2| {+ let sub_detector = match workspace.sub_detectors.entry((leaf1, leaf2)) {+ Entry::Occupied(entry) => {+ let sub_detector = entry.into_mut();+ let manifold = old_manifolds[sub_detector.manifold_id].take();+ sub_detector.manifold_id = manifolds.len();+ sub_detector.timestamp = new_timestamp;+ manifolds.push(manifold);+ sub_detector+ }+ Entry::Vacant(entry) => {+ let sub_detector = SubDetector {+ manifold_id: manifolds.len(),+ timestamp: new_timestamp,+ };++ let mut manifold = ContactManifold::new();++ if flipped {+ manifold.subshape1 = leaf2;+ manifold.subshape2 = leaf1;+ manifold.set_subshape_pos1(part_pos2.copied());+ } else {+ manifold.subshape1 = leaf1;+ manifold.subshape2 = leaf2;+ manifold.set_subshape_pos2(part_pos2.copied());+ };++ manifolds.push(manifold);+ entry.insert(sub_detector)+ }+ };++ let manifold = &mut manifolds[sub_detector.manifold_id];+ if deformable {+ manifold.mark_shapes_deformed();+ }++ #[cfg(feature = "dim2")]+ let triangle_normals = None::<()>;+ #[cfg(feature = "dim3")]+ let triangle_normals = heightfield1.triangle_normal_constraints(leaf1);+ let normal_constraints1 = triangle_normals+ .as_ref()+ .map(|proj| proj as &dyn NormalConstraints);++ if flipped {+ let _ = dispatcher.contact_manifold_convex_convex(+ &part_pos2.inv_mul(pos21),+ part_shape2,+ &sub_shape1,+ normal_constraints2,+ normal_constraints1,+ prediction,+ manifold,+ );+ } else {+ let _ = dispatcher.contact_manifold_convex_convex(+ &part_pos2.prepend_to(pos12),+ &sub_shape1,+ part_shape2,+ normal_constraints1,+ normal_constraints2,+ prediction,+ manifold,+ );+ }+ });+ };++ for leaf_id in bvh2.intersect_aabb(&ls_aabb1_2) {+ leaf_fn2(leaf_id);+ }+ });++ workspace+ .sub_detectors+ .retain(|_, detector| detector.timestamp == new_timestamp);+}++impl WorkspaceData for HeightFieldCompositeShapeContactManifoldsWorkspace {+ fn as_typed_workspace_data(&self) -> TypedWorkspaceData<'_> {+ TypedWorkspaceData::HeightfieldCompositeShapeContactManifoldsWorkspace(self)+ }++ fn clone_dyn(&self) -> Box<dyn WorkspaceData> {+ Box::new(self.clone())+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_heightfield_shape.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_heightfield_shape.rsnew file mode 100644index 0000000..eebbe22--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_heightfield_shape.rs@@ -0,0 +1,198 @@+use alloc::{boxed::Box, vec::Vec};++use crate::bounding_volume::BoundingVolume;+use crate::math::{Pose, Real};+use crate::query::contact_manifolds::contact_manifolds_workspace::{+ TypedWorkspaceData, WorkspaceData,+};+use crate::query::contact_manifolds::ContactManifoldsWorkspace;+use crate::query::query_dispatcher::PersistentQueryDispatcher;+use crate::query::ContactManifold;+#[cfg(feature = "dim2")]+use crate::shape::Capsule;+use crate::shape::{HeightField, Shape};+use crate::utils::hashmap::{Entry, HashMap};++#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Clone)]+struct SubDetector {+ manifold_id: usize,+ timestamp: bool,+}++#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[derive(Clone, Default)]+pub struct HeightFieldShapeContactManifoldsWorkspace {+ timestamp: bool,+ sub_detectors: HashMap<u32, SubDetector>,+}++impl HeightFieldShapeContactManifoldsWorkspace {+ pub fn new() -> Self {+ Self::default()+ }+}++/// Computes the contact manifold between an heightfield and a shape, both represented as `Shape` trait-objects.+pub fn contact_manifolds_heightfield_shape_shapes<ManifoldData, ContactData>(+ dispatcher: &dyn PersistentQueryDispatcher<ManifoldData, ContactData>,+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+) where+ ManifoldData: Default + Clone,+ ContactData: Default + Copy,+{+ if let Some(heightfield1) = shape1.as_heightfield() {+ contact_manifolds_heightfield_shape(+ dispatcher,+ pos12,+ heightfield1,+ shape2,+ prediction,+ manifolds,+ workspace,+ false,+ )+ } else if let Some(heightfield2) = shape2.as_heightfield() {+ contact_manifolds_heightfield_shape(+ dispatcher,+ &pos12.inverse(),+ heightfield2,+ shape1,+ prediction,+ manifolds,+ workspace,+ true,+ )+ }+}++fn ensure_workspace_exists(workspace: &mut Option<ContactManifoldsWorkspace>) {+ if workspace+ .as_ref()+ .and_then(|w| {+ w.0.downcast_ref::<HeightFieldShapeContactManifoldsWorkspace>()+ })+ .is_some()+ {+ return;+ }++ *workspace = Some(ContactManifoldsWorkspace(Box::new(+ HeightFieldShapeContactManifoldsWorkspace::new(),+ )));+}++/// Computes the contact manifold between an heightfield and an abstract shape.+pub fn contact_manifolds_heightfield_shape<ManifoldData, ContactData>(+ dispatcher: &dyn PersistentQueryDispatcher<ManifoldData, ContactData>,+ pos12: &Pose,+ heightfield1: &HeightField,+ shape2: &dyn Shape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+ flipped: bool,+) where+ ManifoldData: Default + Clone,+ ContactData: Default + Copy,+{+ ensure_workspace_exists(workspace);+ let workspace: &mut HeightFieldShapeContactManifoldsWorkspace =+ workspace.as_mut().unwrap().0.downcast_mut().unwrap();+ let new_timestamp = !workspace.timestamp;+ workspace.timestamp = new_timestamp;++ /*+ * Compute interferences.+ */+ // TODO: somehow precompute the Aabb and reuse it?+ let ls_aabb2 = shape2.compute_aabb(pos12).loosened(prediction);+ let mut old_manifolds = core::mem::take(manifolds);++ heightfield1.map_elements_in_local_aabb(&ls_aabb2, &mut |i, part1| {+ #[cfg(feature = "dim2")]+ let sub_shape1 = Capsule::new(part1.a, part1.b, 0.0); // TODO: use a segment instead.+ #[cfg(feature = "dim3")]+ let sub_shape1 = *part1;++ let sub_detector = match workspace.sub_detectors.entry(i) {+ Entry::Occupied(entry) => {+ let sub_detector = entry.into_mut();+ let manifold = old_manifolds[sub_detector.manifold_id].take();+ sub_detector.manifold_id = manifolds.len();+ sub_detector.timestamp = new_timestamp;+ manifolds.push(manifold);+ sub_detector+ }+ Entry::Vacant(entry) => {+ let sub_detector = SubDetector {+ manifold_id: manifolds.len(),+ timestamp: new_timestamp,+ };++ let (id1, id2) = if flipped { (0, i) } else { (i, 0) };+ manifolds.push(ContactManifold::with_data(+ id1,+ id2,+ ManifoldData::default(),+ ));++ entry.insert(sub_detector)+ }+ };++ let manifold = &mut manifolds[sub_detector.manifold_id];++ #[cfg(feature = "dim2")]+ let pseudo_normals = None::<()>;+ #[cfg(feature = "dim3")]+ let pseudo_normals = heightfield1.triangle_normal_constraints(i);++ let normal_constraints1 = pseudo_normals.as_ref().map(|pn| pn as &_);++ if flipped {+ let _ = dispatcher.contact_manifold_convex_convex(+ &pos12.inverse(),+ shape2,+ &sub_shape1,+ None,+ normal_constraints1,+ prediction,+ manifold,+ );+ } else {+ let _ = dispatcher.contact_manifold_convex_convex(+ pos12,+ &sub_shape1,+ shape2,+ normal_constraints1,+ None,+ prediction,+ manifold,+ );+ }+ });++ workspace+ .sub_detectors+ .retain(|_, detector| detector.timestamp == new_timestamp);+}++impl WorkspaceData for HeightFieldShapeContactManifoldsWorkspace {+ fn as_typed_workspace_data(&self) -> TypedWorkspaceData<'_> {+ TypedWorkspaceData::HeightfieldShapeContactManifoldsWorkspace(self)+ }++ fn clone_dyn(&self) -> Box<dyn WorkspaceData> {+ Box::new(self.clone())+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_pfm_pfm.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_pfm_pfm.rsnew file mode 100644index 0000000..0d61c74--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_pfm_pfm.rs@@ -0,0 +1,165 @@+use crate::math::{Pose, Real, Vector};+use crate::query::contact_manifolds::{NormalConstraints, NormalConstraintsPair};+use crate::query::{+ self,+ gjk::{GJKResult, VoronoiSimplex},+ ContactManifold, TrackedContact,+};+use crate::shape::{PackedFeatureId, PolygonalFeature, PolygonalFeatureMap, Shape};++/// Computes the contact manifold between two convex shapes implementing the `PolygonalSupportMap`+/// trait, both represented as `Shape` trait-objects.+pub fn contact_manifold_pfm_pfm_shapes<ManifoldData, ContactData>(+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ normal_constraints1: Option<&dyn NormalConstraints>,+ normal_constraints2: Option<&dyn NormalConstraints>,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+) where+ ManifoldData: Default,+ ContactData: Default + Copy,+{+ if let (Some((pfm1, border_radius1)), Some((pfm2, border_radius2))) = (+ shape1.as_polygonal_feature_map(),+ shape2.as_polygonal_feature_map(),+ ) {+ contact_manifold_pfm_pfm(+ pos12,+ pfm1,+ border_radius1,+ normal_constraints1,+ pfm2,+ border_radius2,+ normal_constraints2,+ prediction,+ manifold,+ );+ }+}++/// Computes the contact manifold between two convex shapes implementing the `PolygonalSupportMap` trait.+pub fn contact_manifold_pfm_pfm<'a, ManifoldData, ContactData, S1, S2>(+ pos12: &Pose,+ pfm1: &'a S1,+ border_radius1: Real,+ normal_constraints1: Option<&dyn NormalConstraints>,+ pfm2: &'a S2,+ border_radius2: Real,+ normal_constraints2: Option<&dyn NormalConstraints>,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+) where+ S1: ?Sized + PolygonalFeatureMap,+ S2: ?Sized + PolygonalFeatureMap,+ ManifoldData: Default,+ ContactData: Default + Copy,+{+ // We use very small thresholds for the manifold update because something to high would+ // cause numerical drifts with the effect of introducing bumps in+ // what should have been smooth rolling motions.+ if manifold.try_update_contacts_eps(pos12, crate::utils::COS_1_DEGREES, 1.0e-6) {+ return;+ }++ let init_dir = (manifold.local_n1).try_normalize();+ let total_prediction = prediction + border_radius1 + border_radius2;+ let contact = query::details::contact_support_map_support_map_with_params(+ pos12,+ pfm1,+ pfm2,+ total_prediction,+ &mut VoronoiSimplex::new(),+ init_dir,+ );++ let old_manifold_points = manifold.points.clone();+ manifold.clear();++ match contact {+ GJKResult::ClosestPoints(p1, p2_1, dir) => {+ let mut local_n1 = dir;+ let mut local_n2 = pos12.rotation.inverse() * -dir;+ let dist = (p2_1 - p1).dot(local_n1);++ if !(normal_constraints1, normal_constraints2).project_local_normals(+ pos12,+ &mut local_n1,+ &mut local_n2,+ ) {+ // The contact got completely discarded by the normal correction.+ return;+ }++ let mut feature1 = PolygonalFeature::default();+ let mut feature2 = PolygonalFeature::default();+ pfm1.local_support_feature_toward(local_n1, p1, &mut feature1);+ pfm2.local_support_feature_toward(+ local_n2,+ pos12.inverse_transform_point(p2_1),+ &mut feature2,+ );++ PolygonalFeature::contacts(+ pos12,+ &pos12.inverse(),+ local_n1,+ local_n2,+ &feature1,+ &feature2,+ manifold,+ false,+ );++ if (cfg!(feature = "dim3") || cfg!(feature = "dim2") && manifold.points.is_empty())+ // If normal constraints changed the GJK direction, it is no longer valid so we cant use it for this additional contact.+ && local_n1 == dir+ {+ let contact = TrackedContact::new(+ p1,+ pos12.inverse_transform_point(p2_1),+ PackedFeatureId::UNKNOWN, // TODO: We don't know what features are involved.+ PackedFeatureId::UNKNOWN,+ (p2_1 - p1).dot(local_n1),+ );+ manifold.points.push(contact);+ }++ if normal_constraints1.is_some() || normal_constraints2.is_some() {+ // HACK: some normal correction can lead to very incorrect penetration+ // depth, e.g., if the other object extends very far toward that direction.+ // This is caused by the locality of the convex/convex check.+ // I haven’t found a good mathematically robust approach to account for+ // that locally, so for now, we eliminate points that are large divergence+ // relative to the unconstrained penetration distance.+ manifold+ .points+ .retain(|pt| dist >= 0.0 || pt.dist >= 0.0 || pt.dist >= dist * 5.0);+ }++ // Adjust points to take the radius into account.+ if border_radius1 != 0.0 || border_radius2 != 0.0 {+ for contact in &mut manifold.points {+ contact.local_p1 += local_n1 * border_radius1;+ contact.local_p2 += local_n2 * border_radius2;+ contact.dist -= border_radius1 + border_radius2;+ }+ }++ manifold.local_n1 = local_n1;+ manifold.local_n2 = local_n2;+ }+ GJKResult::NoIntersection(dir) => {+ // Use the manifold normal as a cache.+ manifold.local_n1 = dir;+ }+ _ => {+ // Reset the cached direction.+ manifold.local_n1 = Vector::ZERO;+ }+ }++ // Transfer impulses.+ manifold.match_contacts(&old_manifold_points);+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_trimesh_shape.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_trimesh_shape.rsnew file mode 100644index 0000000..902de96--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_trimesh_shape.rs@@ -0,0 +1,246 @@+use alloc::{boxed::Box, vec::Vec};++use crate::bounding_volume::{Aabb, BoundingVolume};+use crate::math::{Pose, Real};+use crate::query::contact_manifolds::contact_manifolds_workspace::{+ TypedWorkspaceData, WorkspaceData,+};+use crate::query::contact_manifolds::{+ contact_manifolds_composite_shape_shape, ContactManifoldsWorkspace,+};+use crate::query::details::NormalConstraints;+use crate::query::query_dispatcher::PersistentQueryDispatcher;+use crate::query::ContactManifold;+use crate::shape::{CompositeShape, Shape, TriMesh, TriMeshFlags};++#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Clone)]+pub struct TriMeshShapeContactManifoldsWorkspace {+ interferences: Vec<u32>,+ local_aabb2: Aabb,+ old_interferences: Vec<u32>,+}++impl Default for TriMeshShapeContactManifoldsWorkspace {+ fn default() -> Self {+ Self::new()+ }+}++impl TriMeshShapeContactManifoldsWorkspace {+ pub fn new() -> Self {+ Self {+ interferences: Vec::new(),+ local_aabb2: Aabb::new_invalid(),+ old_interferences: Vec::new(),+ }+ }+}++/// Computes the contact manifold between a triangle-mesh an a shape, both represented as `Shape` trait-objects.+pub fn contact_manifolds_trimesh_shape_shapes<ManifoldData, ContactData>(+ dispatcher: &dyn PersistentQueryDispatcher<ManifoldData, ContactData>,+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+) where+ ManifoldData: Default + Clone + Send + Sync,+ ContactData: Default + Copy + Send + Sync,+{+ if let Some(trimesh1) = shape1.as_trimesh() {+ contact_manifolds_trimesh_shape(+ dispatcher, pos12, trimesh1, shape2, prediction, manifolds, workspace, false,+ )+ } else if let Some(trimesh2) = shape2.as_trimesh() {+ contact_manifolds_trimesh_shape(+ dispatcher,+ &pos12.inverse(),+ trimesh2,+ shape1,+ prediction,+ manifolds,+ workspace,+ true,+ )+ }+}++fn ensure_workspace_exists(workspace: &mut Option<ContactManifoldsWorkspace>) {+ if workspace+ .as_mut()+ .and_then(|w| w.0.downcast_mut::<TriMeshShapeContactManifoldsWorkspace>())+ .is_some()+ {+ return;+ }++ *workspace = Some(ContactManifoldsWorkspace(Box::new(+ TriMeshShapeContactManifoldsWorkspace::new(),+ )));+}++/// Computes the contact manifold between a triangle-mesh and a shape.+///+/// A mesh flagged [`TriMeshFlags::DEFORMABLE`] goes through+/// [`contact_manifolds_composite_shape_shape`](fn@contact_manifolds_composite_shape_shape) instead:+/// the interfering-triangle cache kept in this function's workspace assumes a rigid mesh.+pub fn contact_manifolds_trimesh_shape<ManifoldData, ContactData>(+ dispatcher: &dyn PersistentQueryDispatcher<ManifoldData, ContactData>,+ pos12: &Pose,+ trimesh1: &TriMesh,+ shape2: &dyn Shape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+ flipped: bool,+) where+ ManifoldData: Default + Clone + Send + Sync,+ ContactData: Default + Copy + Send + Sync,+{+ if trimesh1.flags().contains(TriMeshFlags::DEFORMABLE) {+ return contact_manifolds_composite_shape_shape(+ dispatcher,+ pos12,+ trimesh1 as &(dyn CompositeShape + Sync),+ shape2,+ prediction,+ manifolds,+ workspace,+ flipped,+ );+ }++ ensure_workspace_exists(workspace);+ let workspace: &mut TriMeshShapeContactManifoldsWorkspace =+ workspace.as_mut().unwrap().0.downcast_mut().unwrap();++ /*+ * Compute interferences.+ */+ // TODO: somehow precompute the Aabb and reuse it?+ let mut new_local_aabb2 = shape2.compute_aabb(pos12).loosened(prediction);+ let same_local_aabb2 = workspace.local_aabb2.contains(&new_local_aabb2);+ let mut old_manifolds = Vec::new();++ if !same_local_aabb2 {+ let extra_margin =+ (new_local_aabb2.maxs - new_local_aabb2.mins).map(|e| (e / 10.0).min(0.1));+ new_local_aabb2.mins -= extra_margin;+ new_local_aabb2.maxs += extra_margin;++ let local_aabb2 = new_local_aabb2; // .loosened(prediction * 2.0); // TODO: what would be the best value?+ core::mem::swap(+ &mut workspace.old_interferences,+ &mut workspace.interferences,+ );++ core::mem::swap(manifolds, &mut old_manifolds);++ // NOTE: This assertion may fire due to the invalid triangle_ids that the+ // near-phase may return (due to SIMD sentinels).+ //+ // assert_eq!(+ // workspace+ // .old_interferences+ // .len()+ // .min(trimesh1.num_triangles()),+ // workspace.old_manifolds.len()+ // );++ workspace.interferences.clear();+ workspace+ .interferences+ .extend(trimesh1.bvh().intersect_aabb(&local_aabb2));+ workspace.local_aabb2 = local_aabb2;+ }++ /*+ * Dispatch to the specific solver by keeping the previous manifold if we already had one.+ */+ let new_interferences = &workspace.interferences;+ let mut old_inter_it = workspace.old_interferences.drain(..).peekable();+ let mut old_manifolds_it = old_manifolds.drain(..);++ // TODO: don't redispatch at each frame (we should probably do the same as+ // the heightfield).+ for (i, triangle_id) in new_interferences.iter().enumerate() {+ if *triangle_id >= trimesh1.num_triangles() as u32 {+ // Because of SIMD padding, the broad-phase may return triangle indices greater+ // than the max.+ continue;+ }++ if !same_local_aabb2 {+ loop {+ match old_inter_it.peek() {+ Some(old_triangle_id) if *old_triangle_id < *triangle_id => {+ let _ = old_inter_it.next();+ let _ = old_manifolds_it.next();+ }+ _ => break,+ }+ }++ let manifold = if old_inter_it.peek() != Some(triangle_id) {+ let (id1, id2) = if flipped {+ (0, *triangle_id)+ } else {+ (*triangle_id, 0)+ };+ ContactManifold::with_data(id1, id2, ManifoldData::default())+ } else {+ // We already have a manifold for this triangle.+ let _ = old_inter_it.next();+ old_manifolds_it.next().unwrap()+ };++ manifolds.push(manifold);+ }++ let manifold = &mut manifolds[i];+ let triangle1 = trimesh1.triangle(*triangle_id);+ let triangle_normals1 = trimesh1.triangle_normal_constraints(*triangle_id);+ let normal_constraints1 = triangle_normals1+ .as_ref()+ .map(|proj| proj as &dyn NormalConstraints);++ if flipped {+ let _ = dispatcher.contact_manifold_convex_convex(+ &pos12.inverse(),+ shape2,+ &triangle1,+ None,+ normal_constraints1,+ prediction,+ manifold,+ );+ } else {+ let _ = dispatcher.contact_manifold_convex_convex(+ pos12,+ &triangle1,+ shape2,+ normal_constraints1,+ None,+ prediction,+ manifold,+ );+ }+ }+}++impl WorkspaceData for TriMeshShapeContactManifoldsWorkspace {+ fn as_typed_workspace_data(&self) -> TypedWorkspaceData<'_> {+ TypedWorkspaceData::TriMeshShapeContactManifoldsWorkspace(self)+ }++ fn clone_dyn(&self) -> Box<dyn WorkspaceData> {+ Box::new(self.clone())+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_voxels_ball.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_voxels_ball.rsnew file mode 100644index 0000000..fc16604--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_voxels_ball.rs@@ -0,0 +1,217 @@+use crate::bounding_volume::BoundingVolume;+use crate::math::{Pose, Real, Vector, VectorExt};+use crate::query::{ContactManifold, PointQuery, TrackedContact};+use crate::shape::{+ Ball, Cuboid, OctantPattern, PackedFeatureId, Shape, VoxelState, VoxelType, Voxels,+};+use alloc::vec::Vec;++/// Computes the contact manifold between a convex shape and a ball, both represented as a `Shape` trait-object.+pub fn contact_manifolds_voxels_ball_shapes<ManifoldData, ContactData>(+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+) where+ ManifoldData: Default,+ ContactData: Default + Copy,+{+ if let (Some(voxels1), Some(ball2)) = (shape1.as_voxels(), shape2.as_ball()) {+ contact_manifolds_voxels_ball(pos12, voxels1, ball2, prediction, manifolds, false);+ } else if let (Some(ball1), Some(voxels2)) = (shape1.as_ball(), shape2.as_voxels()) {+ contact_manifolds_voxels_ball(+ &pos12.inverse(),+ voxels2,+ ball1,+ prediction,+ manifolds,+ true,+ );+ }+}++/// Computes the contact manifold between a convex shape and a ball.+pub fn contact_manifolds_voxels_ball<'a, ManifoldData, ContactData>(+ pos12: &Pose,+ voxels1: &'a Voxels,+ ball2: &'a Ball,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ flipped: bool,+) where+ ManifoldData: Default,+ ContactData: Default + Copy,+{+ // TODO: don’t generate one manifold per voxel.+ manifolds.clear();++ let radius2 = ball2.radius;+ let center2 = Vector::ZERO; // The ball’s center.+ let radius1 = voxels1.voxel_size() / 2.0;++ // FIXME: optimize this.+ let aabb1 = voxels1.local_aabb().loosened(prediction / 2.0);+ let aabb2 = ball2.aabb(pos12).loosened(prediction / 2.0);+ if let Some(aabb_intersection) = aabb1.intersection(&aabb2) {+ for vox1 in voxels1.voxels_intersecting_local_aabb(&aabb_intersection) {+ match vox1.state.voxel_type() {+ #[cfg(feature = "dim2")]+ VoxelType::Vertex | VoxelType::Face => { /* Ok */ }+ #[cfg(feature = "dim3")]+ VoxelType::Vertex | VoxelType::Edge | VoxelType::Face => { /* Ok */ }+ _ => continue,+ }++ detect_hit_voxel_ball(+ *pos12,+ vox1.center,+ radius1,+ vox1.state,+ center2,+ radius2,+ prediction,+ flipped,+ manifolds,+ );+ }+ }+}++pub(crate) fn detect_hit_voxel_ball<ManifoldData, ContactData>(+ pos12: Pose,+ center1: Vector,+ radius1: Vector,+ data1: VoxelState,+ center2: Vector,+ radius2: Real,+ prediction: Real,+ flipped: bool,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+) where+ ManifoldData: Default,+ ContactData: Default + Copy,+{+ let center2_1 = pos12 * center2;+ let projection = project_point_on_pseudo_cube(center1, radius1, data1.octant_mask(), center2_1);++ if let Some((local_n1, dist_to_voxel)) = projection {+ let dist = dist_to_voxel - radius2;++ if dist <= prediction {+ let local_n2 = pos12.rotation.inverse() * -local_n1;+ let local_p1 = center2_1 - local_n1 * dist_to_voxel;+ let local_p2 = center2 + local_n2 * radius2;+ let contact_point = TrackedContact::<ContactData>::flipped(+ local_p1,+ local_p2,+ PackedFeatureId::UNKNOWN,+ PackedFeatureId::UNKNOWN,+ dist,+ flipped,+ );++ let mut manifold = ContactManifold::<ManifoldData, ContactData>::new();+ manifold.points.push(contact_point);++ if flipped {+ manifold.local_n1 = local_n2;+ manifold.local_n2 = local_n1;+ } else {+ manifold.local_n1 = local_n1;+ manifold.local_n2 = local_n2;+ }++ manifolds.push(manifold);+ }+ }+}++pub fn project_point_on_pseudo_cube(+ voxel_center: Vector,+ voxel_radius: Vector,+ voxel_mask: u32,+ point: Vector,+) -> Option<(Vector, Real)> {+ let dpos = point - voxel_center;++ // This maps our easy-to map octant_key, to the vertex key as+ // used by the Aabb::FACES_VERTEX_IDS and Aabb::EDGES_VERTEX_IDS+ // arrays. Could we find a way to avoid this map by computing the+ // correct key right away?+ //+ // NOTE: in 2D the array is [0, 1, 3, 2] which matches the one in 3D.+ const AABB_OCTANT_KEYS: [u32; 8] = [0, 1, 3, 2, 4, 5, 7, 6];+ #[cfg(feature = "dim2")]+ let octant_key = ((dpos.x >= 0.0) as usize) | (((dpos.y >= 0.0) as usize) << 1);+ #[cfg(feature = "dim3")]+ let octant_key = ((dpos.x >= 0.0) as usize)+ | (((dpos.y >= 0.0) as usize) << 1)+ | (((dpos.z >= 0.0) as usize) << 2);+ let aabb_octant_key = AABB_OCTANT_KEYS[octant_key];+ let dpos_signs = dpos.map(|x| x.signum());+ let unit_dpos = dpos.abs() / voxel_radius; // Project the point in "local unit octant space".++ // Extract the feature pattern specific to the selected octant.+ let pattern = (voxel_mask >> (aabb_octant_key * 3)) & 0b0111;++ let unit_result = match pattern {+ OctantPattern::INTERIOR => None,+ OctantPattern::VERTEX => {+ // PERF: inline the projection on cuboid to improve performances further.+ // In particular we already know on what octant we are to compute the+ // collision.+ let cuboid = Cuboid::new(Vector::splat(1.0));+ let unit_dpos_pt = unit_dpos;+ let proj = cuboid.project_local_point(unit_dpos_pt, false);+ let normal = unit_dpos_pt - proj.point;+ let (normal, dist) = normal.normalize_and_length();+ (dist != 0.0).then_some((normal, dist))+ }+ #[cfg(feature = "dim3")]+ OctantPattern::EDGE_X | OctantPattern::EDGE_Y | OctantPattern::EDGE_Z => {+ let cuboid = Cuboid::new(Vector::splat(1.0));+ let unit_dpos_pt = unit_dpos;+ let proj = cuboid.project_local_point(unit_dpos_pt, false);+ let normal = unit_dpos_pt - proj.point;+ let (normal, dist) = normal.normalize_and_length();+ (dist != 0.0).then_some((normal, dist))+ }+ #[cfg(feature = "dim2")]+ OctantPattern::FACE_X | OctantPattern::FACE_Y => {+ let i1 = pattern as usize - OctantPattern::FACE_X as usize;+ let i2 = (i1 + 1) % 2;++ if unit_dpos.vget(i2) > 1.0 || unit_dpos.vget(i2) < 0.0 {+ None+ } else {+ let dist = unit_dpos.vget(i1) - 1.0; // Subtract 1 to get the distance wrt. the boundary of the unit voxel.+ Some((Vector::ith(i1, 1.0), dist))+ }+ }+ #[cfg(feature = "dim3")]+ OctantPattern::FACE_X | OctantPattern::FACE_Y | OctantPattern::FACE_Z => {+ let i1 = pattern as usize - OctantPattern::FACE_X as usize;+ let i2 = (i1 + 1) % 3;+ let i3 = (i1 + 2) % 3;++ if unit_dpos.vget(i2) > 1.0+ || unit_dpos.vget(i2) < 0.0+ || unit_dpos.vget(i3) > 1.0+ || unit_dpos.vget(i3) < 0.0+ {+ None+ } else {+ let dist = unit_dpos.vget(i1) - 1.0; // Subtract 1 to get the distance wrt. the boundary of the unit voxel.+ Some((Vector::ith(i1, 1.0), dist))+ }+ }+ _ => unreachable!(),+ };++ unit_result.map(|(n, d)| {+ let scaled_n = n * (dpos_signs) * (voxel_radius);+ let (n, scaled_d) = scaled_n.normalize_and_length();+ (n, d * scaled_d)+ })+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_voxels_composite_shape.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_voxels_composite_shape.rsnew file mode 100644index 0000000..157da87--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_voxels_composite_shape.rs@@ -0,0 +1,297 @@+use crate::bounding_volume::Aabb;+use crate::math::{Pose, Real, Vector};+use crate::query::details::{+ CanonicalVoxelShape, VoxelsShapeContactManifoldsWorkspace, VoxelsShapeSubDetector,+};+use crate::query::{+ ContactManifold, ContactManifoldsWorkspace, PersistentQueryDispatcher, PointQuery,+ TypedWorkspaceData, WorkspaceData,+};+use crate::shape::{CompositeShape, Cuboid, Shape, SupportMap, VoxelType, Voxels};+use crate::utils::hashmap::Entry;+use crate::utils::PoseOpt;+use alloc::{boxed::Box, vec::Vec};++impl WorkspaceData for VoxelsShapeContactManifoldsWorkspace<3> {+ fn as_typed_workspace_data(&self) -> TypedWorkspaceData<'_> {+ TypedWorkspaceData::VoxelsCompositeShapeContactManifoldsWorkspace(self)+ }++ fn clone_dyn(&self) -> Box<dyn WorkspaceData> {+ Box::new(self.clone())+ }+}++/// Computes the contact manifold between voxels and a composite shape, both represented as a `Shape` trait-object.+pub fn contact_manifolds_voxels_composite_shape_shapes<ManifoldData, ContactData>(+ dispatcher: &dyn PersistentQueryDispatcher<ManifoldData, ContactData>,+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+) where+ ManifoldData: Default + Clone,+ ContactData: Default + Copy,+{+ if let (Some(voxels1), Some(shape2)) = (shape1.as_voxels(), shape2.as_composite_shape()) {+ contact_manifolds_voxels_composite_shape(+ dispatcher, pos12, voxels1, shape2, prediction, manifolds, workspace, false,+ );+ } else if let (Some(shape1), Some(voxels2)) = (shape1.as_composite_shape(), shape2.as_voxels())+ {+ contact_manifolds_voxels_composite_shape(+ dispatcher,+ &pos12.inverse(),+ voxels2,+ shape1,+ prediction,+ manifolds,+ workspace,+ true,+ );+ }+}++/// Computes the contact manifold between voxels and a composite shape.+pub fn contact_manifolds_voxels_composite_shape<ManifoldData, ContactData>(+ dispatcher: &dyn PersistentQueryDispatcher<ManifoldData, ContactData>,+ pos12: &Pose,+ voxels1: &Voxels,+ shape2: &dyn CompositeShape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+ flipped: bool,+) where+ ManifoldData: Default + Clone,+ ContactData: Default + Copy,+{+ VoxelsShapeContactManifoldsWorkspace::<3>::ensure_exists(workspace);+ let workspace: &mut VoxelsShapeContactManifoldsWorkspace<3> =+ workspace.as_mut().unwrap().0.downcast_mut().unwrap();+ let new_timestamp = !workspace.timestamp;+ workspace.timestamp = new_timestamp;++ // TODO: avoid reallocating the new `manifolds` vec at each step.+ let mut old_manifolds = core::mem::take(manifolds);+ let bvh2 = shape2.bvh();+ let deformable = shape2.is_deformable();++ let radius1 = voxels1.voxel_size() / 2.0;++ let aabb1 = voxels1.local_aabb();+ let aabb2_1 = shape2.bvh().root_aabb().transform_by(pos12);+ let domain2_1 = Aabb {+ mins: aabb2_1.mins - radius1 * 10.0,+ maxs: aabb2_1.maxs + radius1 * 10.0,+ };++ if let Some(intersection_aabb1) = aabb1.intersection(&aabb2_1) {+ for vox1 in voxels1.voxels_intersecting_local_aabb(&intersection_aabb1) {+ let vox_type1 = vox1.state.voxel_type();++ // TODO: would be nice to have a strategy to handle interior voxels for depenetration.+ if vox_type1 == VoxelType::Empty || vox_type1 == VoxelType::Interior {+ continue;+ }++ // PERF: could we avoid repeated BVH traversals involving the same canonical shape?+ // The issue is that we need to figure out what contact manifolds are associated+ // to that canonical shape so we can update the included contact bitmask (and+ // one way of figuring this out is to re-traverse the bvh).+ let canon1 = CanonicalVoxelShape::from_voxel(voxels1, &vox1);+ let (canonical_center1, canonical_shape1) = canon1.cuboid(voxels1, &vox1, domain2_1);+ let canonical_pose12 = Pose::from_translation(-canonical_center1) * pos12;++ let mut detect_hit = |leaf2: u32| {+ let key = [canon1.workspace_key[0], canon1.workspace_key[1], leaf2];++ // TODO: could we refactor the workspace system between Voxels, HeightField, and CompoundShape?+ // (and maybe TriMesh too but it's using a different approach).+ let (sub_detector, manifold_updated) =+ match workspace.sub_detectors.entry(key.into()) {+ Entry::Occupied(entry) => {+ let sub_detector = entry.into_mut();++ if sub_detector.timestamp != new_timestamp {+ let manifold = old_manifolds[sub_detector.manifold_id].take();+ *sub_detector = VoxelsShapeSubDetector {+ manifold_id: manifolds.len(),+ timestamp: new_timestamp,+ selected_contacts: 0,+ };++ manifolds.push(manifold);+ (sub_detector, false)+ } else {+ (sub_detector, true)+ }+ }+ Entry::Vacant(entry) => {+ let sub_detector = VoxelsShapeSubDetector {+ manifold_id: manifolds.len(),+ selected_contacts: 0,+ timestamp: new_timestamp,+ };++ let vox_id = vox1.linear_id.flat_id() as u32;+ let (id1, id2) = if flipped {+ (leaf2, vox_id)+ } else {+ (vox_id, leaf2)+ };+ manifolds.push(ContactManifold::with_data(+ id1,+ id2,+ ManifoldData::default(),+ ));++ (entry.insert(sub_detector), false)+ }+ };++ /*+ * Update the contact manifold if needed.+ */+ let manifold = &mut manifolds[sub_detector.manifold_id];++ shape2.map_part_at(leaf2, &mut |part_pos2, part_shape2, _| {+ let relative_pos12 = part_pos2.prepend_to(&canonical_pose12);++ if !manifold_updated {+ if deformable {+ manifold.mark_shapes_deformed();+ }++ // If we already computed contacts in the previous simulation step, their+ // local points are relative to the previously calculated canonical shape+ // which might not have the same local center as the one computed in this+ // step (because it’s based on the position of shape2 relative to voxels1).+ // So we need to adjust the local points to account for the position difference+ // and keep the point at the same "canonical-shape-space" location as in the previous frame.+ let prev_center = if flipped {+ manifold+ .subshape_pos2()+ .as_ref()+ .map(|p| p.translation)+ .unwrap_or_default()+ } else {+ manifold+ .subshape_pos1()+ .as_ref()+ .map(|p| p.translation)+ .unwrap_or_default()+ };+ let delta_center = canonical_center1 - prev_center;++ if flipped {+ for pt in &mut manifold.points {+ pt.local_p2 -= delta_center;+ }+ } else {+ for pt in &mut manifold.points {+ pt.local_p1 -= delta_center;+ }+ }++ // Update contacts.+ if flipped {+ manifold.set_subshape_pos1(part_pos2.copied());+ manifold+ .set_subshape_pos2(Some(Pose::from_translation(canonical_center1)));+ let _ = dispatcher.contact_manifold_convex_convex(+ &relative_pos12.inverse(),+ part_shape2,+ &canonical_shape1,+ None,+ None,+ prediction,+ manifold,+ );+ } else {+ manifold+ .set_subshape_pos1(Some(Pose::from_translation(canonical_center1)));+ manifold.set_subshape_pos2(part_pos2.copied());+ let _ = dispatcher.contact_manifold_convex_convex(+ &relative_pos12,+ &canonical_shape1,+ part_shape2,+ None,+ None,+ prediction,+ manifold,+ );+ }+ }++ /*+ * Filter-out points that don’t belong to this block.+ */+ let test_voxel = Cuboid::new(radius1 + Vector::splat(1.0e-2));+ let penetration_dir1 = if flipped {+ manifold.local_n2+ } else {+ manifold.local_n1+ };++ for (i, pt) in manifold.points.iter().enumerate() {+ if pt.dist < 0.0 {+ // If this is a penetration, double-check that we are not hitting the+ // interior of the infinitely expanded canonical shape by checking if+ // the opposite normal had led to a better vector.+ let cuboid1 = Cuboid::new(radius1);+ let sp1 = cuboid1.local_support_point(-penetration_dir1) + vox1.center;+ let sm2 = part_shape2+ .as_support_map()+ .expect("Unsupported collision pair.");+ let sp2 = sm2.support_point(&relative_pos12, penetration_dir1)+ + canonical_center1;+ let test_dist = (sp2 - sp1).dot(-penetration_dir1);+ let keep = test_dist < pt.dist;++ if !keep {+ // We don’t want to keep this point as it is an incorrect penetration+ // caused by the canonical shape expansion.+ continue;+ }+ }++ let pt_in_voxel_space = if flipped {+ manifold.subshape_pos2().transform_point(pt.local_p2) - vox1.center+ } else {+ manifold.subshape_pos1().transform_point(pt.local_p1) - vox1.center+ };+ sub_detector.selected_contacts |=+ (test_voxel.contains_local_point(pt_in_voxel_space) as u32) << i;+ }+ });+ };++ let canon_aabb1_2 = canonical_shape1.compute_aabb(&canonical_pose12.inverse());++ for leaf_id in bvh2.intersect_aabb(&canon_aabb1_2) {+ detect_hit(leaf_id);+ }+ }+ }++ // Remove contacts marked as ignored.+ for sub_detector in workspace.sub_detectors.values() {+ if sub_detector.timestamp == new_timestamp {+ let manifold = &mut manifolds[sub_detector.manifold_id];+ let mut k = 0;+ manifold.points.retain(|_| {+ let keep = (sub_detector.selected_contacts & (1 << k)) != 0;+ k += 1;+ keep+ });+ }+ }++ // Remove detectors which no longer index a valid manifold.+ workspace+ .sub_detectors+ .retain(|_, detector| detector.timestamp == new_timestamp);+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_voxels_shape.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_voxels_shape.rsnew file mode 100644index 0000000..f0b50e6--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_voxels_shape.rs@@ -0,0 +1,405 @@+use crate::bounding_volume::{Aabb, BoundingVolume};+use crate::math::{IVector, IVectorExt, Int, Pose, Real, Vector, VectorExt, DIM};+use crate::query::{+ ContactManifold, ContactManifoldsWorkspace, PersistentQueryDispatcher, PointQuery,+ TypedWorkspaceData, WorkspaceData,+};+use crate::shape::{AxisMask, Cuboid, Shape, SupportMap, VoxelData, VoxelType, Voxels};+use crate::utils::hashmap::{Entry, HashMap};+use crate::utils::PoseOpt;+use alloc::{boxed::Box, vec::Vec};+use num::AsPrimitive;++#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Clone)]+pub(crate) struct VoxelsShapeSubDetector {+ pub manifold_id: usize,+ pub selected_contacts: u32,+ pub timestamp: bool,+}++#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[derive(Clone, Eq, Hash, PartialEq)]+pub(crate) struct VoxelsWorkspaceKey<const N: usize> {+ #[cfg_attr(feature = "serde-serialize", serde(with = "serde_arrays"))]+ idx: [u32; N],+}++impl<const N: usize> From<[u32; N]> for VoxelsWorkspaceKey<N> {+ fn from(idx: [u32; N]) -> Self {+ Self { idx }+ }+}++// NOTE: this is using a similar kind of cache as compound shape and height-field.+// It is different from the trimesh cash though. Which one is better?+/// A workspace for collision-detection against voxels shape.+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[derive(Clone, Default)]+pub struct VoxelsShapeContactManifoldsWorkspace<const N: usize> {+ pub(crate) timestamp: bool,+ pub(crate) sub_detectors: HashMap<VoxelsWorkspaceKey<N>, VoxelsShapeSubDetector>,+}++impl<const N: usize> VoxelsShapeContactManifoldsWorkspace<N> {+ /// A new empty workspace for collision-detection against voxels shape.+ pub fn new() -> Self {+ Self::default()+ }++ pub(crate) fn ensure_exists(workspace: &mut Option<ContactManifoldsWorkspace>)+ where+ Self: WorkspaceData,+ {+ if workspace+ .as_ref()+ .and_then(|w| {+ w.0.downcast_ref::<VoxelsShapeContactManifoldsWorkspace<N>>()+ })+ .is_some()+ {+ return;+ }++ *workspace = Some(ContactManifoldsWorkspace(Box::new(+ VoxelsShapeContactManifoldsWorkspace::new(),+ )));+ }+}++impl WorkspaceData for VoxelsShapeContactManifoldsWorkspace<2> {+ fn as_typed_workspace_data(&self) -> TypedWorkspaceData<'_> {+ TypedWorkspaceData::VoxelsShapeContactManifoldsWorkspace(self)+ }++ fn clone_dyn(&self) -> Box<dyn WorkspaceData> {+ Box::new(self.clone())+ }+}++/// Computes the contact manifold between a convex shape and a voxels shape, both represented as a `Shape` trait-object.+pub fn contact_manifolds_voxels_shape_shapes<ManifoldData, ContactData>(+ dispatcher: &dyn PersistentQueryDispatcher<ManifoldData, ContactData>,+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+) where+ ManifoldData: Default + Clone,+ ContactData: Default + Copy,+{+ if let Some(voxels1) = shape1.as_voxels() {+ contact_manifolds_voxels_shape(+ dispatcher, pos12, voxels1, shape2, prediction, manifolds, workspace, false,+ );+ } else if let Some(voxels2) = shape2.as_voxels() {+ contact_manifolds_voxels_shape(+ dispatcher,+ &pos12.inverse(),+ voxels2,+ shape1,+ prediction,+ manifolds,+ workspace,+ true,+ );+ }+}++/// Computes the contact manifold between a convex shape and a voxels shape.+pub fn contact_manifolds_voxels_shape<ManifoldData, ContactData>(+ dispatcher: &dyn PersistentQueryDispatcher<ManifoldData, ContactData>,+ pos12: &Pose,+ voxels1: &Voxels,+ shape2: &dyn Shape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+ flipped: bool,+) where+ ManifoldData: Default + Clone,+ ContactData: Default + Copy,+{+ VoxelsShapeContactManifoldsWorkspace::<2>::ensure_exists(workspace);+ let workspace: &mut VoxelsShapeContactManifoldsWorkspace<2> =+ workspace.as_mut().unwrap().0.downcast_mut().unwrap();+ let new_timestamp = !workspace.timestamp;+ workspace.timestamp = new_timestamp;++ // TODO: avoid reallocating the new `manifolds` vec at each step.+ let mut old_manifolds = core::mem::take(manifolds);++ let radius1 = voxels1.voxel_size() / 2.0;++ let aabb1 = voxels1.local_aabb();+ // Loosen by `prediction` (like the trimesh/heightfield/compound manifold generators do)+ // so that speculative contacts within the prediction distance are generated too.+ let aabb2_1 = shape2.compute_aabb(pos12).loosened(prediction);+ let domain2_1 = Aabb {+ mins: aabb2_1.mins - radius1 * 10.0,+ maxs: aabb2_1.maxs + radius1 * 10.0,+ };++ if let Some(intersection_aabb1) = aabb1.intersection(&aabb2_1) {+ for vox1 in voxels1.voxels_intersecting_local_aabb(&intersection_aabb1) {+ let vox_type1 = vox1.state.voxel_type();++ // TODO: would be nice to have a strategy to handle interior voxels for depenetration.+ if vox_type1 == VoxelType::Empty || vox_type1 == VoxelType::Interior {+ continue;+ }++ let canon1 = CanonicalVoxelShape::from_voxel(voxels1, &vox1);++ // TODO: could we refactor the workspace system between Voxels, HeightField, and CompoundShape?+ // (and maybe TriMesh too but it’s using a different approach).+ let (sub_detector, manifold_updated) =+ match workspace.sub_detectors.entry(canon1.workspace_key.into()) {+ Entry::Occupied(entry) => {+ let sub_detector = entry.into_mut();++ if sub_detector.timestamp != new_timestamp {+ let manifold = old_manifolds[sub_detector.manifold_id].take();+ *sub_detector = VoxelsShapeSubDetector {+ manifold_id: manifolds.len(),+ timestamp: new_timestamp,+ selected_contacts: 0,+ };++ manifolds.push(manifold);+ (sub_detector, false)+ } else {+ (sub_detector, true)+ }+ }+ Entry::Vacant(entry) => {+ let sub_detector = VoxelsShapeSubDetector {+ manifold_id: manifolds.len(),+ selected_contacts: 0,+ timestamp: new_timestamp,+ };++ let vid = vox1.linear_id.flat_id() as u32;+ let (id1, id2) = if flipped { (0, vid) } else { (vid, 0) };+ manifolds.push(ContactManifold::with_data(+ id1,+ id2,+ ManifoldData::default(),+ ));++ (entry.insert(sub_detector), false)+ }+ };++ /*+ * Update the contact manifold if needed.+ */+ let manifold = &mut manifolds[sub_detector.manifold_id];++ if !manifold_updated {+ let (canonical_center1, canonical_pseudo_cube1) =+ canon1.cuboid(voxels1, &vox1, domain2_1);++ let canonical_shape1 = &canonical_pseudo_cube1 as &dyn Shape;+ let canonical_pos12 = Pose::from_translation(-canonical_center1) * pos12;++ // If we already computed contacts in the previous simulation step, their+ // local points are relative to the previously calculated canonical shape+ // which might not have the same local center as the one computed in this+ // step (because it’s based on the position of shape2 relative to voxels1).+ // So we need to adjust the local points to account for the position difference+ // and keep the point at the same "canonica-shape-space" location as in the previous frame.+ let prev_center = if flipped {+ manifold+ .subshape_pos2()+ .as_ref()+ .map(|p| p.translation)+ .unwrap_or_default()+ } else {+ manifold+ .subshape_pos1()+ .as_ref()+ .map(|p| p.translation)+ .unwrap_or_default()+ };+ let delta_center = canonical_center1 - prev_center;++ if flipped {+ for pt in &mut manifold.points {+ pt.local_p2 -= delta_center;+ }+ } else {+ for pt in &mut manifold.points {+ pt.local_p1 -= delta_center;+ }+ }++ // Update contacts.+ if flipped {+ manifold.set_subshape_pos2(Some(Pose::from_translation(canonical_center1)));+ let _ = dispatcher.contact_manifold_convex_convex(+ &canonical_pos12.inverse(),+ shape2,+ canonical_shape1,+ None,+ None,+ prediction,+ manifold,+ );+ } else {+ manifold.set_subshape_pos1(Some(Pose::from_translation(canonical_center1)));+ let _ = dispatcher.contact_manifold_convex_convex(+ &canonical_pos12,+ canonical_shape1,+ shape2,+ None,+ None,+ prediction,+ manifold,+ );+ }+ }++ /*+ * Filter-out points that don’t belong to this block.+ */+ let test_voxel = Cuboid::new(radius1 + Vector::splat(1.0e-2));+ let penetration_dir1 = if flipped {+ manifold.local_n2+ } else {+ manifold.local_n1+ };++ for (i, pt) in manifold.points.iter().enumerate() {+ if pt.dist < 0.0 {+ // If this is a penetration, double-check that we are not hitting the+ // interior of the infinitely expanded canonical shape by checking if+ // the opposite normal had led to a better vector.+ let cuboid1 = Cuboid::new(radius1);+ let sp1 = cuboid1.local_support_point(-penetration_dir1) + vox1.center;+ let sm2 = shape2+ .as_support_map()+ .expect("Unsupported collision pair.");+ let sp2 = sm2.support_point(pos12, penetration_dir1);+ let test_dist = (sp2 - sp1).dot(-penetration_dir1);+ let keep = test_dist < pt.dist;++ if !keep {+ // We don’t want to keep this point as it is an incorrect penetration+ // caused by the canonical shape expansion.+ continue;+ }+ }++ let pt_in_voxel_space = if flipped {+ manifold.subshape_pos2().transform_point(pt.local_p2) - vox1.center+ } else {+ manifold.subshape_pos1().transform_point(pt.local_p1) - vox1.center+ };+ sub_detector.selected_contacts |=+ (test_voxel.contains_local_point(pt_in_voxel_space) as u32) << i;+ }+ }+ }++ // Remove contacts marked as ignored.+ for sub_detector in workspace.sub_detectors.values() {+ if sub_detector.timestamp == new_timestamp {+ let manifold = &mut manifolds[sub_detector.manifold_id];+ let mut k = 0;+ manifold.points.retain(|_| {+ let keep = (sub_detector.selected_contacts & (1 << k)) != 0;+ k += 1;+ keep+ });+ }+ }++ // Remove detectors which no longer index a valid manifold.+ workspace+ .sub_detectors+ .retain(|_, detector| detector.timestamp == new_timestamp);+}++#[derive(Copy, Clone, Debug)]+pub(crate) struct CanonicalVoxelShape {+ pub range: [IVector; 2],+ pub workspace_key: [u32; 2],+}++impl CanonicalVoxelShape {+ pub fn from_voxel(voxels: &Voxels, vox: &VoxelData) -> Self {+ let mut key_low = vox.grid_coords;+ let mut key_high = key_low;++ // NOTE: the mins/maxs here are offset by 1 so we can expand past the last voxel if it+ // happens to also be infinite along the same axis (due to cross-voxels internal edges+ // detection).+ let mins = voxels.domain()[0] - IVector::splat(1);+ let maxs = voxels.domain()[1];+ let counts = maxs - mins;+ let mask1 = vox.state.free_faces();++ let adjust_canon = |axis: AxisMask, i: usize, key: &mut IVector, val: Int| {+ if !mask1.contains(axis) {+ key.ivset(i, val.as_());+ }+ };++ adjust_canon(AxisMask::X_POS, 0, &mut key_high, maxs.x);+ adjust_canon(AxisMask::X_NEG, 0, &mut key_low, mins.x);+ adjust_canon(AxisMask::Y_POS, 1, &mut key_high, maxs.y);+ adjust_canon(AxisMask::Y_NEG, 1, &mut key_low, mins.y);++ #[cfg(feature = "dim3")]+ {+ adjust_canon(AxisMask::Z_POS, 2, &mut key_high, maxs.z);+ adjust_canon(AxisMask::Z_NEG, 2, &mut key_low, mins.z);+ }++ #[cfg(feature = "dim2")]+ let workspace_id = |vox: IVector| {+ let local = vox - mins;+ (local.x + local.y * counts.x) as u32+ };++ #[cfg(feature = "dim3")]+ let workspace_id = |vox: IVector| {+ let local = vox - mins;+ (local.x + local.y * counts.x + local.z * counts.x * counts.y) as u32+ };++ Self {+ range: [key_low, key_high],+ workspace_key: [workspace_id(key_low), workspace_id(key_high)],+ }+ }++ pub fn cuboid(&self, voxels: &Voxels, vox: &VoxelData, domain2_1: Aabb) -> (Vector, Cuboid) {+ let radius = voxels.voxel_size() / 2.0;+ let mut canonical_mins = voxels.voxel_center(self.range[0]);+ let mut canonical_maxs = voxels.voxel_center(self.range[1]);++ for k in 0..DIM {+ if self.range[0].ivget(k) != vox.grid_coords.ivget(k) {+ canonical_mins.vset(k, canonical_mins.vget(k).max(domain2_1.mins.vget(k)));+ }++ if self.range[1].ivget(k) != vox.grid_coords.ivget(k) {+ canonical_maxs.vset(k, canonical_maxs.vget(k).min(domain2_1.maxs.vget(k)));+ }+ }++ let canonical_half_extents = (canonical_maxs - canonical_mins) / 2.0 + radius;+ let canonical_center = canonical_mins.midpoint(canonical_maxs);+ let canonical_cube = Cuboid::new(canonical_half_extents);++ (canonical_center, canonical_cube)+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_voxels_voxels.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_voxels_voxels.rsnew file mode 100644index 0000000..630ab3a--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_voxels_voxels.rs@@ -0,0 +1,332 @@+use crate::bounding_volume::BoundingVolume;+use crate::math::{Pose, Real, Vector};+use crate::query::contact_manifolds::{CanonicalVoxelShape, VoxelsShapeContactManifoldsWorkspace};+use crate::query::details::VoxelsShapeSubDetector;+use crate::query::{+ ContactManifold, ContactManifoldsWorkspace, PersistentQueryDispatcher, PointQuery,+ TypedWorkspaceData, WorkspaceData,+};+use crate::shape::{Cuboid, Shape, SupportMap, VoxelData, VoxelType, Voxels};+use crate::utils::hashmap::Entry;+use crate::utils::PoseOpt;+use alloc::{boxed::Box, vec::Vec};++impl WorkspaceData for VoxelsShapeContactManifoldsWorkspace<4> {+ fn as_typed_workspace_data(&self) -> TypedWorkspaceData<'_> {+ TypedWorkspaceData::VoxelsVoxelsContactManifoldsWorkspace(self)+ }++ fn clone_dyn(&self) -> Box<dyn WorkspaceData> {+ Box::new(self.clone())+ }+}++/// Computes the contact manifold between a convex shape and a ball, both represented as a `Shape` trait-object.+pub fn contact_manifolds_voxels_voxels_shapes<ManifoldData, ContactData>(+ dispatcher: &dyn PersistentQueryDispatcher<ManifoldData, ContactData>,+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+) where+ ManifoldData: Default + Clone,+ ContactData: Default + Copy,+{+ if let (Some(voxels1), Some(voxels2)) = (shape1.as_voxels(), shape2.as_voxels()) {+ contact_manifolds_voxels_voxels(+ dispatcher, pos12, voxels1, voxels2, prediction, manifolds, workspace,+ );+ }+}++/// Computes the contact manifold between a convex shape and a ball.+pub fn contact_manifolds_voxels_voxels<'a, ManifoldData, ContactData>(+ dispatcher: &dyn PersistentQueryDispatcher<ManifoldData, ContactData>,+ pos12: &Pose,+ voxels1: &'a Voxels,+ voxels2: &'a Voxels,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+) where+ ManifoldData: Default + Clone,+ ContactData: Default + Copy,+{+ VoxelsShapeContactManifoldsWorkspace::<4>::ensure_exists(workspace);+ let workspace: &mut VoxelsShapeContactManifoldsWorkspace<4> =+ workspace.as_mut().unwrap().0.downcast_mut().unwrap();+ let new_timestamp = !workspace.timestamp;+ workspace.timestamp = new_timestamp;++ // TODO: avoid reallocating the new `manifolds` vec at each step.+ let mut old_manifolds = core::mem::take(manifolds);++ let radius1 = voxels1.voxel_size() / 2.0;+ let radius2 = voxels2.voxel_size() / 2.0;++ let aabb1 = voxels1.local_aabb().loosened(prediction / 2.0);+ let aabb2 = voxels2.local_aabb().loosened(prediction / 2.0);++ let pos21 = pos12.inverse();++ let mut checked_hits = 0;++ if let Some((intersection_aabb1, intersection_aabb2)) =+ aabb1.aligned_intersections(pos12, &aabb2)+ {+ let domain_margin = (radius1 + radius2) * 10.0;+ let full_domain2_1 = voxels2.compute_aabb(pos12).add_half_extents(domain_margin);+ let domain2_1 = full_domain2_1+ .intersection(&aabb1.add_half_extents(domain_margin))+ .unwrap_or(full_domain2_1);+ let full_domain1_2 = voxels1.compute_aabb(&pos21).add_half_extents(domain_margin);+ let domain1_2 = full_domain1_2+ .intersection(&aabb2.add_half_extents(domain_margin))+ .unwrap_or(full_domain1_2);++ let mut detect_hit = |canon1: CanonicalVoxelShape,+ canon2: CanonicalVoxelShape,+ vox1: &VoxelData,+ vox2: &VoxelData| {+ // Compute canonical shapes and dispatch.+ let workspace_key = [+ canon1.workspace_key[0],+ canon1.workspace_key[1],+ canon2.workspace_key[0],+ canon2.workspace_key[1],+ ];++ checked_hits += 1;++ // TODO: could we refactor the workspace system with the Voxels-Shape+ // collision detection system?+ let (sub_detector, manifold_updated) =+ match workspace.sub_detectors.entry(workspace_key.into()) {+ Entry::Occupied(entry) => {+ let sub_detector = entry.into_mut();++ if sub_detector.timestamp != new_timestamp {+ let manifold = old_manifolds[sub_detector.manifold_id].take();+ *sub_detector = VoxelsShapeSubDetector {+ manifold_id: manifolds.len(),+ timestamp: new_timestamp,+ selected_contacts: 0,+ };++ manifolds.push(manifold);+ (sub_detector, false)+ } else {+ (sub_detector, true)+ }+ }+ Entry::Vacant(entry) => {+ let sub_detector = VoxelsShapeSubDetector {+ manifold_id: manifolds.len(),+ selected_contacts: 0,+ timestamp: new_timestamp,+ };++ manifolds.push(ContactManifold::with_data(+ vox1.linear_id.flat_id() as u32,+ vox2.linear_id.flat_id() as u32,+ ManifoldData::default(),+ ));++ (entry.insert(sub_detector), false)+ }+ };++ /*+ * Update the contact manifold if needed.+ */+ let manifold = &mut manifolds[sub_detector.manifold_id];+ let (canonical_center1, canonical_pseudo_cube1) =+ canon1.cuboid(voxels1, vox1, domain2_1);+ let (canonical_center2, canonical_pseudo_cube2) =+ canon2.cuboid(voxels2, vox2, domain1_2);++ if !manifold_updated {+ let canonical_pos12 = Pose::from_translation(-canonical_center1)+ * pos12+ * Pose::from_translation(canonical_center2);++ // If we already computed contacts in the previous simulation step, their+ // local points are relative to the previously calculated canonical shape+ // which might not have the same local center as the one computed in this+ // step (because it’s based on the position of shape2 relative to voxels1).+ // So we need to adjust the local points to account for the position difference+ // and keep the point at the same "canonical-shape-space" location as in the previous frame.+ let prev_center1 = manifold+ .subshape_pos1()+ .as_ref()+ .map(|p| p.translation)+ .unwrap_or_default();+ let delta_center1 = canonical_center1 - prev_center1;+ let prev_center2 = manifold+ .subshape_pos2()+ .as_ref()+ .map(|p| p.translation)+ .unwrap_or_default();+ let delta_center2 = canonical_center2 - prev_center2;++ for pt in &mut manifold.points {+ pt.local_p1 -= delta_center1;+ pt.local_p2 -= delta_center2;+ }++ // Update contacts.+ manifold.set_subshape_pos1(Some(Pose::from_translation(canonical_center1)));+ manifold.set_subshape_pos2(Some(Pose::from_translation(canonical_center2)));+ let _ = dispatcher.contact_manifold_convex_convex(+ &canonical_pos12,+ &canonical_pseudo_cube1,+ &canonical_pseudo_cube2,+ None,+ None,+ prediction,+ manifold,+ );+ }++ /*+ * Filter-out points that don’t belong to this block.+ */+ let test_voxel1 = Cuboid::new(radius1 + Vector::splat(1.0e-2));+ let test_voxel2 = Cuboid::new(radius2 + Vector::splat(1.0e-2));+ let penetration_dir1 = manifold.local_n1;++ for (i, pt) in manifold.points.iter().enumerate() {+ if pt.dist < 0.0 {+ // If this is a penetration, double-check that we are not hitting the+ // interior of the infinitely expanded canonical shape by checking if+ // the opposite normal had led to a better vector.+ let cuboid1 = Cuboid::new(radius1);+ let cuboid2 = Cuboid::new(radius2);+ let sp1 = cuboid1.local_support_point(-penetration_dir1) + vox1.center;+ let sp2 = cuboid2.support_point(+ &(pos12 * Pose::from_translation(vox2.center)),+ penetration_dir1,+ );+ let test_dist = (sp2 - sp1).dot(-penetration_dir1);+ let keep = test_dist < pt.dist;++ if !keep {+ // We don’t want to keep this point as it is an incorrect penetration+ // caused by the canonical shape expansion.+ continue;+ }+ }++ let pt_in_voxel_space1 =+ manifold.subshape_pos1().transform_point(pt.local_p1) - vox1.center;+ let pt_in_voxel_space2 =+ manifold.subshape_pos2().transform_point(pt.local_p2) - vox2.center;+ sub_detector.selected_contacts |=+ ((test_voxel1.contains_local_point(pt_in_voxel_space1) as u32) << i)+ & ((test_voxel2.contains_local_point(pt_in_voxel_space2) as u32) << i);+ }+ };++ for vox1 in voxels1.voxels_intersecting_local_aabb(&intersection_aabb1) {+ let type1 = vox1.state.voxel_type();+ match type1 {+ #[cfg(feature = "dim2")]+ VoxelType::Vertex => { /* Ok */ }+ #[cfg(feature = "dim3")]+ VoxelType::Vertex | VoxelType::Edge => { /* Ok */ }+ _ => continue,+ }++ let canon1 = CanonicalVoxelShape::from_voxel(voxels1, &vox1);+ let centered_aabb1_2 = Cuboid::new(radius1 + Vector::splat(prediction))+ .compute_aabb(&(pos21 * Pose::from_translation(vox1.center)));++ for vox2 in voxels2.voxels_intersecting_local_aabb(¢ered_aabb1_2) {+ let type2 = vox2.state.voxel_type();++ #[cfg(feature = "dim2")]+ match (type1, type2) {+ (VoxelType::Vertex, VoxelType::Vertex)+ | (VoxelType::Vertex, VoxelType::Face)+ | (VoxelType::Face, VoxelType::Vertex) => { /* OK */ }+ _ => continue, /* Ignore */+ }++ #[cfg(feature = "dim3")]+ match (type1, type2) {+ (VoxelType::Vertex, VoxelType::Vertex)+ | (VoxelType::Vertex, VoxelType::Edge)+ | (VoxelType::Vertex, VoxelType::Face)+ | (VoxelType::Edge, VoxelType::Vertex)+ | (VoxelType::Edge, VoxelType::Edge)+ | (VoxelType::Face, VoxelType::Vertex) => { /* OK */ }+ _ => continue, /* Ignore */+ }++ let canon2 = CanonicalVoxelShape::from_voxel(voxels2, &vox2);+ detect_hit(canon1, canon2, &vox1, &vox2);+ }+ }++ for vox2 in voxels2.voxels_intersecting_local_aabb(&intersection_aabb2) {+ let type2 = vox2.state.voxel_type();+ match type2 {+ #[cfg(feature = "dim2")]+ VoxelType::Vertex => { /* Ok */ }+ #[cfg(feature = "dim3")]+ VoxelType::Vertex | VoxelType::Edge => { /* Ok */ }+ _ => continue,+ }++ let canon2 = CanonicalVoxelShape::from_voxel(voxels2, &vox2);+ let centered_aabb2_1 = Cuboid::new(radius2 + Vector::splat(prediction))+ .compute_aabb(&(pos12 * Pose::from_translation(vox2.center)));++ for vox1 in voxels1.voxels_intersecting_local_aabb(¢ered_aabb2_1) {+ let type1 = vox1.state.voxel_type();++ #[cfg(feature = "dim2")]+ match (type1, type2) {+ (VoxelType::Vertex, VoxelType::Vertex)+ | (VoxelType::Vertex, VoxelType::Face)+ | (VoxelType::Face, VoxelType::Vertex) => { /* OK */ }+ _ => continue, /* Ignore */+ }++ #[cfg(feature = "dim3")]+ match (type1, type2) {+ (VoxelType::Vertex, VoxelType::Vertex)+ | (VoxelType::Vertex, VoxelType::Edge)+ | (VoxelType::Vertex, VoxelType::Face)+ | (VoxelType::Edge, VoxelType::Vertex)+ | (VoxelType::Edge, VoxelType::Edge)+ | (VoxelType::Face, VoxelType::Vertex) => { /* OK */ }+ _ => continue, /* Ignore */+ }++ let canon1 = CanonicalVoxelShape::from_voxel(voxels1, &vox1);+ detect_hit(canon1, canon2, &vox1, &vox2);+ }+ }++ // Remove contacts marked as ignored.+ for sub_detector in workspace.sub_detectors.values() {+ if sub_detector.timestamp == new_timestamp {+ let manifold = &mut manifolds[sub_detector.manifold_id];+ let mut k = 0;+ manifold.points.retain(|_| {+ let keep = (sub_detector.selected_contacts & (1 << k)) != 0;+ k += 1;+ keep+ });+ }+ }+ }++ // Remove detectors which no longer index a valid manifold.+ workspace+ .sub_detectors+ .retain(|_, detector| detector.timestamp == new_timestamp);+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_workspace.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_workspace.rsnew file mode 100644index 0000000..4a558a9--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/contact_manifolds_workspace.rs@@ -0,0 +1,142 @@+#![allow(clippy::multiple_bound_locations)] // for impl_downcast++use alloc::boxed::Box;+use downcast_rs::{impl_downcast, DowncastSync};++use crate::query::contact_manifolds::{+ CompositeShapeCompositeShapeContactManifoldsWorkspace,+ CompositeShapeShapeContactManifoldsWorkspace,+ HeightFieldCompositeShapeContactManifoldsWorkspace, HeightFieldShapeContactManifoldsWorkspace,+ TriMeshShapeContactManifoldsWorkspace, VoxelsShapeContactManifoldsWorkspace,+};++#[derive(Copy, Clone)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize))]+/// Enum representing workspace data of a specific type.+pub enum TypedWorkspaceData<'a> {+ /// A trimesh workspace.+ TriMeshShapeContactManifoldsWorkspace(&'a TriMeshShapeContactManifoldsWorkspace),+ /// A heightfield vs. shape workspace.+ HeightfieldShapeContactManifoldsWorkspace(&'a HeightFieldShapeContactManifoldsWorkspace),+ /// A heightfield vs. composite shape workspace.+ HeightfieldCompositeShapeContactManifoldsWorkspace(+ &'a HeightFieldCompositeShapeContactManifoldsWorkspace,+ ),+ /// A composite shape vs. composite shape workspace.+ CompositeShapeCompositeShapeContactManifoldsWorkspace(+ &'a CompositeShapeCompositeShapeContactManifoldsWorkspace,+ ),+ /// A composite shape vs. shape workspace.+ CompositeShapeShapeContactManifoldsWorkspace(&'a CompositeShapeShapeContactManifoldsWorkspace),+ /// A voxels vs. shape workspace.+ VoxelsShapeContactManifoldsWorkspace(&'a VoxelsShapeContactManifoldsWorkspace<2>),+ /// A voxels vs. composite shape workspace.+ VoxelsCompositeShapeContactManifoldsWorkspace(&'a VoxelsShapeContactManifoldsWorkspace<3>),+ /// A voxels vs. voxels workspace.+ VoxelsVoxelsContactManifoldsWorkspace(&'a VoxelsShapeContactManifoldsWorkspace<4>),+ /// A custom workspace.+ Custom,+}++// NOTE: must match the TypedWorkspaceData enum.+#[cfg(feature = "serde-serialize")]+#[derive(Deserialize)]+enum DeserializableWorkspaceData {+ TriMeshShapeContactManifoldsWorkspace(TriMeshShapeContactManifoldsWorkspace),+ HeightfieldShapeContactManifoldsWorkspace(HeightFieldShapeContactManifoldsWorkspace),+ HeightfieldCompositeShapeContactManifoldsWorkspace(+ HeightFieldCompositeShapeContactManifoldsWorkspace,+ ),+ CompositeShapeCompositeShapeContactManifoldsWorkspace(+ CompositeShapeCompositeShapeContactManifoldsWorkspace,+ ),+ CompositeShapeShapeContactManifoldsWorkspace(CompositeShapeShapeContactManifoldsWorkspace),+ VoxelsShapeContactManifoldsWorkspace(VoxelsShapeContactManifoldsWorkspace<2>),+ VoxelsCompositeShapeContactManifoldsWorkspace(VoxelsShapeContactManifoldsWorkspace<3>),+ VoxelsVoxelsContactManifoldsWorkspace(VoxelsShapeContactManifoldsWorkspace<4>),+ #[allow(dead_code)]+ Custom,+}++#[cfg(feature = "serde-serialize")]+impl DeserializableWorkspaceData {+ pub fn into_contact_manifold_workspace(self) -> Option<ContactManifoldsWorkspace> {+ match self {+ DeserializableWorkspaceData::TriMeshShapeContactManifoldsWorkspace(w) => {+ Some(ContactManifoldsWorkspace(Box::new(w)))+ }+ DeserializableWorkspaceData::HeightfieldShapeContactManifoldsWorkspace(w) => {+ Some(ContactManifoldsWorkspace(Box::new(w)))+ }+ DeserializableWorkspaceData::HeightfieldCompositeShapeContactManifoldsWorkspace(w) => {+ Some(ContactManifoldsWorkspace(Box::new(w)))+ }+ DeserializableWorkspaceData::CompositeShapeCompositeShapeContactManifoldsWorkspace(+ w,+ ) => Some(ContactManifoldsWorkspace(Box::new(w))),+ DeserializableWorkspaceData::CompositeShapeShapeContactManifoldsWorkspace(w) => {+ Some(ContactManifoldsWorkspace(Box::new(w)))+ }+ DeserializableWorkspaceData::VoxelsShapeContactManifoldsWorkspace(w) => {+ Some(ContactManifoldsWorkspace(Box::new(w)))+ }+ DeserializableWorkspaceData::VoxelsCompositeShapeContactManifoldsWorkspace(w) => {+ Some(ContactManifoldsWorkspace(Box::new(w)))+ }+ DeserializableWorkspaceData::VoxelsVoxelsContactManifoldsWorkspace(w) => {+ Some(ContactManifoldsWorkspace(Box::new(w)))+ }+ DeserializableWorkspaceData::Custom => None,+ }+ }+}++/// Data from a [`ContactManifoldsWorkspace`].+pub trait WorkspaceData: DowncastSync {+ /// Gets the underlying workspace as an enum.+ fn as_typed_workspace_data(&self) -> TypedWorkspaceData<'_>;++ /// Clones `self`.+ fn clone_dyn(&self) -> Box<dyn WorkspaceData>;+}++impl_downcast!(sync WorkspaceData);++// Note we have this newtype because it simplifies the serialization/deserialization code.+/// A serializable workspace used by some contact-manifolds computation algorithms.+pub struct ContactManifoldsWorkspace(pub Box<dyn WorkspaceData>);++impl Clone for ContactManifoldsWorkspace {+ fn clone(&self) -> Self {+ ContactManifoldsWorkspace(self.0.clone_dyn())+ }+}++impl<T: WorkspaceData> From<T> for ContactManifoldsWorkspace {+ fn from(data: T) -> Self {+ Self(Box::new(data) as Box<dyn WorkspaceData>)+ }+}++#[cfg(feature = "serde-serialize")]+impl serde::Serialize for ContactManifoldsWorkspace {+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: serde::Serializer,+ {+ self.0.as_typed_workspace_data().serialize(serializer)+ }+}++#[cfg(feature = "serde-serialize")]+impl<'de> serde::Deserialize<'de> for ContactManifoldsWorkspace {+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>+ where+ D: serde::Deserializer<'de>,+ {+ use crate::serde::de::Error;+ DeserializableWorkspaceData::deserialize(deserializer)?+ .into_contact_manifold_workspace()+ .ok_or(D::Error::custom("Cannot deserialize custom shape."))+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/mod.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/mod.rsnew file mode 100644index 0000000..7fe44fb--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/mod.rs@@ -0,0 +1,212 @@+//! Contact manifolds for persistent collision detection.+//!+//! # What are Contact Manifolds?+//!+//! A **contact manifold** is a collection of contact points between two shapes that share+//! the same contact normal and contact kinematics. Contact manifolds are fundamental to+//! physics simulation because they provide stable, persistent contact information that can+//! be reused across multiple simulation frames.+//!+//! Unlike single-shot contact queries that compute contact information from scratch each+//! frame, contact manifolds maintain and update contact information over time, leading to+//! more stable and efficient physics simulations.+//!+//! # Why are Contact Manifolds Important?+//!+//! Contact manifolds are critical for physics simulation for several reasons:+//!+//! 1. **Stability**: By maintaining persistent contact information across frames, physics+//! engines can provide more stable contact resolution without jittering.+//!+//! 2. **Performance**: Updating existing contact points is often faster than recomputing+//! them from scratch, especially for complex shapes.+//!+//! 3. **Contact Tracking**: Each contact point in a manifold has a unique identifier+//! (feature IDs) that allows physics engines to track contacts over time and maintain+//! contact-specific data like accumulated impulses for warm-starting.+//!+//! 4. **Multiple Contact Points**: Many shape pairs require multiple contact points for+//! stable physics simulation. For example, a box resting on a plane typically needs+//! 4 contact points (one for each corner).+//!+//! # Basic Usage+//!+//! ```rust+//! # #[cfg(all(feature = "dim3", feature = "f32"))] {+//! use parry3d::query::{ContactManifold, TrackedContact};+//! use parry3d::query::details::contact_manifold_ball_ball;+//! use parry3d::shape::Ball;+//! use parry3d::math::{Pose, Vector};+//!+//! // Create two balls+//! let ball1 = Ball::new(1.0);+//! let ball2 = Ball::new(1.0);+//!+//! // Position them so they're touching+//! let pos12 = Pose::translation(1.9, 0.0, 0.0);+//!+//! // Create an empty contact manifold+//! // Note: ManifoldData and ContactData are user-defined types for tracking data+//! let mut manifold = ContactManifold::<(), ()>::new();+//!+//! // Compute the contact manifold with a prediction distance+//! let prediction = 0.1; // Look ahead distance+//! contact_manifold_ball_ball(&pos12, &ball1, &ball2, prediction, &mut manifold);+//!+//! // Check if we have any contacts+//! if let Some(contact) = manifold.points.first() {+//! println!("Contact distance: {}", contact.dist);+//! println!("Contact point on ball1: {:?}", contact.local_p1);+//! println!("Contact point on ball2: {:?}", contact.local_p2);+//! }+//! # }+//! ```+//!+//! # Updating Contact Manifolds+//!+//! One of the key benefits of contact manifolds is the ability to efficiently update them+//! using spatial coherence:+//!+//! ```rust+//! # #[cfg(all(feature = "dim3", feature = "f32"))] {+//! use parry3d::query::{ContactManifold, TrackedContact};+//! use parry3d::query::details::contact_manifold_ball_ball;+//! use parry3d::shape::Ball;+//! use parry3d::math::Pose;+//!+//! let ball1 = Ball::new(1.0);+//! let ball2 = Ball::new(1.0);+//! let mut manifold = ContactManifold::<(), ()>::new();+//!+//! // Initial contact computation+//! let pos12_frame1 = Pose::translation(1.9, 0.0, 0.0);+//! contact_manifold_ball_ball(&pos12_frame1, &ball1, &ball2, 0.1, &mut manifold);+//!+//! // On the next frame, try to update using spatial coherence+//! let pos12_frame2 = Pose::translation(1.85, 0.0, 0.0);+//!+//! // Try to update contacts efficiently+//! if !manifold.try_update_contacts(&pos12_frame2) {+//! // Update failed (shapes moved too much or orientation changed significantly)+//! // Fall back to full recomputation+//! contact_manifold_ball_ball(&pos12_frame2, &ball1, &ball2, 0.1, &mut manifold);+//! }+//! # }+//! ```+//!+//! # Contact Prediction+//!+//! The `prediction` parameter is a distance threshold that allows detecting contacts+//! slightly before shapes actually touch. This is useful for:+//!+//! - **Continuous Collision Detection**: Predicting contacts helps prevent tunneling+//! - **Speculative Contacts**: Physics engines can prepare for imminent collisions+//! - **Contact Caching**: Maintaining contacts even when shapes briefly separate+//!+//! A typical prediction value might be 1-10% of the smallest shape dimension.+//!+//! # Shape-Specific Contact Computation+//!+//! This module provides specialized contact manifold computation functions for various+//! shape pairs. Each function is optimized for the specific geometric properties of the+//! shapes involved:+//!+//! - `contact_manifold_ball_ball`: Two spheres (simplest case, always 1 contact)+//! - `contact_manifold_cuboid_cuboid`: Two boxes (up to 8 contacts in 3D)+//! - `contact_manifold_capsule_capsule`: Two capsules+//! - `contact_manifold_convex_ball`: Convex shape vs sphere+//! - And many more specialized functions for different shape combinations+//!+//! # Working with Composite Shapes+//!+//! For composite shapes (triangle meshes, heightfields, compounds), contact manifold+//! computation is more complex and requires workspace objects for efficient memory management:+//!+//! - `contact_manifolds_trimesh_shape`: Triangle mesh vs any shape+//! - `contact_manifolds_heightfield_shape`: Heightfield terrain vs any shape+//! - `contact_manifolds_composite_shape_shape`: Compound shape vs any shape+//! - `contact_manifolds_voxels_shape`: Voxel grid vs any shape+//!+//! These functions use workspace objects to avoid repeated allocations.++pub use self::contact_manifold::{ContactManifold, TrackedContact};+pub use self::contact_manifolds_ball_ball::{+ contact_manifold_ball_ball, contact_manifold_ball_ball_shapes,+};+pub use self::contact_manifolds_capsule_capsule::{+ contact_manifold_capsule_capsule, contact_manifold_capsule_capsule_shapes,+};+pub use self::contact_manifolds_convex_ball::{+ contact_manifold_convex_ball, contact_manifold_convex_ball_shapes,+};+// pub use self::contact_manifolds_cuboid_capsule::{+// contact_manifold_cuboid_capsule, contact_manifold_cuboid_capsule_shapes,+// };+pub use self::contact_manifolds_composite_shape_composite_shape::contact_manifolds_composite_shape_composite_shape;+pub use self::contact_manifolds_composite_shape_shape::contact_manifolds_composite_shape_shape;+pub use self::contact_manifolds_cuboid_cuboid::{+ contact_manifold_cuboid_cuboid, contact_manifold_cuboid_cuboid_shapes,+};+pub use self::contact_manifolds_cuboid_triangle::{+ contact_manifold_cuboid_triangle, contact_manifold_cuboid_triangle_shapes,+};+pub use self::contact_manifolds_halfspace_pfm::{+ contact_manifold_halfspace_pfm, contact_manifold_halfspace_pfm_shapes,+};+pub use self::contact_manifolds_heightfield_composite_shape::contact_manifolds_heightfield_composite_shape;+pub use self::contact_manifolds_heightfield_shape::{+ contact_manifolds_heightfield_shape, contact_manifolds_heightfield_shape_shapes,+};+pub use self::contact_manifolds_pfm_pfm::{+ contact_manifold_pfm_pfm, contact_manifold_pfm_pfm_shapes,+};+pub use self::contact_manifolds_trimesh_shape::{+ contact_manifolds_trimesh_shape, contact_manifolds_trimesh_shape_shapes,+};+pub use self::contact_manifolds_voxels_ball::contact_manifolds_voxels_ball_shapes;+pub use self::contact_manifolds_voxels_composite_shape::{+ contact_manifolds_voxels_composite_shape, contact_manifolds_voxels_composite_shape_shapes,+};+pub use self::contact_manifolds_voxels_shape::{+ contact_manifolds_voxels_shape, contact_manifolds_voxels_shape_shapes,+ VoxelsShapeContactManifoldsWorkspace,+};+pub(crate) use self::contact_manifolds_voxels_shape::{+ CanonicalVoxelShape, VoxelsShapeSubDetector,+};+pub use self::contact_manifolds_voxels_voxels::{+ contact_manifolds_voxels_voxels, contact_manifolds_voxels_voxels_shapes,+};+pub use self::contact_manifolds_workspace::{+ ContactManifoldsWorkspace, TypedWorkspaceData, WorkspaceData,+};+pub use self::normals_constraint::{NormalConstraints, NormalConstraintsPair};++use {+ self::contact_manifolds_composite_shape_composite_shape::CompositeShapeCompositeShapeContactManifoldsWorkspace,+ self::contact_manifolds_composite_shape_shape::CompositeShapeShapeContactManifoldsWorkspace,+ self::contact_manifolds_heightfield_composite_shape::HeightFieldCompositeShapeContactManifoldsWorkspace,+ self::contact_manifolds_heightfield_shape::HeightFieldShapeContactManifoldsWorkspace,+ self::contact_manifolds_trimesh_shape::TriMeshShapeContactManifoldsWorkspace,+};++mod contact_manifold;+mod contact_manifolds_ball_ball;+mod contact_manifolds_capsule_capsule;+mod contact_manifolds_convex_ball;+// mod contact_manifolds_cuboid_capsule;+mod contact_manifolds_composite_shape_composite_shape;+mod contact_manifolds_composite_shape_shape;+mod contact_manifolds_cuboid_cuboid;+mod contact_manifolds_cuboid_triangle;+mod contact_manifolds_halfspace_pfm;+mod contact_manifolds_heightfield_composite_shape;+mod contact_manifolds_heightfield_shape;+mod contact_manifolds_pfm_pfm;+mod contact_manifolds_trimesh_shape;+mod contact_manifolds_voxels_ball;+mod contact_manifolds_voxels_composite_shape;+mod contact_manifolds_voxels_shape;+mod contact_manifolds_voxels_voxels;+mod contact_manifolds_workspace;+mod normals_constraint;diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/normals_constraint.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/normals_constraint.rsnew file mode 100644index 0000000..b5d0517--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/normals_constraint.rs@@ -0,0 +1,125 @@+use crate::math::{Pose, Vector};++// NOTE: the 'static requirement is only needed for the following impl to work:+// impl<'a> TypedCompositeShape for dyn CompositeShape+// We can probably work something out if that becomes too restrictive in+// the future.+/// Constraints of contact normals, generally for internal edges resolution.+///+/// This trait used for applying constraints on normal direction for contact manifolds calculation.+/// Non-convex shapes will generally simplify collision-detection as a collection of simpler+/// convex-based collision-detection problems. However, that partial convex formulation allows+/// some contact normals that are theoretically impossible (in a convex analysis sense). The normal+/// constraints aims to correct/remove invalid normals, avoiding some artifacts in physics+/// simulations. In particular, this addresses the well-known "internal edges" problem on triangle+/// meshes and heightfields.+pub trait NormalConstraints: 'static {+ /// Corrects in-place or discards the specified normal (assumed to be unit-sized) based on the+ /// constraints encoded by `Self`.+ ///+ /// If this method returns `false` then the contacts associated to that normal should be+ /// considered invalid and be ignored by the collision-detection pipeline.+ fn project_local_normal_mut(&self, normal: &mut Vector) -> bool;+ /// Corrects or discards the specified normal (assumed to be unit-sized) based on the constraints+ /// encoded by `Self`.+ ///+ /// If this method returns `None` then the contacts associated to that normal should be+ /// considered invalid and be ignored by the collision-detection pipeline.+ fn project_local_normal(&self, mut normal: Vector) -> Option<Vector> {+ self.project_local_normal_mut(&mut normal).then_some(normal)+ }++ // NOTE: the normal is assumed to be unit-sized.+ /// Applies normal correction to the unit vectors `normal1` and `normal2` based on the+ /// assumption that `normal1` is in the same coordinates space as `Self`.+ ///+ /// The `normal2` will be modified to be equal to `-normal1` expressed in the local coordinate+ /// space of the second shape.+ ///+ /// If this method returns `false` then the contacts associated to that normal should be+ /// considered invalid and be ignored by the collision-detection pipeline.+ fn project_local_normal1(+ &self,+ pos12: &Pose,+ normal1: &mut Vector,+ normal2: &mut Vector,+ ) -> bool {+ if !self.project_local_normal_mut(normal1) {+ return false;+ }++ *normal2 = pos12.rotation.inverse() * -*normal1;++ true+ }++ /// Applies normal correction to the unit vectors `normal1` and `normal2` based on the+ /// assumption that `normal2` is in the same coordinates space as `Self`.+ ///+ /// The `normal1` will be modified to be equal to `-normal2` expressed in the local coordinate+ /// space of the first shape.+ ///+ /// If this method returns `false` then the contacts associated to that normal should be+ /// considered invalid and be ignored by the collision-detection pipeline.+ fn project_local_normal2(+ &self,+ pos12: &Pose,+ normal1: &mut Vector,+ normal2: &mut Vector,+ ) -> bool {+ if !self.project_local_normal_mut(normal2) {+ return false;+ }++ *normal1 = pos12.rotation * (-*normal2);++ true+ }+}++impl NormalConstraints for () {+ fn project_local_normal_mut(&self, _: &mut Vector) -> bool {+ true+ }+}++/// A pair of [`NormalConstraints`].+pub trait NormalConstraintsPair {+ /// Applies the normal constraints to `normal1` and `normal2`.+ ///+ /// This trait is mostly used internally to combine two [`NormalConstraints`] conveniently.+ fn project_local_normals(+ &self,+ pos12: &Pose,+ normal1: &mut Vector,+ normal2: &mut Vector,+ ) -> bool;+}++// We generally use Option<&dyn NormalConstraints> instead of the naked+// trait-object in our codebase so providing this impl is convenient.+impl NormalConstraintsPair+ for (+ Option<&dyn NormalConstraints>,+ Option<&dyn NormalConstraints>,+ )+{+ fn project_local_normals(+ &self,+ pos12: &Pose,+ normal1: &mut Vector,+ normal2: &mut Vector,+ ) -> bool {+ if let Some(proj) = self.0 {+ if !proj.project_local_normal1(pos12, normal1, normal2) {+ return false;+ }+ }++ if let Some(proj) = self.1 {+ proj.project_local_normal2(pos12, normal1, normal2)+ } else {+ true+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/contact_manifolds/polygon_polygon_contact_generator.rs b/renderer/third_party/parry3d/src/query/contact_manifolds/polygon_polygon_contact_generator.rsnew file mode 100644index 0000000..1de5039--- /dev/null+++ b/renderer/third_party/parry3d/src/query/contact_manifolds/polygon_polygon_contact_generator.rs@@ -0,0 +1,150 @@+#![allow(dead_code)] // TODO: remove this once we support polygons.++use crate::geometry::contact_generator::PrimitiveContactGenerationContext;+use crate::geometry::{sat, Contact, ContactData, ContactManifold, ContactManifoldData, Polygon};+use crate::math::{Pose, Vector, Real};+#[cfg(feature = "dim2")]+use crate::{math::Vector, utils};+use parry::query;++pub fn generate_contacts_polygon_polygon(_ctxt: &mut PrimitiveContactGenerationContext) {+ unimplemented!()+ // if let (Shape::Polygon(polygon1), Shape::Polygon(polygon2)) = (ctxt.shape1, ctxt.shape2) {+ // generate_contacts(+ // polygon1,+ // &ctxt.position1,+ // polygon2,+ // &ctxt.position2,+ // ctxt.manifold,+ // );+ // ContactManifoldData::update_warmstart_multiplier(ctxt.manifold);+ // } else {+ // unreachable!()+ // }+ //+}++fn generate_contacts<'a>(+ mut p1: &'a Polygon,+ mut m1: &'a Pose,+ mut p2: &'a Polygon,+ mut m2: &'a Pose,+ manifold: &'a mut ContactManifold,+) {+ let mut m12 = m1.inv_mul(&m2);+ let mut m21 = m12.inverse();++ if manifold.try_update_contacts(&m12) {+ return;+ }++ let mut sep1 = sat::polygon_polygon_compute_separation_features(p1, p2, &m12);+ if sep1.0 > 0.0 {+ manifold.points.clear();+ return;+ }++ let mut sep2 = sat::polygon_polygon_compute_separation_features(p2, p1, &m21);+ if sep2.0 > 0.0 {+ manifold.points.clear();+ return;+ }++ let mut swapped = false;+ if sep2.0 > sep1.0 {+ core::mem::swap(&mut sep1, &mut sep2);+ core::mem::swap(&mut m1, &mut m2);+ core::mem::swap(&mut p1, &mut p2);+ core::mem::swap(&mut m12, &mut m21);+ manifold.swap_identifiers();+ swapped = true;+ }++ let support_face1 = sep1.1;+ let local_n1 = p1.normals[support_face1];+ let local_n2 = m21.rotation * -local_n1;+ let support_face2 = p2.support_face(&local_n2);+ let len1 = p1.vertices.len();+ let len2 = p2.vertices.len();++ let seg1 = (+ p1.vertices[support_face1],+ p1.vertices[(support_face1 + 1) % len1],+ );+ let seg2 = (+ m12 * p2.vertices[support_face2],+ m12 * p2.vertices[(support_face2 + 1) % len2],+ );+ if let Some((clip_a, clip_b)) = query::details::clip_segment_segment(seg1, seg2) {+ let dist_a = (clip_a.1 - clip_a.0).dot(local_n1);+ let dist_b = (clip_b.1 - clip_b.0).dot(local_n1);++ let mut data_a = ContactData::default();+ let mut data_b = ContactData::default();++ let fids_a = (+ ((support_face1 * 2 + clip_a.2) % (len1 * 2)) as u8,+ ((support_face2 * 2 + clip_a.3) % (len2 * 2)) as u8,+ );++ let fids_b = (+ ((support_face1 * 2 + clip_b.2) % (len1 * 2)) as u8,+ ((support_face2 * 2 + clip_b.3) % (len2 * 2)) as u8,+ );++ if !manifold.points.is_empty() {+ assert_eq!(manifold.points.len(), 2);++ // We already had 2 points in the previous iteration.+ // Match the features to see if we keep the cached impulse.+ let original_fids_a;+ let original_fids_b;++ // NOTE: the previous manifold may have its bodies swapped wrt. our new manifold.+ // So we have to adjust accordingly the features we will be comparing.+ if swapped {+ original_fids_a = (manifold.points[0].fid1, manifold.points[0].fid2);+ original_fids_b = (manifold.points[1].fid1, manifold.points[1].fid2);+ } else {+ original_fids_a = (manifold.points[0].fid2, manifold.points[0].fid1);+ original_fids_b = (manifold.points[1].fid2, manifold.points[1].fid1);+ }++ if fids_a == original_fids_a {+ data_a = manifold.points[0].data;+ } else if fids_a == original_fids_b {+ data_a = manifold.points[1].data;+ }++ if fids_b == original_fids_a {+ data_b = manifold.points[0].data;+ } else if fids_b == original_fids_b {+ data_b = manifold.points[1].data;+ }+ }++ manifold.points.clear();+ manifold.points.push(Contact {+ local_p1: clip_a.0,+ local_p2: m21 * clip_a.1,+ fid1: fids_a.0,+ fid2: fids_a.1,+ dist: dist_a,+ data: data_a,+ });++ manifold.points.push(Contact {+ local_p1: clip_b.0,+ local_p2: m21 * clip_b.1,+ fid1: fids_b.0,+ fid2: fids_b.1,+ dist: dist_b,+ data: data_b,+ });++ manifold.local_n1 = local_n1;+ manifold.local_n2 = local_n2;+ } else {+ manifold.points.clear();+ }+}diff --git a/renderer/third_party/parry3d/src/query/default_query_dispatcher.rs b/renderer/third_party/parry3d/src/query/default_query_dispatcher.rsnew file mode 100644index 0000000..2984bc7--- /dev/null+++ b/renderer/third_party/parry3d/src/query/default_query_dispatcher.rs@@ -0,0 +1,823 @@+use crate::math::{Pose, Real, Vector};+use crate::query::details::ShapeCastOptions;+use crate::query::{+ self, details::NonlinearShapeCastMode, ClosestPoints, Contact, NonlinearRigidMotion,+ QueryDispatcher, ShapeCastHit, ShapeDistance, ShapeIntersection, Unsupported,+};+#[cfg(feature = "alloc")]+use crate::query::{+ contact_manifolds::{ContactManifoldsWorkspace, NormalConstraints},+ query_dispatcher::PersistentQueryDispatcher,+ ContactManifold,+};+use crate::shape::{HalfSpace, Segment, Shape};+#[cfg(feature = "alloc")]+use alloc::vec::Vec;++#[cfg(any(feature = "std", feature = "alloc"))]+use crate::shape::ShapeType;++/// The default query dispatcher implementation provided by Parry.+///+/// This dispatcher handles all the built-in shape types and automatically selects the most+/// appropriate algorithm for each shape pair combination. It is used internally by all the+/// free functions in the [`crate::query`] module.+///+/// # What It Does+///+/// `DefaultQueryDispatcher` implements efficient query dispatch logic that:+///+/// 1. **Examines shape types** using runtime type checking (`as_ball()`, `as_cuboid()`, etc.)+/// 2. **Selects specialized algorithms** for specific shape pairs (e.g., ball-ball, cuboid-cuboid)+/// 3. **Falls back to general algorithms** when specialized versions aren't available (e.g., GJK/EPA for support map shapes)+/// 4. **Handles composite shapes** by decomposing them and performing multiple sub-queries+///+/// # Supported Shape Combinations+///+/// The dispatcher provides optimized implementations for many shape pairs, including:+///+/// ## Basic Shapes+/// - **Ball-Ball**: Analytical formulas (fastest)+/// - **Ball-Convex**: Specialized algorithms+/// - **Cuboid-Cuboid**: SAT-based algorithms+/// - **Segment-Segment**: Direct geometric calculations+///+/// ## Support Map Shapes+/// For shapes implementing the `SupportMap` trait (most convex shapes):+/// - Uses **GJK algorithm** for distance and intersection queries+/// - Uses **EPA algorithm** for penetration depth when shapes overlap+///+/// ## Composite Shapes+/// Handles complex shapes by decomposing them:+/// - **TriMesh**: Queries individual triangles using BVH acceleration+/// - **Compound**: Queries component shapes+/// - **HeightField**: Efficiently queries relevant cells+/// - **Voxels**: Queries occupied voxels+///+/// ## Special Cases+/// - **HalfSpace**: Infinite planes with specialized handling+/// - **Rounded shapes**: Automatically accounts for border radius+///+/// # When to Use+///+/// You typically don't need to create `DefaultQueryDispatcher` explicitly. The free functions+/// in [`crate::query`] use it automatically:+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query;+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+/// let pos1 = Pose::identity();+/// let pos2 = Pose::translation(5.0, 0.0, 0.0);+///+/// // This uses DefaultQueryDispatcher internally+/// let distance = query::distance(&pos1, &ball1, &pos2, &ball2);+/// # }+/// ```+///+/// However, you might use it explicitly when:+///+/// - Creating a dispatcher chain with custom dispatchers+/// - Implementing custom query logic that needs to delegate to default behavior+/// - Building a custom collision detection pipeline+///+/// # Example: Direct Usage+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{QueryDispatcher, DefaultQueryDispatcher};+/// use parry3d::shape::{Ball, Cuboid};+/// use parry3d::math::{Pose, Vector};+///+/// let dispatcher = DefaultQueryDispatcher;+///+/// let ball = Ball::new(1.0);+/// let cuboid = Cuboid::new(Vector::splat(1.0));+///+/// let pos1 = Pose::identity();+/// let pos2 = Pose::translation(3.0, 0.0, 0.0);+/// let pos12 = pos1.inv_mul(&pos2);+///+/// // Query intersection+/// let intersects = dispatcher.intersection_test(&pos12, &ball, &cuboid)+/// .expect("This shape pair is supported")+/// .intersecting;+///+/// // Query distance+/// let dist = dispatcher.distance(&pos12, &ball, &cuboid)+/// .expect("This shape pair is supported")+/// .distance;+///+/// println!("Distance: {}, Intersecting: {}", dist, intersects);+/// # }+/// ```+///+/// # Example: Chaining with Custom Dispatcher+///+/// ```ignore+/// # {+/// use parry3d::query::{QueryDispatcher, DefaultQueryDispatcher};+///+/// struct MyCustomDispatcher;+/// // ... implement QueryDispatcher for MyCustomDispatcher ...+///+/// // Try custom dispatcher first, fall back to default+/// let dispatcher = MyCustomDispatcher.chain(DefaultQueryDispatcher);+///+/// // Now queries will use your custom logic when applicable,+/// // and Parry's default logic otherwise+/// let dist = dispatcher.distance(pos12, shape1, shape2)?;+/// # }+/// ```+///+/// # Algorithm Selection Strategy+///+/// The dispatcher follows this priority order when selecting algorithms:+///+/// 1. **Exact shape type matching**: Ball-Ball, Cuboid-Cuboid, etc.+/// 2. **Specialized asymmetric pairs**: Ball-ConvexShape, HalfSpace-SupportMap, etc.+/// 3. **Support map fallback**: Any SupportMap-SupportMap pair uses GJK/EPA+/// 4. **Composite shape decomposition**: TriMesh, Compound, HeightField, Voxels+/// 5. **Unsupported**: Returns `Err(Unsupported)` if no algorithm exists+///+/// # Performance Characteristics+///+/// - **Type checking overhead**: Minimal - uses efficient trait object downcasting+/// - **Specialized algorithms**: O(1) for ball-ball, O(log n) to O(n) for composite shapes+/// - **GJK/EPA**: Iterative algorithms that typically converge in 5-20 iterations+/// - **Composite shapes**: Use BVH for O(log n) acceleration of sub-queries+///+/// # Thread Safety+///+/// `DefaultQueryDispatcher` is `Send + Sync` and has no internal state, making it safe to+/// share across threads. You can use a single instance for all queries in a parallel+/// collision detection system.+///+/// # Limitations+///+/// Some shape pairs are not supported and will return `Err(Unsupported)`:+///+/// - Custom shapes not implementing required traits (e.g., not convex, no support map)+/// - Some asymmetric pairs that lack specialized implementations+/// - Certain combinations involving custom user shapes+///+/// When encountering `Unsupported`, you can implement a custom dispatcher to handle these cases.+///+/// # See Also+///+/// - [`QueryDispatcher`]: The trait this struct implements+/// - [`crate::query`]: High-level query functions that use this dispatcher+/// - [`PersistentQueryDispatcher`]: Extended trait for contact manifold queries+#[derive(Debug, Clone)]+pub struct DefaultQueryDispatcher;++impl QueryDispatcher for DefaultQueryDispatcher {+ fn intersection_test(+ &self,+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ ) -> Result<ShapeIntersection, Unsupported> {+ if let (Some(b1), Some(b2)) = (shape1.as_ball(), shape2.as_ball()) {+ let p12 = pos12.translation;+ Ok(query::details::intersection_test_ball_ball(p12, b1, b2).into())+ } else if let (Some(c1), Some(c2)) = (shape1.as_cuboid(), shape2.as_cuboid()) {+ Ok(query::details::intersection_test_cuboid_cuboid(pos12, c1, c2).into())+ } else if let (Some(t1), Some(c2)) = (shape1.as_triangle(), shape2.as_cuboid()) {+ Ok(query::details::intersection_test_triangle_cuboid(pos12, t1, c2).into())+ } else if let (Some(c1), Some(t2)) = (shape1.as_cuboid(), shape2.as_triangle()) {+ Ok(query::details::intersection_test_cuboid_triangle(pos12, c1, t2).into())+ } else if let Some(b1) = shape1.as_ball() {+ Ok(query::details::intersection_test_ball_point_query(+ pos12, b1, shape2,+ ))+ } else if let Some(b2) = shape2.as_ball() {+ Ok(query::details::intersection_test_point_query_ball(+ pos12, shape1, b2,+ ))+ } else if let (Some(p1), Some(s2)) =+ (shape1.as_shape::<HalfSpace>(), shape2.as_support_map())+ {+ Ok(query::details::intersection_test_halfspace_support_map(pos12, p1, s2).into())+ } else if let (Some(s1), Some(p2)) =+ (shape1.as_support_map(), shape2.as_shape::<HalfSpace>())+ {+ Ok(query::details::intersection_test_support_map_halfspace(pos12, s1, p2).into())+ } else if let (Some(s1), Some(s2)) = (shape1.as_support_map(), shape2.as_support_map()) {+ Ok(query::details::intersection_test_support_map_support_map(pos12, s1, s2).into())+ } else {+ #[cfg(feature = "alloc")]+ if let Some(c1) = shape1.as_composite_shape() {+ return Ok(query::details::intersection_test_composite_shape_shape(+ self, pos12, c1, shape2,+ ));+ } else if let Some(c2) = shape2.as_composite_shape() {+ return Ok(query::details::intersection_test_shape_composite_shape(+ self, pos12, shape1, c2,+ ));+ } else if let Some(v1) = shape1.as_voxels() {+ return Ok(query::details::intersection_test_voxels_shape(+ self, pos12, v1, shape2,+ ));+ } else if let Some(v2) = shape2.as_voxels() {+ return Ok(query::details::intersection_test_shape_voxels(+ self, pos12, shape1, v2,+ ));+ }++ Err(Unsupported)+ }+ }++ /// Computes the minimum distance separating two shapes.+ ///+ /// Returns `0.0` if the objects are touching or penetrating.+ fn distance(+ &self,+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ ) -> Result<ShapeDistance, Unsupported> {+ let ball1 = shape1.as_ball();+ let ball2 = shape2.as_ball();++ if let (Some(b1), Some(b2)) = (ball1, ball2) {+ let p2 = pos12.translation;+ Ok(query::details::distance_ball_ball(b1, p2, b2).into())+ } else if let (Some(b1), true) = (ball1, shape2.is_convex()) {+ Ok(query::details::distance_ball_convex_polyhedron(pos12, b1, shape2).into())+ } else if let (true, Some(b2)) = (shape1.is_convex(), ball2) {+ Ok(query::details::distance_convex_polyhedron_ball(pos12, shape1, b2).into())+ } else if let (Some(c1), Some(c2)) = (shape1.as_cuboid(), shape2.as_cuboid()) {+ Ok(query::details::distance_cuboid_cuboid(pos12, c1, c2).into())+ } else if let (Some(s1), Some(s2)) = (shape1.as_segment(), shape2.as_segment()) {+ Ok(query::details::distance_segment_segment(pos12, s1, s2).into())+ } else if let (Some(p1), Some(s2)) =+ (shape1.as_shape::<HalfSpace>(), shape2.as_support_map())+ {+ Ok(query::details::distance_halfspace_support_map(pos12, p1, s2).into())+ } else if let (Some(s1), Some(p2)) =+ (shape1.as_support_map(), shape2.as_shape::<HalfSpace>())+ {+ Ok(query::details::distance_support_map_halfspace(pos12, s1, p2).into())+ } else if let (Some(s1), Some(s2)) = (shape1.as_support_map(), shape2.as_support_map()) {+ Ok(query::details::distance_support_map_support_map(pos12, s1, s2).into())+ } else {+ #[cfg(feature = "alloc")]+ if let Some(c1) = shape1.as_composite_shape() {+ return Ok(query::details::distance_composite_shape_shape(+ self, pos12, c1, shape2,+ ));+ } else if let Some(c2) = shape2.as_composite_shape() {+ return Ok(query::details::distance_shape_composite_shape(+ self, pos12, shape1, c2,+ ));+ }++ Err(Unsupported)+ }+ }++ fn contact(+ &self,+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ prediction: Real,+ ) -> Result<Option<Contact>, Unsupported> {+ let ball1 = shape1.as_ball();+ let ball2 = shape2.as_ball();++ if let (Some(b1), Some(b2)) = (ball1, ball2) {+ Ok(query::details::contact_ball_ball(pos12, b1, b2, prediction))+ // } else if let (Some(c1), Some(c2)) = (shape1.as_cuboid(), shape2.as_cuboid()) {+ // Ok(query::details::contact_cuboid_cuboid(+ // pos12, c1, c2, prediction,+ // ))+ } else if let (Some(p1), Some(s2)) =+ (shape1.as_shape::<HalfSpace>(), shape2.as_support_map())+ {+ Ok(query::details::contact_halfspace_support_map(+ pos12, p1, s2, prediction,+ ))+ } else if let (Some(s1), Some(p2)) =+ (shape1.as_support_map(), shape2.as_shape::<HalfSpace>())+ {+ Ok(query::details::contact_support_map_halfspace(+ pos12, s1, p2, prediction,+ ))+ } else if let (Some(b1), true) = (ball1, shape2.is_convex()) {+ Ok(query::details::contact_ball_convex_polyhedron(+ pos12, b1, shape2, prediction,+ ))+ } else if let (true, Some(b2)) = (shape1.is_convex(), ball2) {+ Ok(query::details::contact_convex_polyhedron_ball(+ pos12, shape1, b2, prediction,+ ))+ } else {+ #[cfg(feature = "alloc")]+ if let (Some(s1), Some(s2)) = (shape1.as_support_map(), shape2.as_support_map()) {+ return Ok(query::details::contact_support_map_support_map(+ pos12, s1, s2, prediction,+ ));+ } else if let Some(hf1) = shape1.as_heightfield() {+ return Ok(query::details::contact_heightfield_shape(+ self, pos12, hf1, shape2, prediction,+ ));+ } else if let Some(hf2) = shape2.as_heightfield() {+ return Ok(query::details::contact_shape_heightfield(+ self, pos12, shape1, hf2, prediction,+ ));+ } else if let Some(c1) = shape1.as_composite_shape() {+ return Ok(query::details::contact_composite_shape_shape(+ self, pos12, c1, shape2, prediction,+ ));+ } else if let Some(c2) = shape2.as_composite_shape() {+ return Ok(query::details::contact_shape_composite_shape(+ self, pos12, shape1, c2, prediction,+ ));+ }++ Err(Unsupported)+ }+ }++ fn closest_points(+ &self,+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ max_dist: Real,+ ) -> Result<ClosestPoints, Unsupported> {+ let ball1 = shape1.as_ball();+ let ball2 = shape2.as_ball();++ if let (Some(b1), Some(b2)) = (ball1, ball2) {+ Ok(query::details::closest_points_ball_ball(+ pos12, b1, b2, max_dist,+ ))+ } else if let (Some(b1), true) = (ball1, shape2.is_convex()) {+ Ok(query::details::closest_points_ball_convex_polyhedron(+ pos12, b1, shape2, max_dist,+ ))+ } else if let (true, Some(b2)) = (shape1.is_convex(), ball2) {+ Ok(query::details::closest_points_convex_polyhedron_ball(+ pos12, shape1, b2, max_dist,+ ))+ } else if let (Some(s1), Some(s2)) =+ (shape1.as_shape::<Segment>(), shape2.as_shape::<Segment>())+ {+ Ok(query::details::closest_points_segment_segment(+ pos12, s1, s2, max_dist,+ ))+ // } else if let (Some(c1), Some(c2)) = (shape1.as_cuboid(), shape2.as_cuboid()) {+ // Ok(query::details::closest_points_cuboid_cuboid(+ // pos12, c1, c2, max_dist,+ // ))+ } else if let (Some(s1), Some(s2)) = (shape1.as_segment(), shape2.as_segment()) {+ Ok(query::details::closest_points_segment_segment(+ pos12, s1, s2, max_dist,+ ))+ // } else if let (Some(c1), Some(t2)) = (shape1.as_cuboid(), shape2.as_triangle()) {+ // Ok(query::details::closest_points_cuboid_triangle(+ // pos12, c1, t2, max_dist,+ // ))+ } else if let (Some(t1), Some(c2)) = (shape1.as_triangle(), shape2.as_cuboid()) {+ Ok(query::details::closest_points_triangle_cuboid(+ pos12, t1, c2, max_dist,+ ))+ } else if let (Some(p1), Some(s2)) =+ (shape1.as_shape::<HalfSpace>(), shape2.as_support_map())+ {+ Ok(query::details::closest_points_halfspace_support_map(+ pos12, p1, s2, max_dist,+ ))+ } else if let (Some(s1), Some(p2)) =+ (shape1.as_support_map(), shape2.as_shape::<HalfSpace>())+ {+ Ok(query::details::closest_points_support_map_halfspace(+ pos12, s1, p2, max_dist,+ ))+ } else if let (Some(s1), Some(s2)) = (shape1.as_support_map(), shape2.as_support_map()) {+ Ok(query::details::closest_points_support_map_support_map(+ pos12, s1, s2, max_dist,+ ))+ } else {+ #[cfg(feature = "alloc")]+ if let Some(c1) = shape1.as_composite_shape() {+ return Ok(query::details::closest_points_composite_shape_shape(+ self, pos12, c1, shape2, max_dist,+ ));+ } else if let Some(c2) = shape2.as_composite_shape() {+ return Ok(query::details::closest_points_shape_composite_shape(+ self, pos12, shape1, c2, max_dist,+ ));+ }++ Err(Unsupported)+ }+ }++ fn cast_shapes(+ &self,+ pos12: &Pose,+ local_vel12: Vector,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ options: ShapeCastOptions,+ ) -> Result<Option<ShapeCastHit>, Unsupported> {+ if let (Some(b1), Some(b2)) = (shape1.as_ball(), shape2.as_ball()) {+ Ok(query::details::cast_shapes_ball_ball(+ pos12,+ local_vel12,+ b1,+ b2,+ options,+ ))+ } else if let (Some(p1), Some(s2)) =+ (shape1.as_shape::<HalfSpace>(), shape2.as_support_map())+ {+ Ok(query::details::cast_shapes_halfspace_support_map(+ pos12,+ local_vel12,+ p1,+ s2,+ options,+ ))+ } else if let (Some(s1), Some(p2)) =+ (shape1.as_support_map(), shape2.as_shape::<HalfSpace>())+ {+ Ok(query::details::cast_shapes_support_map_halfspace(+ pos12,+ local_vel12,+ s1,+ p2,+ options,+ ))+ } else {+ #[cfg(feature = "alloc")]+ if let Some(heightfield1) = shape1.as_heightfield() {+ return query::details::cast_shapes_heightfield_shape(+ self,+ pos12,+ local_vel12,+ heightfield1,+ shape2,+ options,+ );+ } else if let Some(heightfield2) = shape2.as_heightfield() {+ return query::details::cast_shapes_shape_heightfield(+ self,+ pos12,+ local_vel12,+ shape1,+ heightfield2,+ options,+ );+ } else if let (Some(s1), Some(s2)) = (shape1.as_support_map(), shape2.as_support_map())+ {+ return Ok(query::details::cast_shapes_support_map_support_map(+ pos12,+ local_vel12,+ s1,+ s2,+ options,+ ));+ } else if let Some(c1) = shape1.as_composite_shape() {+ return Ok(query::details::cast_shapes_composite_shape_shape(+ self,+ pos12,+ local_vel12,+ c1,+ shape2,+ options,+ ));+ } else if let Some(c2) = shape2.as_composite_shape() {+ return Ok(query::details::cast_shapes_shape_composite_shape(+ self,+ pos12,+ local_vel12,+ shape1,+ c2,+ options,+ ));+ } else if let Some(v1) = shape1.as_voxels() {+ return Ok(query::details::cast_shapes_voxels_shape(+ self,+ pos12,+ local_vel12,+ v1,+ shape2,+ options,+ ));+ } else if let Some(v2) = shape2.as_voxels() {+ return Ok(query::details::cast_shapes_shape_voxels(+ self,+ pos12,+ local_vel12,+ shape1,+ v2,+ options,+ ));+ }++ Err(Unsupported)+ }+ }++ fn cast_shapes_nonlinear(+ &self,+ motion1: &NonlinearRigidMotion,+ shape1: &dyn Shape,+ motion2: &NonlinearRigidMotion,+ shape2: &dyn Shape,+ start_time: Real,+ end_time: Real,+ stop_at_penetration: bool,+ ) -> Result<Option<ShapeCastHit>, Unsupported> {+ if let (Some(sm1), Some(sm2)) = (shape1.as_support_map(), shape2.as_support_map()) {+ let mode = if stop_at_penetration {+ NonlinearShapeCastMode::StopAtPenetration+ } else {+ NonlinearShapeCastMode::directional_toi(shape1, shape2)+ };++ Ok(+ query::details::cast_shapes_nonlinear_support_map_support_map(+ self, motion1, sm1, shape1, motion2, sm2, shape2, start_time, end_time, mode,+ ),+ )+ } else {+ #[cfg(feature = "alloc")]+ if let Some(c1) = shape1.as_composite_shape() {+ return Ok(query::details::cast_shapes_nonlinear_composite_shape_shape(+ self,+ motion1,+ c1,+ motion2,+ shape2,+ start_time,+ end_time,+ stop_at_penetration,+ ));+ } else if let Some(c2) = shape2.as_composite_shape() {+ return Ok(query::details::cast_shapes_nonlinear_shape_composite_shape(+ self,+ motion1,+ shape1,+ motion2,+ c2,+ start_time,+ end_time,+ stop_at_penetration,+ ));+ } else if let Some(c1) = shape1.as_voxels() {+ return Ok(query::details::cast_shapes_nonlinear_voxels_shape(+ self,+ motion1,+ c1,+ motion2,+ shape2,+ start_time,+ end_time,+ stop_at_penetration,+ ));+ } else if let Some(c2) = shape2.as_voxels() {+ return Ok(query::details::cast_shapes_nonlinear_shape_voxels(+ self,+ motion1,+ shape1,+ motion2,+ c2,+ start_time,+ end_time,+ stop_at_penetration,+ ));+ }+ /* } else if let (Some(p1), Some(s2)) = (shape1.as_shape::<HalfSpace>(), shape2.as_support_map()) {+ // query::details::cast_shapes_nonlinear_halfspace_support_map(m1, vel1, p1, m2, vel2, s2)+ unimplemented!()+ } else if let (Some(s1), Some(p2)) = (shape1.as_support_map(), shape2.as_shape::<HalfSpace>()) {+ // query::details::cast_shapes_nonlinear_support_map_halfspace(m1, vel1, s1, m2, vel2, p2)+ unimplemented!() */++ Err(Unsupported)+ }+ }+}++#[cfg(feature = "alloc")]+impl<ManifoldData, ContactData> PersistentQueryDispatcher<ManifoldData, ContactData>+ for DefaultQueryDispatcher+where+ ManifoldData: Default + Clone + Send + Sync,+ ContactData: Default + Copy + Send + Sync,+{+ fn contact_manifolds(+ &self,+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+ ) -> Result<(), Unsupported> {+ use crate::query::contact_manifolds::*;++ let composite1 = shape1.as_composite_shape();+ let composite2 = shape2.as_composite_shape();++ if let (Some(composite1), Some(composite2)) = (composite1, composite2) {+ contact_manifolds_composite_shape_composite_shape(+ self, pos12, composite1, composite2, prediction, manifolds, workspace,+ );++ return Ok(());+ }++ match (shape1.shape_type(), shape2.shape_type()) {+ (ShapeType::TriMesh, _) | (_, ShapeType::TriMesh) => {+ contact_manifolds_trimesh_shape_shapes(+ self, pos12, shape1, shape2, prediction, manifolds, workspace,+ );+ }+ (ShapeType::HeightField, _) => {+ if let Some(composite2) = composite2 {+ contact_manifolds_heightfield_composite_shape(+ self,+ pos12,+ &pos12.inverse(),+ shape1.as_heightfield().unwrap(),+ composite2,+ prediction,+ manifolds,+ workspace,+ false,+ )+ } else {+ contact_manifolds_heightfield_shape_shapes(+ self, pos12, shape1, shape2, prediction, manifolds, workspace,+ );+ }+ }+ (_, ShapeType::HeightField) => {+ if let Some(composite1) = composite1 {+ contact_manifolds_heightfield_composite_shape(+ self,+ &pos12.inverse(),+ pos12,+ shape2.as_heightfield().unwrap(),+ composite1,+ prediction,+ manifolds,+ workspace,+ true,+ )+ } else {+ contact_manifolds_heightfield_shape_shapes(+ self, pos12, shape1, shape2, prediction, manifolds, workspace,+ );+ }+ }+ (ShapeType::Voxels, ShapeType::Voxels) => contact_manifolds_voxels_voxels_shapes(+ self, pos12, shape1, shape2, prediction, manifolds, workspace,+ ),+ (ShapeType::Voxels, ShapeType::Ball) | (ShapeType::Ball, ShapeType::Voxels) => {+ contact_manifolds_voxels_ball_shapes(pos12, shape1, shape2, prediction, manifolds)+ }+ (ShapeType::Voxels, _) | (_, ShapeType::Voxels) => {+ if composite1.is_some() || composite2.is_some() {+ contact_manifolds_voxels_composite_shape_shapes(+ self, pos12, shape1, shape2, prediction, manifolds, workspace,+ )+ } else {+ contact_manifolds_voxels_shape_shapes(+ self, pos12, shape1, shape2, prediction, manifolds, workspace,+ )+ }+ }+ _ => {+ if let Some(composite1) = composite1 {+ contact_manifolds_composite_shape_shape(+ self, pos12, composite1, shape2, prediction, manifolds, workspace, false,+ );+ } else if let Some(composite2) = composite2 {+ contact_manifolds_composite_shape_shape(+ self,+ &pos12.inverse(),+ composite2,+ shape1,+ prediction,+ manifolds,+ workspace,+ true,+ );+ } else {+ if manifolds.is_empty() {+ manifolds.push(ContactManifold::new());+ }++ return self.contact_manifold_convex_convex(+ pos12,+ shape1,+ shape2,+ None,+ None,+ prediction,+ &mut manifolds[0],+ );+ }+ }+ }++ Ok(())+ }++ fn contact_manifold_convex_convex(+ &self,+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+ normal_constraints1: Option<&dyn NormalConstraints>,+ normal_constraints2: Option<&dyn NormalConstraints>,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+ ) -> Result<(), Unsupported> {+ use crate::query::contact_manifolds::*;++ match (shape1.shape_type(), shape2.shape_type()) {+ (ShapeType::Ball, ShapeType::Ball) => {+ contact_manifold_ball_ball_shapes(pos12, shape1, shape2, prediction, manifold)+ }+ (ShapeType::Cuboid, ShapeType::Cuboid) =>+ contact_manifold_cuboid_cuboid_shapes(pos12, shape1, shape2, prediction, manifold)+ ,+ // (ShapeType::Polygon, ShapeType::Polygon) => (+ // PrimitiveContactGenerator {+ // generate_contacts: super::generate_contacts_polygon_polygon,+ // ..PrimitiveContactGenerator::default()+ // },+ // None,+ // ),+ (ShapeType::Capsule, ShapeType::Capsule) => {+ contact_manifold_capsule_capsule_shapes(pos12, shape1, shape2, prediction, manifold)+ }+ (_, ShapeType::Ball) | (ShapeType::Ball, _) => {+ contact_manifold_convex_ball_shapes(pos12, shape1, shape2, normal_constraints1, normal_constraints2, prediction, manifold)+ }+ // (ShapeType::Capsule, ShapeType::Cuboid) | (ShapeType::Cuboid, ShapeType::Capsule) =>+ // contact_manifold_cuboid_capsule_shapes(pos12, shape1, shape2, prediction, manifold),+ (ShapeType::Triangle, ShapeType::Cuboid) | (ShapeType::Cuboid, ShapeType::Triangle) => {+ contact_manifold_cuboid_triangle_shapes(pos12, shape1, shape2, normal_constraints1, normal_constraints2, prediction, manifold)+ }+ (ShapeType::HalfSpace, _) => {+ if let Some((pfm2, border_radius2)) = shape2.as_polygonal_feature_map() {+ contact_manifold_halfspace_pfm(+ pos12,+ shape1.as_halfspace().unwrap(),+ pfm2,+ border_radius2,+ prediction,+ manifold,+ false+ )+ } else {+ return Err(Unsupported)+ }+ }+ (_, ShapeType::HalfSpace) => {+ if let Some((pfm1, border_radius1)) = shape1.as_polygonal_feature_map() {+ contact_manifold_halfspace_pfm(+ &pos12.inverse(),+ shape2.as_halfspace().unwrap(),+ pfm1,+ border_radius1,+ prediction,+ manifold,+ true+ )+ } else {+ return Err(Unsupported)+ }+ }+ _ => {+ if let (Some(pfm1), Some(pfm2)) = (+ shape1.as_polygonal_feature_map(),+ shape2.as_polygonal_feature_map(),+ ) {+ contact_manifold_pfm_pfm(+ pos12, pfm1.0, pfm1.1, normal_constraints1, pfm2.0, pfm2.1, normal_constraints2, prediction, manifold,+ )+ } else {+ return Err(Unsupported);+ }+ }+ }++ Ok(())+ }+}diff --git a/renderer/third_party/parry3d/src/query/distance/distance.rs b/renderer/third_party/parry3d/src/query/distance/distance.rsnew file mode 100644index 0000000..ecf4d15--- /dev/null+++ b/renderer/third_party/parry3d/src/query/distance/distance.rs@@ -0,0 +1,152 @@+use crate::shape::SubShapeId;++/// The distance between two shapes, and the sub-shapes it was measured between.+#[derive(Copy, Clone, Debug, PartialEq)]+pub struct ShapeDistance {+ /// The separation between the two shapes; `0.0` when they touch or overlap.+ pub distance: Real,+ /// The sub-shape of the first shape the distance was measured to.+ ///+ /// Always `0` for a shape with no sub-shapes.+ pub subshape1: SubShapeId,+ /// The sub-shape of the second shape the distance was measured to.+ ///+ /// Always `0` for a shape with no sub-shapes.+ pub subshape2: SubShapeId,+}++impl ShapeDistance {+ /// A distance measured between shapes with no sub-shapes to distinguish.+ pub fn new(distance: Real) -> Self {+ Self {+ distance,+ subshape1: 0,+ subshape2: 0,+ }+ }++ /// Sets the sub-shapes this distance was measured between.+ pub fn with_subshapes(mut self, subshape1: SubShapeId, subshape2: SubShapeId) -> Self {+ self.subshape1 = subshape1;+ self.subshape2 = subshape2;+ self+ }++ /// Swaps the roles of the two shapes.+ pub fn swapped(mut self) -> Self {+ core::mem::swap(&mut self.subshape1, &mut self.subshape2);+ self+ }+}++#[cfg(feature = "alloc")]+impl crate::partitioning::BvhLeafCost for ShapeDistance {+ #[inline]+ fn cost(&self) -> Real {+ self.distance+ }+}++impl From<Real> for ShapeDistance {+ fn from(distance: Real) -> Self {+ Self::new(distance)+ }+}++use crate::math::{Pose, Real};++use crate::query::{DefaultQueryDispatcher, QueryDispatcher, Unsupported};+use crate::shape::Shape;++/// Computes the minimum distance separating two shapes.+///+/// This is one of the most fundamental geometric queries in collision detection.+/// It calculates the shortest distance between any two points on the surfaces of+/// the two shapes.+///+/// # Behavior+///+/// - Returns the **shortest distance** between the two shape surfaces+/// - Returns `0.0` if the shapes are **touching** (surfaces just make contact)+/// - Returns `0.0` if the shapes are **penetrating** (overlapping)+/// - Always returns a **non-negative** value+///+/// # Arguments+///+/// * `pos1` - Position and orientation of the first shape in world space+/// * `g1` - The first shape (can be any shape implementing the `Shape` trait)+/// * `pos2` - Position and orientation of the second shape in world space+/// * `g2` - The second shape (can be any shape implementing the `Shape` trait)+///+/// # Returns+///+/// * `Ok(distance)` - The minimum distance between the shapes+/// * `Err(Unsupported)` - If this shape pair combination is not supported+///+/// # Performance+///+/// Performance varies by shape type:+/// - **Ball-Ball**: Very fast (analytical solution)+/// - **Cuboid-Cuboid**: Fast (SAT-based)+/// - **Convex-Convex**: Moderate (GJK algorithm)+/// - **Concave shapes**: Slower (requires BVH traversal)+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::distance;+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// // Create two balls+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(2.0);+///+/// // Position them 10 units apart along the x-axis+/// let pos1 = Pose::translation(0.0, 0.0, 0.0);+/// let pos2 = Pose::translation(10.0, 0.0, 0.0);+///+/// // Compute distance+/// let dist = distance(&pos1, &ball1, &pos2, &ball2).unwrap().distance;+///+/// // Distance = 10.0 (separation) - 1.0 (radius1) - 2.0 (radius2) = 7.0+/// assert_eq!(dist, 7.0);+/// # }+/// ```+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::distance;+/// use parry3d::shape::Cuboid;+/// use parry3d::math::{Pose, Vector};+///+/// // Create two boxes+/// let box1 = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+/// let box2 = Cuboid::new(Vector::new(0.5, 0.5, 0.5));+///+/// // Position them so they're touching+/// let pos1 = Pose::translation(0.0, 0.0, 0.0);+/// let pos2 = Pose::translation(1.5, 0.0, 0.0); // Edge to edge+///+/// let dist = distance(&pos1, &box1, &pos2, &box2).unwrap().distance;+///+/// // They're touching, so distance is 0.0+/// assert_eq!(dist, 0.0);+/// # }+/// ```+///+/// # See Also+///+/// - [`closest_points`](crate::query::closest_points()) - For finding the actual closest points+/// - [`contact`](crate::query::contact()) - For penetration depth when overlapping+/// - [`intersection_test`](crate::query::intersection_test()) - For boolean overlap test+pub fn distance(+ pos1: &Pose,+ g1: &dyn Shape,+ pos2: &Pose,+ g2: &dyn Shape,+) -> Result<ShapeDistance, Unsupported> {+ let pos12 = pos1.inv_mul(pos2);+ DefaultQueryDispatcher.distance(&pos12, g1, g2)+}diff --git a/renderer/third_party/parry3d/src/query/distance/distance_ball_ball.rs b/renderer/third_party/parry3d/src/query/distance/distance_ball_ball.rsnew file mode 100644index 0000000..0b44f40--- /dev/null+++ b/renderer/third_party/parry3d/src/query/distance/distance_ball_ball.rs@@ -0,0 +1,18 @@+use crate::math::ComplexField;+use crate::math::{Real, Vector};+use crate::shape::Ball;++/// Distance between balls.+#[inline]+pub fn distance_ball_ball(b1: &Ball, center2: Vector, b2: &Ball) -> Real {+ let r1 = b1.radius;+ let r2 = b2.radius;+ let distance_squared = center2.length_squared();+ let sum_radius = r1 + r2;++ if distance_squared <= sum_radius * sum_radius {+ 0.0+ } else {+ <Real as ComplexField>::sqrt(distance_squared) - sum_radius+ }+}diff --git a/renderer/third_party/parry3d/src/query/distance/distance_ball_convex_polyhedron.rs b/renderer/third_party/parry3d/src/query/distance/distance_ball_convex_polyhedron.rsnew file mode 100644index 0000000..f3057c2--- /dev/null+++ b/renderer/third_party/parry3d/src/query/distance/distance_ball_convex_polyhedron.rs@@ -0,0 +1,30 @@+use crate::math::{Pose, Real};+use crate::shape::{Ball, Shape};++/// Distance between a ball and a convex polyhedron.+///+/// This function panics if the input shape does not implement+/// both the ConvexPolyhedron and PointQuery traits.+#[inline]+pub fn distance_ball_convex_polyhedron(+ pos12: &Pose,+ ball1: &Ball,+ shape2: &(impl Shape + ?Sized),+) -> Real {+ distance_convex_polyhedron_ball(&pos12.inverse(), shape2, ball1)+}++/// Distance between a convex polyhedron and a ball.+///+/// This function panics if the input shape does not implement+/// both the ConvexPolyhedron and PointQuery traits.+#[inline]+pub fn distance_convex_polyhedron_ball(+ pos12: &Pose,+ shape1: &(impl Shape + ?Sized),+ ball2: &Ball,+) -> Real {+ let center2_1 = pos12.translation;+ let proj = shape1.project_local_point(center2_1, true);+ ((proj.point - center2_1).length() - ball2.radius).max(0.0)+}diff --git a/renderer/third_party/parry3d/src/query/distance/distance_composite_shape_shape.rs b/renderer/third_party/parry3d/src/query/distance/distance_composite_shape_shape.rsnew file mode 100644index 0000000..ce7118d--- /dev/null+++ b/renderer/third_party/parry3d/src/query/distance/distance_composite_shape_shape.rs@@ -0,0 +1,80 @@+use crate::bounding_volume::Aabb;+use crate::math::{Pose, Real};+use crate::partitioning::BvhNode;+use crate::query::{QueryDispatcher, ShapeDistance};+use crate::shape::{CompositeShapeRef, Shape, SubShapeId, TypedCompositeShape};+use crate::utils::PoseOpt;++impl<S: ?Sized + TypedCompositeShape> CompositeShapeRef<'_, S> {+ /// Calculates the closest distance between `self` and the given `shape2` positioned at+ /// `pose12` relative to `self`.+ ///+ /// Returns the index of the sub-shape of `self` closest to `shape2` alongside the distance,+ /// which is left as that sub-shape reported it (its `subshape1` is the sub-shape's own when+ /// it is a composite too, and `subshape2` is `shape2`'s).+ pub fn distance_to_shape<D: ?Sized + QueryDispatcher>(+ &self,+ dispatcher: &D,+ pose12: &Pose,+ shape2: &dyn Shape,+ ) -> Option<(SubShapeId, ShapeDistance)> {+ let ls_aabb2 = shape2.compute_aabb(pose12);+ let msum_shift = -ls_aabb2.center();+ let msum_margin = ls_aabb2.half_extents();++ self.0.bvh().find_best(+ Real::MAX,+ |node: &BvhNode, _| {+ // Compute the minkowski sum of the two Aabbs.+ let msum = Aabb {+ mins: node.mins() + msum_shift - msum_margin,+ maxs: node.maxs() + msum_shift + msum_margin,+ };+ msum.distance_to_origin()+ },+ |part_id, _| {+ self.0+ .map_untyped_part_at(part_id, |part_pos1, part_g1, _| {+ dispatcher.distance(&part_pos1.inv_mul(pose12), part_g1, shape2)+ })?+ .ok()+ },+ )+ }+}++/// Smallest distance between a composite shape and any other shape.+pub fn distance_composite_shape_shape<D, G1>(+ dispatcher: &D,+ pos12: &Pose,+ g1: &G1,+ g2: &dyn Shape,+) -> ShapeDistance+where+ D: ?Sized + QueryDispatcher,+ G1: ?Sized + TypedCompositeShape,+{+ // `subshape2` is left as the dispatch set it: `g2` may be a composite too, and only it+ // knows which of its parts answered.+ CompositeShapeRef(g1)+ .distance_to_shape(dispatcher, pos12, g2)+ .map(|(part_id, mut result)| {+ result.subshape1 = part_id;+ result+ })+ .unwrap_or(ShapeDistance::new(Real::MAX))+}++/// Smallest distance between a shape and a composite shape.+pub fn distance_shape_composite_shape<D, G2>(+ dispatcher: &D,+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &G2,+) -> ShapeDistance+where+ D: ?Sized + QueryDispatcher,+ G2: ?Sized + TypedCompositeShape,+{+ distance_composite_shape_shape(dispatcher, &pos12.inverse(), g2, g1).swapped()+}diff --git a/renderer/third_party/parry3d/src/query/distance/distance_cuboid_cuboid.rs b/renderer/third_party/parry3d/src/query/distance/distance_cuboid_cuboid.rsnew file mode 100644index 0000000..9dcf8f9--- /dev/null+++ b/renderer/third_party/parry3d/src/query/distance/distance_cuboid_cuboid.rs@@ -0,0 +1,12 @@+use crate::math::{Pose, Real};+use crate::query::ClosestPoints;+use crate::shape::Cuboid;++/// Distance between two cuboids.+#[inline]+pub fn distance_cuboid_cuboid(pos12: &Pose, cuboid1: &Cuboid, cuboid2: &Cuboid) -> Real {+ match crate::query::details::closest_points_cuboid_cuboid(pos12, cuboid1, cuboid2, Real::MAX) {+ ClosestPoints::WithinMargin(p1, p2) => (p1 - (pos12 * p2)).length(),+ _ => 0.0,+ }+}diff --git a/renderer/third_party/parry3d/src/query/distance/distance_halfspace_support_map.rs b/renderer/third_party/parry3d/src/query/distance/distance_halfspace_support_map.rsnew file mode 100644index 0000000..5bbd512--- /dev/null+++ b/renderer/third_party/parry3d/src/query/distance/distance_halfspace_support_map.rs@@ -0,0 +1,22 @@+use crate::math::{Pose, Real};+use crate::shape::HalfSpace;+use crate::shape::SupportMap;++/// Distance between a halfspace and a support-mapped shape.+pub fn distance_halfspace_support_map<G: ?Sized + SupportMap>(+ pos12: &Pose,+ halfspace: &HalfSpace,+ other: &G,+) -> Real {+ let deepest = other.support_point_toward(pos12, -halfspace.normal);+ halfspace.normal.dot(deepest).max(0.0)+}++/// Distance between a support-mapped shape and a halfspace.+pub fn distance_support_map_halfspace<G: ?Sized + SupportMap>(+ pos12: &Pose,+ other: &G,+ halfspace: &HalfSpace,+) -> Real {+ distance_halfspace_support_map(&pos12.inverse(), halfspace, other)+}diff --git a/renderer/third_party/parry3d/src/query/distance/distance_segment_segment.rs b/renderer/third_party/parry3d/src/query/distance/distance_segment_segment.rsnew file mode 100644index 0000000..dae3993--- /dev/null+++ b/renderer/third_party/parry3d/src/query/distance/distance_segment_segment.rs@@ -0,0 +1,17 @@+use crate::math::{Pose, Real};+use crate::query::ClosestPoints;+use crate::shape::Segment;++/// Distance between two segments.+#[inline]+pub fn distance_segment_segment(pos12: &Pose, segment1: &Segment, segment2: &Segment) -> Real {+ match crate::query::details::closest_points_segment_segment(+ pos12,+ segment1,+ segment2,+ Real::MAX,+ ) {+ ClosestPoints::WithinMargin(p1, p2) => (p1 - (pos12 * p2)).length(),+ _ => 0.0,+ }+}diff --git a/renderer/third_party/parry3d/src/query/distance/distance_support_map_support_map.rs b/renderer/third_party/parry3d/src/query/distance/distance_support_map_support_map.rsnew file mode 100644index 0000000..0123be3--- /dev/null+++ b/renderer/third_party/parry3d/src/query/distance/distance_support_map_support_map.rs@@ -0,0 +1,47 @@+use crate::math::{Pose, Real, Vector};+use crate::query::gjk::{self, CsoPoint, GJKResult, VoronoiSimplex};+use crate::shape::SupportMap;+use num::Bounded;++/// Distance between support-mapped shapes.+pub fn distance_support_map_support_map<G1, G2>(pos12: &Pose, g1: &G1, g2: &G2) -> Real+where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+{+ distance_support_map_support_map_with_params(pos12, g1, g2, &mut VoronoiSimplex::new(), None)+}++/// Distance between support-mapped shapes.+///+/// This allows a more fine grained control other the underlying GJK algorigtm.+pub fn distance_support_map_support_map_with_params<G1, G2>(+ pos12: &Pose,+ g1: &G1,+ g2: &G2,+ simplex: &mut VoronoiSimplex,+ init_dir: Option<Vector>,+) -> Real+where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+{+ // TODO: or m2.translation - m1.translation ?+ let dir = init_dir.unwrap_or_else(|| -pos12.translation);++ let normalized_dir =+ if dir.length_squared() > crate::math::DEFAULT_EPSILON * crate::math::DEFAULT_EPSILON {+ dir.normalize()+ } else {+ Vector::X+ };++ simplex.reset(CsoPoint::from_shapes(pos12, g1, g2, normalized_dir));++ match gjk::closest_points(pos12, g1, g2, Real::max_value(), true, simplex) {+ GJKResult::Intersection => 0.0,+ GJKResult::ClosestPoints(p1, p2, _) => (p1 - p2).length(),+ GJKResult::Proximity(_) => unreachable!(),+ GJKResult::NoIntersection(_) => 0.0, // TODO: GJK did not converge.+ }+}diff --git a/renderer/third_party/parry3d/src/query/distance/mod.rs b/renderer/third_party/parry3d/src/query/distance/mod.rsnew file mode 100644index 0000000..9424818--- /dev/null+++ b/renderer/third_party/parry3d/src/query/distance/mod.rs@@ -0,0 +1,29 @@+//! Implementation details of the `distance` function.++pub use self::distance::{distance, ShapeDistance};+pub use self::distance_ball_ball::distance_ball_ball;+pub use self::distance_ball_convex_polyhedron::{+ distance_ball_convex_polyhedron, distance_convex_polyhedron_ball,+};+#[cfg(feature = "alloc")]+pub use self::distance_composite_shape_shape::{+ distance_composite_shape_shape, distance_shape_composite_shape,+};+pub use self::distance_cuboid_cuboid::distance_cuboid_cuboid;+pub use self::distance_halfspace_support_map::{+ distance_halfspace_support_map, distance_support_map_halfspace,+};+pub use self::distance_segment_segment::distance_segment_segment;+pub use self::distance_support_map_support_map::{+ distance_support_map_support_map, distance_support_map_support_map_with_params,+};++mod distance;+mod distance_ball_ball;+mod distance_ball_convex_polyhedron;+#[cfg(feature = "alloc")]+mod distance_composite_shape_shape;+mod distance_cuboid_cuboid;+mod distance_halfspace_support_map;+mod distance_segment_segment;+mod distance_support_map_support_map;diff --git a/renderer/third_party/parry3d/src/query/epa/epa2.rs b/renderer/third_party/parry3d/src/query/epa/epa2.rsnew file mode 100644index 0000000..555280d--- /dev/null+++ b/renderer/third_party/parry3d/src/query/epa/epa2.rs@@ -0,0 +1,594 @@+//! Two-dimensional penetration depth queries using the Expanding Polytope Algorithm.+//!+//! This module provides the 2D-specific implementation of EPA, which works with+//! polygons (edges) rather than polyhedra (faces) as in the 3D version.++use alloc::{collections::BinaryHeap, vec::Vec};+use core::cmp::Ordering;+use num::Bounded;++use crate::math::{Pose, Real, Vector};+use crate::query::gjk::{self, ConstantOrigin, CsoPoint, VoronoiSimplex};+use crate::shape::SupportMap;+use crate::utils;++#[derive(Copy, Clone, PartialEq)]+struct FaceId {+ id: usize,+ neg_dist: Real,+}++impl FaceId {+ /// Creates a new face id, rejecting faces whose `neg_dist` is positive beyond `tol`.+ fn new(id: usize, neg_dist: Real, tol: Real) -> Option<Self> {+ if neg_dist > tol {+ None+ } else {+ Some(FaceId { id, neg_dist })+ }+ }+}++impl Eq for FaceId {}++impl PartialOrd for FaceId {+ #[inline]+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {+ Some(self.cmp(other))+ }+}++impl Ord for FaceId {+ #[inline]+ fn cmp(&self, other: &Self) -> Ordering {+ if self.neg_dist < other.neg_dist {+ Ordering::Less+ } else if self.neg_dist > other.neg_dist {+ Ordering::Greater+ } else {+ Ordering::Equal+ }+ }+}++#[derive(Clone, Debug)]+struct Face {+ pts: [usize; 2],+ normal: Vector,+ proj: Vector,+ bcoords: [Real; 2],+ deleted: bool,+}++impl Face {+ pub fn new(vertices: &[CsoPoint], pts: [usize; 2]) -> (Self, bool) {+ if let Some((proj, bcoords)) =+ project_origin(vertices[pts[0]].point, vertices[pts[1]].point)+ {+ (Self::new_with_proj(vertices, proj, bcoords, pts), true)+ } else {+ (+ Self::new_with_proj(vertices, Vector::ZERO, [0.0; 2], pts),+ false,+ )+ }+ }++ pub fn new_with_proj(+ vertices: &[CsoPoint],+ proj: Vector,+ bcoords: [Real; 2],+ pts: [usize; 2],+ ) -> Self {+ let normal;+ let deleted;++ if let Some(n) = utils::ccw_face_normal([vertices[pts[0]].point, vertices[pts[1]].point]) {+ normal = n;+ deleted = false;+ } else {+ normal = Vector::ZERO;+ deleted = true;+ }++ Face {+ pts,+ normal,+ proj,+ bcoords,+ deleted,+ }+ }++ pub fn closest_points(&self, vertices: &[CsoPoint]) -> (Vector, Vector) {+ (+ vertices[self.pts[0]].orig1 * self.bcoords[0]+ + vertices[self.pts[1]].orig1 * self.bcoords[1],+ vertices[self.pts[0]].orig2 * self.bcoords[0]+ + vertices[self.pts[1]].orig2 * self.bcoords[1],+ )+ }+}++/// The Expanding Polytope Algorithm in 2D.+///+/// This structure computes the penetration depth between two shapes when they are overlapping.+/// It's used after GJK (Gilbert-Johnson-Keerthi) determines that two shapes are penetrating.+///+/// # What does EPA do?+///+/// EPA finds:+/// - The **penetration depth**: How far the shapes are overlapping+/// - The **contact normal**: The direction to separate the shapes+/// - The **contact points**: Where the shapes are touching on each surface+///+/// # How it works in 2D+///+/// In 2D, EPA maintains a polygon in the Minkowski difference space (CSO - Configuration Space+/// Obstacle) that encloses the origin. It iteratively:+///+/// 1. Finds the edge closest to the origin+/// 2. Expands the polygon by adding a new support point in the direction of that edge's normal+/// 3. Updates the polygon structure with the new point+/// 4. Repeats until the polygon cannot expand further (convergence)+///+/// The final closest edge provides the penetration depth (distance to origin) and contact normal.+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::query::epa::EPA;+/// use parry2d::query::gjk::VoronoiSimplex;+/// use parry2d::shape::Ball;+/// use parry2d::math::Pose;+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+/// let pos12 = Pose::translation(1.5, 0.0); // Overlapping circles+///+/// // After GJK determines penetration and fills a simplex:+/// let mut epa = EPA::new();+/// let simplex = VoronoiSimplex::new(); // Would be filled by GJK+///+/// // EPA computes the contact details+/// // if let Some((pt1, pt2, normal)) = epa.closest_points(&pos12, &ball1, &ball2, &simplex) {+/// // println!("Penetration depth: {}", (pt2 - pt1).length());+/// // println!("Contact normal: {}", normal);+/// // }+/// # }+/// ```+///+/// # Reusability+///+/// The `EPA` structure can be reused across multiple queries to avoid allocations.+/// Internal buffers are cleared and reused in each call to [`closest_points`](EPA::closest_points).+///+/// # Convergence and Failure Cases+///+/// EPA may return `None` in these situations:+/// - The shapes are not actually penetrating (GJK should be used instead)+/// - Degenerate or nearly-degenerate geometry causes numerical instability+/// - The initial simplex from GJK is invalid+/// - The algorithm fails to converge after 100 iterations+///+/// When `None` is returned, the shapes may be touching at a single point or edge, or there+/// may be numerical precision issues with the input geometry.+#[derive(Default)]+pub struct EPA {+ vertices: Vec<CsoPoint>,+ faces: Vec<Face>,+ heap: BinaryHeap<FaceId>,+}++impl EPA {+ /// Creates a new instance of the 2D Expanding Polytope Algorithm.+ ///+ /// This allocates internal data structures (vertices, faces, and a priority heap).+ /// The same `EPA` instance can be reused for multiple queries to avoid repeated allocations.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::query::epa::EPA;+ ///+ /// let mut epa = EPA::new();+ /// // Use epa for multiple queries...+ /// # }+ /// ```+ pub fn new() -> Self {+ EPA::default()+ }++ fn reset(&mut self) {+ self.vertices.clear();+ self.faces.clear();+ self.heap.clear();+ }++ /// Projects the origin onto the boundary of the given shape.+ ///+ /// This is a specialized version of [`closest_points`](EPA::closest_points) for projecting+ /// a point (the origin) onto a single shape's surface.+ ///+ /// # Parameters+ ///+ /// - `m`: The position and orientation of the shape in world space+ /// - `g`: The shape to project onto (must implement [`SupportMap`])+ /// - `simplex`: A Voronoi simplex from GJK that encloses the origin (indicating the origin+ /// is inside the shape)+ ///+ /// # Returns+ ///+ /// - `Some(point)`: The closest point on the shape's boundary to the origin, in the local+ /// space of `g`+ /// - `None`: If the origin is not inside the shape, or if EPA failed to converge+ ///+ /// # Prerequisites+ ///+ /// The origin **must be inside** the shape. If it's outside, use GJK instead.+ /// Typically, you would:+ /// 1. Run GJK to detect if a point is inside a shape+ /// 2. If inside, use this method to find the closest boundary point+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::query::epa::EPA;+ /// use parry2d::query::gjk::VoronoiSimplex;+ /// use parry2d::shape::Ball;+ /// use parry2d::math::Pose;+ ///+ /// let ball = Ball::new(2.0);+ /// let pos = Pose::identity();+ ///+ /// // Assume GJK determined the origin is inside and filled simplex+ /// let simplex = VoronoiSimplex::new();+ /// let mut epa = EPA::new();+ ///+ /// // Find the closest point on the ball's surface to the origin+ /// // if let Some(surface_point) = epa.project_origin(&pos, &ball, &simplex) {+ /// // println!("Closest surface point: {:?}", surface_point);+ /// // }+ /// # }+ /// ```+ pub fn project_origin<G: ?Sized + SupportMap>(+ &mut self,+ m: &Pose,+ g: &G,+ simplex: &VoronoiSimplex,+ ) -> Option<Vector> {+ self.closest_points(&m.inverse(), g, &ConstantOrigin, simplex)+ .map(|(p, _, _)| p)+ }++ /// Computes the closest points between two penetrating shapes and their contact normal.+ ///+ /// This is the main EPA method that computes detailed contact information for overlapping shapes.+ /// It should be called after GJK determines that two shapes are penetrating.+ ///+ /// # Parameters+ ///+ /// - `pos12`: The relative position/orientation from `g2`'s frame to `g1`'s frame+ /// (typically computed as `pos1.inverse() * pos2`)+ /// - `g1`: The first shape (must implement [`SupportMap`])+ /// - `g2`: The second shape (must implement [`SupportMap`])+ /// - `simplex`: A Voronoi simplex from GJK that encloses the origin, indicating penetration+ ///+ /// # Returns+ ///+ /// Returns `Some((point1, point2, normal))` where:+ /// - `point1`: Contact point on shape `g1` in `g1`'s local frame+ /// - `point2`: Contact point on shape `g2` in `g2`'s local frame+ /// - `normal`: Contact normal pointing from `g2` toward `g1`, normalized+ ///+ /// The **penetration depth** can be computed as `(point1 - point2).length()` after transforming+ /// both points to the same coordinate frame.+ ///+ /// Returns `None` if:+ /// - The shapes are not actually penetrating+ /// - EPA fails to converge (degenerate geometry, numerical issues)+ /// - The simplex is invalid or empty+ /// - The algorithm reaches the maximum iteration limit (100 iterations)+ ///+ /// # Prerequisites+ ///+ /// The shapes **must be penetrating**. The typical workflow is:+ /// 1. Run GJK to check if shapes intersect+ /// 2. If GJK detects penetration and returns a simplex enclosing the origin+ /// 3. Use EPA with that simplex to compute detailed contact information+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::query::epa::EPA;+ /// use parry2d::query::gjk::{GJKResult, VoronoiSimplex};+ /// use parry2d::shape::Ball;+ /// use parry2d::math::Pose;+ ///+ /// let ball1 = Ball::new(1.0);+ /// let ball2 = Ball::new(1.0);+ ///+ /// let pos1 = Pose::identity();+ /// let pos2 = Pose::translation(1.5, 0.0); // Overlapping+ /// let pos12 = pos1.inverse() * pos2;+ ///+ /// // After GJK detects penetration:+ /// let mut simplex = VoronoiSimplex::new();+ /// // ... simplex would be filled by GJK ...+ ///+ /// let mut epa = EPA::new();+ /// // if let Some((pt1, pt2, normal)) = epa.closest_points(&pos12, &ball1, &ball2, &simplex) {+ /// // println!("Contact on shape 1: {:?}", pt1);+ /// // println!("Contact on shape 2: {:?}", pt2);+ /// // println!("Contact normal: {}", normal);+ /// // println!("Penetration depth: ~0.5");+ /// // }+ /// # }+ /// ```+ ///+ /// # Technical Details+ ///+ /// The algorithm works in the **Minkowski difference space** (also called the Configuration+ /// Space Obstacle or CSO), where the difference between support points of the two shapes+ /// forms a new shape. When shapes penetrate, this CSO contains the origin.+ ///+ /// EPA iteratively expands a polygon (in 2D) that surrounds the origin, finding the edge+ /// closest to the origin at each iteration. This closest edge defines the penetration+ /// depth and contact normal.+ pub fn closest_points<G1, G2>(+ &mut self,+ pos12: &Pose,+ g1: &G1,+ g2: &G2,+ simplex: &VoronoiSimplex,+ ) -> Option<(Vector, Vector, Vector)>+ where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+ {+ let _eps: Real = crate::math::DEFAULT_EPSILON;+ let _eps_tol = _eps * 100.0;++ self.reset();++ /*+ * Initialization.+ */+ for i in 0..simplex.dimension() + 1 {+ self.vertices.push(*simplex.point(i));+ }++ // Tolerance used to reject degenerate faces. It is scaled relative to the magnitude of+ // the simplex coordinates: dot products used to compute face distances accumulate+ // rounding errors proportional to the coordinate magnitudes, so an absolute tolerance+ // would spuriously abort EPA for large coordinates.+ // See <https://github.com/dimforge/parry/issues/415>.+ let dist_tol = {+ let scale = self+ .vertices+ .iter()+ .map(|v| v.point.length())+ .fold(0.0, Real::max);+ gjk::eps_tol() * scale.max(1.0)+ };++ if simplex.dimension() == 0 {+ const MAX_ITERS: usize = 100; // If there is no convergence, just use whatever direction was extracted so fare++ // The contact is vertex-vertex.+ // We need to determine a valid normal that lies+ // on both vertices' normal cone.+ let mut n = Vector::Y;++ // First, find a vector on the first vertex tangent cone.+ let orig1 = self.vertices[0].orig1;+ for _ in 0..MAX_ITERS {+ let supp1 = g1.local_support_point(n);+ if let Some(tangent) = (supp1 - orig1).try_normalize() {+ if n.dot(tangent) < _eps_tol {+ break;+ }++ n = Vector::new(-tangent.y, tangent.x);+ } else {+ break;+ }+ }++ // Second, ensure the direction lies on the second vertex's tangent cone.+ let orig2 = self.vertices[0].orig2;+ for _ in 0..MAX_ITERS {+ let supp2 = g2.support_point(pos12, -n);+ if let Some(tangent) = (supp2 - orig2).try_normalize() {+ if (-n).dot(tangent) < _eps_tol {+ break;+ }++ n = Vector::new(-tangent.y, tangent.x);+ } else {+ break;+ }+ }++ // The CSO point lies at the origin, so both support points coincide at the+ // touching location: report them instead of fabricated zeros.+ let v = self.vertices[0];+ return Some((v.orig1, v.orig2, n));+ } else if simplex.dimension() == 2 {+ let dp1 = self.vertices[1] - self.vertices[0];+ let dp2 = self.vertices[2] - self.vertices[0];++ if dp1.perp_dot(dp2) < 0.0 {+ self.vertices.swap(1, 2)+ }++ let pts1 = [0, 1];+ let pts2 = [1, 2];+ let pts3 = [2, 0];++ let (face1, proj_inside1) = Face::new(&self.vertices, pts1);+ let (face2, proj_inside2) = Face::new(&self.vertices, pts2);+ let (face3, proj_inside3) = Face::new(&self.vertices, pts3);++ self.faces.push(face1);+ self.faces.push(face2);+ self.faces.push(face3);++ if proj_inside1 {+ let dist1 = self.faces[0].normal.dot(self.vertices[0].point);+ self.heap.push(FaceId::new(0, -dist1, dist_tol)?);+ }++ if proj_inside2 {+ let dist2 = self.faces[1].normal.dot(self.vertices[1].point);+ self.heap.push(FaceId::new(1, -dist2, dist_tol)?);+ }++ if proj_inside3 {+ let dist3 = self.faces[2].normal.dot(self.vertices[2].point);+ self.heap.push(FaceId::new(2, -dist3, dist_tol)?);+ }++ if !(proj_inside1 || proj_inside2 || proj_inside3) {+ // Related issues:+ // https://github.com/dimforge/parry/issues/253+ // https://github.com/dimforge/parry/issues/246+ log::debug!("Hit unexpected state in EPA: failed to project the origin on the initial simplex.");+ return None;+ }+ } else {+ let pts1 = [0, 1];+ let pts2 = [1, 0];++ self.faces.push(Face::new_with_proj(+ &self.vertices,+ Vector::ZERO,+ [1.0, 0.0],+ pts1,+ ));+ self.faces.push(Face::new_with_proj(+ &self.vertices,+ Vector::ZERO,+ [1.0, 0.0],+ pts2,+ ));++ let dist1 = self.faces[0].normal.dot(self.vertices[0].point);+ let dist2 = self.faces[1].normal.dot(self.vertices[1].point);++ self.heap.push(FaceId::new(0, dist1, dist_tol)?);+ self.heap.push(FaceId::new(1, dist2, dist_tol)?);+ }++ let mut niter = 0;+ let mut max_dist = Real::max_value();+ let mut best_face_id = *self.heap.peek().unwrap();+ let mut old_dist = 0.0;++ /*+ * Run the expansion.+ */+ while let Some(face_id) = self.heap.pop() {+ // Create new faces.+ let face = self.faces[face_id.id].clone();++ if face.deleted {+ continue;+ }++ let cso_point = CsoPoint::from_shapes(pos12, g1, g2, face.normal);+ let support_point_id = self.vertices.len();+ self.vertices.push(cso_point);++ let candidate_max_dist = cso_point.point.dot(face.normal);++ if candidate_max_dist < max_dist {+ best_face_id = face_id;+ max_dist = candidate_max_dist;+ }++ let curr_dist = -face_id.neg_dist;++ if max_dist - curr_dist < _eps_tol ||+ // Accept the intersection as the algorithm is stuck and no new points will be found+ // This happens because of numerical stability issue+ ((curr_dist - old_dist).abs() < _eps && candidate_max_dist < max_dist)+ {+ let best_face = &self.faces[best_face_id.id];+ let cpts = best_face.closest_points(&self.vertices);+ return Some((cpts.0, cpts.1, best_face.normal));+ }++ old_dist = curr_dist;++ let pts1 = [face.pts[0], support_point_id];+ let pts2 = [support_point_id, face.pts[1]];++ let new_faces = [+ Face::new(&self.vertices, pts1),+ Face::new(&self.vertices, pts2),+ ];++ for f in new_faces.iter() {+ if f.1 {+ let dist = f.0.normal.dot(f.0.proj);+ if dist < curr_dist {+ // TODO: if we reach this point, there were issues due to+ // numerical errors.+ let cpts = f.0.closest_points(&self.vertices);+ return Some((cpts.0, cpts.1, f.0.normal));+ }++ if !f.0.deleted {+ self.heap+ .push(FaceId::new(self.faces.len(), -dist, dist_tol)?);+ }+ }++ self.faces.push(f.0.clone());+ }++ niter += 1;+ if niter > 100 {+ // if we reached this point, our algorithm didn't converge to what precision we wanted.+ // still return an intersection point, as it's probably close enough.+ break;+ }+ }++ let best_face = &self.faces[best_face_id.id];+ let cpts = best_face.closest_points(&self.vertices);+ Some((cpts.0, cpts.1, best_face.normal))+ }+}++fn project_origin(a: Vector, b: Vector) -> Option<(Vector, [Real; 2])> {+ let ab = b - a;+ let ap = -a;+ let ab_ap = ab.dot(ap);+ let sqnab = ab.length_squared();++ if sqnab == 0.0 {+ return None;+ }++ let position_on_segment;++ let _eps: Real = gjk::eps_tol();++ if ab_ap < -_eps || ab_ap > sqnab + _eps {+ // Voronoï region of vertex 'a' or 'b'.+ None+ } else {+ // Voronoï region of the segment interior.+ position_on_segment = ab_ap / sqnab;++ let res = a + ab * position_on_segment;++ Some((res, [1.0 - position_on_segment, position_on_segment]))+ }+}diff --git a/renderer/third_party/parry3d/src/query/epa/epa3.rs b/renderer/third_party/parry3d/src/query/epa/epa3.rsnew file mode 100644index 0000000..a32b339--- /dev/null+++ b/renderer/third_party/parry3d/src/query/epa/epa3.rs@@ -0,0 +1,781 @@+//! Three-dimensional penetration depth queries using the Expanding Polytope Algorithm.+//!+//! This module provides the 3D-specific implementation of EPA, which works with+//! polyhedra (triangular faces) rather than polygons (edges) as in the 2D version.++use crate::math::{Pose, Real, Vector};+use crate::query::gjk::{self, ConstantOrigin, CsoPoint, VoronoiSimplex};+use crate::query::PointQueryWithLocation;+use crate::shape::{SupportMap, Triangle, TrianglePointLocation};+use crate::utils;+use alloc::collections::BinaryHeap;+use alloc::vec::Vec;+use core::cmp::Ordering;+use num::Bounded;++#[derive(Copy, Clone, PartialEq)]+struct FaceId {+ id: usize,+ neg_dist: Real,+}++impl FaceId {+ /// Creates a new face id, rejecting faces whose `neg_dist` is positive beyond `tol`.+ fn new(id: usize, neg_dist: Real, tol: Real) -> Option<Self> {+ if neg_dist > tol {+ None+ } else {+ Some(FaceId { id, neg_dist })+ }+ }+}++impl Eq for FaceId {}++impl PartialOrd for FaceId {+ #[inline]+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {+ Some(self.cmp(other))+ }+}++impl Ord for FaceId {+ #[inline]+ fn cmp(&self, other: &Self) -> Ordering {+ if self.neg_dist < other.neg_dist {+ Ordering::Less+ } else if self.neg_dist > other.neg_dist {+ Ordering::Greater+ } else {+ Ordering::Equal+ }+ }+}++#[derive(Clone, Debug)]+struct Face {+ pts: [usize; 3],+ adj: [usize; 3],+ normal: Vector,+ bcoords: [Real; 3],+ deleted: bool,+}++impl Face {+ pub fn new_with_proj(+ vertices: &[CsoPoint],+ bcoords: [Real; 3],+ pts: [usize; 3],+ adj: [usize; 3],+ ) -> Self {+ let normal;++ if let Some(n) = utils::ccw_face_normal([+ vertices[pts[0]].point,+ vertices[pts[1]].point,+ vertices[pts[2]].point,+ ]) {+ normal = n;+ } else {+ // This is a bit of a hack for degenerate faces.+ // TODO: It will work OK with our current code, though+ // we should do this in another way to avoid any risk+ // of misusing the face normal in the future.+ normal = Vector::ZERO;+ }++ Face {+ pts,+ bcoords,+ adj,+ normal,+ deleted: false,+ }+ }++ pub fn new(vertices: &[CsoPoint], pts: [usize; 3], adj: [usize; 3]) -> (Self, bool) {+ let tri = Triangle::new(+ vertices[pts[0]].point,+ vertices[pts[1]].point,+ vertices[pts[2]].point,+ );+ let (proj, loc) = tri.project_local_point_and_get_location(Vector::ZERO, true);++ match loc {+ TrianglePointLocation::OnVertex(_) | TrianglePointLocation::OnEdge(_, _) => {+ let eps_tol = crate::math::DEFAULT_EPSILON * 100.0; // Same as in closest_points+ (+ // barycentric_coordinates is guaranteed to work in OnVertex and OnEdge locations+ Self::new_with_proj(vertices, loc.barycentric_coordinates().unwrap(), pts, adj),+ proj.is_inside_eps(Vector::ZERO, eps_tol),+ )+ }+ TrianglePointLocation::OnFace(_, bcoords) => {+ (Self::new_with_proj(vertices, bcoords, pts, adj), true)+ }+ _ => (Self::new_with_proj(vertices, [0.0; 3], pts, adj), false),+ }+ }++ pub fn closest_points(&self, vertices: &[CsoPoint]) -> (Vector, Vector) {+ (+ vertices[self.pts[0]].orig1 * self.bcoords[0]+ + vertices[self.pts[1]].orig1 * self.bcoords[1]+ + vertices[self.pts[2]].orig1 * self.bcoords[2],+ vertices[self.pts[0]].orig2 * self.bcoords[0]+ + vertices[self.pts[1]].orig2 * self.bcoords[1]+ + vertices[self.pts[2]].orig2 * self.bcoords[2],+ )+ }++ pub fn contains_point(&self, id: usize) -> bool {+ self.pts[0] == id || self.pts[1] == id || self.pts[2] == id+ }++ pub fn next_ccw_pt_id(&self, id: usize) -> usize {+ if self.pts[0] == id {+ 1+ } else if self.pts[1] == id {+ 2+ } else {+ if self.pts[2] != id {+ log::debug!(+ "Hit unexpected state in EPA: found index {}, expected: {}.",+ self.pts[2],+ id+ );+ }++ 0+ }+ }++ pub fn can_be_seen_by(&self, vertices: &[CsoPoint], point: usize, opp_pt_id: usize) -> bool {+ let p0 = &vertices[self.pts[opp_pt_id]].point;+ let p1 = &vertices[self.pts[(opp_pt_id + 1) % 3]].point;+ let p2 = &vertices[self.pts[(opp_pt_id + 2) % 3]].point;+ let pt = &vertices[point].point;++ // NOTE: it is important that we return true for the case where+ // the dot product is zero. This is because degenerate faces will+ // have a zero normal, causing the dot product to be zero.+ // So return true for these case will let us skip the triangle+ // during silhouette computation.+ (*pt - *p0).dot(self.normal) >= -gjk::eps_tol()+ || Triangle::new(*p1, *p2, *pt).is_affinely_dependent()+ }+}++struct SilhouetteEdge {+ face_id: usize,+ opp_pt_id: usize,+}++impl SilhouetteEdge {+ pub fn new(face_id: usize, opp_pt_id: usize) -> Self {+ SilhouetteEdge { face_id, opp_pt_id }+ }+}++/// The Expanding Polytope Algorithm in 3D.+///+/// This structure computes the penetration depth between two shapes when they are overlapping.+/// It's used after GJK (Gilbert-Johnson-Keerthi) determines that two shapes are penetrating.+///+/// # What does EPA do?+///+/// EPA finds:+/// - The **penetration depth**: How far the shapes are overlapping+/// - The **contact normal**: The direction to separate the shapes+/// - The **contact points**: Where the shapes are touching on each surface+///+/// # How it works in 3D+///+/// In 3D, EPA maintains a convex polyhedron (made of triangular faces) in the Minkowski+/// difference space (CSO - Configuration Space Obstacle) that encloses the origin. It iteratively:+///+/// 1. Finds the triangular face closest to the origin+/// 2. Expands the polyhedron by adding a new support point in the direction of that face's normal+/// 3. Removes faces that can be "seen" from the new point (they're now inside)+/// 4. Creates new faces connecting the boundary edges (silhouette) to the new point+/// 5. Repeats until the polyhedron cannot expand further (convergence)+///+/// The final closest face provides the penetration depth (distance to origin) and contact normal.+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::epa::EPA;+/// use parry3d::query::gjk::VoronoiSimplex;+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+/// let pos12 = Pose::translation(1.5, 0.0, 0.0); // Overlapping spheres+///+/// // After GJK determines penetration and fills a simplex:+/// let mut epa = EPA::new();+/// let simplex = VoronoiSimplex::new(); // Would be filled by GJK+///+/// // EPA computes the contact details+/// // if let Some((pt1, pt2, normal)) = epa.closest_points(&pos12, &ball1, &ball2, &simplex) {+/// // println!("Penetration depth: {}", (pt2 - pt1).length());+/// // println!("Contact normal: {}", normal);+/// // }+/// # }+/// ```+///+/// # Reusability+///+/// The `EPA` structure can be reused across multiple queries to avoid allocations.+/// Internal buffers are cleared and reused in each call to [`closest_points`](EPA::closest_points).+///+/// # Convergence and Failure Cases+///+/// EPA may return `None` in these situations:+/// - The shapes are not actually penetrating (GJK should be used instead)+/// - Degenerate or nearly-degenerate geometry causes numerical instability+/// - The initial simplex from GJK is invalid+/// - The algorithm fails to converge after 100 iterations+/// - Silhouette extraction fails (topology issues)+///+/// When `None` is returned, the shapes may be touching at a single point, edge, or face,+/// or there may be numerical precision issues with the input geometry.+///+/// # Complexity+///+/// The 3D EPA implementation is more complex than 2D because:+/// - It maintains a 3D mesh topology with face adjacency information+/// - It needs to compute silhouettes (visible edges from a point)+/// - It handles more degenerate cases (coplanar faces, edge cases)+#[derive(Default)]+pub struct EPA {+ vertices: Vec<CsoPoint>,+ faces: Vec<Face>,+ silhouette: Vec<SilhouetteEdge>,+ heap: BinaryHeap<FaceId>,+}++impl EPA {+ /// Creates a new instance of the 3D Expanding Polytope Algorithm.+ ///+ /// This allocates internal data structures (vertices, faces, silhouette buffer, and a priority heap).+ /// The same `EPA` instance can be reused for multiple queries to avoid repeated allocations.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::epa::EPA;+ ///+ /// let mut epa = EPA::new();+ /// // Use epa for multiple queries...+ /// # }+ /// ```+ pub fn new() -> Self {+ Self::default()+ }++ fn reset(&mut self) {+ self.vertices.clear();+ self.faces.clear();+ self.heap.clear();+ self.silhouette.clear();+ }++ /// Projects the origin onto the boundary of the given shape.+ ///+ /// This is a specialized version of [`closest_points`](EPA::closest_points) for projecting+ /// a point (the origin) onto a single shape's surface.+ ///+ /// # Parameters+ ///+ /// - `m`: The position and orientation of the shape in world space+ /// - `g`: The shape to project onto (must implement [`SupportMap`])+ /// - `simplex`: A Voronoi simplex from GJK that encloses the origin (indicating the origin+ /// is inside the shape)+ ///+ /// # Returns+ ///+ /// - `Some(point)`: The closest point on the shape's boundary to the origin, in the local+ /// space of `g`+ /// - `None`: If the origin is not inside the shape, or if EPA failed to converge+ ///+ /// # Prerequisites+ ///+ /// The origin **must be inside** the shape. If it's outside, use GJK instead.+ /// Typically, you would:+ /// 1. Run GJK to detect if a point is inside a shape+ /// 2. If inside, use this method to find the closest boundary point+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::epa::EPA;+ /// use parry3d::query::gjk::VoronoiSimplex;+ /// use parry3d::shape::Ball;+ /// use parry3d::math::Pose;+ ///+ /// let ball = Ball::new(2.0);+ /// let pos = Pose::identity();+ ///+ /// // Assume GJK determined the origin is inside and filled simplex+ /// let simplex = VoronoiSimplex::new();+ /// let mut epa = EPA::new();+ ///+ /// // Find the closest point on the ball's surface to the origin+ /// // if let Some(surface_point) = epa.project_origin(&pos, &ball, &simplex) {+ /// // println!("Closest surface point: {:?}", surface_point);+ /// // }+ /// # }+ /// ```+ pub fn project_origin<G: ?Sized + SupportMap>(+ &mut self,+ m: &Pose,+ g: &G,+ simplex: &VoronoiSimplex,+ ) -> Option<Vector> {+ self.closest_points(&m.inverse(), g, &ConstantOrigin, simplex)+ .map(|(p, _, _)| p)+ }++ /// Computes the closest points between two penetrating shapes and their contact normal.+ ///+ /// This is the main EPA method that computes detailed contact information for overlapping shapes.+ /// It should be called after GJK determines that two shapes are penetrating.+ ///+ /// # Parameters+ ///+ /// - `pos12`: The relative position/orientation from `g2`'s frame to `g1`'s frame+ /// (typically computed as `pos1.inverse() * pos2`)+ /// - `g1`: The first shape (must implement [`SupportMap`])+ /// - `g2`: The second shape (must implement [`SupportMap`])+ /// - `simplex`: A Voronoi simplex from GJK that encloses the origin, indicating penetration+ ///+ /// # Returns+ ///+ /// Returns `Some((point1, point2, normal))` where:+ /// - `point1`: Contact point on shape `g1` in `g1`'s local frame+ /// - `point2`: Contact point on shape `g2` in `g2`'s local frame+ /// - `normal`: Contact normal pointing from `g2` toward `g1`, normalized+ ///+ /// The **penetration depth** can be computed as `(point1 - point2).length()` after transforming+ /// both points to the same coordinate frame.+ ///+ /// Returns `None` if:+ /// - The shapes are not actually penetrating+ /// - EPA fails to converge (degenerate geometry, numerical issues)+ /// - The simplex is invalid or empty+ /// - The algorithm reaches the maximum iteration limit (100 iterations)+ /// - Silhouette extraction fails (indicates topology corruption)+ ///+ /// # Prerequisites+ ///+ /// The shapes **must be penetrating**. The typical workflow is:+ /// 1. Run GJK to check if shapes intersect+ /// 2. If GJK detects penetration and returns a simplex enclosing the origin+ /// 3. Use EPA with that simplex to compute detailed contact information+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::epa::EPA;+ /// use parry3d::query::gjk::{GJKResult, VoronoiSimplex};+ /// use parry3d::shape::Ball;+ /// use parry3d::math::Pose;+ ///+ /// let ball1 = Ball::new(1.0);+ /// let ball2 = Ball::new(1.0);+ ///+ /// let pos1 = Pose::identity();+ /// let pos2 = Pose::translation(1.5, 0.0, 0.0); // Overlapping+ /// let pos12 = pos1.inverse() * pos2;+ ///+ /// // After GJK detects penetration:+ /// let mut simplex = VoronoiSimplex::new();+ /// // ... simplex would be filled by GJK ...+ ///+ /// let mut epa = EPA::new();+ /// // if let Some((pt1, pt2, normal)) = epa.closest_points(&pos12, &ball1, &ball2, &simplex) {+ /// // println!("Contact on shape 1: {:?}", pt1);+ /// // println!("Contact on shape 2: {:?}", pt2);+ /// // println!("Contact normal: {}", normal);+ /// // println!("Penetration depth: ~0.5");+ /// // }+ /// # }+ /// ```+ ///+ /// # Technical Details+ ///+ /// The algorithm works in the **Minkowski difference space** (also called the Configuration+ /// Space Obstacle or CSO), where the difference between support points of the two shapes+ /// forms a new shape. When shapes penetrate, this CSO contains the origin.+ ///+ /// EPA iteratively expands a convex polyhedron (in 3D) that surrounds the origin. At each+ /// iteration:+ /// 1. It finds the triangular face closest to the origin+ /// 2. Computes a support point in that face's normal direction+ /// 3. Determines which existing faces are visible from the new point (the **silhouette**)+ /// 4. Removes visible faces and creates new ones connecting the silhouette boundary to the new point+ ///+ /// This process maintains a valid convex hull that progressively tightens around the+ /// origin until convergence, at which point the closest face defines the penetration+ /// depth and contact normal.+ pub fn closest_points<G1, G2>(+ &mut self,+ pos12: &Pose,+ g1: &G1,+ g2: &G2,+ simplex: &VoronoiSimplex,+ ) -> Option<(Vector, Vector, Vector)>+ where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+ {+ let _eps = crate::math::DEFAULT_EPSILON;+ let _eps_tol = _eps * 100.0;++ self.reset();++ /*+ * Initialization.+ */+ for i in 0..simplex.dimension() + 1 {+ self.vertices.push(*simplex.point(i));+ }++ if simplex.dimension() == 0 {+ // The GJK simplex degenerated to a single point on the CSO boundary, typically+ // an exactly-touching contact. Bootstrap a second vertex from an axis-aligned+ // support direction so the expansion below can find the normal.+ let candidates = [+ Vector::X,+ Vector::Y,+ Vector::Z,+ -Vector::X,+ -Vector::Y,+ -Vector::Z,+ ];+ let sep_tol = gjk::eps_tol();+ let bootstrap = candidates.iter().find_map(|dir| {+ let pt = CsoPoint::from_shapes(pos12, g1, g2, *dir);+ ((pt.point - self.vertices[0].point).length_squared() > sep_tol * sep_tol)+ .then_some(pt)+ });++ match bootstrap {+ Some(pt) => self.vertices.push(pt),+ None => {+ // The CSO is degenerate (a single point): no meaningful normal exists.+ let v = self.vertices[0];+ return Some((v.orig1, v.orig2, Vector::Y));+ }+ }+ }++ // Tolerance used to reject degenerate faces. It is scaled relative to the magnitude of+ // the simplex coordinates: dot products used to compute face distances accumulate+ // rounding errors proportional to the coordinate magnitudes, so an absolute tolerance+ // would spuriously abort EPA for large coordinates.+ // See <https://github.com/dimforge/parry/issues/415>.+ let dist_tol = {+ let scale = self+ .vertices+ .iter()+ .map(|v| v.point.length())+ .fold(0.0, Real::max);+ gjk::eps_tol() * scale.max(1.0)+ };++ if simplex.dimension() == 3 {+ let dp1 = self.vertices[1] - self.vertices[0];+ let dp2 = self.vertices[2] - self.vertices[0];+ let dp3 = self.vertices[3] - self.vertices[0];++ if dp1.cross(dp2).dot(dp3) > 0.0 {+ self.vertices.swap(1, 2)+ }++ let pts1 = [0, 1, 2];+ let pts2 = [1, 3, 2];+ let pts3 = [0, 2, 3];+ let pts4 = [0, 3, 1];++ let adj1 = [3, 1, 2];+ let adj2 = [3, 2, 0];+ let adj3 = [0, 1, 3];+ let adj4 = [2, 1, 0];++ let (face1, proj_inside1) = Face::new(&self.vertices, pts1, adj1);+ let (face2, proj_inside2) = Face::new(&self.vertices, pts2, adj2);+ let (face3, proj_inside3) = Face::new(&self.vertices, pts3, adj3);+ let (face4, proj_inside4) = Face::new(&self.vertices, pts4, adj4);++ self.faces.push(face1);+ self.faces.push(face2);+ self.faces.push(face3);+ self.faces.push(face4);++ if proj_inside1 {+ let dist1 = self.faces[0].normal.dot(self.vertices[0].point);+ self.heap.push(FaceId::new(0, -dist1, dist_tol)?);+ }++ if proj_inside2 {+ let dist2 = self.faces[1].normal.dot(self.vertices[1].point);+ self.heap.push(FaceId::new(1, -dist2, dist_tol)?);+ }++ if proj_inside3 {+ let dist3 = self.faces[2].normal.dot(self.vertices[2].point);+ self.heap.push(FaceId::new(2, -dist3, dist_tol)?);+ }++ if proj_inside4 {+ let dist4 = self.faces[3].normal.dot(self.vertices[3].point);+ self.heap.push(FaceId::new(3, -dist4, dist_tol)?);+ }++ if !(proj_inside1 || proj_inside2 || proj_inside3 || proj_inside4) {+ // Related issues:+ // https://github.com/dimforge/parry/issues/253+ // https://github.com/dimforge/parry/issues/246+ log::debug!("Hit unexpected state in EPA: failed to project the origin on the initial simplex.");+ return None;+ }+ } else {+ // NOTE: len == 2 covers both a 1-dimensional GJK simplex and a 0-dimensional+ // one completed by the bootstrap above.+ if self.vertices.len() == 2 {+ let dpt = self.vertices[1] - self.vertices[0];++ crate::math::orthonormal_subspace_basis(&[dpt], |dir| {+ // dir is already normalized by orthonormal_subspace_basis+ self.vertices+ .push(CsoPoint::from_shapes(pos12, g1, g2, dir));+ false+ });+ }++ let pts1 = [0, 1, 2];+ let pts2 = [0, 2, 1];++ let adj1 = [1, 1, 1];+ let adj2 = [0, 0, 0];++ let (face1, _) = Face::new(&self.vertices, pts1, adj1);+ let (face2, _) = Face::new(&self.vertices, pts2, adj2);+ self.faces.push(face1);+ self.faces.push(face2);++ self.heap.push(FaceId::new(0, 0.0, dist_tol)?);+ self.heap.push(FaceId::new(1, 0.0, dist_tol)?);+ }++ let mut niter = 0;+ let mut max_dist = Real::max_value();+ let mut best_face_id = *self.heap.peek()?;+ let mut old_dist = 0.0;++ /*+ * Run the expansion.+ */+ while let Some(face_id) = self.heap.pop() {+ // Create new faces.+ let face = self.faces[face_id.id].clone();++ if face.deleted {+ continue;+ }++ let cso_point = CsoPoint::from_shapes(pos12, g1, g2, face.normal);+ let support_point_id = self.vertices.len();+ self.vertices.push(cso_point);++ let candidate_max_dist = cso_point.point.dot(face.normal);++ if candidate_max_dist < max_dist {+ best_face_id = face_id;+ max_dist = candidate_max_dist;+ }++ let curr_dist = -face_id.neg_dist;++ if max_dist - curr_dist < _eps_tol ||+ // Accept the intersection as the algorithm is stuck and no new points will be found+ // This happens because of numerical stability issue+ ((curr_dist - old_dist).abs() < _eps && candidate_max_dist < max_dist)+ {+ let best_face = &self.faces[best_face_id.id];+ let points = best_face.closest_points(&self.vertices);+ return Some((points.0, points.1, best_face.normal));+ }++ old_dist = curr_dist;++ self.faces[face_id.id].deleted = true;++ let adj_opp_pt_id1 = self.faces[face.adj[0]].next_ccw_pt_id(face.pts[0]);+ let adj_opp_pt_id2 = self.faces[face.adj[1]].next_ccw_pt_id(face.pts[1]);+ let adj_opp_pt_id3 = self.faces[face.adj[2]].next_ccw_pt_id(face.pts[2]);++ self.compute_silhouette(support_point_id, face.adj[0], adj_opp_pt_id1);+ self.compute_silhouette(support_point_id, face.adj[1], adj_opp_pt_id2);+ self.compute_silhouette(support_point_id, face.adj[2], adj_opp_pt_id3);++ let first_new_face_id = self.faces.len();++ if self.silhouette.is_empty() {+ // TODO: Something went very wrong because we failed to extract a silhouette…+ return None;+ }++ for edge in &self.silhouette {+ if !self.faces[edge.face_id].deleted {+ let new_face_id = self.faces.len();++ let face_adj = &mut self.faces[edge.face_id];+ let pt_id1 = face_adj.pts[(edge.opp_pt_id + 2) % 3];+ let pt_id2 = face_adj.pts[(edge.opp_pt_id + 1) % 3];++ let pts = [pt_id1, pt_id2, support_point_id];+ let adj = [edge.face_id, new_face_id + 1, new_face_id - 1];+ let new_face = Face::new(&self.vertices, pts, adj);++ face_adj.adj[(edge.opp_pt_id + 1) % 3] = new_face_id;++ self.faces.push(new_face.0);++ if new_face.1 {+ let pt = self.vertices[self.faces[new_face_id].pts[0]].point;+ let dist = self.faces[new_face_id].normal.dot(pt);+ if dist < curr_dist {+ // TODO: if we reach this point, there were issues due to+ // numerical errors.+ let points = face.closest_points(&self.vertices);+ return Some((points.0, points.1, face.normal));+ }++ self.heap.push(FaceId::new(new_face_id, -dist, dist_tol)?);+ }+ }+ }++ if first_new_face_id == self.faces.len() {+ // Something went very wrong because all the edges+ // from the silhouette belonged to deleted faces.+ return None;+ }++ self.faces[first_new_face_id].adj[2] = self.faces.len() - 1;+ self.faces.last_mut().unwrap().adj[1] = first_new_face_id;++ self.silhouette.clear();+ // self.check_topology(); // NOTE: for debugging only.++ niter += 1;+ if niter > 100 {+ // if we reached this point, our algorithm didn't converge to what precision we wanted.+ // still return an intersection point, as it's probably close enough.+ break;+ }+ }++ let best_face = &self.faces[best_face_id.id];+ let points = best_face.closest_points(&self.vertices);+ Some((points.0, points.1, best_face.normal))+ }++ fn compute_silhouette(&mut self, point: usize, id: usize, opp_pt_id: usize) {+ if !self.faces[id].deleted {+ if !self.faces[id].can_be_seen_by(&self.vertices, point, opp_pt_id) {+ self.silhouette.push(SilhouetteEdge::new(id, opp_pt_id));+ } else {+ self.faces[id].deleted = true;++ let adj_pt_id1 = (opp_pt_id + 2) % 3;+ let adj_pt_id2 = opp_pt_id;++ let adj1 = self.faces[id].adj[adj_pt_id1];+ let adj2 = self.faces[id].adj[adj_pt_id2];++ let adj_opp_pt_id1 =+ self.faces[adj1].next_ccw_pt_id(self.faces[id].pts[adj_pt_id1]);+ let adj_opp_pt_id2 =+ self.faces[adj2].next_ccw_pt_id(self.faces[id].pts[adj_pt_id2]);++ self.compute_silhouette(point, adj1, adj_opp_pt_id1);+ self.compute_silhouette(point, adj2, adj_opp_pt_id2);+ }+ }+ }++ #[allow(dead_code)]+ #[cfg(feature = "std")]+ fn print_silhouette(&self) {+ use std::{print, println};++ print!("Silhouette points: ");+ for i in 0..self.silhouette.len() {+ let edge = &self.silhouette[i];+ let face = &self.faces[edge.face_id];++ if !face.deleted {+ print!(+ "({}, {}) ",+ face.pts[(edge.opp_pt_id + 2) % 3],+ face.pts[(edge.opp_pt_id + 1) % 3]+ );+ }+ }+ println!();+ }++ #[allow(dead_code)]+ fn check_topology(&self) {+ for i in 0..self.faces.len() {+ let face = &self.faces[i];+ if face.deleted {+ continue;+ }++ // println!("checking {}-th face.", i);+ let adj1 = &self.faces[face.adj[0]];+ let adj2 = &self.faces[face.adj[1]];+ let adj3 = &self.faces[face.adj[2]];++ assert!(!adj1.deleted);+ assert!(!adj2.deleted);+ assert!(!adj3.deleted);++ assert!(face.pts[0] != face.pts[1]);+ assert!(face.pts[0] != face.pts[2]);+ assert!(face.pts[1] != face.pts[2]);++ assert!(adj1.contains_point(face.pts[0]));+ assert!(adj1.contains_point(face.pts[1]));++ assert!(adj2.contains_point(face.pts[1]));+ assert!(adj2.contains_point(face.pts[2]));++ assert!(adj3.contains_point(face.pts[2]));+ assert!(adj3.contains_point(face.pts[0]));++ let opp_pt_id1 = adj1.next_ccw_pt_id(face.pts[0]);+ let opp_pt_id2 = adj2.next_ccw_pt_id(face.pts[1]);+ let opp_pt_id3 = adj3.next_ccw_pt_id(face.pts[2]);++ assert!(!face.contains_point(adj1.pts[opp_pt_id1]));+ assert!(!face.contains_point(adj2.pts[opp_pt_id2]));+ assert!(!face.contains_point(adj3.pts[opp_pt_id3]));++ assert!(adj1.adj[(opp_pt_id1 + 1) % 3] == i);+ assert!(adj2.adj[(opp_pt_id2 + 1) % 3] == i);+ assert!(adj3.adj[(opp_pt_id3 + 1) % 3] == i);+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/epa/mod.rs b/renderer/third_party/parry3d/src/query/epa/mod.rsnew file mode 100644index 0000000..2f59e2c--- /dev/null+++ b/renderer/third_party/parry3d/src/query/epa/mod.rs@@ -0,0 +1,97 @@+//! Expanding Polytope Algorithm (EPA) for computing penetration depth and contact information.+//!+//! # What is EPA?+//!+//! The **Expanding Polytope Algorithm (EPA)** is a computational geometry algorithm used to+//! determine how deeply two convex shapes are penetrating each other. It works as a follow-up+//! to the GJK (Gilbert-Johnson-Keerthi) algorithm.+//!+//! # How EPA relates to GJK+//!+//! **GJK and EPA work together as a two-stage process:**+//!+//! 1. **GJK** (Gilbert-Johnson-Keerthi) quickly determines if two shapes are intersecting+//! - If shapes are **separated**: GJK computes the distance between them+//! - If shapes are **penetrating**: GJK detects the penetration but cannot compute the depth+//!+//! 2. **EPA** takes over when shapes are penetrating+//! - Uses GJK's final simplex (a set of points surrounding the origin) as a starting point+//! - Iteratively expands this simplex to find the penetration depth and contact normal+//!+//! # When to use EPA+//!+//! EPA is used when you need detailed contact information for **penetrating shapes**:+//!+//! - **Physics simulation**: Resolving interpenetration between colliding objects+//! - **Contact manifold generation**: Finding contact points and normals for collision response+//! - **Penetration depth queries**: Determining how far apart to move objects to resolve overlap+//!+//! **Key requirement**: Both shapes must implement the [`SupportMap`](crate::shape::SupportMap)+//! trait, which provides support points in any direction.+//!+//! # How EPA works (simplified)+//!+//! 1. **Start with GJK simplex**: Begin with the simplex from GJK that encloses the origin+//! in the Minkowski difference space (the CSO - Configuration Space Obstacle)+//!+//! 2. **Find closest face**: Identify which face of the polytope is closest to the origin+//!+//! 3. **Expand polytope**: Add a new support point in the direction of the closest face's normal+//!+//! 4. **Update and repeat**: Incorporate the new point and find the new closest face+//!+//! 5. **Converge**: Stop when the closest face cannot be expanded further+//! - The distance to this face is the **penetration depth**+//! - The face's normal is the **contact normal**+//! - The closest points on the face map back to **contact points** on the original shapes+//!+//! # Example usage+//!+//! ```+//! # #[cfg(all(feature = "dim3", feature = "f32"))] {+//! use parry3d::query::epa::EPA;+//! use parry3d::query::gjk::VoronoiSimplex;+//! use parry3d::shape::Ball;+//! use parry3d::math::Pose;+//!+//! let ball1 = Ball::new(1.0);+//! let ball2 = Ball::new(1.0);+//! let pos12 = Pose::translation(1.5, 0.0, 0.0); // Overlapping balls+//!+//! // GJK detects penetration, EPA computes contact details+//! let simplex = VoronoiSimplex::new(); // Would be filled by GJK+//! let mut epa = EPA::new();+//!+//! // If GJK detected penetration, EPA can compute:+//! // - Contact points on each shape+//! // - Penetration depth+//! // - Contact normal+//! // if let Some((pt1, pt2, normal)) = epa.closest_points(&pos12, &ball1, &ball2, &simplex) {+//! // println!("Contact normal: {}", normal);+//! // }+//! # }+//! ```+//!+//! # Implementation notes+//!+//! - **Dimension-specific**: EPA has separate implementations for 2D (`epa2`) and 3D (`epa3`)+//! because the polytope expansion differs:+//! - 2D: Expands polygons (edges)+//! - 3D: Expands polyhedra (faces)+//!+//! - **Convergence**: EPA uses tolerances to determine when to stop expanding. In rare cases+//! with degenerate geometry or numerical precision issues, it may return `None` if it cannot+//! converge to a solution.+//!+//! - **Performance**: EPA is more expensive than GJK, which is why it's only used when shapes+//! are actually penetrating. For separated shapes, GJK alone is sufficient.+//!+#[cfg(feature = "dim2")]+pub use self::epa2::EPA;+#[cfg(feature = "dim3")]+pub use self::epa3::EPA;++#[cfg(feature = "dim2")]+pub mod epa2;+#[cfg(feature = "dim3")]+pub mod epa3;diff --git a/renderer/third_party/parry3d/src/query/error.rs b/renderer/third_party/parry3d/src/query/error.rsnew file mode 100644index 0000000..e4b17b1--- /dev/null+++ b/renderer/third_party/parry3d/src/query/error.rs@@ -0,0 +1,156 @@+use core::fmt;++/// Error indicating that a geometric query is not supported between certain shape combinations.+///+/// Many geometric queries in Parry (like distance calculation, contact detection, or time-of-impact)+/// are implemented using specialized algorithms for specific pairs of shapes. When you attempt a+/// query between two shapes for which no implementation exists, this error is returned.+///+/// # When This Error Occurs+///+/// This error typically occurs in two situations:+///+/// 1. **Missing Implementation**: The query has not been implemented for the specific pair of shapes.+/// For example, some advanced queries might not support all combinations of composite shapes.+///+/// 2. **Complex Shape Combinations**: Certain queries involving composite shapes (like [`Compound`],+/// [`TriMesh`], or [`HeightField`]) may not be fully supported, especially for less common operations.+///+/// # Common Scenarios+///+/// - Computing contact manifolds between two custom shapes that don't have a specialized implementation+/// - Using non-linear shape casting with certain composite shapes+/// - Querying distance between shapes that require more complex algorithms not yet implemented+///+/// # How to Handle This Error+///+/// When you encounter this error, you have several options:+///+/// ## 1. Use a Different Query Type+///+/// Try a more basic query that's more widely supported:+///+/// ```no_run+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::query::{contact, distance};+/// # use parry3d::shape::{Ball, Cuboid};+/// # use parry3d::math::{Pose, Vector};+/// # let shape1 = Ball::new(1.0);+/// # let shape2 = Cuboid::new(Vector::splat(1.0));+/// # let pos1 = Pose::identity();+/// # let pos2 = Pose::identity();+/// // If contact manifolds are unsupported, try basic contact:+/// if let Ok(contact) = contact(&pos1, &shape1, &pos2, &shape2, 0.0) {+/// // Process the contact point+/// }+///+/// // Or try distance computation:+/// let dist = distance(&pos1, &shape1, &pos2, &shape2);+/// # }+/// ```+///+/// ## 2. Decompose Complex Shapes+///+/// Break down complex shapes into simpler components:+///+/// ```no_run+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::shape::{TriMesh, Ball, Compound, SharedShape};+/// # use parry3d::query::distance;+/// # use parry3d::math::{Pose, Vector};+/// # let mesh = TriMesh::new(vec![], vec![]).unwrap();+/// # let ball = Ball::new(1.0);+/// # let pos1 = Pose::identity();+/// # let pos2 = Pose::identity();+/// // Instead of querying against a complex mesh directly,+/// // iterate through its triangles:+/// for triangle in mesh.triangles() {+/// let dist = distance(&pos1, &triangle, &pos2, &ball);+/// // Process each triangle-ball pair+/// }+/// # }+/// ```+///+/// ## 3. Use the BVH for Composite Shapes+///+/// For shapes with BVH acceleration structures (like [`TriMesh`]), use specialized traversal methods:+///+/// ```no_run+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::shape::TriMesh;+/// # use parry3d::bounding_volume::Aabb;+/// # use parry3d::math::Vector;+/// # let mesh = TriMesh::new(vec![Vector::ZERO], vec![[0, 0, 0]]).unwrap();+/// # let query_aabb = Aabb::new(Vector::ZERO, Vector::ZERO);+/// // Use BVH queries instead of direct shape queries:+/// for leaf_id in mesh.bvh().intersect_aabb(&query_aabb) {+/// let triangle = mesh.triangle(leaf_id);+/// // Process the triangle+/// }+/// # }+/// ```+///+/// ## 4. Implement a Custom Query Dispatcher+///+/// For advanced use cases, implement the [`QueryDispatcher`] trait to add support for your specific+/// shape combinations:+///+/// ```no_run+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::query::{QueryDispatcher, DefaultQueryDispatcher};+/// # use parry3d::shape::Shape;+/// # use parry3d::math::{Pose, Real};+/// struct MyQueryDispatcher {+/// default: DefaultQueryDispatcher,+/// }+///+/// // Implement QueryDispatcher and add your custom query implementations+/// # }+/// ```+///+/// # Example: Catching and Handling the Error+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::query::{contact, Unsupported};+/// # use parry3d::shape::{Ball, Cuboid};+/// # use parry3d::math::{Pose, Vector};+/// let ball = Ball::new(1.0);+/// let cuboid = Cuboid::new(Vector::splat(1.0));+/// let pos1 = Pose::identity();+/// let pos2 = Pose::identity();+///+/// // Most queries return Result<T, Unsupported>+/// match contact(&pos1, &ball, &pos2, &cuboid, 0.0) {+/// Ok(Some(contact)) => {+/// // Query succeeded and found a contact+/// println!("Contact found at distance: {}", contact.dist);+/// }+/// Ok(None) => {+/// // Query succeeded but no contact found+/// println!("No contact");+/// }+/// Err(Unsupported) => {+/// // Query not supported for this shape combination+/// println!("This query is not supported between these shapes");+/// // Fall back to an alternative approach+/// }+/// }+/// # }+/// ```+///+/// [`Compound`]: crate::shape::Compound+/// [`TriMesh`]: crate::shape::TriMesh+/// [`HeightField`]: crate::shape::HeightField+/// [`QueryDispatcher`]: crate::query::QueryDispatcher+#[derive(Debug, Copy, Clone, Eq, PartialEq)]+pub struct Unsupported;++impl fmt::Display for Unsupported {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.pad("query not supported between these shapes")+ }+}++#[cfg(feature = "alloc")]+impl core::error::Error for Unsupported {}diff --git a/renderer/third_party/parry3d/src/query/gjk/cso_point.rs b/renderer/third_party/parry3d/src/query/gjk/cso_point.rsnew file mode 100644index 0000000..1f294b9--- /dev/null+++ b/renderer/third_party/parry3d/src/query/gjk/cso_point.rs@@ -0,0 +1,99 @@+use crate::math::{Pose, Vector};+use crate::shape::SupportMap;+use core::ops::Sub;++/// A point of a Configuration-Space Obstacle.+///+/// A Configuration-Space Obstacle (CSO) is the result of the+/// Minkowski Difference of two solids. In other words, each of its+/// points correspond to the difference of two point, each belonging+/// to a different solid.+#[derive(Copy, Clone, Debug, PartialEq)]+pub struct CsoPoint {+ /// The point on the CSO. This is equal to `self.orig1 - self.orig2`, unless this CsoPoint+ /// has been translated with self.translate.+ pub point: Vector,+ /// The original point on the first shape used to compute `self.point`.+ pub orig1: Vector,+ /// The original point on the second shape used to compute `self.point`.+ pub orig2: Vector,+}++impl CsoPoint {+ /// A CSO point where all components are zero.+ pub const ZERO: Self = Self {+ point: Vector::ZERO,+ orig1: Vector::ZERO,+ orig2: Vector::ZERO,+ };++ /// Initializes a CSO point with `orig1 - orig2`.+ pub fn new(orig1: Vector, orig2: Vector) -> Self {+ let point = orig1 - orig2;+ Self::new_with_point(point, orig1, orig2)+ }++ /// Initializes a CSO point with all information provided.+ ///+ /// It is assumed, but not checked, that `point == orig1 - orig2`.+ pub fn new_with_point(point: Vector, orig1: Vector, orig2: Vector) -> Self {+ CsoPoint {+ point,+ orig1,+ orig2,+ }+ }++ /// Initializes a CSO point where both original points are equal.+ pub fn single_point(point: Vector) -> Self {+ Self::new_with_point(point, point, Vector::ZERO)+ }++ /// CSO point where all components are set to zero.+ pub fn origin() -> Self {+ CsoPoint::new(Vector::ZERO, Vector::ZERO)+ }++ /// Computes the support point of the CSO of `g1` and `g2` toward the unit direction `dir`.+ pub fn from_shapes_toward<G1, G2>(pos12: &Pose, g1: &G1, g2: &G2, dir: Vector) -> Self+ where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+ {+ let sp1 = g1.local_support_point_toward(dir);+ let sp2 = g2.support_point_toward(pos12, -dir);++ CsoPoint::new(sp1, sp2)+ }++ /// Computes the support point of the CSO of `g1` and `g2` toward the direction `dir`.+ pub fn from_shapes<G1, G2>(pos12: &Pose, g1: &G1, g2: &G2, dir: Vector) -> Self+ where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+ {+ let sp1 = g1.local_support_point(dir);+ let sp2 = g2.support_point(pos12, -dir);++ CsoPoint::new(sp1, sp2)+ }++ /// Translate the CSO point.+ pub fn translate(&self, dir: Vector) -> Self {+ CsoPoint::new_with_point(self.point + dir, self.orig1, self.orig2)+ }++ /// Translate in-place the CSO point.+ pub fn translate_mut(&mut self, dir: Vector) {+ self.point += dir;+ }+}++impl Sub<CsoPoint> for CsoPoint {+ type Output = Vector;++ #[inline]+ fn sub(self, rhs: CsoPoint) -> Vector {+ self.point - rhs.point+ }+}diff --git a/renderer/third_party/parry3d/src/query/gjk/gjk.rs b/renderer/third_party/parry3d/src/query/gjk/gjk.rsnew file mode 100644index 0000000..56f4cae--- /dev/null+++ b/renderer/third_party/parry3d/src/query/gjk/gjk.rs@@ -0,0 +1,893 @@+//! The Gilbert-Johnson-Keerthi distance algorithm.+//!+//! # What is GJK?+//!+//! The **Gilbert-Johnson-Keerthi (GJK)** algorithm is a fundamental geometric algorithm used+//! to compute the distance between two convex shapes. It's one of the most important algorithms+//! in collision detection and is used extensively in physics engines, robotics, and computer graphics.+//!+//! ## How GJK Works (Simplified)+//!+//! GJK works by operating on the **Minkowski difference** (also called Configuration Space Obstacle or CSO)+//! of two shapes. Instead of directly comparing the shapes, GJK:+//!+//! 1. Constructs a simplex (triangle in 2D, tetrahedron in 3D) within the Minkowski difference+//! 2. Iteratively refines this simplex to find the point closest to the origin+//! 3. The distance from the origin to this closest point equals the distance between the shapes+//!+//! If the origin is **inside** the Minkowski difference, the shapes are intersecting.+//! If the origin is **outside**, the distance to the closest point gives the separation distance.+//!+//! ## When is GJK Used?+//!+//! GJK is used whenever you need to:+//! - **Check if two convex shapes intersect** (collision detection)+//! - **Find the minimum distance** between two convex shapes+//! - **Compute closest points** on two shapes+//! - **Cast a shape along a direction** to find the time of impact (continuous collision detection)+//!+//! ## Key Advantages of GJK+//!+//! - Works with **any convex shape** that can provide a support function+//! - Does **not require the full geometry** of the shapes (only support points)+//! - Very **fast convergence** in most practical cases+//! - Forms the basis for many collision detection systems+//!+//! ## Limitations+//!+//! - Only works with **convex shapes** (use convex decomposition for concave shapes)+//! - When shapes are penetrating, GJK can only detect intersection but not penetration depth+//! (use EPA - Expanding Polytope Algorithm - for penetration depth)+//!+//! # Main Functions in This Module+//!+//! - [`closest_points`] - The core GJK algorithm for finding distance and closest points+//! - [`project_origin`] - Projects the origin onto a shape's boundary+//! - [`cast_local_ray`] - Casts a ray against a shape (used for raycasting)+//! - [`directional_distance`] - Computes how far a shape can move before touching another+//!+//! # Example+//!+//! See individual function documentation for usage examples.++use crate::math::ComplexField;++use crate::query::gjk::{ConstantOrigin, CsoPoint, VoronoiSimplex};+use crate::shape::SupportMap;+// use query::Proximity;+use crate::math::{Pose, Real, Vector, DIM};+use crate::query::{self, Ray};++use num::{Bounded, Zero};++/// Results of the GJK algorithm.+///+/// This enum represents the different outcomes when running the GJK algorithm to find+/// the distance between two shapes. The result depends on whether the shapes are intersecting,+/// how far apart they are, and what information was requested.+///+/// # Understanding the Results+///+/// - **Intersection**: The shapes are overlapping. The origin lies inside the Minkowski difference.+/// - **ClosestPoints**: The exact closest points on both shapes were computed, along with the+/// separation direction.+/// - **Proximity**: The shapes are close but not intersecting. Only an approximate separation+/// direction is provided (used when exact distance computation is not needed).+/// - **NoIntersection**: The shapes are too far apart (beyond the specified `max_dist` threshold).+///+/// # Coordinate Spaces+///+/// All points and vectors in this result are expressed in the **local-space of the first shape**+/// (the shape passed as `g1` to the GJK functions). This is important when working with+/// transformed shapes.+#[derive(Clone, Debug, PartialEq)]+pub enum GJKResult {+ /// The shapes are intersecting (overlapping).+ ///+ /// This means the origin is inside the Minkowski difference of the two shapes.+ /// GJK cannot compute penetration depth; use the EPA (Expanding Polytope Algorithm)+ /// for that purpose.+ Intersection,++ /// The closest points on both shapes were found.+ ///+ /// # Fields+ ///+ /// - First `Vector`: The closest point on the first shape (in local-space of shape 1)+ /// - Second `Vector`: The closest point on the second shape (in local-space of shape 1)+ /// - `Vector`: The unit direction vector from shape 1 to shape 2 (separation axis)+ ///+ /// This variant is returned when `exact_dist` is `true` in the GJK algorithm and the+ /// shapes are not intersecting.+ ClosestPoints(Vector, Vector, Vector),++ /// The shapes are in proximity (close but not intersecting).+ ///+ /// # Fields+ ///+ /// - `Vector`: An approximate separation axis (unit direction from shape 1 to shape 2)+ ///+ /// This variant is returned when `exact_dist` is `false` and the algorithm determines+ /// the shapes are close but not intersecting. It's faster than computing exact closest+ /// points when you only need to know if shapes are nearby.+ Proximity(Vector),++ /// The shapes are too far apart.+ ///+ /// # Fields+ ///+ /// - `Vector`: A separation axis (unit direction from shape 1 to shape 2)+ ///+ /// This variant is returned when the minimum distance between the shapes exceeds+ /// the `max_dist` parameter passed to the GJK algorithm.+ NoIntersection(Vector),+}++/// The absolute tolerance used by the GJK algorithm.+///+/// This function returns the epsilon (tolerance) value that GJK uses to determine when+/// it has converged to a solution. The tolerance affects:+///+/// - When two points are considered "close enough" to be the same+/// - When the algorithm decides it has found the minimum distance+/// - Numerical stability in edge cases+///+/// The returned value is 10 times the default machine epsilon for the current floating-point+/// precision (f32 or f64). This provides a balance between accuracy and robustness.+///+/// # Returns+///+/// The absolute tolerance value (10 * DEFAULT_EPSILON)+pub fn eps_tol() -> Real {+ let _eps = crate::math::DEFAULT_EPSILON;+ _eps * 10.0+}++/// Projects the origin onto the boundary of the given shape.+///+/// This function finds the point on the shape's surface that is closest to the origin (0, 0)+/// in 2D or (0, 0, 0) in 3D. This is useful for distance queries and collision detection+/// when you need to know the closest point on a shape.+///+/// # Important: Origin Must Be Outside+///+/// **The origin is assumed to be outside of the shape.** If the origin is inside the shape,+/// this function returns `None`. For penetrating cases, use the EPA (Expanding Polytope Algorithm)+/// instead.+///+/// # Parameters+///+/// - `m`: The position and orientation (isometry) of the shape in world space+/// - `g`: The shape to project onto (must implement `SupportMap`)+/// - `simplex`: A reusable simplex structure for the GJK algorithm. Initialize with+/// `VoronoiSimplex::new()` before first use.+///+/// # Returns+///+/// - `Some(Vector)`: The closest point on the shape's boundary, in the shape's **local space**+/// - `None`: If the origin is inside the shape+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Ball;+/// use parry3d::query::gjk::{project_origin, VoronoiSimplex};+/// use parry3d::math::Pose;+///+/// // Create a ball at position (5, 0, 0)+/// let ball = Ball::new(1.0);+/// let position = Pose::translation(5.0, 0.0, 0.0);+///+/// // Project the origin onto the ball+/// let mut simplex = VoronoiSimplex::new();+/// if let Some(closest_point) = project_origin(&position, &ball, &mut simplex) {+/// println!("Closest point on ball: {:?}", closest_point);+/// // The point will be approximately (-1, 0, 0) in local space+/// // which is the left side of the ball facing the origin+/// }+/// # }+/// ```+///+/// # Performance Note+///+/// The `simplex` parameter can be reused across multiple calls to avoid allocations.+/// This is particularly beneficial when performing many projection queries.+pub fn project_origin<G: ?Sized + SupportMap>(+ m: &Pose,+ g: &G,+ simplex: &mut VoronoiSimplex,+) -> Option<Vector> {+ match closest_points(+ &m.inverse(),+ g,+ &ConstantOrigin,+ Real::max_value(),+ true,+ simplex,+ ) {+ GJKResult::Intersection => None,+ GJKResult::ClosestPoints(p, _, _) => Some(p),+ _ => unreachable!(),+ }+}++/*+ * Separating Axis GJK+ */+/// Computes the closest points between two shapes using the GJK algorithm.+///+/// This is the **core function** of the GJK implementation in Parry. It can compute:+/// - Whether two shapes are intersecting+/// - The distance between two separated shapes+/// - The closest points on both shapes+/// - An approximate separation axis when exact distance isn't needed+///+/// # How It Works+///+/// The algorithm operates on the Minkowski difference (CSO) of the two shapes and iteratively+/// builds a simplex that approximates the point closest to the origin. The algorithm terminates+/// when:+/// - The shapes are proven to intersect (origin is inside the CSO)+/// - The minimum distance is found within the tolerance+/// - The shapes are proven to be farther than `max_dist` apart+///+/// # Parameters+///+/// - `pos12`: The relative position of shape 2 with respect to shape 1. This is the isometry+/// that transforms from shape 1's space to shape 2's space.+/// - `g1`: The first shape (must implement `SupportMap`)+/// - `g2`: The second shape (must implement `SupportMap`)+/// - `max_dist`: Maximum distance to check. If shapes are farther than this, the algorithm+/// returns `GJKResult::NoIntersection` early. Use `Real::max_value()` to disable this check.+/// - `exact_dist`: Whether to compute exact closest points:+/// - `true`: Computes exact distance and returns `GJKResult::ClosestPoints`+/// - `false`: May return `GJKResult::Proximity` with only an approximate separation axis,+/// which is faster when you only need to know if shapes are nearby+/// - `simplex`: A reusable simplex structure. Initialize with `VoronoiSimplex::new()` before+/// first use. Can be reused across calls for better performance.+///+/// # Returns+///+/// Returns a [`GJKResult`] which can be:+/// - `Intersection`: The shapes are overlapping+/// - `ClosestPoints(p1, p2, normal)`: The closest points on each shape (when `exact_dist` is true)+/// - `Proximity(axis)`: An approximate separation axis (when `exact_dist` is false)+/// - `NoIntersection(axis)`: The shapes are farther than `max_dist` apart+///+/// # Example: Basic Distance Query+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Ball, Cuboid};+/// use parry3d::query::gjk::{closest_points, VoronoiSimplex};+/// use parry3d::math::{Pose, Vector};+///+/// // Create two shapes+/// let ball = Ball::new(1.0);+/// let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+///+/// // Position them in space+/// let pos1 = Pose::translation(0.0, 0.0, 0.0);+/// let pos2 = Pose::translation(5.0, 0.0, 0.0);+///+/// // Compute relative position+/// let pos12 = pos1.inv_mul(&pos2);+///+/// // Run GJK+/// let mut simplex = VoronoiSimplex::new();+/// let result = closest_points(+/// &pos12,+/// &ball,+/// &cuboid,+/// f32::MAX, // No distance limit+/// true, // Compute exact distance+/// &mut simplex,+/// );+///+/// match result {+/// parry3d::query::gjk::GJKResult::ClosestPoints(p1, p2, normal) => {+/// println!("Closest point on ball: {:?}", p1);+/// println!("Closest point on cuboid: {:?}", p2);+/// println!("Separation direction: {:?}", normal);+/// let distance = (p2 - p1).length();+/// println!("Distance: {}", distance);+/// }+/// parry3d::query::gjk::GJKResult::Intersection => {+/// println!("Shapes are intersecting!");+/// }+/// _ => {}+/// }+/// # }+/// ```+///+/// # Example: Fast Proximity Check+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Ball;+/// use parry3d::query::gjk::{closest_points, VoronoiSimplex};+/// use parry3d::math::Pose;+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+/// let pos12 = Pose::translation(3.0, 0.0, 0.0);+///+/// let mut simplex = VoronoiSimplex::new();+/// let result = closest_points(+/// &pos12,+/// &ball1,+/// &ball2,+/// 5.0, // Only check up to distance 5.0+/// false, // Don't compute exact distance+/// &mut simplex,+/// );+///+/// match result {+/// parry3d::query::gjk::GJKResult::Proximity(_axis) => {+/// println!("Shapes are close but not intersecting");+/// }+/// parry3d::query::gjk::GJKResult::Intersection => {+/// println!("Shapes are intersecting");+/// }+/// parry3d::query::gjk::GJKResult::NoIntersection(_) => {+/// println!("Shapes are too far apart (> 5.0 units)");+/// }+/// _ => {}+/// }+/// # }+/// ```+///+/// # Performance Tips+///+/// 1. Reuse the `simplex` across multiple queries to avoid allocations+/// 2. Set `exact_dist` to `false` when you only need proximity information+/// 3. Use a reasonable `max_dist` to allow early termination+/// 4. GJK converges fastest when shapes are well-separated+///+/// # Notes+///+/// - All returned points and vectors are in the local-space of shape 1+/// - The algorithm typically converges in 5-10 iterations for well-separated shapes+/// - Maximum iteration count is 100 to prevent infinite loops+pub fn closest_points<G1, G2>(+ pos12: &Pose,+ g1: &G1,+ g2: &G2,+ max_dist: Real,+ exact_dist: bool,+ simplex: &mut VoronoiSimplex,+) -> GJKResult+where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+{+ let _eps = crate::math::DEFAULT_EPSILON;+ let _eps_tol: Real = eps_tol();+ let _eps_rel: Real = <Real as ComplexField>::sqrt(_eps_tol);++ // TODO: reset the simplex if it is empty?+ let mut proj = simplex.project_origin_and_reduce();++ let mut old_dir;++ if let Some(proj_dir) = proj.try_normalize() {+ old_dir = -proj_dir;+ } else {+ return GJKResult::Intersection;+ }++ let mut max_bound = Real::max_value();+ let mut dir;+ let mut niter = 0;+ // Tightest lower bound on the distance from the origin to the CSO: `min_bound`+ // maximized over the directions probed. Its sign classifies the origin: `> 0`+ // means separation, `~ 0` puts it on the CSO boundary (touching),+ // `< 0` bounds the penetration depth.+ let mut best_min_bound = -Real::max_value();+ // Largest CSO support magnitude seen, used to scale the tolerance below.+ let mut support_scale: Real = 0.0;+ let mut nb_perturbs = 0usize;+ const MAX_PERTURBATIONS: usize = 2 * DIM;++ loop {+ let old_max_bound = max_bound;++ let neg_proj_coords = -proj;+ let (normalized, dist) = neg_proj_coords.normalize_and_length();+ if dist > _eps_tol {+ dir = normalized;+ max_bound = dist;+ } else {+ // The origin is on the simplex.+ return GJKResult::Intersection;+ }++ if max_bound >= old_max_bound {+ if best_min_bound > 0.0 {+ // Separation certified: the converged witnesses are the answer.+ if exact_dist {+ let (p1, p2) = result(simplex, true);+ return GJKResult::ClosestPoints(p1, p2, old_dir); // upper bounds inconsistencies+ } else {+ return GJKResult::Proximity(old_dir);+ }+ } else if exact_dist && best_min_bound >= -_eps_rel * support_scale {+ // Origin on the CSO boundary: the pair is touching, so the witnesses+ // describe the contact.+ let (p1, p2) = result(simplex, true);+ return GJKResult::ClosestPoints(p1, p2, old_dir);+ } else if nb_perturbs < MAX_PERTURBATIONS {+ // Try slight perturbations to avoid getting stuck into a numerical ambiguity.+ nb_perturbs += 1;+ dir = perturbed_dir(dir, nb_perturbs);+ } else {+ // The CSO reaches past the origin in every direction probed.+ return GJKResult::Intersection;+ }+ }++ let cso_point = CsoPoint::from_shapes(pos12, g1, g2, dir);+ let min_bound = -dir.dot(cso_point.point);++ assert!(min_bound.is_finite());++ best_min_bound = best_min_bound.max(min_bound);+ support_scale = support_scale.max(cso_point.point.length());++ if min_bound > max_dist {+ return GJKResult::NoIntersection(dir);+ } else if !exact_dist && min_bound > 0.0 && max_bound <= max_dist {+ return GJKResult::Proximity(old_dir);+ } else if max_bound - min_bound <= _eps_rel * max_bound {+ if exact_dist {+ let (p1, p2) = result(simplex, false);+ return GJKResult::ClosestPoints(p1, p2, dir); // the distance found has a good enough precision+ } else {+ return GJKResult::Proximity(dir);+ }+ }++ if !simplex.add_point(cso_point) {+ // See the stagnation branch above for how `best_min_bound` classifies a stall.+ if best_min_bound > 0.0 {+ if exact_dist {+ let (p1, p2) = result(simplex, false);+ return GJKResult::ClosestPoints(p1, p2, dir);+ } else {+ return GJKResult::Proximity(dir);+ }+ } else if exact_dist && best_min_bound >= -_eps_rel * support_scale {+ let (p1, p2) = result(simplex, false);+ return GJKResult::ClosestPoints(p1, p2, dir);+ } else if nb_perturbs < MAX_PERTURBATIONS {+ // The duplicate support point cannot enrich the simplex; jump back to+ // the top of the loop where the stagnation branch will perturb `dir`.+ continue;+ } else {+ return GJKResult::Intersection;+ }+ }++ old_dir = dir;+ proj = simplex.project_origin_and_reduce();++ if simplex.dimension() == DIM {+ if min_bound >= _eps_tol {+ if exact_dist {+ let (p1, p2) = result(simplex, true);+ return GJKResult::ClosestPoints(p1, p2, old_dir);+ } else {+ // NOTE: previous implementation used old_proj here.+ return GJKResult::Proximity(old_dir);+ }+ } else {+ return GJKResult::Intersection; // Vector inside of the cso.+ }+ }+ niter += 1;++ if niter == 100 {+ return GJKResult::NoIntersection(Vector::X);+ }+ }+}++/// Casts a ray against a shape using the GJK algorithm.+///+/// This function performs raycasting by testing a ray against a shape to find if and where+/// the ray intersects the shape. It uses a specialized version of GJK that works with rays.+///+/// # What is Raycasting?+///+/// Raycasting shoots a ray (infinite line starting from a point in a direction) and finds+/// where it first hits a shape. This is essential for:+/// - Mouse picking in 3D scenes+/// - Line-of-sight checks+/// - Projectile collision detection+/// - Laser/scanner simulations+///+/// # Parameters+///+/// - `shape`: The shape to cast the ray against (must implement `SupportMap`)+/// - `simplex`: A reusable simplex structure. Initialize with `VoronoiSimplex::new()`.+/// - `ray`: The ray to cast, containing an origin point and direction vector+/// - `max_time_of_impact`: Maximum distance along the ray to check. The ray will be treated+/// as a line segment of length `max_time_of_impact * ray.dir.length()`.+///+/// # Returns+///+/// - `Some((toi, normal))`: If the ray hits the shape+/// - `toi`: Time of impact - multiply by `ray.dir.length()` to get the actual distance+/// - `normal`: Surface normal at the hit point+/// - `None`: If the ray doesn't hit the shape within the maximum distance+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Ball;+/// use parry3d::query::{Ray, gjk::{cast_local_ray, VoronoiSimplex}};+/// use parry3d::math::Vector;+///+/// // Create a ball at the origin+/// let ball = Ball::new(1.0);+///+/// // Create a ray starting at (0, 0, -5) pointing toward +Z+/// let ray = Ray::new(+/// Vector::new(0.0, 0.0, -5.0),+/// Vector::new(0.0, 0.0, 1.0)+/// );+///+/// let mut simplex = VoronoiSimplex::new();+/// if let Some((toi, normal)) = cast_local_ray(&ball, &mut simplex, &ray, f32::MAX) {+/// let hit_point = ray.point_at(toi);+/// println!("Ray hit at: {:?}", hit_point);+/// println!("Surface normal: {:?}", normal);+/// println!("Distance: {}", toi);+/// } else {+/// println!("Ray missed the shape");+/// }+/// # }+/// ```+///+/// # Notes+///+/// - The ray is specified in the local-space of the shape+/// - The returned normal points outward from the shape+/// - For normalized ray directions, `toi` equals the distance to the hit point+/// - This function is typically called by higher-level raycasting APIs+pub fn cast_local_ray<G: ?Sized + SupportMap>(+ shape: &G,+ simplex: &mut VoronoiSimplex,+ ray: &Ray,+ max_time_of_impact: Real,+) -> Option<(Real, Vector)> {+ let g2 = ConstantOrigin;+ minkowski_ray_cast(+ &Pose::IDENTITY,+ shape,+ &g2,+ ray,+ max_time_of_impact,+ simplex,+ )+}++/// Computes how far a shape can move in a direction before touching another shape.+///+/// This function answers the question: "If I move shape 1 along this direction, how far+/// can it travel before it touches shape 2?" This is useful for:+/// - Continuous collision detection (CCD)+/// - Movement planning and obstacle avoidance+/// - Computing time-of-impact for moving objects+/// - Safe navigation distances+///+/// # How It Works+///+/// The function casts shape 1 along the given direction vector and finds the first point+/// where it would contact shape 2. It returns:+/// - The distance that can be traveled+/// - The contact normal at the point of first contact+/// - The witness points (closest points) on both shapes at contact+///+/// # Parameters+///+/// - `pos12`: The relative position of shape 2 with respect to shape 1 (isometry from+/// shape 1's space to shape 2's space)+/// - `g1`: The first shape being moved (must implement `SupportMap`)+/// - `g2`: The second shape (static target, must implement `SupportMap`)+/// - `dir`: The direction vector to move shape 1 in (in local-space of shape 1)+/// - `simplex`: A reusable simplex structure. Initialize with `VoronoiSimplex::new()`.+///+/// # Returns+///+/// - `Some((distance, normal, witness1, witness2))`: If contact would occur+/// - `distance`: How far shape 1 can travel before touching shape 2+/// - `normal`: The contact normal at the point of first contact+/// - `witness1`: The contact point on shape 1 (in local-space of shape 1)+/// - `witness2`: The contact point on shape 2 (in local-space of shape 1)+/// - `None`: If no contact would occur (shapes don't intersect along this direction)+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Ball;+/// use parry3d::query::gjk::{directional_distance, VoronoiSimplex};+/// use parry3d::math::{Pose, Vector};+///+/// // Two balls: one at origin, one at (10, 0, 0)+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+/// let pos12 = Pose::translation(10.0, 0.0, 0.0);+///+/// // Move ball1 toward ball2 along the +X axis+/// let direction = Vector::new(1.0, 0.0, 0.0);+///+/// let mut simplex = VoronoiSimplex::new();+/// if let Some((distance, normal, w1, w2)) = directional_distance(+/// &pos12,+/// &ball1,+/// &ball2,+/// direction,+/// &mut simplex+/// ) {+/// println!("Ball1 can move {} units before contact", distance);+/// println!("Contact normal: {:?}", normal);+/// println!("Contact point on ball1: {:?}", w1);+/// println!("Contact point on ball2: {:?}", w2);+/// // Expected: distance ≈ 8.0 (10.0 - 1.0 - 1.0)+/// }+/// # }+/// ```+///+/// # Use Cases+///+/// **1. Continuous Collision Detection:**+/// ```ignore+/// let movement_dir = velocity * time_step;+/// if let Some((toi, normal, _, _)) = directional_distance(...) {+/// if toi < 1.0 {+/// // Collision will occur during this timestep+/// let collision_time = toi * time_step;+/// }+/// }+/// ```+///+/// **2. Safe Movement Distance:**+/// ```ignore+/// let desired_movement = Vector::new(5.0, 0.0, 0.0);+/// if let Some((max_safe_dist, _, _, _)) = directional_distance(...) {+/// let actual_movement = desired_movement.normalize() * max_safe_dist.min(5.0);+/// }+/// ```+///+/// # Notes+///+/// - All inputs and outputs are in the local-space of shape 1+/// - If the shapes are already intersecting, the returned distance is 0.0 and witness+/// points are undefined (set to origin)+/// - The direction vector does not need to be normalized+/// - This function internally uses GJK raycasting on the Minkowski difference+pub fn directional_distance<G1, G2>(+ pos12: &Pose,+ g1: &G1,+ g2: &G2,+ dir: Vector,+ simplex: &mut VoronoiSimplex,+) -> Option<(Real, Vector, Vector, Vector)>+where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+{+ let ray = Ray::new(Vector::ZERO, dir);+ minkowski_ray_cast(pos12, g1, g2, &ray, Real::max_value(), simplex).map(+ |(time_of_impact, normal)| {+ let witnesses = if !time_of_impact.is_zero() {+ result(simplex, simplex.dimension() == DIM)+ } else {+ // If there is penetration, the witness points+ // are undefined.+ (Vector::ZERO, Vector::ZERO)+ };++ (time_of_impact, normal, witnesses.0, witnesses.1)+ },+ )+}++// Ray-cast on the Minkowski Difference `g1 - pos12 * g2`.+fn minkowski_ray_cast<G1, G2>(+ pos12: &Pose,+ g1: &G1,+ g2: &G2,+ ray: &Ray,+ max_time_of_impact: Real,+ simplex: &mut VoronoiSimplex,+) -> Option<(Real, Vector)>+where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+{+ let _eps = crate::math::DEFAULT_EPSILON;+ let _eps_tol: Real = eps_tol();+ let _eps_rel: Real = <Real as ComplexField>::sqrt(_eps_tol);++ let ray_length = ray.dir.length();++ if relative_eq!(ray_length, 0.0) {+ return None;+ }++ let mut ltoi = 0.0;+ let mut curr_ray = Ray::new(ray.origin, ray.dir / ray_length);+ let dir = -curr_ray.dir;+ let mut ldir = dir;++ // Initialize the simplex.+ let support_point = CsoPoint::from_shapes(pos12, g1, g2, dir);+ simplex.reset(support_point.translate(-curr_ray.origin));++ // TODO: reset the simplex if it is empty?+ let mut proj = simplex.project_origin_and_reduce();+ let mut max_bound = Real::max_value();+ let mut dir;+ let mut niter = 0;+ let mut last_chance = false;++ loop {+ let old_max_bound = max_bound;++ let neg_proj_coords = -proj;+ let (normalized, dist) = neg_proj_coords.normalize_and_length();+ if dist > _eps_tol {+ dir = normalized;+ max_bound = dist;+ } else {+ return Some((ltoi / ray_length, ldir));+ }++ let support_point = if max_bound >= old_max_bound {+ // Upper bounds inconsistencies. Keep the projection as a valid support point+ // for the last-chance path below.+ last_chance = true;+ CsoPoint::single_point(proj + curr_ray.origin)+ } else {+ CsoPoint::from_shapes(pos12, g1, g2, dir)+ };++ if last_chance && ltoi > 0.0 {+ // The witnesses stay precise when large support coordinates stop the upper+ // bound from decreasing, so refine the lower bound with their separation+ // along the cast direction before accepting the impact.+ let (witness1, witness2) = result(simplex, simplex.dimension() == DIM);+ let witness_ltoi = (witness1 - witness2 - ray.origin).dot(curr_ray.dir);+ if witness_ltoi.is_finite() && witness_ltoi > ltoi {+ ltoi = witness_ltoi;++ if ltoi / ray_length > max_time_of_impact {+ return None;+ }+ }++ return Some((ltoi / ray_length, ldir));+ }++ // Clip the ray on the support halfspace (None <=> t < 0)+ // The configurations are:+ // dir.dot(curr_ray.dir) | t | Action+ // −−−−−−−−−−−−−−−−−−−−-----+−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ // < 0 | < 0 | Continue.+ // < 0 | > 0 | New lower bound, move the origin.+ // > 0 | < 0 | Miss. No intersection.+ // > 0 | > 0 | New higher bound.+ match query::details::ray_toi_with_halfspace(support_point.point, dir, &curr_ray) {+ Some(t) => {+ if dir.dot(curr_ray.dir) < 0.0 && t > 0.0 {+ // new lower bound+ ldir = dir;+ ltoi += t;++ // NOTE: we divide by ray_length instead of doing max_time_of_impact * ray_length+ // because the multiplication may cause an overflow if max_time_of_impact is set+ // to Real::max_value() by users that want to have an infinite ray.+ if ltoi / ray_length > max_time_of_impact {+ return None;+ }++ let shift = curr_ray.dir * t;+ curr_ray.origin += shift;+ max_bound = Real::max_value();+ simplex.modify_pnts(&|pt| pt.translate_mut(-shift));+ last_chance = false;+ }+ }+ None => {+ if dir.dot(curr_ray.dir) > _eps_tol {+ // miss+ return None;+ }+ }+ }++ if last_chance {+ return None;+ }++ let min_bound = -dir.dot(support_point.point - curr_ray.origin);++ assert!(min_bound.is_finite());++ if max_bound - min_bound <= _eps_rel * max_bound {+ // This is needed when using fixed-points to avoid missing+ // some castes.+ // TODO: I feel like we should always return `Some` in+ // this case, even with floating-point numbers. Though it+ // has not been sufficiently tested with floats yet to be sure.+ if cfg!(feature = "improved_fixed_point_support") {+ return Some((ltoi / ray_length, ldir));+ } else {+ return None;+ }+ }++ let _ = simplex.add_point(support_point.translate(-curr_ray.origin));+ proj = simplex.project_origin_and_reduce();++ if simplex.dimension() == DIM {+ // `min_bound` accumulates rounding errors proportional to the magnitude of the+ // support coordinates, so we scale the tolerance accordingly.+ let scale = support_point.point.length().max(curr_ray.origin.length());+ if min_bound >= _eps_tol * scale.max(1.0) {+ return None;+ } else {+ return Some((ltoi / ray_length, ldir)); // Vector inside of the cso.+ }+ }++ niter += 1;+ if niter == 100 {+ return None;+ }+ }+}++// Deterministically perturbs the unit direction `dir` to escape degenerate support+// directions that stall the GJK simplex without proving separation.+// Successive seeds cycle through ±offsets along each coordinate axis.+fn perturbed_dir(dir: Vector, seed: usize) -> Vector {+ const OFFSET: Real = 1.0e-2;+ let axis = (seed - 1) % DIM;+ let sign = if ((seed - 1) / DIM).is_multiple_of(2) {+ 1.0+ } else {+ -1.0+ };+ let mut res = dir;+ res[axis] += sign * OFFSET;+ res.try_normalize().unwrap_or(dir)+}++fn result(simplex: &VoronoiSimplex, prev: bool) -> (Vector, Vector) {+ let mut res = (Vector::ZERO, Vector::ZERO);+ if prev {+ for i in 0..simplex.prev_dimension() + 1 {+ let coord = simplex.prev_proj_coord(i);+ let point = simplex.prev_point(i);+ res.0 += point.orig1 * coord;+ res.1 += point.orig2 * coord;+ }++ res+ } else {+ for i in 0..simplex.dimension() + 1 {+ let coord = simplex.proj_coord(i);+ let point = simplex.point(i);+ res.0 += point.orig1 * coord;+ res.1 += point.orig2 * coord;+ }++ res+ }+}diff --git a/renderer/third_party/parry3d/src/query/gjk/mod.rs b/renderer/third_party/parry3d/src/query/gjk/mod.rsnew file mode 100644index 0000000..fc9ef00--- /dev/null+++ b/renderer/third_party/parry3d/src/query/gjk/mod.rs@@ -0,0 +1,17 @@+//! The GJK algorithm for distance computation.++pub use self::cso_point::CsoPoint;+#[cfg(feature = "dim2")]+pub use self::voronoi_simplex2::VoronoiSimplex;+#[cfg(feature = "dim3")]+pub use self::voronoi_simplex3::VoronoiSimplex;+pub use gjk::*;+pub use special_support_maps::*;++mod cso_point;+mod gjk;+mod special_support_maps;+#[cfg(feature = "dim2")]+mod voronoi_simplex2;+#[cfg(feature = "dim3")]+mod voronoi_simplex3;diff --git a/renderer/third_party/parry3d/src/query/gjk/special_support_maps.rs b/renderer/third_party/parry3d/src/query/gjk/special_support_maps.rsnew file mode 100644index 0000000..9a8f798--- /dev/null+++ b/renderer/third_party/parry3d/src/query/gjk/special_support_maps.rs@@ -0,0 +1,84 @@+use crate::math::{Pose, Real, Vector};+use crate::shape::SupportMap;++/// A support mapping that is a single point.+pub struct ConstantPoint(pub Vector);++impl SupportMap for ConstantPoint {+ #[inline]+ fn support_point(&self, m: &Pose, _: Vector) -> Vector {+ m * self.0+ }++ #[inline]+ fn support_point_toward(&self, m: &Pose, _: Vector) -> Vector {+ m * self.0+ }++ #[inline]+ fn local_support_point(&self, _: Vector) -> Vector {+ self.0+ }++ #[inline]+ fn local_support_point_toward(&self, _: Vector) -> Vector {+ self.0+ }+}++/// A support mapping that is the point at (0.0, 0.0, 0.0).+pub struct ConstantOrigin;++impl SupportMap for ConstantOrigin {+ #[inline]+ fn support_point(&self, m: &Pose, _: Vector) -> Vector {+ m.translation+ }++ #[inline]+ fn support_point_toward(&self, m: &Pose, _: Vector) -> Vector {+ m.translation+ }++ #[inline]+ fn local_support_point(&self, _: Vector) -> Vector {+ Vector::ZERO+ }++ #[inline]+ fn local_support_point_toward(&self, _: Vector) -> Vector {+ Vector::ZERO+ }+}++/// The Minkowski sum of a shape and a ball.+pub struct DilatedShape<'a, S: ?Sized + SupportMap> {+ /// The shape involved in the Minkowski sum.+ pub shape: &'a S,+ /// The radius of the ball involved in the Minkoski sum.+ pub radius: Real,+}++impl<S: ?Sized + SupportMap> SupportMap for DilatedShape<'_, S> {+ #[inline]+ fn support_point(&self, m: &Pose, dir: Vector) -> Vector {+ let normalized_dir = dir.normalize_or_zero();+ self.support_point_toward(m, normalized_dir)+ }++ #[inline]+ fn support_point_toward(&self, m: &Pose, dir: Vector) -> Vector {+ self.shape.support_point_toward(m, dir) + dir * self.radius+ }++ #[inline]+ fn local_support_point(&self, dir: Vector) -> Vector {+ let normalized_dir = dir.normalize_or_zero();+ self.local_support_point_toward(normalized_dir)+ }++ #[inline]+ fn local_support_point_toward(&self, dir: Vector) -> Vector {+ self.shape.local_support_point_toward(dir) + dir * self.radius+ }+}diff --git a/renderer/third_party/parry3d/src/query/gjk/voronoi_simplex2.rs b/renderer/third_party/parry3d/src/query/gjk/voronoi_simplex2.rsnew file mode 100644index 0000000..2b6ca73--- /dev/null+++ b/renderer/third_party/parry3d/src/query/gjk/voronoi_simplex2.rs@@ -0,0 +1,218 @@+use crate::math::{Real, Vector};+use crate::query::gjk::{self, CsoPoint};+use crate::query::{PointQuery, PointQueryWithLocation};+use crate::shape::{Segment, SegmentPointLocation, Triangle, TrianglePointLocation};++/// A simplex of dimension up to 2 using Voronoï regions for computing point projections.+#[derive(Clone, Debug)]+pub struct VoronoiSimplex {+ prev_vertices: [usize; 3],+ prev_dim: usize,+ prev_proj: [Real; 2],++ vertices: [CsoPoint; 3],+ proj: [Real; 2],+ dim: usize,+}++impl Default for VoronoiSimplex {+ fn default() -> Self {+ Self::new()+ }+}++impl VoronoiSimplex {+ /// Crates a new empty simplex.+ pub fn new() -> VoronoiSimplex {+ VoronoiSimplex {+ prev_vertices: [0, 1, 2],+ prev_proj: [0.0; 2],+ prev_dim: 0,+ vertices: [CsoPoint::ZERO; 3],+ proj: [0.0; 2],+ dim: 0,+ }+ }++ /// Swap two vertices of this simplex.+ pub fn swap(&mut self, i1: usize, i2: usize) {+ self.vertices.swap(i1, i2);+ self.prev_vertices.swap(i1, i2);+ }++ /// Resets this simplex to a single point.+ pub fn reset(&mut self, pt: CsoPoint) {+ self.prev_dim = 0;+ self.dim = 0;+ self.vertices[0] = pt;+ }++ /// Add a point to this simplex.+ pub fn add_point(&mut self, pt: CsoPoint) -> bool {+ self.prev_dim = self.dim;+ self.prev_proj = self.proj;+ self.prev_vertices = [0, 1, 2];++ for i in 0..self.dim + 1 {+ if (self.vertices[i].point - pt.point).length_squared() < gjk::eps_tol() {+ return false;+ }+ }++ self.dim += 1;+ self.vertices[self.dim] = pt;+ true+ }++ /// Retrieves the barycentric coordinate associated to the `i`-th by the last call to `project_origin_and_reduce`.+ pub fn proj_coord(&self, i: usize) -> Real {+ assert!(i <= self.dim, "Index out of bounds.");+ self.proj[i]+ }++ /// The i-th point of this simplex.+ pub fn point(&self, i: usize) -> &CsoPoint {+ assert!(i <= self.dim, "Index out of bounds.");+ &self.vertices[i]+ }++ /// Retrieves the barycentric coordinate associated to the `i`-th before the last call to `project_origin_and_reduce`.+ pub fn prev_proj_coord(&self, i: usize) -> Real {+ assert!(i <= self.prev_dim, "Index out of bounds.");+ self.prev_proj[i]+ }++ /// The i-th point of the simplex before the last call to `project_origin_and_reduce`.+ pub fn prev_point(&self, i: usize) -> &CsoPoint {+ assert!(i <= self.prev_dim, "Index out of bounds.");+ &self.vertices[self.prev_vertices[i]]+ }++ /// Projects the origin on the boundary of this simplex and reduces `self` the smallest subsimplex containing the origin.+ ///+ /// Returns the result of the projection or Vector::ZERO if the origin lies inside of the simplex.+ /// The state of the simplex before projection is saved, and can be retrieved using the methods prefixed+ /// by `prev_`.+ pub fn project_origin_and_reduce(&mut self) -> Vector {+ if self.dim == 0 {+ self.proj[0] = 1.0;+ self.vertices[0].point+ } else if self.dim == 1 {+ let (proj, location) = Segment::new(self.vertices[0].point, self.vertices[1].point)+ .project_local_point_and_get_location(Vector::ZERO, true);++ match location {+ SegmentPointLocation::OnVertex(0) => {+ self.proj[0] = 1.0;+ self.dim = 0;+ }+ SegmentPointLocation::OnVertex(1) => {+ self.proj[0] = 1.0;+ self.swap(0, 1);+ self.dim = 0;+ }+ SegmentPointLocation::OnEdge(coords) => {+ self.proj = coords;+ }+ _ => unreachable!(),+ }++ proj.point+ } else {+ assert!(self.dim == 2);+ let (proj, location) = Triangle::new(+ self.vertices[0].point,+ self.vertices[1].point,+ self.vertices[2].point,+ )+ .project_local_point_and_get_location(Vector::ZERO, true);++ match location {+ TrianglePointLocation::OnVertex(i) => {+ self.swap(0, i as usize);+ self.proj[0] = 1.0;+ self.dim = 0;+ }+ TrianglePointLocation::OnEdge(0, coords) => {+ self.proj = coords;+ self.dim = 1;+ }+ TrianglePointLocation::OnEdge(1, coords) => {+ self.swap(0, 2);+ self.proj[0] = coords[1];+ self.proj[1] = coords[0];+ self.dim = 1;+ }+ TrianglePointLocation::OnEdge(2, coords) => {+ self.swap(1, 2);+ self.proj = coords;+ self.dim = 1;+ }+ _ => {}+ }++ proj.point+ }+ }++ /// Compute the projection of the origin on the boundary of this simplex.+ pub fn project_origin(&mut self) -> Vector {+ if self.dim == 0 {+ self.vertices[0].point+ } else if self.dim == 1 {+ let seg = Segment::new(self.vertices[0].point, self.vertices[1].point);+ seg.project_local_point(Vector::ZERO, true).point+ } else {+ assert!(self.dim == 2);+ let tri = Triangle::new(+ self.vertices[0].point,+ self.vertices[1].point,+ self.vertices[2].point,+ );+ tri.project_local_point(Vector::ZERO, true).point+ }+ }++ /// Tests if the given point is already a vertex of this simplex.+ pub fn contains_point(&self, pt: Vector) -> bool {+ for i in 0..self.dim + 1 {+ if self.vertices[i].point == pt {+ return true;+ }+ }++ false+ }++ /// The dimension of the smallest subspace that can contain this simplex.+ pub fn dimension(&self) -> usize {+ self.dim+ }++ /// The dimension of the simplex before the last call to `project_origin_and_reduce`.+ pub fn prev_dimension(&self) -> usize {+ self.prev_dim+ }++ /// The maximum squared length of the vertices of this simplex.+ pub fn max_sq_len(&self) -> Real {+ let mut max_sq_len = 0.0;++ for i in 0..self.dim + 1 {+ let norm = self.vertices[i].point.length_squared();++ if norm > max_sq_len {+ max_sq_len = norm+ }+ }++ max_sq_len+ }++ /// Apply a function to all the vertices of this simplex.+ pub fn modify_pnts(&mut self, f: &dyn Fn(&mut CsoPoint)) {+ for i in 0..self.dim + 1 {+ f(&mut self.vertices[i])+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/gjk/voronoi_simplex3.rs b/renderer/third_party/parry3d/src/query/gjk/voronoi_simplex3.rsnew file mode 100644index 0000000..867161c--- /dev/null+++ b/renderer/third_party/parry3d/src/query/gjk/voronoi_simplex3.rs@@ -0,0 +1,345 @@+use crate::math::{Real, Vector};+use crate::query::gjk::{self, CsoPoint};+use crate::query::{PointQuery, PointQueryWithLocation};+use crate::shape::{+ Segment, SegmentPointLocation, Tetrahedron, TetrahedronPointLocation, Triangle,+ TrianglePointLocation,+};++/// A simplex of dimension up to 3 that uses Voronoï regions for computing point projections.+#[derive(Clone, Debug)]+pub struct VoronoiSimplex {+ prev_vertices: [usize; 4],+ prev_proj: [Real; 3],+ prev_dim: usize,++ vertices: [CsoPoint; 4],+ proj: [Real; 3],+ dim: usize,+}++impl Default for VoronoiSimplex {+ fn default() -> Self {+ Self::new()+ }+}++impl VoronoiSimplex {+ /// Creates a new empty simplex.+ pub fn new() -> VoronoiSimplex {+ VoronoiSimplex {+ prev_vertices: [0, 1, 2, 3],+ prev_proj: [0.0; 3],+ prev_dim: 0,+ vertices: [CsoPoint::ZERO; 4],+ proj: [0.0; 3],+ dim: 0,+ }+ }++ /// Swap two vertices of this simplex.+ pub fn swap(&mut self, i1: usize, i2: usize) {+ self.vertices.swap(i1, i2);+ self.prev_vertices.swap(i1, i2);+ }++ /// Resets this simplex to a single point.+ pub fn reset(&mut self, pt: CsoPoint) {+ self.dim = 0;+ self.prev_dim = 0;+ self.vertices[0] = pt;+ }++ /// Add a point to this simplex.+ pub fn add_point(&mut self, pt: CsoPoint) -> bool {+ self.prev_dim = self.dim;+ self.prev_proj = self.proj;+ self.prev_vertices = [0, 1, 2, 3];++ match self.dim {+ 0 => {+ if (self.vertices[0] - pt).length_squared() < gjk::eps_tol() {+ return false;+ }+ }+ 1 => {+ let ab = self.vertices[1] - self.vertices[0];+ let ac = pt - self.vertices[0];++ if ab.cross(ac).length_squared() < gjk::eps_tol() {+ return false;+ }+ }+ 2 => {+ let ab = self.vertices[1] - self.vertices[0];+ let ac = self.vertices[2] - self.vertices[0];+ let ap = pt - self.vertices[0];+ let n = ab.cross(ac).normalize();++ if n.dot(ap).abs() < gjk::eps_tol() {+ return false;+ }+ }+ _ => unreachable!(),+ }++ self.dim += 1;+ self.vertices[self.dim] = pt;+ true+ }++ /// Retrieves the barycentric coordinate associated to the `i`-th by the last call to `project_origin_and_reduce`.+ pub fn proj_coord(&self, i: usize) -> Real {+ assert!(i <= self.dim, "Index out of bounds.");+ self.proj[i]+ }++ /// The i-th point of this simplex.+ pub fn point(&self, i: usize) -> &CsoPoint {+ assert!(i <= self.dim, "Index out of bounds.");+ &self.vertices[i]+ }++ /// Retrieves the barycentric coordinate associated to the `i`-th before the last call to `project_origin_and_reduce`.+ pub fn prev_proj_coord(&self, i: usize) -> Real {+ assert!(i <= self.prev_dim, "Index out of bounds.");+ self.prev_proj[i]+ }++ /// The i-th point of the simplex before the last call to `project_origin_and_reduce`.+ pub fn prev_point(&self, i: usize) -> &CsoPoint {+ assert!(i <= self.prev_dim, "Index out of bounds.");+ &self.vertices[self.prev_vertices[i]]+ }++ /// Projects the origin on the boundary of this simplex and reduces `self` the smallest subsimplex containing the origin.+ ///+ /// Returns the result of the projection or `Vector::ZERO` if the origin lies inside of the simplex.+ /// The state of the simplex before projection is saved, and can be retrieved using the methods prefixed+ /// by `prev_`.+ pub fn project_origin_and_reduce(&mut self) -> Vector {+ if self.dim == 0 {+ self.proj[0] = 1.0;+ self.vertices[0].point+ } else if self.dim == 1 {+ let (proj, location) = Segment::new(self.vertices[0].point, self.vertices[1].point)+ .project_local_point_and_get_location(Vector::ZERO, true);++ match location {+ SegmentPointLocation::OnVertex(0) => {+ self.proj[0] = 1.0;+ self.dim = 0;+ }+ SegmentPointLocation::OnVertex(1) => {+ self.swap(0, 1);+ self.proj[0] = 1.0;+ self.dim = 0;+ }+ SegmentPointLocation::OnEdge(coords) => {+ self.proj[0] = coords[0];+ self.proj[1] = coords[1];+ }+ _ => unreachable!(),+ }++ proj.point+ } else if self.dim == 2 {+ let (proj, location) = Triangle::new(+ self.vertices[0].point,+ self.vertices[1].point,+ self.vertices[2].point,+ )+ .project_local_point_and_get_location(Vector::ZERO, true);++ match location {+ TrianglePointLocation::OnVertex(i) => {+ self.swap(0, i as usize);+ self.proj[0] = 1.0;+ self.dim = 0;+ }+ TrianglePointLocation::OnEdge(0, coords) => {+ self.proj[0] = coords[0];+ self.proj[1] = coords[1];+ self.dim = 1;+ }+ TrianglePointLocation::OnEdge(1, coords) => {+ self.swap(0, 2);+ self.proj[0] = coords[1];+ self.proj[1] = coords[0];+ self.dim = 1;+ }+ TrianglePointLocation::OnEdge(2, coords) => {+ self.swap(1, 2);+ self.proj[0] = coords[0];+ self.proj[1] = coords[1];+ self.dim = 1;+ }+ TrianglePointLocation::OnFace(_, coords) => {+ self.proj = coords;+ }+ _ => {}+ }++ proj.point+ } else {+ assert!(self.dim == 3);+ let (proj, location) = Tetrahedron::new(+ self.vertices[0].point,+ self.vertices[1].point,+ self.vertices[2].point,+ self.vertices[3].point,+ )+ .project_local_point_and_get_location(Vector::ZERO, true);++ match location {+ TetrahedronPointLocation::OnVertex(i) => {+ self.swap(0, i as usize);+ self.proj[0] = 1.0;+ self.dim = 0;+ }+ TetrahedronPointLocation::OnEdge(i, coords) => {+ match i {+ 0 => {+ // ab+ }+ 1 => {+ // ac+ self.swap(1, 2)+ }+ 2 => {+ // ad+ self.swap(1, 3)+ }+ 3 => {+ // bc+ self.swap(0, 2)+ }+ 4 => {+ // bd+ self.swap(0, 3)+ }+ 5 => {+ // cd+ self.swap(0, 2);+ self.swap(1, 3);+ }+ _ => unreachable!(),+ }++ match i {+ 0 | 1 | 2 | 5 => {+ self.proj[0] = coords[0];+ self.proj[1] = coords[1];+ }+ 3 | 4 => {+ self.proj[0] = coords[1];+ self.proj[1] = coords[0];+ }+ _ => unreachable!(),+ }+ self.dim = 1;+ }+ TetrahedronPointLocation::OnFace(i, coords) => {+ match i {+ 0 => {+ // abc+ self.proj = coords;+ }+ 1 => {+ // abd+ self.vertices[2] = self.vertices[3];+ self.proj = coords;+ }+ 2 => {+ // acd+ self.vertices[1] = self.vertices[3];+ self.proj[0] = coords[0];+ self.proj[1] = coords[2];+ self.proj[2] = coords[1];+ }+ 3 => {+ // bcd+ self.vertices[0] = self.vertices[3];+ self.proj[0] = coords[2];+ self.proj[1] = coords[0];+ self.proj[2] = coords[1];+ }+ _ => unreachable!(),+ }+ self.dim = 2;+ }+ _ => {}+ }++ proj.point+ }+ }++ /// Compute the projection of the origin on the boundary of this simplex.+ pub fn project_origin(&mut self) -> Vector {+ if self.dim == 0 {+ self.vertices[0].point+ } else if self.dim == 1 {+ let seg = Segment::new(self.vertices[0].point, self.vertices[1].point);+ seg.project_local_point(Vector::ZERO, true).point+ } else if self.dim == 2 {+ let tri = Triangle::new(+ self.vertices[0].point,+ self.vertices[1].point,+ self.vertices[2].point,+ );+ tri.project_local_point(Vector::ZERO, true).point+ } else {+ let tetr = Tetrahedron::new(+ self.vertices[0].point,+ self.vertices[1].point,+ self.vertices[2].point,+ self.vertices[3].point,+ );+ tetr.project_local_point(Vector::ZERO, true).point+ }+ }++ /// Tests if the given point is already a vertex of this simplex.+ pub fn contains_point(&self, pt: Vector) -> bool {+ for i in 0..self.dim + 1 {+ if self.vertices[i].point == pt {+ return true;+ }+ }++ false+ }++ /// The dimension of the smallest subspace that can contain this simplex.+ pub fn dimension(&self) -> usize {+ self.dim+ }++ /// The dimension of the simplex before the last call to `project_origin_and_reduce`.+ pub fn prev_dimension(&self) -> usize {+ self.prev_dim+ }++ /// The maximum squared length of the vertices of this simplex.+ pub fn max_sq_len(&self) -> Real {+ let mut max_sq_len = 0.0;++ for i in 0..self.dim + 1 {+ let norm = self.vertices[i].point.length_squared();++ if norm > max_sq_len {+ max_sq_len = norm+ }+ }++ max_sq_len+ }++ /// Apply a function to all the vertices of this simplex.+ pub fn modify_pnts(&mut self, f: &dyn Fn(&mut CsoPoint)) {+ for i in 0..self.dim + 1 {+ f(&mut self.vertices[i])+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/intersection_test/intersection_test.rs b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test.rsnew file mode 100644index 0000000..6443f92--- /dev/null+++ b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test.rs@@ -0,0 +1,143 @@+use crate::shape::SubShapeId;++/// Whether two shapes intersect, and the sub-shapes that do.+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub struct ShapeIntersection {+ /// Whether the two shapes intersect.+ pub intersecting: bool,+ /// The sub-shape of the first shape that intersects.+ ///+ /// Always `0` for a shape with no sub-shapes, and meaningless unless `intersecting` is `true`.+ pub subshape1: SubShapeId,+ /// The sub-shape of the second shape that intersects.+ ///+ /// Always `0` for a shape with no sub-shapes, and meaningless unless `intersecting` is `true`.+ pub subshape2: SubShapeId,+}++impl ShapeIntersection {+ /// A result between shapes with no sub-shapes to distinguish.+ pub fn new(intersecting: bool) -> Self {+ Self {+ intersecting,+ subshape1: 0,+ subshape2: 0,+ }+ }++ /// Sets the sub-shapes that intersect.+ pub fn with_subshapes(mut self, subshape1: SubShapeId, subshape2: SubShapeId) -> Self {+ self.subshape1 = subshape1;+ self.subshape2 = subshape2;+ self+ }++ /// Swaps the roles of the two shapes.+ pub fn swapped(mut self) -> Self {+ core::mem::swap(&mut self.subshape1, &mut self.subshape2);+ self+ }+}++impl From<bool> for ShapeIntersection {+ fn from(intersecting: bool) -> Self {+ Self::new(intersecting)+ }+}++use crate::math::Pose;+use crate::query::{DefaultQueryDispatcher, QueryDispatcher, Unsupported};+use crate::shape::Shape;++/// Tests whether two shapes are intersecting (overlapping).+///+/// This is the fastest collision query, returning only a boolean result without+/// computing contact points, normals, or penetration depth. Use this when you only+/// need to know **if** shapes collide, not **where** or **how much**.+///+/// # Behavior+///+/// Returns `true` if:+/// - Shapes are **touching** (surfaces just make contact)+/// - Shapes are **penetrating** (overlapping with any amount)+///+/// Returns `false` if:+/// - Shapes are **separated** (any distance apart, even very close)+///+/// # Performance+///+/// This is the fastest collision detection query:+/// - **Ball-Ball**: Extremely fast (just distance check)+/// - **AABB-AABB**: Very fast (6 comparisons in 3D)+/// - **Convex-Convex**: Fast (early-exit GJK algorithm)+/// - **Concave shapes**: Uses BVH for acceleration+///+/// Significantly faster than `contact()` or `distance()` because it can+/// terminate early once any intersection is found.+///+/// # Arguments+///+/// * `pos1` - Position and orientation of the first shape+/// * `g1` - The first shape+/// * `pos2` - Position and orientation of the second shape+/// * `g2` - The second shape+///+/// # Returns+///+/// * `Ok(true)` - Shapes are intersecting+/// * `Ok(false)` - Shapes are not intersecting+/// * `Err(Unsupported)` - This shape pair combination is not supported+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::intersection_test;+/// use parry3d::shape::Ball;+/// use parry3d::math::Pose;+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+///+/// // Overlapping balls+/// let pos1 = Pose::translation(0.0, 0.0, 0.0);+/// let pos2 = Pose::translation(1.5, 0.0, 0.0);+///+/// let intersecting = intersection_test(&pos1, &ball1, &pos2, &ball2).unwrap().intersecting;+/// assert!(intersecting); // Distance 1.5 < combined radii 2.0+///+/// // Separated balls+/// let pos3 = Pose::translation(5.0, 0.0, 0.0);+/// let not_intersecting = intersection_test(&pos1, &ball1, &pos3, &ball2).unwrap().intersecting;+/// assert!(!not_intersecting); // Distance 5.0 > combined radii 2.0+/// # }+/// ```+///+/// # Use Cases+///+/// - **Trigger volumes**: Detect when player enters an area+/// - **Broad-phase**: Quickly filter out distant object pairs+/// - **Game logic**: Simple overlap detection (pickup items, damage zones)+/// - **Optimization**: Pre-check before expensive narrow-phase queries+///+/// # When to Use Other Queries+///+/// - Need contact points/normal? → Use [`contact`](crate::query::contact())+/// - Need penetration depth? → Use [`contact`](crate::query::contact())+/// - Need separation distance? → Use [`distance`](crate::query::distance())+/// - Need closest points? → Use [`closest_points`](crate::query::closest_points())+///+/// # See Also+///+/// - [`contact`](crate::query::contact()) - Get contact information if intersecting+/// - [`distance`](crate::query::distance()) - Get separation distance+/// - [`closest_points`](crate::query::closest_points()) - Get closest point locations+pub fn intersection_test(+ pos1: &Pose,+ g1: &dyn Shape,+ pos2: &Pose,+ g2: &dyn Shape,+) -> Result<ShapeIntersection, Unsupported> {+ let pos12 = pos1.inv_mul(pos2);+ DefaultQueryDispatcher.intersection_test(&pos12, g1, g2)+}diff --git a/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_ball_ball.rs b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_ball_ball.rsnew file mode 100644index 0000000..66ae4f2--- /dev/null+++ b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_ball_ball.rs@@ -0,0 +1,12 @@+use crate::math::Vector;+use crate::shape::Ball;++/// Intersection test between balls.+#[inline]+pub fn intersection_test_ball_ball(center12: Vector, b1: &Ball, b2: &Ball) -> bool {+ let r1 = b1.radius;+ let r2 = b2.radius;+ let distance_squared = center12.length_squared();+ let sum_radius = r1 + r2;+ distance_squared <= sum_radius * sum_radius+}diff --git a/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_ball_point_query.rs b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_ball_point_query.rsnew file mode 100644index 0000000..4693ea7--- /dev/null+++ b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_ball_point_query.rs@@ -0,0 +1,26 @@+use crate::math::Pose;+use crate::query::{PointQuery, ShapeIntersection};+use crate::shape::Ball;++/// Intersection test between a ball and a shape implementing the `PointQuery` trait.+pub fn intersection_test_ball_point_query<P: ?Sized + PointQuery>(+ pos12: &Pose,+ ball1: &Ball,+ point_query2: &P,+) -> ShapeIntersection {+ intersection_test_point_query_ball(&pos12.inverse(), point_query2, ball1).swapped()+}++/// Intersection test between a shape implementing the `PointQuery` trait and a ball.+pub fn intersection_test_point_query_ball<P: ?Sized + PointQuery>(+ pos12: &Pose,+ point_query1: &P,+ ball2: &Ball,+) -> ShapeIntersection {+ let local_p2_1 = pos12.translation;+ let proj = point_query1.project_local_point(local_p2_1, true);+ let intersecting =+ proj.is_inside || (local_p2_1 - proj.point).length_squared() <= ball2.radius * ball2.radius;+ // The projection knows which sub-shape of `point_query1` answered.+ ShapeIntersection::new(intersecting).with_subshapes(proj.subshape, 0)+}diff --git a/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_composite_shape_shape.rs b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_composite_shape_shape.rsnew file mode 100644index 0000000..86a42c6--- /dev/null+++ b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_composite_shape_shape.rs@@ -0,0 +1,72 @@+use crate::bounding_volume::BoundingVolume;+use crate::math::Pose;+use crate::partitioning::BvhNode;+use crate::query::{QueryDispatcher, ShapeIntersection};+use crate::shape::{CompositeShapeRef, Shape, SubShapeId, TypedCompositeShape};+use crate::utils::PoseOpt;++impl<S: ?Sized + TypedCompositeShape> CompositeShapeRef<'_, S> {+ /// Tests whether the given other `shape`, positioned at `pose12` relative to `self`,+ /// intersects `self`.+ ///+ /// Returns `None` when they do not intersect. Otherwise returns the index of a sub-shape of+ /// `self` that `shape` intersects alongside that sub-shape's own result (its `subshape1` is+ /// the sub-shape's own when it is a composite too, and `subshape2` is `shape`'s).+ pub fn intersects_shape<D: ?Sized + QueryDispatcher>(+ &self,+ dispatcher: &D,+ pose12: &Pose,+ shape: &dyn Shape,+ ) -> Option<(SubShapeId, ShapeIntersection)> {+ let ls_aabb2 = shape.compute_aabb(pose12);+ self.0+ .bvh()+ .leaves(|node: &BvhNode| node.aabb().intersects(&ls_aabb2))+ .find_map(|leaf_id| {+ self.0+ .map_untyped_part_at(leaf_id, |part_pose1, sub1, _| {+ dispatcher+ .intersection_test(&part_pose1.inv_mul(pose12), sub1, shape)+ .ok()+ .filter(|result| result.intersecting)+ .map(|result| (leaf_id, result))+ })+ .flatten()+ })+ }+}++/// Intersection test between a composite shape (`Mesh`, `Compound`) and any other shape.+pub fn intersection_test_composite_shape_shape<D, G1>(+ dispatcher: &D,+ pos12: &Pose,+ g1: &G1,+ g2: &dyn Shape,+) -> ShapeIntersection+where+ D: ?Sized + QueryDispatcher,+ G1: ?Sized + TypedCompositeShape,+{+ // `subshape2` is left as the dispatch set it: `g2` may be a composite too, and only it+ // knows which of its parts answered.+ match CompositeShapeRef(g1).intersects_shape(dispatcher, pos12, g2) {+ Some((part_id, result)) => {+ ShapeIntersection::new(true).with_subshapes(part_id, result.subshape2)+ }+ None => ShapeIntersection::new(false),+ }+}++/// Proximity between a shape and a composite (`Mesh`, `Compound`) shape.+pub fn intersection_test_shape_composite_shape<D, G2>(+ dispatcher: &D,+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &G2,+) -> ShapeIntersection+where+ D: ?Sized + QueryDispatcher,+ G2: ?Sized + TypedCompositeShape,+{+ intersection_test_composite_shape_shape(dispatcher, &pos12.inverse(), g2, g1).swapped()+}diff --git a/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_cuboid_cuboid.rs b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_cuboid_cuboid.rsnew file mode 100644index 0000000..48fc3c9--- /dev/null+++ b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_cuboid_cuboid.rs@@ -0,0 +1,27 @@+use crate::math::Pose;+use crate::query::sat;+use crate::shape::Cuboid;++/// Intersection test between cuboids.+#[inline]+pub fn intersection_test_cuboid_cuboid(pos12: &Pose, cuboid1: &Cuboid, cuboid2: &Cuboid) -> bool {+ let sep1 = sat::cuboid_cuboid_find_local_separating_normal_oneway(cuboid1, cuboid2, pos12).0;++ if sep1 > 0.0 {+ return false;+ }++ let pos21 = pos12.inverse();+ let sep2 = sat::cuboid_cuboid_find_local_separating_normal_oneway(cuboid2, cuboid1, &pos21).0;+ if sep2 > 0.0 {+ return false;+ }++ #[cfg(feature = "dim2")]+ return true; // This case does not exist in 2D.+ #[cfg(feature = "dim3")]+ {+ let sep3 = sat::cuboid_cuboid_find_local_separating_edge_twoway(cuboid1, cuboid2, pos12).0;+ sep3 <= 0.0+ }+}diff --git a/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_cuboid_segment.rs b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_cuboid_segment.rsnew file mode 100644index 0000000..52bf526--- /dev/null+++ b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_cuboid_segment.rs@@ -0,0 +1,53 @@+use crate::bounding_volume::Aabb;+use crate::math::{Pose, Rotation};+use crate::query::sat;+use crate::shape::{Cuboid, Segment};++/// Test if a segment intersects an Aabb.+pub fn intersection_test_aabb_segment(aabb1: &Aabb, segment2: &Segment) -> bool {+ let cuboid1 = Cuboid::new(aabb1.half_extents());+ let pos12 = Pose::from_parts(-aabb1.center(), Rotation::IDENTITY);+ intersection_test_cuboid_segment(&pos12, &cuboid1, segment2)+}++/// Test if a segment intersects a cuboid.+#[inline]+pub fn intersection_test_segment_cuboid(+ pos12: &Pose,+ segment1: &Segment,+ cuboid2: &Cuboid,+) -> bool {+ intersection_test_cuboid_segment(&pos12.inverse(), cuboid2, segment1)+}++/// Test if a segment intersects a cuboid.+#[inline]+pub fn intersection_test_cuboid_segment(pos12: &Pose, cube1: &Cuboid, segment2: &Segment) -> bool {+ let sep1 =+ sat::cuboid_support_map_find_local_separating_normal_oneway(cube1, segment2, pos12).0;+ if sep1 > 0.0 {+ return false;+ }++ // This case does not exist in 3D.+ #[cfg(feature = "dim2")]+ {+ let sep2 = sat::segment_cuboid_find_local_separating_normal_oneway(+ segment2,+ cube1,+ &pos12.inverse(),+ )+ .0;+ if sep2 > 0.0 {+ return false;+ }+ }++ #[cfg(feature = "dim2")]+ return true; // This case does not exist in 2D.+ #[cfg(feature = "dim3")]+ {+ let sep3 = sat::cuboid_segment_find_local_separating_edge_twoway(cube1, segment2, pos12).0;+ sep3 <= 0.0+ }+}diff --git a/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_cuboid_triangle.rs b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_cuboid_triangle.rsnew file mode 100644index 0000000..1f9b7a0--- /dev/null+++ b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_cuboid_triangle.rs@@ -0,0 +1,50 @@+use crate::bounding_volume::Aabb;+use crate::math::{Pose, Rotation};+use crate::query::sat;+use crate::shape::{Cuboid, Triangle};++/// Tests if a triangle intersects an Aabb.+pub fn intersection_test_aabb_triangle(aabb1: &Aabb, triangle2: &Triangle) -> bool {+ let cuboid1 = Cuboid::new(aabb1.half_extents());+ let pos12 = Pose::from_parts(-aabb1.center(), Rotation::IDENTITY);+ intersection_test_cuboid_triangle(&pos12, &cuboid1, triangle2)+}++/// Tests if a triangle intersects a cuboid.+#[inline]+pub fn intersection_test_triangle_cuboid(+ pos12: &Pose,+ triangle1: &Triangle,+ cuboid2: &Cuboid,+) -> bool {+ intersection_test_cuboid_triangle(&pos12.inverse(), cuboid2, triangle1)+}++/// Tests if a triangle intersects an cuboid.+#[inline]+pub fn intersection_test_cuboid_triangle(+ pos12: &Pose,+ cube1: &Cuboid,+ triangle2: &Triangle,+) -> bool {+ let sep1 =+ sat::cuboid_support_map_find_local_separating_normal_oneway(cube1, triangle2, pos12).0;+ if sep1 > 0.0 {+ return false;+ }++ let pos21 = pos12.inverse();+ let sep2 = sat::triangle_cuboid_find_local_separating_normal_oneway(triangle2, cube1, &pos21).0;+ if sep2 > 0.0 {+ return false;+ }++ #[cfg(feature = "dim2")]+ return true; // This case does not exist in 2D.+ #[cfg(feature = "dim3")]+ {+ let sep3 =+ sat::cuboid_triangle_find_local_separating_edge_twoway(cube1, triangle2, pos12).0;+ sep3 <= 0.0+ }+}diff --git a/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_halfspace_support_map.rs b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_halfspace_support_map.rsnew file mode 100644index 0000000..c373296--- /dev/null+++ b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_halfspace_support_map.rs@@ -0,0 +1,22 @@+use crate::math::Pose;+use crate::shape::HalfSpace;+use crate::shape::SupportMap;++/// Intersection test between a halfspace and a support-mapped shape (Cuboid, ConvexHull, etc.)+pub fn intersection_test_halfspace_support_map<G: ?Sized + SupportMap>(+ pos12: &Pose,+ halfspace: &HalfSpace,+ other: &G,+) -> bool {+ let deepest = other.support_point_toward(pos12, -halfspace.normal);+ halfspace.normal.dot(deepest) <= 0.0+}++/// Intersection test between a support-mapped shape (Cuboid, ConvexHull, etc.) and a halfspace.+pub fn intersection_test_support_map_halfspace<G: ?Sized + SupportMap>(+ pos12: &Pose,+ other: &G,+ halfspace: &HalfSpace,+) -> bool {+ intersection_test_halfspace_support_map(&pos12.inverse(), halfspace, other)+}diff --git a/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_polygon_polygon.rs b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_polygon_polygon.rsnew file mode 100644index 0000000..6a085b5--- /dev/null+++ b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_polygon_polygon.rs@@ -0,0 +1,57 @@+#![allow(dead_code)]++use crate::geometry::proximity_detector::PrimitiveProximityDetectionContext;+use crate::geometry::{sat, Polygon, Proximity};+use crate::math::{Pose, Real};++pub fn detect_proximity_polygon_polygon(+ _ctxt: &mut PrimitiveProximityDetectionContext,+) -> Proximity {+ unimplemented!()+ // if let (Some(polygon1), Some(polygon2)) = (ctxt.shape1.as_polygon(), ctxt.shape2.as_polygon()) {+ // detect_proximity(+ // ctxt.prediction_distance,+ // polygon1,+ // &ctxt.position1,+ // polygon2,+ // &ctxt.position2,+ // )+ // } else {+ // unreachable!()+ // }+}++fn detect_proximity<'a>(+ prediction_distance: Real,+ p1: &'a Polygon,+ m1: &'a Pose,+ p2: &'a Polygon,+ m2: &'a Pose,+) -> Proximity {+ let m12 = m1.inv_mul(&m2);+ let m21 = m12.inverse();++ let sep1 = sat::polygon_polygon_compute_separation_features(p1, p2, &m12);+ if sep1.0 > prediction_distance {+ return Proximity::Disjoint;+ }++ let sep2 = sat::polygon_polygon_compute_separation_features(p2, p1, &m21);+ if sep2.0 > prediction_distance {+ return Proximity::Disjoint;+ }++ if sep2.0 > sep1.0 {+ if sep2.0 > 0.0 {+ Proximity::WithinMargin+ } else {+ Proximity::Intersecting+ }+ } else {+ if sep1.0 > 0.0 {+ Proximity::WithinMargin+ } else {+ Proximity::Intersecting+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_support_map_support_map.rs b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_support_map_support_map.rsnew file mode 100644index 0000000..6d87e57--- /dev/null+++ b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_support_map_support_map.rs@@ -0,0 +1,51 @@+use crate::math::{Pose, Vector};+use crate::query::gjk::{self, CsoPoint, GJKResult, VoronoiSimplex};+use crate::shape::SupportMap;++/// Intersection test between support-mapped shapes (`Cuboid`, `ConvexHull`, etc.)+pub fn intersection_test_support_map_support_map<G1, G2>(pos12: &Pose, g1: &G1, g2: &G2) -> bool+where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+{+ intersection_test_support_map_support_map_with_params(+ pos12,+ g1,+ g2,+ &mut VoronoiSimplex::new(),+ None,+ )+ .0+}++/// Intersection test between support-mapped shapes (`Cuboid`, `ConvexHull`, etc.)+///+/// This allows a more fine grained control other the underlying GJK algorithm.+pub fn intersection_test_support_map_support_map_with_params<G1, G2>(+ pos12: &Pose,+ g1: &G1,+ g2: &G2,+ simplex: &mut VoronoiSimplex,+ init_dir: Option<Vector>,+) -> (bool, Vector)+where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+{+ let dir = if let Some(init_dir) = init_dir {+ init_dir+ } else if let Some(init_dir) = (pos12.translation).try_normalize() {+ init_dir+ } else {+ Vector::X+ };++ simplex.reset(CsoPoint::from_shapes(pos12, g1, g2, dir));++ match gjk::closest_points(pos12, g1, g2, 0.0, false, simplex) {+ GJKResult::Intersection => (true, dir),+ GJKResult::Proximity(dir) => (false, dir),+ GJKResult::NoIntersection(dir) => (false, dir),+ GJKResult::ClosestPoints(..) => unreachable!(),+ }+}diff --git a/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_voxels_shape.rs b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_voxels_shape.rsnew file mode 100644index 0000000..c77eb06--- /dev/null+++ b/renderer/third_party/parry3d/src/query/intersection_test/intersection_test_voxels_shape.rs@@ -0,0 +1,65 @@+use crate::math::Pose;+use crate::query::{PersistentQueryDispatcher, ShapeIntersection};+use crate::shape::{Cuboid, Shape, VoxelType, Voxels};++/// Checks for any intersection between voxels and an arbitrary shape, both represented as a `Shape` trait-object.+pub fn intersection_test_voxels_shape_shapes(+ dispatcher: &dyn PersistentQueryDispatcher,+ pos12: &Pose,+ shape1: &dyn Shape,+ shape2: &dyn Shape,+) -> ShapeIntersection {+ if let Some(voxels1) = shape1.as_voxels() {+ intersection_test_voxels_shape(dispatcher, pos12, voxels1, shape2)+ } else if let Some(voxels2) = shape2.as_voxels() {+ intersection_test_voxels_shape(dispatcher, &pos12.inverse(), voxels2, shape1).swapped()+ } else {+ ShapeIntersection::new(false)+ }+}++/// Checks for any intersection between voxels and an arbitrary shape.+pub fn intersection_test_voxels_shape(+ dispatcher: &dyn PersistentQueryDispatcher,+ pos12: &Pose,+ voxels1: &Voxels,+ shape2: &dyn Shape,+) -> ShapeIntersection {+ let radius1 = voxels1.voxel_size() / 2.0;+ let aabb1 = voxels1.local_aabb();+ let aabb2_1 = shape2.compute_aabb(pos12);++ if let Some(intersection_aabb1) = aabb1.intersection(&aabb2_1) {+ for vox1 in voxels1.voxels_intersecting_local_aabb(&intersection_aabb1) {+ let vox_type1 = vox1.state.voxel_type();++ if vox_type1 == VoxelType::Empty {+ continue;+ }++ let center1 = vox1.center;+ let cuboid1 = Cuboid::new(radius1);+ let cuboid_pose12 = Pose::from_translation(-center1) * pos12;++ if let Ok(result) = dispatcher.intersection_test(&cuboid_pose12, &cuboid1, shape2) {+ if result.intersecting {+ // `shape2` may be a composite; keep the sub-shape it reported.+ return ShapeIntersection::new(true)+ .with_subshapes(vox1.linear_id.flat_id() as u32, result.subshape2);+ }+ }+ }+ }++ ShapeIntersection::new(false)+}++/// Checks for any intersection between voxels and an arbitrary shape.+pub fn intersection_test_shape_voxels(+ dispatcher: &dyn PersistentQueryDispatcher,+ pos12: &Pose,+ shape1: &dyn Shape,+ voxels2: &Voxels,+) -> ShapeIntersection {+ intersection_test_voxels_shape(dispatcher, &pos12.inverse(), voxels2, shape1).swapped()+}diff --git a/renderer/third_party/parry3d/src/query/intersection_test/mod.rs b/renderer/third_party/parry3d/src/query/intersection_test/mod.rsnew file mode 100644index 0000000..3499329--- /dev/null+++ b/renderer/third_party/parry3d/src/query/intersection_test/mod.rs@@ -0,0 +1,45 @@+//! Implementation details of the `intersection_test` function.++pub use self::intersection_test::{intersection_test, ShapeIntersection};+pub use self::intersection_test_ball_ball::intersection_test_ball_ball;+pub use self::intersection_test_ball_point_query::{+ intersection_test_ball_point_query, intersection_test_point_query_ball,+};+pub use self::intersection_test_cuboid_cuboid::intersection_test_cuboid_cuboid;+pub use self::intersection_test_cuboid_segment::{+ intersection_test_aabb_segment, intersection_test_cuboid_segment,+ intersection_test_segment_cuboid,+};+pub use self::intersection_test_cuboid_triangle::{+ intersection_test_aabb_triangle, intersection_test_cuboid_triangle,+ intersection_test_triangle_cuboid,+};+pub use self::intersection_test_halfspace_support_map::{+ intersection_test_halfspace_support_map, intersection_test_support_map_halfspace,+};+pub use self::intersection_test_support_map_support_map::intersection_test_support_map_support_map;+pub use self::intersection_test_support_map_support_map::intersection_test_support_map_support_map_with_params;+#[cfg(feature = "alloc")]+pub use self::{+ intersection_test_composite_shape_shape::{+ intersection_test_composite_shape_shape, intersection_test_shape_composite_shape,+ },+ intersection_test_voxels_shape::{+ intersection_test_shape_voxels, intersection_test_voxels_shape,+ intersection_test_voxels_shape_shapes,+ },+};++mod intersection_test;+mod intersection_test_ball_ball;+mod intersection_test_ball_point_query;+#[cfg(feature = "alloc")]+mod intersection_test_composite_shape_shape;+mod intersection_test_cuboid_cuboid;+mod intersection_test_cuboid_segment;+mod intersection_test_cuboid_triangle;+mod intersection_test_halfspace_support_map;+mod intersection_test_support_map_support_map;++#[cfg(feature = "alloc")]+mod intersection_test_voxels_shape;diff --git a/renderer/third_party/parry3d/src/query/mod.rs b/renderer/third_party/parry3d/src/query/mod.rsnew file mode 100644index 0000000..48bd33f--- /dev/null+++ b/renderer/third_party/parry3d/src/query/mod.rs@@ -0,0 +1,89 @@+//! Non-persistent geometric queries.+//!+//! # General cases+//! The most general methods provided by this module are:+//!+//! * [`closest_points()`] to compute the closest points between two shapes.+//! * [`distance()`] to compute the distance between two shapes.+//! * [`contact()`] to compute one pair of contact points between two shapes, including penetrating contact.+//! * [`intersection_test()`] to determine if two shapes are intersecting or not.+//! * [`cast_shapes()`] to determine when two shapes undergoing translational motions hit for the first time.+//! * [`cast_shapes_nonlinear()`] to determine when two shapes undergoing continuous rigid motions hit for the first time.+//!+//! Ray-casting and point-projection can be achieved by importing traits:+//!+//! * [`RayCast`] for ray-casting.+//! * [`PointQuery`] for point projection.+//!+//! # Specific cases+//! The functions exported by the `details` submodule are more specific versions of the ones described above.+//! For example `distance_ball_ball` computes the distance between two shapes known at compile-time to be balls.+//! They are less convenient to use than the most generic version but will be slightly faster due to the lack of dynamic dispatch.+//! The specific functions have the form `[operation]_[shape1]_[shape2]()` where:+//!+//! * `[operation]` can be `closest_points`, `distance`, `contact`, `intersection_test` or `time_of_impact`.+//! * `[shape1]` is the type of the first shape passed to the function, e.g., `ball`, or `halfspace`. Can also identify a trait implemented by supported shapes, e.g., `support_map`.+//! * `[shape2]` is the type of the second shape passed to the function, e.g., `ball`, or `halfspace`. Can also identify a trait implemented by supported shapes, e.g., `support_map`.++pub use self::closest_points::{closest_points, ClosestPoints};+pub use self::contact::{contact, Contact};+#[cfg(feature = "alloc")]+pub use self::contact_manifolds::{+ ContactManifold, ContactManifoldsWorkspace, TrackedContact, TypedWorkspaceData, WorkspaceData,+};+pub use self::default_query_dispatcher::DefaultQueryDispatcher;+pub use self::distance::{distance, ShapeDistance};+pub use self::error::Unsupported;+pub use self::intersection_test::{intersection_test, ShapeIntersection};+pub use self::nonlinear_shape_cast::{cast_shapes_nonlinear, NonlinearRigidMotion};+pub use self::point::{PointProjection, PointQuery, PointQueryWithLocation};+#[cfg(feature = "alloc")]+pub use self::query_dispatcher::PersistentQueryDispatcher;+pub use self::query_dispatcher::{QueryDispatcher, QueryDispatcherChain};+pub use self::ray::{Ray, RayCast, RayIntersection, SimdRay};+pub use self::shape_cast::{cast_shapes, ShapeCastHit, ShapeCastOptions, ShapeCastStatus};+pub use self::split::{IntersectResult, SplitResult};+pub use self::sweep_toi::{+ sweep_time_of_impact, SimplexCache, Sweep, SweepToiOutput, SweepToiStatus, ToiProxy,+};+#[cfg(feature = "alloc")]+pub use self::sweep_toi::{sweep_time_of_impact_composite, SweepCompositeFastShape};++#[cfg(all(feature = "dim3", feature = "alloc"))]+pub use self::ray::RayCullingMode;++mod clip;+pub mod closest_points;+pub mod contact;+#[cfg(feature = "alloc")]+mod contact_manifolds;+mod default_query_dispatcher;+mod distance;+#[cfg(feature = "alloc")]+pub mod epa;+mod error;+pub mod gjk;+mod intersection_test;+mod nonlinear_shape_cast;+pub mod point;+mod query_dispatcher;+mod ray;+pub mod sat;+mod shape_cast;+mod split;+pub mod sweep_toi;++/// Queries dedicated to specific pairs of shapes.+pub mod details {+ pub use super::clip::*;+ pub use super::closest_points::*;+ pub use super::contact::*;+ #[cfg(feature = "alloc")]+ pub use super::contact_manifolds::*;+ pub use super::distance::*;+ pub use super::intersection_test::*;+ pub use super::nonlinear_shape_cast::*;+ pub use super::point::*;+ pub use super::ray::*;+ pub use super::shape_cast::*;+}diff --git a/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/mod.rs b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/mod.rsnew file mode 100644index 0000000..cd77b84--- /dev/null+++ b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/mod.rs@@ -0,0 +1,152 @@+//! Nonlinear shape casting with rotation for continuous collision detection.+//!+//! This module provides **nonlinear shape casting** - detecting when and where two shapes+//! moving with both **translation and rotation** will first collide. This is essential for+//! accurate continuous collision detection (CCD) when objects are spinning or tumbling.+//!+//! # What is Nonlinear Shape Casting?+//!+//! While linear shape casting (see [`cast_shapes`](crate::query::cast_shapes)) handles objects+//! moving in straight lines, **nonlinear shape casting** accounts for rotational motion:+//!+//! - **Linear casting**: Objects translate only (constant velocity, straight path)+//! - **Nonlinear casting**: Objects both translate and rotate (curved trajectory)+//!+//! When objects rotate during motion, their effective path through space becomes nonlinear,+//! requiring more sophisticated algorithms to detect the first moment of contact.+//!+//! # When to Use Nonlinear vs Linear Shape Casting+//!+//! ## Use **Nonlinear** Shape Casting When:+//!+//! - Objects have **angular velocity** (spinning, rotating, tumbling)+//! - Accurate rotation is critical (e.g., rotating blades, tumbling debris)+//! - Objects can rotate significantly during the timestep+//! - You need physically accurate CCD for rotational motion+//!+//! ## Use **Linear** Shape Casting When:+//!+//! - Objects only translate (no rotation)+//! - Rotational effects are negligible for the timestep+//! - Performance is critical and rotation can be approximated+//! - You're implementing simple sweeping/sliding mechanics+//!+//! # Key Differences from Linear Shape Casting+//!+//! | Aspect | Linear (`cast_shapes`) | Nonlinear (`cast_shapes_nonlinear`) |+//! |--------|------------------------|--------------------------------------|+//! | **Motion** | Translation only | Translation + rotation |+//! | **Path** | Straight line | Curved (helical) trajectory |+//! | **Input** | Position + velocity | Position + velocity + angular velocity |+//! | **Complexity** | Lower (simpler math) | Higher (rotational transforms) |+//! | **Accuracy** | Perfect for non-rotating | Accurate for rotating objects |+//! | **Performance** | Faster | Slower (more iterations) |+//!+//! # Main Types+//!+//! - [`cast_shapes_nonlinear`] - Main function for nonlinear shape casting+//! - [`NonlinearRigidMotion`] - Describes an object's motion (position, velocities, rotation center)+//!+//! # Physics Background+//!+//! In rigid body physics, an object's motion has 6 degrees of freedom (3D):+//! - **3 translational**: Linear velocity in x, y, z+//! - **3 rotational**: Angular velocity around x, y, z axes+//!+//! Nonlinear shape casting simulates this complete motion to find collision times,+//! ensuring no tunneling occurs even when objects spin at high angular velocities.+//!+//! # Example: Rotating vs Non-Rotating Collision+//!+//! ```rust+//! # #[cfg(all(feature = "dim3", feature = "f32"))] {+//! use parry3d::query::{cast_shapes, cast_shapes_nonlinear, ShapeCastOptions, NonlinearRigidMotion};+//! use parry3d::shape::Cuboid;+//! use parry3d::math::{Pose, Vector};+//!+//! let cube1 = Cuboid::new(Vector::splat(1.0));+//! let cube2 = Cuboid::new(Vector::splat(0.5));+//!+//! let pos1 = Pose::translation(0.0, 0.0, 0.0);+//! let pos2 = Pose::translation(5.0, 0.0, 0.0);+//!+//! // Linear motion: cube moves right+//! let vel1 = Vector::new(1.0, 0.0, 0.0);+//! let options = ShapeCastOptions::default();+//!+//! let linear_hit = cast_shapes(&pos1, vel1, &cube1, &pos2, Vector::ZERO, &cube2, options);+//!+//! // Nonlinear motion: cube moves right AND spins around Y axis+//! let motion1 = NonlinearRigidMotion::new(+//! pos1,+//! Vector::ZERO, // rotation center+//! vel1, // linear velocity+//! Vector::new(0.0, 5.0, 0.0), // angular velocity (spinning fast)+//! );+//! let motion2 = NonlinearRigidMotion::constant_position(pos2);+//!+//! let nonlinear_hit = cast_shapes_nonlinear(+//! &motion1,+//! &cube1,+//! &motion2,+//! &cube2,+//! 0.0, // start time+//! 10.0, // end time+//! true, // stop at penetration+//! );+//!+//! // The spinning cube may collide at a different time due to rotation!+//! // Its corners sweep out a larger effective volume as it spins.+//! # }+//! ```+//!+//! # Performance Considerations+//!+//! Nonlinear shape casting is computationally more expensive than linear casting:+//!+//! - More iterations needed for convergence (curved paths harder to solve)+//! - Additional rotational transform calculations+//! - More complex geometry at each time step+//!+//! **Optimization Tips:**+//! - Use linear casting when angular velocity is near zero+//! - Keep time intervals (`end_time - start_time`) reasonably small+//! - Consider approximating slow rotations with linear motion+//!+//! # Common Use Cases+//!+//! 1. **Physics Simulations**: Accurate CCD for spinning rigid bodies+//! 2. **Game Mechanics**: Rotating blades, spinning projectiles, tumbling objects+//! 3. **Robotics**: Robotic arms with rotating joints+//! 4. **Vehicle Physics**: Rolling wheels, spinning debris from impacts+//! 5. **Animation**: Ensuring no intersections during animated rotations+//!+//! # See Also+//!+//! - [`cast_shapes`](crate::query::cast_shapes) - Linear shape casting (translation only)+//! - [`ShapeCastHit`](crate::query::ShapeCastHit) - Result structure with impact information+//! - [`contact`](crate::query::contact::contact()) - Static contact detection (no motion)++#[cfg(feature = "alloc")]+pub use self::nonlinear_shape_cast_composite_shape_shape::{+ cast_shapes_nonlinear_composite_shape_shape, cast_shapes_nonlinear_shape_composite_shape,+};+#[cfg(feature = "alloc")]+pub use self::nonlinear_shape_cast_voxels_shape::{+ cast_shapes_nonlinear_shape_voxels, cast_shapes_nonlinear_voxels_shape,+};+//pub use self::nonlinear_shape_cast_halfspace_support_map::{cast_shapes_nonlinear_halfspace_support_map, cast_shapes_nonlinear_support_map_halfspace};+pub use self::nonlinear_rigid_motion::NonlinearRigidMotion;+pub use self::nonlinear_shape_cast::cast_shapes_nonlinear;+pub use self::nonlinear_shape_cast_support_map_support_map::{+ cast_shapes_nonlinear_support_map_support_map, NonlinearShapeCastMode,+};++#[cfg(feature = "alloc")]+mod nonlinear_shape_cast_composite_shape_shape;+#[cfg(feature = "alloc")]+mod nonlinear_shape_cast_voxels_shape;+//mod cast_shapes_nonlinear_halfspace_support_map;+mod nonlinear_rigid_motion;+mod nonlinear_shape_cast;+mod nonlinear_shape_cast_support_map_support_map;diff --git a/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_rigid_motion.rs b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_rigid_motion.rsnew file mode 100644index 0000000..586c55c--- /dev/null+++ b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_rigid_motion.rs@@ -0,0 +1,570 @@+use crate::math::{Pose, Real, Vector};++/// Describes the complete motion of a rigid body with both translation and rotation.+///+/// This type represents the **6 degrees of freedom** motion of a rigid body:+/// - **3 translational** (linear velocity in x, y, z)+/// - **3 rotational** (angular velocity around x, y, z axes)+///+/// The motion is assumed to have **constant velocities** over the time interval, meaning:+/// - Linear velocity doesn't change (no acceleration)+/// - Angular velocity doesn't change (no angular acceleration)+///+/// This is used with [`cast_shapes_nonlinear`](crate::query::cast_shapes_nonlinear) to perform+/// continuous collision detection for rotating objects.+///+/// # Physics Model+///+/// At any time `t`, the object's position is computed as:+/// 1. Rotate around `local_center` by `angvel * t`+/// 2. Translate by `linvel * t`+/// 3. Apply to the starting position `start`+///+/// This creates a **helical trajectory** (螺旋軌跡) when both velocities are non-zero:+/// - Pure translation: straight line+/// - Pure rotation: circular arc+/// - Both: helix/spiral path+///+/// # Fields+///+/// * `start` - The initial position and orientation at time `t = 0`+/// * `local_center` - The point (in the shape's local coordinate system) around which+/// rotation occurs. For most cases, use the center of mass or `Vector::ZERO`.+/// * `linvel` - Linear velocity vector (units per second). Direction is the direction+/// of motion, magnitude is speed.+/// * `angvel` - Angular velocity:+/// - **2D**: Scalar rotation rate in radians/second (positive = counter-clockwise)+/// - **3D**: Axis-angle vector (direction = rotation axis, magnitude = rotation rate in radians/second)+///+/// # Example: Simple Translation+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::NonlinearRigidMotion;+/// use parry3d::math::{Pose, Vector};+///+/// // Object moving right at 5 units/second, no rotation+/// let motion = NonlinearRigidMotion::new(+/// Pose::translation(0.0, 0.0, 0.0), // start at origin+/// Vector::ZERO, // rotation center (irrelevant here)+/// Vector::new(5.0, 0.0, 0.0), // moving right+/// Vector::ZERO, // not rotating+/// );+///+/// // At t=2.0 seconds, object has moved 10 units right+/// let pos_at_2 = motion.position_at_time(2.0);+/// assert_eq!(pos_at_2.translation.x, 10.0);+/// # }+/// ```+///+/// # Example: Pure Rotation (3D)+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::NonlinearRigidMotion;+/// use parry3d::math::{Pose, Vector};+/// use std::f32::consts::PI;+///+/// // Object spinning around Y axis, no translation+/// let motion = NonlinearRigidMotion::new(+/// Pose::translation(0.0, 0.0, 0.0),+/// Vector::ZERO, // rotate around origin+/// Vector::ZERO, // not translating+/// Vector::new(0.0, PI, 0.0), // rotating around Y at π rad/s (180°/s)+/// );+///+/// // At t=1.0 second, object has rotated 180 degrees+/// let pos_at_1 = motion.position_at_time(1.0);+/// // Object is now rotated 180° around Y axis+/// # }+/// ```+///+/// # Example: Combined Translation and Rotation (Helical Path)+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::NonlinearRigidMotion;+/// use parry3d::math::{Pose, Vector};+///+/// // Spinning projectile moving forward+/// let motion = NonlinearRigidMotion::new(+/// Pose::translation(0.0, 0.0, 0.0),+/// Vector::ZERO,+/// Vector::new(10.0, 0.0, 0.0), // moving forward at 10 units/s+/// Vector::new(20.0, 0.0, 0.0), // spinning around its movement axis+/// );+///+/// // The object traces a helical path (like a bullet with rifling)+/// let pos_at_half = motion.position_at_time(0.5);+/// // Moved 5 units forward AND rotated 10 radians+/// # }+/// ```+///+/// # Example: Rotation Around Off-Center Vector+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::NonlinearRigidMotion;+/// use parry3d::math::{Pose, Vector};+///+/// // Object rotating around a point that's NOT its center+/// // Useful for: swinging weapons, rotating around pivot point, etc.+/// let motion = NonlinearRigidMotion::new(+/// Pose::translation(5.0, 0.0, 0.0), // object is at x=5+/// Vector::new(-5.0, 0.0, 0.0), // rotate around x=0 (in local space)+/// Vector::ZERO,+/// Vector::new(0.0, 1.0, 0.0), // rotate around Y axis at 1 rad/s+/// );+///+/// // The object orbits in a circle around the world origin+/// // Like a hammer being swung around+/// # }+/// ```+///+/// # Common Use Cases+///+/// 1. **Spinning Projectiles**: Bullets, thrown objects with spin+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::query::NonlinearRigidMotion;+/// # use parry3d::math::{Pose, Vector};+/// let bullet = NonlinearRigidMotion::new(+/// Pose::translation(0.0, 1.5, 0.0),+/// Vector::ZERO,+/// Vector::new(100.0, -2.0, 0.0), // fast forward, slight drop+/// Vector::new(50.0, 0.0, 0.0), // high spin rate+/// );+/// # }+/// ```+///+/// 2. **Tumbling Debris**: Objects affected by explosion or impact+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::query::NonlinearRigidMotion;+/// # use parry3d::math::{Pose, Vector};+/// let debris = NonlinearRigidMotion::new(+/// Pose::translation(0.0, 2.0, 0.0),+/// Vector::ZERO,+/// Vector::new(3.0, 5.0, -2.0), // chaotic velocity+/// Vector::new(2.0, -3.0, 1.5), // chaotic rotation+/// );+/// # }+/// ```+///+/// 3. **Rotating Machinery**: Blades, gears, rotating parts+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::query::NonlinearRigidMotion;+/// # use parry3d::math::{Pose, Vector};+/// let blade = NonlinearRigidMotion::new(+/// Pose::translation(0.0, 1.0, 0.0),+/// Vector::ZERO, // spin around center+/// Vector::ZERO, // blade doesn't translate+/// Vector::new(0.0, 10.0, 0.0), // fast rotation+/// );+/// # }+/// ```+///+/// 4. **Stationary Objects**: Use `constant_position()` for non-moving obstacles+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::query::NonlinearRigidMotion;+/// # use parry3d::math::Pose;+/// let wall = NonlinearRigidMotion::constant_position(+/// Pose::translation(10.0, 0.0, 0.0)+/// );+/// # }+/// ```+///+/// # 2D vs 3D Angular Velocity+///+/// The representation of `angvel` differs between 2D and 3D:+///+/// **2D (scalar)**:+/// - Positive value: counter-clockwise rotation+/// - Negative value: clockwise rotation+/// - Magnitude: rotation rate in radians/second+///+/// ```rust+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::query::NonlinearRigidMotion;+/// use parry2d::math::{Pose, Vector};+///+/// let motion = NonlinearRigidMotion::new(+/// Pose::translation(0.0, 0.0),+/// Vector::ZERO,+/// Vector::ZERO,+/// 3.14, // rotating counter-clockwise at π rad/s+/// );+/// # }+/// ```+///+/// **3D (axis-angle vector)**:+/// - Direction: axis of rotation (right-hand rule)+/// - Magnitude: rotation rate in radians/second+/// - Zero vector: no rotation+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::NonlinearRigidMotion;+/// use parry3d::math::{Pose, Vector};+///+/// let motion = NonlinearRigidMotion::new(+/// Pose::translation(0.0, 0.0, 0.0),+/// Vector::ZERO,+/// Vector::ZERO,+/// Vector::new(0.0, 3.14, 0.0), // rotate around Y axis at π rad/s+/// );+/// # }+/// ```+///+/// # Important Notes+///+/// 1. **Local vs World Space**: The `local_center` must be in the **shape's local+/// coordinate system**, not world space. For a shape centered at origin,+/// use `Vector::ZERO`.+///+/// 2. **Angular Velocity Units**: Always use **radians per second**, not degrees!+/// - To convert: `degrees * (PI / 180.0) = radians`+/// - Example: 90°/s = `90.0 * (PI / 180.0)` ≈ 1.571 rad/s+///+/// 3. **Constant Velocities**: This assumes velocities don't change over time.+/// For physics simulations with acceleration/forces, you typically:+/// - Compute motion for a single small timestep (e.g., 1/60 second)+/// - Update velocities after each step+/// - Create new `NonlinearRigidMotion` for next timestep+///+/// 4. **Center of Mass**: For realistic physics, `local_center` should be the+/// shape's center of mass. For simple cases, `Vector::ZERO` often works.+///+/// # See Also+///+/// - [`cast_shapes_nonlinear`](crate::query::cast_shapes_nonlinear) - Uses this type for collision detection+/// - [`cast_shapes`](crate::query::cast_shapes) - Linear motion (no rotation)+/// - [`position_at_time`](Self::position_at_time) - Compute position at any time+#[derive(Debug, Copy, Clone)]+pub struct NonlinearRigidMotion {+ /// The starting isometry at `t = 0`.+ pub start: Pose,+ /// The local-space point at which the rotational part of this motion is applied.+ pub local_center: Vector,+ /// The translational velocity of this motion.+ pub linvel: Vector,+ /// The angular velocity of this motion.+ #[cfg(feature = "dim2")]+ pub angvel: Real,+ /// The angular velocity of this motion.+ #[cfg(feature = "dim3")]+ pub angvel: Vector,+}++impl NonlinearRigidMotion {+ /// Creates a new rigid motion from a starting position and velocities.+ ///+ /// # Arguments+ ///+ /// * `start` - Initial position and orientation at time `t = 0`+ /// * `local_center` - Vector (in local coordinates) around which rotation occurs+ /// * `linvel` - Linear velocity vector (units per second)+ /// * `angvel` - Angular velocity (2D: radians/sec scalar, 3D: axis-angle vector)+ ///+ /// # Example (2D)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::query::NonlinearRigidMotion;+ /// use parry2d::math::{Pose, Vector};+ /// use std::f32::consts::PI;+ ///+ /// // Object moving right and rotating counter-clockwise+ /// let motion = NonlinearRigidMotion::new(+ /// Pose::translation(0.0, 0.0),+ /// Vector::ZERO,+ /// Vector::new(5.0, 0.0), // 5 units/sec to the right+ /// PI, // π rad/sec counter-clockwise+ /// );+ /// # }+ /// ```+ ///+ /// # Example (3D)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::NonlinearRigidMotion;+ /// use parry3d::math::{Pose, Vector};+ ///+ /// // Object moving forward and spinning around its movement axis+ /// let motion = NonlinearRigidMotion::new(+ /// Pose::translation(0.0, 0.0, 0.0),+ /// Vector::ZERO,+ /// Vector::new(10.0, 0.0, 0.0), // moving forward+ /// Vector::new(5.0, 0.0, 0.0), // spinning around X axis+ /// );+ /// # }+ /// ```+ #[cfg(feature = "dim2")]+ pub fn new(start: Pose, local_center: Vector, linvel: Vector, angvel: Real) -> Self {+ NonlinearRigidMotion {+ start,+ local_center,+ linvel,+ angvel,+ }+ }++ /// Creates a new rigid motion from a starting position and velocities.+ ///+ /// # Arguments+ ///+ /// * `start` - Initial position and orientation at time `t = 0`+ /// * `local_center` - Vector (in local coordinates) around which rotation occurs+ /// * `linvel` - Linear velocity vector (units per second)+ /// * `angvel` - Angular velocity as axis-angle vector (radians per second)+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::NonlinearRigidMotion;+ /// use parry3d::math::{Pose, Vector};+ ///+ /// // Object moving forward and spinning around its movement axis+ /// let motion = NonlinearRigidMotion::new(+ /// Pose::translation(0.0, 0.0, 0.0),+ /// Vector::ZERO,+ /// Vector::new(10.0, 0.0, 0.0), // moving forward+ /// Vector::new(5.0, 0.0, 0.0), // spinning around X axis+ /// );+ /// # }+ /// ```+ #[cfg(feature = "dim3")]+ pub fn new(start: Pose, local_center: Vector, linvel: Vector, angvel: Vector) -> Self {+ NonlinearRigidMotion {+ start,+ local_center,+ linvel,+ angvel,+ }+ }++ /// Creates a stationary motion at the origin (identity transformation).+ ///+ /// Equivalent to `constant_position(Pose::identity())`.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::NonlinearRigidMotion;+ ///+ /// let stationary = NonlinearRigidMotion::identity();+ /// // Object stays at origin with no rotation, forever+ /// # }+ /// ```+ pub fn identity() -> Self {+ Self::constant_position(Pose::IDENTITY)+ }++ /// Creates a motion that stays at a constant position (no translation, no rotation).+ ///+ /// Useful for representing static/stationary objects in collision queries.+ /// Both linear and angular velocities are set to zero.+ ///+ /// # Arguments+ ///+ /// * `pos` - The fixed position and orientation+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::NonlinearRigidMotion;+ /// use parry3d::math::Pose;+ ///+ /// // A wall that never moves+ /// let wall_motion = NonlinearRigidMotion::constant_position(+ /// Pose::translation(10.0, 0.0, 0.0)+ /// );+ ///+ /// // At any time t, position is always (10, 0, 0)+ /// let pos_at_5 = wall_motion.position_at_time(5.0);+ /// assert_eq!(pos_at_5.translation.x, 10.0);+ /// # }+ /// ```+ pub fn constant_position(pos: Pose) -> Self {+ Self {+ start: pos,+ linvel: Vector::ZERO,+ #[cfg(feature = "dim2")]+ angvel: 0.0,+ #[cfg(feature = "dim3")]+ angvel: Vector::ZERO,+ local_center: Vector::ZERO,+ }+ }++ fn set_start(&mut self, new_start: Pose) {+ // NOTE: we need to adjust the local_center so that the angular+ // velocity is still expressed wrt. the original center.+ self.local_center = new_start.inverse_transform_point(self.start * self.local_center);+ self.start = new_start;+ }++ /// Freezes this motion at a specific time, making it stationary from that point forward.+ ///+ /// After calling this method:+ /// - `self.start` is updated to the position at time `t`+ /// - Both velocities are set to zero+ /// - All future calls to `position_at_time()` return the same frozen position+ ///+ /// This is useful for "stopping" an object mid-motion, or capturing a specific+ /// moment in a motion trajectory.+ ///+ /// # Arguments+ ///+ /// * `t` - The time at which to freeze the motion+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::NonlinearRigidMotion;+ /// use parry3d::math::{Pose, Vector};+ ///+ /// let mut motion = NonlinearRigidMotion::new(+ /// Pose::translation(0.0, 0.0, 0.0),+ /// Vector::ZERO,+ /// Vector::new(5.0, 0.0, 0.0), // moving right+ /// Vector::ZERO,+ /// );+ ///+ /// // Freeze at t=2.0 (when object is at x=10)+ /// motion.freeze(2.0);+ ///+ /// // Now position is constant at x=10, regardless of time+ /// let pos_at_100 = motion.position_at_time(100.0);+ /// assert_eq!(pos_at_100.translation.x, 10.0);+ /// # }+ /// ```+ pub fn freeze(&mut self, t: Real) {+ self.start = self.position_at_time(t);+ self.linvel = Vector::ZERO;+ #[cfg(feature = "dim2")]+ {+ self.angvel = 0.0;+ }+ #[cfg(feature = "dim3")]+ {+ self.angvel = Vector::ZERO;+ }+ }++ /// Appends a constant translation to this rigid-motion.+ #[must_use]+ pub fn append_translation(&self, tra: Vector) -> Self {+ let mut result = *self;+ result.set_start(Pose::from_translation(tra) * result.start);+ result+ }++ /// Prepends a constant translation to this rigid-motion.+ #[must_use]+ pub fn prepend_translation(&self, tra: Vector) -> Self {+ let mut result = *self;+ result.set_start(result.start * Pose::from_translation(tra));+ result+ }++ /// Appends a constant isometry to this rigid-motion.+ #[must_use]+ pub fn append(&self, iso: Pose) -> Self {+ let mut result = *self;+ result.set_start(iso * result.start);+ result+ }++ /// Prepends a constant translation to this rigid-motion.+ #[must_use]+ pub fn prepend(&self, iso: Pose) -> Self {+ let mut result = *self;+ result.set_start(result.start * iso);+ result+ }++ /// Computes the position and orientation at a given time.+ ///+ /// Returns the full isometry (position + orientation) of the rigid body at time `t`,+ /// accounting for both translation and rotation from the starting position.+ ///+ /// The computation follows this sequence:+ /// 1. Rotate around `local_center` by angle `angvel * t`+ /// 2. Translate by displacement `linvel * t`+ /// 3. Apply to the starting position `start`+ ///+ /// # Arguments+ ///+ /// * `t` - Time value (typically in seconds, matching your velocity units)+ ///+ /// # Returns+ ///+ /// The complete transformation (position and orientation) at time `t`.+ ///+ /// # Example: Tracking a Moving Object+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::NonlinearRigidMotion;+ /// use parry3d::math::{Pose, Vector};+ ///+ /// let motion = NonlinearRigidMotion::new(+ /// Pose::translation(0.0, 0.0, 0.0),+ /// Vector::ZERO,+ /// Vector::new(3.0, 0.0, 0.0), // 3 units/sec to the right+ /// Vector::new(0.0, 1.0, 0.0), // 1 radian/sec around Y axis+ /// );+ ///+ /// // Position at t=0+ /// let pos_0 = motion.position_at_time(0.0);+ /// assert_eq!(pos_0.translation.x, 0.0);+ ///+ /// // Position at t=2.0 seconds+ /// let pos_2 = motion.position_at_time(2.0);+ /// // Object has moved 6 units to the right+ /// assert!((pos_2.translation.x - 6.0).abs() < 0.01);+ /// // And rotated 2 radians around Y+ /// # }+ /// ```+ ///+ /// # Example: Animation Frame+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::NonlinearRigidMotion;+ /// use parry3d::math::{Pose, Vector};+ ///+ /// let motion = NonlinearRigidMotion::new(+ /// Pose::translation(0.0, 5.0, 0.0),+ /// Vector::ZERO,+ /// Vector::new(0.0, -9.8, 0.0), // falling (gravity)+ /// Vector::new(1.0, 2.0, 0.5), // tumbling+ /// );+ ///+ /// // Render at 60 FPS+ /// let dt = 1.0 / 60.0;+ /// for frame in 0..60 {+ /// let t = frame as f32 * dt;+ /// let pos = motion.position_at_time(t);+ /// // Use `pos` to render object at this frame+ /// }+ /// # }+ /// ```+ pub fn position_at_time(&self, t: Real) -> Pose {+ let center = self.start * self.local_center;+ let shift = Pose::from_translation(center);+ (shift * Pose::new(self.linvel * t, self.angvel * t)) * (shift.inverse() * self.start)+ }+}diff --git a/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast.rs b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast.rsnew file mode 100644index 0000000..a910189--- /dev/null+++ b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast.rs@@ -0,0 +1,267 @@+use crate::math::Real;+use crate::query::{+ DefaultQueryDispatcher, NonlinearRigidMotion, QueryDispatcher, ShapeCastHit, Unsupported,+};+use crate::shape::Shape;++/// Computes when two shapes moving with translation and rotation will first collide.+///+/// This function performs **nonlinear shape casting** - finding the time of impact (TOI) for+/// two shapes that are both translating and rotating. Unlike linear shape casting which only+/// handles straight-line motion, this accounts for the curved trajectories created by rotation.+///+/// # What This Function Does+///+/// Given two shapes with complete rigid body motion (position, linear velocity, and angular+/// velocity), this function finds:+/// - **When** they will first touch (time of impact)+/// - **Where** they touch (witness points)+/// - **How** they touch (contact normals)+///+/// The function solves a complex nonlinear root-finding problem to determine the exact moment+/// when the shapes' minimum distance reaches zero (or a target threshold).+///+/// # How It Differs from Linear Shape Casting+///+/// | Feature | Linear (`cast_shapes`) | Nonlinear (`cast_shapes_nonlinear`) |+/// |---------|------------------------|--------------------------------------|+/// | **Motion type** | Translation only | Translation + rotation |+/// | **Trajectory** | Straight line | Curved (helical path) |+/// | **Input** | Position + velocity | Full rigid motion (position + velocities + angular vel) |+/// | **Use case** | Sliding, sweeping | Spinning, tumbling, realistic physics |+/// | **Performance** | Faster | Slower (more complex) |+///+/// # Arguments+///+/// * `motion1` - Complete motion description for shape 1 ([`NonlinearRigidMotion`])+/// - Starting position and orientation+/// - Linear velocity (translation)+/// - Angular velocity (rotation)+/// - Local center of rotation+/// * `g1` - The first shape geometry+/// * `motion2` - Complete motion description for shape 2+/// * `g2` - The second shape geometry+/// * `start_time` - Beginning of time interval to check (typically `0.0`)+/// * `end_time` - End of time interval to check (e.g., your physics timestep)+/// * `stop_at_penetration` - Controls behavior when shapes start penetrating:+/// - `true`: Returns immediately with `time_of_impact = start_time`+/// - `false`: Checks if they're separating; if so, looks for later impacts+///+/// # The `stop_at_penetration` Parameter+///+/// This parameter is crucial for handling initially-penetrating shapes:+///+/// - **`true` (recommended for most cases)**: If shapes overlap at `start_time`, immediately+/// return a hit at `start_time`. This is safer and prevents tunneling.+///+/// - **`false` (advanced)**: If shapes overlap at `start_time` BUT are moving apart (separating+/// velocity), ignore this initial penetration and search for a later collision that could+/// cause tunneling. Use this when you have external penetration resolution and only care+/// about future impacts.+///+/// # Returns+///+/// * `Ok(Some(hit))` - Collision detected, see [`ShapeCastHit`] for impact details+/// - `time_of_impact`: When collision occurs (in `[start_time, end_time]`)+/// - `witness1`, `witness2`: Contact points on each shape (local space)+/// - `normal1`, `normal2`: Contact normals on each shape (local space)+/// - `status`: Algorithm convergence status+/// * `Ok(None)` - No collision within the time interval+/// * `Err(Unsupported)` - This shape pair is not supported for nonlinear casting+///+/// # Example: Basic Spinning Collision+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{cast_shapes_nonlinear, NonlinearRigidMotion};+/// use parry3d::shape::Ball;+/// use parry3d::math::{Pose, Vector};+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+///+/// // Ball 1: moving right AND spinning around Y axis+/// let motion1 = NonlinearRigidMotion::new(+/// Pose::translation(0.0, 0.0, 0.0), // start position+/// Vector::ZERO, // rotation center (local space)+/// Vector::new(2.0, 0.0, 0.0), // moving right at speed 2+/// Vector::new(0.0, 10.0, 0.0), // spinning around Y axis+/// );+///+/// // Ball 2: stationary at x=10+/// let motion2 = NonlinearRigidMotion::constant_position(+/// Pose::translation(10.0, 0.0, 0.0)+/// );+///+/// let result = cast_shapes_nonlinear(+/// &motion1, &ball1,+/// &motion2, &ball2,+/// 0.0, // start at t=0+/// 10.0, // check up to t=10+/// true, // stop if initially penetrating+/// );+///+/// if let Ok(Some(hit)) = result {+/// println!("Collision at time: {}", hit.time_of_impact);+/// println!("Contact point on ball1: {:?}", hit.witness1);+/// println!("Contact normal on ball1: {:?}", hit.normal1);+/// }+/// # }+/// ```+///+/// # Example: Tumbling Box vs Stationary Wall+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{cast_shapes_nonlinear, NonlinearRigidMotion};+/// use parry3d::shape::Cuboid;+/// use parry3d::math::{Pose, Vector};+///+/// // A cuboid tumbling through space+/// let cube = Cuboid::new(Vector::new(0.5, 0.5, 0.5));+///+/// // Large wall (very wide cuboid)+/// let wall = Cuboid::new(Vector::new(10.0, 10.0, 0.1));+///+/// // Cube falling and tumbling+/// let motion_cube = NonlinearRigidMotion::new(+/// Pose::translation(0.0, 5.0, 0.0), // starting 5 units above+/// Vector::ZERO, // rotate around center+/// Vector::new(0.0, -2.0, 0.0), // falling down+/// Vector::new(1.0, 0.5, 2.0), // tumbling (complex rotation)+/// );+///+/// // Wall is stationary+/// let motion_wall = NonlinearRigidMotion::constant_position(+/// Pose::translation(0.0, 0.0, 0.0)+/// );+///+/// let result = cast_shapes_nonlinear(+/// &motion_cube, &cube,+/// &motion_wall, &wall,+/// 0.0,+/// 5.0, // check 5 seconds of motion+/// true,+/// );+///+/// if let Ok(Some(hit)) = result {+/// // Cube will hit wall while tumbling+/// // Time depends on both falling speed and rotation+/// println!("Tumbling cube hits wall at t = {}", hit.time_of_impact);+/// }+/// # }+/// ```+///+/// # Example: Handling Initial Penetration+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{cast_shapes_nonlinear, NonlinearRigidMotion};+/// use parry3d::shape::Ball;+/// use parry3d::math::{Pose, Vector};+///+/// let ball1 = Ball::new(2.0);+/// let ball2 = Ball::new(2.0);+///+/// // Balls overlapping (3 units apart, but radii sum to 4)+/// let motion1 = NonlinearRigidMotion::new(+/// Pose::translation(0.0, 0.0, 0.0),+/// Vector::ZERO,+/// Vector::new(-1.0, 0.0, 0.0), // moving AWAY from ball2+/// Vector::ZERO,+/// );+///+/// let motion2 = NonlinearRigidMotion::constant_position(+/// Pose::translation(3.0, 0.0, 0.0)+/// );+///+/// // With stop_at_penetration = true+/// let result_stop = cast_shapes_nonlinear(+/// &motion1, &ball1, &motion2, &ball2,+/// 0.0, 10.0, true, // STOP at penetration+/// );+/// // Returns Some(hit) with time_of_impact = 0.0+///+/// // With stop_at_penetration = false+/// let result_continue = cast_shapes_nonlinear(+/// &motion1, &ball1, &motion2, &ball2,+/// 0.0, 10.0, false, // DON'T stop - they're separating+/// );+/// // Returns None - shapes are moving apart, no future impact+/// # }+/// ```+///+/// # When to Use This vs Linear Shape Casting+///+/// **Use `cast_shapes_nonlinear` when:**+/// - Objects have significant angular velocity+/// - Rotation accuracy matters (spinning blades, tumbling debris)+/// - Physics simulation with full 6-DOF motion+/// - Objects can rotate > 10-15 degrees during timestep+///+/// **Use `cast_shapes` (linear) when:**+/// - Objects don't rotate (angular velocity ≈ 0)+/// - Rotation is negligible for your timestep+/// - Performance is critical+/// - Implementing simple sweep/slide mechanics+///+/// # Performance Considerations+///+/// Nonlinear shape casting is significantly more expensive than linear:+/// - **Iterative root-finding**: Multiple evaluations to converge+/// - **Rotational transforms**: Matrix operations at each evaluation+/// - **Complex geometry**: Shape changes orientation during motion+///+/// Typical cost: 3-10x slower than linear shape casting, depending on:+/// - Shape complexity (balls faster than meshes)+/// - Angular velocity magnitude (faster rotation = more iterations)+/// - Time interval length (longer intervals may need more precision)+///+/// # Algorithm Notes+///+/// The implementation uses conservative root-finding algorithms that:+/// - Guarantee no false negatives (won't miss collisions)+/// - May require multiple iterations to converge+/// - Handle degenerate cases (parallel surfaces, grazing contact)+/// - Account for numerical precision limits+///+/// # Common Pitfalls+///+/// 1. **Units**: Ensure time, velocity, and angular velocity units match+/// - If time is in seconds, velocity should be units/second+/// - Angular velocity in radians/second (not degrees!)+///+/// 2. **Time interval**: Keep `end_time - start_time` reasonable+/// - Very large intervals may miss fast rotations+/// - Typical: use your physics timestep (e.g., 1/60 second)+///+/// 3. **Rotation center**: `local_center` in [`NonlinearRigidMotion`] must be in+/// the shape's local coordinate system, not world space+///+/// 4. **Initial penetration**: Understand `stop_at_penetration` behavior for your use case+///+/// # See Also+///+/// - [`NonlinearRigidMotion`] - Describes an object's complete motion+/// - [`cast_shapes`](crate::query::cast_shapes) - Linear shape casting (no rotation)+/// - [`ShapeCastHit`] - Result structure+/// - [`contact`](crate::query::contact::contact()) - Static contact queries (no motion)+pub fn cast_shapes_nonlinear(+ motion1: &NonlinearRigidMotion,+ g1: &dyn Shape,+ motion2: &NonlinearRigidMotion,+ g2: &dyn Shape,+ start_time: Real,+ end_time: Real,+ stop_at_penetration: bool,+) -> Result<Option<ShapeCastHit>, Unsupported> {+ DefaultQueryDispatcher.cast_shapes_nonlinear(+ motion1,+ g1,+ motion2,+ g2,+ start_time,+ end_time,+ stop_at_penetration,+ )+}diff --git a/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast_composite_shape_shape.rs b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast_composite_shape_shape.rsnew file mode 100644index 0000000..de5a825--- /dev/null+++ b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast_composite_shape_shape.rs@@ -0,0 +1,145 @@+use crate::math::Real;+use crate::partitioning::BvhNode;+use crate::query::{+ self, details::NonlinearShapeCastMode, NonlinearRigidMotion, QueryDispatcher, ShapeCastHit,+};+use crate::shape::{Ball, CompositeShapeRef, Shape, SubShapeId, TypedCompositeShape};++impl<S: ?Sized + TypedCompositeShape> CompositeShapeRef<'_, S> {+ /// Performs a non-linear shape-cast between `self` animated subject to the `motion1` and+ /// the `shape2` subject to the `motion2`.+ ///+ /// Returns the index of the sub-shape of `self` that was involved alongside the hit, which is+ /// left as that sub-shape reported it (its `subshape1` is the sub-shape's own when it is a+ /// composite too, and `subshape2` is `shape2`'s).+ pub fn cast_shape_nonlinear<D: ?Sized + QueryDispatcher>(+ &self,+ dispatcher: &D,+ motion1: &NonlinearRigidMotion,+ motion2: &NonlinearRigidMotion,+ shape2: &dyn Shape,+ start_time: Real,+ end_time: Real,+ stop_at_penetration: bool,+ ) -> Option<(SubShapeId, ShapeCastHit)> {+ let sphere2 = shape2.compute_local_bounding_sphere();++ self.0.bvh().find_best(+ end_time,+ |node: &BvhNode, _| {+ let aabb1 = node.aabb();+ let center1 = aabb1.center();+ let radius1 = aabb1.half_extents().length();+ let ball1 = Ball::new(radius1);+ let ball2 = Ball::new(sphere2.radius());+ let ball_motion1 = motion1.prepend_translation(center1);+ let ball_motion2 = motion2.prepend_translation(sphere2.center);++ query::details::cast_shapes_nonlinear_support_map_support_map(+ dispatcher,+ &ball_motion1,+ &ball1,+ &ball1,+ &ball_motion2,+ &ball2,+ &ball2,+ start_time,+ end_time,+ NonlinearShapeCastMode::StopAtPenetration,+ )+ .map(|hit| hit.time_of_impact)+ .unwrap_or(Real::MAX)+ },+ |part_id, _| {+ self.0+ .map_untyped_part_at(part_id, |part_pos1, part_shape1, _| {+ if let Some(part_pos1) = part_pos1 {+ dispatcher+ .cast_shapes_nonlinear(+ &motion1.prepend(*part_pos1),+ part_shape1,+ motion2,+ shape2,+ start_time,+ end_time,+ stop_at_penetration,+ )+ .ok()?+ .map(|hit| hit.transform1_by(part_pos1))+ } else {+ dispatcher+ .cast_shapes_nonlinear(+ motion1,+ part_shape1,+ motion2,+ shape2,+ start_time,+ end_time,+ stop_at_penetration,+ )+ .ok()?+ }+ })?+ },+ )+ }+}++/// Time Of Impact of a composite shape with any other shape, under a rigid motion (translation + rotation).+pub fn cast_shapes_nonlinear_composite_shape_shape<D, G1>(+ dispatcher: &D,+ motion1: &NonlinearRigidMotion,+ shape1: &G1,+ motion2: &NonlinearRigidMotion,+ shape2: &dyn Shape,+ start_time: Real,+ end_time: Real,+ stop_at_penetration: bool,+) -> Option<ShapeCastHit>+where+ D: ?Sized + QueryDispatcher,+ G1: ?Sized + TypedCompositeShape,+{+ CompositeShapeRef(shape1)+ .cast_shape_nonlinear(+ dispatcher,+ motion1,+ motion2,+ shape2,+ start_time,+ end_time,+ stop_at_penetration,+ )+ .map(|(part_id, mut hit)| {+ hit.subshape1 = part_id;+ hit+ })+}++/// Time Of Impact of any shape with a composite shape, under a rigid motion (translation + rotation).+pub fn cast_shapes_nonlinear_shape_composite_shape<D, G2>(+ dispatcher: &D,+ motion1: &NonlinearRigidMotion,+ shape1: &dyn Shape,+ motion2: &NonlinearRigidMotion,+ shape2: &G2,+ start_time: Real,+ end_time: Real,+ stop_at_penetration: bool,+) -> Option<ShapeCastHit>+where+ D: ?Sized + QueryDispatcher,+ G2: ?Sized + TypedCompositeShape,+{+ cast_shapes_nonlinear_composite_shape_shape(+ dispatcher,+ motion2,+ shape2,+ motion1,+ shape1,+ start_time,+ end_time,+ stop_at_penetration,+ )+ .map(|hit| hit.swapped())+}diff --git a/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast_halfspace_support_map.rs b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast_halfspace_support_map.rsnew file mode 100644index 0000000..9e24f54--- /dev/null+++ b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast_halfspace_support_map.rs@@ -0,0 +1,42 @@+use crate::math::ComplexField;++use crate::math::{Pose, Real, Vector};+use crate::query::{Ray, RayCast};+use crate::shape::HalfSpace;+use crate::shape::SupportMap;++/// Time Of Impact of a halfspace with a support-mapped shape under a rigid motion (translation + rotation).+pub fn cast_shapes_nonlinear_halfspace_support_map<G: ?Sized + SupportMap>(+ pos12: &Pose,+ vel12: Vector,+ halfspace: &HalfSpace,+ other: &G,+) -> Option {+ /*+ let halfspace_normal = mhalfspace * halfspace.normal();+ let mut curr = 0.0;+++ loop {+ let curr_mother = mother.advance(dvel);+ let closest_point = other.support_point(curr_mother, &-halfspace_normal);++ }++ let vel = *vel_other - *vel_halfspace;+ let closest_point = other.support_point(mother, &-halfspace_normal);++ halfspace.cast_ray(mhalfspace, &Ray::new(closest_point, vel), true)+ */+ unimplemented!()+}++/// Time Of Impact of a halfspace with a support-mapped shape under a rigid motion (translation + rotation).+pub fn cast_shapes_nonlinear_support_map_halfspace<G: ?Sized + SupportMap>(+ pos12: &Pose,+ vel12: Vector,+ other: &G,+ halfspace: &HalfSpace,+) -> Option {+ cast_shapes_nonlinear_halfspace_support_map(pos12, vel12, halfspace, other)+}diff --git a/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast_support_map_support_map.rs b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast_support_map_support_map.rsnew file mode 100644index 0000000..36f4025--- /dev/null+++ b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast_support_map_support_map.rs@@ -0,0 +1,507 @@+use crate::math::{Real, RealField, Vector};+use crate::query::{+ self, ClosestPoints, NonlinearRigidMotion, QueryDispatcher, ShapeCastHit, ShapeCastStatus,+};+use crate::shape::{Shape, SupportMap};+use crate::utils::WCross;++use crate::query::gjk::ConstantPoint;+use num::Bounded;++/// Enum specifying the behavior of shape-casting when there is a penetration at the starting time.+#[derive(Copy, Clone, Debug)]+pub enum NonlinearShapeCastMode {+ /// Stop shape-casting as soon as there is a penetration.+ StopAtPenetration,+ /// When there is a penetration, don't stop the shape-cast if the relative velocity+ /// at the penetration points is negative (i.e. if the points are separating).+ Directional {+ /// The sum of the `Shape::ccd_thickness` of both shapes involved in the shape-cast.+ sum_linear_thickness: Real,+ /// The max of the `Shape::ccd_angular_thickness` of both shapes involved in the shape-cast.+ max_angular_thickness: Real,+ },+}++impl NonlinearShapeCastMode {+ /// Initializes a directional `NonlinearShapeCastMode`.+ ///+ /// With the "directional" shape-cast mode, the nonlinear shape-casting won't+ /// immediately stop if the shapes are already intersecting at `t = 0`.+ /// Instead, it will search for the first time when a contact between+ /// the shapes would result in a deeper penetration (with risk of tunnelling).+ /// This effectively checks the relative velocity of the shapes at their point+ /// of impact.+ pub fn directional_toi<S1, S2>(shape1: &S1, shape2: &S2) -> Self+ where+ S1: ?Sized + Shape,+ S2: ?Sized + Shape,+ {+ let sum_linear_thickness = shape1.ccd_thickness() + shape2.ccd_thickness();+ let max_angular_thickness = shape1+ .ccd_angular_thickness()+ .max(shape2.ccd_angular_thickness());++ NonlinearShapeCastMode::Directional {+ sum_linear_thickness,+ max_angular_thickness,+ }+ }+}++/// Compute the time of first impact between two support-map shapes following+/// a nonlinear (with translations and rotations) motion.+pub fn cast_shapes_nonlinear_support_map_support_map<D, SM1, SM2>(+ dispatcher: &D,+ motion1: &NonlinearRigidMotion,+ sm1: &SM1,+ g1: &dyn Shape,+ motion2: &NonlinearRigidMotion,+ sm2: &SM2,+ g2: &dyn Shape,+ start_time: Real,+ end_time: Real,+ mode: NonlinearShapeCastMode,+) -> Option<ShapeCastHit>+where+ D: ?Sized + QueryDispatcher,+ SM1: ?Sized + SupportMap,+ SM2: ?Sized + SupportMap,+{+ let sphere1 = g1.compute_local_bounding_sphere();+ let sphere2 = g2.compute_local_bounding_sphere();++ // Use the shape with the largest radius as the first shape.+ // This will give better convergence because everything will+ // be expressed in the local-space as that first shape (including+ // the separating axes used in the bisection).+ if sphere1.radius >= sphere2.radius {+ compute_toi(+ dispatcher, motion1, sm1, g1, motion2, sm2, g2, start_time, end_time, mode,+ )+ } else {+ compute_toi(+ dispatcher, motion2, sm2, g2, motion1, sm1, g1, start_time, end_time, mode,+ )+ .map(|hit| hit.swapped())+ }+}++/// Time of impacts between two support-mapped shapes under a rigid motion.+pub fn compute_toi<D, SM1, SM2>(+ dispatcher: &D,+ motion1: &NonlinearRigidMotion,+ sm1: &SM1,+ g1: &dyn Shape,+ motion2: &NonlinearRigidMotion,+ sm2: &SM2,+ g2: &dyn Shape,+ start_time: Real,+ end_time: Real,+ mode: NonlinearShapeCastMode,+) -> Option<ShapeCastHit>+where+ D: ?Sized + QueryDispatcher,+ SM1: ?Sized + SupportMap,+ SM2: ?Sized + SupportMap,+{+ let mut prev_min_t = start_time;+ let abs_tol: Real = query::gjk::eps_tol();++ let mut result = ShapeCastHit {+ time_of_impact: start_time,+ normal1: Vector::X,+ normal2: Vector::X,+ witness1: Vector::ZERO,+ witness2: Vector::ZERO,+ status: ShapeCastStatus::PenetratingOrWithinTargetDist,+ subshape1: 0,+ subshape2: 0,+ };++ loop {+ let pos1 = motion1.position_at_time(result.time_of_impact);+ let pos2 = motion2.position_at_time(result.time_of_impact);+ let pos12 = pos1.inv_mul(&pos2);++ // TODO: use the _with_params version of the closest points query.+ match dispatcher+ .closest_points(&pos12, g1, g2, Bounded::max_value())+ .ok()?+ {+ ClosestPoints::Intersecting => {+ // println!(">> Intersecting.");+ if result.time_of_impact == start_time {+ result.status = ShapeCastStatus::PenetratingOrWithinTargetDist+ } else {+ result.status = ShapeCastStatus::Failed;+ }+ break;+ }+ ClosestPoints::WithinMargin(p1, p2) => {+ // println!(">> Within margin.");+ result.witness1 = p1;+ result.witness2 = p2;++ let (normal1, dist) = (pos12 * p2 - p1).normalize_and_length();+ if dist >= crate::math::DEFAULT_EPSILON {+ // TODO: do the "inverse transform unit vector" only when we are about to return.+ result.normal1 = normal1;+ result.normal2 = pos12.rotation.inverse() * -normal1;++ let curr_range = BisectionRange {+ min_t: result.time_of_impact,+ max_t: end_time,+ curr_t: result.time_of_impact,+ };++ let (new_range, niter) =+ bisect(dist, motion1, sm1, motion2, sm2, normal1, curr_range);+ // println!(+ // "Bisection result: {:?}, normal1: {:?}, normal2: {:?}",+ // new_range, result.normal1, result.normal2+ // );+ result.time_of_impact = new_range.curr_t;++ if new_range.min_t - prev_min_t < abs_tol {+ if new_range.max_t == end_time {+ // Check the configuration at max_t to see if the object are not disjoint.+ // NOTE: could we do this earlier, before the above loop?+ // It feels like this could prevent catching some corner-cases like+ // if one object is rotated by almost 180 degrees while the other is immobile.+ let pos1 = motion1.position_at_time(new_range.max_t);+ let pos2 = motion2.position_at_time(new_range.max_t);+ let pos12 = pos1.inv_mul(&pos2);++ let pt1 = sm1.local_support_point_toward(normal1);+ let pt2 = sm2.support_point_toward(&pos12, -normal1);++ if (pt2 - pt1).dot(normal1) > 0.0 {+ // We found an axis that separate both objects at the end configuration.+ return None;+ }+ }++ result.status = ShapeCastStatus::Converged;+ break;+ }++ prev_min_t = new_range.min_t;++ if niter == 0 {+ result.status = ShapeCastStatus::Converged;+ break;+ }+ } else {+ result.status = ShapeCastStatus::Failed;+ break;+ }+ }+ ClosestPoints::Disjoint => {+ // TODO: this case should be unreachable and needs some debugging+ // see: https://github.com/dimforge/parry/issues/176+ log::debug!(+ "Closest points not found despite setting the max distance to infinity."+ );+ result.status = ShapeCastStatus::Failed;+ break;+ }+ }+ }++ // In we started with a penetration, we need to compute a full contact manifold and+ // see if any of these contact points may result in tunnelling. If the is one, return+ // that time of impact instead. That way, object moving tangentially on a surface (always keeping+ // a contact with it) won't report an useless impact.+ //+ // Note that this must be done here instead of outside of the `cast_shapes_nonlinear`+ // function so that this works properly with composite shapes.+ match mode {+ NonlinearShapeCastMode::Directional {+ sum_linear_thickness,+ max_angular_thickness,+ } => {+ if (result.time_of_impact - start_time).abs() < 1.0e-5 {+ handle_penetration_at_start_time(+ dispatcher,+ motion1,+ sm1,+ g1,+ motion2,+ sm2,+ g2,+ start_time,+ end_time,+ sum_linear_thickness,+ max_angular_thickness,+ )+ } else {+ Some(result)+ }+ }+ NonlinearShapeCastMode::StopAtPenetration => Some(result),+ }+}++fn handle_penetration_at_start_time<D, SM1, SM2>(+ dispatcher: &D,+ motion1: &NonlinearRigidMotion,+ sm1: &SM1,+ g1: &dyn Shape,+ motion2: &NonlinearRigidMotion,+ sm2: &SM2,+ g2: &dyn Shape,+ start_time: Real,+ end_time: Real,+ sum_linear_thickness: Real,+ max_angular_thickness: Real,+) -> Option<ShapeCastHit>+where+ D: ?Sized + QueryDispatcher,+ SM1: ?Sized + SupportMap,+ SM2: ?Sized + SupportMap,+{+ // Because we are doing non-linear CCD, we need an iterative method here.+ // First we need to check if the `time_of_impact = start_time` is legitimate, i.e.,+ // if tunnelling will happen if we don't clamp the motion.+ //+ // If the contact isn't "legitimate" (i.e. if we have a separating velocity),+ // then we need to check by how much the bodies can move without tunnelling.+ // With linear CCD it's easy: any linear movement is OK because we have+ // a separating velocity.+ //+ // With non-linear CCD it's more complicated because we need to take the+ // angular velocity into account, which will result in new contact points+ // that could tunnel (imagine for example 2D cuboid touching the ground at one+ // point. By rotating, its second end point will end up touching the ground too,+ // and we need to detect that so we don't permit a rotation larger than what's+ // needed for this second contact to happen).+ //+ // The iterative method here will iteratively check multiple rotation angles to+ // find new future contact points after some rotation; and check the relative+ // velocity at these future contact points.+ #[cfg(feature = "dim2")]+ let dangvel = (motion2.angvel - motion1.angvel).abs();+ #[cfg(feature = "dim3")]+ let dangvel = (motion2.angvel - motion1.angvel).length();+ let inv_dangvel = crate::utils::inv(dangvel);+ let linear_increment = sum_linear_thickness;+ let angular_increment = Real::pi() - max_angular_thickness;++ let linear_time_increment =+ linear_increment * crate::utils::inv((motion2.linvel - motion1.linvel).length());+ let angular_time_increment = angular_increment * inv_dangvel;+ let mut time_increment = angular_time_increment+ .min(linear_time_increment)+ // This is needed to avoid some tunnelling. But this is+ // kind of "brute force" so we should find something better.+ .min((end_time - start_time) / 10.0);++ // println!(+ // "Lin time incr: {}, ang time incr: {}",+ // linear_time_increment, angular_time_increment+ // );++ if time_increment == 0.0 {+ time_increment = end_time;+ }++ let mut next_time = start_time;++ // TODO: looping until we reach π sounds enough for most purposes.+ // Is there a practical case where we need to loop until we reach 2π ?+ while next_time < end_time {+ // dbg!("A");+ let pos1_at_next_time = motion1.position_at_time(next_time);+ let pos2_at_next_time = motion2.position_at_time(next_time);+ let pos12_at_next_time = pos1_at_next_time.inv_mul(&pos2_at_next_time);+ let contact = dispatcher+ .contact(&pos12_at_next_time, g1, g2, Real::MAX)+ .ok()??;+ {+ // dbg!("C");++ // 1. Compute the relative velocity at that contact point.+ // 2. Check if this results in a potential tunnelling.+ // 3. Use bisection to adjust the shape-cast to the time where a pair+ // of contact points potentially causing tunneling hit for the first time.+ let r1 = contact.point1 - motion1.local_center;+ let r2 = contact.point2 - motion2.local_center;+ let vel1 = motion1.linvel + motion1.angvel.gcross(pos1_at_next_time.rotation * r1);+ let vel2 = motion2.linvel + motion2.angvel.gcross(pos2_at_next_time.rotation * r2);+ let vel12 = vel2 - vel1;+ let normal_vel = -vel12.dot(pos1_at_next_time.rotation * contact.normal1);+ let ccd_threshold = if contact.dist <= 0.0 {+ sum_linear_thickness+ } else {+ contact.dist + sum_linear_thickness+ };++ // println!(+ // "linvel: {:?}, angvel: {:?}, r2: {:?}, angpart: {:?}, vel2: {:?}",+ // motion2.linvel,+ // motion2.angvel,+ // r2,+ // motion2.angvel.gcross(pos2_at_next_time * r2),+ // vel2,+ // );+ //+ // println!(+ // "Found normal vel: {}, dist: {}, threshold: {}, if_value: {}, time: {}",+ // normal_vel,+ // contact.dist,+ // ccd_threshold,+ // normal_vel * (end_time - next_time),+ // next_time+ // );++ if normal_vel * (end_time - next_time) > ccd_threshold {+ // dbg!("D1");++ let mut result = ShapeCastHit {+ time_of_impact: next_time,+ witness1: contact.point1,+ witness2: contact.point2,+ normal1: contact.normal1,+ normal2: contact.normal2,+ status: ShapeCastStatus::Converged,+ subshape1: 0,+ subshape2: 0,+ };++ if contact.dist > 0.0 {+ // This is an acceptable impact. Now determine when+ // the impacts happens exactly.+ let curr_range = BisectionRange {+ min_t: next_time,+ max_t: end_time,+ curr_t: next_time,+ };+ let (new_range, _) = bisect(+ contact.dist,+ motion1,+ sm1,+ motion2,+ sm2,+ contact.normal1,+ curr_range,+ );++ // TODO: the bisection isn't always enough here. We should check that we+ // still have a contact now. If not, we should run the loop from+ // cast_shapes_nonlinear_support_map_support_map again from this+ // point forward.+ result.time_of_impact = new_range.curr_t;+ } else {+ // dbg!("Bissecting points");+ // This is an acceptable impact. Now determine when+ // the impacts happens exactly.+ let curr_range = BisectionRange {+ min_t: start_time,+ max_t: next_time,+ curr_t: next_time,+ };+ let (new_range, _) = bisect(+ contact.dist,+ motion1,+ &ConstantPoint(contact.point1),+ motion2,+ &ConstantPoint(contact.point2),+ contact.normal1,+ curr_range,+ );++ // TODO: the bisection isn't always enough here. We should check that we+ // still have a contact now. If not, we should run the loop from+ // cast_shapes_nonlinear_support_map_support_map again from this+ // point forward.+ result.time_of_impact = new_range.curr_t;+ }++ // println!("Fount new time_of_impact: {}", result.time_of_impact);+ return Some(result);+ }++ // dbg!("D2");+ }++ // If there is no angular velocity, we don't have to+ // continue because we can't rotate the object.+ if inv_dangvel == 0.0 {+ return None;+ }++ // dbg!("E");+ next_time += time_increment;+ }++ None+}++#[derive(Copy, Clone, Debug)]+struct BisectionRange {+ min_t: Real,+ curr_t: Real,+ max_t: Real,+}++fn bisect<SM1, SM2>(+ mut dist: Real,+ motion1: &NonlinearRigidMotion,+ sm1: &SM1,+ motion2: &NonlinearRigidMotion,+ sm2: &SM2,+ normal1: Vector,+ mut range: BisectionRange,+) -> (BisectionRange, usize)+where+ SM1: ?Sized + SupportMap,+ SM2: ?Sized + SupportMap,+{+ let abs_tol: Real = query::gjk::eps_tol();+ let rel_tol = abs_tol; // ComplexField::sqrt(abs_tol);+ let mut niter = 0;++ // Use the world-space normal so it doesn't move with the shapes.+ // This is necessary to reduce the risk of extracting a root that+ // is not the root happening at the smallest time.+ let pos1 = motion1.position_at_time(range.curr_t);+ let world_normal1 = pos1.rotation * normal1;++ loop {+ // println!("Bisection dist: {}, range: {:?}", dist, range);+ // TODO: use the secant method too for finding the next iterate and converge more quickly.+ if dist < 0.0 {+ // Too close or penetration, go back in time.+ range.max_t = range.curr_t;+ range.curr_t = (range.min_t + range.curr_t) * 0.5;+ } else if dist > rel_tol {+ // Too far apart, go forward in time.+ range.min_t = range.curr_t;+ range.curr_t = (range.curr_t + range.max_t) * 0.5;+ } else {+ // Reached tolerance, break.+ // println!("Bisection, break on dist tolerance.");+ break;+ }++ if range.max_t - range.min_t < abs_tol {+ range.curr_t = range.max_t;+ // println!("Bisection, break on tiny range.");+ break;+ }++ let pos1 = motion1.position_at_time(range.curr_t);+ let pos2 = motion2.position_at_time(range.curr_t);+ let pos12 = pos1.inv_mul(&pos2);++ let normal1 = pos1.rotation.inverse() * world_normal1;+ let pt1 = sm1.local_support_point_toward(normal1);+ let pt2 = sm2.support_point_toward(&pos12, -normal1);+ dist = pt2.dot(normal1) - pt1.dot(normal1);++ niter += 1;+ }++ (range, niter)+}diff --git a/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast_voxels_shape.rs b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast_voxels_shape.rsnew file mode 100644index 0000000..123a8e3--- /dev/null+++ b/renderer/third_party/parry3d/src/query/nonlinear_shape_cast/nonlinear_shape_cast_voxels_shape.rs@@ -0,0 +1,198 @@+use crate::bounding_volume::BoundingVolume;+use crate::math::{IVector, IVectorExt, Real, Vector, VectorExt};+use crate::query::{NonlinearRigidMotion, QueryDispatcher, ShapeCastHit};+use crate::shape::{Cuboid, Shape, Voxels};++/// Time Of Impact of a voxels shape with any other shape, under a rigid motion (translation + rotation).+pub fn cast_shapes_nonlinear_voxels_shape<D>(+ dispatcher: &D,+ motion1: &NonlinearRigidMotion,+ g1: &Voxels,+ motion2: &NonlinearRigidMotion,+ g2: &dyn Shape,+ start_time: Real,+ end_time: Real,+ stop_at_penetration: bool,+) -> Option<ShapeCastHit>+where+ D: ?Sized + QueryDispatcher,+{+ use num_traits::Bounded;++ // HACK: really supporting nonlinear shape-casting on a rotating voxels shape would+ // be extremely inefficient without any sort of hierarchical traversal on the voxel.+ // So for now we assume that the voxels shape only has a translational motion.+ // We can fix that once we introduce a sparse representation (and its accompanying+ // acceleration structure) for the voxels shape.+ let mut motion2 = *motion2;+ let mut motion1 = *motion1;+ motion2.linvel -= motion1.linvel;+ motion1.freeze(start_time);+ let pos1 = motion1.position_at_time(start_time);++ // Search for the smallest time of impact.+ //+ // 1. Check all the cells in the AABB at time `start_time`.+ // 2. Check which wall of unchecked voxels is hit first.+ // 3. Check one additional layer of voxels behind that wall.+ // 4. Continue, with a new AABB taken at the position at the time we hit the+ // wall.+ // 5. Continue until `curr_t` is bigger than `smallest_t`.+ //+ // PERF: This will be fairly efficient if the shape being cast has a size in the same order+ // of magnitude as the voxels, and if it doesn’t have a significant off-center angular+ // motion. Otherwise, this method will be fairly slow, and would require an acceleration+ // structure to improve.++ let mut hit = None;+ let mut smallest_t = end_time;++ // NOTE: we approximate the AABB of the shape using its orientation at the start and+ // end time. It might miss some cases if the object is rotating fast.+ let start_pos2_1 = pos1.inv_mul(&motion2.position_at_time(start_time));+ let mut end_pos2_1 = pos1.inv_mul(&motion2.position_at_time(end_time));+ end_pos2_1.translation = start_pos2_1.translation;+ let start_aabb2_1 = g2+ .compute_aabb(&start_pos2_1)+ .merged(&g2.compute_aabb(&end_pos2_1));++ let mut check_voxels_in_range = |search_domain: [IVector; 2]| {+ for vox in g1.voxels_in_range(search_domain[0], search_domain[1]) {+ if !vox.state.is_empty() {+ // PERF: could we check the canonical shape instead, and deduplicate accordingly?+ let center = g1.voxel_center(vox.grid_coords);+ let cuboid = Cuboid::new(g1.voxel_size() / 2.0);+ let vox_motion1 = motion1.prepend_translation(center);+ if let Some(new_hit) = dispatcher+ .cast_shapes_nonlinear(+ &vox_motion1,+ &cuboid,+ &motion2,+ g2,+ start_time,+ end_time,+ stop_at_penetration,+ )+ .ok()+ .flatten()+ {+ if new_hit.time_of_impact < smallest_t {+ smallest_t = new_hit.time_of_impact;+ hit = Some(new_hit);+ }+ }+ }+ }+ };++ let mut search_domain = g1.voxel_range_intersecting_local_aabb(&start_aabb2_1);+ check_voxels_in_range(search_domain);++ // Run the propagation.+ let [domain_mins, domain_maxs] = g1.domain();++ loop {+ let search_domain_aabb = g1.voxel_range_aabb(search_domain[0], search_domain[1]);++ // Figure out if we should move the aabb up/down/right/left.+ #[cfg(feature = "dim2")]+ let ii = [0, 1];+ #[cfg(feature = "dim3")]+ let ii = [0, 1, 2];++ let toi = ii.map(|i| {+ if motion2.linvel.vget(i) > 0.0 {+ let t = (search_domain_aabb.maxs.vget(i) - start_aabb2_1.maxs.vget(i))+ / motion2.linvel.vget(i);+ if t < 0.0 {+ (Real::max_value(), true)+ } else {+ (t, true)+ }+ } else if motion2.linvel.vget(i) < 0.0 {+ let t = (search_domain_aabb.mins.vget(i) - start_aabb2_1.mins.vget(i))+ / motion2.linvel.vget(i);+ if t < 0.0 {+ (Real::max_value(), false)+ } else {+ (t, false)+ }+ } else {+ (Real::max_value(), false)+ }+ });++ #[cfg(feature = "dim2")]+ if toi[0].0 > end_time && toi[1].0 > end_time {+ break;+ }++ #[cfg(feature = "dim3")]+ if toi[0].0 > end_time && toi[1].0 > end_time && toi[2].0 > end_time {+ break;+ }++ let imin = Vector::from(toi.map(|t| t.0)).min_position();++ if toi[imin].1 {+ search_domain[0].ivset(imin, search_domain[0].ivget(imin) + 1);+ search_domain[1].ivset(imin, search_domain[1].ivget(imin) + 1);++ if search_domain[1].ivget(imin) <= domain_maxs.ivget(imin) {+ // Check the voxels on the added row.+ let mut prev_row = search_domain[0];+ prev_row.ivset(imin, search_domain[1].ivget(imin) - 1);++ let range_to_check = [prev_row, search_domain[1]];+ check_voxels_in_range(range_to_check);+ } else if search_domain[0].ivget(imin) >= domain_maxs.ivget(imin) {+ // Leaving the shape's bounds.+ break;+ }+ } else {+ search_domain[0].ivset(imin, search_domain[0].ivget(imin) - 1);+ search_domain[1].ivset(imin, search_domain[1].ivget(imin) - 1);++ if search_domain[0].ivget(imin) >= domain_mins.ivget(imin) {+ // Check the voxels on the added row.+ let mut next_row = search_domain[1];+ next_row.ivset(imin, search_domain[0].ivget(imin) + 1);++ let range_to_check = [search_domain[0], next_row];+ check_voxels_in_range(range_to_check);+ } else if search_domain[1].ivget(imin) <= domain_mins.ivget(imin) {+ // Leaving the shape's bounds.+ break;+ }+ }+ }++ hit+}++/// Time Of Impact of any shape with a composite shape, under a rigid motion (translation + rotation).+pub fn cast_shapes_nonlinear_shape_voxels<D>(+ dispatcher: &D,+ motion1: &NonlinearRigidMotion,+ g1: &dyn Shape,+ motion2: &NonlinearRigidMotion,+ g2: &Voxels,+ start_time: Real,+ end_time: Real,+ stop_at_penetration: bool,+) -> Option<ShapeCastHit>+where+ D: ?Sized + QueryDispatcher,+{+ cast_shapes_nonlinear_voxels_shape(+ dispatcher,+ motion2,+ g2,+ motion1,+ g1,+ start_time,+ end_time,+ stop_at_penetration,+ )+ .map(|hit| hit.swapped())+}diff --git a/renderer/third_party/parry3d/src/query/point/mod.rs b/renderer/third_party/parry3d/src/query/point/mod.rsnew file mode 100644index 0000000..3ecf325--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/mod.rs@@ -0,0 +1,32 @@+//! Vector inclusion and projection.++#[doc(inline)]+pub use self::point_query::{PointProjection, PointQuery, PointQueryWithLocation};+#[cfg(feature = "alloc")]+pub use self::point_support_map::local_point_projection_on_support_map;++mod point_aabb;+mod point_ball;+mod point_bounding_sphere;+mod point_capsule;+#[cfg(feature = "alloc")]+mod point_composite_shape;+#[cfg(feature = "dim3")]+mod point_cone;+mod point_cuboid;+#[cfg(feature = "dim3")]+mod point_cylinder;+mod point_halfspace;+#[cfg(feature = "alloc")]+mod point_heightfield;+#[doc(hidden)]+pub mod point_query;+mod point_round_shape;+mod point_segment;+#[cfg(feature = "alloc")]+mod point_support_map;+#[cfg(feature = "dim3")]+mod point_tetrahedron;+mod point_triangle;+#[cfg(feature = "alloc")]+mod point_voxels;diff --git a/renderer/third_party/parry3d/src/query/point/point_aabb.rs b/renderer/third_party/parry3d/src/query/point/point_aabb.rsnew file mode 100644index 0000000..a21a380--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_aabb.rs@@ -0,0 +1,145 @@+use crate::bounding_volume::Aabb;+use crate::math::{Real, Vector, VectorExt, DIM};+use crate::num::Zero;+use crate::query::{PointProjection, PointQuery};+use crate::shape::FeatureId;+use crate::utils::WSign;++impl Aabb {+ fn do_project_local_point(&self, pt: Vector, solid: bool) -> (bool, Vector, Vector) {+ let mins_pt = self.mins - pt;+ let pt_maxs = pt - self.maxs;+ let shift = mins_pt.max(Vector::ZERO) - pt_maxs.max(Vector::ZERO);++ if shift != Vector::ZERO {+ (false, pt + shift, shift)+ } else if solid {+ (true, pt, Vector::ZERO)+ } else {+ // Projection for the case where the point is inside the box.+ let centered_pt = pt - self.center();+ let pt_sgn_with_zero = centered_pt.copy_sign_to(Vector::splat(1.0));+ // This is the sign of pt, or -1 for components that were zero.+ // This bias is arbitrary (we could have picked +1), but we picked it so+ // it matches the previous implementation.+ let pt_sgn = pt_sgn_with_zero + (pt_sgn_with_zero.abs() - Vector::ONE);+ let diff = self.half_extents() - pt_sgn * centered_pt;++ #[cfg(feature = "dim2")]+ let shift = {+ let pick_x = diff.x <= diff.y;+ let shift_x = Vector::new(diff.x * pt_sgn.x, 0.0);+ let shift_y = Vector::new(0.0, diff.y * pt_sgn.y);+ if pick_x {+ shift_x+ } else {+ shift_y+ }+ };++ #[cfg(feature = "dim3")]+ let shift = {+ let pick_x = diff.x <= diff.y && diff.x <= diff.z;+ let pick_y = diff.y <= diff.x && diff.y <= diff.z;+ let shift_x = Vector::new(diff.x * pt_sgn.x, 0.0, 0.0);+ let shift_y = Vector::new(0.0, diff.y * pt_sgn.y, 0.0);+ let shift_z = Vector::new(0.0, 0.0, diff.z * pt_sgn.z);+ if pick_x {+ shift_x+ } else if pick_y {+ shift_y+ } else {+ shift_z+ }+ };++ (true, pt + shift, shift)+ }+ }+}++impl PointQuery for Aabb {+ #[inline]+ fn project_local_point(&self, pt: Vector, solid: bool) -> PointProjection {+ let (inside, ls_pt, _) = self.do_project_local_point(pt, solid);+ PointProjection::new(inside, ls_pt)+ }++ #[allow(unused_assignments)] // For last_zero_shift which is used only in 3D.+ #[allow(unused_variables)] // For last_zero_shift which is used only in 3D.+ #[inline]+ fn project_local_point_and_get_feature(&self, pt: Vector) -> (PointProjection, FeatureId) {+ let (inside, ls_pt, shift) = self.do_project_local_point(pt, false);+ let proj = PointProjection::new(inside, ls_pt);+ let mut nzero_shifts = 0;+ let mut last_zero_shift = 0;+ let mut last_not_zero_shift = 0;++ for i in 0..DIM {+ if shift.vget(i).is_zero() {+ nzero_shifts += 1;+ last_zero_shift = i;+ } else {+ last_not_zero_shift = i;+ }+ }++ if nzero_shifts == DIM {+ for i in 0..DIM {+ if ls_pt.vget(i) > self.maxs.vget(i) - crate::math::DEFAULT_EPSILON {+ return (proj, FeatureId::Face(i as u32));+ }+ if ls_pt.vget(i) <= self.mins.vget(i) + crate::math::DEFAULT_EPSILON {+ return (proj, FeatureId::Face((i + DIM) as u32));+ }+ }++ (proj, FeatureId::Unknown)+ } else if nzero_shifts == DIM - 1 {+ // On a 3D face.+ if ls_pt.vget(last_not_zero_shift) < self.center().vget(last_not_zero_shift) {+ (proj, FeatureId::Face((last_not_zero_shift + DIM) as u32))+ } else {+ (proj, FeatureId::Face(last_not_zero_shift as u32))+ }+ } else {+ // On a vertex or edge.+ let mut id = 0;+ let center = self.center();++ for i in 0..DIM {+ if ls_pt.vget(i) < center.vget(i) {+ id |= 1 << i;+ }+ }++ #[cfg(feature = "dim3")]+ {+ if nzero_shifts == 0 {+ (proj, FeatureId::Vertex(id))+ } else {+ (proj, FeatureId::Edge((id << 2) | (last_zero_shift as u32)))+ }+ }++ #[cfg(feature = "dim2")]+ {+ (proj, FeatureId::Vertex(id))+ }+ }+ }++ #[inline]+ fn distance_to_local_point(&self, pt: Vector, solid: bool) -> Real {+ let mins_pt = self.mins - pt;+ let pt_maxs = pt - self.maxs;+ let shift = mins_pt.max(pt_maxs).max(Vector::ZERO);++ if solid || shift != Vector::ZERO {+ shift.length()+ } else {+ // TODO: optimize that.+ -pt.distance(self.project_local_point(pt, solid).point)+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_ball.rs b/renderer/third_party/parry3d/src/query/point/point_ball.rsnew file mode 100644index 0000000..5da6d33--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_ball.rs@@ -0,0 +1,42 @@+use crate::math::ComplexField;++use crate::math::{Real, Vector};+use crate::query::{PointProjection, PointQuery};+use crate::shape::{Ball, FeatureId};++impl PointQuery for Ball {+ #[inline]+ fn project_local_point(&self, pt: Vector, solid: bool) -> PointProjection {+ let distance_squared = pt.length_squared();++ let inside = distance_squared <= self.radius * self.radius;++ if inside && solid {+ PointProjection::new(true, pt)+ } else {+ let proj = pt * (self.radius / <Real as ComplexField>::sqrt(distance_squared));+ PointProjection::new(inside, proj)+ }+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, pt: Vector) -> (PointProjection, FeatureId) {+ (self.project_local_point(pt, false), FeatureId::Face(0))+ }++ #[inline]+ fn distance_to_local_point(&self, pt: Vector, solid: bool) -> Real {+ let dist = pt.length() - self.radius;++ if solid && dist < 0.0 {+ 0.0+ } else {+ dist+ }+ }++ #[inline]+ fn contains_local_point(&self, pt: Vector) -> bool {+ pt.length_squared() <= self.radius * self.radius+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_bounding_sphere.rs b/renderer/third_party/parry3d/src/query/point/point_bounding_sphere.rsnew file mode 100644index 0000000..dce2ae9--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_bounding_sphere.rs@@ -0,0 +1,32 @@+use crate::bounding_volume::BoundingSphere;+use crate::math::{Real, Vector};+use crate::query::{PointProjection, PointQuery};+use crate::shape::{Ball, FeatureId};++impl PointQuery for BoundingSphere {+ #[inline]+ fn project_local_point(&self, pt: Vector, solid: bool) -> PointProjection {+ let centered_pt = pt - self.center();+ let mut proj = Ball::new(self.radius()).project_local_point(centered_pt, solid);++ proj.point += self.center();+ proj+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, pt: Vector) -> (PointProjection, FeatureId) {+ (self.project_local_point(pt, false), FeatureId::Face(0))+ }++ #[inline]+ fn distance_to_local_point(&self, pt: Vector, solid: bool) -> Real {+ let centered_pt = pt - self.center();+ Ball::new(self.radius()).distance_to_local_point(centered_pt, solid)+ }++ #[inline]+ fn contains_local_point(&self, pt: Vector) -> bool {+ let centered_pt = pt - self.center();+ Ball::new(self.radius()).contains_local_point(centered_pt)+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_capsule.rs b/renderer/third_party/parry3d/src/query/point/point_capsule.rsnew file mode 100644index 0000000..48c9868--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_capsule.rs@@ -0,0 +1,47 @@+use crate::approx::AbsDiffEq;+use crate::math::{Real, Vector, VectorExt};+use crate::query::{PointProjection, PointQuery};+use crate::shape::{Capsule, FeatureId, Segment};++impl PointQuery for Capsule {+ #[inline]+ fn project_local_point(&self, pt: Vector, solid: bool) -> PointProjection {+ let seg = Segment::new(self.segment.a, self.segment.b);+ let proj = seg.project_local_point(pt, solid);+ let dproj = pt - proj.point;+ let (dir, dist) = dproj.normalize_and_length();+ if dist >= Real::default_epsilon() {+ let inside = dist <= self.radius;+ if solid && inside {+ return PointProjection::new(true, pt);+ } else {+ return PointProjection::new(inside, proj.point + dir * self.radius);+ }+ } else if solid {+ return PointProjection::new(true, pt);+ }++ #[cfg(feature = "dim2")]+ if let Some(dir) = seg.normal() {+ PointProjection::new(true, proj.point + dir * self.radius)+ } else {+ // The segment has no normal, likely because it degenerates to a point.+ PointProjection::new(true, proj.point + Vector::ith(1, self.radius))+ }++ #[cfg(feature = "dim3")]+ if let Some(dir) = seg.direction() {+ use crate::utils::WBasis;+ let dir = dir.orthonormal_basis()[0];+ PointProjection::new(true, proj.point + dir * self.radius)+ } else {+ // The segment has no normal, likely because it degenerates to a point.+ PointProjection::new(true, proj.point + Vector::ith(1, self.radius))+ }+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, pt: Vector) -> (PointProjection, FeatureId) {+ (self.project_local_point(pt, false), FeatureId::Face(0))+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_composite_shape.rs b/renderer/third_party/parry3d/src/query/point/point_composite_shape.rsnew file mode 100644index 0000000..48d2463--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_composite_shape.rs@@ -0,0 +1,404 @@+#![allow(unused_parens)] // Needed by the macro.++use crate::math::{Real, Vector};+use crate::partitioning::BvhNode;+use crate::query::{PointProjection, PointQuery, PointQueryWithLocation};+use crate::shape::{+ CompositeShapeRef, FeatureId, SegmentPointLocation, SubShapeId, TriMesh, TrianglePointLocation,+ TypedCompositeShape,+};++use crate::shape::{Compound, Polyline};++/// The feature of a triangle a point projected onto, as `Triangle`'s own point query reports it.+fn triangle_point_location_feature(location: TrianglePointLocation) -> FeatureId {+ match location {+ TrianglePointLocation::OnVertex(i) => FeatureId::Vertex(i),+ #[cfg(feature = "dim3")]+ TrianglePointLocation::OnEdge(i, _) => FeatureId::Edge(i),+ #[cfg(feature = "dim2")]+ TrianglePointLocation::OnEdge(i, _) => FeatureId::Face(i),+ TrianglePointLocation::OnFace(i, _) => FeatureId::Face(i),+ TrianglePointLocation::OnSolid => FeatureId::Face(0),+ }+}++impl<S: TypedCompositeShape> CompositeShapeRef<'_, S> {+ /// Project a point on this composite shape.+ ///+ /// Returns the index of the sub-shape of `self` that answered, the projection as that+ /// sub-shape reported it, and some shape-specific information about the projected point.+ #[inline]+ pub fn project_local_point_and_get_location(+ &self,+ point: Vector,+ max_dist: Real,+ solid: bool,+ ) -> Option<(+ SubShapeId,+ PointProjection,+ <S::PartShape as PointQueryWithLocation>::Location,+ )>+ where+ S::PartShape: PointQueryWithLocation,+ {+ self.0+ .bvh()+ .find_best(+ max_dist,+ |node: &BvhNode, _best_so_far| node.aabb().distance_to_local_point(point, true),+ |primitive, _best_so_far| {+ let proj = self.0.map_typed_part_at(primitive, |pose, shape, _| {+ if let Some(pose) = pose {+ shape.project_point_and_get_location(pose, point, solid)+ } else {+ shape.project_local_point_and_get_location(point, solid)+ }+ })?;+ let cost = (proj.0.point - point).length();+ Some((cost, proj))+ },+ )+ .map(|(best_id, (_, (proj, location)))| (best_id, proj, location))+ }++ /// Project a point on this composite shape.+ ///+ /// Returns the index of the sub-shape of `self` that answered and the projection as that+ /// sub-shape reported it. If `solid` is `false` then the point will be projected to the+ /// closest boundary of `self` even if it is contained by one of its sub-shapes.+ pub fn project_local_point(+ &self,+ point: Vector,+ max_dist: Real,+ solid: bool,+ ) -> Option<(SubShapeId, PointProjection)> {+ let (best_id, (_, proj)) = self.0.bvh().find_best(+ max_dist,+ |node: &BvhNode, _best_so_far| node.aabb().distance_to_local_point(point, true),+ |primitive, _best_so_far| {+ let proj = self.0.map_typed_part_at(primitive, |pose, shape, _| {+ if let Some(pose) = pose {+ shape.project_point(pose, point, solid)+ } else {+ shape.project_local_point(point, solid)+ }+ })?;+ let dist = (proj.point - point).length();+ Some((dist, proj))+ },+ )?;+ Some((best_id, proj))+ }++ /// Project a point on this composite shape.+ ///+ /// Returns the index of the sub-shape of `self` that answered, the projection as that+ /// sub-shape reported it, and the feature of that sub-shape the projection landed on.+ #[inline]+ pub fn project_local_point_and_get_feature(+ &self,+ point: Vector,+ max_dist: Real,+ ) -> Option<(SubShapeId, PointProjection, FeatureId)> {+ let (best_id, (_, (proj, feature_id))) = self.0.bvh().find_best(+ max_dist,+ |node: &BvhNode, _best_so_far| node.aabb().distance_to_local_point(point, true),+ |primitive, _best_so_far| {+ let proj = self.0.map_typed_part_at(primitive, |pose, shape, _| {+ if let Some(pose) = pose {+ shape.project_point_and_get_feature(pose, point)+ } else {+ shape.project_local_point_and_get_feature(point)+ }+ })?;+ let cost = (proj.0.point - point).length();+ Some((cost, proj))+ },+ )?;+ Some((best_id, proj, feature_id))+ }++ // TODO: implement distance_to_point too?++ /// Returns the index of any sub-shape of `self` that contains the given point.+ #[inline]+ pub fn contains_local_point(&self, point: Vector) -> Option<SubShapeId> {+ self.0+ .bvh()+ .leaves(|node: &BvhNode| node.aabb().contains_local_point(point))+ .find(|leaf_id| {+ self.0+ .map_typed_part_at(*leaf_id, |pose, shape, _| {+ if let Some(pose) = pose {+ shape.contains_point(pose, point)+ } else {+ shape.contains_local_point(point)+ }+ })+ .unwrap_or(false)+ })+ }+}++impl PointQuery for Polyline {+ #[inline]+ fn project_local_point(&self, point: Vector, solid: bool) -> PointProjection {+ self.project_local_point_and_get_location(point, solid).0+ }++ #[inline]+ #[allow(unused_mut)] // Because we need mut in 2D but not in 3D.+ fn project_local_point_and_get_feature(&self, point: Vector) -> (PointProjection, FeatureId) {+ // Every comparison involving a NaN is false, so the traversal finds no candidate+ // at all when `point` (or `self`) isn’t finite. Report `point` itself rather than+ // an arbitrary projection onto whichever part we happened to pick.+ let Some((segment_id, mut proj, feature)) =+ CompositeShapeRef(self).project_local_point_and_get_feature(point, Real::MAX)+ else {+ return (PointProjection::new(false, point), FeatureId::Unknown);+ };+ proj.subshape = segment_id;++ // A point behind the outward pseudo-normal is inside.+ #[cfg(feature = "dim2")]+ if let Some(constraints) = self.segment_normal_constraints(segment_id) {+ let pseudo_normal = match feature {+ FeatureId::Vertex(i) => constraints.edges[i as usize],+ _ => constraints.face,+ };+ proj.is_inside = (point - proj.point).dot(pseudo_normal) <= 0.0;+ }++ // The feature is the segment's own; `proj.subshape` says which segment it belongs to.+ (proj, feature)+ }++ // TODO: implement distance_to_point too?++ #[inline]+ fn contains_local_point(&self, point: Vector) -> bool {+ // An oriented polyline has a solid interior; reuse the projection's inside test.+ #[cfg(feature = "dim2")]+ if self.flags().contains(crate::shape::PolylineFlags::ORIENTED) {+ return self+ .project_local_point_and_get_location(point, true)+ .0+ .is_inside;+ }++ CompositeShapeRef(self)+ .contains_local_point(point)+ .is_some()+ }+}++impl PointQuery for TriMesh {+ #[inline]+ fn project_local_point(&self, point: Vector, solid: bool) -> PointProjection {+ self.project_local_point_with_max_dist(point, solid, Real::MAX)+ // Shouldn’t happen (trimesh must not be empty). But return something+ // instead of crashing with `unwrap`.+ .unwrap_or(PointProjection::new(false, point))+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, point: Vector) -> (PointProjection, FeatureId) {+ #[cfg(feature = "dim3")]+ if self.pseudo_normals().is_some() {+ // If we can, in 3D, take the pseudo-normals into account. The location carries the+ // triangle's own feature; `proj.subshape` says which triangle it belongs to.+ let (proj, (_, location)) = self.project_local_point_and_get_location(point, false);+ return (proj, triangle_point_location_feature(location));+ }++ let solid = cfg!(feature = "dim2");+ // No candidate: `point` (or `self`) isn’t finite. See+ // `Polyline::project_local_point_and_get_feature`.+ let Some((triangle_id, proj, location)) =+ CompositeShapeRef(self).project_local_point_and_get_location(point, Real::MAX, solid)+ else {+ return (PointProjection::new(false, point), FeatureId::Unknown);+ };+ // The feature is the triangle's own; `proj.subshape` says which triangle it belongs to.+ (+ proj.with_subshape(triangle_id),+ triangle_point_location_feature(location),+ )+ }++ // TODO: implement distance_to_point too?++ #[inline]+ fn contains_local_point(&self, point: Vector) -> bool {+ #[cfg(feature = "dim3")]+ if self.pseudo_normals.is_some() {+ // If we can, in 3D, take the pseudo-normals into account.+ return self+ .project_local_point_and_get_location(point, true)+ .0+ .is_inside;+ }++ CompositeShapeRef(self)+ .contains_local_point(point)+ .is_some()+ }++ /// Projects a point on `self` transformed by `m`, unless the projection lies further than the given max distance.+ fn project_local_point_with_max_dist(+ &self,+ pt: Vector,+ solid: bool,+ max_dist: Real,+ ) -> Option<PointProjection> {+ self.project_local_point_and_get_location_with_max_dist(pt, solid, max_dist)+ .map(|proj| proj.0)+ }+}++impl PointQuery for Compound {+ #[inline]+ fn project_local_point(&self, point: Vector, solid: bool) -> PointProjection {+ CompositeShapeRef(self)+ .project_local_point(point, Real::MAX, solid)+ .map(|(part_id, proj)| proj.with_subshape(part_id))+ // No candidate: `point` (or `self`) isn’t finite. See+ // `Polyline::project_local_point_and_get_feature`.+ .unwrap_or(PointProjection::new(false, point))+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, point: Vector) -> (PointProjection, FeatureId) {+ // The feature is the part's own; `proj.subshape` says which part it belongs to.+ CompositeShapeRef(self)+ .project_local_point_and_get_feature(point, Real::MAX)+ .map(|(part_id, proj, feature)| (proj.with_subshape(part_id), feature))+ // No candidate: `point` (or `self`) isn’t finite. See+ // `Polyline::project_local_point_and_get_feature`.+ .unwrap_or((PointProjection::new(false, point), FeatureId::Unknown))+ }++ #[inline]+ fn contains_local_point(&self, point: Vector) -> bool {+ CompositeShapeRef(self)+ .contains_local_point(point)+ .is_some()+ }+}++impl PointQueryWithLocation for Polyline {+ type Location = (u32, SegmentPointLocation);++ #[inline]+ fn project_local_point_and_get_location(+ &self,+ point: Vector,+ solid: bool,+ ) -> (PointProjection, Self::Location) {+ self.project_local_point_and_get_location_with_max_dist(point, solid, Real::MAX)+ // No candidate: `point` (or `self`) isn’t finite. See+ // `Polyline::project_local_point_and_get_feature`.+ .unwrap_or((+ PointProjection::new(false, point),+ (0, SegmentPointLocation::OnVertex(0)),+ ))+ }++ /// Projects a point on `self`, with a maximum projection distance.+ fn project_local_point_and_get_location_with_max_dist(+ &self,+ point: Vector,+ solid: bool,+ max_dist: Real,+ ) -> Option<(PointProjection, Self::Location)> {+ #[allow(unused_mut)] // Because we need mut in 2D but not in 3D.+ if let Some((seg_id, mut proj, loc)) =+ CompositeShapeRef(self).project_local_point_and_get_location(point, max_dist, solid)+ {+ proj.subshape = seg_id;++ // A point behind the outward pseudo-normal is inside.+ #[cfg(feature = "dim2")]+ if let Some(constraints) = self.segment_normal_constraints(seg_id) {+ let pseudo_normal = match loc {+ SegmentPointLocation::OnVertex(i) => constraints.edges[i as usize],+ SegmentPointLocation::OnEdge(_) => constraints.face,+ };+ proj.is_inside = (point - proj.point).dot(pseudo_normal) <= 0.0;++ if proj.is_inside && solid {+ proj.point = point;+ }+ }++ Some((proj, (seg_id, loc)))+ } else {+ None+ }+ }+}++impl PointQueryWithLocation for TriMesh {+ type Location = (u32, TrianglePointLocation);++ #[inline]+ #[allow(unused_mut)] // Because we need mut in 3D but not in 2D.+ fn project_local_point_and_get_location(+ &self,+ point: Vector,+ solid: bool,+ ) -> (PointProjection, Self::Location) {+ self.project_local_point_and_get_location_with_max_dist(point, solid, Real::MAX)+ // No candidate: `point` (or `self`) isn’t finite. See+ // `Polyline::project_local_point_and_get_feature`.+ .unwrap_or((+ PointProjection::new(false, point),+ (0, TrianglePointLocation::OnVertex(0)),+ ))+ }++ /// Projects a point on `self`, with a maximum projection distance.+ fn project_local_point_and_get_location_with_max_dist(+ &self,+ point: Vector,+ solid: bool,+ max_dist: Real,+ ) -> Option<(PointProjection, Self::Location)> {+ #[allow(unused_mut)] // mut is needed in 3D.+ if let Some((part_id, mut proj, location)) =+ CompositeShapeRef(self).project_local_point_and_get_location(point, max_dist, solid)+ {+ proj.subshape = part_id;++ #[cfg(feature = "dim3")]+ if let Some(pseudo_normals) = self.pseudo_normals_if_oriented() {+ let pseudo_normal = match location {+ TrianglePointLocation::OnFace(..) | TrianglePointLocation::OnSolid => {+ Some(self.triangle(part_id).scaled_normal())+ }+ TrianglePointLocation::OnEdge(i, _) => pseudo_normals+ .edges_pseudo_normal+ .get(part_id as usize)+ .map(|pn| pn[i as usize]),+ TrianglePointLocation::OnVertex(i) => {+ let idx = self.indices()[part_id as usize];+ pseudo_normals+ .vertices_pseudo_normal+ .get(idx[i as usize] as usize)+ .copied()+ }+ };++ if let Some(pseudo_normal) = pseudo_normal {+ let dpt = point - proj.point;+ proj.is_inside = dpt.dot(pseudo_normal) <= 0.0;+ }+ }++ Some((proj, (part_id, location)))+ } else {+ None+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_cone.rs b/renderer/third_party/parry3d/src/query/point/point_cone.rsnew file mode 100644index 0000000..2cd054e--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_cone.rs@@ -0,0 +1,69 @@+use crate::math::{Vector, Vector2};+use crate::query::{PointProjection, PointQuery};+use crate::shape::{Cone, FeatureId, Segment};++impl PointQuery for Cone {+ #[inline]+ fn project_local_point(&self, pt: Vector, solid: bool) -> PointProjection {+ // Project on the basis.+ let (mut dir_from_basis_center, planar_dist_from_basis_center) =+ Vector2::new(pt.x, pt.z).normalize_and_length();++ if planar_dist_from_basis_center <= crate::math::DEFAULT_EPSILON {+ dir_from_basis_center = Vector2::X;+ }++ let projection_on_basis = Vector::new(pt.x, -self.half_height, pt.z);++ if pt.y < -self.half_height && planar_dist_from_basis_center <= self.radius {+ // The projection is on the basis.+ return PointProjection::new(false, projection_on_basis);+ }++ // Project on the basis circle.+ let proj2d = dir_from_basis_center * self.radius;+ let projection_on_basis_circle = Vector::new(proj2d[0], -self.half_height, proj2d[1]);++ // Project on the conic side.+ // TODO: we could solve this in 2D using the plane passing through the cone axis and the conic_side_segment to save some computation.+ let apex_point = Vector::new(0.0, self.half_height, 0.0);+ let conic_side_segment = Segment::new(apex_point, projection_on_basis_circle);+ let conic_side_segment_dir = conic_side_segment.scaled_direction();+ let mut proj = conic_side_segment.project_local_point(pt, true);++ let apex_to_basis_center = Vector::new(0.0, -2.0 * self.half_height, 0.0);++ // Now determine if the point is inside of the cone.+ if pt.y >= -self.half_height+ && pt.y <= self.half_height+ && conic_side_segment_dir+ .cross(pt - apex_point)+ .dot(conic_side_segment_dir.cross(apex_to_basis_center))+ >= 0.0+ {+ if solid {+ PointProjection::new(true, pt)+ } else {+ // We are inside of the cone, so the correct projection is+ // either on the basis of the cone, or on the conic side.+ if (proj.point - pt).length_squared() > (projection_on_basis - pt).length_squared()+ {+ PointProjection::new(true, projection_on_basis)+ } else {+ proj.is_inside = true;+ proj+ }+ }+ } else {+ // We are outside of the cone, return the computed proj+ // as-is.+ proj+ }+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, pt: Vector) -> (PointProjection, FeatureId) {+ // TODO: get the actual feature.+ (self.project_local_point(pt, false), FeatureId::Unknown)+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_cuboid.rs b/renderer/third_party/parry3d/src/query/point/point_cuboid.rsnew file mode 100644index 0000000..345e851--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_cuboid.rs@@ -0,0 +1,34 @@+use crate::bounding_volume::Aabb;+use crate::math::{Real, Vector};+use crate::query::{PointProjection, PointQuery};+use crate::shape::{Cuboid, FeatureId};++impl PointQuery for Cuboid {+ #[inline]+ fn project_local_point(&self, pt: Vector, solid: bool) -> PointProjection {+ let dl = -self.half_extents;+ let ur = self.half_extents;+ Aabb::new(dl, ur).project_local_point(pt, solid)+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, pt: Vector) -> (PointProjection, FeatureId) {+ let dl = -self.half_extents;+ let ur = self.half_extents;+ Aabb::new(dl, ur).project_local_point_and_get_feature(pt)+ }++ #[inline]+ fn distance_to_local_point(&self, pt: Vector, solid: bool) -> Real {+ let dl = -self.half_extents;+ let ur = self.half_extents;+ Aabb::new(dl, ur).distance_to_local_point(pt, solid)+ }++ #[inline]+ fn contains_local_point(&self, pt: Vector) -> bool {+ let dl = -self.half_extents;+ let ur = self.half_extents;+ Aabb::new(dl, ur).contains_local_point(pt)+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_cylinder.rs b/renderer/third_party/parry3d/src/query/point/point_cylinder.rsnew file mode 100644index 0000000..0b08fbd--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_cylinder.rs@@ -0,0 +1,77 @@+use crate::math::{Vector, Vector2};+use crate::query::{PointProjection, PointQuery};+use crate::shape::{Cylinder, FeatureId};++impl PointQuery for Cylinder {+ #[inline]+ fn project_local_point(&self, pt: Vector, solid: bool) -> PointProjection {+ // Project on the basis.+ let (mut dir_from_basis_center, planar_dist_from_basis_center) =+ Vector2::new(pt.x, pt.z).normalize_and_length();++ if planar_dist_from_basis_center <= crate::math::DEFAULT_EPSILON {+ {+ dir_from_basis_center = Vector2::X;+ }+ }++ let proj2d = dir_from_basis_center * self.radius;++ if pt.y >= -self.half_height+ && pt.y <= self.half_height+ && planar_dist_from_basis_center <= self.radius+ {+ // The point is inside of the cylinder.+ if solid {+ PointProjection::new(true, pt)+ } else {+ let dist_to_top = self.half_height - pt.y;+ let dist_to_bottom = pt.y - (-self.half_height);+ let dist_to_side = self.radius - planar_dist_from_basis_center;++ if dist_to_top < dist_to_bottom && dist_to_top < dist_to_side {+ let projection_on_top = Vector::new(pt.x, self.half_height, pt.z);+ PointProjection::new(true, projection_on_top)+ } else if dist_to_bottom < dist_to_top && dist_to_bottom < dist_to_side {+ let projection_on_bottom = Vector::new(pt.x, -self.half_height, pt.z);+ PointProjection::new(true, projection_on_bottom)+ } else {+ let projection_on_side = Vector::new(proj2d[0], pt.y, proj2d[1]);+ PointProjection::new(true, projection_on_side)+ }+ }+ } else {+ // The point is outside of the cylinder.+ if pt.y > self.half_height {+ if planar_dist_from_basis_center <= self.radius {+ let projection_on_top = Vector::new(pt.x, self.half_height, pt.z);+ PointProjection::new(false, projection_on_top)+ } else {+ let projection_on_top_circle =+ Vector::new(proj2d[0], self.half_height, proj2d[1]);+ PointProjection::new(false, projection_on_top_circle)+ }+ } else if pt.y < -self.half_height {+ // Project on the bottom plane or the bottom circle.+ if planar_dist_from_basis_center <= self.radius {+ let projection_on_bottom = Vector::new(pt.x, -self.half_height, pt.z);+ PointProjection::new(false, projection_on_bottom)+ } else {+ let projection_on_bottom_circle =+ Vector::new(proj2d[0], -self.half_height, proj2d[1]);+ PointProjection::new(false, projection_on_bottom_circle)+ }+ } else {+ // Project on the side.+ let projection_on_side = Vector::new(proj2d[0], pt.y, proj2d[1]);+ PointProjection::new(false, projection_on_side)+ }+ }+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, pt: Vector) -> (PointProjection, FeatureId) {+ // TODO: get the actual feature.+ (self.project_local_point(pt, false), FeatureId::Unknown)+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_halfspace.rs b/renderer/third_party/parry3d/src/query/point/point_halfspace.rsnew file mode 100644index 0000000..42a6112--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_halfspace.rs@@ -0,0 +1,39 @@+use crate::math::{Real, Vector};+use crate::query::{PointProjection, PointQuery};+use crate::shape::{FeatureId, HalfSpace};++impl PointQuery for HalfSpace {+ #[inline]+ fn project_local_point(&self, pt: Vector, solid: bool) -> PointProjection {+ let d = self.normal.dot(pt);+ let inside = d <= 0.0;++ if inside && solid {+ PointProjection::new(true, pt)+ } else {+ PointProjection::new(inside, pt + (-self.normal * d))+ }+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, pt: Vector) -> (PointProjection, FeatureId) {+ (self.project_local_point(pt, false), FeatureId::Face(0))+ }++ #[inline]+ fn distance_to_local_point(&self, pt: Vector, solid: bool) -> Real {+ let dist = self.normal.dot(pt);++ if dist < 0.0 && solid {+ 0.0+ } else {+ // This will automatically be negative if the point is inside.+ dist+ }+ }++ #[inline]+ fn contains_local_point(&self, pt: Vector) -> bool {+ self.normal.dot(pt) <= 0.0+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_heightfield.rs b/renderer/third_party/parry3d/src/query/point/point_heightfield.rsnew file mode 100644index 0000000..621596c--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_heightfield.rs@@ -0,0 +1,97 @@+use crate::bounding_volume::Aabb;+#[cfg(not(feature = "std"))]+use crate::math::ComplexField;+use crate::math::{Real, Vector};+use crate::query::{PointProjection, PointQuery, PointQueryWithLocation};+use crate::shape::{FeatureId, HeightField, TrianglePointLocation}; // For sqrt.++impl PointQuery for HeightField {+ fn project_local_point_with_max_dist(+ &self,+ pt: Vector,+ solid: bool,+ max_dist: Real,+ ) -> Option<PointProjection> {+ let aabb = Aabb::new(pt - Vector::splat(max_dist), pt + Vector::splat(max_dist));+ let mut sq_smallest_dist = Real::MAX;+ let mut best_proj = None;++ self.map_elements_in_local_aabb(&aabb, &mut |_, triangle| {+ let proj = triangle.project_local_point(pt, solid);+ let sq_dist = (pt - proj.point).length_squared();++ if sq_dist < sq_smallest_dist {+ sq_smallest_dist = sq_dist;++ if sq_dist.sqrt() <= max_dist {+ best_proj = Some(proj);+ }+ }+ });++ best_proj+ }++ #[inline]+ fn project_local_point(&self, point: Vector, solid: bool) -> PointProjection {+ // Grow a search neighborhood around `point` geometrically instead of iterating on+ // every element. A projection found at `dist <= max_dist` is the global closest+ // one: any closer element would intersect the ball of radius `dist` around+ // `point`, which the searched AABB contains.+ let root_aabb = self.root_aabb();+ let extents = root_aabb.extents();++ // Distance beyond which the search AABB covers every cell, making the search+ // below exhaustive.+ let max_search_dist = (point - root_aabb.center()).length() + extents.length();++ #[cfg(feature = "dim2")]+ let cell_size = self.cell_width();+ #[cfg(feature = "dim3")]+ let cell_size = self.cell_width().max(self.cell_height());++ // Initial guess: distance to the root AABB plus one cell, so the first search+ // usually visits only a few cells.+ let dist_to_aabb = (point - point.clamp(root_aabb.mins, root_aabb.maxs)).length();+ let mut search_dist = (dist_to_aabb + cell_size).max(max_search_dist * 1.0e-4);++ // TODO: the search AABB only grows, so each iteration re-tests the elements the+ // previous ones already tested. Visit only the ring added by each step.+ while search_dist < max_search_dist {+ if let Some(proj) = self.project_local_point_with_max_dist(point, solid, search_dist) {+ return proj;+ }++ search_dist *= 4.0;+ }++ self.project_local_point_with_max_dist(point, solid, max_search_dist)+ .unwrap_or_else(|| PointProjection::new(false, point))+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, point: Vector) -> (PointProjection, FeatureId) {+ // TODO: compute the feature properly.+ (self.project_local_point(point, false), FeatureId::Unknown)+ }++ // TODO: implement distance_to_point too?++ #[inline]+ fn contains_local_point(&self, _point: Vector) -> bool {+ false+ }+}++impl PointQueryWithLocation for HeightField {+ type Location = (usize, TrianglePointLocation);++ #[inline]+ fn project_local_point_and_get_location(+ &self,+ _point: Vector,+ _: bool,+ ) -> (PointProjection, Self::Location) {+ unimplemented!()+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_query.rs b/renderer/third_party/parry3d/src/query/point/point_query.rsnew file mode 100644index 0000000..7b66d3e--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_query.rs@@ -0,0 +1,353 @@+use crate::math::{Pose, Real, Vector};+use crate::shape::{FeatureId, SubShapeId};++/// The result of projecting a point onto a shape.+///+/// Vector projection finds the closest point on a shape's surface to a given query point.+/// This is fundamental for many geometric queries including distance calculation,+/// collision detection, and surface sampling.+///+/// # Fields+///+/// - **is_inside**: Whether the query point is inside the shape+/// - **point**: The closest point on the shape's surface+///+/// # Inside vs Outside+///+/// The `is_inside` flag indicates the query point's location relative to the shape:+/// - `true`: Query point is inside the shape (projection is on boundary)+/// - `false`: Query point is outside the shape (projection is nearest surface point)+///+/// # Solid Parameter+///+/// Most projection functions take a `solid` parameter:+/// - `solid = true`: Shape is treated as solid (filled interior)+/// - `solid = false`: Shape is treated as hollow (surface only)+///+/// This affects `is_inside` calculation for points in the interior.+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::PointQuery;+/// use parry3d::shape::Ball;+/// use parry3d::math::{Vector, Pose};+///+/// let ball = Ball::new(5.0);+/// let ball_pos = Pose::translation(10.0, 0.0, 0.0);+///+/// // Project a point outside the ball+/// let outside_point = Vector::ZERO;+/// let proj = ball.project_point(&ball_pos, outside_point, true);+///+/// // Closest point on ball surface+/// assert_eq!(proj.point, Vector::new(5.0, 0.0, 0.0));+/// assert!(!proj.is_inside);+///+/// // Project a point inside the ball+/// let inside_point = Vector::new(10.0, 0.0, 0.0); // At center+/// let proj2 = ball.project_point(&ball_pos, inside_point, true);+/// assert!(proj2.is_inside);+/// # }+/// ```+#[derive(Copy, Clone, Debug, Default)]+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+pub struct PointProjection {+ /// The closest point on the shape's surface to the query point.+ ///+ /// If `is_inside = true`, this is the nearest point on the boundary.+ /// If `is_inside = false`, this is the nearest surface point.+ pub point: Vector,++ /// Whether the query point was inside the shape.+ ///+ /// - `true`: Vector is in the interior (for solid shapes)+ /// - `false`: Vector is outside the shape+ pub is_inside: bool,++ /// The sub-shape the point projects onto.+ ///+ /// Identifies the part of a composite shape that answered: a triangle of a+ /// [`TriMesh`](crate::shape::TriMesh), a part of a [`Compound`](crate::shape::Compound), a+ /// voxel of a [`Voxels`](crate::shape::Voxels), and so on. Always `0` for a shape with no+ /// sub-shapes.+ pub subshape: SubShapeId,+}++impl PointProjection {+ /// Initializes a new `PointProjection`.+ pub fn new(is_inside: bool, point: Vector) -> Self {+ PointProjection {+ is_inside,+ point,+ subshape: 0,+ }+ }++ /// Sets the sub-shape this projection came from.+ pub fn with_subshape(mut self, subshape: SubShapeId) -> Self {+ self.subshape = subshape;+ self+ }++ /// Transforms `self.point` by `pos`.+ pub fn transform_by(&self, pos: &Pose) -> Self {+ PointProjection {+ is_inside: self.is_inside,+ point: pos * self.point,+ subshape: self.subshape,+ }+ }++ /// Returns `true` if `Self::is_inside` is `true` or if the distance between the projected point and `point` is smaller than `min_dist`.+ pub fn is_inside_eps(&self, original_point: Vector, min_dist: Real) -> bool {+ self.is_inside || (original_point - self.point).length_squared() < min_dist * min_dist+ }+}++/// Trait for shapes that support point projection and containment queries.+///+/// This trait provides methods to:+/// - Project points onto the shape's surface+/// - Calculate distance from a point to the shape+/// - Test if a point is inside the shape+///+/// All major shapes implement this trait, making it easy to perform point queries+/// on any collision shape.+///+/// # Methods Overview+///+/// - **Projection**: `project_point()`, `project_local_point()`+/// - **Distance**: `distance_to_point()`, `distance_to_local_point()`+/// - **Containment**: `contains_point()`, `contains_local_point()`+///+/// # Local vs World Space+///+/// Methods with `local_` prefix work in the shape's local coordinate system:+/// - **Local methods**: Vector must be in shape's coordinate frame+/// - **World methods**: Vector in world space, shape transformation applied+///+/// # Solid Parameter+///+/// The `solid` parameter affects how interior points are handled:+/// - `solid = true`: Shape is filled (has interior volume/area)+/// - `solid = false`: Shape is hollow (surface only, no interior)+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::PointQuery;+/// use parry3d::shape::Cuboid;+/// use parry3d::math::{Vector, Pose};+///+/// let cuboid = Cuboid::new(Vector::splat(1.0));+/// let cuboid_pos = Pose::translation(5.0, 0.0, 0.0);+///+/// let query_point = Vector::ZERO;+///+/// // Project point onto cuboid surface+/// let projection = cuboid.project_point(&cuboid_pos, query_point, true);+/// println!("Closest point on cuboid: {:?}", projection.point);+/// println!("Is inside: {}", projection.is_inside);+///+/// // Calculate distance to cuboid+/// let distance = cuboid.distance_to_point(&cuboid_pos, query_point, true);+/// println!("Distance: {}", distance);+///+/// // Test if point is inside cuboid+/// let is_inside = cuboid.contains_point(&cuboid_pos, query_point);+/// println!("Contains: {}", is_inside);+/// # }+/// ```+pub trait PointQuery {+ /// Projects a point onto the shape, with a maximum distance limit.+ ///+ /// Returns `None` if the projection would be further than `max_dist` from the query point.+ /// This is useful for optimization when you only care about nearby projections.+ ///+ /// The point is in the shape's local coordinate system.+ ///+ /// # Arguments+ ///+ /// * `pt` - The point to project (in local space)+ /// * `solid` - Whether to treat the shape as solid (filled)+ /// * `max_dist` - Maximum distance to consider+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::PointQuery;+ /// use parry3d::shape::Ball;+ /// use parry3d::math::Vector;+ ///+ /// let ball = Ball::new(1.0);+ /// let far_point = Vector::new(100.0, 0.0, 0.0);+ ///+ /// // Projection exists but is far away+ /// assert!(ball.project_local_point(far_point, true).point.x > 0.0);+ ///+ /// // With max distance limit of 10, projection is rejected+ /// assert!(ball.project_local_point_with_max_dist(far_point, true, 10.0).is_none());+ ///+ /// // Nearby point is accepted+ /// let near_point = Vector::new(2.0, 0.0, 0.0);+ /// assert!(ball.project_local_point_with_max_dist(near_point, true, 10.0).is_some());+ /// # }+ /// ```+ fn project_local_point_with_max_dist(+ &self,+ pt: Vector,+ solid: bool,+ max_dist: Real,+ ) -> Option<PointProjection> {+ let proj = self.project_local_point(pt, solid);+ if (proj.point - pt).length() > max_dist {+ None+ } else {+ Some(proj)+ }+ }++ /// Projects a point on `self` transformed by `m`, unless the projection lies further than the given max distance.+ fn project_point_with_max_dist(+ &self,+ m: &Pose,+ pt: Vector,+ solid: bool,+ max_dist: Real,+ ) -> Option<PointProjection> {+ self.project_local_point_with_max_dist(m.inverse_transform_point(pt), solid, max_dist)+ .map(|proj| proj.transform_by(m))+ }++ /// Projects a point on `self`.+ ///+ /// The point is assumed to be expressed in the local-space of `self`.+ fn project_local_point(&self, pt: Vector, solid: bool) -> PointProjection;++ /// Projects a point on the boundary of `self` and returns the id of the+ /// feature the point was projected on.+ fn project_local_point_and_get_feature(&self, pt: Vector) -> (PointProjection, FeatureId);++ /// Computes the minimal distance between a point and `self`.+ fn distance_to_local_point(&self, pt: Vector, solid: bool) -> Real {+ let proj = self.project_local_point(pt, solid);+ let dist = (pt - proj.point).length();++ if solid || !proj.is_inside {+ dist+ } else {+ -dist+ }+ }++ /// Tests if the given point is inside of `self`.+ fn contains_local_point(&self, pt: Vector) -> bool {+ self.project_local_point(pt, true).is_inside+ }++ /// Projects a point on `self` transformed by `m`.+ fn project_point(&self, m: &Pose, pt: Vector, solid: bool) -> PointProjection {+ self.project_local_point(m.inverse_transform_point(pt), solid)+ .transform_by(m)+ }++ /// Computes the minimal distance between a point and `self` transformed by `m`.+ #[inline]+ fn distance_to_point(&self, m: &Pose, pt: Vector, solid: bool) -> Real {+ self.distance_to_local_point(m.inverse_transform_point(pt), solid)+ }++ /// Projects a point on the boundary of `self` transformed by `m` and returns the id of the+ /// feature the point was projected on.+ fn project_point_and_get_feature(&self, m: &Pose, pt: Vector) -> (PointProjection, FeatureId) {+ let res = self.project_local_point_and_get_feature(m.inverse_transform_point(pt));+ (res.0.transform_by(m), res.1)+ }++ /// Tests if the given point is inside of `self` transformed by `m`.+ #[inline]+ fn contains_point(&self, m: &Pose, pt: Vector) -> bool {+ self.contains_local_point(m.inverse_transform_point(pt))+ }+}++/// Returns shape-specific info in addition to generic projection information+///+/// One requirement for the `PointQuery` trait is to be usable as a trait+/// object. Unfortunately this precludes us from adding an associated type to it+/// that might allow us to return shape-specific information in addition to the+/// general information provided in `PointProjection`. This is where+/// `PointQueryWithLocation` comes in. It forgoes the ability to be used as a trait+/// object in exchange for being able to provide shape-specific projection+/// information.+///+/// Any shapes that implement `PointQuery` but are able to provide extra+/// information, can implement `PointQueryWithLocation` in addition and have their+/// `PointQuery::project_point` implementation just call out to+/// `PointQueryWithLocation::project_point_and_get_location`.+pub trait PointQueryWithLocation {+ /// Additional shape-specific projection information+ ///+ /// In addition to the generic projection information returned in+ /// `PointProjection`, implementations might provide shape-specific+ /// projection info. The type of this shape-specific information is defined+ /// by this associated type.+ type Location;++ /// Projects a point on `self`.+ fn project_local_point_and_get_location(+ &self,+ pt: Vector,+ solid: bool,+ ) -> (PointProjection, Self::Location);++ /// Projects a point on `self` transformed by `m`.+ fn project_point_and_get_location(+ &self,+ m: &Pose,+ pt: Vector,+ solid: bool,+ ) -> (PointProjection, Self::Location) {+ let res = self.project_local_point_and_get_location(m.inverse_transform_point(pt), solid);+ (res.0.transform_by(m), res.1)+ }++ /// Projects a point on `self`, with a maximum projection distance.+ fn project_local_point_and_get_location_with_max_dist(+ &self,+ pt: Vector,+ solid: bool,+ max_dist: Real,+ ) -> Option<(PointProjection, Self::Location)> {+ let (proj, location) = self.project_local_point_and_get_location(pt, solid);+ if (proj.point - pt).length() > max_dist {+ None+ } else {+ Some((proj, location))+ }+ }++ /// Projects a point on `self` transformed by `m`, with a maximum projection distance.+ fn project_point_and_get_location_with_max_dist(+ &self,+ m: &Pose,+ pt: Vector,+ solid: bool,+ max_dist: Real,+ ) -> Option<(PointProjection, Self::Location)> {+ self.project_local_point_and_get_location_with_max_dist(+ m.inverse_transform_point(pt),+ solid,+ max_dist,+ )+ .map(|res| (res.0.transform_by(m), res.1))+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_round_shape.rs b/renderer/third_party/parry3d/src/query/point/point_round_shape.rsnew file mode 100644index 0000000..5800090--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_round_shape.rs@@ -0,0 +1,32 @@+use crate::math::Vector;+#[cfg(feature = "alloc")]+use crate::query::gjk::VoronoiSimplex;+use crate::query::{PointProjection, PointQuery};+use crate::shape::{FeatureId, RoundShape, SupportMap};++// TODO: if PointQuery had a `project_point_with_normal` method, we could just+// call this and adjust the projected point accordingly.+impl<S: SupportMap> PointQuery for RoundShape<S> {+ #[inline]+ #[allow(unreachable_code)]+ #[allow(clippy::diverging_sub_expression)]+ fn project_local_point(&self, _point: Vector, _solid: bool) -> PointProjection {+ #[cfg(not(feature = "alloc"))]+ return unimplemented!(+ "The projection of points on a round shape isn't supported without alloc yet."+ );++ #[cfg(feature = "alloc")]+ return crate::query::details::local_point_projection_on_support_map(+ self,+ &mut VoronoiSimplex::new(),+ _point,+ _solid,+ );+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, point: Vector) -> (PointProjection, FeatureId) {+ (self.project_local_point(point, false), FeatureId::Unknown)+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_segment.rs b/renderer/third_party/parry3d/src/query/point/point_segment.rsnew file mode 100644index 0000000..4fa5eb0--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_segment.rs@@ -0,0 +1,77 @@+use crate::math::Vector;+use crate::query::{PointProjection, PointQuery, PointQueryWithLocation};+use crate::shape::{FeatureId, Segment, SegmentPointLocation};+use crate::utils::relative_eq_vector;++impl PointQuery for Segment {+ #[inline]+ fn project_local_point(&self, pt: Vector, solid: bool) -> PointProjection {+ self.project_local_point_and_get_location(pt, solid).0+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, pt: Vector) -> (PointProjection, FeatureId) {+ let (proj, loc) = self.project_local_point_and_get_location(pt, false);+ let feature = match loc {+ SegmentPointLocation::OnVertex(i) => FeatureId::Vertex(i),+ SegmentPointLocation::OnEdge(..) => {+ #[cfg(feature = "dim2")]+ {+ let dir = self.scaled_direction();+ let dpt = pt - proj.point;+ if dpt.perp_dot(dir) >= 0.0 {+ FeatureId::Face(0)+ } else {+ FeatureId::Face(1)+ }+ }++ #[cfg(feature = "dim3")]+ {+ FeatureId::Edge(0)+ }+ }+ };++ (proj, feature)+ }++ // NOTE: the default implementation of `.distance_to_point(...)` will return the error that was+ // eaten by the `::approx_eq(...)` on `project_point(...)`.+}++impl PointQueryWithLocation for Segment {+ type Location = SegmentPointLocation;++ #[inline]+ fn project_local_point_and_get_location(+ &self,+ pt: Vector,+ _: bool,+ ) -> (PointProjection, Self::Location) {+ let ab = self.b - self.a;+ let ap = pt - self.a;+ let ab_ap = ab.dot(ap);+ let sqnab = ab.length_squared();++ let (location, proj) = if ab_ap <= 0.0 {+ // Voronoï region of vertex 'a'.+ (SegmentPointLocation::OnVertex(0), self.a)+ } else if ab_ap >= sqnab {+ // Voronoï region of vertex 'b'.+ (SegmentPointLocation::OnVertex(1), self.b)+ } else {+ assert!(sqnab != 0.0);++ // Voronoï region of the segment interior.+ let u = ab_ap / sqnab;+ let bcoords = [1.0 - u, u];+ (SegmentPointLocation::OnEdge(bcoords), self.a + ab * u)+ };++ // TODO: is this acceptable?+ let inside = relative_eq_vector(proj, pt);++ (PointProjection::new(inside, proj), location)+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_support_map.rs b/renderer/third_party/parry3d/src/query/point/point_support_map.rsnew file mode 100644index 0000000..c400d4b--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_support_map.rs@@ -0,0 +1,99 @@+use crate::math::{Pose, Vector};+#[cfg(feature = "alloc")]+use crate::query::epa::EPA;+use crate::query::gjk::{self, ConstantOrigin, CsoPoint, VoronoiSimplex};+use crate::query::{PointProjection, PointQuery};+#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+use crate::shape::ConvexPolygon;+#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+use crate::shape::ConvexPolyhedron;+use crate::shape::{FeatureId, SupportMap};++/// Projects a point on a shape using the GJK algorithm.+pub fn local_point_projection_on_support_map<G>(+ shape: &G,+ simplex: &mut VoronoiSimplex,+ point: Vector,+ solid: bool,+) -> PointProjection+where+ G: SupportMap,+{+ #[cfg(feature = "dim2")]+ let m = Pose::new(-point, 0.0);+ #[cfg(feature = "dim3")]+ let m = Pose::new(-point, Vector::ZERO);+ #[cfg(feature = "dim2")]+ let m_inv = Pose::new(point, 0.0);+ #[cfg(feature = "dim3")]+ let m_inv = Pose::new(point, Vector::ZERO);+ let dir = (-m.translation).try_normalize().unwrap_or(Vector::X);+ let support_point = CsoPoint::from_shapes(&m_inv, shape, &ConstantOrigin, dir);++ simplex.reset(support_point);++ if let Some(proj) = gjk::project_origin(&m, shape, simplex) {+ PointProjection::new(false, proj)+ } else if solid {+ PointProjection::new(true, point)+ } else {+ let mut epa = EPA::new();+ if let Some(pt) = epa.project_origin(&m, shape, simplex) {+ PointProjection::new(true, pt)+ } else {+ // return match minkowski_sampling::project_origin(&m, shape, simplex) {+ // Some(p) => PointProjection::new(true, p + point),+ // None => PointProjection::new(true, *point),+ // };++ //// All failed.+ PointProjection::new(true, point)+ }+ }+}++#[cfg(feature = "dim3")]+impl PointQuery for ConvexPolyhedron {+ #[inline]+ fn project_local_point(&self, point: Vector, solid: bool) -> PointProjection {+ local_point_projection_on_support_map(self, &mut VoronoiSimplex::new(), point, solid)+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, point: Vector) -> (PointProjection, FeatureId) {+ let proj = self.project_local_point(point, false);+ let dpt = point - proj.point;+ let local_dir = if proj.is_inside { -dpt } else { dpt };++ if let Some(local_dir) = (local_dir).try_normalize() {+ let feature = self.support_feature_id_toward(local_dir);+ (proj, feature)+ } else {+ (proj, FeatureId::Unknown)+ }+ }+}++#[cfg(feature = "dim2")]+impl PointQuery for ConvexPolygon {+ #[inline]+ fn project_local_point(&self, point: Vector, solid: bool) -> PointProjection {+ local_point_projection_on_support_map(self, &mut VoronoiSimplex::new(), point, solid)+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, point: Vector) -> (PointProjection, FeatureId) {+ let proj = self.project_local_point(point, false);+ let dpt = point - proj.point;+ let local_dir = if proj.is_inside { -dpt } else { dpt };++ if let Some(local_dir) = (local_dir).try_normalize() {+ let feature = self.support_feature_id_toward(local_dir);+ (proj, feature)+ } else {+ (proj, FeatureId::Unknown)+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_tetrahedron.rs b/renderer/third_party/parry3d/src/query/point/point_tetrahedron.rsnew file mode 100644index 0000000..faa3df6--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_tetrahedron.rs@@ -0,0 +1,337 @@+use crate::math::{Real, Vector};+use crate::query::{PointProjection, PointQuery, PointQueryWithLocation};+use crate::shape::{FeatureId, Tetrahedron, TetrahedronPointLocation};++impl PointQuery for Tetrahedron {+ #[inline]+ fn project_local_point(&self, pt: Vector, solid: bool) -> PointProjection {+ self.project_local_point_and_get_location(pt, solid).0+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, pt: Vector) -> (PointProjection, FeatureId) {+ let (proj, loc) = self.project_local_point_and_get_location(pt, false);+ let feature = match loc {+ TetrahedronPointLocation::OnVertex(i) => FeatureId::Vertex(i),+ TetrahedronPointLocation::OnEdge(i, _) => FeatureId::Edge(i),+ TetrahedronPointLocation::OnFace(i, _) => FeatureId::Face(i),+ TetrahedronPointLocation::OnSolid => unreachable!(),+ };++ (proj, feature)+ }+}++impl PointQueryWithLocation for Tetrahedron {+ type Location = TetrahedronPointLocation;++ #[inline]+ fn project_local_point_and_get_location(+ &self,+ pt: Vector,+ solid: bool,+ ) -> (PointProjection, Self::Location) {+ let ab = self.b - self.a;+ let ac = self.c - self.a;+ let ad = self.d - self.a;+ let ap = pt - self.a;++ /*+ * Voronoï regions of vertices.+ */+ let ap_ab = ap.dot(ab);+ let ap_ac = ap.dot(ac);+ let ap_ad = ap.dot(ad);++ if ap_ab <= 0.0 && ap_ac <= 0.0 && ap_ad <= 0.0 {+ // Voronoï region of `a`.+ let proj = PointProjection::new(false, self.a);+ return (proj, TetrahedronPointLocation::OnVertex(0));+ }++ let bc = self.c - self.b;+ let bd = self.d - self.b;+ let bp = pt - self.b;++ let bp_bc = bp.dot(bc);+ let bp_bd = bp.dot(bd);+ let bp_ab = bp.dot(ab);++ if bp_bc <= 0.0 && bp_bd <= 0.0 && bp_ab >= 0.0 {+ // Voronoï region of `b`.+ let proj = PointProjection::new(false, self.b);+ return (proj, TetrahedronPointLocation::OnVertex(1));+ }++ let cd = self.d - self.c;+ let cp = pt - self.c;++ let cp_ac = cp.dot(ac);+ let cp_bc = cp.dot(bc);+ let cp_cd = cp.dot(cd);++ if cp_cd <= 0.0 && cp_bc >= 0.0 && cp_ac >= 0.0 {+ // Voronoï region of `c`.+ let proj = PointProjection::new(false, self.c);+ return (proj, TetrahedronPointLocation::OnVertex(2));+ }++ let dp = pt - self.d;++ let dp_cd = dp.dot(cd);+ let dp_bd = dp.dot(bd);+ let dp_ad = dp.dot(ad);++ if dp_ad >= 0.0 && dp_bd >= 0.0 && dp_cd >= 0.0 {+ // Voronoï region of `d`.+ let proj = PointProjection::new(false, self.d);+ return (proj, TetrahedronPointLocation::OnVertex(3));+ }++ /*+ * Voronoï regions of edges.+ */+ #[inline(always)]+ fn check_edge(+ i: usize,+ a: Vector,+ _: Vector,+ nabc: Vector,+ nabd: Vector,+ ap: Vector,+ ab: Vector,+ ap_ab: Real, /*ap_ac: Real, ap_ad: Real,*/+ bp_ab: Real, /*bp_ac: Real, bp_ad: Real*/+ ) -> (+ Real,+ Real,+ Option<(PointProjection, TetrahedronPointLocation)>,+ ) {+ let ab_ab = ap_ab - bp_ab;++ // NOTE: The following avoids the subsequent cross and dot products but are not+ // numerically stable.+ //+ // let dabc = ap_ab * (ap_ac - bp_ac) - ap_ac * ab_ab;+ // let dabd = ap_ab * (ap_ad - bp_ad) - ap_ad * ab_ab;++ let ap_x_ab = ap.cross(ab);+ let dabc = ap_x_ab.dot(nabc);+ let dabd = ap_x_ab.dot(nabd);++ // TODO: the case where ab_ab == 0.0 is not well defined.+ if ab_ab != 0.0 && dabc >= 0.0 && dabd >= 0.0 && ap_ab >= 0.0 && ap_ab <= ab_ab {+ // Voronoi region of `ab`.+ let u = ap_ab / ab_ab;+ let bcoords = [1.0 - u, u];+ let res = a + ab * u;+ let proj = PointProjection::new(false, res);+ (+ dabc,+ dabd,+ Some((proj, TetrahedronPointLocation::OnEdge(i as u32, bcoords))),+ )+ } else {+ (dabc, dabd, None)+ }+ }++ // Voronoï region of ab.+ // let bp_ad = bp_bd + bp_ab;+ // let bp_ac = bp_bc + bp_ab;+ let nabc = ab.cross(ac);+ let nabd = ab.cross(ad);+ let (dabc, dabd, res) = check_edge(+ 0, self.a, self.b, nabc, nabd, ap, ab, ap_ab,+ /*ap_ac, ap_ad,*/ bp_ab, /*, bp_ac, bp_ad*/+ );+ if let Some(res) = res {+ return res;+ }++ // Voronoï region of ac.+ // Substitutions (wrt. ab):+ // b -> c+ // c -> d+ // d -> b+ // let cp_ab = cp_ac - cp_bc;+ // let cp_ad = cp_cd + cp_ac;+ let nacd = ac.cross(ad);+ let (dacd, dacb, res) = check_edge(+ 1, self.a, self.c, nacd, -nabc, ap, ac, ap_ac,+ /*ap_ad, ap_ab,*/ cp_ac, /*, cp_ad, cp_ab*/+ );+ if let Some(res) = res {+ return res;+ }++ // Voronoï region of ad.+ // Substitutions (wrt. ab):+ // b -> d+ // c -> b+ // d -> c+ // let dp_ac = dp_ad - dp_cd;+ // let dp_ab = dp_ad - dp_bd;+ let (dadb, dadc, res) = check_edge(+ 2, self.a, self.d, -nabd, -nacd, ap, ad, ap_ad,+ /*ap_ab, ap_ac,*/ dp_ad, /*, dp_ab, dp_ac*/+ );+ if let Some(res) = res {+ return res;+ }++ // Voronoï region of bc.+ // Substitutions (wrt. ab):+ // a -> b+ // b -> c+ // c -> a+ // let cp_bd = cp_cd + cp_bc;+ let nbcd = bc.cross(bd);+ // NOTE: nabc = nbcd+ let (dbca, dbcd, res) = check_edge(+ 3, self.b, self.c, nabc, nbcd, bp, bc, bp_bc,+ /*-bp_ab, bp_bd,*/ cp_bc, /*, -cp_ab, cp_bd*/+ );+ if let Some(res) = res {+ return res;+ }++ // Voronoï region of bd.+ // Substitutions (wrt. ab):+ // a -> b+ // b -> d+ // d -> a++ // let dp_bc = dp_bd - dp_cd;+ // NOTE: nbdc = -nbcd+ // NOTE: nbda = nabd+ let (dbdc, dbda, res) = check_edge(+ 4, self.b, self.d, -nbcd, nabd, bp, bd, bp_bd,+ /*bp_bc, -bp_ab,*/ dp_bd, /*, dp_bc, -dp_ab*/+ );+ if let Some(res) = res {+ return res;+ }++ // Voronoï region of cd.+ // Substitutions (wrt. ab):+ // a -> c+ // b -> d+ // c -> a+ // d -> b+ // NOTE: ncda = nacd+ // NOTE: ncdb = nbcd+ let (dcda, dcdb, res) = check_edge(+ 5, self.c, self.d, nacd, nbcd, cp, cd, cp_cd,+ /*-cp_ac, -cp_bc,*/ dp_cd, /*, -dp_ac, -dp_bc*/+ );+ if let Some(res) = res {+ return res;+ }++ /*+ * Voronoï regions of faces.+ */+ #[inline(always)]+ fn check_face(+ i: usize,+ a: Vector,+ b: Vector,+ c: Vector,+ ap: Vector,+ bp: Vector,+ cp: Vector,+ ab: Vector,+ ac: Vector,+ ad: Vector,+ dabc: Real,+ dbca: Real,+ dacb: Real,+ /* ap_ab: Real, bp_ab: Real, cp_ab: Real,+ ap_ac: Real, bp_ac: Real, cp_ac: Real, */+ ) -> Option<(PointProjection, TetrahedronPointLocation)> {+ if dabc < 0.0 && dbca < 0.0 && dacb < 0.0 {+ let n = ab.cross(ac); // TODO: is is possible to avoid this cross product?+ if n.dot(ad) * n.dot(ap) < 0.0 {+ // Voronoï region of the face.++ // NOTE:+ // The following avoids expansive computations but are not very+ // numerically stable.+ //+ // let va = bp_ab * cp_ac - cp_ab * bp_ac;+ // let vb = cp_ab * ap_ac - ap_ab * cp_ac;+ // let vc = ap_ab * bp_ac - bp_ab * ap_ac;++ // NOTE: the normalization may fail even if the dot products+ // above were < 0. This happens, e.g., when we use fixed-point+ // numbers and there are not enough decimal bits to perform+ // the normalization.+ let normal = n.try_normalize()?;+ let vc = normal.dot(ap.cross(bp));+ let va = normal.dot(bp.cross(cp));+ let vb = normal.dot(cp.cross(ap));++ let denom = va + vb + vc;+ assert!(denom != 0.0);+ let inv_denom = 1.0 / denom;++ let bcoords = [va * inv_denom, vb * inv_denom, vc * inv_denom];+ let res = a * bcoords[0] + b * bcoords[1] + c * bcoords[2];+ let proj = PointProjection::new(false, res);++ return Some((proj, TetrahedronPointLocation::OnFace(i as u32, bcoords)));+ }+ }+ None+ }++ // Face abc.+ if let Some(res) = check_face(+ 0, self.a, self.b, self.c, ap, bp, cp, ab, ac, ad, dabc, dbca,+ dacb,+ /*ap_ab, bp_ab, cp_ab,+ ap_ac, bp_ac, cp_ac*/+ ) {+ return res;+ }++ // Face abd.+ if let Some(res) = check_face(+ 1, self.a, self.b, self.d, ap, bp, dp, ab, ad, ac, dadb, dabd,+ dbda,+ /*ap_ab, bp_ab, dp_ab,+ ap_ad, bp_ad, dp_ad*/+ ) {+ return res;+ }+ // Face acd.+ if let Some(res) = check_face(+ 2, self.a, self.c, self.d, ap, cp, dp, ac, ad, ab, dacd, dcda,+ dadc,+ /*ap_ac, cp_ac, dp_ac,+ ap_ad, cp_ad, dp_ad*/+ ) {+ return res;+ }+ // Face bcd.+ if let Some(res) = check_face(+ 3, self.b, self.c, self.d, bp, cp, dp, bc, bd, -ab, dbcd, dcdb,+ dbdc,+ /*bp_bc, cp_bc, dp_bc,+ bp_bd, cp_bd, dp_bd*/+ ) {+ return res;+ }++ if !solid {+ // XXX: implement the non-solid projection.+ unimplemented!(+ "Non-solid ray-cast/point projection on a tetrahedron is not yet implemented."+ )+ }++ let proj = PointProjection::new(true, pt);+ (proj, TetrahedronPointLocation::OnSolid)+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_triangle.rs b/renderer/third_party/parry3d/src/query/point/point_triangle.rsnew file mode 100644index 0000000..810e3e3--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_triangle.rs@@ -0,0 +1,318 @@+use crate::math::{Real, Vector, DIM};+use crate::query::{PointProjection, PointQuery, PointQueryWithLocation};+use crate::shape::{FeatureId, Segment, SegmentPointLocation, Triangle, TrianglePointLocation};+#[cfg(feature = "dim3")]+use crate::utils::relative_eq_vector;++#[inline]+fn compute_result(pt: Vector, proj: Vector) -> PointProjection {+ #[cfg(feature = "dim2")]+ {+ PointProjection::new(pt == proj, proj)+ }++ #[cfg(feature = "dim3")]+ {+ // TODO: is this acceptable to assume the point is inside of the+ // triangle if it is close enough?+ let inside = relative_eq_vector(proj, pt);+ PointProjection::new(inside, proj)+ }+}++impl PointQuery for Triangle {+ #[inline]+ fn project_local_point(&self, pt: Vector, solid: bool) -> PointProjection {+ self.project_local_point_and_get_location(pt, solid).0+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, pt: Vector) -> (PointProjection, FeatureId) {+ let (proj, loc) = if DIM == 2 {+ self.project_local_point_and_get_location(pt, false)+ } else {+ self.project_local_point_and_get_location(pt, true)+ };++ let feature = match loc {+ TrianglePointLocation::OnVertex(i) => FeatureId::Vertex(i),+ #[cfg(feature = "dim3")]+ TrianglePointLocation::OnEdge(i, _) => FeatureId::Edge(i),+ #[cfg(feature = "dim2")]+ TrianglePointLocation::OnEdge(i, _) => FeatureId::Face(i),+ TrianglePointLocation::OnFace(i, _) => FeatureId::Face(i),+ TrianglePointLocation::OnSolid => FeatureId::Face(0),+ };++ (proj, feature)+ }++ // NOTE: the default implementation of `.distance_to_point(...)` will return the error that was+ // eaten by the `::approx_eq(...)` on `project_point(...)`.+}++impl PointQueryWithLocation for Triangle {+ type Location = TrianglePointLocation;++ #[inline]+ fn project_local_point_and_get_location(+ &self,+ pt: Vector,+ solid: bool,+ ) -> (PointProjection, Self::Location) {+ // To understand the ideas, consider reading the slides below+ // https://box2d.org/files/ErinCatto_GJK_GDC2010.pdf++ let a = self.a;+ let b = self.b;+ let c = self.c;++ let ab = b - a;+ let ac = c - a;+ let ap = pt - a;++ let ab_ap = ab.dot(ap);+ let ac_ap = ac.dot(ap);++ if ab_ap <= 0.0 && ac_ap <= 0.0 {+ // Voronoï region of `a`.+ return (compute_result(pt, a), TrianglePointLocation::OnVertex(0));+ }++ let bp = pt - b;+ let ab_bp = ab.dot(bp);+ let ac_bp = ac.dot(bp);++ if ab_bp >= 0.0 && ac_bp <= ab_bp {+ // Voronoï region of `b`.+ return (compute_result(pt, b), TrianglePointLocation::OnVertex(1));+ }++ let cp = pt - c;+ let ab_cp = ab.dot(cp);+ let ac_cp = ac.dot(cp);++ if ac_cp >= 0.0 && ab_cp <= ac_cp {+ // Voronoï region of `c`.+ return (compute_result(pt, c), TrianglePointLocation::OnVertex(2));+ }++ enum ProjectionInfo {+ OnAB,+ OnAC,+ OnBC,+ // The usize indicates if we are on the CW side (0) or CCW side (1) of the face.+ OnFace(usize, Real, Real, Real),+ }++ // Checks on which edge voronoï region the point is.+ // For 2D and 3D, it uses explicit cross/perp products that are+ // more numerically stable.+ fn stable_check_edges_voronoi(+ ab: Vector,+ ac: Vector,+ bc: Vector,+ ap: Vector,+ bp: Vector,+ cp: Vector,+ ab_ap: Real,+ ab_bp: Real,+ ac_ap: Real,+ ac_cp: Real,+ ac_bp: Real,+ ab_cp: Real,+ ) -> ProjectionInfo {+ #[cfg(feature = "dim2")]+ {+ let n = ab.perp_dot(ac);+ let vc = n * ab.perp_dot(ap);+ if vc < 0.0 && ab_ap >= 0.0 && ab_bp <= 0.0 {+ return ProjectionInfo::OnAB;+ }++ let vb = -n * ac.perp_dot(cp);+ if vb < 0.0 && ac_ap >= 0.0 && ac_cp <= 0.0 {+ return ProjectionInfo::OnAC;+ }++ let va = n * bc.perp_dot(bp);+ if va < 0.0 && ac_bp - ab_bp >= 0.0 && ab_cp - ac_cp >= 0.0 {+ return ProjectionInfo::OnBC;+ }++ ProjectionInfo::OnFace(0, va, vb, vc)+ }+ #[cfg(feature = "dim3")]+ {+ let n;++ #[cfg(feature = "improved_fixed_point_support")]+ {+ let scaled_n = ab.cross(ac);+ n = scaled_n.try_normalize(0.0).unwrap_or(scaled_n);+ }++ #[cfg(not(feature = "improved_fixed_point_support"))]+ {+ n = ab.cross(ac);+ }++ let vc = n.dot(ab.cross(ap));+ if vc < 0.0 && ab_ap >= 0.0 && ab_bp <= 0.0 {+ return ProjectionInfo::OnAB;+ }++ let vb = -n.dot(ac.cross(cp));+ if vb < 0.0 && ac_ap >= 0.0 && ac_cp <= 0.0 {+ return ProjectionInfo::OnAC;+ }++ let va = n.dot(bc.cross(bp));+ if va < 0.0 && ac_bp - ab_bp >= 0.0 && ab_cp - ac_cp >= 0.0 {+ return ProjectionInfo::OnBC;+ }++ let clockwise = if n.dot(ap) >= 0.0 { 0 } else { 1 };++ ProjectionInfo::OnFace(clockwise, va, vb, vc)+ }+ }++ let bc = c - b;+ match stable_check_edges_voronoi(+ ab, ac, bc, ap, bp, cp, ab_ap, ab_bp, ac_ap, ac_cp, ac_bp, ab_cp,+ ) {+ ProjectionInfo::OnAB => {+ // Voronoï region of `ab`.+ let v = ab_ap / ab.length_squared();+ let bcoords = [1.0 - v, v];++ let res = a + ab * v;+ return (+ compute_result(pt, res),+ TrianglePointLocation::OnEdge(0, bcoords),+ );+ }+ ProjectionInfo::OnAC => {+ // Voronoï region of `ac`.+ let w = ac_ap / ac.length_squared();+ let bcoords = [1.0 - w, w];++ let res = a + ac * w;+ return (+ compute_result(pt, res),+ TrianglePointLocation::OnEdge(2, bcoords),+ );+ }+ ProjectionInfo::OnBC => {+ // Voronoï region of `bc`.+ let w = bc.dot(bp) / bc.length_squared();+ let bcoords = [1.0 - w, w];++ let res = b + bc * w;+ return (+ compute_result(pt, res),+ TrianglePointLocation::OnEdge(1, bcoords),+ );+ }+ ProjectionInfo::OnFace(face_side, va, vb, vc) => {+ // Voronoï region of the face.+ let denom = va + vb + vc;++ if denom == 0.0 {+ // Collinear vertices: the zero face normal skipped every edge Voronoï+ // test, so projecting on the "face" would report the point as inside+ // (or produce NaNs). A degenerate triangle has no interior, so project+ // on its longest edge regardless of `solid`.+ let sq_ab = ab.length_squared();+ let sq_ac = ac.length_squared();+ let sq_bc = bc.length_squared();++ // (segment, edge id, triangle vertex ids of the segment endpoints)+ let (seg, eid, vids) = if sq_ab >= sq_ac && sq_ab >= sq_bc {+ (Segment::new(a, b), 0, [0, 1])+ } else if sq_ac >= sq_bc {+ (Segment::new(a, c), 2, [0, 2])+ } else {+ (Segment::new(b, c), 1, [1, 2])+ };++ let (proj, loc) = seg.project_local_point_and_get_location(pt, solid);+ let loc = match loc {+ SegmentPointLocation::OnVertex(i) => {+ TrianglePointLocation::OnVertex(vids[i as usize])+ }+ SegmentPointLocation::OnEdge(bcoords) => {+ TrianglePointLocation::OnEdge(eid, bcoords)+ }+ };++ return (proj, loc);+ } else if DIM != 2 {+ // NOTE: divide instead of multiplying by `1.0 / denom`, whose+ // reciprocal overflows to infinity for subnormal `denom`.+ let v = vb / denom;+ let w = vc / denom;+ let bcoords = [1.0 - v - w, v, w];+ let res = a + ab * v + ac * w;++ return (+ compute_result(pt, res),+ TrianglePointLocation::OnFace(face_side as u32, bcoords),+ );+ }+ }+ }++ // Special treatment if we work in 2d because in this case we really are inside of the+ // object.+ if solid {+ (+ PointProjection::new(true, pt),+ TrianglePointLocation::OnSolid,+ )+ } else {+ // We have to project on the closest edge.++ // TODO: this might be optimizable.+ // TODO: be careful with numerical errors.+ let v = ab_ap / (ab_ap - ab_bp); // proj on ab = a + ab * v+ let w = ac_ap / (ac_ap - ac_cp); // proj on ac = a + ac * w+ let u = (ac_bp - ab_bp) / (ac_bp - ab_bp + ab_cp - ac_cp); // proj on bc = b + bc * u++ let bc = c - b;+ let d_ab = ap.length_squared() - (ab.length_squared() * v * v);+ let d_ac = ap.length_squared() - (ac.length_squared() * w * w);+ let d_bc = bp.length_squared() - (bc.length_squared() * u * u);++ let proj;+ let loc;++ if d_ab < d_ac {+ if d_ab < d_bc {+ // ab+ let bcoords = [1.0 - v, v];+ proj = a + ab * v;+ loc = TrianglePointLocation::OnEdge(0, bcoords);+ } else {+ // bc+ let bcoords = [1.0 - u, u];+ proj = b + bc * u;+ loc = TrianglePointLocation::OnEdge(1, bcoords);+ }+ } else if d_ac < d_bc {+ // ac+ let bcoords = [1.0 - w, w];+ proj = a + ac * w;+ loc = TrianglePointLocation::OnEdge(2, bcoords);+ } else {+ // bc+ let bcoords = [1.0 - u, u];+ proj = b + bc * u;+ loc = TrianglePointLocation::OnEdge(1, bcoords);+ }++ (PointProjection::new(true, proj), loc)+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/point/point_voxels.rs b/renderer/third_party/parry3d/src/query/point/point_voxels.rsnew file mode 100644index 0000000..45bf607--- /dev/null+++ b/renderer/third_party/parry3d/src/query/point/point_voxels.rs@@ -0,0 +1,65 @@+use crate::math::{Real, Vector};+use crate::query::{PointProjection, PointQuery};+use crate::shape::{Cuboid, FeatureId, Voxels, VoxelsChunkRef};++impl PointQuery for Voxels {+ #[inline]+ fn project_local_point(&self, pt: Vector, solid: bool) -> PointProjection {+ self.chunk_bvh()+ .project_point(pt, Real::MAX, |chunk_id, _| {+ let chunk = self.chunk_ref(chunk_id);+ chunk+ .project_local_point_and_get_vox_id(pt, solid)+ .map(|(proj, vox)| proj.with_subshape(vox))+ })+ .map(|res| res.1 .1)+ .unwrap_or(PointProjection::new(false, Vector::splat(Real::MAX)))+ }++ #[inline]+ fn project_local_point_and_get_feature(&self, pt: Vector) -> (PointProjection, FeatureId) {+ self.chunk_bvh()+ .project_point_and_get_feature(pt, Real::MAX, |chunk_id, _| {+ let chunk = self.chunk_ref(chunk_id);+ // TODO: report the feature on the voxel; `subshape` already identifies the voxel.+ chunk+ .project_local_point_and_get_vox_id(pt, false)+ .map(|(proj, vox)| (proj.with_subshape(vox), FeatureId::Unknown))+ })+ .map(|res| res.1 .1)+ .unwrap_or((+ PointProjection::new(false, Vector::splat(Real::MAX)),+ FeatureId::Unknown,+ ))+ }+}++impl<'a> VoxelsChunkRef<'a> {+ #[inline]+ fn project_local_point_and_get_vox_id(+ &self,+ pt: Vector,+ solid: bool,+ ) -> Option<(PointProjection, u32)> {+ // TODO: optimize this naive implementation that just iterates on all the voxels+ // from this chunk.+ let base_cuboid = Cuboid::new(self.parent.voxel_size() / 2.0);+ let mut smallest_dist = Real::MAX;+ let mut result = PointProjection::new(false, pt);+ let mut result_vox_id = 0;++ for vox in self.voxels() {+ let mut candidate = base_cuboid.project_local_point(pt - vox.center, solid);+ candidate.point += vox.center;++ let candidate_dist = (candidate.point - pt).length();+ if candidate_dist < smallest_dist {+ result = candidate;+ result_vox_id = vox.linear_id.flat_id();+ smallest_dist = candidate_dist;+ }+ }++ (smallest_dist < Real::MAX).then_some((result, result_vox_id as u32))+ }+}diff --git a/renderer/third_party/parry3d/src/query/query_dispatcher.rs b/renderer/third_party/parry3d/src/query/query_dispatcher.rsnew file mode 100644index 0000000..2c3515a--- /dev/null+++ b/renderer/third_party/parry3d/src/query/query_dispatcher.rs@@ -0,0 +1,668 @@+//! Query dispatcher system for extensible geometric queries.+//!+//! # Overview+//!+//! This module provides the **query dispatcher** abstraction, which allows Parry to perform+//! geometric queries (distance, contact, ray casting, etc.) between different shape types in+//! an extensible and customizable way.+//!+//! # What is a Query Dispatcher?+//!+//! A query dispatcher is an object that knows how to perform geometric queries between pairs+//! of shapes. When you ask "what is the distance between shape A and shape B?", the query+//! dispatcher:+//!+//! 1. Examines the types of both shapes (Ball, Cuboid, ConvexMesh, etc.)+//! 2. Selects the most appropriate algorithm for that shape pair+//! 3. Executes the query and returns the result+//!+//! For example, computing distance between two balls uses a simple formula, while computing+//! distance between two convex meshes requires the GJK algorithm. The query dispatcher+//! handles this selection automatically.+//!+//! # Why Do Query Dispatchers Exist?+//!+//! Query dispatchers provide **extensibility** for several use cases:+//!+//! 1. **Custom Shapes**: If you implement a custom shape type (e.g., a superellipsoid or+//! implicit surface), you can create a custom query dispatcher that knows how to handle+//! queries involving your shape, while delegating other queries to the default dispatcher.+//!+//! 2. **Specialized Algorithms**: You might have a faster algorithm for specific shape pairs+//! in your application domain. A custom dispatcher lets you override just those cases.+//!+//! 3. **Debugging and Profiling**: You can wrap the default dispatcher to log query calls,+//! collect statistics, or inject debug visualizations.+//!+//! 4. **Fallback Chains**: Multiple dispatchers can be chained together using the `chain()`+//! method, so if one dispatcher doesn't support a query, it automatically falls back to+//! the next one.+//!+//! # When to Use Query Dispatchers+//!+//! Most users will never need to directly use or implement query dispatchers. The high-level+//! query functions in [`crate::query`] use the [`DefaultQueryDispatcher`](crate::query::DefaultQueryDispatcher) automatically.+//!+//! You should implement a custom query dispatcher when:+//!+//! - You have custom shape types not supported by Parry+//! - You need specialized algorithms for specific shape pairs+//! - You're integrating Parry into a larger system that needs to intercept queries+//! - You want to add logging, profiling, or debugging to queries+//!+//! # Basic Usage+//!+//! ## Using the Default Dispatcher+//!+//! The simplest way is to use the free functions in [`crate::query`], which use the default+//! dispatcher internally:+//!+//! ```+//! # #[cfg(all(feature = "dim3", feature = "f32"))] {+//! use parry3d::query;+//! use parry3d::shape::Ball;+//! use parry3d::math::Pose;+//!+//! let ball1 = Ball::new(0.5);+//! let ball2 = Ball::new(1.0);+//! let pos1 = Pose::identity();+//! let pos2 = Pose::translation(5.0, 0.0, 0.0);+//!+//! // Uses DefaultQueryDispatcher automatically+//! let distance = query::distance(&pos1, &ball1, &pos2, &ball2);+//! # }+//! ```+//!+//! ## Using a Dispatcher Directly+//!+//! If you need explicit control, you can create and use a dispatcher:+//!+//! ```+//! # #[cfg(all(feature = "dim3", feature = "f32"))] {+//! use parry3d::query::{QueryDispatcher, DefaultQueryDispatcher};+//! use parry3d::shape::Ball;+//! use parry3d::math::Pose;+//!+//! let dispatcher = DefaultQueryDispatcher;+//! let ball1 = Ball::new(0.5);+//! let ball2 = Ball::new(1.0);+//!+//! let pos1 = Pose::identity();+//! let pos2 = Pose::translation(5.0, 0.0, 0.0);+//!+//! // Compute relative position of shape2 in shape1's local space+//! let pos12 = pos1.inv_mul(&pos2);+//!+//! let distance = dispatcher.distance(&pos12, &ball1, &ball2).unwrap();+//! # }+//! ```+//!+//! ## Chaining Dispatchers+//!+//! You can chain multiple dispatchers to create a fallback sequence:+//!+//! ```ignore+//! use parry3d::query::{QueryDispatcher, DefaultQueryDispatcher};+//!+//! // Create a custom dispatcher for your custom shapes+//! let custom = MyCustomDispatcher::new();+//!+//! // Chain it with the default dispatcher as a fallback+//! let dispatcher = custom.chain(DefaultQueryDispatcher);+//!+//! // Now dispatcher will try your custom dispatcher first,+//! // and fall back to the default if it returns Unsupported+//! ```+//!+//! # Implementing a Custom Query Dispatcher+//!+//! To implement a custom query dispatcher, implement the [`QueryDispatcher`] trait:+//!+//! ```ignore+//! use parry3d::query::{QueryDispatcher, Unsupported};+//! use parry3d::shape::Shape;+//! use parry3d::math::{Pose, Real};+//!+//! struct MyDispatcher {+//! // Your dispatcher state+//! }+//!+//! impl QueryDispatcher for MyDispatcher {+//! fn intersection_test(+//! &self,+//! pos12: &Pose,+//! g1: &dyn Shape,+//! g2: &dyn Shape,+//! ) -> Result<ShapeIntersection, Unsupported> {+//! // Try to downcast to your custom shape types+//! if let (Some(my_shape1), Some(my_shape2)) = (+//! g1.as_any().downcast_ref::<MyCustomShape>(),+//! g2.as_any().downcast_ref::<MyCustomShape>(),+//! ) {+//! // Implement your custom intersection test+//! Ok(my_custom_intersection_test(my_shape1, my_shape2, pos12))+//! } else {+//! // Return Unsupported for shape pairs you don't handle+//! Err(Unsupported)+//! }+//! }+//!+//! fn distance(+//! &self,+//! pos12: &Pose,+//! g1: &dyn Shape,+//! g2: &dyn Shape,+//! ) -> Result<ShapeDistance, Unsupported> {+//! // Implement other query methods similarly+//! Err(Unsupported)+//! }+//!+//! // ... implement other required methods+//! }+//! ```+//!+//! # Important Notes+//!+//! ## The `pos12` Parameter+//!+//! All query methods take a `pos12` parameter, which is the **relative position** of shape 2+//! in shape 1's local coordinate frame. This is computed as:+//!+//! ```ignore+//! let pos12 = pos1.inv_mul(&pos2); // Transform from g2's space to g1's space+//! ```+//!+//! This convention reduces the number of transformations needed during queries.+//!+//! ## Thread Safety+//!+//! Query dispatchers must implement `Send + Sync` because they may be shared across threads+//! in parallel collision detection scenarios (e.g., when using Rapier physics engine).+//!+//! ## Error Handling+//!+//! Query methods return `Result<T, Unsupported>`. Return `Err(Unsupported)` when:+//! - The dispatcher doesn't know how to handle the given shape pair+//! - The shapes cannot be queried with the requested operation+//!+//! When chaining dispatchers, returning `Unsupported` allows the next dispatcher in the+//! chain to try handling the query.++use crate::math::{Pose, Real, Vector};+use crate::query::details::ShapeCastOptions;+#[cfg(feature = "alloc")]+use crate::query::{+ contact_manifolds::{ContactManifoldsWorkspace, NormalConstraints},+ ContactManifold,+};+use crate::query::{+ ClosestPoints, Contact, NonlinearRigidMotion, ShapeCastHit, ShapeDistance, ShapeIntersection,+ Unsupported,+};+use crate::shape::Shape;+#[cfg(feature = "alloc")]+use alloc::vec::Vec;++#[cfg(feature = "alloc")]+/// A query dispatcher for queries relying on spatial coherence, including contact-manifold computation.+///+/// This trait extends [`QueryDispatcher`] with methods that maintain persistent state between+/// queries to improve performance through **spatial and temporal coherence**.+///+/// # What is Spatial Coherence?+///+/// Spatial coherence is the principle that objects that are close to each other in one frame+/// are likely to remain close in subsequent frames. Contact manifolds exploit this by:+///+/// 1. Tracking contact points over multiple frames+/// 2. Reusing previous contact information to accelerate new queries+/// 3. Maintaining contact IDs for physics solvers to track persistent contacts+///+/// # Contact Manifolds vs Single Contacts+///+/// - **Single Contact** ([`QueryDispatcher::contact`]): Returns one contact point, suitable+/// for one-off queries or simple collision detection.+///+/// - **Contact Manifold** ([`PersistentQueryDispatcher::contact_manifolds`]): Returns multiple+/// contact points that persist across frames, essential for stable physics simulation.+///+/// # When to Use This Trait+///+/// Use `PersistentQueryDispatcher` when:+/// - Implementing physics simulation that needs stable contact tracking+/// - Building a custom physics engine on top of Parry+/// - Optimizing repeated collision queries between the same shape pairs+///+/// # Generic Parameters+///+/// - `ManifoldData`: Custom data attached to each contact manifold (default: `()`)+/// - `ContactData`: Custom data attached to each contact point (default: `()`)+///+/// These allow physics engines to attach solver-specific data to contacts without modifying+/// Parry's core types.+pub trait PersistentQueryDispatcher<ManifoldData = (), ContactData = ()>: QueryDispatcher {+ /// Compute all the contacts between two shapes.+ ///+ /// The output is written into `manifolds` and `context`. Both can persist+ /// between multiple calls to `contacts` by re-using the result of the previous+ /// call to `contacts`. This persistence can significantly improve collision+ /// detection performances by allowing the underlying algorithms to exploit+ /// spatial and temporal coherence.+ fn contact_manifolds(+ &self,+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &dyn Shape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+ ) -> Result<(), Unsupported>;++ /// Computes the contact-manifold between two convex shapes.+ fn contact_manifold_convex_convex(+ &self,+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &dyn Shape,+ normal_constraints1: Option<&dyn NormalConstraints>,+ normal_constraints2: Option<&dyn NormalConstraints>,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+ ) -> Result<(), Unsupported>;+}++/// Dispatcher for pairwise geometric queries between shapes.+///+/// This is the core trait for performing geometric queries (distance, intersection, contact, etc.)+/// between pairs of shapes in Parry. It provides a uniform interface for querying different shape+/// combinations.+///+/// # Purpose+///+/// The `QueryDispatcher` trait serves as an abstraction layer that:+///+/// 1. **Decouples query algorithms from shape types**: Different shape pairs may require different+/// algorithms (e.g., sphere-sphere uses simple math, while convex-convex uses GJK/EPA).+///+/// 2. **Enables extensibility**: You can implement custom dispatchers to add support for custom+/// shape types or specialized algorithms without modifying Parry's core code.+///+/// 3. **Provides fallback mechanisms**: Dispatchers can be chained together using [`chain()`](Self::chain),+/// allowing graceful fallback when a query is not supported.+///+/// # The `pos12` Parameter Convention+///+/// All query methods in this trait take a `pos12` parameter, which represents the **relative+/// position** of shape 2 (`g2`) in shape 1's (`g1`) local coordinate frame:+///+/// ```ignore+/// pos12 = pos1.inverse() * pos2+/// ```+///+/// This convention is used because:+/// - It reduces redundant transformations during query execution+/// - Many algorithms naturally work in one shape's local space+/// - It's more efficient than passing two separate world-space positions+///+/// When using the high-level query functions, this transformation is done automatically.+///+/// # Query Methods Overview+///+/// The trait provides several categories of queries:+///+/// ## Basic Queries+/// - [`intersection_test`](Self::intersection_test): Boolean intersection check (fastest)+/// - [`distance`](Self::distance): Minimum separating distance+/// - [`closest_points`](Self::closest_points): Pair of closest points+/// - [`contact`](Self::contact): Contact point with penetration depth+///+/// ## Motion Queries (Time of Impact)+/// - [`cast_shapes`](Self::cast_shapes): Linear motion (translation only)+/// - [`cast_shapes_nonlinear`](Self::cast_shapes_nonlinear): Nonlinear motion (translation + rotation)+///+/// # Thread Safety+///+/// Query dispatchers must be `Send + Sync` because they're often shared across threads in:+/// - Parallel collision detection+/// - Physics simulations with multi-threaded broad phase+/// - Game engines with parallel scene queries+///+/// Ensure your custom dispatcher implementations are thread-safe or use appropriate synchronization.+///+/// # Error Handling with `Unsupported`+///+/// All query methods return `Result<T, Unsupported>`. The `Unsupported` error indicates:+///+/// - The dispatcher doesn't know how to handle the given shape pair+/// - The shapes don't support this type of query+/// - The query is mathematically undefined for these shapes+///+/// When chaining dispatchers with [`chain()`](Self::chain), returning `Unsupported` causes the+/// next dispatcher in the chain to be tried.+///+/// # Example: Using the Default Dispatcher+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{QueryDispatcher, DefaultQueryDispatcher};+/// use parry3d::shape::{Ball, Cuboid};+/// use parry3d::math::{Pose, Vector};+///+/// let dispatcher = DefaultQueryDispatcher;+///+/// let ball = Ball::new(1.0);+/// let cuboid = Cuboid::new(Vector::splat(2.0));+///+/// let pos1 = Pose::identity();+/// let pos2 = Pose::translation(5.0, 0.0, 0.0);+/// let pos12 = pos1.inv_mul(&pos2);+///+/// // Test intersection+/// let intersects = dispatcher.intersection_test(&pos12, &ball, &cuboid).unwrap().intersecting;+///+/// // Compute distance+/// let dist = dispatcher.distance(&pos12, &ball, &cuboid).unwrap().distance;+///+/// println!("Intersects: {}, Distance: {}", intersects, dist);+/// # }+/// ```+///+/// # Example: Chaining Dispatchers+///+/// ```ignore+/// # {+/// use parry3d::query::{QueryDispatcher, DefaultQueryDispatcher};+///+/// struct MyCustomDispatcher;+///+/// impl QueryDispatcher for MyCustomDispatcher {+/// fn distance(+/// &self,+/// pos12: &Pose,+/// g1: &dyn Shape,+/// g2: &dyn Shape,+/// ) -> Result<ShapeDistance, Unsupported> {+/// // Handle custom shape types+/// if let Some(my_shape) = g1.as_any().downcast_ref::<MyShape>() {+/// // ... custom distance computation+/// Ok(computed_distance)+/// } else {+/// // Don't know how to handle this, let the next dispatcher try+/// Err(Unsupported)+/// }+/// }+///+/// // ... implement other methods+/// }+///+/// // Chain custom dispatcher with default as fallback+/// let dispatcher = MyCustomDispatcher.chain(DefaultQueryDispatcher);+///+/// // Now all queries try custom dispatcher first, then default+/// let dist = dispatcher.distance(pos12, shape1, shape2)?;+/// # }+/// ```+///+/// # See Also+///+/// - [`DefaultQueryDispatcher`](crate::query::DefaultQueryDispatcher): The built-in implementation used by Parry+/// - [`PersistentQueryDispatcher`]: Extended trait for contact manifold queries+/// - [`crate::query`]: High-level query functions that use dispatchers internally+pub trait QueryDispatcher: Send + Sync {+ /// Tests whether two shapes are intersecting.+ fn intersection_test(+ &self,+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &dyn Shape,+ ) -> Result<ShapeIntersection, Unsupported>;++ /// Computes the minimum distance separating two shapes.+ ///+ /// Returns `0.0` if the objects are touching or penetrating.+ fn distance(+ &self,+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &dyn Shape,+ ) -> Result<ShapeDistance, Unsupported>;++ /// Computes one pair of contact points point between two shapes.+ ///+ /// Returns `None` if the objects are separated by a distance greater than `prediction`.+ fn contact(+ &self,+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &dyn Shape,+ prediction: Real,+ ) -> Result<Option<Contact>, Unsupported>;++ /// Computes the pair of closest points between two shapes.+ ///+ /// Returns `ClosestPoints::Disjoint` if the objects are separated by a distance greater than `max_dist`.+ fn closest_points(+ &self,+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &dyn Shape,+ max_dist: Real,+ ) -> Result<ClosestPoints, Unsupported>;++ /// Computes the smallest time when two shapes under translational movement are separated by a+ /// distance smaller or equal to `distance`.+ ///+ /// Returns `0.0` if the objects are touching or penetrating.+ ///+ /// # Parameters+ /// - `pos12`: the position of the second shape relative to the first shape.+ /// - `local_vel12`: the relative velocity between the two shapes, expressed in the local-space+ /// of the first shape. In other world: `pos1.inverse() * (vel2 - vel1)`.+ /// - `g1`: the first shape involved in the shape-cast.+ /// - `g2`: the second shape involved in the shape-cast.+ /// - `target_dist`: a hit will be returned as soon as the two shapes get closer than `target_dist`.+ /// - `max_time_of_impact`: the maximum allowed travel time. This method returns `None` if the time-of-impact+ /// detected is theater than this value.+ fn cast_shapes(+ &self,+ pos12: &Pose,+ local_vel12: Vector,+ g1: &dyn Shape,+ g2: &dyn Shape,+ options: ShapeCastOptions,+ ) -> Result<Option<ShapeCastHit>, Unsupported>;++ /// Construct a `QueryDispatcher` that falls back on `other` for cases not handled by `self`+ fn chain<U: QueryDispatcher>(self, other: U) -> QueryDispatcherChain<Self, U>+ where+ Self: Sized,+ {+ QueryDispatcherChain(self, other)+ }++ /// Computes the smallest time of impact of two shapes under translational and rotational movement.+ ///+ /// # Parameters+ /// * `motion1` - The motion of the first shape.+ /// * `g1` - The first shape involved in the query.+ /// * `motion2` - The motion of the second shape.+ /// * `g2` - The second shape involved in the query.+ /// * `start_time` - The starting time of the interval where the motion takes place.+ /// * `end_time` - The end time of the interval where the motion takes place.+ /// * `stop_at_penetration` - If the casted shape starts in a penetration state with any+ /// collider, two results are possible. If `stop_at_penetration` is `true` then, the+ /// result will have a `time_of_impact` equal to `start_time`. If `stop_at_penetration` is `false`+ /// then the nonlinear shape-casting will see if further motion wrt. the penetration normal+ /// would result in tunnelling. If it does not (i.e. we have a separating velocity along+ /// that normal) then the nonlinear shape-casting will attempt to find another impact,+ /// at a time `> start_time` that could result in tunnelling.+ fn cast_shapes_nonlinear(+ &self,+ motion1: &NonlinearRigidMotion,+ g1: &dyn Shape,+ motion2: &NonlinearRigidMotion,+ g2: &dyn Shape,+ start_time: Real,+ end_time: Real,+ stop_at_penetration: bool,+ ) -> Result<Option<ShapeCastHit>, Unsupported>;+}++/// A chain of two query dispatchers that provides fallback behavior.+///+/// This struct is created by calling [`QueryDispatcher::chain()`] and allows combining multiple+/// dispatchers into a fallback sequence. When a query is performed:+///+/// 1. The first dispatcher (`T`) is tried+/// 2. If it returns `Err(Unsupported)`, the second dispatcher (`U`) is tried+/// 3. If the second also returns `Unsupported`, the error is propagated+///+/// # Use Cases+///+/// Dispatcher chains are useful for:+///+/// - **Custom shapes with default fallback**: Handle your custom shapes specifically, but fall+/// back to Parry's default dispatcher for standard shapes+///+/// - **Performance optimization**: Try a fast specialized algorithm first, fall back to a general+/// but slower algorithm if needed+///+/// - **Progressive feature support**: Layer dispatchers that support different feature sets+///+/// - **Debugging**: Wrap the default dispatcher with a logging dispatcher that passes through+///+/// # Example+///+/// ```ignore+/// # {+/// use parry3d::query::{QueryDispatcher, DefaultQueryDispatcher};+///+/// // A dispatcher that handles only custom shapes+/// struct CustomShapeDispatcher;+/// impl QueryDispatcher for CustomShapeDispatcher {+/// fn distance(+/// &self,+/// pos12: &Pose,+/// g1: &dyn Shape,+/// g2: &dyn Shape,+/// ) -> Result<ShapeDistance, Unsupported> {+/// // Try to handle custom shapes+/// match (g1.as_any().downcast_ref::<MyShape>(),+/// g2.as_any().downcast_ref::<MyShape>()) {+/// (Some(s1), Some(s2)) => Ok(custom_distance(s1, s2, pos12)),+/// _ => Err(Unsupported), // Let the next dispatcher handle it+/// }+/// }+/// // ... other methods return Err(Unsupported)+/// }+///+/// // Chain: try custom first, fall back to default+/// let dispatcher = CustomShapeDispatcher.chain(DefaultQueryDispatcher);+///+/// // This will use CustomShapeDispatcher if both are MyShape,+/// // otherwise DefaultQueryDispatcher handles it+/// let dist = dispatcher.distance(pos12, shape1, shape2)?;+/// # }+/// ```+///+/// # Performance Note+///+/// Chaining has minimal overhead - it's just two function calls in the worst case. The first+/// dispatcher is always tried first, so place your most likely-to-succeed dispatcher at the+/// front of the chain for best performance.+///+/// # Multiple Chains+///+/// You can chain more than two dispatchers by chaining chains:+///+/// ```ignore+/// let dispatcher = custom1+/// .chain(custom2)+/// .chain(DefaultQueryDispatcher);+/// ```+///+/// This creates a chain of three dispatchers: `custom1` -> `custom2` -> `DefaultQueryDispatcher`.+pub struct QueryDispatcherChain<T, U>(T, U);++macro_rules! chain_method {+ ($name:ident ( $( $arg:ident : $ty:ty,)*) -> $result:ty) => {+ fn $name(&self, $($arg : $ty,)*+ ) -> Result<$result, Unsupported> {+ (self.0).$name($($arg,)*)+ .or_else(|Unsupported| (self.1).$name($($arg,)*))+ }+ }+}++impl<T, U> QueryDispatcher for QueryDispatcherChain<T, U>+where+ T: QueryDispatcher,+ U: QueryDispatcher,+{+ chain_method!(intersection_test(+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &dyn Shape,+ ) -> ShapeIntersection);++ chain_method!(distance(pos12: &Pose, g1: &dyn Shape, g2: &dyn Shape,) -> ShapeDistance);++ chain_method!(contact(+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &dyn Shape,+ prediction: Real,+ ) -> Option<Contact>);++ chain_method!(closest_points(+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &dyn Shape,+ max_dist: Real,+ ) -> ClosestPoints);++ chain_method!(cast_shapes(+ pos12: &Pose,+ vel12: Vector,+ g1: &dyn Shape,+ g2: &dyn Shape,+ options: ShapeCastOptions,+ ) -> Option<ShapeCastHit>);++ chain_method!(cast_shapes_nonlinear(+ motion1: &NonlinearRigidMotion,+ g1: &dyn Shape,+ motion2: &NonlinearRigidMotion,+ g2: &dyn Shape,+ start_time: Real,+ end_time: Real,+ stop_at_penetration: bool,+ ) -> Option<ShapeCastHit>);+}++#[cfg(feature = "alloc")]+impl<ManifoldData, ContactData, T, U> PersistentQueryDispatcher<ManifoldData, ContactData>+ for QueryDispatcherChain<T, U>+where+ T: PersistentQueryDispatcher<ManifoldData, ContactData>,+ U: PersistentQueryDispatcher<ManifoldData, ContactData>,+{+ chain_method!(contact_manifolds(+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &dyn Shape,+ prediction: Real,+ manifolds: &mut Vec<ContactManifold<ManifoldData, ContactData>>,+ workspace: &mut Option<ContactManifoldsWorkspace>,+ ) -> ());++ chain_method!(contact_manifold_convex_convex(+ pos12: &Pose,+ g1: &dyn Shape,+ g2: &dyn Shape,+ normal_constraints1: Option<&dyn NormalConstraints>,+ normal_constraints2: Option<&dyn NormalConstraints>,+ prediction: Real,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+ ) -> ());+}diff --git a/renderer/third_party/parry3d/src/query/ray/mod.rs b/renderer/third_party/parry3d/src/query/ray/mod.rsnew file mode 100644index 0000000..feccf6c--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/mod.rs@@ -0,0 +1,33 @@+//! Ray-casting related definitions and implementations.++#[doc(inline)]+pub use self::ray::{Ray, RayCast, RayIntersection};+pub use self::ray_ball::ray_toi_with_ball;+pub use self::ray_halfspace::{line_toi_with_halfspace, ray_toi_with_halfspace};+pub use self::ray_support_map::local_ray_intersection_with_support_map_with_params;+#[cfg(feature = "dim3")]+pub use self::ray_triangle::local_ray_intersection_with_triangle;+#[cfg(all(feature = "dim3", feature = "alloc"))]+pub use self::ray_trimesh::RayCullingMode;+pub use self::simd_ray::SimdRay;++#[doc(hidden)]+pub mod ray;+mod ray_aabb;+mod ray_ball;+mod ray_bounding_sphere;+mod ray_capsule;+#[cfg(feature = "alloc")]+mod ray_composite_shape;+mod ray_cuboid;+mod ray_halfspace;+#[cfg(feature = "alloc")]+mod ray_heightfield;+mod ray_round_shape;+mod ray_support_map;+mod ray_triangle;+#[cfg(feature = "alloc")]+mod ray_trimesh;+#[cfg(feature = "alloc")]+mod ray_voxels;+mod simd_ray;diff --git a/renderer/third_party/parry3d/src/query/ray/ray.rs b/renderer/third_party/parry3d/src/query/ray/ray.rsnew file mode 100644index 0000000..017f6e4--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray.rs@@ -0,0 +1,419 @@+//! Traits and structure needed to cast rays.++use crate::math::{Pose, Real, Vector};+use crate::shape::{FeatureId, SubShapeId};++#[cfg(feature = "alloc")]+use crate::partitioning::BvhLeafCost;++/// A ray for ray-casting queries.+///+/// A ray is a half-infinite line starting at an origin point and extending+/// infinitely in a direction. Rays are fundamental for visibility queries,+/// shooting mechanics, and collision prediction.+///+/// # Structure+///+/// - **origin**: The starting point of the ray+/// - **dir**: The direction vector (does NOT need to be normalized)+///+/// # Direction Vector+///+/// The direction can be any non-zero vector:+/// - **Normalized**: `dir` with length 1.0 gives time-of-impact in world units+/// - **Not normalized**: Time-of-impact is scaled by `dir.length()`+///+/// Most applications use normalized directions for intuitive results.+///+/// # Use Cases+///+/// - **Shooting/bullets**: Check what a projectile hits+/// - **Line of sight**: Check if one object can "see" another+/// - **Mouse picking**: Select objects by clicking+/// - **Laser beams**: Simulate light or laser paths+/// - **Proximity sensing**: Detect obstacles in a direction+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{Ray, RayCast};+/// use parry3d::shape::Ball;+/// use parry3d::math::{Vector, Pose};+///+/// // Create a ray from origin pointing along +X axis+/// let ray = Ray::new(+/// Vector::ZERO,+/// Vector::new(1.0, 0.0, 0.0) // Normalized direction+/// );+///+/// // Create a ball at position (5, 0, 0) with radius 1+/// let ball = Ball::new(1.0);+/// let ball_pos = Pose::translation(5.0, 0.0, 0.0);+///+/// // Cast the ray against the ball+/// if let Some(toi) = ball.cast_ray(&ball_pos, &ray, 100.0, true) {+/// // Ray hits at t=4.0 (center at 5.0 minus radius 1.0)+/// assert_eq!(toi, 4.0);+///+/// // Compute the actual hit point+/// let hit_point = ray.point_at(toi);+/// assert_eq!(hit_point, Vector::new(4.0, 0.0, 0.0));+/// }+/// # }+/// ```+#[derive(Debug, Clone, Copy)]+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+pub struct Ray {+ /// Starting point of the ray.+ ///+ /// This is where the ray begins. Vectors along the ray are computed as+ /// `origin + dir * t` for `t ≥ 0`.+ pub origin: Vector,++ /// Direction vector of the ray.+ ///+ /// This vector points in the direction the ray travels. It does NOT need+ /// to be normalized, but using a normalized direction makes time-of-impact+ /// values represent actual distances.+ pub dir: Vector,+}++impl Ray {+ /// Creates a new ray from an origin point and direction vector.+ ///+ /// # Arguments+ ///+ /// * `origin` - The starting point of the ray+ /// * `dir` - The direction vector (typically normalized but not required)+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::Ray;+ /// use parry3d::math::Vector;+ ///+ /// // Horizontal ray pointing along +X axis+ /// let ray = Ray::new(+ /// Vector::new(0.0, 5.0, 0.0),+ /// Vector::new(1.0, 0.0, 0.0)+ /// );+ ///+ /// // Ray starts at (0, 5, 0) and points along +X+ /// assert_eq!(ray.origin, Vector::new(0.0, 5.0, 0.0));+ /// assert_eq!(ray.dir, Vector::new(1.0, 0.0, 0.0));+ /// # }+ /// ```+ pub fn new(origin: Vector, dir: Vector) -> Ray {+ Ray { origin, dir }+ }++ /// Transforms this ray by the given isometry (translation + rotation).+ ///+ /// Both the origin and direction are transformed.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::Ray;+ /// use parry3d::math::{Pose, Vector};+ ///+ /// let ray = Ray::new(Vector::ZERO, Vector::X);+ ///+ /// // Translate by (5, 0, 0)+ /// let transform = Pose::translation(5.0, 0.0, 0.0);+ /// let transformed = ray.transform_by(&transform);+ ///+ /// assert_eq!(transformed.origin, Vector::new(5.0, 0.0, 0.0));+ /// assert_eq!(transformed.dir, Vector::X);+ /// # }+ /// ```+ #[inline]+ pub fn transform_by(&self, m: &Pose) -> Self {+ Self::new(m * self.origin, m.rotation * self.dir)+ }++ /// Transforms this ray by the inverse of the given isometry.+ ///+ /// This is equivalent to transforming the ray to the local space of an object.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::Ray;+ /// use parry3d::math::{Pose, Vector};+ ///+ /// let ray = Ray::new(Vector::new(10.0, 0.0, 0.0), Vector::X);+ ///+ /// let transform = Pose::translation(5.0, 0.0, 0.0);+ /// let local_ray = ray.inverse_transform_by(&transform);+ ///+ /// // Origin moved back by the translation+ /// assert_eq!(local_ray.origin, Vector::new(5.0, 0.0, 0.0));+ /// # }+ /// ```+ #[inline]+ pub fn inverse_transform_by(&self, m: &Pose) -> Self {+ Self::new(+ m.inverse_transform_point(self.origin),+ m.rotation.inverse() * self.dir,+ )+ }++ /// Translates this ray by the given vector.+ ///+ /// Only the origin is moved; the direction remains unchanged.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::Ray;+ /// use parry3d::math::Vector;+ ///+ /// let ray = Ray::new(Vector::ZERO, Vector::X);+ /// let translated = ray.translate_by(Vector::new(10.0, 5.0, 0.0));+ ///+ /// assert_eq!(translated.origin, Vector::new(10.0, 5.0, 0.0));+ /// assert_eq!(translated.dir, Vector::X); // Direction unchanged+ /// # }+ /// ```+ #[inline]+ pub fn translate_by(&self, v: Vector) -> Self {+ Self::new(self.origin + v, self.dir)+ }++ /// Computes a point along the ray at parameter `t`.+ ///+ /// Returns `origin + dir * t`. For `t ≥ 0`, this gives points along the ray.+ ///+ /// # Arguments+ ///+ /// * `t` - The parameter (typically the time-of-impact from ray casting)+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::query::Ray;+ /// use parry3d::math::Vector;+ ///+ /// let ray = Ray::new(+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0)+ /// );+ ///+ /// // Vector at t=5.0+ /// assert_eq!(ray.point_at(5.0), Vector::new(5.0, 0.0, 0.0));+ ///+ /// // Vector at t=0.0 is the origin+ /// assert_eq!(ray.point_at(0.0), ray.origin);+ /// # }+ /// ```+ #[inline]+ pub fn point_at(&self, t: Real) -> Vector {+ self.origin + self.dir * t+ }+}++/// Result of a successful ray cast against a shape.+///+/// This structure contains all information about where and how a ray intersects+/// a shape, including the time of impact, surface normal, and geometric feature hit.+///+/// # Fields+///+/// - **time_of_impact**: The `t` parameter where the ray hits (use with `ray.point_at(t)`)+/// - **normal**: The surface normal at the hit point+/// - **feature**: Which geometric feature was hit (vertex, edge, or face)+///+/// # Time of Impact+///+/// The time of impact is the parameter `t` in the ray equation `origin + dir * t`:+/// - If `dir` is normalized: `t` represents the distance traveled+/// - If `dir` is not normalized: `t` represents time (distance / speed)+///+/// # Normal Direction+///+/// The normal behavior depends on the ray origin and `solid` parameter:+/// - **Outside solid shape**: Normal points outward from the surface+/// - **Inside non-solid shape**: Normal points inward (toward the interior)+/// - **At t=0.0**: Normal may be unreliable due to numerical precision+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{Ray, RayCast};+/// use parry3d::shape::Cuboid;+/// use parry3d::math::{Vector, Pose};+///+/// let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+/// let ray = Ray::new(+/// Vector::new(-5.0, 0.0, 0.0),+/// Vector::new(1.0, 0.0, 0.0)+/// );+///+/// if let Some(intersection) = cuboid.cast_ray_and_get_normal(+/// &Pose::identity(),+/// &ray,+/// 100.0,+/// true+/// ) {+/// // Ray hits the -X face of the cuboid at x=-1.0+/// assert_eq!(intersection.time_of_impact, 4.0); // Distance from -5 to -1+///+/// // Hit point is at (-1, 0, 0) - the surface of the cuboid+/// let hit_point = ray.point_at(intersection.time_of_impact);+/// assert_eq!(hit_point.x, -1.0);+///+/// // Normal points outward (in -X direction for the -X face)+/// assert_eq!(intersection.normal, Vector::new(-1.0, 0.0, 0.0));+/// }+/// # }+/// ```+#[derive(Copy, Clone, Debug)]+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+pub struct RayIntersection {+ /// The time of impact (parameter `t`) where the ray hits the shape.+ ///+ /// The exact hit point can be computed with `ray.point_at(time_of_impact)`.+ /// If the ray direction is normalized, this represents the distance traveled.+ pub time_of_impact: Real,++ /// The surface normal at the intersection point.+ ///+ /// - Typically points outward from the shape+ /// - May point inward if ray origin is inside a non-solid shape+ /// - May be unreliable if `time_of_impact` is exactly zero+ ///+ /// Note: This should be a unit vector but is not enforced by the type system yet.+ // TODO: use a Vector instead.+ pub normal: Vector,++ /// The geometric feature (vertex, edge, or face) that was hit.+ ///+ /// This can be used for more detailed collision response or to identify+ /// exactly which part of the shape was struck.+ pub feature: FeatureId,++ /// The sub-shape that was hit.+ ///+ /// Identifies the part of a composite shape the ray struck: a triangle of a+ /// [`TriMesh`](crate::shape::TriMesh), a part of a [`Compound`](crate::shape::Compound), a+ /// voxel of a [`Voxels`](crate::shape::Voxels), and so on. Always `0` for a shape with no+ /// sub-shapes.+ pub subshape: SubShapeId,+}++impl RayIntersection {+ #[inline]+ /// Creates a new `RayIntersection`.+ #[cfg(feature = "dim3")]+ pub fn new(time_of_impact: Real, normal: Vector, feature: FeatureId) -> RayIntersection {+ RayIntersection {+ time_of_impact,+ normal,+ feature,+ subshape: 0,+ }+ }++ #[inline]+ /// Creates a new `RayIntersection`.+ #[cfg(feature = "dim2")]+ pub fn new(time_of_impact: Real, normal: Vector, feature: FeatureId) -> RayIntersection {+ RayIntersection {+ time_of_impact,+ normal,+ feature,+ subshape: 0,+ }+ }++ /// Sets the sub-shape this intersection came from.+ #[inline]+ pub fn with_subshape(mut self, subshape: SubShapeId) -> Self {+ self.subshape = subshape;+ self+ }++ #[inline]+ pub fn transform_by(&self, transform: &Pose) -> Self {+ RayIntersection {+ time_of_impact: self.time_of_impact,+ normal: transform.rotation * self.normal,+ feature: self.feature,+ subshape: self.subshape,+ }+ }+}++#[cfg(feature = "alloc")]+impl BvhLeafCost for RayIntersection {+ #[inline]+ fn cost(&self) -> Real {+ self.time_of_impact+ }+}++/// Traits of objects which can be transformed and tested for intersection with a ray.+pub trait RayCast {+ /// Computes the time of impact between this transform shape and a ray.+ fn cast_local_ray(&self, ray: &Ray, max_time_of_impact: Real, solid: bool) -> Option<Real> {+ self.cast_local_ray_and_get_normal(ray, max_time_of_impact, solid)+ .map(|inter| inter.time_of_impact)+ }++ /// Computes the time of impact, and normal between this transformed shape and a ray.+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection>;++ /// Tests whether a ray intersects this transformed shape.+ #[inline]+ fn intersects_local_ray(&self, ray: &Ray, max_time_of_impact: Real) -> bool {+ self.cast_local_ray(ray, max_time_of_impact, true).is_some()+ }++ /// Computes the time of impact between this transform shape and a ray.+ fn cast_ray(&self, m: &Pose, ray: &Ray, max_time_of_impact: Real, solid: bool) -> Option<Real> {+ let ls_ray = ray.inverse_transform_by(m);+ self.cast_local_ray(&ls_ray, max_time_of_impact, solid)+ }++ /// Computes the time of impact, and normal between this transformed shape and a ray.+ fn cast_ray_and_get_normal(+ &self,+ m: &Pose,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ let ls_ray = ray.inverse_transform_by(m);+ self.cast_local_ray_and_get_normal(&ls_ray, max_time_of_impact, solid)+ .map(|inter| inter.transform_by(m))+ }++ /// Tests whether a ray intersects this transformed shape.+ #[inline]+ fn intersects_ray(&self, m: &Pose, ray: &Ray, max_time_of_impact: Real) -> bool {+ let ls_ray = ray.inverse_transform_by(m);+ self.intersects_local_ray(&ls_ray, max_time_of_impact)+ }+}diff --git a/renderer/third_party/parry3d/src/query/ray/ray_aabb.rs b/renderer/third_party/parry3d/src/query/ray/ray_aabb.rsnew file mode 100644index 0000000..7ff5e85--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray_aabb.rs@@ -0,0 +1,119 @@+use core::mem;++use crate::bounding_volume::Aabb;+use crate::math::{Real, Vector, VectorExt, DIM};+use crate::query::{Ray, RayCast, RayIntersection};+use crate::shape::FeatureId;+use num::Zero;++impl RayCast for Aabb {+ fn cast_local_ray(&self, ray: &Ray, max_time_of_impact: Real, solid: bool) -> Option<Real> {+ let mut tmin: Real = 0.0;+ let mut tmax: Real = max_time_of_impact;++ for i in 0usize..DIM {+ if ray.dir.vget(i).is_zero() {+ if ray.origin.vget(i) < self.mins.vget(i) || ray.origin.vget(i) > self.maxs.vget(i)+ {+ return None;+ }+ } else {+ let denom = 1.0 / ray.dir.vget(i);+ let mut inter_with_near_halfspace =+ (self.mins.vget(i) - ray.origin.vget(i)) * denom;+ let mut inter_with_far_halfspace = (self.maxs.vget(i) - ray.origin.vget(i)) * denom;++ if inter_with_near_halfspace > inter_with_far_halfspace {+ mem::swap(+ &mut inter_with_near_halfspace,+ &mut inter_with_far_halfspace,+ )+ }++ tmin = tmin.max(inter_with_near_halfspace);+ tmax = tmax.min(inter_with_far_halfspace);++ if tmin > tmax {+ // This covers the case where tmax is negative because tmin is+ // initialized at zero.+ return None;+ }+ }+ }++ if tmin.is_zero() && !solid {+ Some(tmax)+ } else {+ Some(tmin)+ }+ }++ #[inline]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ ray_aabb(self, ray, max_time_of_impact, solid).map(|(t, n, i)| {+ // NOTE: `i` is the side of the AABB that was hit, as an integer in `[-DIM, DIM]`.+ // The special value `0` indicates that the ray direction is zero/NaN and its+ // origin lies inside the AABB; in that case there is no specific face hit.+ let feature = if i == 0 {+ FeatureId::Unknown+ } else if i < 0 {+ FeatureId::Face((-i) as u32 - 1 + 3)+ } else {+ FeatureId::Face(i as u32 - 1)+ };++ RayIntersection::new(t, n, feature)+ })+ }+}++fn ray_aabb(+ aabb: &Aabb,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+) -> Option<(Real, Vector, isize)> {+ use crate::query::clip;+ clip::clip_aabb_line(aabb, ray.origin, ray.dir).and_then(|(near, far)| {+ if near.0 < 0.0 {+ if solid {+ Some((0.0, Vector::ZERO, far.2))+ } else if far.0 <= max_time_of_impact {+ Some(far)+ } else {+ None+ }+ } else if near.0 <= max_time_of_impact {+ Some(near)+ } else {+ None+ }+ })+}++#[cfg(test)]+mod test {+ use super::*;++ /// Regression test for <https://github.com/dimforge/parry/issues/383>:+ /// casting a ray with a zero direction starting inside an AABB used to panic with+ /// "attempt to subtract with overflow" while computing the hit feature id.+ #[test]+ fn cast_zero_dir_ray_from_inside_aabb_does_not_overflow() {+ let aabb = Aabb::new(-Vector::splat(1.0), Vector::splat(1.0));+ let ray = Ray::new(Vector::ZERO, Vector::ZERO);++ // Both `solid` and non-`solid` variants must not panic.+ let solid = aabb.cast_local_ray_and_get_normal(&ray, 100.0, true);+ let hollow = aabb.cast_local_ray_and_get_normal(&ray, 100.0, false);++ assert!(solid.is_some());+ assert!(hollow.is_some());+ assert_eq!(solid.unwrap().feature, FeatureId::Unknown);+ }+}diff --git a/renderer/third_party/parry3d/src/query/ray/ray_ball.rs b/renderer/third_party/parry3d/src/query/ray/ray_ball.rsnew file mode 100644index 0000000..4dc7646--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray_ball.rs@@ -0,0 +1,96 @@+use crate::math::{ComplexField, Real, Vector};+use crate::query::{Ray, RayCast, RayIntersection};+use crate::shape::{Ball, FeatureId};+use num::Zero;++impl RayCast for Ball {+ #[inline]+ fn cast_local_ray(&self, ray: &Ray, max_time_of_impact: Real, solid: bool) -> Option<Real> {+ ray_toi_with_ball(Vector::ZERO, self.radius, ray, solid)+ .1+ .filter(|time_of_impact| *time_of_impact <= max_time_of_impact)+ }++ #[inline]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ ray_toi_and_normal_with_ball(Vector::ZERO, self.radius, ray, solid)+ .1+ .filter(|int| int.time_of_impact <= max_time_of_impact)+ }+}++/// Computes the time of impact of a ray on a ball.+///+/// The first result element is `true` if the ray started inside of the ball.+#[inline]+pub fn ray_toi_with_ball(+ center: Vector,+ radius: Real,+ ray: &Ray,+ solid: bool,+) -> (bool, Option<Real>) {+ let dcenter = ray.origin - center;++ let a = ray.dir.length_squared();+ let b = dcenter.dot(ray.dir);+ let c = dcenter.length_squared() - radius * radius;++ // Special case for when the dir is zero.+ if a.is_zero() {+ if c > 0.0 {+ return (false, None);+ } else {+ return (true, Some(0.0));+ }+ }++ if c > 0.0 && b > 0.0 {+ (false, None)+ } else {+ let delta = b * b - a * c;++ if delta < 0.0 {+ // no solution+ (false, None)+ } else {+ let t = (-b - <Real as ComplexField>::sqrt(delta)) / a;++ if t <= 0.0 {+ // origin inside of the ball+ if solid {+ (true, Some(0.0))+ } else {+ (true, Some((-b + delta.sqrt()) / a))+ }+ } else {+ (false, Some(t))+ }+ }+ }+}++/// Computes the time of impact and contact normal of a ray on a ball.+#[inline]+pub fn ray_toi_and_normal_with_ball(+ center: Vector,+ radius: Real,+ ray: &Ray,+ solid: bool,+) -> (bool, Option<RayIntersection>) {+ let (inside, inter) = ray_toi_with_ball(center, radius, ray, solid);++ (+ inside,+ inter.map(|n| {+ let pos = ray.origin + ray.dir * n - center;+ let normal = pos.normalize();++ RayIntersection::new(n, if inside { -normal } else { normal }, FeatureId::Face(0))+ }),+ )+}diff --git a/renderer/third_party/parry3d/src/query/ray/ray_bounding_sphere.rs b/renderer/third_party/parry3d/src/query/ray/ray_bounding_sphere.rsnew file mode 100644index 0000000..672a807--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray_bounding_sphere.rs@@ -0,0 +1,33 @@+use crate::bounding_volume::BoundingSphere;+use crate::math::Real;+use crate::query::{Ray, RayCast, RayIntersection};+use crate::shape::Ball;++impl RayCast for BoundingSphere {+ #[inline]+ fn cast_local_ray(&self, ray: &Ray, max_time_of_impact: Real, solid: bool) -> Option<Real> {+ let centered_ray = ray.translate_by(-self.center());+ Ball::new(self.radius()).cast_local_ray(¢ered_ray, max_time_of_impact, solid)+ }++ #[inline]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ let centered_ray = ray.translate_by(-self.center());+ Ball::new(self.radius()).cast_local_ray_and_get_normal(+ ¢ered_ray,+ max_time_of_impact,+ solid,+ )+ }++ #[inline]+ fn intersects_local_ray(&self, ray: &Ray, max_time_of_impact: Real) -> bool {+ let centered_ray = ray.translate_by(-self.center());+ Ball::new(self.radius()).intersects_local_ray(¢ered_ray, max_time_of_impact)+ }+}diff --git a/renderer/third_party/parry3d/src/query/ray/ray_capsule.rs b/renderer/third_party/parry3d/src/query/ray/ray_capsule.rsnew file mode 100644index 0000000..d11699d--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray_capsule.rs@@ -0,0 +1,440 @@+use crate::math::{ComplexField, Real, Vector};+use crate::query::{Ray, RayCast, RayIntersection};+use crate::shape::{Capsule, FeatureId, Segment};++impl RayCast for Capsule {+ #[inline]+ fn cast_local_ray(&self, ray: &Ray, max_time_of_impact: Real, solid: bool) -> Option<Real> {+ ray_toi_with_capsule(&self.segment, self.radius, ray, solid)+ .1+ .filter(|time_of_impact| *time_of_impact <= max_time_of_impact)+ }++ #[inline]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ ray_toi_and_normal_with_capsule(&self.segment, self.radius, ray, solid)+ .filter(|inter| inter.time_of_impact <= max_time_of_impact)+ }+}++/// Computes the time of impact of a ray on a capsule.+/// Returns true if the ray started inside the capsule and the time of impact.+///+/// Adapted from Inigo Quilez (<https://iquilezles.org/articles/intersectors/>).+/// Adapted to unnormalized ray direction.+/// Made robust to degenerate cases and ray origin inside the capsule.+/// Switched to projecting onto the plane with cross products+/// because they introduce much less error than a difference of dot products.+/// Discriminants are measured at the ray's closest approach to the axis or cap center,+/// so a distant ray origin doesn't cancel out the radius.+fn ray_toi_with_capsule(+ segment: &Segment,+ radius: Real,+ ray: &Ray,+ solid: bool,+) -> (bool, Option<Real>) {+ let ab = segment.b - segment.a;+ let ao = ray.origin - segment.a;++ let ab_ab = ab.length_squared();+ let dir_dir = ray.dir.length_squared();+ let ab_dir = ab.dot(ray.dir);+ let ab_ao = ab.dot(ao);+ let radius_squared = radius * radius;++ // do a circle intersection on the plane perpendicular to the capsule's axis.+ // all these variables are scaled by ab+ let dir_on_plane = cross(ray.dir, ab);+ let origin_on_plane = cross(ao, ab);+ let ray_step = dir_on_plane.length_squared();+ let radius_on_plane_squared = radius_squared * ab_ab;++ let inside = origin_on_plane.length_squared() <= radius_on_plane_squared+ && (0.0 < ab_ao || ao.length_squared() <= radius_squared)+ && (ab_ao < ab_ab || (ray.origin - segment.b).length_squared() <= radius_squared);++ if inside && solid {+ return (true, Some(0.0));+ }++ let check_sphere_a = if ray_step == 0.0 {+ // the ray is parallel to the capsule,+ // so it can only hit one of the caps+ (ab_dir > 0.0) ^ inside+ } else {+ // cylinder part+ let Some(t) = closest_approach_root(+ origin_on_plane,+ dir_on_plane,+ ray_step,+ radius_on_plane_squared,+ inside,+ ) else {+ return (false, None);+ };+ let y = ab_ao + t * ab_dir;+ if 0.0 < y && y < ab_ab && t >= 0.0 {+ return (inside, Some(t));+ }+ y <= 0.0+ };++ if dir_dir == 0.0 {+ return (inside, None);+ }++ // caps+ let oc = if check_sphere_a {+ ao+ } else {+ ray.origin - segment.b+ };+ let t = closest_approach_root(oc, ray.dir, dir_dir, radius_squared, inside);+ (inside, t.filter(|t| *t >= 0.0))+}++/// Solves `|origin + t * dir|² = radius²` for the entry (outside) or exit (inside) root.+///+/// Returns `None` if the line misses. When inside, rounding can't turn the exit into a miss or a+/// negative time.+#[inline]+fn closest_approach_root(+ origin: Vector,+ dir: Vector,+ dir_dir: Real,+ radius_squared: Real,+ inside: bool,+) -> Option<Real> {+ let t_closest = -dir.dot(origin) / dir_dir;+ let closest = origin + dir * t_closest;+ let h = radius_squared - closest.length_squared();+ if h < 0.0 && !inside {+ return None;+ }+ let half_chord = <Real as ComplexField>::sqrt(h.max(0.0) / dir_dir);+ if inside {+ Some((t_closest + half_chord).max(0.0))+ } else {+ Some(t_closest - half_chord)+ }+}++#[cfg(feature = "dim3")]+#[inline]+fn cross(v: Vector, segment: Vector) -> Vector {+ v.cross(segment)+}++/// Returns a vector with zero y, which is complete nonsense+/// but makes the 2D case work with the same code as the 3D case.+#[cfg(feature = "dim2")]+#[inline]+fn cross(v: Vector, segment: Vector) -> Vector {+ Vector::new(v.x * segment.y - v.y * segment.x, 0.0)+}++/// Computes the time of impact and contact normal of a ray on a capsule.+fn ray_toi_and_normal_with_capsule(+ segment: &Segment,+ radius: Real,+ ray: &Ray,+ solid: bool,+) -> Option<RayIntersection> {+ let (inside, inter) = ray_toi_with_capsule(segment, radius, ray, solid);++ inter.map(|t| {+ let normal = if solid && inside {+ Vector::ZERO+ } else {+ let p = ray.origin + ray.dir * t;+ let a_to_p = p - segment.a;+ let seg = segment.b - segment.a;+ let seg_squared = seg.length_squared();++ // the projection of the point onto the capsule's axis times the segment's length+ let proj_times_seg = a_to_p.dot(seg);++ // zero-radius capsules hit on the axis, where the normal is undefined+ let n = if proj_times_seg <= 0.0 {+ a_to_p.normalize_or_zero()+ } else if proj_times_seg >= seg_squared {+ (p - segment.b).normalize_or_zero()+ } else {+ (a_to_p - (proj_times_seg / seg_squared) * seg).normalize_or_zero()+ };+ if inside {+ -n+ } else {+ n+ }+ };+ RayIntersection::new(t, normal, FeatureId::Face(0))+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::math::Vector;+ use crate::query::point::point_query::PointQuery;+ use oorandom::Rand32;++ #[test]+ fn exact_cases() {+ let c = Capsule::new(v2(0.0, 0.5), v2(0.0, 1.5), 0.5);+ // Hit straight down the axis on the top cap, unnormalized direction.+ expect_hit(&c, v2(0.0, 5.0), v2(0.0, -0.2), true, 15.0, v2(0.0, 1.0));+ // Oblique hit on the cylinder.+ expect_hit(&c, v2(5.0, 1.0), v2(-0.3, 0.0), true, 15.0, v2(1.0, 0.0));+ // Tangential hit at the tip of the top cap.+ expect_hit(&c, v2(5.0, 2.0), v2(-1.0, 0.0), true, 5.0, v2(0.0, 1.0));+ // Hit on the bottom cap from below, parallel to the axis but offset+ // from it.+ expect_hit(+ &c,+ v2(0.1, -4.0),+ v2(0.0, 0.2),+ true,+ 20.0505,+ v2(0.2, -0.9798),+ );+ // Lateral miss.+ assert!(c+ .cast_local_ray(&Ray::new(v2(10.0, 5.0), v2(0.0, 0.1)), 50.0, true)+ .is_none());++ // Outside-origin misses where the ray's line crosses the tube (or a cap+ // sphere) only BEHIND the origin: the entry root is negative and must+ // not be reported. The fuzz can't catch these (it only aims rays at+ // interior points, so its entries are always positive).+ // Inside the infinite tube past the b-cap, receding. The tube entry is+ // behind (t = -0.9) with a phantom axis coordinate inside the band.+ assert!(c+ .cast_local_ray(&Ray::new(v2(0.4, 1.85), v2(1.0, 1.0)), 50.0, true)+ .is_none());+ // On-axis past the b-cap, parallel, receding (phantom t = -2.1).+ assert!(c+ .cast_local_ray(&Ray::new(v2(0.0, 2.1), v2(0.0, 1.0)), 50.0, true)+ .is_none());+ // Inside the tube past the b-cap, receding at an angle. Phantom axis+ // coordinate beyond the slab, cap entry behind (t = -0.87).+ assert!(c+ .cast_local_ray(&Ray::new(v2(0.4, 1.85), v2(1.0, 0.2)), 50.0, true)+ .is_none());+ // Outside everything, receding. The line crosses the tube behind the+ // origin, phantom axis coordinate in the band (t = -2.5).+ assert!(c+ .cast_local_ray(&Ray::new(v2(2.0, 1.0), v2(1.0, 0.0)), 50.0, true)+ .is_none());+ // Same, with the phantom axis coordinate exactly on the a-end boundary.+ assert!(c+ .cast_local_ray(&Ray::new(v2(2.0, 3.0), v2(1.0, 1.0)), 50.0, true)+ .is_none());+ // Inside, solid: contact at the origin, zero normal.+ expect_hit(&c, v2(0.1, 1.0), v2(0.0, 1.0), true, 0.0, v2(0.0, 0.0));+ // Inside, hollow: the exit, inward normal.+ expect_hit(&c, v2(0.0, 1.0), v2(0.0, 1.0), false, 1.0, v2(0.0, -1.0));+ // Same, toward the a-cap (the other parallel routing branch).+ expect_hit(&c, v2(0.0, 1.0), v2(0.0, -1.0), false, 1.0, v2(0.0, 1.0));+ // Inside, hollow: exit through the cylinder's side (the band exit+ // root, not a cap).+ expect_hit(&c, v2(0.0, 1.0), v2(1.0, 0.0), false, 0.5, v2(-1.0, 0.0));+ // Same, oblique.+ expect_hit(&c, v2(0.1, 0.8), v2(1.0, 0.5), false, 0.4, v2(-1.0, 0.0));+ // Inside the b-cap sphere past the slab: the b-sphere exit (t = 0.6)+ // is an intermediate crossing and must be skipped in favor of the+ // last one (the a-sphere exit at t = 1.6).+ expect_hit(&c, v2(0.0, 1.6), v2(0.0, -1.0), false, 1.6, v2(0.0, 1.0));+ // Degenerate zero-length ray, inside / outside.+ expect_hit(&c, v2(0.1, 1.0), v2(0.0, 0.0), true, 0.0, v2(0.0, 0.0));+ assert!(c+ .cast_local_ray(&Ray::new(v2(0.1, 3.0), v2(0.0, 0.0)), 50.0, true)+ .is_none());+ // Degenerate capsule (a == b): behaves as a ball of radius 1 at (0, 1).+ let ball = Capsule::new(v2(0.0, 1.0), v2(0.0, 1.0), 1.0);+ expect_hit(&ball, v2(0.0, 5.0), v2(0.0, -1.0), true, 3.0, v2(0.0, 1.0));+ expect_hit(&ball, v2(0.5, 1.0), v2(1.0, 0.0), true, 0.0, v2(0.0, 0.0));+ // max_toi filtering (the top-cap hit above is at t = 15).+ assert!(c+ .cast_local_ray(&Ray::new(v2(0.0, 5.0), v2(0.0, -0.2)), 14.9, true)+ .is_none());+ assert!(c+ .cast_local_ray(&Ray::new(v2(0.0, 5.0), v2(0.0, -0.2)), 15.1, true)+ .is_some());+ assert!(c+ .cast_local_ray_and_get_normal(&Ray::new(v2(0.0, 5.0), v2(0.0, -0.2)), 14.9, true)+ .is_none());+ }++ #[test]+ fn distant_origin_precision() {+ // A plain quadratic loses the radius against the origin's distance in f32 and reports+ // hits up to a whole radius off at these scales.+ let c = Capsule::new(v2(1.0e4, 0.0), v2(1.0e4, 5.0), 1.0);+ let i = c+ .cast_local_ray_and_get_normal(&Ray::new(v2(-1.0e4, 2.5), v2(2.0e4, 0.0)), 2.0, true)+ .unwrap();+ let hit = -1.0e4 + i.time_of_impact * 2.0e4;+ assert!((hit - (1.0e4 - 1.0)).abs() < 1.0e-2, "hit at x = {hit}");++ // Oblique hit on the cylinder's side at (-1, 2.5).+ let c = Capsule::new(v2(0.0, 0.0), v2(0.0, 5.0), 1.0);+ let dir = v2(1.0e4, 3.0e3);+ let i = c+ .cast_local_ray_and_get_normal(&Ray::new(v2(-1.0, 2.5) - dir, dir), 2.0, true)+ .unwrap();+ assert!((i.time_of_impact - 1.0).abs() * dir.length() < 1.0e-2);+ assert!((i.normal - v2(-1.0, 0.0)).length() < 1.0e-3);+ }++ #[test]+ fn zero_radius_normal_is_finite() {+ let c = Capsule::new(v2(0.0, -1.0), v2(0.0, 1.0), 0.0);+ for dir in [v2(1.0, 0.0), v2(0.0, -1.0)] {+ let i = c+ .cast_local_ray_and_get_normal(&Ray::new(v2(0.0, 0.0) - dir * 2.0, dir), 10.0, true)+ .unwrap();+ assert!(i.normal.is_finite(), "normal: {:?}", i.normal);+ }+ }++ fn v2(x: Real, y: Real) -> Vector {+ Vector::new(+ x,+ y,+ #[cfg(feature = "dim3")]+ 0.0,+ )+ }++ #[track_caller]+ fn expect_hit(c: &Capsule, o: Vector, d: Vector, solid: bool, et: Real, en: Vector) {+ let i = c+ .cast_local_ray_and_get_normal(&Ray::new(o, d), 50.0, solid)+ .unwrap_or_else(|| panic!("expected hit (o={:?}, d={:?})", o, d));+ assert!(+ (i.time_of_impact - et).abs() < 1e-4,+ "t: got {}, want {}",+ i.time_of_impact,+ et+ );+ assert!(+ (i.normal - en).length() < 1e-3,+ "n: got {:?}, want {:?}",+ i.normal,+ en+ );+ }++ #[test]+ fn fuzz_capsule_ray_casts() {+ let epsilon = 0.002;+ let mut rng = Rand32::new(42);++ for _ in 0..100_000 {+ let (a, b) = (rnd_vec(&mut rng, 10.0), rnd_vec(&mut rng, 10.0));+ let r = 0.5 + 5.0 * rnd(&mut rng);+ let capsule = Capsule::new(a, b, r);++ // a random point inside the capsule+ let inside = {+ let mut w = rnd_vec(&mut rng, r);+ while w.length_squared() >= r * r {+ w = rnd_vec(&mut rng, r);+ }+ a + (b - a) * rnd(&mut rng) + w+ };++ // cast random ray toward the inside point+ let far_enough = r + a.distance(b);+ let mut offset = Vector::ZERO;+ while offset.length_squared() < far_enough * far_enough {+ offset = rnd_vec(&mut rng, far_enough * 2.0);+ }++ let o = (a + b) * 0.5 + offset;+ let d = (inside - o) * (0.1 + 0.9 * rnd(&mut rng));+ let i = capsule+ .cast_local_ray_and_get_normal(&Ray::new(o, d), 1000.0, true)+ .expect("a ray aimed at an interior point must hit");++ let hit = o + d * i.time_of_impact;+ assert!(+ capsule.contains_local_point(hit - i.normal * epsilon),+ "nudging inward along the normal should go inside the capsule"+ );+ assert!(+ !capsule.contains_local_point(hit + i.normal * epsilon),+ "nudging outward along the normal should go outside the capsule"+ );++ // A ray from the interior point to the far point (hollow) must+ // exit the capsule; its normal points inward.+ let i_in = capsule+ .cast_local_ray_and_get_normal(&Ray::new(inside, o - inside), 1000.0, false)+ .expect("a ray from inside toward the outside must exit");+ let hit_in = inside + (o - inside) * i_in.time_of_impact;+ assert!(+ capsule.contains_local_point(hit_in + i_in.normal * epsilon),+ "nudging along the inward normal should stay inside"+ );+ assert!(+ !capsule.contains_local_point(hit_in - i_in.normal * epsilon),+ "nudging against the inward normal should go outside"+ );++ assert!(+ capsule+ .cast_local_ray(&Ray::new(o, -d), 1000.0, true)+ .is_none(),+ "a retreating ray must miss"+ );++ #[cfg(feature = "dim2")]+ let tangent = Vector::new(-i.normal.y, i.normal.x);+ #[cfg(feature = "dim3")]+ let tangent = {+ let mut tangent = Vector::ZERO;+ while tangent.length_squared() < 1e-8 {+ tangent = rnd_vec(&mut rng, 1.0).cross(i.normal);+ }+ tangent+ };+ let origin = hit + i.normal * (epsilon + rnd(&mut rng)) - rnd(&mut rng) * tangent;+ assert!(+ capsule+ .cast_local_ray(&Ray::new(origin, tangent), 1000.0, true)+ .is_none(),+ "tangent outside the capsule should miss"+ );+ }+ }++ fn rnd(rng: &mut Rand32) -> Real {+ #[cfg(feature = "f32")]+ {+ rng.rand_float()+ }+ #[cfg(feature = "f64")]+ {+ rng.rand_float() as Real+ }+ }++ fn rnd_vec(rng: &mut Rand32, scale: Real) -> Vector {+ let mut component = || (rnd(rng) - 0.5) * 2.0 * scale;+ #[cfg(feature = "dim2")]+ {+ Vector::new(component(), component())+ }+ #[cfg(feature = "dim3")]+ {+ Vector::new(component(), component(), component())+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/ray/ray_composite_shape.rs b/renderer/third_party/parry3d/src/query/ray/ray_composite_shape.rsnew file mode 100644index 0000000..6938c08--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray_composite_shape.rs@@ -0,0 +1,109 @@+use crate::math::Real;+use crate::partitioning::BvhNode;+use crate::query::{Ray, RayCast, RayIntersection};+use crate::shape::{CompositeShapeRef, Compound, Polyline, SubShapeId, TypedCompositeShape};++impl<S: TypedCompositeShape> CompositeShapeRef<'_, S> {+ /// Casts a ray on this composite shape.+ ///+ /// The ray is effectively limited to a segment that starts at `Ray::origin` and ends at+ /// `Ray::origin + Ray::direction * max_time_of_impact`. Set `max_time_of_impact` to `Real::MAX`+ /// for an unbounded ray.+ ///+ /// If `solid` is `false`, then the sub-shapes of `self` are seen as hollow and the ray won’t+ /// immediately stop until it reaches a boundary even if it started inside a shape.+ ///+ /// Returns the ray’s time of impact and the index of the sub-shape of `self` that was hit.+ /// The hit point can be retrieved with `ray.point_at(t)` where `t` is the value returned+ /// by this function.+ #[inline]+ pub fn cast_local_ray(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<(SubShapeId, Real)> {+ let hit = self+ .0+ .bvh()+ .cast_ray(ray, max_time_of_impact, |primitive, best_so_far| {+ self.0.map_typed_part_at(primitive, |pose, part, _| {+ if let Some(pose) = pose {+ part.cast_ray(pose, ray, best_so_far, solid)+ } else {+ part.cast_local_ray(ray, best_so_far, solid)+ }+ })?+ })?;+ (hit.1 < max_time_of_impact).then_some(hit)+ }++ /// Same as [`Self::cast_local_ray`] but also computes the normal at the hit location.+ ///+ /// Returns the index of the sub-shape of `self` that was hit alongside the hit, which is+ /// left as that sub-shape reported it (its `subshape` is the sub-shape's own, when it is a+ /// composite too).+ #[inline]+ pub fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<(SubShapeId, RayIntersection)> {+ self.0.bvh().find_best(+ max_time_of_impact,+ |node: &BvhNode, best_so_far| node.cast_ray(ray, best_so_far),+ |primitive, best_so_far| {+ self.0.map_typed_part_at(primitive, |pose, part, _| {+ if let Some(pose) = pose {+ part.cast_ray_and_get_normal(pose, ray, best_so_far, solid)+ } else {+ part.cast_local_ray_and_get_normal(ray, best_so_far, solid)+ }+ })?+ },+ )+ }+}++impl RayCast for Polyline {+ #[inline]+ fn cast_local_ray(&self, ray: &Ray, max_time_of_impact: Real, solid: bool) -> Option<Real> {+ CompositeShapeRef(self)+ .cast_local_ray(ray, max_time_of_impact, solid)+ .map(|hit| hit.1)+ }++ #[inline]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ CompositeShapeRef(self)+ .cast_local_ray_and_get_normal(ray, max_time_of_impact, solid)+ .map(|(segment_id, hit)| hit.with_subshape(segment_id))+ }+}++impl RayCast for Compound {+ #[inline]+ fn cast_local_ray(&self, ray: &Ray, max_time_of_impact: Real, solid: bool) -> Option<Real> {+ CompositeShapeRef(self)+ .cast_local_ray(ray, max_time_of_impact, solid)+ .map(|hit| hit.1)+ }++ #[inline]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ CompositeShapeRef(self)+ .cast_local_ray_and_get_normal(ray, max_time_of_impact, solid)+ .map(|(part_id, hit)| hit.with_subshape(part_id))+ }+}diff --git a/renderer/third_party/parry3d/src/query/ray/ray_cuboid.rs b/renderer/third_party/parry3d/src/query/ray/ray_cuboid.rsnew file mode 100644index 0000000..f4a55f3--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray_cuboid.rs@@ -0,0 +1,25 @@+use crate::bounding_volume::Aabb;+use crate::math::Real;+use crate::query::{Ray, RayCast, RayIntersection};+use crate::shape::Cuboid;++impl RayCast for Cuboid {+ #[inline]+ fn cast_local_ray(&self, ray: &Ray, max_time_of_impact: Real, solid: bool) -> Option<Real> {+ let dl = -self.half_extents;+ let ur = self.half_extents;+ Aabb::new(dl, ur).cast_local_ray(ray, max_time_of_impact, solid)+ }++ #[inline]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ let dl = -self.half_extents;+ let ur = self.half_extents;+ Aabb::new(dl, ur).cast_local_ray_and_get_normal(ray, max_time_of_impact, solid)+ }+}diff --git a/renderer/third_party/parry3d/src/query/ray/ray_halfspace.rs b/renderer/third_party/parry3d/src/query/ray/ray_halfspace.rsnew file mode 100644index 0000000..edc4f6f--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray_halfspace.rs@@ -0,0 +1,66 @@+use crate::math::{Real, Vector};+use crate::query::{Ray, RayCast, RayIntersection};+use crate::shape::{FeatureId, HalfSpace};++/// Computes the time_of_impact of an unbounded line with a halfspace described by its center and normal.+#[inline]+pub fn line_toi_with_halfspace(+ halfspace_center: Vector,+ halfspace_normal: Vector,+ line_origin: Vector,+ line_dir: Vector,+) -> Option<Real> {+ let dpos = halfspace_center - line_origin;+ let denom = halfspace_normal.dot(line_dir);++ if relative_eq!(denom, 0.0) {+ None+ } else {+ Some(halfspace_normal.dot(dpos) / denom)+ }+}++/// Computes the time_of_impact of a ray with a halfspace described by its center and normal.+#[inline]+pub fn ray_toi_with_halfspace(center: Vector, normal: Vector, ray: &Ray) -> Option<Real> {+ if let Some(t) = line_toi_with_halfspace(center, normal, ray.origin, ray.dir) {+ if t >= 0.0 {+ return Some(t);+ }+ }++ None+}++impl RayCast for HalfSpace {+ #[inline]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ let dpos = -ray.origin;++ let dot_normal_dpos = self.normal.dot(dpos);++ if solid && dot_normal_dpos > 0.0 {+ // The ray is inside of the solid half-space.+ return Some(RayIntersection::new(0.0, Vector::ZERO, FeatureId::Face(0)));+ }++ let t = dot_normal_dpos / self.normal.dot(ray.dir);++ if t >= 0.0 && t <= max_time_of_impact {+ let n = if dot_normal_dpos > 0.0 {+ -self.normal+ } else {+ self.normal+ };++ Some(RayIntersection::new(t, n, FeatureId::Face(0)))+ } else {+ None+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/ray/ray_heightfield.rs b/renderer/third_party/parry3d/src/query/ray/ray_heightfield.rsnew file mode 100644index 0000000..760ed1e--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray_heightfield.rs@@ -0,0 +1,232 @@+use crate::math::Real;+#[cfg(feature = "dim2")]+use crate::query;+use crate::query::{Ray, RayCast, RayIntersection};+#[cfg(feature = "dim2")]+use crate::shape::FeatureId;+use crate::shape::HeightField;++#[cfg(feature = "dim2")]+impl RayCast for HeightField {+ #[inline]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ _: bool,+ ) -> Option<RayIntersection> {+ let aabb = self.local_aabb();+ let (min_t, mut max_t) = aabb.clip_ray_parameters(ray)?;++ if min_t > max_time_of_impact {+ return None;+ }++ max_t = max_t.min(max_time_of_impact);++ let clip_ray_a = ray.point_at(min_t);++ // None may happen due to slight numerical errors.+ let mut curr = self.cell_at_point(clip_ray_a).unwrap_or_else(|| {+ if ray.origin.x > 0.0 {+ self.num_cells() - 1+ } else {+ 0_usize+ }+ });++ /*+ * Test the segment under the ray.+ */+ if let Some(seg) = self.segment_at(curr) {+ let (s, t) = query::details::closest_points_line_line_parameters(+ ray.origin,+ ray.dir,+ seg.a,+ seg.scaled_direction(),+ );+ if s >= 0.0 && t >= 0.0 && t <= 1.0 {+ // Cast succeeded on the first element!+ let n = seg.normal().unwrap();+ // The feature is the hit segment's own side; `subshape` says which segment.+ let fid = if n.dot(ray.dir) > 0.0 { 1 } else { 0 };++ return Some(+ RayIntersection::new(s, n, FeatureId::Face(fid)).with_subshape(curr as u32),+ );+ }+ }++ /*+ * Test other segments in the path of the ray.+ */+ if ray.dir.x == 0.0 {+ return None;+ }++ let right = ray.dir.x > 0.0;+ let cell_width = self.cell_width();+ let start_x = self.start_x();++ while (right && curr < self.num_cells()) || (!right && curr > 0) {+ let curr_param;++ if right {+ curr += 1;+ curr_param = (cell_width * (curr as Real) + start_x - ray.origin.x) / ray.dir.x;+ } else {+ curr_param = (ray.origin.x - cell_width * (curr as Real) - start_x) / ray.dir.x;+ curr -= 1;+ }++ if curr_param >= max_t {+ // The part of the ray after max_t is outside of the heightfield Aabb.+ return None;+ }++ if let Some(seg) = self.segment_at(curr) {+ // TODO: test the y-coordinates (equivalent to an Aabb test) before actually computing the intersection.+ let (s, t) = query::details::closest_points_line_line_parameters(+ ray.origin,+ ray.dir,+ seg.a,+ seg.scaled_direction(),+ );++ if t >= 0.0 && t <= 1.0 && s <= max_time_of_impact {+ let n = seg.normal().unwrap();+ // The feature is the hit segment's own side; `subshape` says which segment.+ let fid = if n.dot(ray.dir) > 0.0 { 1 } else { 0 };+ return Some(+ RayIntersection::new(s, n, FeatureId::Face(fid)).with_subshape(curr as u32),+ );+ }+ }+ }++ None+ }+}++#[cfg(feature = "dim3")]+impl RayCast for HeightField {+ #[inline]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ use num_traits::Bounded;++ let aabb = self.local_aabb();+ let (min_t, mut max_t) = aabb.clip_ray_parameters(ray)?;+ max_t = max_t.min(max_time_of_impact);+ let clip_ray_a = ray.point_at(min_t);+ let mut cell = match self.cell_at_point(clip_ray_a) {+ Some(cell) => cell,+ // None may happen due to slight numerical errors.+ None => {+ let i = if ray.origin.z > 0.0 {+ self.nrows() - 1+ } else {+ 0+ };++ let j = if ray.origin.x > 0.0 {+ self.ncols() - 1+ } else {+ 0+ };++ (i, j)+ }+ };++ loop {+ let tris = self.triangles_at(cell.0, cell.1);+ let inter1 = tris+ .0+ .and_then(|tri| tri.cast_local_ray_and_get_normal(ray, max_time_of_impact, solid));+ let inter2 = tris+ .1+ .and_then(|tri| tri.cast_local_ray_and_get_normal(ray, max_time_of_impact, solid));++ // The feature stays the one the triangle reported; `subshape` says which triangle it+ // belongs to.+ match (inter1, inter2) {+ (Some(mut inter1), Some(mut inter2)) => {+ if inter1.time_of_impact < inter2.time_of_impact {+ inter1.subshape = self.triangle_id(cell.0, cell.1, true);+ return Some(inter1);+ } else {+ inter2.subshape = self.triangle_id(cell.0, cell.1, false);+ return Some(inter2);+ }+ }+ (Some(mut inter), None) => {+ inter.subshape = self.triangle_id(cell.0, cell.1, true);+ return Some(inter);+ }+ (None, Some(mut inter)) => {+ inter.subshape = self.triangle_id(cell.0, cell.1, false);+ return Some(inter);+ }+ (None, None) => {}+ }++ /*+ * Find the next cell to cast the ray on.+ */+ let (toi_x, right) = if ray.dir.x > 0.0 {+ let x = self.x_at(cell.1 + 1);+ ((x - ray.origin.x) / ray.dir.x, true)+ } else if ray.dir.x < 0.0 {+ let x = self.x_at(cell.1);+ ((x - ray.origin.x) / ray.dir.x, false)+ } else {+ (Real::max_value(), false)+ };++ let (toi_z, down) = if ray.dir.z > 0.0 {+ let z = self.z_at(cell.0 + 1);+ ((z - ray.origin.z) / ray.dir.z, true)+ } else if ray.dir.z < 0.0 {+ let z = self.z_at(cell.0);+ ((z - ray.origin.z) / ray.dir.z, false)+ } else {+ (Real::max_value(), false)+ };++ if toi_x > max_t && toi_z > max_t {+ break;+ }++ if toi_x >= 0.0 && toi_x < toi_z {+ if right {+ cell.1 += 1+ } else if cell.1 > 0 {+ cell.1 -= 1+ } else {+ break;+ }+ } else if toi_z >= 0.0 {+ if down {+ cell.0 += 1+ } else if cell.0 > 0 {+ cell.0 -= 1+ } else {+ break;+ }+ } else {+ break;+ }++ if cell.0 >= self.nrows() || cell.1 >= self.ncols() {+ break;+ }+ }++ None+ }+}diff --git a/renderer/third_party/parry3d/src/query/ray/ray_round_shape.rs b/renderer/third_party/parry3d/src/query/ray/ray_round_shape.rsnew file mode 100644index 0000000..b37d9cd--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray_round_shape.rs@@ -0,0 +1,21 @@+use crate::math::Real;+use crate::query::gjk::VoronoiSimplex;+use crate::query::{Ray, RayCast, RayIntersection};+use crate::shape::{RoundShape, SupportMap};++impl<S: SupportMap> RayCast for RoundShape<S> {+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ crate::query::details::local_ray_intersection_with_support_map_with_params(+ self,+ &mut VoronoiSimplex::new(),+ ray,+ max_time_of_impact,+ solid,+ )+ }+}diff --git a/renderer/third_party/parry3d/src/query/ray/ray_support_map.rs b/renderer/third_party/parry3d/src/query/ray/ray_support_map.rsnew file mode 100644index 0000000..033320f--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray_support_map.rs@@ -0,0 +1,241 @@+use crate::math::Real;+#[cfg(feature = "dim2")]+use crate::query;+use crate::query::gjk::{self, CsoPoint, VoronoiSimplex};+use crate::query::{Ray, RayCast, RayIntersection};+#[cfg(all(feature = "alloc", feature = "dim2"))]+use crate::shape::ConvexPolygon;+#[cfg(all(feature = "alloc", feature = "dim3"))]+use crate::shape::ConvexPolyhedron;+#[cfg(feature = "dim3")]+use crate::shape::{Cone, Cylinder};+use crate::shape::{FeatureId, Segment, SupportMap};++use num::Zero;++/// Cast a ray on a shape using the GJK algorithm.+pub fn local_ray_intersection_with_support_map_with_params<G: ?Sized + SupportMap>(+ shape: &G,+ simplex: &mut VoronoiSimplex,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+) -> Option<RayIntersection> {+ let supp = shape.local_support_point(-ray.dir);+ simplex.reset(CsoPoint::single_point(supp - ray.origin));++ let inter = gjk::cast_local_ray(shape, simplex, ray, max_time_of_impact);++ if !solid {+ inter.and_then(|(time_of_impact, normal)| {+ if time_of_impact.is_zero() {+ // the ray is inside of the shape.+ let ndir = ray.dir.normalize();+ let supp = shape.local_support_point(ndir);+ let eps: Real = 0.001;+ let shift = (supp - ray.origin).dot(ndir) + eps;+ let new_ray = Ray::new(ray.origin + ndir * shift, -ray.dir);++ // TODO: replace by? : simplex.translate_by(&(ray.origin - new_ray.origin));+ simplex.reset(CsoPoint::single_point(supp - new_ray.origin));++ gjk::cast_local_ray(shape, simplex, &new_ray, shift + eps).and_then(+ |(time_of_impact, outward_normal)| {+ let time_of_impact = shift - time_of_impact;+ if time_of_impact <= max_time_of_impact {+ Some(RayIntersection::new(+ time_of_impact,+ -outward_normal,+ FeatureId::Unknown,+ ))+ } else {+ None+ }+ },+ )+ } else {+ Some(RayIntersection::new(+ time_of_impact,+ normal,+ FeatureId::Unknown,+ ))+ }+ })+ } else {+ inter.map(|(time_of_impact, normal)| {+ RayIntersection::new(time_of_impact, normal, FeatureId::Unknown)+ })+ }+}++#[cfg(feature = "dim3")]+impl RayCast for Cylinder {+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ local_ray_intersection_with_support_map_with_params(+ self,+ &mut VoronoiSimplex::new(),+ ray,+ max_time_of_impact,+ solid,+ )+ }+}++#[cfg(feature = "dim3")]+impl RayCast for Cone {+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ local_ray_intersection_with_support_map_with_params(+ self,+ &mut VoronoiSimplex::new(),+ ray,+ max_time_of_impact,+ solid,+ )+ }+}++#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+impl RayCast for ConvexPolyhedron {+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ local_ray_intersection_with_support_map_with_params(+ self,+ &mut VoronoiSimplex::new(),+ ray,+ max_time_of_impact,+ solid,+ )+ }+}++#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+impl RayCast for ConvexPolygon {+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ local_ray_intersection_with_support_map_with_params(+ self,+ &mut VoronoiSimplex::new(),+ ray,+ max_time_of_impact,+ solid,+ )+ }+}++#[allow(unused_variables)]+impl RayCast for Segment {+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ #[cfg(feature = "dim2")]+ {+ use crate::math::Vector;++ let seg_dir = self.scaled_direction();+ let (s, t, parallel) = query::details::closest_points_line_line_parameters_eps(+ ray.origin,+ ray.dir,+ self.a,+ seg_dir,+ crate::math::DEFAULT_EPSILON,+ );++ if parallel {+ // The lines are parallel, we have to distinguish+ // the case where there is no intersection at all+ // from the case where the line are collinear.+ let dpos = self.a - ray.origin;+ let normal = self.normal().unwrap_or(Vector::ZERO);++ if dpos.dot(normal).abs() < crate::math::DEFAULT_EPSILON {+ // The rays and the segment are collinear.+ let dist1 = dpos.dot(ray.dir);+ let dist2 = dist1 + seg_dir.dot(ray.dir);++ match (dist1 >= 0.0, dist2 >= 0.0) {+ (true, true) => {+ let time_of_impact = dist1.min(dist2) / ray.dir.length_squared();+ if time_of_impact > max_time_of_impact {+ None+ } else if dist1 <= dist2 {+ Some(RayIntersection::new(+ time_of_impact,+ normal,+ FeatureId::Vertex(0),+ ))+ } else {+ Some(RayIntersection::new(+ dist2 / ray.dir.length_squared(),+ normal,+ FeatureId::Vertex(1),+ ))+ }+ }+ (true, false) | (false, true) => {+ // The ray origin lies on the segment.+ Some(RayIntersection::new(0.0, normal, FeatureId::Face(0)))+ }+ (false, false) => {+ // The segment is behind the ray.+ None+ }+ }+ } else {+ // The rays never intersect.+ None+ }+ } else if s >= 0.0 && s <= max_time_of_impact && t >= 0.0 && t <= 1.0 {+ let normal = self.normal().unwrap_or(Vector::ZERO);++ let dot = normal.dot(ray.dir);+ if dot > 0.0 {+ Some(RayIntersection::new(s, -normal, FeatureId::Face(1)))+ } else if dot < 0.0 {+ Some(RayIntersection::new(s, normal, FeatureId::Face(0)))+ } else {+ // dot == 0 happens when lines are parallel, which is normally handled before,+ // but this may happen if segment is zero length, as the ray is not considered parallel.+ None+ }+ } else {+ // The closest points are outside of+ // the ray or segment bounds.+ None+ }+ }+ #[cfg(feature = "dim3")]+ {+ // XXX: implement an analytic solution for 3D too.+ local_ray_intersection_with_support_map_with_params(+ self,+ &mut VoronoiSimplex::new(),+ ray,+ max_time_of_impact,+ solid,+ )+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/ray/ray_triangle.rs b/renderer/third_party/parry3d/src/query/ray/ray_triangle.rsnew file mode 100644index 0000000..9615484--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray_triangle.rs@@ -0,0 +1,161 @@+use crate::math::Real;+#[cfg(feature = "dim2")]+use crate::math::Vector;+#[cfg(feature = "dim3")]+use crate::math::Vector;+use crate::query::{Ray, RayCast, RayIntersection};+use crate::shape::{FeatureId, Triangle};++impl RayCast for Triangle {+ #[inline]+ #[cfg(feature = "dim2")]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ let edges = self.edges();++ if solid {+ // Check if ray starts in triangle+ let perp_sign1 = edges[0]+ .scaled_direction()+ .perp_dot(ray.origin - edges[0].a)+ > 0.0;+ let perp_sign2 = edges[1]+ .scaled_direction()+ .perp_dot(ray.origin - edges[1].a)+ > 0.0;+ let perp_sign3 = edges[2]+ .scaled_direction()+ .perp_dot(ray.origin - edges[2].a)+ > 0.0;++ if perp_sign1 == perp_sign2 && perp_sign1 == perp_sign3 {+ return Some(RayIntersection::new(0.0, Vector::Y, FeatureId::Face(0)));+ }+ }++ let mut best = None;+ let mut smallest_toi = Real::MAX;++ for edge in &edges {+ if let Some(inter) = edge.cast_local_ray_and_get_normal(ray, max_time_of_impact, solid)+ {+ if inter.time_of_impact < smallest_toi {+ smallest_toi = inter.time_of_impact;+ best = Some(inter);+ }+ }+ }++ best+ }++ #[inline]+ #[cfg(feature = "dim3")]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ _: bool,+ ) -> Option<RayIntersection> {+ let inter = local_ray_intersection_with_triangle(self.a, self.b, self.c, ray)?.0;++ if inter.time_of_impact <= max_time_of_impact {+ Some(inter)+ } else {+ None+ }+ }+}++/// Computes the intersection between a triangle and a ray.+///+/// If an intersection is found, the time of impact, the normal and the barycentric coordinates of+/// the intersection point are returned.+#[cfg(feature = "dim3")]+pub fn local_ray_intersection_with_triangle(+ a: Vector,+ b: Vector,+ c: Vector,+ ray: &Ray,+) -> Option<(RayIntersection, Vector)> {+ let ab = b - a;+ let ac = c - a;++ // normal+ let n = ab.cross(ac);+ let d = n.dot(ray.dir);++ // the normal and the ray direction are parallel+ if d == 0.0 {+ return None;+ }++ let ap = ray.origin - a;+ let t = ap.dot(n);++ // the ray does not intersect the halfspace defined by the triangle+ if (t < 0.0 && d < 0.0) || (t > 0.0 && d > 0.0) {+ return None;+ }++ let fid = if d < 0.0 { 0 } else { 1 };++ let d = d.abs();++ //+ // intersection: compute barycentric coordinates+ //+ let e = -ray.dir.cross(ap);++ let mut v;+ let mut w;+ let time_of_impact;+ let normal;++ if t < 0.0 {+ v = -ac.dot(e);++ if v < 0.0 || v > d {+ return None;+ }++ w = ab.dot(e);++ if w < 0.0 || v + w > d {+ return None;+ }++ let invd = 1.0 / d;+ time_of_impact = -t * invd;+ normal = -n.normalize();+ v *= invd;+ w *= invd;+ } else {+ v = ac.dot(e);++ if v < 0.0 || v > d {+ return None;+ }++ w = -ab.dot(e);++ if w < 0.0 || v + w > d {+ return None;+ }++ let invd = 1.0 / d;+ time_of_impact = t * invd;+ normal = n.normalize();+ v *= invd;+ w *= invd;+ }++ Some((+ RayIntersection::new(time_of_impact, normal, FeatureId::Face(fid)),+ Vector::new(-v - w + 1.0, v, w),+ ))+}diff --git a/renderer/third_party/parry3d/src/query/ray/ray_trimesh.rs b/renderer/third_party/parry3d/src/query/ray/ray_trimesh.rsnew file mode 100644index 0000000..e4e8aea--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray_trimesh.rs@@ -0,0 +1,196 @@+use crate::math::Real;+use crate::query::{Ray, RayCast, RayIntersection};+use crate::shape::{CompositeShapeRef, TriMesh};++#[cfg(feature = "dim3")]+pub use ray_cast_with_culling::RayCullingMode;++impl RayCast for TriMesh {+ #[inline]+ fn cast_local_ray(&self, ray: &Ray, max_time_of_impact: Real, solid: bool) -> Option<Real> {+ CompositeShapeRef(self)+ .cast_local_ray(ray, max_time_of_impact, solid)+ .map(|hit| hit.1)+ }++ #[inline]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ CompositeShapeRef(self)+ .cast_local_ray_and_get_normal(ray, max_time_of_impact, solid)+ .map(|(triangle_id, hit)| hit.with_subshape(triangle_id))+ }+}++// NOTE: implement the ray-cast with culling on its own submodule to facilitate feature gating.+#[cfg(feature = "dim3")]+mod ray_cast_with_culling {+ use crate::math::{Pose, Real, Vector};+ use crate::partitioning::Bvh;+ use crate::query::details::NormalConstraints;+ use crate::query::{Ray, RayIntersection};+ use crate::shape::{+ CompositeShape, CompositeShapeRef, Shape, TriMesh, Triangle, TypedCompositeShape,+ };++ /// Controls which side of a triangle a ray-cast is allowed to hit.+ #[derive(Copy, Clone, PartialEq, Eq, Debug)]+ pub enum RayCullingMode {+ /// Ray-casting won’t hit back faces.+ IgnoreBackfaces,+ /// Ray-casting won’t hit front faces.+ IgnoreFrontfaces,+ }++ impl RayCullingMode {+ fn check(self, tri_normal: Vector, ray_dir: Vector) -> bool {+ match self {+ RayCullingMode::IgnoreBackfaces => tri_normal.dot(ray_dir) < 0.0,+ RayCullingMode::IgnoreFrontfaces => tri_normal.dot(ray_dir) > 0.0,+ }+ }+ }++ /// A utility shape with a `TypedCompositeShape` implementation that skips triangles that+ /// are back-faces or front-faces relative to a given ray and culling mode.+ struct TriMeshWithCulling<'a> {+ trimesh: &'a TriMesh,+ culling: RayCullingMode,+ ray: &'a Ray,+ }++ impl CompositeShape for TriMeshWithCulling<'_> {+ fn map_part_at(+ &self,+ shape_id: u32,+ f: &mut dyn FnMut(Option<&Pose>, &dyn Shape, Option<&dyn NormalConstraints>),+ ) {+ let _ = self.map_untyped_part_at(shape_id, f);+ }++ /// Gets the acceleration structure of the composite shape.+ fn bvh(&self) -> &Bvh {+ self.trimesh.bvh()+ }+ }++ impl TypedCompositeShape for TriMeshWithCulling<'_> {+ type PartShape = Triangle;+ type PartNormalConstraints = ();++ #[inline(always)]+ fn map_typed_part_at<T>(+ &self,+ i: u32,+ mut f: impl FnMut(+ Option<&Pose>,+ &Self::PartShape,+ Option<&Self::PartNormalConstraints>,+ ) -> T,+ ) -> Option<T> {+ let tri = self.trimesh.triangle(i);+ let tri_normal = tri.scaled_normal();++ if self.culling.check(tri_normal, self.ray.dir) {+ Some(f(None, &tri, None))+ } else {+ None+ }+ }++ #[inline(always)]+ fn map_untyped_part_at<T>(+ &self,+ i: u32,+ mut f: impl FnMut(Option<&Pose>, &dyn Shape, Option<&dyn NormalConstraints>) -> T,+ ) -> Option<T> {+ let tri = self.trimesh.triangle(i);+ let tri_normal = tri.scaled_normal();++ if self.culling.check(tri_normal, self.ray.dir) {+ Some(f(None, &tri, None))+ } else {+ None+ }+ }+ }++ impl TriMesh {+ /// Casts a ray on this triangle mesh transformed by `m`.+ ///+ /// Hits happening later than `max_time_of_impact` are ignored. In other words, hits are+ /// only searched along the segment `[ray.origin, ray.origin + ray.dir * max_time_of_impact`].+ ///+ /// Hits on back-faces or front-faces are ignored, depending on the given `culling` mode.+ #[inline]+ pub fn cast_ray_with_culling(+ &self,+ m: &Pose,+ ray: &Ray,+ max_time_of_impact: Real,+ culling: RayCullingMode,+ ) -> Option<RayIntersection> {+ let ls_ray = ray.inverse_transform_by(m);+ self.cast_local_ray_with_culling(&ls_ray, max_time_of_impact, culling)+ .map(|inter| inter.transform_by(m))+ }++ /// Casts a ray on this triangle mesh.+ ///+ /// This is the same as [`TriMesh::cast_ray_with_culling`] except that the ray is given+ /// in the mesh’s local-space.+ pub fn cast_local_ray_with_culling(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ culling: RayCullingMode,+ ) -> Option<RayIntersection> {+ let mesh_with_culling = TriMeshWithCulling {+ trimesh: self,+ culling,+ ray,+ };+ CompositeShapeRef(&mesh_with_culling)+ .cast_local_ray_and_get_normal(ray, max_time_of_impact, false)+ .map(|(triangle_id, hit)| hit.with_subshape(triangle_id))+ }+ }++ #[cfg(test)]+ mod test {+ use crate::math::Vector;+ use crate::query::{Ray, RayCullingMode};+ use crate::shape::TriMesh;++ #[test]+ fn cast_ray_on_trimesh_with_culling() {+ let vertices = vec![+ Vector::ZERO,+ Vector::new(1.0, 0.0, 0.0),+ Vector::new(0.0, 1.0, 0.0),+ ];+ let indices = vec![[0, 1, 2]];+ let ray_up = Ray::new(Vector::new(0.0, 0.0, -1.0), Vector::new(0.0, 0.0, 1.0));+ let ray_down = Ray::new(Vector::new(0.0, 0.0, 1.0), Vector::new(0.0, 0.0, -1.0));++ let mesh = TriMesh::new(vertices, indices).unwrap();+ assert!(mesh+ .cast_local_ray_with_culling(&ray_up, 1000.0, RayCullingMode::IgnoreFrontfaces)+ .is_some());+ assert!(mesh+ .cast_local_ray_with_culling(&ray_down, 1000.0, RayCullingMode::IgnoreFrontfaces)+ .is_none());++ assert!(mesh+ .cast_local_ray_with_culling(&ray_up, 1000.0, RayCullingMode::IgnoreBackfaces)+ .is_none());+ assert!(mesh+ .cast_local_ray_with_culling(&ray_down, 1000.0, RayCullingMode::IgnoreBackfaces)+ .is_some());+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/ray/ray_voxels.rs b/renderer/third_party/parry3d/src/query/ray/ray_voxels.rsnew file mode 100644index 0000000..3fd89b0--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/ray_voxels.rs@@ -0,0 +1,159 @@+use crate::math::{IVectorExt, Int, Real, Vector, VectorExt};+use crate::partitioning::BvhNode;+use crate::query::{Ray, RayCast, RayIntersection};+use crate::shape::{FeatureId, Voxels, VoxelsChunkRef};++impl RayCast for Voxels {+ #[inline]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ self.chunk_bvh()+ .find_best(+ max_time_of_impact,+ |node: &BvhNode, best_so_far| node.cast_ray(ray, best_so_far),+ |primitive, best_so_far| {+ let chunk = self.chunk_ref(primitive);+ chunk.cast_local_ray_and_get_normal(ray, best_so_far, solid)+ },+ )+ .map(|(_chunk_id, hit)| hit)+ }+}++impl<'a> RayCast for VoxelsChunkRef<'a> {+ /// The cells of the chunk walked one by one along the ray (Amanatides and Woo), each one's bounds the lattice+ /// planes `key * voxel_size`: the first solid cell is hit where the ray entered it, on the face it crossed.+ ///+ /// ThreeRT's patch (see `PATCH.md`): the walk used to ask a solid cell's box for the hit again, and a ray lying in+ /// one of the box's face planes (a ray straight down at x = 1.5 over cells of 0.1 m) grazes that box, which+ /// answered none: the walk went on and the ray missed every cell. Here a ray along the planes of an axis belongs+ /// to the cells its coordinate floors into (on a plane between two cells or chunks, the upper one), and a cell+ /// that is solid is a hit. A ray that starts in a solid cell is, `solid`, a hit at 0 with no normal (as every shape+ /// answers from inside); only the hollow cast still asks that cell's box where the ray leaves it.+ #[inline]+ fn cast_local_ray_and_get_normal(+ &self,+ ray: &Ray,+ max_time_of_impact: Real,+ solid: bool,+ ) -> Option<RayIntersection> {+ #[cfg(feature = "dim2")]+ let ii = [0, 1];+ #[cfg(feature = "dim3")]+ let ii = [0, 1, 2];++ let size = self.parent.voxel_size();+ let [domain_mins, domain_maxs] = self.domain();+ let origin_key = self.voxel_at_point_unchecked(ray.origin);++ // The stretch of the ray inside the chunk's box, and the axis it enters by.+ let mut t0: Real = 0.0;+ let mut t1 = max_time_of_impact;+ let mut entered: Option<usize> = None;+ for i in ii {+ let d = ray.dir.vget(i);+ if d == 0.0 {+ // (By the cell its coordinate floors into, as the walk takes cells: the same answer in both chunks+ // on either side of a plane.)+ let k = origin_key.ivget(i);+ if k < domain_mins.ivget(i) || k >= domain_maxs.ivget(i) {+ return None;+ }+ continue;+ }+ let o = ray.origin.vget(i);+ let lo = (domain_mins.ivget(i) as Real * size.vget(i) - o) / d;+ let hi = (domain_maxs.ivget(i) as Real * size.vget(i) - o) / d;+ let (near, far) = if lo <= hi { (lo, hi) } else { (hi, lo) };+ if near > t0 {+ t0 = near;+ entered = Some(i);+ }+ if far < t1 {+ t1 = far;+ }+ }+ if !(t0 <= t1) {+ return None;+ }++ // The cell the ray is in there, held inside the chunk (it enters on a face, to rounding).+ let mut key = if entered.is_some() {+ self.voxel_at_point_unchecked(ray.point_at(t0))+ } else {+ origin_key+ };+ for i in ii {+ key.ivset(+ i,+ key.ivget(i)+ .clamp(domain_mins.ivget(i), domain_maxs.ivget(i) - 1),+ );+ }+ let mut t = t0;+ let mut axis = entered;++ loop {+ if let Some(voxel) = self.voxel_state(key) {+ if !voxel.is_empty() {+ // We hit a voxel!+ let mut hit = match axis {+ // Entered across a face: that face, when it was crossed.+ Some(i) => {+ let mut normal = Vector::ZERO;+ let up = ray.dir.vget(i) > 0.0;+ normal.vset(i, if up { -1.0 } else { 1.0 });+ let face = if up { i as u32 } else { i as u32 + 3 };+ RayIntersection::new(t, normal, FeatureId::Face(face))+ }+ // The ray starts in this cell (the cell its origin floors into): inside a solid shape, a hit at+ // once with no normal, as every shape answers; the cell's box is not asked (centre +- half a+ // cell, it may round off a plane the origin lies on, and graze).+ None if solid => RayIntersection::new(0.0, Vector::ZERO, FeatureId::Unknown),+ // Hollow: where the ray leaves the cell's box, as before.+ // TODO: the ray should go on until it reaches empty space again.+ None => self+ .voxel_aabb_unchecked(key)+ .cast_local_ray_and_get_normal(ray, t1, solid)?,+ };+ // `subshape` says which voxel it belongs to.+ hit.subshape = self.flat_id(key).unwrap_or_else(|| unreachable!());+ return Some(hit);+ }+ }++ /*+ * The next cell: across the nearest lattice plane ahead (the lower axis first on a tie), never behind+ * where the ray is.+ */+ let mut next: Option<(Real, usize)> = None;+ for i in ii {+ let d = ray.dir.vget(i);+ if d != 0.0 {+ let plane = (key.ivget(i) + (d > 0.0) as Int) as Real * size.vget(i);+ let ti = ((plane - ray.origin.vget(i)) / d).max(t);+ if next.map_or(true, |(tn, _)| ti < tn) {+ next = Some((ti, i));+ }+ }+ }+ // (A ray with no direction stays in its cell.)+ let (tn, i) = next?;+ if tn > t1 {+ return None;+ }+ t = tn;+ axis = Some(i);+ let k = key.ivget(i) + if ray.dir.vget(i) > 0.0 { 1 } else { -1 };+ if k < domain_mins.ivget(i) || k >= domain_maxs.ivget(i) {+ // Leaving the chunk's bounds.+ return None;+ }+ key.ivset(i, k);+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/ray/simd_ray.rs b/renderer/third_party/parry3d/src/query/ray/simd_ray.rsnew file mode 100644index 0000000..9034ff0--- /dev/null+++ b/renderer/third_party/parry3d/src/query/ray/simd_ray.rs@@ -0,0 +1,23 @@+use crate::math::Vector;+use crate::query::Ray;++/// A structure representing 4 rays in an SIMD SoA fashion.+///+/// Note: When SIMD is not enabled, this is equivalent to a single Ray.+#[derive(Debug, Copy, Clone)]+pub struct SimdRay {+ /// The origin of the rays represented as a single SIMD point.+ pub origin: Vector,+ /// The direction of the rays represented as a single SIMD vector.+ pub dir: Vector,+}++impl SimdRay {+ /// Creates a new SIMD ray with all its lanes filled with the same ray.+ pub fn splat(ray: Ray) -> Self {+ Self {+ origin: ray.origin,+ dir: ray.dir,+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/sat/mod.rs b/renderer/third_party/parry3d/src/query/sat/mod.rsnew file mode 100644index 0000000..866e69f--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sat/mod.rs@@ -0,0 +1,106 @@+//! Application of the Separating Axis Theorem (SAT) for collision detection.+//!+//! # What is the Separating Axis Theorem?+//!+//! The **Separating Axis Theorem (SAT)** is a fundamental geometric principle used in collision+//! detection. It states that two convex shapes do **not** intersect if and only if there exists+//! an axis (a line) onto which the projections of the two shapes do not overlap.+//!+//! In simpler terms: if you can find a direction where, when you "shine a light" from that direction+//! and look at the shadows cast by both shapes, those shadows don't overlap, then the shapes+//! are not colliding.+//!+//! # How Does SAT Work?+//!+//! SAT works by testing a finite set of candidate axes to find a separating axis:+//!+//! 1. **Select candidate axes**: For polygons/polyhedra, these are typically:+//! - Face normals (perpendicular to each face)+//! - Edge cross products (perpendicular to pairs of edges from each shape, in 3D)+//!+//! 2. **Project both shapes onto each axis**: Find the extent (min and max) of each shape+//! along the axis by computing support points (the furthest points in that direction).+//!+//! 3. **Check for overlap**: If the projections don't overlap on any axis, the shapes don't collide.+//! If all axes show overlap, the shapes are intersecting.+//!+//! 4. **Find minimum separation**: The axis with the smallest overlap (or largest separation)+//! is the "best" separating axis, useful for computing penetration depth and contact normals.+//!+//! # When is SAT Used?+//!+//! SAT is particularly effective for:+//!+//! - **Convex polygonal shapes**: Cuboids (boxes), triangles, convex polygons/polyhedra+//! - **Accurate contact information**: SAT can provide exact penetration depth and contact normals+//! - **Shallow penetrations**: Works best when shapes are just touching or slightly overlapping+//! - **Edge-edge contacts**: In 3D, SAT naturally handles edge-edge collisions between polyhedra+//!+//! Parry uses SAT alongside other algorithms:+//! - **GJK**: For general convex shapes (faster for distance queries, but less accurate for contacts)+//! - **EPA**: For penetration depth when GJK detects overlap (but SAT is often more accurate)+//! - **Specialized algorithms**: For specific shape pairs (sphere-sphere, etc.)+//!+//! # Example: Cuboid-Cuboid Collision+//!+//! ```rust+//! # #[cfg(all(feature = "dim3", feature = "f32"))] {+//! use parry3d::shape::Cuboid;+//! use parry3d::query::sat::*;+//! use parry3d::math::{Pose, Vector};+//!+//! // Create two boxes+//! let box1 = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+//! let box2 = Cuboid::new(Vector::new(0.5, 0.5, 0.5));+//!+//! // Position them close together+//! let pos12 = Pose::translation(1.5, 0.0, 0.0);+//!+//! // Test face normals from box1+//! let (separation, _normal) = cuboid_cuboid_find_local_separating_normal_oneway(+//! &box1, &box2, &pos12+//! );+//!+//! if separation > 0.0 {+//! println!("Boxes are separated by {}", separation);+//! } else {+//! println!("Boxes are overlapping by {}", -separation);+//! }+//! # }+//! ```+//!+//! # Module Organization+//!+//! This module provides SAT implementations for common shape pairs:+//!+//! - **Cuboid-Cuboid**: Box vs box collision (2D and 3D)+//! - **Cuboid-Triangle**: Box vs triangle (2D and 3D)+//! - **Cuboid-Segment**: Box vs line segment (2D and 3D)+//! - **Cuboid-SupportMap**: Box vs any convex shape+//! - **Triangle-Segment**: Triangle vs line segment (3D only)+//! - **SupportMap-SupportMap**: Generic convex shape vs convex shape+//!+//! Each module provides functions to:+//! - Find the best separating normal (testing face normals)+//! - Find the best separating edge (testing edge cross products, 3D only)+//! - Compute separation distance along a given axis++pub use self::sat_cuboid_cuboid::*;+pub use self::sat_cuboid_point::*;+pub use self::sat_cuboid_segment::*;+pub use self::sat_cuboid_support_map::*;+pub use self::sat_cuboid_triangle::*;+pub use self::sat_support_map_support_map::*;+#[cfg(feature = "dim3")]+pub use self::sat_triangle_segment::*;+// pub use self::sat_polygon_polygon::*;++mod sat_cuboid_cuboid;+mod sat_cuboid_point;+mod sat_cuboid_segment;+mod sat_cuboid_support_map;+mod sat_cuboid_triangle;+mod sat_support_map_support_map;+#[cfg(feature = "dim3")]+mod sat_triangle_segment;+// mod sat_polygon_polygon;diff --git a/renderer/third_party/parry3d/src/query/sat/sat_cuboid_cuboid.rs b/renderer/third_party/parry3d/src/query/sat/sat_cuboid_cuboid.rsnew file mode 100644index 0000000..1b97b68--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sat/sat_cuboid_cuboid.rs@@ -0,0 +1,294 @@+use crate::math::{Pose, Real, Vector, VectorExt, DIM};+use crate::shape::{Cuboid, SupportMap};+use crate::utils::WSign;++/// Computes the separation distance between two cuboids along a given axis.+///+/// This function is part of the Separating Axis Theorem (SAT) implementation for cuboid-cuboid+/// collision detection. It projects both cuboids onto the specified axis and computes how far+/// apart they are (positive = separated, negative = overlapping).+///+/// # How It Works+///+/// 1. Orients the axis to point from cuboid1 toward cuboid2 (using the translation vector)+/// 2. Finds the support points (furthest points) on each cuboid in that direction+/// 3. Computes the signed distance between these support points along the axis+///+/// # Parameters+///+/// - `cuboid1`: The first cuboid (in its local coordinate frame)+/// - `cuboid2`: The second cuboid+/// - `pos12`: The position of cuboid2 relative to cuboid1 (transforms from cuboid2's space to cuboid1's space)+/// - `axis1`: The axis direction in cuboid1's local space to test for separation+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The separation distance along the axis+/// - **Positive**: Shapes are separated by this distance+/// - **Negative**: Shapes are overlapping (penetration depth is the absolute value)+/// - **Zero**: Shapes are exactly touching+/// - `Vector`: The oriented axis direction (pointing from cuboid1 toward cuboid2)+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Cuboid;+/// use parry3d::query::sat::cuboid_cuboid_compute_separation_wrt_local_line;+/// use parry3d::math::{Pose, Vector};+///+/// let cube1 = Cuboid::new(Vector::splat(1.0));+/// let cube2 = Cuboid::new(Vector::splat(1.0));+///+/// // Position cube2 at (3, 0, 0) relative to cube1+/// let pos12 = Pose::translation(3.0, 0.0, 0.0);+///+/// // Test separation along the X axis+/// let (separation, _axis) = cuboid_cuboid_compute_separation_wrt_local_line(+/// &cube1,+/// &cube2,+/// &pos12,+/// Vector::X+/// );+///+/// // Should be separated by 1.0 (distance 3.0 - half_extents 1.0 - 1.0)+/// assert!(separation > 0.0);+/// # }+/// ```+#[cfg(feature = "dim3")]+pub fn cuboid_cuboid_compute_separation_wrt_local_line(+ cuboid1: &Cuboid,+ cuboid2: &Cuboid,+ pos12: &Pose,+ axis1: Vector,+) -> (Real, Vector) {+ #[expect(clippy::unnecessary_cast)]+ let signum = pos12.translation.dot(axis1).copy_sign_to(1.0 as Real);+ let axis1 = axis1 * signum;+ let axis2 = pos12.rotation.inverse() * -axis1;+ let local_pt1 = cuboid1.local_support_point(axis1);+ let local_pt2 = cuboid2.local_support_point(axis2);+ let pt2 = pos12 * local_pt2;+ let separation = (pt2 - local_pt1).dot(axis1);+ (separation, axis1)+}++/// Finds the best separating axis by testing all edge-edge combinations between two cuboids.+///+/// In 3D, edge-edge contact is common when two boxes collide. This function tests all possible+/// axes formed by the cross product of edges from each cuboid to find the axis with maximum+/// separation (or minimum penetration).+///+/// # Why Test Edge Cross Products?+///+/// When two 3D convex polyhedra collide, the separating axis (if one exists) must be either:+/// 1. A face normal from one shape+/// 2. A face normal from the other shape+/// 3. **Perpendicular to an edge from each shape** (the cross product of the edges)+///+/// This function handles case 3. For two cuboids, there are 3 edges per cuboid (aligned with X, Y, Z),+/// giving 3 × 3 = 9 possible edge pair combinations to test.+///+/// # Parameters+///+/// - `cuboid1`: The first cuboid (in its local coordinate frame)+/// - `cuboid2`: The second cuboid+/// - `pos12`: The position of cuboid2 relative to cuboid1+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The best (maximum) separation found across all edge-edge axes+/// - **Positive**: Shapes are separated+/// - **Negative**: Shapes are overlapping+/// - `Vector`: The axis direction that gives this separation+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Cuboid;+/// use parry3d::query::sat::cuboid_cuboid_find_local_separating_edge_twoway;+/// use parry3d::math::{Pose, Vector};+///+/// let cube1 = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+/// let cube2 = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+///+/// // Rotate and position cube2 so edge-edge contact is likely+/// let pos12 = Pose::translation(2.0, 2.0, 0.0);+///+/// let (separation, _axis) = cuboid_cuboid_find_local_separating_edge_twoway(+/// &cube1,+/// &cube2,+/// &pos12+/// );+///+/// if separation > 0.0 {+/// println!("Separated by {} along an edge-edge axis", separation);+/// }+/// # }+/// ```+///+/// # Note+///+/// This function only tests edge-edge axes. For a complete SAT test, you must also test+/// face normals using [`cuboid_cuboid_find_local_separating_normal_oneway`].+#[cfg(feature = "dim3")]+pub fn cuboid_cuboid_find_local_separating_edge_twoway(+ cuboid1: &Cuboid,+ cuboid2: &Cuboid,+ pos12: &Pose,+) -> (Real, Vector) {+ use approx::AbsDiffEq;+ let mut best_separation = -Real::MAX;+ let mut best_dir = Vector::ZERO;++ let x2 = pos12.rotation * Vector::X;+ let y2 = pos12.rotation * Vector::Y;+ let z2 = pos12.rotation * Vector::Z;++ // We have 3 * 3 = 9 axes to test.+ let axes = [+ // Vector::{x, y ,z}().cross(y2)+ Vector::new(0.0, -x2.z, x2.y),+ Vector::new(x2.z, 0.0, -x2.x),+ Vector::new(-x2.y, x2.x, 0.0),+ // Vector::{x, y ,z}().cross(y2)+ Vector::new(0.0, -y2.z, y2.y),+ Vector::new(y2.z, 0.0, -y2.x),+ Vector::new(-y2.y, y2.x, 0.0),+ // Vector::{x, y ,z}().cross(y2)+ Vector::new(0.0, -z2.z, z2.y),+ Vector::new(z2.z, 0.0, -z2.x),+ Vector::new(-z2.y, z2.x, 0.0),+ ];++ for axis1 in &axes {+ let norm1 = axis1.length();+ if norm1 > Real::default_epsilon() {+ let (separation, axis1) = cuboid_cuboid_compute_separation_wrt_local_line(+ cuboid1,+ cuboid2,+ pos12,+ axis1 / norm1,+ );++ if separation > best_separation {+ best_separation = separation;+ best_dir = axis1;+ }+ }+ }++ (best_separation, best_dir)+}++/// Finds the best separating axis by testing the face normals of the first cuboid.+///+/// This function tests the face normals (X, Y, Z axes in 2D/3D) of `cuboid1` to find which+/// direction gives the maximum separation between the two cuboids. This is the "one-way" test+/// that only considers faces from one cuboid.+///+/// # Why "One-Way"?+///+/// For a complete SAT test between two cuboids, you need to test:+/// 1. Face normals from cuboid1 (this function)+/// 2. Face normals from cuboid2 (call this function again with swapped arguments)+/// 3. Edge-edge cross products in 3D (`cuboid_cuboid_find_local_separating_edge_twoway`)+///+/// By testing only one shape's normals at a time, the implementation can be more efficient+/// and reusable.+///+/// # Parameters+///+/// - `cuboid1`: The cuboid whose face normals will be tested+/// - `cuboid2`: The other cuboid+/// - `pos12`: The position of cuboid2 relative to cuboid1+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The maximum separation found among cuboid1's face normals+/// - **Positive**: Shapes are separated by at least this distance+/// - **Negative**: Shapes are overlapping (penetration)+/// - `Vector`: The face normal direction that gives this separation+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::shape::Cuboid;+/// use parry2d::query::sat::cuboid_cuboid_find_local_separating_normal_oneway;+/// use parry2d::math::{Pose, Vector};+///+/// let rect1 = Cuboid::new(Vector::new(1.0, 1.0));+/// let rect2 = Cuboid::new(Vector::new(0.5, 0.5));+///+/// // Position rect2 to the right of rect1+/// let pos12 = Pose::translation(2.5, 0.0);+///+/// // Test rect1's face normals (X and Y axes)+/// let (sep1, normal1) = cuboid_cuboid_find_local_separating_normal_oneway(+/// &rect1, &rect2, &pos12+/// );+///+/// // Test rect2's face normals by swapping arguments and inverting the transform+/// let (sep2, normal2) = cuboid_cuboid_find_local_separating_normal_oneway(+/// &rect2, &rect1, &pos12.inverse()+/// );+///+/// // The maximum separation indicates if shapes collide+/// let max_separation = sep1.max(sep2);+/// if max_separation > 0.0 {+/// println!("Shapes are separated!");+/// }+/// # }+/// ```+pub fn cuboid_cuboid_find_local_separating_normal_oneway(+ cuboid1: &Cuboid,+ cuboid2: &Cuboid,+ pos12: &Pose,+) -> (Real, Vector) {+ // The largest separation over all axes, which is what SAT reports.+ let mut best_separation = -Real::MAX;+ let mut best_dir = Vector::ZERO;+ let mut axis_acc = Vector::ZERO;+ let mut num_positive = 0;++ for i in 0..DIM {+ #[expect(clippy::unnecessary_cast)]+ let sign = pos12.translation.vget(i).copy_sign_to(1.0 as Real);+ let axis1 = Vector::ith(i, sign);+ let axis2 = pos12.rotation.inverse() * -axis1;+ let local_pt2 = cuboid2.local_support_point(axis2);+ let pt2 = pos12 * local_pt2;+ let separation = pt2.vget(i) * sign - cuboid1.half_extents.vget(i);++ if separation > best_separation {+ best_separation = separation;+ best_dir = axis1;+ }++ if separation >= 0.0 {+ // Add the axis weighted by the separation.+ // If the separation is exactly zero, add a little separation to+ // keep a little nudge towards that direction. The resulting axis remains+ // correct as it will be a linear combination of the separating axis (so it+ // will be contained by the vertex/edge’s normal cone).+ axis_acc[i] += sign * separation.max(Real::EPSILON);+ num_positive += 1;+ }+ }++ if num_positive > 1 {+ let axis_acc_dir = axis_acc.normalize();+ let pt1 = cuboid1.local_support_point(axis_acc_dir);+ let pt2 = cuboid2.support_point(pos12, -axis_acc_dir);+ let separation = (pt2 - pt1).dot(axis_acc_dir);+ debug_assert!(separation >= 0.0);+ (separation, axis_acc_dir)+ } else {+ (best_separation, best_dir)+ }+}diff --git a/renderer/third_party/parry3d/src/query/sat/sat_cuboid_point.rs b/renderer/third_party/parry3d/src/query/sat/sat_cuboid_point.rsnew file mode 100644index 0000000..460e163--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sat/sat_cuboid_point.rs@@ -0,0 +1,92 @@+use crate::math::{Pose, Real, Vector};+use crate::shape::{Cuboid, SupportMap};++/// Computes the separation distance between a point and a cuboid along a specified normal direction.+///+/// This function is used in SAT (Separating Axis Theorem) implementations for shapes that can be+/// treated as having a single representative point with an associated normal vector. Examples include:+/// - Segments (in 2D, using one endpoint and the segment's normal)+/// - Triangles (in 3D, using one vertex and the triangle's face normal)+///+/// # Why This Works+///+/// For a cuboid centered at the origin with symmetry, we only need to test one direction of the+/// normal (not both +normal and -normal) because the cuboid looks the same from both directions.+/// This optimization makes the function more efficient than the general support map approach.+///+/// # Parameters+///+/// - `point1`: A point in the first shape's local coordinate space+/// - `normal1`: Optional unit normal vector associated with the point (e.g., triangle face normal)+/// - If `None`, the function returns maximum negative separation (indicating overlap)+/// - `shape2`: The cuboid to test against+/// - `pos12`: The position of `shape2` (cuboid) relative to `point1`'s coordinate frame+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The separation distance along the normal direction+/// - **Positive**: The point and cuboid are separated+/// - **Negative**: The point penetrates the cuboid (or normal is None)+/// - **Zero**: The point exactly touches the cuboid surface+/// - `Vector`: The oriented normal direction used for the test (pointing from point toward cuboid)+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::shape::Cuboid;+/// use parry2d::query::sat::point_cuboid_find_local_separating_normal_oneway;+/// use parry2d::math::{Vector, Pose};+///+/// let point = Vector::ZERO;+/// let normal = Some((Vector::X.normalize()));+/// let cuboid = Cuboid::new(Vector::new(1.0, 1.0));+///+/// // Position cuboid 3 units to the right+/// let pos12 = Pose::translation(3.0, 0.0);+///+/// let (separation, _dir) = point_cuboid_find_local_separating_normal_oneway(+/// point,+/// normal,+/// &cuboid,+/// &pos12+/// );+///+/// // Should be separated by 1.0 (distance 3.0 - cuboid extent 1.0 - point distance 0.0)+/// assert!(separation > 0.0);+/// # }+/// ```+///+/// # Implementation Note+///+/// This function only works correctly when the **cuboid is on the right-hand side** (as shape2)+/// because it exploits the cuboid's symmetry around the origin. The cuboid must be centered at+/// its local origin for this optimization to be valid.+pub fn point_cuboid_find_local_separating_normal_oneway(+ point1: Vector,+ normal1: Option<Vector>,+ shape2: &Cuboid,+ pos12: &Pose,+) -> (Real, Vector) {+ let mut best_separation = -Real::MAX;+ let mut best_dir = Vector::ZERO;++ if let Some(normal1) = normal1 {+ let axis1 = if (pos12.translation - point1).dot(normal1) >= 0.0 {+ normal1+ } else {+ -normal1+ };++ let pt2 = shape2.support_point_toward(pos12, -axis1);+ let separation = (pt2 - point1).dot(axis1);++ if separation > best_separation {+ best_separation = separation;+ best_dir = axis1;+ }+ }++ (best_separation, best_dir)+}diff --git a/renderer/third_party/parry3d/src/query/sat/sat_cuboid_segment.rs b/renderer/third_party/parry3d/src/query/sat/sat_cuboid_segment.rsnew file mode 100644index 0000000..9a0127a--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sat/sat_cuboid_segment.rs@@ -0,0 +1,155 @@+use crate::math::{Pose, Real, Vector};+use crate::query::sat;+use crate::shape::{Cuboid, Segment};++/// Finds the best separating axis by testing edge-edge combinations between a cuboid and a segment (3D only).+///+/// In 3D, when a box collides with a line segment, the contact might occur along an axis+/// perpendicular to both a cuboid edge and the segment itself. This function tests all such+/// axes (cross products) to find the one with maximum separation.+///+/// # Parameters+///+/// - `cube1`: The cuboid+/// - `segment2`: The line segment+/// - `pos12`: The position of the segment relative to the cuboid+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The maximum separation found across all edge-edge axes+/// - **Positive**: Shapes are separated+/// - **Negative**: Shapes are overlapping+/// - `Vector`: The axis direction that gives this separation+///+/// # The 3 Axes Tested+///+/// A segment is a single edge, so we test cross products between:+/// - The segment's direction (B - A)+/// - Each of the 3 cuboid edge directions (X, Y, Z)+///+/// This gives 3 potential separating axes. The function delegates to+/// [`cuboid_support_map_find_local_separating_edge_twoway`](super::cuboid_support_map_find_local_separating_edge_twoway)+/// to perform the actual separation tests.+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Cuboid, Segment};+/// use parry3d::query::sat::cuboid_segment_find_local_separating_edge_twoway;+/// use parry3d::math::{Vector, Pose};+///+/// let cube = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+/// let segment = Segment::new(+/// Vector::ZERO,+/// Vector::new(0.0, 2.0, 0.0)+/// );+///+/// // Position segment to the right of the cube+/// let pos12 = Pose::translation(2.5, 0.0, 0.0);+///+/// let (separation, axis) = cuboid_segment_find_local_separating_edge_twoway(+/// &cube,+/// &segment,+/// &pos12+/// );+///+/// println!("Edge-edge separation: {}", separation);+/// # }+/// ```+///+/// # Usage in Complete SAT+///+/// For a complete cuboid-segment collision test, you must also test:+/// 1. Cuboid face normals (X, Y, Z axes)+/// 2. Segment normal (in 2D) or face normal (for degenerate 3D cases)+/// 3. Edge-edge axes (this function, 3D only)+#[cfg(feature = "dim3")]+pub fn cuboid_segment_find_local_separating_edge_twoway(+ cube1: &Cuboid,+ segment2: &Segment,+ pos12: &Pose,+) -> (Real, Vector) {+ let x2 = pos12.rotation * (segment2.b - segment2.a);++ let axes = [+ // Vector::{x, y ,z}().cross(y2)+ Vector::new(0.0, -x2.z, x2.y),+ Vector::new(x2.z, 0.0, -x2.x),+ Vector::new(-x2.y, x2.x, 0.0),+ ];++ sat::cuboid_support_map_find_local_separating_edge_twoway(cube1, segment2, &axes, pos12)+}++/// Finds the best separating axis by testing a segment's normal against a cuboid (2D only).+///+/// In 2D, a segment (line segment) has an associated normal vector perpendicular to the segment.+/// This function tests both directions of this normal to find the maximum separation from the cuboid.+///+/// # How It Works+///+/// The function treats the segment as a point-with-normal using one of its endpoints (point A)+/// and delegates to [`point_cuboid_find_local_separating_normal_oneway`](super::point_cuboid_find_local_separating_normal_oneway).+///+/// # Parameters+///+/// - `segment1`: The line segment whose normal will be tested+/// - `shape2`: The cuboid+/// - `pos12`: The position of the cuboid relative to the segment+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The separation distance along the segment's normal+/// - **Positive**: Shapes are separated+/// - **Negative**: Shapes are overlapping+/// - `Vector`: The normal direction that gives this separation+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::shape::{Segment, Cuboid};+/// use parry2d::query::sat::segment_cuboid_find_local_separating_normal_oneway;+/// use parry2d::math::{Vector, Pose};+///+/// // Horizontal segment+/// let segment = Segment::new(+/// Vector::ZERO,+/// Vector::new(2.0, 0.0)+/// );+/// let cuboid = Cuboid::new(Vector::new(1.0, 1.0));+///+/// // Position cuboid above the segment+/// let pos12 = Pose::translation(1.0, 2.5);+///+/// let (separation, normal) = segment_cuboid_find_local_separating_normal_oneway(+/// &segment,+/// &cuboid,+/// &pos12+/// );+///+/// println!("Separation along segment normal: {}", separation);+/// # }+/// ```+///+/// # 2D Only+///+/// This function is only available in 2D. In 3D, segments don't have a unique normal direction+/// (there are infinitely many perpendicular directions), so edge-edge cross products are used+/// instead (see `cuboid_segment_find_local_separating_edge_twoway`).+#[cfg(feature = "dim2")]+pub fn segment_cuboid_find_local_separating_normal_oneway(+ segment1: &Segment,+ shape2: &Cuboid,+ pos12: &Pose,+) -> (Real, Vector) {+ sat::point_cuboid_find_local_separating_normal_oneway(+ segment1.a,+ segment1.normal(),+ shape2,+ pos12,+ )+}diff --git a/renderer/third_party/parry3d/src/query/sat/sat_cuboid_support_map.rs b/renderer/third_party/parry3d/src/query/sat/sat_cuboid_support_map.rsnew file mode 100644index 0000000..50f4257--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sat/sat_cuboid_support_map.rs@@ -0,0 +1,274 @@+use crate::math::{Pose, Real, Vector, VectorExt, DIM};+use crate::shape::{Cuboid, SupportMap};++/// Computes the separation distance between a cuboid and a convex support map shape along a given axis.+///+/// This function tests both the positive and negative directions of the axis to find which+/// orientation gives the actual separation between the shapes. This is necessary because we don't+/// know in advance which direction will show the true separation.+///+/// # Parameters+///+/// - `cube1`: The cuboid+/// - `shape2`: Any convex shape implementing [`SupportMap`] (sphere, capsule, convex mesh, etc.)+/// - `pos12`: The position of `shape2` relative to `cube1`+/// - `axis1`: The unit direction vector (in `cube1`'s local space) to test+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The separation distance along the better of the two axis directions+/// - **Positive**: Shapes are separated+/// - **Negative**: Shapes are overlapping+/// - `Vector`: The axis direction (either `axis1` or `-axis1`) that gives this separation+///+/// # Why Test Both Directions?+///+/// When testing separation along an axis, we need to check both `axis1` and `-axis1` because:+/// - The shapes might be oriented such that one direction shows separation while the other shows overlap+/// - We want to find the direction that gives the maximum (least negative) separation+///+/// For symmetric shapes like sphere vs sphere, both directions give the same result, but for+/// asymmetric configurations, testing both is necessary for correctness.+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Cuboid, Ball};+/// use parry3d::query::sat::cuboid_support_map_compute_separation_wrt_local_line;+/// use parry3d::math::{Pose, Vector};+///+/// let cube = Cuboid::new(Vector::splat(1.0));+/// let sphere = Ball::new(0.5);+///+/// // Position sphere near the cube+/// let pos12 = Pose::translation(2.0, 0.0, 0.0);+///+/// // Test separation along an arbitrary axis+/// let axis = Vector::new(1.0, 1.0, 0.0).normalize();+/// let (separation, chosen_axis) = cuboid_support_map_compute_separation_wrt_local_line(+/// &cube,+/// &sphere,+/// &pos12,+/// axis+/// );+///+/// println!("Separation: {} along axis: {:?}", separation, chosen_axis);+/// # }+/// ```+///+/// # Performance Note+///+/// This is a relatively expensive operation as it computes support points in both directions.+/// For specific shape pairs (like cuboid-cuboid), there are optimized versions that avoid this+/// double computation.+#[cfg(feature = "dim3")]+pub fn cuboid_support_map_compute_separation_wrt_local_line(+ cube1: &Cuboid,+ shape2: &impl SupportMap,+ pos12: &Pose,+ axis1: Vector,+) -> (Real, Vector) {+ let axis1_2 = pos12.rotation.inverse() * axis1;+ let separation1 = {+ let axis2 = -axis1_2;+ let local_pt1 = cube1.local_support_point_toward(axis1);+ let local_pt2 = shape2.local_support_point_toward(axis2);+ let pt2 = pos12 * local_pt2;+ (pt2 - local_pt1).dot(axis1)+ };++ let separation2 = {+ let axis2 = axis1_2;+ let local_pt1 = cube1.local_support_point_toward(-axis1);+ let local_pt2 = shape2.local_support_point_toward(axis2);+ let pt2 = pos12 * local_pt2;+ (pt2 - local_pt1).dot(-axis1)+ };++ if separation1 > separation2 {+ (separation1, axis1)+ } else {+ (separation2, -axis1)+ }+}++/// Finds the best separating axis by testing edge-edge combinations between a cuboid and a support map shape.+///+/// This function is used in 3D SAT implementations where edge-edge contact is possible. It tests+/// a precomputed set of axes (typically cross products of edges from both shapes) to find the+/// axis with maximum separation.+///+/// # Parameters+///+/// - `cube1`: The cuboid+/// - `shape2`: Any convex shape implementing [`SupportMap`]+/// - `axes`: A slice of axis directions to test (not necessarily unit length)+/// - `pos12`: The position of `shape2` relative to `cube1`+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The maximum separation found across all tested axes+/// - **Positive**: Shapes are separated+/// - **Negative**: Shapes are overlapping (minimum penetration)+/// - `Vector`: The axis direction that gives this separation (normalized)+///+/// # Why Precomputed Axes?+///+/// The caller typically computes the candidate axes as cross products of edges:+/// - Cuboid has 3 edge directions (X, Y, Z)+/// - The other shape's edges depend on its geometry+/// - Cross products of these edges give potential separating axes+///+/// This function handles the actual separation testing for those precomputed axes.+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Cuboid, Capsule};+/// use parry3d::query::sat::cuboid_support_map_find_local_separating_edge_twoway;+/// use parry3d::math::{Pose, Vector};+///+/// let cube = Cuboid::new(Vector::splat(1.0));+/// let capsule = Capsule::new(Vector::new(0.0, -1.0, 0.0), Vector::new(0.0, 1.0, 0.0), 0.5);+///+/// // Position capsule near the cube+/// let pos12 = Pose::translation(2.0, 0.0, 0.0);+///+/// // Compute edge cross products+/// let capsule_dir = Vector::Y; // capsule's axis direction+/// let axes = [+/// Vector::X.cross(capsule_dir), // cube X × capsule axis+/// Vector::Y.cross(capsule_dir), // cube Y × capsule axis+/// Vector::Z.cross(capsule_dir), // cube Z × capsule axis+/// ];+///+/// let (separation, axis) = cuboid_support_map_find_local_separating_edge_twoway(+/// &cube,+/// &capsule,+/// &axes,+/// &pos12+/// );+///+/// println!("Best edge-edge separation: {} along {:?}", separation, axis);+/// # }+/// ```+///+/// # Implementation Details+///+/// - Axes with near-zero length are skipped (they represent parallel or degenerate edges)+/// - Each axis is normalized before computing separation+/// - The function tests both positive and negative directions of each axis using+/// `cuboid_support_map_compute_separation_wrt_local_line`+#[cfg(feature = "dim3")]+pub fn cuboid_support_map_find_local_separating_edge_twoway(+ cube1: &Cuboid,+ shape2: &impl SupportMap,+ axes: &[Vector],+ pos12: &Pose,+) -> (Real, Vector) {+ let mut best_separation = -Real::MAX;+ let mut best_dir = Vector::ZERO;++ for axis1 in axes {+ if let Some(axis1) = (*axis1).try_normalize() {+ let (separation, axis1) =+ cuboid_support_map_compute_separation_wrt_local_line(cube1, shape2, pos12, axis1);++ if separation > best_separation {+ best_separation = separation;+ best_dir = axis1;+ }+ }+ }++ (best_separation, best_dir)+}++/// Finds the best separating axis by testing the face normals of a cuboid against a support map shape.+///+/// This function tests all face normals (X, Y, and Z axes in both positive and negative directions)+/// of the cuboid to find which direction gives the maximum separation from the support map shape.+///+/// # Parameters+///+/// - `cube1`: The cuboid whose face normals will be tested+/// - `shape2`: Any convex shape implementing [`SupportMap`]+/// - `pos12`: The position of `shape2` relative to `cube1`+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The maximum separation found among the cuboid's face normals+/// - **Positive**: Shapes are separated+/// - **Negative**: Shapes are overlapping+/// - `Vector`: The face normal direction that gives this separation+///+/// # Usage in Complete SAT+///+/// This function tests only the face normals of the cuboid. For a complete SAT collision test+/// between a cuboid and another shape, you typically need to:+///+/// 1. Test cuboid's face normals (this function)+/// 2. Test the other shape's face normals (if applicable)+/// 3. Test edge-edge cross products in 3D (if both shapes have edges)+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::shape::{Cuboid, Ball};+/// use parry2d::query::sat::cuboid_support_map_find_local_separating_normal_oneway;+/// use parry2d::math::{Pose, Vector};+///+/// let cube = Cuboid::new(Vector::new(1.0, 1.0));+/// let sphere = Ball::new(0.5);+///+/// // Position sphere to the right of the cube+/// let pos12 = Pose::translation(2.0, 0.0);+///+/// let (separation, normal) = cuboid_support_map_find_local_separating_normal_oneway(+/// &cube,+/// &sphere,+/// &pos12+/// );+///+/// if separation > 0.0 {+/// println!("Shapes separated by {} along normal {}", separation, normal);+/// } else {+/// println!("Shapes overlapping by {} along normal {}", -separation, normal);+/// }+/// # }+/// ```+///+/// # Performance+///+/// This function is more efficient than `cuboid_support_map_compute_separation_wrt_local_line`+/// for face normals because it can directly compute the separation without testing both directions.+/// It tests 2×DIM axes (where DIM is 2 or 3).+pub fn cuboid_support_map_find_local_separating_normal_oneway<S: SupportMap>(+ cube1: &Cuboid,+ shape2: &S,+ pos12: &Pose,+) -> (Real, Vector) {+ let mut best_separation = -Real::MAX;+ let mut best_dir = Vector::ZERO;++ for i in 0..DIM {+ for sign in &[-1.0, 1.0] {+ let axis1 = Vector::ith(i, *sign);+ let pt2 = shape2.support_point_toward(pos12, -axis1);+ let separation = pt2.vget(i) * *sign - cube1.half_extents.vget(i);++ if separation > best_separation {+ best_separation = separation;+ best_dir = axis1;+ }+ }+ }++ (best_separation, best_dir)+}diff --git a/renderer/third_party/parry3d/src/query/sat/sat_cuboid_triangle.rs b/renderer/third_party/parry3d/src/query/sat/sat_cuboid_triangle.rsnew file mode 100644index 0000000..81338c0--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sat/sat_cuboid_triangle.rs@@ -0,0 +1,332 @@+#[cfg(feature = "dim3")]+use crate::approx::AbsDiffEq;+use crate::math::{Pose, Real, Vector};+#[cfg(feature = "dim3")]+use crate::query::sat;+#[cfg(feature = "dim2")]+use crate::query::sat::support_map_support_map_compute_separation;+use crate::shape::{Cuboid, SupportMap, Triangle};++#[cfg(all(feature = "dim3", not(feature = "std")))]+use simba::scalar::ComplexField;++/// Finds the best separating axis by testing all edge-edge combinations between a cuboid and a triangle (3D only).+///+/// In 3D collision detection, when a box and triangle intersect, the contact may occur along an+/// axis perpendicular to an edge from each shape. This function tests all 3×3 = 9 such axes+/// (cross products of cuboid edges with triangle edges) to find the one with maximum separation.+///+/// # Parameters+///+/// - `cube1`: The cuboid (in its local coordinate frame)+/// - `triangle2`: The triangle+/// - `pos12`: The position of the triangle relative to the cuboid+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The maximum separation found across all edge-edge axes+/// - **Positive**: Shapes are separated+/// - **Negative**: Shapes are overlapping (penetration depth)+/// - `Vector`: The axis direction that gives this separation+///+/// # The 9 Axes Tested+///+/// The function tests cross products between:+/// - 3 cuboid edge directions: X, Y, Z (aligned with cuboid axes)+/// - 3 triangle edge vectors: AB, BC, CA+///+/// This gives 3×3 = 9 potential separating axes. Each axis is normalized before testing,+/// and degenerate axes (near-zero length, indicating parallel edges) are skipped.+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Cuboid, Triangle};+/// use parry3d::query::sat::cuboid_triangle_find_local_separating_edge_twoway;+/// use parry3d::math::{Vector, Pose};+///+/// let cube = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+/// let triangle = Triangle::new(+/// Vector::ZERO,+/// Vector::new(1.0, 0.0, 0.0),+/// Vector::new(0.0, 1.0, 0.0)+/// );+///+/// // Position triangle near the cube+/// let pos12 = Pose::translation(2.0, 0.0, 0.0);+///+/// let (separation, axis) = cuboid_triangle_find_local_separating_edge_twoway(+/// &cube,+/// &triangle,+/// &pos12+/// );+///+/// println!("Edge-edge separation: {} along {}", separation, axis);+/// # }+/// ```+///+/// # Usage in Complete SAT+///+/// For a complete cuboid-triangle SAT test, you must also test:+/// 1. Cuboid face normals (X, Y, Z axes)+/// 2. Triangle face normal (perpendicular to the triangle plane)+/// 3. Edge-edge axes (this function)+#[cfg(feature = "dim3")]+#[inline(always)]+pub fn cuboid_triangle_find_local_separating_edge_twoway(+ cube1: &Cuboid,+ triangle2: &Triangle,+ pos12: &Pose,+) -> (Real, Vector) {+ // NOTE: everything in this method will be expressed+ // in the local-space of the first triangle. So we+ // don't bother adding 2_1 suffixes (e.g. `a2_1`) to everything in+ // order to keep the code more readable.+ let a = pos12 * triangle2.a;+ let b = pos12 * triangle2.b;+ let c = pos12 * triangle2.c;++ let ab = b - a;+ let bc = c - b;+ let ca = a - c;++ // We have 3 * 3 = 9 axes to test.+ let axes = [+ // Vector::{x, y ,z}().cross(ab)+ Vector::new(0.0, -ab.z, ab.y),+ Vector::new(ab.z, 0.0, -ab.x),+ Vector::new(-ab.y, ab.x, 0.0),+ // Vector::{x, y ,z}().cross(bc)+ Vector::new(0.0, -bc.z, bc.y),+ Vector::new(bc.z, 0.0, -bc.x),+ Vector::new(-bc.y, bc.x, 0.0),+ // Vector::{x, y ,z}().cross(ca)+ Vector::new(0.0, -ca.z, ca.y),+ Vector::new(ca.z, 0.0, -ca.x),+ Vector::new(-ca.y, ca.x, 0.0),+ ];++ let tri_dots = [+ (axes[0].dot(a), axes[0].dot(c)),+ (axes[1].dot(a), axes[1].dot(c)),+ (axes[2].dot(a), axes[2].dot(c)),+ (axes[3].dot(a), axes[3].dot(c)),+ (axes[4].dot(a), axes[4].dot(c)),+ (axes[5].dot(a), axes[5].dot(c)),+ (axes[6].dot(a), axes[6].dot(b)),+ (axes[7].dot(a), axes[7].dot(b)),+ (axes[8].dot(a), axes[8].dot(b)),+ ];++ let mut best_sep = -Real::MAX;+ let mut best_axis = axes[0];++ for (i, axis) in axes.iter().enumerate() {+ let axis_norm_squared = axis.length_squared();++ if axis_norm_squared > Real::default_epsilon() {+ let axis_norm = axis_norm_squared.sqrt();++ // NOTE: for both axis and -axis, the dot1 will have the same+ // value because of the cuboid's symmetry.+ let local_pt1 = cube1.local_support_point(*axis);+ let dot1 = local_pt1.dot(*axis) / axis_norm;++ let (dot2_min, dot2_max) = crate::utils::sort2(tri_dots[i].0, tri_dots[i].1);++ let separation_a = dot2_min / axis_norm - dot1; // separation on axis+ let separation_b = -dot2_max / axis_norm - dot1; // separation on -axis++ if separation_a > best_sep {+ best_sep = separation_a;+ best_axis = *axis / axis_norm;+ }++ if separation_b > best_sep {+ best_sep = separation_b;+ best_axis = -*axis / axis_norm;+ }+ }+ }++ (best_sep, best_axis)+}++/// Finds the best separating axis by testing the edge normals of a triangle against a support map shape (2D only).+///+/// In 2D, a triangle has three edges, each with an associated outward-pointing normal.+/// This function tests all three edge normals to find which gives the maximum separation+/// from the support map shape.+///+/// # Parameters+///+/// - `triangle1`: The triangle whose edge normals will be tested+/// - `shape2`: Any convex shape implementing [`SupportMap`]+/// - `pos12`: The position of `shape2` relative to `triangle1`+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The maximum separation found among the triangle's edge normals+/// - **Positive**: Shapes are separated+/// - **Negative**: Shapes are overlapping+/// - `Vector`: The edge normal direction that gives this separation+///+/// # 2D vs 3D+///+/// In 2D, triangles are true polygons with edges that have normals. In 3D, triangles are+/// planar surfaces with a face normal (see the 3D version of this function).+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::shape::{Triangle, Ball};+/// use parry2d::query::sat::triangle_support_map_find_local_separating_normal_oneway;+/// use parry2d::math::{Vector, Pose};+///+/// let triangle = Triangle::new(+/// Vector::ZERO,+/// Vector::new(2.0, 0.0),+/// Vector::new(1.0, 2.0)+/// );+/// let sphere = Ball::new(0.5);+///+/// let pos12 = Pose::translation(3.0, 1.0);+///+/// let (separation, normal) = triangle_support_map_find_local_separating_normal_oneway(+/// &triangle,+/// &sphere,+/// &pos12+/// );+///+/// if separation > 0.0 {+/// println!("Separated by {} along edge normal {}", separation, normal);+/// }+/// # }+/// ```+#[cfg(feature = "dim2")]+pub fn triangle_support_map_find_local_separating_normal_oneway(+ triangle1: &Triangle,+ shape2: &impl SupportMap,+ pos12: &Pose,+) -> (Real, Vector) {+ let mut best_sep = -Real::MAX;+ let mut best_normal = Vector::ZERO;++ for edge in &triangle1.edges() {+ if let Some(normal) = edge.normal() {+ let sep = support_map_support_map_compute_separation(triangle1, shape2, pos12, normal);++ if sep > best_sep {+ best_sep = sep;+ best_normal = normal;+ }+ }+ }++ (best_sep, best_normal)+}++/// Finds the best separating axis by testing a triangle's normals against a cuboid (2D only).+///+/// This is a specialized version of [`triangle_support_map_find_local_separating_normal_oneway`]+/// for the specific case of a triangle and cuboid. In 2D, it tests the three edge normals of+/// the triangle.+///+/// # Parameters+///+/// - `triangle1`: The triangle whose edge normals will be tested+/// - `shape2`: The cuboid+/// - `pos12`: The position of the cuboid relative to the triangle+///+/// # Returns+///+/// A tuple containing the maximum separation and the corresponding edge normal direction.+///+/// See [`triangle_support_map_find_local_separating_normal_oneway`] for more details and examples.+#[cfg(feature = "dim2")]+pub fn triangle_cuboid_find_local_separating_normal_oneway(+ triangle1: &Triangle,+ shape2: &Cuboid,+ pos12: &Pose,+) -> (Real, Vector) {+ triangle_support_map_find_local_separating_normal_oneway(triangle1, shape2, pos12)+}++/// Finds the best separating axis by testing a triangle's face normal against a cuboid (3D only).+///+/// In 3D, a triangle is a planar surface with a single face normal (perpendicular to the plane).+/// This function tests both directions of this normal (+normal and -normal) to find the maximum+/// separation from the cuboid.+///+/// # How It Works+///+/// The function uses the triangle's face normal and one of its vertices (point A) to represent+/// the triangle as a point-with-normal. It then delegates to+/// [`point_cuboid_find_local_separating_normal_oneway`](super::point_cuboid_find_local_separating_normal_oneway)+/// which efficiently handles this case.+///+/// # Parameters+///+/// - `triangle1`: The triangle whose face normal will be tested+/// - `shape2`: The cuboid+/// - `pos12`: The position of the cuboid relative to the triangle+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The separation distance along the triangle's face normal+/// - **Positive**: Shapes are separated+/// - **Negative**: Shapes are overlapping+/// - `Vector`: The face normal direction (or its negation) that gives this separation+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Triangle, Cuboid};+/// use parry3d::query::sat::triangle_cuboid_find_local_separating_normal_oneway;+/// use parry3d::math::{Vector, Pose};+///+/// // Horizontal triangle in the XY plane+/// let triangle = Triangle::new(+/// Vector::ZERO,+/// Vector::new(2.0, 0.0, 0.0),+/// Vector::new(1.0, 2.0, 0.0)+/// );+/// let cube = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+///+/// // Position cube above the triangle+/// let pos12 = Pose::translation(1.0, 1.0, 2.0);+///+/// let (separation, normal) = triangle_cuboid_find_local_separating_normal_oneway(+/// &triangle,+/// &cube,+/// &pos12+/// );+///+/// println!("Separation along triangle normal: {}", separation);+/// # }+/// ```+///+/// # 2D vs 3D+///+/// - **2D version**: Tests three edge normals (one per triangle edge)+/// - **3D version** (this function): Tests one face normal (perpendicular to triangle plane)+#[cfg(feature = "dim3")]+#[inline(always)]+pub fn triangle_cuboid_find_local_separating_normal_oneway(+ triangle1: &Triangle,+ shape2: &Cuboid,+ pos12: &Pose,+) -> (Real, Vector) {+ sat::point_cuboid_find_local_separating_normal_oneway(+ triangle1.a,+ triangle1.normal(),+ shape2,+ pos12,+ )+}diff --git a/renderer/third_party/parry3d/src/query/sat/sat_support_map_support_map.rs b/renderer/third_party/parry3d/src/query/sat/sat_support_map_support_map.rsnew file mode 100644index 0000000..b1fcff8--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sat/sat_support_map_support_map.rs@@ -0,0 +1,88 @@+use crate::math::{Pose, Real, Vector};+use crate::shape::SupportMap;++/// Computes the separation distance between two convex shapes along a given direction.+///+/// This is the most general SAT separation computation function in Parry. It works with any+/// two convex shapes that implement the [`SupportMap`] trait, which includes spheres, capsules,+/// cones, convex polyhedra, and more.+///+/// # What is a Support Map?+///+/// A support map is a function that, given a direction vector, returns the furthest point on+/// the shape in that direction. This is a fundamental operation in collision detection algorithms+/// like GJK, EPA, and SAT.+///+/// # How This Function Works+///+/// 1. Finds the furthest point on `sm1` in direction `dir1` (the "support point")+/// 2. Finds the furthest point on `sm2` in direction `-dir1` (opposite direction)+/// 3. Transforms `sm2`'s support point to `sm1`'s coordinate space+/// 4. Computes the signed distance between these points along `dir1`+///+/// # Parameters+///+/// - `sm1`: The first convex shape+/// - `sm2`: The second convex shape+/// - `pos12`: The position of `sm2` relative to `sm1`+/// - `dir1`: The unit direction vector (in `sm1`'s local space) along which to compute separation+///+/// # Returns+///+/// The separation distance as a `Real`:+/// - **Positive**: The shapes are separated by at least this distance along `dir1`+/// - **Negative**: The shapes are overlapping (the absolute value is the penetration depth)+/// - **Zero**: The shapes are exactly touching along this axis+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Ball, Cuboid};+/// use parry3d::query::sat::support_map_support_map_compute_separation;+/// use parry3d::math::{Pose, Vector};+///+/// let sphere = Ball::new(1.0);+/// let cube = Cuboid::new(Vector::splat(1.0));+///+/// // Position cube to the right of the sphere+/// let pos12 = Pose::translation(3.0, 0.0, 0.0);+///+/// // Test separation along the X axis+/// let dir = Vector::X.normalize();+/// let separation = support_map_support_map_compute_separation(+/// &sphere,+/// &cube,+/// &pos12,+/// dir+/// );+///+/// // They should be separated (sphere radius 1.0 + cube extent 1.0 = 2.0, distance 3.0)+/// assert!(separation > 0.0);+/// # }+/// ```+///+/// # Use Cases+///+/// This function is typically used as a building block in SAT implementations. You would:+/// 1. Generate candidate separating axes (face normals, edge cross products, etc.)+/// 2. Call this function for each candidate axis+/// 3. Track the axis with maximum separation+/// 4. If the maximum separation is positive, the shapes don't collide+///+/// # Performance Note+///+/// This function is generic and works with any support map shapes, but specialized implementations+/// (like [`cuboid_cuboid_find_local_separating_normal_oneway`](super::cuboid_cuboid_find_local_separating_normal_oneway))+/// may be more efficient for specific shape pairs.+#[allow(dead_code)]+pub fn support_map_support_map_compute_separation(+ sm1: &impl SupportMap,+ sm2: &impl SupportMap,+ pos12: &Pose,+ dir1: Vector,+) -> Real {+ let p1 = sm1.local_support_point_toward(dir1);+ let p2 = sm2.support_point_toward(pos12, -dir1);+ (p2 - p1).dot(dir1)+}diff --git a/renderer/third_party/parry3d/src/query/sat/sat_triangle_segment.rs b/renderer/third_party/parry3d/src/query/sat/sat_triangle_segment.rsnew file mode 100644index 0000000..1e1b15f--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sat/sat_triangle_segment.rs@@ -0,0 +1,207 @@+use crate::math::{Pose, Real, Vector};+use crate::query::sat;+use crate::shape::{Segment, SupportMap, Triangle};++/// Finds the best separating axis by testing a triangle's face normal against a segment (3D only).+///+/// In 3D, a triangle has a face normal (perpendicular to its plane). This function tests both+/// directions of this normal (+normal and -normal) to find the maximum separation from the segment.+///+/// # How It Works+///+/// The function computes support points on the segment in both the positive and negative normal+/// directions, then measures which direction gives greater separation from the triangle's surface.+///+/// # Parameters+///+/// - `triangle1`: The triangle whose face normal will be tested+/// - `segment2`: The line segment+/// - `pos12`: The position of the segment relative to the triangle+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The separation distance along the triangle's face normal+/// - **Positive**: Shapes are separated+/// - **Negative**: Shapes are overlapping+/// - **Very negative** if the triangle has no normal (degenerate triangle)+/// - `Vector`: The face normal direction (or its negation) that gives this separation+///+/// # Degenerate Triangles+///+/// If the triangle is degenerate (all three points are collinear), it has no valid normal.+/// In this case, the function returns `-Real::MAX` for separation and a zero vector for the normal.+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Triangle, Segment};+/// use parry3d::query::sat::triangle_segment_find_local_separating_normal_oneway;+/// use parry3d::math::{Vector, Pose};+///+/// // Triangle in the XY plane+/// let triangle = Triangle::new(+/// Vector::ZERO,+/// Vector::new(2.0, 0.0, 0.0),+/// Vector::new(1.0, 2.0, 0.0)+/// );+///+/// // Vertical segment above the triangle+/// let segment = Segment::new(+/// Vector::new(1.0, 1.0, 1.0),+/// Vector::new(1.0, 1.0, 3.0)+/// );+///+/// let pos12 = Pose::identity();+///+/// let (separation, normal) = triangle_segment_find_local_separating_normal_oneway(+/// &triangle,+/// &segment,+/// &pos12+/// );+///+/// if separation > 0.0 {+/// println!("Separated by {} along triangle normal", separation);+/// }+/// # }+/// ```+///+/// # Usage in Complete SAT+///+/// For a complete triangle-segment collision test, you must also test:+/// 1. Triangle face normal (this function)+/// 2. Segment normal (in 2D) or edge-edge axes (in 3D)+/// 3. Edge-edge cross products (see [`segment_triangle_find_local_separating_edge_twoway`])+pub fn triangle_segment_find_local_separating_normal_oneway(+ triangle1: &Triangle,+ segment2: &Segment,+ pos12: &Pose,+) -> (Real, Vector) {+ if let Some(dir) = triangle1.normal() {+ let p2a = segment2.support_point_toward(pos12, -dir);+ let p2b = segment2.support_point_toward(pos12, dir);+ let sep_a = (p2a - triangle1.a).dot(dir);+ let sep_b = -(p2b - triangle1.a).dot(dir);++ if sep_a >= sep_b {+ (sep_a, dir)+ } else {+ (sep_b, -dir)+ }+ } else {+ (-Real::MAX, Vector::ZERO)+ }+}++/// Finds the best separating axis by testing edge-edge combinations between a segment and a triangle (3D only).+///+/// In 3D, when a line segment and triangle collide, the contact might occur along an axis+/// perpendicular to both the segment and one of the triangle's edges. This function tests all+/// such axes (cross products) to find the one with maximum separation.+///+/// # Parameters+///+/// - `segment1`: The line segment+/// - `triangle2`: The triangle+/// - `pos12`: The position of the triangle relative to the segment+///+/// # Returns+///+/// A tuple containing:+/// - `Real`: The maximum separation found across all edge-edge axes+/// - **Positive**: Shapes are separated+/// - **Negative**: Shapes are overlapping+/// - `Vector`: The axis direction that gives this separation+///+/// # The Axes Tested+///+/// The function computes cross products between:+/// - The segment's direction (B - A)+/// - Each of the 3 triangle edges (AB, BC, CA)+///+/// This gives 3 base axes. The function tests both each axis and its negation (6 total),+/// finding which gives the maximum separation.+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Segment, Triangle};+/// use parry3d::query::sat::segment_triangle_find_local_separating_edge_twoway;+/// use parry3d::math::{Vector, Pose};+///+/// let segment = Segment::new(+/// Vector::ZERO,+/// Vector::new(0.0, 0.0, 2.0)+/// );+///+/// let triangle = Triangle::new(+/// Vector::new(1.0, 0.0, 1.0),+/// Vector::new(3.0, 0.0, 1.0),+/// Vector::new(2.0, 2.0, 1.0)+/// );+///+/// let pos12 = Pose::identity();+///+/// let (separation, axis) = segment_triangle_find_local_separating_edge_twoway(+/// &segment,+/// &triangle,+/// &pos12+/// );+///+/// if separation > 0.0 {+/// println!("Separated by {} along edge-edge axis", separation);+/// }+/// # }+/// ```+///+/// # Implementation Details+///+/// - Axes with near-zero length (parallel edges) are skipped+/// - The function uses [`support_map_support_map_compute_separation`](super::support_map_support_map_compute_separation)+/// to compute the actual separation along each axis+/// - Both positive and negative directions are tested for each cross product+///+/// # Usage in Complete SAT+///+/// For a complete segment-triangle collision test, you must also test:+/// 1. Triangle face normal ([`triangle_segment_find_local_separating_normal_oneway`])+/// 2. Segment-specific axes (depends on whether the segment has associated normals)+/// 3. Edge-edge cross products (this function)+pub fn segment_triangle_find_local_separating_edge_twoway(+ segment1: &Segment,+ triangle2: &Triangle,+ pos12: &Pose,+) -> (Real, Vector) {+ let x2 = pos12.rotation * (triangle2.b - triangle2.a);+ let y2 = pos12.rotation * (triangle2.c - triangle2.b);+ let z2 = pos12.rotation * (triangle2.a - triangle2.c);+ let dir1 = segment1.scaled_direction();++ let crosses1 = [dir1.cross(x2), dir1.cross(y2), dir1.cross(z2)];+ let axes1 = [+ crosses1[0],+ crosses1[1],+ crosses1[2],+ -crosses1[0],+ -crosses1[1],+ -crosses1[2],+ ];+ let mut max_separation = -Real::MAX;+ let mut sep_dir = axes1[0];++ for axis1 in &axes1 {+ if let Some(axis1) = (*axis1).try_normalize() {+ let sep =+ sat::support_map_support_map_compute_separation(segment1, triangle2, pos12, axis1);++ if sep > max_separation {+ max_separation = sep;+ sep_dir = axis1;+ }+ }+ }++ (max_separation, sep_dir)+}diff --git a/renderer/third_party/parry3d/src/query/shape_cast/mod.rs b/renderer/third_party/parry3d/src/query/shape_cast/mod.rsnew file mode 100644index 0000000..4dad80a--- /dev/null+++ b/renderer/third_party/parry3d/src/query/shape_cast/mod.rs@@ -0,0 +1,28 @@+//! Implementation details of the `cast_shapes` function.++pub use self::shape_cast::{cast_shapes, ShapeCastHit, ShapeCastOptions, ShapeCastStatus};+pub use self::shape_cast_ball_ball::cast_shapes_ball_ball;+pub use self::shape_cast_halfspace_support_map::{+ cast_shapes_halfspace_support_map, cast_shapes_support_map_halfspace,+};+#[cfg(feature = "alloc")]+pub use self::{+ shape_cast_composite_shape_shape::{+ cast_shapes_composite_shape_shape, cast_shapes_shape_composite_shape,+ },+ shape_cast_heightfield_shape::{cast_shapes_heightfield_shape, cast_shapes_shape_heightfield},+ shape_cast_support_map_support_map::cast_shapes_support_map_support_map,+ shape_cast_voxels_shape::{cast_shapes_shape_voxels, cast_shapes_voxels_shape},+};++mod shape_cast;+mod shape_cast_ball_ball;+#[cfg(feature = "alloc")]+mod shape_cast_composite_shape_shape;+mod shape_cast_halfspace_support_map;+#[cfg(feature = "alloc")]+mod shape_cast_heightfield_shape;+#[cfg(feature = "alloc")]+mod shape_cast_support_map_support_map;+#[cfg(feature = "alloc")]+mod shape_cast_voxels_shape;diff --git a/renderer/third_party/parry3d/src/query/shape_cast/shape_cast.rs b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast.rsnew file mode 100644index 0000000..4d2b9d9--- /dev/null+++ b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast.rs@@ -0,0 +1,310 @@+use crate::math::{Pose, Real, Vector};+use crate::query::{DefaultQueryDispatcher, QueryDispatcher, Unsupported};+use crate::shape::{Shape, SubShapeId};++#[cfg(feature = "alloc")]+use crate::partitioning::BvhLeafCost;++/// The status of the time-of-impact computation algorithm.+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub enum ShapeCastStatus {+ /// The shape-casting algorithm ran out of iterations before achieving convergence.+ ///+ /// The content of the `ShapeCastHit` will still be a conservative approximation of the actual result so+ /// it is often fine to interpret this case as a success.+ OutOfIterations,+ /// The shape-casting algorithm converged successfully.+ Converged,+ /// Something went wrong during the shape-casting, likely due to numerical instabilities.+ ///+ /// The content of the `ShapeCastHit` will still be a conservative approximation of the actual result so+ /// it is often fine to interpret this case as a success.+ Failed,+ /// The two shape already overlap, or are separated by a distance smaller than+ /// [`ShapeCastOptions::target_distance`] at the time 0.+ ///+ /// The witness points and normals provided by the `ShapeCastHit` will have unreliable values unless+ /// [`ShapeCastOptions::compute_impact_geometry_on_penetration`] was set to `true` when calling+ /// the time-of-impact function.+ PenetratingOrWithinTargetDist,+}++/// The result of a shape casting.+///+/// # Frame conventions+///+/// The `witness1`/`normal1` (resp. `witness2`/`normal2`) fields are expressed in the frame the+/// first (resp. second) shape was described in when performing the query:+/// - For shape-local queries like [`cast_shapes`] or [`QueryDispatcher::cast_shapes`], this is+/// the local frame of the corresponding shape.+/// - For queries where a shape is a composite with its parts posed in another frame (e.g.+/// casting a shape on Rapier's `QueryPipeline`, where the colliders hit are posed in world+/// space), the corresponding fields are expressed in that frame (e.g. world space).+#[derive(Copy, Clone, Debug)]+pub struct ShapeCastHit {+ /// The time at which the objects touch.+ pub time_of_impact: Real,+ /// The closest point on the first shape at the time of impact, expressed in the frame of+ /// the query (see the [frame conventions](ShapeCastHit#frame-conventions)).+ ///+ /// This value is unreliable if `status` is [`ShapeCastStatus::PenetratingOrWithinTargetDist`]+ /// and [`ShapeCastOptions::compute_impact_geometry_on_penetration`] was set to `false`.+ pub witness1: Vector,+ /// The closest point on the second shape at the time of impact, expressed in the frame of+ /// the query (see the [frame conventions](ShapeCastHit#frame-conventions)).+ ///+ /// This value is unreliable if `status` is [`ShapeCastStatus::PenetratingOrWithinTargetDist`]+ /// and both [`ShapeCastOptions::compute_impact_geometry_on_penetration`] was set to `false`+ /// when calling the time-of-impact function.+ pub witness2: Vector,+ /// The outward normal on the first shape at the time of impact, expressed in the frame of+ /// the query (see the [frame conventions](ShapeCastHit#frame-conventions)).+ ///+ /// This value is unreliable if `status` is [`ShapeCastStatus::PenetratingOrWithinTargetDist`]+ /// and both [`ShapeCastOptions::compute_impact_geometry_on_penetration`] was set to `false`+ /// when calling the time-of-impact function.+ pub normal1: Vector,+ /// The outward normal on the second shape at the time of impact, expressed in the frame of+ /// the query (see the [frame conventions](ShapeCastHit#frame-conventions)).+ ///+ /// This value is unreliable if `status` is [`ShapeCastStatus::PenetratingOrWithinTargetDist`]+ /// and both [`ShapeCastOptions::compute_impact_geometry_on_penetration`] was set to `false`+ /// when calling the time-of-impact function.+ pub normal2: Vector,+ /// The way the shape-casting algorithm terminated.+ pub status: ShapeCastStatus,+ /// The sub-shape of the first shape that was hit.+ ///+ /// Always `0` for a shape with no sub-shapes.+ pub subshape1: SubShapeId,+ /// The sub-shape of the second shape that was hit.+ ///+ /// Always `0` for a shape with no sub-shapes.+ pub subshape2: SubShapeId,+}++impl ShapeCastHit {+ /// Swaps every data of this shape-casting result such that the role of both shapes are swapped.+ ///+ /// In practice, this makes it so that `self.witness1` and `self.normal1` are swapped with+ /// `self.witness2` and `self.normal2`.+ pub fn swapped(self) -> Self {+ Self {+ time_of_impact: self.time_of_impact,+ witness1: self.witness2,+ witness2: self.witness1,+ normal1: self.normal2,+ normal2: self.normal1,+ status: self.status,+ subshape1: self.subshape2,+ subshape2: self.subshape1,+ }+ }++ /// Transform `self.witness1` and `self.normal1` by `pos`.+ pub fn transform1_by(&self, pos: &Pose) -> Self {+ Self {+ time_of_impact: self.time_of_impact,+ witness1: pos * self.witness1,+ witness2: self.witness2,+ normal1: pos.rotation * self.normal1,+ normal2: self.normal2,+ status: self.status,+ subshape1: self.subshape1,+ subshape2: self.subshape2,+ }+ }+}++#[cfg(feature = "alloc")]+impl BvhLeafCost for ShapeCastHit {+ #[inline]+ fn cost(&self) -> Real {+ self.time_of_impact+ }+}++/// Configuration for controlling the behavior of time-of-impact (i.e. shape-casting) calculations.+#[derive(Copy, Clone, Debug, PartialEq)]+pub struct ShapeCastOptions {+ /// The maximum time-of-impacts that can be computed.+ ///+ /// Any impact occurring after this time will be ignored.+ pub max_time_of_impact: Real,+ /// The shapes will be considered as impacting as soon as their distance is smaller or+ /// equal to this target distance. Must be positive or zero.+ ///+ /// If the shapes are separated by a distance smaller than `target_distance` at time 0, the+ /// calculated witness points and normals are only reliable if+ /// [`Self::compute_impact_geometry_on_penetration`] is set to `true`.+ pub target_distance: Real,+ /// If `false`, the time-of-impact algorithm will automatically discard any impact at time+ /// 0 where the velocity is separating (i.e., the relative velocity is such that the distance+ /// between the objects projected on the impact normal is increasing through time).+ pub stop_at_penetration: bool,+ /// If `true`, witness points and normals will be calculated even when the time-of-impact is 0.+ pub compute_impact_geometry_on_penetration: bool,+}++impl ShapeCastOptions {+ // Constructor for the most common use-case.+ /// Crates a [`ShapeCastOptions`] with the default values except for the maximum time of impact.+ pub fn with_max_time_of_impact(max_time_of_impact: Real) -> Self {+ Self {+ max_time_of_impact,+ ..Default::default()+ }+ }+}++impl Default for ShapeCastOptions {+ fn default() -> Self {+ Self {+ max_time_of_impact: Real::MAX,+ target_distance: 0.0,+ stop_at_penetration: true,+ compute_impact_geometry_on_penetration: true,+ }+ }+}++/// Computes when two moving shapes will collide (shape casting / swept collision detection).+///+/// This function determines the **time of impact** when two shapes moving with constant+/// linear velocities will first touch. This is essential for **continuous collision detection**+/// (CCD) to prevent fast-moving objects from tunneling through each other.+///+/// # What is Shape Casting?+///+/// Shape casting extends ray casting to arbitrary shapes:+/// - **Ray casting**: Vector moving in a direction (infinitely thin)+/// - **Shape casting**: Full shape moving in a direction (has volume)+///+/// The shapes move linearly (no rotation) from their initial positions along their+/// velocities until they touch or the time limit is reached.+///+/// # Behavior+///+/// - **Will collide**: Returns `Some(hit)` with time of first impact+/// - **Already touching**: Returns `Some(hit)` with `time_of_impact = 0.0`+/// - **Won't collide**: Returns `None` (no impact within time range)+/// - **Moving apart**: May return `None` depending on `stop_at_penetration` option+///+/// # Arguments+///+/// * `pos1` - Initial position and orientation of the first shape+/// * `vel1` - Linear velocity of the first shape (units per time)+/// * `g1` - The first shape+/// * `pos2` - Initial position and orientation of the second shape+/// * `vel2` - Linear velocity of the second shape+/// * `g2` - The second shape+/// * `options` - Configuration options (max time, target distance, etc.)+///+/// # Options+///+/// Configure behavior with [`ShapeCastOptions`]:+/// - `max_time_of_impact`: Maximum time to check (ignore later impacts)+/// - `target_distance`: Consider "close enough" when within this distance+/// - `stop_at_penetration`: Stop if initially penetrating and moving apart+/// - `compute_impact_geometry_on_penetration`: Compute reliable witnesses at t=0+///+/// # Returns+///+/// * `Ok(Some(hit))` - Impact found, see [`ShapeCastHit`] for details+/// * `Ok(None)` - No impact within time range+/// * `Err(Unsupported)` - This shape pair is not supported+///+/// # Example: Basic Shape Casting+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{cast_shapes, ShapeCastOptions};+/// use parry3d::shape::Ball;+/// use parry3d::math::{Pose, Vector};+///+/// let ball1 = Ball::new(1.0);+/// let ball2 = Ball::new(1.0);+///+/// // Ball 1 at origin, moving right at speed 2.0+/// let pos1 = Pose::translation(0.0, 0.0, 0.0);+/// let vel1 = Vector::new(2.0, 0.0, 0.0);+///+/// // Ball 2 at x=10, stationary+/// let pos2 = Pose::translation(10.0, 0.0, 0.0);+/// let vel2 = Vector::ZERO;+///+/// let options = ShapeCastOptions::default();+///+/// if let Ok(Some(hit)) = cast_shapes(&pos1, vel1, &ball1, &pos2, vel2, &ball2, options) {+/// // Time when surfaces touch+/// // Distance to cover: 10.0 - 1.0 (radius) - 1.0 (radius) = 8.0+/// // Speed: 2.0, so time = 8.0 / 2.0 = 4.0+/// assert_eq!(hit.time_of_impact, 4.0);+///+/// // Position at impact+/// let impact_pos1 = pos1.translation + vel1 * hit.time_of_impact;+/// // Ball 1 moved 8 units to x=8.0, touching ball 2 at x=10.0+/// }+/// # }+/// ```+///+/// # Example: Already Penetrating+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::query::{cast_shapes, ShapeCastOptions, ShapeCastStatus};+/// use parry3d::shape::Ball;+/// use parry3d::math::{Pose, Vector};+///+/// let ball1 = Ball::new(2.0);+/// let ball2 = Ball::new(2.0);+///+/// // Overlapping balls (centers 3 units apart, radii sum to 4)+/// let pos1 = Pose::translation(0.0, 0.0, 0.0);+/// let pos2 = Pose::translation(3.0, 0.0, 0.0);+/// let vel1 = Vector::X;+/// let vel2 = Vector::ZERO;+///+/// let options = ShapeCastOptions::default();+///+/// if let Ok(Some(hit)) = cast_shapes(&pos1, vel1, &ball1, &pos2, vel2, &ball2, options) {+/// // Already penetrating+/// assert_eq!(hit.time_of_impact, 0.0);+/// assert_eq!(hit.status, ShapeCastStatus::PenetratingOrWithinTargetDist);+/// }+/// # }+/// ```+///+/// # Use Cases+///+/// - **Continuous collision detection**: Prevent tunneling at high speeds+/// - **Predictive collision**: Know when collision will occur+/// - **Sweep tests**: Moving platforms, sliding objects+/// - **Bullet physics**: Fast projectiles that need CCD+///+/// # Performance+///+/// Shape casting is more expensive than static queries:+/// - Uses iterative root-finding algorithms+/// - Multiple distance/contact queries per iteration+/// - Complexity depends on shape types and relative velocities+///+/// # See Also+///+/// - [`cast_shapes_nonlinear`](crate::query::cast_shapes_nonlinear()) - For rotating shapes+/// - [`Ray::cast_ray`](crate::query::RayCast::cast_ray) - For point-like casts+/// - [`ShapeCastOptions`] - Configuration options+/// - [`ShapeCastHit`] - Result structure+pub fn cast_shapes(+ pos1: &Pose,+ vel1: Vector,+ g1: &dyn Shape,+ pos2: &Pose,+ vel2: Vector,+ g2: &dyn Shape,+ options: ShapeCastOptions,+) -> Result<Option<ShapeCastHit>, Unsupported> {+ let pos12 = pos1.inv_mul(pos2);+ let vel12 = pos1.rotation.inverse() * (vel2 - vel1);+ DefaultQueryDispatcher.cast_shapes(&pos12, vel12, g1, g2, options)+}diff --git a/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_ball_ball.rs b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_ball_ball.rsnew file mode 100644index 0000000..47ab0eb--- /dev/null+++ b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_ball_ball.rs@@ -0,0 +1,69 @@+use crate::math::{Pose, Vector};+use crate::query::details::ShapeCastOptions;+use crate::query::{self, Ray, ShapeCastHit, ShapeCastStatus};+use crate::shape::Ball;+use num::Zero;++/// Time Of Impact of two balls under translational movement.+#[inline]+pub fn cast_shapes_ball_ball(+ pos12: &Pose,+ vel12: Vector,+ b1: &Ball,+ b2: &Ball,+ options: ShapeCastOptions,+) -> Option<ShapeCastHit> {+ let rsum = b1.radius + b2.radius + options.target_distance;+ let radius = rsum;+ let center = -pos12.translation;+ let ray = Ray::new(Vector::ZERO, vel12);++ if let (inside, Some(time_of_impact)) =+ query::details::ray_toi_with_ball(center, radius, &ray, true)+ {+ if time_of_impact > options.max_time_of_impact {+ return None;+ }++ let dpt = ray.point_at(time_of_impact) - center;+ let normal1;+ let normal2;+ let witness1;+ let witness2;++ if radius.is_zero() {+ normal1 = Vector::X;+ normal2 = pos12.rotation.inverse() * -Vector::X;+ witness1 = Vector::ZERO;+ witness2 = Vector::ZERO;+ } else {+ normal1 = dpt / radius;+ normal2 = pos12.rotation.inverse() * -normal1;+ witness1 = normal1 * b1.radius;+ witness2 = normal2 * b2.radius;+ }++ if !options.stop_at_penetration && time_of_impact < 1.0e-4 && normal1.dot(vel12) >= 0.0 {+ return None;+ }++ let status = if inside && center.length_squared() < rsum * rsum {+ ShapeCastStatus::PenetratingOrWithinTargetDist+ } else {+ ShapeCastStatus::Converged+ };++ Some(ShapeCastHit {+ time_of_impact,+ normal1,+ normal2,+ witness1,+ witness2,+ status,+ subshape1: 0,+ subshape2: 0,+ })+ } else {+ None+ }+}diff --git a/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_composite_shape_shape.rs b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_composite_shape_shape.rsnew file mode 100644index 0000000..b5cc7ad--- /dev/null+++ b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_composite_shape_shape.rs@@ -0,0 +1,109 @@+use crate::bounding_volume::Aabb;+use crate::math::{Pose, Real, Vector};+use crate::partitioning::BvhNode;+use crate::query::shape_cast::ShapeCastOptions;+use crate::query::{QueryDispatcher, Ray, RayCast, ShapeCastHit};+use crate::shape::{CompositeShapeRef, Shape, SubShapeId, TypedCompositeShape};++impl<S: ?Sized + TypedCompositeShape> CompositeShapeRef<'_, S> {+ /// Performs a shape-cast between `self` and a `shape2` positioned at `pose12` and subject to+ /// a linear velocity `vel12`, relative to `self`.+ ///+ /// Returns the index of the sub-shape of `self` that was involved alongside the hit, which is+ /// left as that sub-shape reported it (its `subshape1` is the sub-shape's own when it is a+ /// composite too, and `subshape2` is `g2`'s).+ pub fn cast_shape<D: ?Sized + QueryDispatcher>(+ &self,+ dispatcher: &D,+ pose12: &Pose,+ vel12: Vector,+ g2: &dyn Shape,+ options: ShapeCastOptions,+ ) -> Option<(SubShapeId, ShapeCastHit)> {+ let ls_aabb2 = g2.compute_aabb(pose12);+ let ray = Ray::new(Vector::ZERO, vel12);+ let msum_shift = -ls_aabb2.center();+ let msum_margin = ls_aabb2.half_extents() + Vector::splat(options.target_distance);++ self.0.bvh().find_best(+ options.max_time_of_impact,+ |node: &BvhNode, best_so_far| {+ // Compute the minkowski sum of the two Aabbs.+ let msum = Aabb {+ mins: node.mins() + msum_shift - msum_margin,+ maxs: node.maxs() + msum_shift + msum_margin,+ };++ // Compute the time of impact.+ msum.cast_local_ray(&ray, best_so_far, true)+ .unwrap_or(Real::MAX)+ },+ |part_id, _| {+ self.0+ .map_untyped_part_at(part_id, |part_pose1, part_g1, _| {+ if let Some(part_pose1) = part_pose1 {+ dispatcher+ .cast_shapes(+ &part_pose1.inv_mul(pose12),+ part_pose1.rotation.inverse() * vel12,+ part_g1,+ g2,+ options,+ )+ .ok()?+ .map(|hit| hit.transform1_by(part_pose1))+ } else {+ dispatcher+ .cast_shapes(pose12, vel12, part_g1, g2, options)+ .ok()?+ }+ })?+ },+ )+ }+}++/// Time Of Impact of a composite shape with any other shape, under translational movement.+pub fn cast_shapes_composite_shape_shape<D, G1>(+ dispatcher: &D,+ pos12: &Pose,+ vel12: Vector,+ g1: &G1,+ g2: &dyn Shape,+ options: ShapeCastOptions,+) -> Option<ShapeCastHit>+where+ D: ?Sized + QueryDispatcher,+ G1: ?Sized + TypedCompositeShape,+{+ CompositeShapeRef(g1)+ .cast_shape(dispatcher, pos12, vel12, g2, options)+ .map(|(part_id, mut hit)| {+ hit.subshape1 = part_id;+ hit+ })+}++/// Time Of Impact of any shape with a composite shape, under translational movement.+pub fn cast_shapes_shape_composite_shape<D, G2>(+ dispatcher: &D,+ pos12: &Pose,+ vel12: Vector,+ g1: &dyn Shape,+ g2: &G2,+ options: ShapeCastOptions,+) -> Option<ShapeCastHit>+where+ D: ?Sized + QueryDispatcher,+ G2: ?Sized + TypedCompositeShape,+{+ cast_shapes_composite_shape_shape(+ dispatcher,+ &pos12.inverse(),+ -(pos12.rotation.inverse() * vel12),+ g2,+ g1,+ options,+ )+ .map(|time_of_impact| time_of_impact.swapped())+}diff --git a/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_halfspace_support_map.rs b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_halfspace_support_map.rsnew file mode 100644index 0000000..1317c1d--- /dev/null+++ b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_halfspace_support_map.rs@@ -0,0 +1,80 @@+use crate::math::{Pose, Vector};+use crate::query::details::ShapeCastOptions;+use crate::query::{Ray, RayCast, ShapeCastHit, ShapeCastStatus};+use crate::shape::{HalfSpace, RoundShapeRef, SupportMap};++/// Time Of Impact of a halfspace with a support-mapped shape under translational movement.+pub fn cast_shapes_halfspace_support_map<G: ?Sized + SupportMap>(+ pos12: &Pose,+ vel12: Vector,+ halfspace: &HalfSpace,+ other: &G,+ options: ShapeCastOptions,+) -> Option<ShapeCastHit> {+ // TODO: add method to get only the local support point.+ // This would avoid the `inverse_transform_point` later.+ if !options.stop_at_penetration && vel12.dot(halfspace.normal) > 0.0 {+ return None;+ }++ let support_point = if options.target_distance > 0.0 {+ let round_other = RoundShapeRef {+ inner_shape: other,+ border_radius: options.target_distance,+ };+ round_other.support_point(pos12, -halfspace.normal)+ } else {+ other.support_point(pos12, -halfspace.normal)+ };+ let closest_point = support_point;+ let ray = Ray::new(closest_point, vel12);++ if let Some(time_of_impact) = halfspace.cast_local_ray(&ray, options.max_time_of_impact, true) {+ if time_of_impact > options.max_time_of_impact {+ return None;+ }++ let witness2 = support_point + halfspace.normal * options.target_distance;+ let mut witness1 = ray.point_at(time_of_impact);+ // Project the witness point to the halfspace.+ // Note that witness1 is already in the halfspace's local-space.+ witness1 -= halfspace.normal * witness1.dot(halfspace.normal);++ let status = if support_point.dot(halfspace.normal) < 0.0 {+ ShapeCastStatus::PenetratingOrWithinTargetDist+ } else {+ ShapeCastStatus::Converged+ };++ Some(ShapeCastHit {+ time_of_impact,+ normal1: halfspace.normal,+ normal2: pos12.rotation.inverse() * -halfspace.normal,+ witness1,+ witness2: pos12.inverse_transform_point(witness2),+ status,+ subshape1: 0,+ subshape2: 0,+ })+ } else {+ None+ }+}++/// Time Of Impact of a halfspace with a support-mapped shape under translational movement.+pub fn cast_shapes_support_map_halfspace<G: ?Sized + SupportMap>(+ pos12: &Pose,+ vel12: Vector,+ other: &G,+ halfspace: &HalfSpace,+ options: ShapeCastOptions,+) -> Option<ShapeCastHit> {+ cast_shapes_halfspace_support_map(+ &pos12.inverse(),+ -(pos12.rotation.inverse() * vel12),+ halfspace,+ other,+ options,+ )+ .map(|hit| hit.swapped())+}diff --git a/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_heightfield_shape.rs b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_heightfield_shape.rsnew file mode 100644index 0000000..8318203--- /dev/null+++ b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_heightfield_shape.rs@@ -0,0 +1,277 @@+use crate::bounding_volume::BoundingVolume;+use crate::math::{Pose, Real, Vector};+use crate::query::details::ShapeCastOptions;+use crate::query::{QueryDispatcher, Ray, ShapeCastHit, Unsupported};+use crate::shape::{HeightField, Shape};+#[cfg(feature = "dim3")]+use crate::{bounding_volume::Aabb, query::RayCast};++/// Time Of Impact between a moving shape and a heightfield.+#[cfg(feature = "dim2")]+pub fn cast_shapes_heightfield_shape<D: ?Sized + QueryDispatcher>(+ dispatcher: &D,+ pos12: &Pose,+ vel12: Vector,+ heightfield1: &HeightField,+ g2: &dyn Shape,+ options: ShapeCastOptions,+) -> Result<Option<ShapeCastHit>, Unsupported> {+ let aabb2_1 = g2.compute_aabb(pos12).loosened(options.target_distance);+ let ray = Ray::new(aabb2_1.center(), vel12);++ let mut curr_range = heightfield1.unclamped_elements_range_in_local_aabb(&aabb2_1);+ // Enlarge the range by 1 to account for movement within a cell.+ let right = ray.dir.x > 0.0;++ if right {+ curr_range.end += 1;+ } else {+ curr_range.start -= 1;+ }++ let mut best_hit = None::<ShapeCastHit>;++ /*+ * Test the segment under the ray.+ */+ let clamped_curr_range = curr_range.start.clamp(0, heightfield1.num_cells() as isize) as usize+ ..curr_range.end.clamp(0, heightfield1.num_cells() as isize) as usize;+ for curr in clamped_curr_range {+ if let Some(seg) = heightfield1.segment_at(curr) {+ // TODO: pre-check using a ray-cast on the Aabbs first?+ if let Some(hit) = dispatcher.cast_shapes(pos12, vel12, &seg, g2, options)? {+ if hit.time_of_impact < best_hit.map(|h| h.time_of_impact).unwrap_or(Real::MAX) {+ best_hit = Some(hit);+ }+ }+ }+ }++ /*+ * Test other segments in the path of the ray.+ */+ if ray.dir.x == 0.0 {+ return Ok(best_hit);+ }++ let cell_width = heightfield1.cell_width();+ let start_x = heightfield1.start_x();++ let mut curr_elt = if right {+ (curr_range.end - 1).max(0)+ } else {+ curr_range.start.min(heightfield1.num_cells() as isize - 1)+ };++ while (right && curr_elt < heightfield1.num_cells() as isize - 1) || (!right && curr_elt > 0) {+ let curr_param;++ if right {+ curr_elt += 1;+ curr_param = (cell_width * (curr_elt as Real) + start_x - ray.origin.x) / ray.dir.x;+ } else {+ curr_param = (ray.origin.x - cell_width * (curr_elt as Real) - start_x) / ray.dir.x;+ curr_elt -= 1;+ }++ if curr_param >= options.max_time_of_impact {+ break;+ }++ if let Some(seg) = heightfield1.segment_at(curr_elt as usize) {+ // TODO: pre-check using a ray-cast on the Aabbs first?+ if let Some(hit) = dispatcher.cast_shapes(pos12, vel12, &seg, g2, options)? {+ if hit.time_of_impact < best_hit.map(|h| h.time_of_impact).unwrap_or(Real::MAX) {+ best_hit = Some(hit);+ }+ }+ }+ }++ Ok(best_hit)+}++/// Time Of Impact between a moving shape and a heightfield.+#[cfg(feature = "dim3")]+pub fn cast_shapes_heightfield_shape<D: ?Sized + QueryDispatcher>(+ dispatcher: &D,+ pos12: &Pose,+ vel12: Vector,+ heightfield1: &HeightField,+ g2: &dyn Shape,+ options: ShapeCastOptions,+) -> Result<Option<ShapeCastHit>, Unsupported> {+ let aabb1 = heightfield1.local_aabb();+ let mut aabb2_1 = g2.compute_aabb(pos12).loosened(options.target_distance);+ let ray = Ray::new(aabb2_1.center(), vel12);++ // Find the first hit between the aabbs.+ let hext2_1 = aabb2_1.half_extents();+ let msum = Aabb::new(aabb1.mins - hext2_1, aabb1.maxs + hext2_1);+ if let Some(time_of_impact) = msum.cast_local_ray(&ray, options.max_time_of_impact, true) {+ // Advance the aabb2 to the hit point.+ aabb2_1.mins += ray.dir * time_of_impact;+ aabb2_1.maxs += ray.dir * time_of_impact;+ } else {+ return Ok(None);+ }++ let (mut curr_range_i, mut curr_range_j) =+ heightfield1.unclamped_elements_range_in_local_aabb(&aabb2_1);+ let (ncells_i, ncells_j) = heightfield1.num_cells_ij();+ let mut best_hit = None::<ShapeCastHit>;++ /*+ * Enlarge the ranges by 1 to account for any movement within one cell.+ */+ if ray.dir.z > 0.0 {+ curr_range_i.end += 1;+ } else if ray.dir.z < 0.0 {+ curr_range_i.start -= 1;+ }++ if ray.dir.x > 0.0 {+ curr_range_j.end += 1;+ } else if ray.dir.x < 0.0 {+ curr_range_j.start -= 1;+ }++ /*+ * Test the segment under the ray.+ */+ let clamped_curr_range_i = curr_range_i.start.clamp(0, ncells_i as isize)+ ..curr_range_i.end.clamp(0, ncells_i as isize);+ let clamped_curr_range_j = curr_range_j.start.clamp(0, ncells_j as isize)+ ..curr_range_j.end.clamp(0, ncells_j as isize);++ let mut hit_triangles = |i, j| {+ if i >= 0 && j >= 0 {+ let (tri_a, tri_b) = heightfield1.triangles_at(i as usize, j as usize);+ for tri in [tri_a, tri_b].into_iter().flatten() {+ // TODO: pre-check using a ray-cast on the Aabbs first?+ if let Some(hit) = dispatcher.cast_shapes(pos12, vel12, &tri, g2, options)? {+ if hit.time_of_impact < best_hit.map(|h| h.time_of_impact).unwrap_or(Real::MAX)+ {+ best_hit = Some(hit);+ }+ }+ }+ }++ Ok(())+ };++ for i in clamped_curr_range_i {+ for j in clamped_curr_range_j.clone() {+ hit_triangles(i, j)?;+ }+ }++ if ray.dir.y == 0.0 {+ return Ok(best_hit);+ }++ let mut cell = heightfield1.unclamped_cell_at_point(aabb2_1.center());++ loop {+ let prev_cell = cell;++ /*+ * Find the next cell to cast the ray on.+ */+ let toi_x = if ray.dir.x > 0.0 {+ let x = heightfield1.signed_x_at(cell.1 + 1);+ (x - ray.origin.x) / ray.dir.x+ } else if ray.dir.x < 0.0 {+ let x = heightfield1.signed_x_at(cell.1);+ (x - ray.origin.x) / ray.dir.x+ } else {+ Real::MAX+ };++ let toi_z = if ray.dir.z > 0.0 {+ let z = heightfield1.signed_z_at(cell.0 + 1);+ (z - ray.origin.z) / ray.dir.z+ } else if ray.dir.z < 0.0 {+ let z = heightfield1.signed_z_at(cell.0);+ (z - ray.origin.z) / ray.dir.z+ } else {+ Real::MAX+ };++ if toi_x > options.max_time_of_impact && toi_z > options.max_time_of_impact {+ break;+ }++ if toi_x >= 0.0 && toi_x <= toi_z {+ cell.1 += ray.dir.x.signum() as isize;+ }++ if toi_z >= 0.0 && toi_z <= toi_x {+ cell.0 += ray.dir.z.signum() as isize;+ }++ if cell == prev_cell {+ break;+ }++ let cell_diff = (cell.0 - prev_cell.0, cell.1 - prev_cell.1);+ curr_range_i.start += cell_diff.0;+ curr_range_i.end += cell_diff.0;+ curr_range_j.start += cell_diff.1;+ curr_range_j.end += cell_diff.1;++ let new_line_i = if cell_diff.0 > 0 {+ curr_range_i.end+ } else {+ curr_range_i.start+ };++ let new_line_j = if cell_diff.1 > 0 {+ curr_range_j.end+ } else {+ curr_range_j.start+ };++ let ignore_line_i = new_line_i < 0 || new_line_i >= ncells_i as isize;+ let ignore_line_j = new_line_j < 0 || new_line_j >= ncells_j as isize;++ if ignore_line_i && ignore_line_j {+ break;+ }++ if !ignore_line_i && cell_diff.0 != 0 {+ for j in curr_range_j.clone() {+ hit_triangles(new_line_i, j)?;+ }+ }++ if !ignore_line_j && cell_diff.1 != 0 {+ for i in curr_range_i.clone() {+ hit_triangles(i, new_line_j)?;+ }+ }+ }++ Ok(best_hit)+}++/// Time Of Impact between a moving shape and a heightfield.+pub fn cast_shapes_shape_heightfield<D: ?Sized + QueryDispatcher>(+ dispatcher: &D,+ pos12: &Pose,+ vel12: Vector,+ g1: &dyn Shape,+ heightfield2: &HeightField,+ options: ShapeCastOptions,+) -> Result<Option<ShapeCastHit>, Unsupported> {+ Ok(cast_shapes_heightfield_shape(+ dispatcher,+ &pos12.inverse(),+ -(pos12.rotation.inverse() * vel12),+ heightfield2,+ g1,+ options,+ )?+ .map(|hit| hit.swapped()))+}diff --git a/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_support_map_support_map.rs b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_support_map_support_map.rsnew file mode 100644index 0000000..9b16f0e--- /dev/null+++ b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_support_map_support_map.rs@@ -0,0 +1,90 @@+use crate::math::{Pose, Real, Vector};+use crate::query::details;+use crate::query::details::ShapeCastOptions;+use crate::query::gjk::{self, VoronoiSimplex};+use crate::query::{ShapeCastHit, ShapeCastStatus};+use crate::shape::{RoundShapeRef, SupportMap};+use num::Zero;++/// Time of impacts between two support-mapped shapes under translational movement.+pub fn cast_shapes_support_map_support_map<G1, G2>(+ pos12: &Pose,+ vel12: Vector,+ g1: &G1,+ g2: &G2,+ options: ShapeCastOptions,+) -> Option<ShapeCastHit>+where+ G1: ?Sized + SupportMap,+ G2: ?Sized + SupportMap,+{+ let gjk_result = if options.target_distance > 0.0 {+ let round_g1 = RoundShapeRef {+ inner_shape: g1,+ border_radius: options.target_distance,+ };+ gjk::directional_distance(pos12, &round_g1, g2, vel12, &mut VoronoiSimplex::new())+ } else {+ gjk::directional_distance(pos12, g1, g2, vel12, &mut VoronoiSimplex::new())+ };++ gjk_result.and_then(|(time_of_impact, normal1, witness1, witness2)| {+ if time_of_impact > options.max_time_of_impact {+ None+ } else if (options.compute_impact_geometry_on_penetration || !options.stop_at_penetration)+ && time_of_impact < 1.0e-4+ {+ // The GJK-derived normal becomes unreliable for very small TOIs — typically+ // when the cast starts at (or very close to) the `target_distance` boundary+ // with a direction nearly tangent to the contact. Fall back on the contact+ // query, which gives a robust closest-point normal and lets us detect the+ // case where the cast direction is actually moving away from the contact.+ let contact = details::contact_support_map_support_map(pos12, g1, g2, Real::MAX)?;+ let normal_vel = contact.normal1.dot(vel12);++ if !options.stop_at_penetration && normal_vel >= 0.0 {+ None+ } else {+ Some(ShapeCastHit {+ time_of_impact,+ normal1: contact.normal1,+ normal2: contact.normal2,+ witness1: contact.point1,+ witness2: contact.point2,+ // A cast starting exactly touching, neither penetrating nor within+ // the target distance, converged like ball-ball does.+ status: if contact.dist < options.target_distance {+ ShapeCastStatus::PenetratingOrWithinTargetDist+ } else {+ ShapeCastStatus::Converged+ },+ subshape1: 0,+ subshape2: 0,+ })+ }+ } else {+ Some(ShapeCastHit {+ time_of_impact,+ normal1,+ normal2: pos12.rotation.inverse() * -normal1,+ witness1: witness1 - normal1 * options.target_distance,+ witness2: pos12.inverse_transform_point(witness2),+ status: if time_of_impact.is_zero() {+ // A zero TOI means either a real penetration (or a start within the+ // target distance) or a mere touching contact; only the former is+ // `PenetratingOrWithinTargetDist`, as for ball-ball.+ match details::contact_support_map_support_map(pos12, g1, g2, Real::MAX) {+ Some(contact) if contact.dist >= options.target_distance => {+ ShapeCastStatus::Converged+ }+ _ => ShapeCastStatus::PenetratingOrWithinTargetDist,+ }+ } else {+ ShapeCastStatus::Converged+ },+ subshape1: 0,+ subshape2: 0,+ })+ }+ })+}diff --git a/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_voxels_shape.rs b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_voxels_shape.rsnew file mode 100644index 0000000..baa8ada--- /dev/null+++ b/renderer/third_party/parry3d/src/query/shape_cast/shape_cast_voxels_shape.rs@@ -0,0 +1,157 @@+use crate::math::{IVector, IVectorExt, Pose, Real, Vector, VectorExt};+use crate::query::{QueryDispatcher, ShapeCastHit, ShapeCastOptions};+use crate::shape::{Cuboid, Shape, Voxels};++/// Time Of Impact of a voxels shape with any other shape, under a translational movement.+pub fn cast_shapes_voxels_shape<D>(+ dispatcher: &D,+ pos12: &Pose,+ vel12: Vector,+ g1: &Voxels,+ g2: &dyn Shape,+ options: ShapeCastOptions,+) -> Option<ShapeCastHit>+where+ D: ?Sized + QueryDispatcher,+{+ use num_traits::Bounded;++ let mut hit = None;+ let mut smallest_t = options.max_time_of_impact;+ let start_aabb2_1 = g2.compute_aabb(pos12);++ let mut check_voxels_in_range = |search_domain: [IVector; 2]| {+ for vox in g1.voxels_in_range(search_domain[0], search_domain[1]) {+ if !vox.state.is_empty() {+ // PERF: could we check the canonical shape instead, and deduplicate accordingly?+ let center = g1.voxel_center(vox.grid_coords);+ let cuboid = Cuboid::new(g1.voxel_size() / 2.0);+ let vox_pos12 = Pose::from_translation(center).inverse() * pos12;+ if let Some(mut new_hit) = dispatcher+ .cast_shapes(&vox_pos12, vel12, &cuboid, g2, options)+ .ok()+ .flatten()+ {+ if new_hit.time_of_impact < smallest_t {+ // The hit is expressed in the voxel cuboid's frame, i.e. the shape's+ // frame translated by `center`. Shift `witness1` back; the normals+ // and `witness2` are unaffected by a translation.+ new_hit.witness1 += center;+ smallest_t = new_hit.time_of_impact;+ hit = Some(new_hit);+ }+ }+ }+ }+ };++ let mut search_domain = g1.voxel_range_intersecting_local_aabb(&start_aabb2_1);+ check_voxels_in_range(search_domain);++ // Run the propagation.+ let [domain_mins, domain_maxs] = g1.domain();++ loop {+ let search_domain_aabb = g1.voxel_range_aabb(search_domain[0], search_domain[1]);++ // Figure out if we should move the aabb up/down/right/left.+ #[cfg(feature = "dim2")]+ let ii = [0, 1];+ #[cfg(feature = "dim3")]+ let ii = [0, 1, 2];++ let toi = ii.map(|i| {+ if vel12.vget(i) > 0.0 {+ let t =+ (search_domain_aabb.maxs.vget(i) - start_aabb2_1.maxs.vget(i)) / vel12.vget(i);+ if t < 0.0 {+ (Real::max_value(), true)+ } else {+ (t, true)+ }+ } else if vel12.vget(i) < 0.0 {+ let t =+ (search_domain_aabb.mins.vget(i) - start_aabb2_1.mins.vget(i)) / vel12.vget(i);+ if t < 0.0 {+ (Real::max_value(), false)+ } else {+ (t, false)+ }+ } else {+ (Real::max_value(), false)+ }+ });++ #[cfg(feature = "dim2")]+ if toi[0].0 > options.max_time_of_impact && toi[1].0 > options.max_time_of_impact {+ break;+ }++ #[cfg(feature = "dim3")]+ if toi[0].0 > options.max_time_of_impact+ && toi[1].0 > options.max_time_of_impact+ && toi[2].0 > options.max_time_of_impact+ {+ break;+ }++ let imin = Vector::from(toi.map(|t| t.0)).min_position();++ if toi[imin].1 {+ search_domain[0].ivset(imin, search_domain[0].ivget(imin) + 1);+ search_domain[1].ivset(imin, search_domain[1].ivget(imin) + 1);++ if search_domain[1].ivget(imin) <= domain_maxs.ivget(imin) {+ // Check the voxels on the added row.+ let mut prev_row = search_domain[0];+ prev_row.ivset(imin, search_domain[1].ivget(imin) - 1);++ let range_to_check = [prev_row, search_domain[1]];+ check_voxels_in_range(range_to_check);+ } else if search_domain[0].ivget(imin) >= domain_maxs.ivget(imin) {+ // Leaving the shape's bounds.+ break;+ }+ } else {+ search_domain[0].ivset(imin, search_domain[0].ivget(imin) - 1);+ search_domain[1].ivset(imin, search_domain[1].ivget(imin) - 1);++ if search_domain[0].ivget(imin) >= domain_mins.ivget(imin) {+ // Check the voxels on the added row.+ let mut next_row = search_domain[1];+ next_row.ivset(imin, search_domain[0].ivget(imin) + 1);++ let range_to_check = [search_domain[0], next_row];+ check_voxels_in_range(range_to_check);+ } else if search_domain[1].ivget(imin) <= domain_mins.ivget(imin) {+ // Leaving the shape's bounds.+ break;+ }+ }+ }++ hit+}++/// Time Of Impact of any shape with a composite shape, under a rigid motion (translation + rotation).+pub fn cast_shapes_shape_voxels<D>(+ dispatcher: &D,+ pos12: &Pose,+ vel12: Vector,+ g1: &dyn Shape,+ g2: &Voxels,+ options: ShapeCastOptions,+) -> Option<ShapeCastHit>+where+ D: ?Sized + QueryDispatcher,+{+ cast_shapes_voxels_shape(+ dispatcher,+ &pos12.inverse(),+ -(pos12.rotation.inverse() * vel12),+ g2,+ g1,+ options,+ )+ .map(|time_of_impact| time_of_impact.swapped())+}diff --git a/renderer/third_party/parry3d/src/query/split/mod.rs b/renderer/third_party/parry3d/src/query/split/mod.rsnew file mode 100644index 0000000..91a930e--- /dev/null+++ b/renderer/third_party/parry3d/src/query/split/mod.rs@@ -0,0 +1,185 @@+//! Shape splitting and plane intersection operations.+//!+//! # Overview+//!+//! This module provides functionality for splitting geometric shapes with planes and computing+//! plane-shape intersections. These operations are fundamental for various geometric algorithms+//! including:+//!+//! - **Spatial partitioning**: Dividing space with axis-aligned or oriented planes+//! - **CSG (Constructive Solid Geometry)**: Boolean operations on meshes+//! - **Mesh processing**: Cutting and slicing operations on 3D models+//! - **Cross-sections**: Computing 2D slices of 3D geometry+//! - **BVH construction**: Building spatial acceleration structures+//!+//! # What is Shape Splitting?+//!+//! Shape splitting is the process of dividing a geometric shape into two or more pieces using+//! a plane. The plane acts as a "cutting tool" that partitions the shape based on which side+//! of the plane each part lies on:+//!+//! - **Negative half-space**: Vectors where the dot product with the plane normal is less than the bias+//! - **Positive half-space**: Vectors where the dot product with the plane normal is greater than the bias+//! - **On the plane**: Vectors that lie exactly on the plane (within an epsilon tolerance)+//!+//! ## Plane Definition+//!+//! A plane is defined by:+//! - A **normal vector** (unit vector perpendicular to the plane)+//! - A **bias** (signed distance from the origin along the normal)+//!+//! The plane equation is: `normal · point = bias`+//!+//! For canonical splits, the normal is aligned with a coordinate axis (e.g., X, Y, or Z axis),+//! making the operation axis-aligned.+//!+//! # When to Use Shape Splitting+//!+//! Shape splitting is useful in many scenarios:+//!+//! ## 1. Spatial Partitioning+//! When building spatial data structures like octrees or k-d trees, you need to divide space+//! recursively. Shape splitting determines which objects or parts of objects belong in each+//! partition.+//!+//! ```rust+//! # #[cfg(all(feature = "dim3", feature = "f32"))] {+//! use parry3d::bounding_volume::Aabb;+//! use parry3d::math::Vector;+//! use parry3d::query::SplitResult;+//!+//! // Split an AABB along the X-axis at x = 5.0+//! let aabb = Aabb::new(Vector::new(0.0, 0.0, 0.0), Vector::new(10.0, 10.0, 10.0));+//! match aabb.canonical_split(0, 5.0, 1e-6) {+//! SplitResult::Pair(left, right) => {+//! // AABB was split into two pieces+//! // left contains points with x < 5.0+//! // right contains points with x > 5.0+//! }+//! SplitResult::Negative => {+//! // Entire AABB is on the negative side (x < 5.0)+//! }+//! SplitResult::Positive => {+//! // Entire AABB is on the positive side (x > 5.0)+//! }+//! }+//! # }+//! ```+//!+//! ## 2. Mesh Slicing+//! For 3D modeling, CAD applications, or game engines, you might need to cut meshes with+//! planes. This is useful for effects like slicing objects with swords, laser cuts, or+//! architectural cross-sections.+//!+//! ```rust+//! # #[cfg(all(feature = "dim3", feature = "spade", feature = "f32"))]+//! # {+//! use parry3d::shape::TriMesh;+//! use parry3d::math::Vector;+//! use parry3d::query::SplitResult;+//!+//! # let vertices = vec![+//! # Vector::new(0.0, 0.0, 0.0),+//! # Vector::new(1.0, 0.0, 0.0),+//! # Vector::new(0.0, 1.0, 0.0),+//! # ];+//! # let indices = vec![[0u32, 1, 2]];+//! # let mesh = TriMesh::new(vertices, indices).unwrap();+//! // Split a mesh along the Z-axis at z = 0.5+//! match mesh.canonical_split(2, 0.5, 1e-6) {+//! SplitResult::Pair(bottom_half, top_half) => {+//! // Mesh was split into two separate meshes+//! // bottom_half contains the part with z < 0.5+//! // top_half contains the part with z > 0.5+//! // Both meshes are "capped" with new triangles on the cutting plane+//! }+//! SplitResult::Negative => {+//! // Entire mesh is below z = 0.5+//! }+//! SplitResult::Positive => {+//! // Entire mesh is above z = 0.5+//! }+//! }+//! # }+//! ```+//!+//! ## 3. Cross-Section Computation+//! Computing the intersection of a mesh with a plane gives you a 2D cross-section, useful+//! for visualization, analysis, or generating contours.+//!+// FIXME: this loops indefinitely.+// //! ```rust no_run+// //! # #[cfg(all(feature = "dim3", feature = "spade", feature = "f32"))]+// //! # {+// //! use parry3d::shape::TriMesh;+// //! use parry3d::query::IntersectResult;+// //!+// //! # let vertices = vec![+// //! # parry3d::math::Vector::ZERO,+// //! # parry3d::math::Vector::new(1.0, 0.0, 0.0),+// //! # parry3d::math::Vector::new(0.5, 1.0, 0.5),+// //! # parry3d::math::Vector::new(0.5, 0.0, 1.0),+// //! # ];+// //! # let indices = vec![[0u32, 1, 2], [0, 1, 3]];+// //! # let mesh = TriMesh::new(vertices, indices).unwrap();+// //! // Get the cross-section of a mesh at z = 0.5+// //! match mesh.canonical_intersection_with_plane(2, 0.5, 1e-6) {+// //! IntersectResult::Intersect(polyline) => {+// //! // polyline contains the 2D outline of the mesh at z = 0.5+// //! // This can have multiple connected components if the mesh+// //! // has holes or multiple separate pieces at this height+// //! }+// //! IntersectResult::Negative => {+// //! // Mesh doesn't intersect the plane; it's entirely on the negative side+// //! }+// //! IntersectResult::Positive => {+// //! // Mesh doesn't intersect the plane; it's entirely on the positive side+// //! }+// //! }+// //! # }+// //! ```+//!+//! # Supported Shapes+//!+//! Currently, the following shapes support splitting operations:+//!+//! - [`Aabb`](crate::bounding_volume::Aabb) - Axis-aligned bounding boxes+//! - [`Segment`](crate::shape::Segment) - Line segments (in 2D and 3D)+//! - [`TriMesh`](crate::shape::TriMesh) - Triangle meshes (3D only, requires `spade` feature)+//!+//! # Result Types+//!+//! The module provides two result types to represent the outcomes of splitting operations:+//!+//! - [`SplitResult`]: For operations that split a shape into pieces+//! - [`IntersectResult`]: For operations that compute the intersection with a plane+//!+//! Both types use an enum to efficiently represent the three possible outcomes without+//! unnecessary allocations when a split doesn't occur.+//!+//! # Epsilon Tolerance+//!+//! All splitting operations accept an `epsilon` parameter to handle floating-point precision+//! issues. Vectors within `epsilon` distance of the plane are considered to lie on the plane.+//! A typical value is `1e-6` for single precision (`f32`) or `1e-10` for double precision (`f64`).+//!+//! Choosing an appropriate epsilon is important:+//! - **Too small**: May cause numerical instability or incorrect classifications+//! - **Too large**: May merge distinct features or produce incorrect topology+//!+//! # Implementation Notes+//!+//! - **Segment splitting** is implemented for both 2D and 3D+//! - **AABB splitting** preserves axis-alignment and is very efficient+//! - **TriMesh splitting** (3D only) uses Delaunay triangulation to properly cap the mesh+//! where it's cut, ensuring the result is a valid closed mesh if the input was closed+//! - All operations are deterministic given the same input and epsilon value++pub use self::split::{IntersectResult, SplitResult};++mod split;+mod split_aabb;+mod split_segment;++#[cfg(all(feature = "dim3", feature = "spade"))]+mod split_trimesh;diff --git a/renderer/third_party/parry3d/src/query/split/split.rs b/renderer/third_party/parry3d/src/query/split/split.rsnew file mode 100644index 0000000..2e2e9e0--- /dev/null+++ b/renderer/third_party/parry3d/src/query/split/split.rs@@ -0,0 +1,215 @@+/// The result of a plane-splitting operation.+///+/// This enum represents the three possible outcomes when splitting a geometric shape with a plane.+/// It efficiently handles all cases without unnecessary allocations when the shape doesn't need+/// to be split.+///+/// # Type Parameter+///+/// The generic type `T` represents the shape being split. Common types include:+/// - [`Aabb`](crate::bounding_volume::Aabb) - Axis-aligned bounding box+/// - [`Segment`](crate::shape::Segment) - Line segment+/// - [`TriMesh`](crate::shape::TriMesh) - Triangle mesh+///+/// # Half-Space Definition+///+/// Given a plane defined by a normal vector `n` and bias `b`, a point `p` lies in:+/// - **Negative half-space** if `n · p < b` (behind the plane)+/// - **Positive half-space** if `n · p > b` (in front of the plane)+/// - **On the plane** if `n · p ≈ b` (within epsilon tolerance)+///+/// # Examples+///+/// ## Splitting an AABB+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::math::Vector;+/// use parry3d::query::SplitResult;+///+/// let aabb = Aabb::new(Vector::new(0.0, 0.0, 0.0), Vector::new(10.0, 10.0, 10.0));+///+/// // Split along X-axis at x = 5.0+/// match aabb.canonical_split(0, 5.0, 1e-6) {+/// SplitResult::Pair(left, right) => {+/// println!("AABB split into two pieces");+/// println!("Left AABB: {:?}", left);+/// println!("Right AABB: {:?}", right);+/// }+/// SplitResult::Negative => {+/// println!("AABB is entirely on the negative side (x < 5.0)");+/// }+/// SplitResult::Positive => {+/// println!("AABB is entirely on the positive side (x > 5.0)");+/// }+/// }+/// # }+/// ```+///+/// ## Splitting a Segment+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Segment;+/// use parry3d::math::Vector;+/// use parry3d::query::SplitResult;+///+/// let segment = Segment::new(Vector::new(0.0, 0.0, 0.0), Vector::new(10.0, 0.0, 0.0));+///+/// // Split along X-axis at x = 3.0+/// match segment.canonical_split(0, 3.0, 1e-6) {+/// SplitResult::Pair(seg1, seg2) => {+/// println!("Segment split at x = 3.0");+/// println!("First segment: {:?} to {:?}", seg1.a, seg1.b);+/// println!("Second segment: {:?} to {:?}", seg2.a, seg2.b);+/// }+/// SplitResult::Negative => {+/// println!("Entire segment is on the negative side");+/// }+/// SplitResult::Positive => {+/// println!("Entire segment is on the positive side");+/// }+/// }+/// # }+/// ```+pub enum SplitResult<T> {+ /// The split operation yielded two results: one lying on the negative half-space of the plane+ /// and the second lying on the positive half-space of the plane.+ ///+ /// The first element is the shape piece on the **negative side** of the plane (where `n · p < b`).+ /// The second element is the shape piece on the **positive side** of the plane (where `n · p > b`).+ ///+ /// For closed meshes, both pieces are typically "capped" with new geometry on the cutting plane+ /// to ensure the result consists of valid closed shapes.+ Pair(T, T),++ /// The shape being split is fully contained in the negative half-space of the plane.+ ///+ /// This means all points of the shape satisfy `n · p < b` (or are within epsilon of the plane).+ /// No splitting occurred because the shape doesn't cross the plane.+ Negative,++ /// The shape being split is fully contained in the positive half-space of the plane.+ ///+ /// This means all points of the shape satisfy `n · p > b` (or are within epsilon of the plane).+ /// No splitting occurred because the shape doesn't cross the plane.+ Positive,+}++/// The result of a plane-intersection operation.+///+/// This enum represents the outcome when computing the intersection between a geometric shape+/// and a plane. Unlike [`SplitResult`] which produces pieces of the original shape, this produces+/// the geometry that lies exactly on the plane (within epsilon tolerance).+///+/// # Type Parameter+///+/// The generic type `T` represents the result of the intersection. Common types include:+/// - [`Polyline`](crate::shape::Polyline) - For mesh-plane intersections, representing the+/// cross-section outline+///+/// # Use Cases+///+/// Plane-intersection operations are useful for:+/// - **Cross-sectional analysis**: Computing 2D slices of 3D geometry+/// - **Contour generation**: Finding outlines at specific heights+/// - **Visualization**: Displaying cutting planes through complex geometry+/// - **CAD/CAM**: Generating toolpaths or analyzing part geometry+///+/// # Examples+///+/// ## Computing a Mesh Cross-Section+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32", feature = "spade"))] {+/// use parry3d::shape::TriMesh;+/// use parry3d::math::Vector;+/// use parry3d::query::IntersectResult;+///+/// // Create a simple tetrahedron mesh+/// let vertices = vec![+/// Vector::new(0.0, 0.0, 0.0),+/// Vector::new(1.0, 0.0, 0.0),+/// Vector::new(0.5, 1.0, 0.0),+/// Vector::new(0.5, 0.5, 1.0),+/// ];+/// let indices = vec![+/// [0u32, 1, 2], // Bottom face+/// [0, 1, 3], // Front face+/// [1, 2, 3], // Right face+/// [2, 0, 3], // Left face+/// ];+/// let mesh = TriMesh::new(vertices, indices).unwrap();+///+/// // Compute cross-section at z = 0.5+/// match mesh.canonical_intersection_with_plane(2, 0.5, 1e-6) {+/// IntersectResult::Intersect(polyline) => {+/// println!("Cross-section computed!");+/// println!("Number of vertices: {}", polyline.vertices().len());+/// // The polyline represents the outline of the mesh at z = 0.5+/// // It may consist of multiple disconnected loops if the mesh+/// // has multiple separate pieces at this height+/// }+/// IntersectResult::Negative => {+/// println!("Mesh is entirely below z = 0.5");+/// }+/// IntersectResult::Positive => {+/// println!("Mesh is entirely above z = 0.5");+/// }+/// }+/// # }+/// ```+///+/// ## Handling Multiple Connected Components+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32", feature = "spade"))] {+/// use parry3d::shape::TriMesh;+/// use parry3d::query::IntersectResult;+///+/// # let vertices = vec![+/// # parry3d::math::Vector::ZERO,+/// # parry3d::math::Vector::new(1.0, 0.0, 0.0),+/// # parry3d::math::Vector::new(0.5, 1.0, 0.5),+/// # ];+/// # let indices = vec![[0u32, 1, 2]];+/// # let mesh = TriMesh::new(vertices, indices).unwrap();+/// // When intersecting a mesh with holes or multiple separate parts,+/// // the resulting polyline may have multiple connected components+/// match mesh.canonical_intersection_with_plane(2, 0.5, 1e-6) {+/// IntersectResult::Intersect(polyline) => {+/// // The polyline contains all intersection curves+/// // You can identify separate components by analyzing connectivity+/// // through the polyline's segment indices+/// let indices = polyline.indices();+/// println!("Number of edges in cross-section: {}", indices.len());+/// }+/// _ => println!("No intersection"),+/// }+/// # }+/// ```+pub enum IntersectResult<T> {+ /// The intersect operation yielded a result, lying on the plane (within epsilon tolerance).+ ///+ /// For triangle meshes, this is typically a [`Polyline`](crate::shape::Polyline) representing+ /// the outline where the mesh intersects the plane. The polyline may consist of multiple+ /// disconnected loops if the mesh has holes or multiple separate pieces at the intersection+ /// height.+ ///+ /// The intersection geometry lies on the plane, meaning all points `p` satisfy `n · p ≈ b`+ /// (within the specified epsilon tolerance).+ Intersect(T),++ /// The shape being intersected is fully contained in the negative half-space of the plane.+ ///+ /// This means all points of the shape satisfy `n · p < b` (the shape is entirely "behind"+ /// or "below" the plane). The plane doesn't intersect the shape at all.+ Negative,++ /// The shape being intersected is fully contained in the positive half-space of the plane.+ ///+ /// This means all points of the shape satisfy `n · p > b` (the shape is entirely "in front of"+ /// or "above" the plane). The plane doesn't intersect the shape at all.+ Positive,+}diff --git a/renderer/third_party/parry3d/src/query/split/split_aabb.rs b/renderer/third_party/parry3d/src/query/split/split_aabb.rsnew file mode 100644index 0000000..25e0f9f--- /dev/null+++ b/renderer/third_party/parry3d/src/query/split/split_aabb.rs@@ -0,0 +1,29 @@+use crate::bounding_volume::Aabb;+use crate::math::{Real, VectorExt};+use crate::query::SplitResult;++impl Aabb {+ /// Splits this `Aabb` along the given canonical axis.+ ///+ /// This will split the `Aabb` by a plane with a normal with it’s `axis`-th component set to 1.+ /// The splitting plane is shifted wrt. the origin by the `bias` (i.e. it passes through the point+ /// equal to `normal * bias`).+ ///+ /// # Result+ /// Returns the result of the split. The first `Aabb` returned is the piece lying on the negative+ /// half-space delimited by the splitting plane. The second `Aabb` returned is the piece lying on the+ /// positive half-space delimited by the splitting plane.+ pub fn canonical_split(&self, axis: usize, bias: Real, epsilon: Real) -> SplitResult<Self> {+ if self.mins.vget(axis) >= bias - epsilon {+ SplitResult::Positive+ } else if self.maxs.vget(axis) <= bias + epsilon {+ SplitResult::Negative+ } else {+ let mut left = *self;+ let mut right = *self;+ left.maxs.vset(axis, bias);+ right.mins.vset(axis, bias);+ SplitResult::Pair(left, right)+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/split/split_segment.rs b/renderer/third_party/parry3d/src/query/split/split_segment.rsnew file mode 100644index 0000000..9d83afe--- /dev/null+++ b/renderer/third_party/parry3d/src/query/split/split_segment.rs@@ -0,0 +1,66 @@+use crate::math::{Real, Vector, VectorExt};+use crate::query::SplitResult;+use crate::shape::Segment;++impl Segment {+ /// Splits this segment along the given canonical axis.+ ///+ /// This will split the segment by a plane with a normal with it’s `axis`-th component set to 1.+ /// The splitting plane is shifted wrt. the origin by the `bias` (i.e. it passes through the point+ /// equal to `normal * bias`).+ ///+ /// # Result+ /// Returns the result of the split. The first shape returned is the piece lying on the negative+ /// half-space delimited by the splitting plane. The second shape returned is the piece lying on the+ /// positive half-space delimited by the splitting plane.+ pub fn canonical_split(&self, axis: usize, bias: Real, epsilon: Real) -> SplitResult<Self> {+ // TODO: optimize this.+ self.local_split(Vector::ith(axis, 1.0), bias, epsilon)+ }++ /// Splits this segment by a plane identified by its normal `local_axis` and+ /// the `bias` (i.e. the plane passes through the point equal to `normal * bias`).+ pub fn local_split(&self, local_axis: Vector, bias: Real, epsilon: Real) -> SplitResult<Self> {+ self.local_split_and_get_intersection(local_axis, bias, epsilon)+ .0+ }++ /// Split a segment with a plane.+ ///+ /// This returns the result of the splitting operation, as well as+ /// the intersection point (and barycentric coordinate of this point)+ /// with the plane. The intersection point is `None` if the plane is+ /// parallel or near-parallel to the segment.+ pub fn local_split_and_get_intersection(+ &self,+ local_axis: Vector,+ bias: Real,+ epsilon: Real,+ ) -> (SplitResult<Self>, Option<(Vector, Real)>) {+ let dir = self.b - self.a;+ let a = bias - local_axis.dot(self.a);+ let b = local_axis.dot(dir);+ let bcoord = a / b;+ let dir_norm = dir.length();++ if relative_eq!(b, 0.0)+ || bcoord * dir_norm <= epsilon+ || bcoord * dir_norm >= dir_norm - epsilon+ {+ if a >= 0.0 {+ (SplitResult::Negative, None)+ } else {+ (SplitResult::Positive, None)+ }+ } else {+ let intersection = self.a + dir * bcoord;+ let s1 = Segment::new(self.a, intersection);+ let s2 = Segment::new(intersection, self.b);+ if a >= 0.0 {+ (SplitResult::Pair(s1, s2), Some((intersection, bcoord)))+ } else {+ (SplitResult::Pair(s2, s1), Some((intersection, bcoord)))+ }+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/split/split_trimesh.rs b/renderer/third_party/parry3d/src/query/split/split_trimesh.rsnew file mode 100644index 0000000..bf1f8a3--- /dev/null+++ b/renderer/third_party/parry3d/src/query/split/split_trimesh.rs@@ -0,0 +1,738 @@+use crate::bounding_volume::Aabb;+use crate::math::{Pose, Real, Vector, VectorExt};+use crate::query::{IntersectResult, PointQuery, SplitResult};+use crate::shape::{Cuboid, FeatureId, Polyline, Segment, Shape, TriMesh, TriMeshFlags, Triangle};+use crate::transformation::{intersect_meshes, MeshIntersectionError};+use crate::utils::{hashmap::HashMap, SortedPair, WBasis};+use alloc::{vec, vec::Vec};+use core::cmp::Ordering;+use spade::{handles::FixedVertexHandle, ConstrainedDelaunayTriangulation, Triangulation as _};++struct Triangulation {+ delaunay: ConstrainedDelaunayTriangulation<spade::Point2<Real>>,+ basis: [Vector; 2],+ basis_origin: Vector,+ spade2index: HashMap<FixedVertexHandle, u32>,+ index2spade: HashMap<u32, FixedVertexHandle>,+}++impl Triangulation {+ fn new(axis: Vector, basis_origin: Vector) -> Self {+ Triangulation {+ delaunay: ConstrainedDelaunayTriangulation::new(),+ basis: axis.orthonormal_basis(),+ basis_origin,+ spade2index: HashMap::default(),+ index2spade: HashMap::default(),+ }+ }++ fn project(&self, pt: Vector) -> spade::Point2<Real> {+ let dpt = pt - self.basis_origin;+ spade::Point2::new(dpt.dot(self.basis[0]), dpt.dot(self.basis[1]))+ }++ fn add_edge(&mut self, id1: u32, id2: u32, points: &[Vector]) {+ let proj1 = self.project(points[id1 as usize]);+ let proj2 = self.project(points[id2 as usize]);++ let handle1 = *self.index2spade.entry(id1).or_insert_with(|| {+ let h = self.delaunay.insert(proj1).unwrap();+ let _ = self.spade2index.insert(h, id1);+ h+ });++ let handle2 = *self.index2spade.entry(id2).or_insert_with(|| {+ let h = self.delaunay.insert(proj2).unwrap();+ let _ = self.spade2index.insert(h, id2);+ h+ });++ // NOTE: the naming of the `ConstrainedDelaunayTriangulation::can_add_constraint` method is misleading.+ if !self.delaunay.can_add_constraint(handle1, handle2) {+ let _ = self.delaunay.add_constraint(handle1, handle2);+ }+ }+}++impl TriMesh {+ /// Splits this `TriMesh` along the given canonical axis.+ ///+ /// This will split the Aabb by a plane with a normal with it’s `axis`-th component set to 1.+ /// The splitting plane is shifted wrt. the origin by the `bias` (i.e. it passes through the point+ /// equal to `normal * bias`).+ ///+ /// # Result+ /// Returns the result of the split. The first mesh returned is the piece lying on the negative+ /// half-space delimited by the splitting plane. The second mesh returned is the piece lying on the+ /// positive half-space delimited by the splitting plane.+ pub fn canonical_split(&self, axis: usize, bias: Real, epsilon: Real) -> SplitResult<Self> {+ // TODO: optimize this.+ self.local_split(Vector::ith(axis, 1.0), bias, epsilon)+ }++ /// Splits this mesh, transformed by `position` by a plane identified by its normal `local_axis`+ /// and the `bias` (i.e. the plane passes through the point equal to `normal * bias`).+ pub fn split(+ &self,+ position: &Pose,+ axis: Vector,+ bias: Real,+ epsilon: Real,+ ) -> SplitResult<Self> {+ let local_axis = position.rotation.inverse() * axis;+ let added_bias = -position.translation.dot(axis);+ self.local_split(local_axis, bias + added_bias, epsilon)+ }++ /// Splits this mesh by a plane identified by its normal `local_axis`+ /// and the `bias` (i.e. the plane passes through the point equal to `normal * bias`).+ pub fn local_split(&self, local_axis: Vector, bias: Real, epsilon: Real) -> SplitResult<Self> {+ let mut triangulation = if self.pseudo_normals_if_oriented().is_some() {+ Some(Triangulation::new(local_axis, self.vertices()[0]))+ } else {+ None+ };++ // 1. Partition the vertices.+ let vertices = self.vertices();+ let indices = self.indices();+ let mut colors = vec![0u8; self.vertices().len()];++ // Color 0 = on plane.+ // 1 = on negative half-space.+ // 2 = on positive half-space.+ let mut found_negative = false;+ let mut found_positive = false;+ for (i, pt) in vertices.iter().enumerate() {+ let dist_to_plane = pt.dot(local_axis) - bias;+ if dist_to_plane < -epsilon {+ found_negative = true;+ colors[i] = 1;+ } else if dist_to_plane > epsilon {+ found_positive = true;+ colors[i] = 2;+ }+ }++ // Exit early if `self` isn’t crossed by the plane.+ if !found_negative {+ return SplitResult::Positive;+ }++ if !found_positive {+ return SplitResult::Negative;+ }++ // 2. Split the triangles.+ let mut intersections_found = HashMap::default();+ let mut new_indices = indices.to_vec();+ let mut new_vertices = vertices.to_vec();++ for (tri_id, idx) in indices.iter().enumerate() {+ let mut intersection_features = (FeatureId::Unknown, FeatureId::Unknown);++ // First, find where the plane intersects the triangle.+ for ia in 0..3 {+ let ib = (ia + 1) % 3;+ let idx_a = idx[ia as usize];+ let idx_b = idx[ib as usize];++ let fid = match (colors[idx_a as usize], colors[idx_b as usize]) {+ (1, 2) | (2, 1) => FeatureId::Edge(ia),+ // NOTE: the case (_, 0) will be dealt with in the next loop iteration.+ (0, _) => FeatureId::Vertex(ia),+ _ => continue,+ };++ if intersection_features.0 == FeatureId::Unknown {+ intersection_features.0 = fid;+ } else {+ // TODO: this assertion may fire if the triangle is coplanar with the edge?+ // assert_eq!(intersection_features.1, FeatureId::Unknown);+ intersection_features.1 = fid;+ }+ }++ // Helper that intersects an edge with the plane.+ let mut intersect_edge = |idx_a, idx_b| {+ *intersections_found+ .entry(SortedPair::new(idx_a, idx_b))+ .or_insert_with(|| {+ let segment = Segment::new(+ new_vertices[idx_a as usize],+ new_vertices[idx_b as usize],+ );+ // Intersect the segment with the plane.+ if let Some((intersection, _)) = segment+ .local_split_and_get_intersection(local_axis, bias, epsilon)+ .1+ {+ new_vertices.push(intersection);+ colors.push(0);+ (new_vertices.len() - 1) as u32+ } else {+ unreachable!()+ }+ })+ };++ // Perform the intersection, push new triangles, and update+ // triangulation constraints if needed.+ match intersection_features {+ (_, FeatureId::Unknown) => {+ // The plane doesn’t intersect the triangle, or intersects it at+ // a single vertex, so we don’t have anything to do.+ assert!(+ matches!(intersection_features.0, FeatureId::Unknown)+ || matches!(intersection_features.0, FeatureId::Vertex(_))+ );+ }+ (FeatureId::Vertex(v1), FeatureId::Vertex(v2)) => {+ // The plane intersects the triangle along one of its edge.+ // We don’t have to split the triangle, but we need to add+ // a constraint to the triangulation.+ if let Some(triangulation) = &mut triangulation {+ let id1 = idx[v1 as usize];+ let id2 = idx[v2 as usize];+ triangulation.add_edge(id1, id2, &new_vertices);+ }+ }+ (FeatureId::Vertex(iv), FeatureId::Edge(ie))+ | (FeatureId::Edge(ie), FeatureId::Vertex(iv)) => {+ // The plane splits the triangle into exactly two triangles.+ let ia = ie;+ let ib = (ie + 1) % 3;+ let ic = (ie + 2) % 3;+ let idx_a = idx[ia as usize];+ let idx_b = idx[ib as usize];+ let idx_c = idx[ic as usize];+ assert_eq!(iv, ic);++ let intersection_idx = intersect_edge(idx_a, idx_b);++ // Compute the indices of the two triangles.+ let new_tri_a = [idx_c, idx_a, intersection_idx];+ let new_tri_b = [idx_b, idx_c, intersection_idx];++ new_indices[tri_id] = new_tri_a;+ new_indices.push(new_tri_b);++ if let Some(triangulation) = &mut triangulation {+ triangulation.add_edge(intersection_idx, idx_c, &new_vertices);+ }+ }+ (FeatureId::Edge(mut e1), FeatureId::Edge(mut e2)) => {+ // The plane splits the triangle into 1 + 2 triangles.+ // First, make sure the edge indices are consecutive.+ if e2 != (e1 + 1) % 3 {+ core::mem::swap(&mut e1, &mut e2);+ }++ let ia = e2; // The first point of the second edge is the vertex shared by both edges.+ let ib = (e2 + 1) % 3;+ let ic = (e2 + 2) % 3;+ let idx_a = idx[ia as usize];+ let idx_b = idx[ib as usize];+ let idx_c = idx[ic as usize];++ let intersection1 = intersect_edge(idx_c, idx_a);+ let intersection2 = intersect_edge(idx_a, idx_b);++ let new_tri1 = [idx_a, intersection2, intersection1];+ let new_tri2 = [intersection2, idx_b, idx_c];+ let new_tri3 = [intersection2, idx_c, intersection1];+ new_indices[tri_id] = new_tri1;+ new_indices.push(new_tri2);+ new_indices.push(new_tri3);++ if let Some(triangulation) = &mut triangulation {+ triangulation.add_edge(intersection1, intersection2, &new_vertices);+ }+ }+ _ => unreachable!(),+ }+ }++ // 3. Partition the new triangles into two trimeshes.+ let mut vertices_lhs = vec![];+ let mut vertices_rhs = vec![];+ let mut indices_lhs = vec![];+ let mut indices_rhs = vec![];+ let mut remap = vec![];++ for i in 0..new_vertices.len() {+ match colors[i] {+ 0 => {+ remap.push((vertices_lhs.len() as u32, vertices_rhs.len() as u32));+ vertices_lhs.push(new_vertices[i]);+ vertices_rhs.push(new_vertices[i]);+ }+ 1 => {+ remap.push((vertices_lhs.len() as u32, u32::MAX));+ vertices_lhs.push(new_vertices[i]);+ }+ 2 => {+ remap.push((u32::MAX, vertices_rhs.len() as u32));+ vertices_rhs.push(new_vertices[i]);+ }+ _ => unreachable!(),+ }+ }++ for idx in new_indices {+ let idx = [idx[0] as usize, idx[1] as usize, idx[2] as usize]; // Convert to usize.+ let colors = [colors[idx[0]], colors[idx[1]], colors[idx[2]]];+ let remap = [remap[idx[0]], remap[idx[1]], remap[idx[2]]];++ if colors[0] == 1 || colors[1] == 1 || colors[2] == 1 {+ assert!(colors[0] != 2 && colors[1] != 2 && colors[2] != 2);+ indices_lhs.push([remap[0].0, remap[1].0, remap[2].0]);+ } else if colors[0] == 2 || colors[1] == 2 || colors[2] == 2 {+ assert!(colors[0] != 1 && colors[1] != 1 && colors[2] != 1);+ indices_rhs.push([remap[0].1, remap[1].1, remap[2].1]);+ } else {+ // The colors are all 0, so push into both trimeshes.+ indices_lhs.push([remap[0].0, remap[1].0, remap[2].0]);+ indices_rhs.push([remap[0].1, remap[1].1, remap[2].1]);+ }+ }++ // Push the triangulation if there is one.+ if let Some(triangulation) = triangulation {+ for face in triangulation.delaunay.inner_faces() {+ let vtx = face.vertices();+ let mut idx1 = [0; 3];+ let mut idx2 = [0; 3];+ for k in 0..3 {+ let vid = triangulation.spade2index[&vtx[k].fix()];+ assert_eq!(colors[vid as usize], 0);+ idx1[k] = remap[vid as usize].0;+ idx2[k] = remap[vid as usize].1;+ }++ let tri = Triangle::new(+ vertices_lhs[idx1[0] as usize],+ vertices_lhs[idx1[1] as usize],+ vertices_lhs[idx1[2] as usize],+ );++ if self.contains_local_point(tri.center()) {+ indices_lhs.push(idx1);++ idx2.swap(1, 2); // Flip orientation for the second half of the split.+ indices_rhs.push(idx2);+ }+ }+ }++ // TODO: none of the index buffers should be empty at this point unless perhaps+ // because of some rounding errors?+ // Should we just panic if they are empty?+ if indices_rhs.is_empty() {+ SplitResult::Negative+ } else if indices_lhs.is_empty() {+ SplitResult::Positive+ } else {+ let mesh_lhs = TriMesh::new(vertices_lhs, indices_lhs).unwrap();+ let mesh_rhs = TriMesh::new(vertices_rhs, indices_rhs).unwrap();+ SplitResult::Pair(mesh_lhs, mesh_rhs)+ }+ }++ /// Computes the intersection [`Polyline`]s between this mesh and the plane identified by+ /// the given canonical axis.+ ///+ /// This will intersect the mesh by a plane with a normal with it’s `axis`-th component set to 1.+ /// The splitting plane is shifted wrt. the origin by the `bias` (i.e. it passes through the point+ /// equal to `normal * bias`).+ ///+ /// Note that the resultant polyline may have multiple connected components+ pub fn canonical_intersection_with_plane(+ &self,+ axis: usize,+ bias: Real,+ epsilon: Real,+ ) -> IntersectResult<Polyline> {+ self.intersection_with_local_plane(Vector::ith(axis, 1.0), bias, epsilon)+ }++ /// Computes the intersection [`Polyline`]s between this mesh, transformed by `position`,+ /// and a plane identified by its normal `axis` and the `bias`+ /// (i.e. the plane passes through the point equal to `normal * bias`).+ pub fn intersection_with_plane(+ &self,+ position: &Pose,+ axis: Vector,+ bias: Real,+ epsilon: Real,+ ) -> IntersectResult<Polyline> {+ let local_axis = position.rotation.inverse() * axis;+ let added_bias = -position.translation.dot(axis);+ self.intersection_with_local_plane(local_axis, bias + added_bias, epsilon)+ }++ /// Computes the intersection [`Polyline`]s between this mesh+ /// and a plane identified by its normal `local_axis`+ /// and the `bias` (i.e. the plane passes through the point equal to `normal * bias`).+ pub fn intersection_with_local_plane(+ &self,+ local_axis: Vector,+ bias: Real,+ epsilon: Real,+ ) -> IntersectResult<Polyline> {+ // 1. Partition the vertices.+ let vertices = self.vertices();+ let indices = self.indices();+ let mut colors = vec![0u8; self.vertices().len()];++ // Color 0 = on plane.+ // 1 = on negative half-space.+ // 2 = on positive half-space.+ let mut found_negative = false;+ let mut found_positive = false;+ for (i, pt) in vertices.iter().enumerate() {+ let dist_to_plane = pt.dot(local_axis) - bias;+ if dist_to_plane < -epsilon {+ found_negative = true;+ colors[i] = 1;+ } else if dist_to_plane > epsilon {+ found_positive = true;+ colors[i] = 2;+ }+ }++ // Exit early if `self` isn’t crossed by the plane.+ if !found_negative {+ return IntersectResult::Positive;+ }++ if !found_positive {+ return IntersectResult::Negative;+ }++ // 2. Split the triangles.+ let mut index_adjacencies: Vec<Vec<usize>> = Vec::new(); // Adjacency list of indices++ // Helper functions for adding polyline segments to the adjacency list+ let mut add_segment_adjacencies = |idx_a: usize, idx_b| {+ assert!(idx_a <= index_adjacencies.len());++ match idx_a.cmp(&index_adjacencies.len()) {+ Ordering::Less => index_adjacencies[idx_a].push(idx_b),+ Ordering::Equal => index_adjacencies.push(vec![idx_b]),+ Ordering::Greater => {}+ }+ };+ let mut add_segment_adjacencies_symmetric = |idx_a: usize, idx_b| {+ if idx_a < idx_b {+ add_segment_adjacencies(idx_a, idx_b);+ add_segment_adjacencies(idx_b, idx_a);+ } else {+ add_segment_adjacencies(idx_b, idx_a);+ add_segment_adjacencies(idx_a, idx_b);+ }+ };++ let mut intersections_found = HashMap::default();+ let mut existing_vertices_found = HashMap::default();+ let mut new_vertices = Vec::new();++ for idx in indices.iter() {+ let mut intersection_features = (FeatureId::Unknown, FeatureId::Unknown);++ // First, find where the plane intersects the triangle.+ for ia in 0..3 {+ let ib = (ia + 1) % 3;+ let idx_a = idx[ia as usize];+ let idx_b = idx[ib as usize];++ let fid = match (colors[idx_a as usize], colors[idx_b as usize]) {+ (1, 2) | (2, 1) => FeatureId::Edge(ia),+ // NOTE: the case (_, 0) will be dealt with in the next loop iteration.+ (0, _) => FeatureId::Vertex(ia),+ _ => continue,+ };++ if intersection_features.0 == FeatureId::Unknown {+ intersection_features.0 = fid;+ } else {+ // TODO: this assertion may fire if the triangle is coplanar with the edge?+ // assert_eq!(intersection_features.1, FeatureId::Unknown);+ intersection_features.1 = fid;+ }+ }++ // Helper that intersects an edge with the plane.+ let mut intersect_edge = |idx_a, idx_b| {+ *intersections_found+ .entry(SortedPair::new(idx_a, idx_b))+ .or_insert_with(|| {+ let segment =+ Segment::new(vertices[idx_a as usize], vertices[idx_b as usize]);+ // Intersect the segment with the plane.+ if let Some((intersection, _)) = segment+ .local_split_and_get_intersection(local_axis, bias, epsilon)+ .1+ {+ new_vertices.push(intersection);+ colors.push(0);+ new_vertices.len() - 1+ } else {+ unreachable!()+ }+ })+ };++ // Perform the intersection, push new triangles, and update+ // triangulation constraints if needed.+ match intersection_features {+ (_, FeatureId::Unknown) => {+ // The plane doesn’t intersect the triangle, or intersects it at+ // a single vertex, so we don’t have anything to do.+ assert!(+ matches!(intersection_features.0, FeatureId::Unknown)+ || matches!(intersection_features.0, FeatureId::Vertex(_))+ );+ }+ (FeatureId::Vertex(iv1), FeatureId::Vertex(iv2)) => {+ // The plane intersects the triangle along one of its edge.+ // We don’t have to split the triangle, but we need to add+ // the edge to the polyline indices++ let id1 = idx[iv1 as usize];+ let id2 = idx[iv2 as usize];++ let out_id1 = *existing_vertices_found.entry(id1).or_insert_with(|| {+ let v1 = vertices[id1 as usize];++ new_vertices.push(v1);+ new_vertices.len() - 1+ });+ let out_id2 = *existing_vertices_found.entry(id2).or_insert_with(|| {+ let v2 = vertices[id2 as usize];++ new_vertices.push(v2);+ new_vertices.len() - 1+ });++ add_segment_adjacencies_symmetric(out_id1, out_id2);+ }+ (FeatureId::Vertex(iv), FeatureId::Edge(ie))+ | (FeatureId::Edge(ie), FeatureId::Vertex(iv)) => {+ // The plane splits the triangle into exactly two triangles.+ let ia = ie;+ let ib = (ie + 1) % 3;+ let ic = (ie + 2) % 3;+ let idx_a = idx[ia as usize];+ let idx_b = idx[ib as usize];+ let idx_c = idx[ic as usize];+ assert_eq!(iv, ic);++ let intersection_idx = intersect_edge(idx_a, idx_b);++ let out_idx_c = *existing_vertices_found.entry(idx_c).or_insert_with(|| {+ let v2 = vertices[idx_c as usize];++ new_vertices.push(v2);+ new_vertices.len() - 1+ });++ add_segment_adjacencies_symmetric(out_idx_c, intersection_idx);+ }+ (FeatureId::Edge(mut e1), FeatureId::Edge(mut e2)) => {+ // The plane splits the triangle into 1 + 2 triangles.+ // First, make sure the edge indices are consecutive.+ if e2 != (e1 + 1) % 3 {+ core::mem::swap(&mut e1, &mut e2);+ }++ let ia = e2; // The first point of the second edge is the vertex shared by both edges.+ let ib = (e2 + 1) % 3;+ let ic = (e2 + 2) % 3;+ let idx_a = idx[ia as usize];+ let idx_b = idx[ib as usize];+ let idx_c = idx[ic as usize];++ let intersection1 = intersect_edge(idx_c, idx_a);+ let intersection2 = intersect_edge(idx_a, idx_b);++ add_segment_adjacencies_symmetric(intersection1, intersection2);+ }+ _ => unreachable!(),+ }+ }++ // 3. Ensure consistent edge orientation by traversing the adjacency list+ let mut polyline_indices: Vec<[u32; 2]> = Vec::with_capacity(index_adjacencies.len() + 1);++ let mut seen = vec![false; index_adjacencies.len()];+ for (idx, neighbors) in index_adjacencies.iter().enumerate() {+ if !seen[idx] {+ // Start a new component+ // Traverse the adjencies until the loop closes++ let first = idx;+ let mut prev = first;+ let mut next = neighbors.first(); // Arbitrary neighbor++ 'traversal: while let Some(current) = next {+ // If we reach an already-visited index, the traversal cannot make any+ // further progress: stop here instead of looping forever. This guards+ // against degenerate adjacency graphs that don't form a clean loop back+ // to `first`.+ if seen[*current] {+ break;+ }++ seen[*current] = true;+ polyline_indices.push([prev as u32, *current as u32]);++ for neighbor in index_adjacencies[*current].iter() {+ if *neighbor != prev && *neighbor != first {+ prev = *current;+ next = Some(neighbor);+ continue 'traversal;+ } else if *neighbor != prev && *neighbor == first {+ // If the next index is same as the first, close the polyline and exit+ polyline_indices.push([*current as u32, first as u32]);+ next = None;+ continue 'traversal;+ }+ }+ }+ }+ }++ IntersectResult::Intersect(Polyline::new(new_vertices, Some(polyline_indices)))+ }++ /// Computes the intersection mesh between an Aabb and this mesh.+ pub fn intersection_with_aabb(+ &self,+ position: &Pose,+ flip_mesh: bool,+ aabb: &Aabb,+ flip_cuboid: bool,+ epsilon: Real,+ ) -> Result<Option<Self>, MeshIntersectionError> {+ let cuboid = Cuboid::new(aabb.half_extents());+ let cuboid_pos = Pose::from_translation(aabb.center());+ self.intersection_with_cuboid(+ position,+ flip_mesh,+ &cuboid,+ &cuboid_pos,+ flip_cuboid,+ epsilon,+ )+ }++ /// Computes the intersection mesh between a cuboid and this mesh transformed by `position`.+ pub fn intersection_with_cuboid(+ &self,+ position: &Pose,+ flip_mesh: bool,+ cuboid: &Cuboid,+ cuboid_position: &Pose,+ flip_cuboid: bool,+ epsilon: Real,+ ) -> Result<Option<Self>, MeshIntersectionError> {+ self.intersection_with_local_cuboid(+ flip_mesh,+ cuboid,+ &position.inv_mul(cuboid_position),+ flip_cuboid,+ epsilon,+ )+ }++ /// Computes the intersection mesh between a cuboid and this mesh.+ pub fn intersection_with_local_cuboid(+ &self,+ flip_mesh: bool,+ cuboid: &Cuboid,+ cuboid_position: &Pose,+ flip_cuboid: bool,+ _epsilon: Real,+ ) -> Result<Option<Self>, MeshIntersectionError> {+ if self.topology().is_some() && self.pseudo_normals_if_oriented().is_some() {+ let (cuboid_vtx, cuboid_idx) = cuboid.to_trimesh();+ let cuboid_trimesh = TriMesh::with_flags(+ cuboid_vtx,+ cuboid_idx,+ TriMeshFlags::HALF_EDGE_TOPOLOGY | TriMeshFlags::ORIENTED,+ )+ // `TriMesh::with_flags` can't fail for `cuboid.to_trimesh()`.+ .unwrap();++ let intersect_meshes = intersect_meshes(+ &Pose::IDENTITY,+ self,+ flip_mesh,+ cuboid_position,+ &cuboid_trimesh,+ flip_cuboid,+ );+ return intersect_meshes;+ }++ let cuboid_aabb = cuboid.compute_aabb(cuboid_position);+ let intersecting_tris: Vec<_> = self.bvh().intersect_aabb(&cuboid_aabb).collect();++ if intersecting_tris.is_empty() {+ return Ok(None);+ }++ // First, very naive version that outputs a triangle soup without+ // index buffer (shared vertices are duplicated).+ let vertices = self.vertices();+ let indices = self.indices();++ let mut clip_workspace = vec![];+ let mut new_vertices = vec![];+ let mut new_indices = vec![];+ let aabb = cuboid.local_aabb();+ let inv_pos = cuboid_position.inverse();+ let mut to_clip = vec![];++ for tri in intersecting_tris {+ let idx = indices[tri as usize];+ to_clip.extend_from_slice(&[+ inv_pos * vertices[idx[0] as usize],+ inv_pos * vertices[idx[1] as usize],+ inv_pos * vertices[idx[2] as usize],+ ]);++ // There is no need to clip if the triangle is fully inside of the Aabb.+ // Note that we can’t take a shortcut for the case where all the vertices are+ // outside of the Aabb, because the Aabb can still instersect the edges or face.+ if !(aabb.contains_local_point(to_clip[0])+ && aabb.contains_local_point(to_clip[1])+ && aabb.contains_local_point(to_clip[2]))+ {+ aabb.clip_polygon_with_workspace(&mut to_clip, &mut clip_workspace);+ }++ if to_clip.len() >= 3 {+ let base_i = new_vertices.len();+ for i in 1..to_clip.len() - 1 {+ new_indices.push([base_i as u32, (base_i + i) as u32, (base_i + i + 1) as u32]);+ }+ new_vertices.append(&mut to_clip);+ }+ }++ // The clipping outputs points in the local-space of the cuboid.+ // So we need to transform it back.+ for pt in &mut new_vertices {+ *pt = cuboid_position * *pt;+ }++ Ok(if new_vertices.len() >= 3 {+ Some(TriMesh::new(new_vertices, new_indices).unwrap())+ } else {+ None+ })+ }+}diff --git a/renderer/third_party/parry3d/src/query/sweep_toi/composite.rs b/renderer/third_party/parry3d/src/query/sweep_toi/composite.rsnew file mode 100644index 0000000..4da1be5--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sweep_toi/composite.rs@@ -0,0 +1,296 @@+//! Sweep time-of-impact against composite shapes (meshes, polylines, heightfields,+//! compounds): the composite is assumed stationary, its acceleration structure is queried+//! with the swept bounds of the moving shape, and each candidate element runs the convex+//! TOI with a fallback sphere when the element reports an initial overlap.++use super::sweep::Sweep;+use super::sweep_toi::{sweep_time_of_impact, SweepToiOutput, SweepToiStatus};+use super::toi_proxy::ToiProxy;+use crate::bounding_volume::BoundingVolume;+use crate::math::{Pose, Real, Vector};+use crate::shape::{Shape, TypedShape};++#[cfg(feature = "dim2")]+use crate::shape::{PolylineFlags, Segment};+#[cfg(feature = "dim3")]+use crate::shape::{TriMeshFlags, Triangle};++/// Fraction of the fast shape’s minimum extent used for the initial-overlap fallback sphere.+pub const CORE_FRACTION: Real = 0.25;++/// Parameters describing the fast (moving) shape for a composite TOI query.+#[derive(Copy, Clone)]+pub struct SweepCompositeFastShape<'a, 'b> {+ /// Point-cloud proxy of the moving shape.+ pub proxy: &'a ToiProxy<'b>,+ /// Sweep of the moving shape.+ pub sweep: &'a Sweep,+ /// Centroid of the moving shape in its local frame.+ pub local_centroid: Vector,+ /// Smallest extent (inner radius) of the moving shape, used for fallback spheres and+ /// one-sided early-outs.+ pub min_extent: Real,+}++struct CompositeToiContext<'a, 'b> {+ fast: SweepCompositeFastShape<'a, 'b>,+ // Centroid of the moving shape at the sweep endpoints, in the composite’s local frame.+ local_centroid1: Vector,+ local_centroid2: Vector,+ fallback_radius: Real,+ one_sided: bool,+ #[cfg_attr(feature = "dim2", allow(dead_code))]+ target_is_sensor: bool,+ linear_slop: Real,+ max_fraction: Real,+ best: Option<SweepToiOutput>,+}++impl CompositeToiContext<'_, '_> {+ /// Runs the convex TOI of the moving shape against one composite element and keeps the+ /// earliest hit, with a fallback-sphere retry on initial overlap.+ fn toi_against_element(&mut self, element_proxy: &ToiProxy, element_sweep: &Sweep) {+ let output = sweep_time_of_impact(+ element_proxy,+ element_sweep,+ self.fast.proxy,+ self.fast.sweep,+ self.max_fraction,+ self.linear_slop,+ );++ if 0.0 < output.fraction && output.fraction < self.max_fraction {+ self.max_fraction = output.fraction;+ self.best = Some(output);+ } else if output.fraction == 0.0 {+ // Fallback to the TOI of a small ball around the fast shape centroid.+ #[cfg(feature = "dim2")]+ let radius = self.fallback_radius;+ #[cfg(feature = "dim3")]+ let radius = self.fallback_radius + self.linear_slop;++ let fallback_proxy = ToiProxy::point(self.fast.local_centroid, radius);+ let output = sweep_time_of_impact(+ element_proxy,+ element_sweep,+ &fallback_proxy,+ self.fast.sweep,+ self.max_fraction,+ self.linear_slop,+ );++ if 0.0 < output.fraction && output.fraction < self.max_fraction {+ self.max_fraction = output.fraction;+ self.best = Some(output);+ }+ }+ }++ /// One-sided early-out for a 2D chain segment.+ /// Returns `true` when the element can be skipped.+ #[cfg(feature = "dim2")]+ fn one_sided_early_out(&self, segment: &Segment) -> bool {+ if !self.one_sided {+ return false;+ }++ let e = segment.b - segment.a;+ let length = e.length();+ if length <= self.linear_slop {+ return false;+ }+ let e = e / length;++ let separation1 = (self.local_centroid1 - segment.a).perp_dot(e);+ let separation2 = (self.local_centroid2 - segment.a).perp_dot(e);+ let core_distance = CORE_FRACTION * self.fast.min_extent;++ separation1 < 0.0+ || (separation1 - separation2 < core_distance && separation2 > core_distance)+ }++ /// One-sided early-out for a 3D triangle.+ /// Returns `true` when the element can be skipped.+ #[cfg(feature = "dim3")]+ fn one_sided_early_out(&self, triangle: &Triangle) -> bool {+ if !self.one_sided {+ return false;+ }++ let n = (triangle.b - triangle.a)+ .cross(triangle.c - triangle.a)+ .normalize_or_zero();+ let offset1 = n.dot(self.local_centroid1 - triangle.a);+ let offset2 = n.dot(self.local_centroid2 - triangle.a);++ if offset1 < 0.0 {+ // Started behind.+ return true;+ }++ if !self.target_is_sensor+ && offset1 - offset2 < self.fallback_radius+ && offset2 > self.fallback_radius+ {+ // Finished in front.+ return true;+ }++ false+ }+}++/// Computes the time of impact between a stationary composite shape and a moving convex+/// shape.+///+/// Returns `None` if `composite` is not a supported composite shape (triangle mesh,+/// polyline, heightfield, or compound). When supported but nothing is hit, the returned+/// output has status [`SweepToiStatus::Separated`] and `fraction == max_fraction`.+///+/// `one_sided` enables the “started behind / finished in front” early-outs; it+/// should only be set for composites whose elements have meaningful outward normals+/// (oriented polylines, oriented meshes, heightfields).+#[allow(clippy::too_many_arguments)]+pub fn sweep_time_of_impact_composite(+ composite: &dyn Shape,+ composite_pose: &Pose,+ fast: SweepCompositeFastShape,+ one_sided: bool,+ target_is_sensor: bool,+ max_fraction: Real,+ linear_slop: Real,+) -> Option<SweepToiOutput> {+ let typed = composite.as_typed_shape();++ // Fallback sphere radius (2D: core circle; 3D: mesh/compound fallback spheres).+ #[cfg(feature = "dim2")]+ let fallback_radius = CORE_FRACTION * fast.min_extent;+ #[cfg(feature = "dim3")]+ let fallback_radius = match typed {+ TypedShape::Compound(_) => (0.75 * fast.min_extent).max(4.0 * linear_slop),+ _ => (0.5 * fast.min_extent).max(linear_slop),+ };++ // Swept bounds of the fast shape, in the composite’s local frame.+ let start_aabb = fast.proxy.compute_aabb(&fast.sweep.transform_at(0.0));+ let end_aabb = fast+ .proxy+ .compute_aabb(&fast.sweep.transform_at(max_fraction));+ let local_aabb = start_aabb+ .merged(&end_aabb)+ .transform_by(&composite_pose.inverse());++ // Centroid of the fast shape at the sweep endpoints, in the composite’s local frame.+ let centroid_world1 = fast+ .sweep+ .transform_at(0.0)+ .transform_point(fast.local_centroid);+ let centroid_world2 = fast+ .sweep+ .final_transform()+ .transform_point(fast.local_centroid);++ let mut context = CompositeToiContext {+ fast,+ local_centroid1: composite_pose.inverse_transform_point(centroid_world1),+ local_centroid2: composite_pose.inverse_transform_point(centroid_world2),+ fallback_radius,+ one_sided,+ target_is_sensor,+ linear_slop,+ max_fraction,+ best: None,+ };++ // The composite is stationary: every element sweep is degenerate at the composite pose+ // (composed with the child pose for compounds).+ let composite_sweep = Sweep::constant(composite_pose, Vector::ZERO);++ match typed {+ #[cfg(feature = "dim3")]+ TypedShape::TriMesh(mesh) => {+ let one_sided_mesh = mesh.flags().contains(TriMeshFlags::ORIENTED);+ context.one_sided = one_sided || one_sided_mesh;+ for tri_id in mesh.bvh().intersect_aabb(&local_aabb) {+ let triangle = mesh.triangle(tri_id);+ if context.one_sided_early_out(&triangle) {+ continue;+ }+ let proxy = ToiProxy::from_array([triangle.a, triangle.b, triangle.c], 0.0);+ context.toi_against_element(&proxy, &composite_sweep);+ }+ }+ #[cfg(feature = "dim2")]+ TypedShape::TriMesh(mesh) => {+ for tri_id in mesh.bvh().intersect_aabb(&local_aabb) {+ let triangle = mesh.triangle(tri_id);+ let proxy = ToiProxy::from_array([triangle.a, triangle.b, triangle.c], 0.0);+ context.toi_against_element(&proxy, &composite_sweep);+ }+ }+ TypedShape::Polyline(polyline) => {+ #[cfg(feature = "dim2")]+ {+ let oriented = polyline.flags().contains(PolylineFlags::ORIENTED);+ context.one_sided = one_sided || oriented;+ }+ for seg_id in polyline.bvh().intersect_aabb(&local_aabb) {+ let segment = polyline.segment(seg_id);+ #[cfg(feature = "dim2")]+ if context.one_sided_early_out(&segment) {+ continue;+ }+ let proxy = ToiProxy::from_array([segment.a, segment.b], 0.0);+ context.toi_against_element(&proxy, &composite_sweep);+ }+ }+ TypedShape::HeightField(heightfield) => {+ #[cfg(feature = "dim2")]+ heightfield.map_elements_in_local_aabb(&local_aabb, &mut |_, segment| {+ if !context.one_sided_early_out(segment) {+ let proxy = ToiProxy::from_array([segment.a, segment.b], 0.0);+ context.toi_against_element(&proxy, &composite_sweep);+ }+ });+ #[cfg(feature = "dim3")]+ heightfield.map_elements_in_local_aabb(&local_aabb, &mut |_, triangle| {+ if !context.one_sided_early_out(triangle) {+ let proxy = ToiProxy::from_array([triangle.a, triangle.b, triangle.c], 0.0);+ context.toi_against_element(&proxy, &composite_sweep);+ }+ });+ }+ TypedShape::Compound(compound) => {+ for child_id in compound.bvh().intersect_aabb(&local_aabb) {+ let (child_pose, child_shape) = &compound.shapes()[child_id as usize];+ let child_world_pose = *composite_pose * *child_pose;+ if let Some(child_proxy) = ToiProxy::from_shape(child_shape.as_ref()) {+ let child_sweep = Sweep::constant(&child_world_pose, Vector::ZERO);+ context.toi_against_element(&child_proxy, &child_sweep);+ } else if let Some(hit) = sweep_time_of_impact_composite(+ child_shape.as_ref(),+ &child_world_pose,+ context.fast,+ context.one_sided,+ target_is_sensor,+ context.max_fraction,+ linear_slop,+ ) {+ if 0.0 < hit.fraction && hit.fraction < context.max_fraction {+ context.max_fraction = hit.fraction;+ context.best = Some(hit);+ }+ }+ // Children that are neither point-cloud shapes nor composites are skipped.+ }+ }+ _ => return None,+ }++ Some(context.best.unwrap_or(SweepToiOutput {+ status: SweepToiStatus::Separated,+ fraction: max_fraction,+ point: Vector::ZERO,+ normal: Vector::ZERO,+ }))+}diff --git a/renderer/third_party/parry3d/src/query/sweep_toi/mod.rs b/renderer/third_party/parry3d/src/query/sweep_toi/mod.rsnew file mode 100644index 0000000..1ed8d32--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sweep_toi/mod.rs@@ -0,0 +1,26 @@+//! Time-of-impact computation on endpoint-interpolated sweeps.+//!+//! Unlike [`cast_shapes_nonlinear`](crate::query::cast_shapes_nonlinear), which models motion+//! as constant velocities, this module models a timestep as a [`Sweep`] between two endpoint+//! poses (linear center-of-mass interpolation + rotation nlerp) and computes the earliest+//! time at which two swept shapes reach a slop-based target separation, using conservative+//! advancement with separation functions.+//!+//! NOTE: this is mostly ported from Box2D which had much better CCD quality than Rapier.+//! TODO: see how we can combine that with `nonlinear_shape_cast` since they serve similar goals.++pub use self::proxy_distance::{proxy_distance, ProxyDistanceOutput, SimplexCache};+pub use self::sweep::Sweep;+pub use self::sweep_toi::{sweep_time_of_impact, SweepToiOutput, SweepToiStatus};+pub use self::toi_proxy::{ToiProxy, TOI_PROXY_INLINE_POINTS};++#[cfg(feature = "alloc")]+pub use self::composite::{sweep_time_of_impact_composite, SweepCompositeFastShape, CORE_FRACTION};++#[cfg(feature = "alloc")]+mod composite;+mod proxy_distance;+mod separation;+mod sweep;+mod sweep_toi;+mod toi_proxy;diff --git a/renderer/third_party/parry3d/src/query/sweep_toi/proxy_distance.rs b/renderer/third_party/parry3d/src/query/sweep_toi/proxy_distance.rsnew file mode 100644index 0000000..6f541ff--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sweep_toi/proxy_distance.rs@@ -0,0 +1,1027 @@+//! GJK distance between two point-cloud proxies with an index-based simplex cache.+//!+//! The cache warm-starts successive distance queries on the same pair, which is the+//! backbone of the conservative-advancement time-of-impact loop.++use super::toi_proxy::ToiProxy;+use crate::math::{Pose, Real, Vector};++/// Warm-starting simplex cache for [`proxy_distance`].+#[derive(Copy, Clone, Debug, Default)]+pub struct SimplexCache {+ /// Simplex size measure used to detect a stale cache (3D only).+ #[cfg(feature = "dim3")]+ pub metric: Real,+ /// Number of cached simplex vertices (0 to 3).+ pub count: u8,+ /// Cached support indices on the first proxy.+ pub index_a: [u32; 3],+ /// Cached support indices on the second proxy.+ pub index_b: [u32; 3],+}++/// Result of [`proxy_distance`]. All geometric quantities are expressed in the local frame of+/// the first proxy.+#[derive(Copy, Clone, Debug, Default)]+pub struct ProxyDistanceOutput {+ /// Closest point on the first proxy (frame A).+ pub point_a: Vector,+ /// Closest point on the second proxy (frame A).+ pub point_b: Vector,+ /// Separation direction pointing from A to B (frame A). Zero if overlapped.+ pub normal: Vector,+ /// Distance between the two proxies (0 if overlapped).+ pub distance: Real,+ /// Number of GJK iterations used.+ pub iterations: u32,+}++#[derive(Copy, Clone, Default)]+struct SimplexVertex {+ wa: Vector,+ wb: Vector,+ w: Vector,+ a: Real,+ index_a: u32,+ index_b: u32,+}++fn cache_is_valid(cache: &SimplexCache, proxy_a: &ToiProxy, proxy_b: &ToiProxy) -> bool {+ let (na, nb) = (proxy_a.points().len() as u32, proxy_b.points().len() as u32);+ cache.count <= 3+ && cache.index_a[..cache.count as usize]+ .iter()+ .all(|i| *i < na)+ && cache.index_b[..cache.count as usize]+ .iter()+ .all(|i| *i < nb)+}++/// Computes the distance between two point-cloud proxies, warm-started by `cache`.+///+/// `pos12` is the pose of the second proxy relative to the first; the query runs entirely in+/// the first proxy’s local frame. When `use_radii` is `false` the proxy radii are ignored+/// (core-shape distance), which is what the time-of-impact loop uses.+#[cfg(feature = "dim2")]+pub fn proxy_distance(+ pos12: &Pose,+ proxy_a: &ToiProxy,+ proxy_b: &ToiProxy,+ use_radii: bool,+ cache: &mut SimplexCache,+) -> ProxyDistanceOutput {+ let points_a = proxy_a.points();+ let points_b = proxy_b.points();+ let point_b_in_a = |i: u32| pos12.transform_point(points_b[i as usize]);++ let mut output = ProxyDistanceOutput::default();++ // Initialize the simplex from the cache.+ let mut simplex = [SimplexVertex::default(); 3];+ let mut count = if cache_is_valid(cache, proxy_a, proxy_b) {+ cache.count as usize+ } else {+ 0+ };+ for (i, v) in simplex.iter_mut().enumerate().take(count) {+ v.index_a = cache.index_a[i];+ v.index_b = cache.index_b[i];+ v.wa = points_a[v.index_a as usize];+ v.wb = point_b_in_a(v.index_b);+ v.w = v.wa - v.wb;+ // Invalid coefficient; set by the simplex solvers.+ v.a = -1.0;+ }++ if count == 0 {+ let v = &mut simplex[0];+ v.index_a = 0;+ v.index_b = 0;+ v.wa = points_a[0];+ v.wb = point_b_in_a(0);+ v.w = v.wa - v.wb;+ v.a = 1.0;+ count = 1;+ }++ let mut non_unit_normal = Vector::ZERO;+ let mut save_a = [0u32; 3];+ let mut save_b = [0u32; 3];++ // Main iteration loop. All computations are done in frame A.+ const MAX_ITERATIONS: u32 = 20;+ let mut iteration = 0;+ while iteration < MAX_ITERATIONS {+ // Copy simplex indices so we can identify duplicates.+ let save_count = count;+ for i in 0..save_count {+ save_a[i] = simplex[i].index_a;+ save_b[i] = simplex[i].index_b;+ }++ let d = match count {+ 1 => -simplex[0].w,+ 2 => solve_simplex2(&mut simplex, &mut count),+ 3 => solve_simplex3(&mut simplex, &mut count),+ _ => unreachable!(),+ };++ // If we have 3 points, then the origin is in the corresponding triangle.+ if count == 3 {+ let (pa, pb) = witness_points(&simplex, count);+ output.point_a = pa;+ output.point_b = pb;+ output.iterations = iteration;+ return output;+ }++ // Ensure the search direction is numerically fit; a degenerate direction means the+ // origin is contained by a segment, i.e. the shapes are overlapped.+ if d.dot(d) < Real::EPSILON * Real::EPSILON {+ let (pa, pb) = witness_points(&simplex, count);+ output.point_a = pa;+ output.point_b = pb;+ output.iterations = iteration;+ return output;+ }++ non_unit_normal = d;++ // Compute a tentative new simplex vertex using support points:+ // support = support(a, d) - support(b, -d).+ let index_a = proxy_a.support(d);+ let index_b = proxy_b.support(pos12.rotation.inverse_transform_vector(-d));+ let vertex = &mut simplex[count];+ vertex.index_a = index_a;+ vertex.wa = points_a[index_a as usize];+ vertex.index_b = index_b;+ vertex.wb = point_b_in_a(index_b);+ vertex.w = vertex.wa - vertex.wb;++ // Iteration count is equated to the number of support point calls.+ iteration += 1;++ // Check for duplicate support points. This is the main termination criteria.+ let duplicate = (0..save_count).any(|i| index_a == save_a[i] && index_b == save_b[i]);+ if duplicate {+ break;+ }++ // New vertex is valid and needed.+ count += 1;+ }++ let normal = non_unit_normal.normalize_or_zero();+ let (pa, pb) = witness_points(&simplex, count);+ output.normal = normal;+ output.distance = pa.distance(pb);+ output.point_a = pa;+ output.point_b = pb;+ output.iterations = iteration;++ // Cache the simplex.+ cache.count = count as u8;+ for (i, v) in simplex.iter().enumerate().take(count) {+ cache.index_a[i] = v.index_a;+ cache.index_b[i] = v.index_b;+ }++ // Apply radii if requested.+ if use_radii {+ let radius_a = proxy_a.radius;+ let radius_b = proxy_b.radius;+ output.distance = (output.distance - radius_a - radius_b).max(0.0);++ // Keep closest points on perimeter even if overlapped, this way the points move+ // smoothly.+ output.point_a += radius_a * normal;+ output.point_b -= radius_b * normal;+ }++ output+}++#[cfg(feature = "dim2")]+fn witness_points(simplex: &[SimplexVertex; 3], count: usize) -> (Vector, Vector) {+ match count {+ 1 => (simplex[0].wa, simplex[0].wb),+ 2 => (+ simplex[0].a * simplex[0].wa + simplex[1].a * simplex[1].wa,+ simplex[0].a * simplex[0].wb + simplex[1].a * simplex[1].wb,+ ),+ 3 => {+ let pa = simplex[0].a * simplex[0].wa+ + simplex[1].a * simplex[1].wa+ + simplex[2].a * simplex[2].wa;+ (pa, pa)+ }+ _ => unreachable!(),+ }+}++// Returns a vector pointing towards the origin, reducing the simplex if needed.+#[cfg(feature = "dim2")]+fn solve_simplex2(simplex: &mut [SimplexVertex; 3], count: &mut usize) -> Vector {+ let w1 = simplex[0].w;+ let w2 = simplex[1].w;+ let e12 = w2 - w1;++ // w1 region+ let d12_2 = -w1.dot(e12);+ if d12_2 <= 0.0 {+ // a2 <= 0, so we clamp it to 0+ simplex[0].a = 1.0;+ *count = 1;+ return -w1;+ }++ // w2 region+ let d12_1 = w2.dot(e12);+ if d12_1 <= 0.0 {+ // a1 <= 0, so we clamp it to 0+ simplex[1].a = 1.0;+ *count = 1;+ simplex[0] = simplex[1];+ return -w2;+ }++ // Must be in e12 region.+ let inv_d12 = 1.0 / (d12_1 + d12_2);+ simplex[0].a = d12_1 * inv_d12;+ simplex[1].a = d12_2 * inv_d12;+ *count = 2;+ // cross(cross(w1 + w2, e12), e12)+ let s = (w1 + w2).perp_dot(e12);+ Vector::new(-s * e12.y, s * e12.x)+}++#[cfg(feature = "dim2")]+fn solve_simplex3(simplex: &mut [SimplexVertex; 3], count: &mut usize) -> Vector {+ let w1 = simplex[0].w;+ let w2 = simplex[1].w;+ let w3 = simplex[2].w;++ // Edge12: a3 = 0+ let e12 = w2 - w1;+ let w1e12 = w1.dot(e12);+ let w2e12 = w2.dot(e12);+ let d12_1 = w2e12;+ let d12_2 = -w1e12;++ // Edge13: a2 = 0+ let e13 = w3 - w1;+ let w1e13 = w1.dot(e13);+ let w3e13 = w3.dot(e13);+ let d13_1 = w3e13;+ let d13_2 = -w1e13;++ // Edge23: a1 = 0+ let e23 = w3 - w2;+ let w2e23 = w2.dot(e23);+ let w3e23 = w3.dot(e23);+ let d23_1 = w3e23;+ let d23_2 = -w2e23;++ // Triangle123+ let n123 = e12.perp_dot(e13);+ let d123_1 = n123 * w2.perp_dot(w3);+ let d123_2 = n123 * w3.perp_dot(w1);+ let d123_3 = n123 * w1.perp_dot(w2);++ // w1 region+ if d12_2 <= 0.0 && d13_2 <= 0.0 {+ simplex[0].a = 1.0;+ *count = 1;+ return -w1;+ }++ // e12+ if d12_1 > 0.0 && d12_2 > 0.0 && d123_3 <= 0.0 {+ let inv_d12 = 1.0 / (d12_1 + d12_2);+ simplex[0].a = d12_1 * inv_d12;+ simplex[1].a = d12_2 * inv_d12;+ *count = 2;+ let s = (w1 + w2).perp_dot(e12);+ return Vector::new(-s * e12.y, s * e12.x);+ }++ // e13+ if d13_1 > 0.0 && d13_2 > 0.0 && d123_2 <= 0.0 {+ let inv_d13 = 1.0 / (d13_1 + d13_2);+ simplex[0].a = d13_1 * inv_d13;+ simplex[2].a = d13_2 * inv_d13;+ *count = 2;+ simplex[1] = simplex[2];+ let s = (w1 + w3).perp_dot(e13);+ return Vector::new(-s * e13.y, s * e13.x);+ }++ // w2 region+ if d12_1 <= 0.0 && d23_2 <= 0.0 {+ simplex[1].a = 1.0;+ *count = 1;+ simplex[0] = simplex[1];+ return -w2;+ }++ // w3 region+ if d13_1 <= 0.0 && d23_1 <= 0.0 {+ simplex[2].a = 1.0;+ *count = 1;+ simplex[0] = simplex[2];+ return -w3;+ }++ // e23+ if d23_1 > 0.0 && d23_2 > 0.0 && d123_1 <= 0.0 {+ let inv_d23 = 1.0 / (d23_1 + d23_2);+ simplex[1].a = d23_1 * inv_d23;+ simplex[2].a = d23_2 * inv_d23;+ *count = 2;+ simplex[0] = simplex[2];+ let s = (w2 + w3).perp_dot(e23);+ return Vector::new(-s * e23.y, s * e23.x);+ }++ // Must be in triangle123+ let inv_d123 = 1.0 / (d123_1 + d123_2 + d123_3);+ simplex[0].a = d123_1 * inv_d123;+ simplex[1].a = d123_2 * inv_d123;+ simplex[2].a = d123_3 * inv_d123;+ *count = 3;++ // No search direction+ Vector::ZERO+}++// ==================== 3D ====================++#[cfg(feature = "dim3")]+const MAX_GJK_ITERATIONS: u32 = 32;++#[cfg(feature = "dim3")]+fn barycentric_coords_edge(a: Vector, b: Vector) -> [Real; 3] {+ let ab = b - a;+ // Last element is divisor+ [b.dot(ab), -a.dot(ab), ab.dot(ab)]+}++#[cfg(feature = "dim3")]+fn barycentric_coords_tri(a: Vector, b: Vector, c: Vector) -> [Real; 4] {+ let ab = b - a;+ let ac = c - a;++ let b_x_c = b.cross(c);+ let c_x_a = c.cross(a);+ let a_x_b = a.cross(b);++ let ab_x_ac = ab.cross(ac);++ // Last element is divisor+ [+ b_x_c.dot(ab_x_ac),+ c_x_a.dot(ab_x_ac),+ a_x_b.dot(ab_x_ac),+ ab_x_ac.dot(ab_x_ac),+ ]+}++#[cfg(feature = "dim3")]+fn scalar_triple_product(a: Vector, b: Vector, c: Vector) -> Real {+ a.cross(b).dot(c)+}++#[cfg(feature = "dim3")]+fn barycentric_coords_tet(a: Vector, b: Vector, c: Vector, d: Vector) -> [Real; 5] {+ let ab = b - a;+ let ac = c - a;+ let ad = d - a;++ // Last element is divisor (forced to be positive)+ let divisor = scalar_triple_product(ab, ac, ad);+ let sign = if divisor < 0.0 { -1.0 } else { 1.0 };++ [+ sign * scalar_triple_product(b, c, d),+ sign * scalar_triple_product(a, d, c),+ sign * scalar_triple_product(a, b, d),+ sign * scalar_triple_product(a, c, b),+ sign * divisor,+ ]+}++#[cfg(feature = "dim3")]+fn simplex_metric(simplex: &[SimplexVertex; 4], count: usize) -> Real {+ match count {+ 1 => 0.0,+ 2 => simplex[0].w.distance(simplex[1].w),+ 3 => {+ let a = simplex[0].w;+ let b = simplex[1].w;+ let c = simplex[2].w;+ (b - a).cross(c - a).length() / 2.0+ }+ 4 => {+ let a = simplex[0].w;+ let b = simplex[1].w;+ let c = simplex[2].w;+ let d = simplex[3].w;+ scalar_triple_product(b - a, c - a, d - a) / 6.0+ }+ _ => unreachable!(),+ }+}++#[cfg(feature = "dim3")]+fn witness_points3(simplex: &[SimplexVertex; 4], count: usize) -> (Vector, Vector) {+ let vs = simplex;+ match count {+ 1 => (vs[0].wa, vs[0].wb),+ 2 => (+ vs[0].a * vs[0].wa + vs[1].a * vs[1].wa,+ vs[0].a * vs[0].wb + vs[1].a * vs[1].wb,+ ),+ 3 => (+ vs[0].a * vs[0].wa + vs[1].a * vs[1].wa + vs[2].a * vs[2].wa,+ vs[0].a * vs[0].wb + vs[1].a * vs[1].wb + vs[2].a * vs[2].wb,+ ),+ 4 => {+ // Force identical points and *zero* distance+ let sum =+ vs[0].a * vs[0].wa + vs[1].a * vs[1].wa + vs[2].a * vs[2].wa + vs[3].a * vs[3].wa;+ (sum, sum)+ }+ _ => unreachable!(),+ }+}++/// Solves the 2-simplex. Returns `false` when the barycentric divisor degenerates.+#[cfg(feature = "dim3")]+fn solve_simplex2_3d(simplex: &mut [SimplexVertex; 4], count: &mut usize) -> bool {+ let a = simplex[0].w;+ let b = simplex[1].w;+ let ab = b - a;++ let divisor = ab.dot(ab);+ let u = b.dot(ab);+ let v = -a.dot(ab);++ // V(A)+ if v <= 0.0 {+ *count = 1;+ simplex[0].a = 1.0;+ return true;+ }++ // V(B)+ if u <= 0.0 {+ *count = 1;+ simplex[0] = simplex[1];+ simplex[0].a = 1.0;+ return true;+ }++ // Edge region+ if divisor <= 0.0 {+ return false;+ }++ let denominator = 1.0 / divisor;+ simplex[0].a = denominator * u;+ simplex[1].a = denominator * v;+ true+}++#[cfg(feature = "dim3")]+fn solve_simplex3_3d(simplex: &mut [SimplexVertex; 4], count: &mut usize) -> bool {+ let v1 = simplex[0];+ let v2 = simplex[1];+ let v3 = simplex[2];++ let w_ab = barycentric_coords_edge(v1.w, v2.w);+ let w_bc = barycentric_coords_edge(v2.w, v3.w);+ let w_ca = barycentric_coords_edge(v3.w, v1.w);++ // VR(A)+ if w_ab[1] <= 0.0 && w_ca[0] <= 0.0 {+ *count = 1;+ simplex[0] = v1;+ simplex[0].a = 1.0;+ return true;+ }++ // VR(B)+ if w_bc[1] <= 0.0 && w_ab[0] <= 0.0 {+ *count = 1;+ simplex[0] = v2;+ simplex[0].a = 1.0;+ return true;+ }++ // VR(C)+ if w_ca[1] <= 0.0 && w_bc[0] <= 0.0 {+ *count = 1;+ simplex[0] = v3;+ simplex[0].a = 1.0;+ return true;+ }++ let w_abc = barycentric_coords_tri(v1.w, v2.w, v3.w);++ // VR(AB)+ if w_abc[2] <= 0.0 && w_ab[0] > 0.0 && w_ab[1] > 0.0 {+ *count = 2;+ simplex[0] = v1;+ simplex[1] = v2;+ let divisor = w_ab[2];+ if divisor <= 0.0 {+ return false;+ }+ simplex[0].a = w_ab[0] / divisor;+ simplex[1].a = w_ab[1] / divisor;+ return true;+ }++ // VR(BC)+ if w_abc[0] <= 0.0 && w_bc[0] > 0.0 && w_bc[1] > 0.0 {+ *count = 2;+ simplex[0] = v2;+ simplex[1] = v3;+ let divisor = w_bc[2];+ if divisor <= 0.0 {+ return false;+ }+ simplex[0].a = w_bc[0] / divisor;+ simplex[1].a = w_bc[1] / divisor;+ return true;+ }++ // VR(CA)+ if w_abc[1] <= 0.0 && w_ca[0] > 0.0 && w_ca[1] > 0.0 {+ *count = 2;+ simplex[0] = v3;+ simplex[1] = v1;+ let divisor = w_ca[2];+ if divisor <= 0.0 {+ return false;+ }+ simplex[0].a = w_ca[0] / divisor;+ simplex[1].a = w_ca[1] / divisor;+ return true;+ }++ // Face region+ let divisor = w_abc[3];+ if divisor <= 0.0 {+ return false;+ }++ // VR(ABC)+ simplex[0].a = w_abc[0] / divisor;+ simplex[1].a = w_abc[1] / divisor;+ simplex[2].a = w_abc[2] / divisor;+ true+}++#[cfg(feature = "dim3")]+fn solve_simplex4_3d(simplex: &mut [SimplexVertex; 4], count: &mut usize) -> bool {+ let vertex_a = simplex[0];+ let vertex_b = simplex[1];+ let vertex_c = simplex[2];+ let vertex_d = simplex[3];++ let w_ab = barycentric_coords_edge(vertex_a.w, vertex_b.w);+ let w_ac = barycentric_coords_edge(vertex_a.w, vertex_c.w);+ let w_ad = barycentric_coords_edge(vertex_a.w, vertex_d.w);+ let w_bc = barycentric_coords_edge(vertex_b.w, vertex_c.w);+ let w_cd = barycentric_coords_edge(vertex_c.w, vertex_d.w);+ let w_db = barycentric_coords_edge(vertex_d.w, vertex_b.w);++ // VR(A)+ if w_ab[1] <= 0.0 && w_ac[1] <= 0.0 && w_ad[1] <= 0.0 {+ *count = 1;+ simplex[0] = vertex_a;+ simplex[0].a = 1.0;+ return true;+ }++ // VR(B)+ if w_ab[0] <= 0.0 && w_db[0] <= 0.0 && w_bc[1] <= 0.0 {+ *count = 1;+ simplex[0] = vertex_b;+ simplex[0].a = 1.0;+ return true;+ }++ // VR(C)+ if w_ac[0] <= 0.0 && w_bc[0] <= 0.0 && w_cd[1] <= 0.0 {+ *count = 1;+ simplex[0] = vertex_c;+ simplex[0].a = 1.0;+ return true;+ }++ // VR(D)+ if w_ad[0] <= 0.0 && w_cd[0] <= 0.0 && w_db[1] <= 0.0 {+ *count = 1;+ simplex[0] = vertex_d;+ simplex[0].a = 1.0;+ return true;+ }++ let w_acb = barycentric_coords_tri(vertex_a.w, vertex_c.w, vertex_b.w);+ let w_abd = barycentric_coords_tri(vertex_a.w, vertex_b.w, vertex_d.w);+ let w_adc = barycentric_coords_tri(vertex_a.w, vertex_d.w, vertex_c.w);+ let w_bcd = barycentric_coords_tri(vertex_b.w, vertex_c.w, vertex_d.w);++ // VR(AB)+ if w_abd[2] <= 0.0 && w_acb[1] <= 0.0 && w_ab[0] > 0.0 && w_ab[1] > 0.0 {+ *count = 2;+ simplex[0] = vertex_a;+ simplex[1] = vertex_b;+ let divisor = w_ab[2];+ if divisor <= 0.0 {+ return false;+ }+ simplex[0].a = w_ab[0] / divisor;+ simplex[1].a = w_ab[1] / divisor;+ return true;+ }++ // VR(AC)+ if w_acb[2] <= 0.0 && w_adc[1] <= 0.0 && w_ac[0] > 0.0 && w_ac[1] > 0.0 {+ *count = 2;+ simplex[0] = vertex_a;+ simplex[1] = vertex_c;+ let divisor = w_ac[2];+ if divisor <= 0.0 {+ return false;+ }+ simplex[0].a = w_ac[0] / divisor;+ simplex[1].a = w_ac[1] / divisor;+ return true;+ }++ // VR(AD)+ if w_adc[2] <= 0.0 && w_abd[1] <= 0.0 && w_ad[0] > 0.0 && w_ad[1] > 0.0 {+ *count = 2;+ simplex[0] = vertex_a;+ simplex[1] = vertex_d;+ let divisor = w_ad[2];+ if divisor <= 0.0 {+ return false;+ }+ simplex[0].a = w_ad[0] / divisor;+ simplex[1].a = w_ad[1] / divisor;+ return true;+ }++ // VR(BC)+ if w_acb[0] <= 0.0 && w_bcd[2] <= 0.0 && w_bc[0] > 0.0 && w_bc[1] > 0.0 {+ *count = 2;+ simplex[0] = vertex_b;+ simplex[1] = vertex_c;+ let divisor = w_bc[2];+ if divisor <= 0.0 {+ return false;+ }+ simplex[0].a = w_bc[0] / divisor;+ simplex[1].a = w_bc[1] / divisor;+ return true;+ }++ // VR(CD)+ if w_adc[0] <= 0.0 && w_bcd[0] <= 0.0 && w_cd[0] > 0.0 && w_cd[1] > 0.0 {+ *count = 2;+ simplex[0] = vertex_c;+ simplex[1] = vertex_d;+ let divisor = w_cd[2];+ if divisor <= 0.0 {+ return false;+ }+ simplex[0].a = w_cd[0] / divisor;+ simplex[1].a = w_cd[1] / divisor;+ return true;+ }++ // VR(DB)+ if w_abd[0] <= 0.0 && w_bcd[1] <= 0.0 && w_db[0] > 0.0 && w_db[1] > 0.0 {+ *count = 2;+ simplex[0] = vertex_d;+ simplex[1] = vertex_b;+ let divisor = w_db[2];+ if divisor <= 0.0 {+ return false;+ }+ simplex[0].a = w_db[0] / divisor;+ simplex[1].a = w_db[1] / divisor;+ return true;+ }++ let w_abcd = barycentric_coords_tet(vertex_a.w, vertex_b.w, vertex_c.w, vertex_d.w);++ // VR(ACB)+ if w_abcd[3] < 0.0 && w_acb[0] > 0.0 && w_acb[1] > 0.0 && w_acb[2] > 0.0 {+ *count = 3;+ simplex[0] = vertex_a;+ simplex[1] = vertex_c;+ simplex[2] = vertex_b;+ let divisor = w_acb[3];+ if divisor <= 0.0 {+ return false;+ }+ simplex[0].a = w_acb[0] / divisor;+ simplex[1].a = w_acb[1] / divisor;+ simplex[2].a = w_acb[2] / divisor;+ return true;+ }++ // VR(ABD)+ if w_abcd[2] < 0.0 && w_abd[0] > 0.0 && w_abd[1] > 0.0 && w_abd[2] > 0.0 {+ *count = 3;+ simplex[0] = vertex_a;+ simplex[1] = vertex_b;+ simplex[2] = vertex_d;+ let divisor = w_abd[3];+ if divisor <= 0.0 {+ return false;+ }+ simplex[0].a = w_abd[0] / divisor;+ simplex[1].a = w_abd[1] / divisor;+ simplex[2].a = w_abd[2] / divisor;+ return true;+ }++ // VR(ADC)+ if w_abcd[1] < 0.0 && w_adc[0] > 0.0 && w_adc[1] > 0.0 && w_adc[2] > 0.0 {+ *count = 3;+ simplex[0] = vertex_a;+ simplex[1] = vertex_d;+ simplex[2] = vertex_c;+ let divisor = w_adc[3];+ if divisor <= 0.0 {+ return false;+ }+ simplex[0].a = w_adc[0] / divisor;+ simplex[1].a = w_adc[1] / divisor;+ simplex[2].a = w_adc[2] / divisor;+ return true;+ }++ // VR(BCD)+ if w_abcd[0] < 0.0 && w_bcd[0] > 0.0 && w_bcd[1] > 0.0 && w_bcd[2] > 0.0 {+ *count = 3;+ simplex[0] = vertex_b;+ simplex[1] = vertex_c;+ simplex[2] = vertex_d;+ let divisor = w_bcd[3];+ if divisor <= 0.0 {+ return false;+ }+ simplex[0].a = w_bcd[0] / divisor;+ simplex[1].a = w_bcd[1] / divisor;+ simplex[2].a = w_bcd[2] / divisor;+ return true;+ }++ // *** Inside tetrahedron ***+ let divisor = w_abcd[4];+ if divisor <= 0.0 {+ return false;+ }++ // VR(ABCD)+ simplex[0].a = w_abcd[0] / divisor;+ simplex[1].a = w_abcd[1] / divisor;+ simplex[2].a = w_abcd[2] / divisor;+ simplex[3].a = w_abcd[3] / divisor;+ true+}++/// Computes the distance between two point-cloud proxies, warm-started by `cache`.+///+/// `pos12` is the pose of the second proxy relative to the first; the query runs entirely in+/// the first proxy’s local frame. When `use_radii` is `false` the proxy radii are ignored+/// (core-shape distance), which is what the time-of-impact loop uses.+#[cfg(feature = "dim3")]+pub fn proxy_distance(+ pos12: &Pose,+ proxy_a: &ToiProxy,+ proxy_b: &ToiProxy,+ use_radii: bool,+ cache: &mut SimplexCache,+) -> ProxyDistanceOutput {+ let points_a = proxy_a.points();+ let points_b = proxy_b.points();+ let point_b_in_a = |i: u32| pos12.transform_point(points_b[i as usize]);++ let mut output = ProxyDistanceOutput::default();++ // Compute initial simplex from cache. Note that in 3D the CSO points are w = wB - wA+ // (the opposite of the 2D convention).+ let mut simplex = [SimplexVertex::default(); 4];+ let mut count = if cache_is_valid(cache, proxy_a, proxy_b) {+ cache.count as usize+ } else {+ 0+ };+ for (i, v) in simplex.iter_mut().enumerate().take(count) {+ v.index_a = cache.index_a[i];+ v.index_b = cache.index_b[i];+ v.wa = points_a[v.index_a as usize];+ v.wb = point_b_in_a(v.index_b);+ v.w = v.wb - v.wa;+ v.a = 0.0;+ }++ // Compute the new simplex metric; if it is substantially different than the old metric+ // flush the simplex.+ if count > 0 {+ let metric1 = cache.metric;+ let metric2 = simplex_metric(&simplex, count);+ if 2.0 * metric1 < metric2 || metric2 < 0.5 * metric1 || metric2 < Real::EPSILON {+ count = 0;+ }+ }++ // If the cache is invalid or empty.+ if count == 0 {+ let v = &mut simplex[0];+ v.index_a = 0;+ v.index_b = 0;+ v.wa = points_a[0];+ v.wb = point_b_in_a(0);+ v.w = v.wb - v.wa;+ v.a = 0.0;+ count = 1;+ }++ let mut backup = simplex;+ let mut backup_count = 0usize;++ // Keep track of squared distance.+ let mut distance_sq = Real::MAX;+ let mut normal = Vector::ZERO;++ // Run GJK.+ let mut iteration = 0;+ while iteration < MAX_GJK_ITERATIONS {+ // Solve simplex.+ let solved = match count {+ 1 => {+ simplex[0].a = 1.0;+ true+ }+ 2 => solve_simplex2_3d(&mut simplex, &mut count),+ 3 => solve_simplex3_3d(&mut simplex, &mut count),+ 4 => solve_simplex4_3d(&mut simplex, &mut count),+ _ => unreachable!(),+ };++ if !solved {+ // No progress - reconstruct last simplex.+ if backup_count == 0 {+ break;+ }+ simplex = backup;+ count = backup_count;+ break;+ }++ if count == 4 {+ // Overlap+ let (pa, pb) = witness_points3(&simplex, count);+ output.point_a = pa;+ output.point_b = pb;+ output.iterations = iteration;+ return output;+ }++ // Assure distance progression.+ let old_distance_sq = distance_sq;++ // Compute closest point.+ let closest_point = match count {+ 1 => simplex[0].w,+ 2 => simplex[0].a * simplex[0].w + simplex[1].a * simplex[1].w,+ 3 => {+ simplex[0].a * simplex[0].w+ + simplex[1].a * simplex[1].w+ + simplex[2].a * simplex[2].w+ }+ _ => unreachable!(),+ };++ distance_sq = closest_point.dot(closest_point);++ if distance_sq >= old_distance_sq {+ // No progress - reconstruct last simplex.+ if backup_count == 0 {+ break;+ }+ simplex = backup;+ count = backup_count;+ break;+ }++ // Build new tentative support point.+ let search_direction = match count {+ 1 => -simplex[0].w,+ 2 => {+ // v = (AB x AO) x AB+ let a = simplex[0].w;+ let b = simplex[1].w;+ let ab = b - a;+ ab.cross(-a).cross(ab)+ }+ 3 => {+ // v = AB x AC or v = AC x AB+ let a = simplex[0].w;+ let b = simplex[1].w;+ let c = simplex[2].w;+ let n = (b - a).cross(c - a);+ if n.dot(a) < 0.0 {+ n+ } else {+ -n+ }+ }+ _ => unreachable!(),+ };++ if search_direction.length_squared() < 1000.0 * Real::MIN_POSITIVE {+ // The origin is probably contained by a line segment or triangle.+ // Thus the shapes are overlapped.+ let (pa, pb) = witness_points3(&simplex, count);+ output.point_a = pa;+ output.point_b = pb;+ output.iterations = iteration;+ return output;+ }++ normal = -search_direction;++ // Get new support points.+ let index_a = proxy_a.support(-search_direction);+ let support_a = points_a[index_a as usize];+ let index_b = proxy_b.support(pos12.rotation.inverse() * search_direction);+ let support_b = point_b_in_a(index_b);++ // Save current simplex and add new vertex - this can fail if we detect cycling.+ backup = simplex;+ backup_count = count;++ // Check for duplicate support points. This is the main termination criteria.+ let duplicate =+ (0..count).any(|i| simplex[i].index_a == index_a && simplex[i].index_b == index_b);+ if duplicate {+ break;+ }++ simplex[count].index_a = index_a;+ simplex[count].index_b = index_b;+ simplex[count].wa = support_a;+ simplex[count].wb = support_b;+ simplex[count].w = support_b - support_a;+ count += 1;++ iteration += 1;+ }++ let normal = normal.normalize_or_zero();+ if normal == Vector::ZERO {+ // Treat as overlap.+ output.iterations = iteration;+ return output;+ }++ // Build witness points and save cache.+ let (pa, pb) = witness_points3(&simplex, count);+ cache.metric = simplex_metric(&simplex, count);+ cache.count = count.min(3) as u8;+ for (i, v) in simplex.iter().enumerate().take(count.min(3)) {+ cache.index_a[i] = v.index_a;+ cache.index_b[i] = v.index_b;+ }++ // Results stay in frame A.+ output.point_a = pa;+ output.point_b = pb;+ output.distance = pa.distance(pb);+ output.normal = normal;+ output.iterations = iteration;++ // Apply radii if requested.+ if use_radii {+ let ra = proxy_a.radius;+ let rb = proxy_b.radius;+ output.distance = (output.distance - ra - rb).max(0.0);++ // Keep closest points on perimeter even if overlapped, this way the points move+ // smoothly.+ output.point_a += ra * normal;+ output.point_b -= rb * normal;+ }++ output+}diff --git a/renderer/third_party/parry3d/src/query/sweep_toi/separation.rs b/renderer/third_party/parry3d/src/query/sweep_toi/separation.rsnew file mode 100644index 0000000..e6088e2--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sweep_toi/separation.rs@@ -0,0 +1,597 @@+//! Separation functions used by the conservative-advancement time-of-impact loop.+//!+//! A separation function measures the signed separation of two swept proxies along a+//! progressively chosen axis, either re-picking the deepest support points+//! ([`SeparationFunction::find_min_separation`]) or holding witness features fixed for root+//! finding ([`SeparationFunction::evaluate`]).++use super::proxy_distance::SimplexCache;+use super::sweep::{inv_rotate_vec, rotate_vec, Sweep};+use super::toi_proxy::ToiProxy;+use crate::math::{Real, Vector};++/// Sentinel index meaning "no witness index" (face types keep a fixed local point instead).+pub(crate) const INVALID_INDEX: u32 = u32::MAX;++#[cfg(feature = "dim2")]+#[derive(Copy, Clone, PartialEq)]+enum SeparationType {+ Points,+ FaceA,+ FaceB,+}++#[cfg(feature = "dim2")]+pub(crate) struct SeparationFunction<'a, 'b> {+ proxy_a: &'a ToiProxy<'b>,+ proxy_b: &'a ToiProxy<'b>,+ sweep_a: Sweep,+ sweep_b: Sweep,+ local_point: Vector,+ axis: Vector,+ ty: SeparationType,+}++#[cfg(feature = "dim2")]+impl<'a, 'b> SeparationFunction<'a, 'b> {+ pub fn new(+ cache: &SimplexCache,+ proxy_a: &'a ToiProxy<'b>,+ sweep_a: &Sweep,+ proxy_b: &'a ToiProxy<'b>,+ sweep_b: &Sweep,+ _world_normal: Vector,+ t1: Real,+ ) -> Self {+ let count = cache.count as usize;+ debug_assert!(0 < count && count < 3);++ let xf_a = sweep_a.transform_at(t1);+ let xf_b = sweep_b.transform_at(t1);++ if count == 1 {+ let local_point_a = proxy_a.points()[cache.index_a[0] as usize];+ let local_point_b = proxy_b.points()[cache.index_b[0] as usize];+ let point_a = xf_a.transform_point(local_point_a);+ let point_b = xf_b.transform_point(local_point_b);+ return Self {+ proxy_a,+ proxy_b,+ sweep_a: *sweep_a,+ sweep_b: *sweep_b,+ local_point: Vector::ZERO,+ axis: (point_b - point_a).normalize_or_zero(),+ ty: SeparationType::Points,+ };+ }++ if cache.index_a[0] == cache.index_a[1] {+ // Two points on B and one on A.+ let local_point_b1 = proxy_b.points()[cache.index_b[0] as usize];+ let local_point_b2 = proxy_b.points()[cache.index_b[1] as usize];++ // Perpendicular of the edge: cross(edge, 1.0).+ let edge = local_point_b2 - local_point_b1;+ let mut axis = Vector::new(edge.y, -edge.x).normalize_or_zero();+ let normal = rotate_vec(&xf_b.rotation, axis);++ let local_point = 0.5 * (local_point_b1 + local_point_b2);+ let point_b = xf_b.transform_point(local_point);++ let local_point_a = proxy_a.points()[cache.index_a[0] as usize];+ let point_a = xf_a.transform_point(local_point_a);++ if (point_a - point_b).dot(normal) < 0.0 {+ axis = -axis;+ }++ Self {+ proxy_a,+ proxy_b,+ sweep_a: *sweep_a,+ sweep_b: *sweep_b,+ local_point,+ axis,+ ty: SeparationType::FaceB,+ }+ } else {+ // Two points on A and one or two points on B.+ let local_point_a1 = proxy_a.points()[cache.index_a[0] as usize];+ let local_point_a2 = proxy_a.points()[cache.index_a[1] as usize];++ let edge = local_point_a2 - local_point_a1;+ let mut axis = Vector::new(edge.y, -edge.x).normalize_or_zero();+ let normal = rotate_vec(&xf_a.rotation, axis);++ let local_point = 0.5 * (local_point_a1 + local_point_a2);+ let point_a = xf_a.transform_point(local_point);++ let local_point_b = proxy_b.points()[cache.index_b[0] as usize];+ let point_b = xf_b.transform_point(local_point_b);++ if (point_b - point_a).dot(normal) < 0.0 {+ axis = -axis;+ }++ Self {+ proxy_a,+ proxy_b,+ sweep_a: *sweep_a,+ sweep_b: *sweep_b,+ local_point,+ axis,+ ty: SeparationType::FaceA,+ }+ }+ }++ /// Finds the deepest support points at time `t` and returns their signed separation.+ pub fn find_min_separation(&self, t: Real) -> (Real, u32, u32) {+ let xf_a = self.sweep_a.transform_at(t);+ let xf_b = self.sweep_b.transform_at(t);++ match self.ty {+ SeparationType::Points => {+ let axis_a = inv_rotate_vec(&xf_a.rotation, self.axis);+ let axis_b = inv_rotate_vec(&xf_b.rotation, -self.axis);++ let index_a = self.proxy_a.support(axis_a);+ let index_b = self.proxy_b.support(axis_b);++ let point_a = xf_a.transform_point(self.proxy_a.points()[index_a as usize]);+ let point_b = xf_b.transform_point(self.proxy_b.points()[index_b as usize]);++ ((point_b - point_a).dot(self.axis), index_a, index_b)+ }+ SeparationType::FaceA => {+ let normal = rotate_vec(&xf_a.rotation, self.axis);+ let point_a = xf_a.transform_point(self.local_point);++ let axis_b = inv_rotate_vec(&xf_b.rotation, -normal);+ let index_b = self.proxy_b.support(axis_b);+ let point_b = xf_b.transform_point(self.proxy_b.points()[index_b as usize]);++ ((point_b - point_a).dot(normal), INVALID_INDEX, index_b)+ }+ SeparationType::FaceB => {+ let normal = rotate_vec(&xf_b.rotation, self.axis);+ let point_b = xf_b.transform_point(self.local_point);++ let axis_a = inv_rotate_vec(&xf_a.rotation, -normal);+ let index_a = self.proxy_a.support(axis_a);+ let point_a = xf_a.transform_point(self.proxy_a.points()[index_a as usize]);++ ((point_a - point_b).dot(normal), index_a, INVALID_INDEX)+ }+ }+ }++ /// Evaluates the separation of fixed witness features at time `t`.+ pub fn evaluate(&self, index_a: u32, index_b: u32, t: Real) -> Real {+ let xf_a = self.sweep_a.transform_at(t);+ let xf_b = self.sweep_b.transform_at(t);++ match self.ty {+ SeparationType::Points => {+ let point_a = xf_a.transform_point(self.proxy_a.points()[index_a as usize]);+ let point_b = xf_b.transform_point(self.proxy_b.points()[index_b as usize]);+ (point_b - point_a).dot(self.axis)+ }+ SeparationType::FaceA => {+ let normal = rotate_vec(&xf_a.rotation, self.axis);+ let point_a = xf_a.transform_point(self.local_point);+ let point_b = xf_b.transform_point(self.proxy_b.points()[index_b as usize]);+ (point_b - point_a).dot(normal)+ }+ SeparationType::FaceB => {+ let normal = rotate_vec(&xf_b.rotation, self.axis);+ let point_b = xf_b.transform_point(self.local_point);+ let point_a = xf_a.transform_point(self.proxy_a.points()[index_a as usize]);+ (point_a - point_b).dot(normal)+ }+ }+ }++ /// Whether this function uses the edge/edge cross-product axis (3D only; always false in+ /// 2D).+ pub fn uses_edge_axis(&self) -> bool {+ false+ }++ /// Converts an edge-axis function to a fixed world axis (3D only; no-op in 2D).+ pub fn force_fixed_axis(&mut self, _t: Real) {}+}++// ==================== 3D ====================++#[cfg(feature = "dim3")]+#[derive(Copy, Clone, PartialEq)]+enum SeparationType {+ Vertices,+ Edges,+ FaceA,+ FaceB,+}++#[cfg(feature = "dim3")]+pub(crate) struct SeparationFunction<'a, 'b> {+ proxy_a: &'a ToiProxy<'b>,+ proxy_b: &'a ToiProxy<'b>,+ sweep_a: Sweep,+ sweep_b: Sweep,+ // These are associated with different bodies depending on the separation function type.+ // It could be two local vectors/points on the same body (for example, both on bodyA).+ witness1: Vector,+ witness2: Vector,+ ty: SeparationType,+}++#[cfg(feature = "dim3")]+fn unique_count(count: usize, indices: &[u32; 3]) -> usize {+ match count {+ 1 => 1,+ 2 => {+ if indices[0] != indices[1] {+ 2+ } else {+ 1+ }+ }+ 3 => {+ if indices[0] != indices[1] && indices[0] != indices[2] && indices[1] != indices[2] {+ 3+ } else if indices[0] == indices[1] && indices[0] == indices[2] {+ 1+ } else {+ 2+ }+ }+ _ => unreachable!(),+ }+}++// This checks if the cross product of two edges switches direction over the sweep.+#[cfg(feature = "dim3")]+fn check_fast_edges(+ sweep_a: &Sweep,+ local_edge_a: Vector,+ sweep_b: &Sweep,+ local_edge_b: Vector,+ axis0: Vector,+) -> bool {+ // By taking the local witness axes we make sure that we get the correct orientations+ // (e.g. if one axis was flipped)!+ let xf_a2 = sweep_a.final_transform();+ let xf_b2 = sweep_b.final_transform();+ let edge_a = rotate_vec(&xf_a2.rotation, local_edge_a);+ let edge_b = rotate_vec(&xf_b2.rotation, local_edge_b);+ let axis = edge_a.cross(edge_b);+ axis.dot(axis0) < 0.0+}++#[cfg(feature = "dim3")]+impl<'a, 'b> SeparationFunction<'a, 'b> {+ pub fn new(+ cache: &SimplexCache,+ proxy_a: &'a ToiProxy<'b>,+ sweep_a: &Sweep,+ proxy_b: &'a ToiProxy<'b>,+ sweep_b: &Sweep,+ world_normal: Vector,+ t1: Real,+ ) -> Self {+ let count = cache.count as usize;+ debug_assert!(1 <= count && count <= 3);++ let mut index_a = cache.index_a;+ let mut index_b = cache.index_b;++ let unique_count_a = unique_count(count, &index_a);+ let unique_count_b = unique_count(count, &index_b);++ let xf_a1 = sweep_a.transform_at(t1);+ let xf_b1 = sweep_b.transform_at(t1);++ let qa = xf_a1.rotation;+ let qb = xf_b1.rotation;++ // Minimize round-off+ let delta_p = xf_b1.translation - xf_a1.translation;++ let mut result = Self {+ proxy_a,+ proxy_b,+ sweep_a: *sweep_a,+ sweep_b: *sweep_b,+ witness1: world_normal,+ witness2: Vector::ZERO,+ ty: SeparationType::Vertices,+ };++ match count {+ 1 => {+ // Witness is the world space direction+ result.ty = SeparationType::Vertices;+ result.witness1 = world_normal;+ }+ 2 => {+ if unique_count_a == 2 && unique_count_b == 2 {+ Self::init_edges(+ &mut result,+ proxy_a,+ proxy_b,+ &index_a,+ &index_b,+ &qa,+ &qb,+ delta_p,+ world_normal,+ 0.05,+ );+ } else {+ // Vertex versus edge, use world axis witness+ result.ty = SeparationType::Vertices;+ result.witness1 = world_normal;+ }+ }+ 3 => {+ if unique_count_a == 3 {+ let va1 = proxy_a.points()[index_a[0] as usize];+ let va2 = proxy_a.points()[index_a[1] as usize];+ let va3 = proxy_a.points()[index_a[2] as usize];+ let mut local_axis_a = (va2 - va1).cross(va3 - va1).normalize_or_zero();+ let axis_a = rotate_vec(&qa, local_axis_a);++ let local_point_a = (va1 + va2 + va3) / 3.0;+ let local_point_b = proxy_b.points()[index_b[0] as usize];+ let delta =+ rotate_vec(&qb, local_point_b) - rotate_vec(&qa, local_point_a) + delta_p;++ if delta.dot(axis_a) < 0.0 {+ // Make axis point from A to B+ local_axis_a = -local_axis_a;+ }++ // Witness is the local plane of faceA+ result.ty = SeparationType::FaceA;+ result.witness1 = local_axis_a;+ result.witness2 = local_point_a;+ } else if unique_count_b == 3 {+ let vb1 = proxy_b.points()[index_b[0] as usize];+ let vb2 = proxy_b.points()[index_b[1] as usize];+ let vb3 = proxy_b.points()[index_b[2] as usize];+ let mut local_axis_b = (vb2 - vb1).cross(vb3 - vb1).normalize_or_zero();+ let axis_b = rotate_vec(&qb, local_axis_b);++ let local_point_a = proxy_a.points()[index_a[0] as usize];+ let local_point_b = (vb1 + vb2 + vb3) / 3.0;+ let delta =+ rotate_vec(&qa, local_point_a) - rotate_vec(&qb, local_point_b) - delta_p;++ if delta.dot(axis_b) < 0.0 {+ // Make axis point from B to A+ local_axis_b = -local_axis_b;+ }++ // Witness is the local plane of faceB+ result.ty = SeparationType::FaceB;+ result.witness1 = local_axis_b;+ result.witness2 = local_point_b;+ } else {+ debug_assert!(unique_count_a == 2 && unique_count_b == 2);++ if index_a[0] == index_a[1] {+ // Make first two indices unique+ index_a[1] = index_a[2];+ }+ if index_b[0] == index_b[1] {+ // Make first two indices unique+ index_b[1] = index_b[2];+ }++ Self::init_edges(+ &mut result,+ proxy_a,+ proxy_b,+ &index_a,+ &index_b,+ &qa,+ &qb,+ delta_p,+ world_normal,+ 0.005,+ );+ }+ }+ _ => unreachable!(),+ }++ result+ }++ #[allow(clippy::too_many_arguments)]+ fn init_edges(+ result: &mut Self,+ proxy_a: &'a ToiProxy<'b>,+ proxy_b: &'a ToiProxy<'b>,+ index_a: &[u32; 3],+ index_b: &[u32; 3],+ qa: &crate::math::Rotation,+ qb: &crate::math::Rotation,+ delta_p: Vector,+ world_normal: Vector,+ parallel_tolerance: Real,+ ) {+ // Edge/Edge+ let va1 = proxy_a.points()[index_a[0] as usize];+ let local_edge_a = (proxy_a.points()[index_a[1] as usize] - va1).normalize_or_zero();++ let vb1 = proxy_b.points()[index_b[0] as usize];+ let mut local_edge_b = (proxy_b.points()[index_b[1] as usize] - vb1).normalize_or_zero();++ let edge_a = rotate_vec(qa, local_edge_a);+ let edge_b = rotate_vec(qb, local_edge_b);++ let mut axis = edge_a.cross(edge_b);+ let length_squared = axis.length_squared();++ // Skip near parallel edges: |e1 x e2| = sin(alpha) * |e1| * |e2|+ let tolerance_squared = parallel_tolerance * parallel_tolerance;+ if length_squared < tolerance_squared {+ // The axis is not safe to normalize so we use a world axis instead!+ result.ty = SeparationType::Vertices;+ result.witness1 = world_normal;+ return;+ }++ let delta = rotate_vec(qb, vb1) - rotate_vec(qa, va1) + delta_p;+ if delta.dot(axis) < 0.0 {+ // Make axis point from A to B+ axis = -axis;+ local_edge_b = -local_edge_b;+ }++ // Check for possible sign flip in edge/edge cross product+ if check_fast_edges(+ &result.sweep_a,+ local_edge_a,+ &result.sweep_b,+ local_edge_b,+ axis,+ ) {+ // Not safe to use local edges, fall back to initial world space axis instead+ result.ty = SeparationType::Vertices;+ result.witness1 = axis.normalize_or_zero();+ } else {+ // Edge cross product is safe. This converges faster than a fixed axis.+ result.ty = SeparationType::Edges;+ result.witness1 = local_edge_a;+ result.witness2 = local_edge_b;+ }+ }++ /// Finds the deepest support points at time `t` and returns their signed separation.+ pub fn find_min_separation(&self, t: Real) -> (Real, u32, u32) {+ let xf_a = self.sweep_a.transform_at(t);+ let xf_b = self.sweep_b.transform_at(t);++ match self.ty {+ SeparationType::Vertices => {+ let axis = self.witness1;++ let local_axis_a = inv_rotate_vec(&xf_a.rotation, axis);+ let local_axis_b = inv_rotate_vec(&xf_b.rotation, -axis);++ let index_a = self.proxy_a.support(local_axis_a);+ let index_b = self.proxy_b.support(local_axis_b);++ let delta_p = xf_b.translation - xf_a.translation;+ let local_point_a = self.proxy_a.points()[index_a as usize];+ let local_point_b = self.proxy_b.points()[index_b as usize];+ let delta = rotate_vec(&xf_b.rotation, local_point_b)+ - rotate_vec(&xf_a.rotation, local_point_a)+ + delta_p;++ (delta.dot(axis), index_a, index_b)+ }+ SeparationType::Edges => {+ let edge_a = rotate_vec(&xf_a.rotation, self.witness1);+ let edge_b = rotate_vec(&xf_b.rotation, self.witness2);+ let axis = edge_a.cross(edge_b).normalize_or_zero();++ let axis_a = inv_rotate_vec(&xf_a.rotation, axis);+ let index_a = self.proxy_a.support(axis_a);++ let axis_b = inv_rotate_vec(&xf_b.rotation, axis);+ let index_b = self.proxy_b.support(-axis_b);++ let delta_p = xf_b.translation - xf_a.translation;+ let local_point_a = self.proxy_a.points()[index_a as usize];+ let local_point_b = self.proxy_b.points()[index_b as usize];+ let delta = rotate_vec(&xf_b.rotation, local_point_b)+ - rotate_vec(&xf_a.rotation, local_point_a)+ + delta_p;++ (delta.dot(axis), index_a, index_b)+ }+ SeparationType::FaceA => {+ let normal = rotate_vec(&xf_a.rotation, self.witness1);+ let point_a = xf_a.transform_point(self.witness2);++ let axis_b = inv_rotate_vec(&xf_b.rotation, normal);+ let index_b = self.proxy_b.support(-axis_b);+ let point_b = xf_b.transform_point(self.proxy_b.points()[index_b as usize]);++ ((point_b - point_a).dot(normal), INVALID_INDEX, index_b)+ }+ SeparationType::FaceB => {+ let normal = rotate_vec(&xf_b.rotation, self.witness1);++ let axis_a = inv_rotate_vec(&xf_a.rotation, normal);+ let index_a = self.proxy_a.support(-axis_a);+ let point_a = xf_a.transform_point(self.proxy_a.points()[index_a as usize]);++ let point_b = xf_b.transform_point(self.witness2);++ ((point_a - point_b).dot(normal), index_a, INVALID_INDEX)+ }+ }+ }++ /// Evaluates the separation of fixed witness features at time `t`.+ pub fn evaluate(&self, index_a: u32, index_b: u32, t: Real) -> Real {+ let xf_a = self.sweep_a.transform_at(t);+ let xf_b = self.sweep_b.transform_at(t);++ match self.ty {+ SeparationType::Vertices => {+ let axis = self.witness1;+ let point_a = xf_a.transform_point(self.proxy_a.points()[index_a as usize]);+ let point_b = xf_b.transform_point(self.proxy_b.points()[index_b as usize]);+ (point_b - point_a).dot(axis)+ }+ SeparationType::Edges => {+ let edge_a = rotate_vec(&xf_a.rotation, self.witness1);+ let edge_b = rotate_vec(&xf_b.rotation, self.witness2);+ let axis = edge_a.cross(edge_b).normalize_or_zero();++ let point_a = xf_a.transform_point(self.proxy_a.points()[index_a as usize]);+ let point_b = xf_b.transform_point(self.proxy_b.points()[index_b as usize]);+ (point_b - point_a).dot(axis)+ }+ SeparationType::FaceA => {+ let axis = rotate_vec(&xf_a.rotation, self.witness1);+ let point_a = xf_a.transform_point(self.witness2);+ let point_b = xf_b.transform_point(self.proxy_b.points()[index_b as usize]);+ (point_b - point_a).dot(axis)+ }+ SeparationType::FaceB => {+ let axis = rotate_vec(&xf_b.rotation, self.witness1);+ let point_a = xf_a.transform_point(self.proxy_a.points()[index_a as usize]);+ let point_b = xf_b.transform_point(self.witness2);+ (point_a - point_b).dot(axis)+ }+ }+ }++ /// Whether this function uses the edge/edge cross-product axis.+ pub fn uses_edge_axis(&self) -> bool {+ self.ty == SeparationType::Edges+ }++ /// Converts an edge-axis function to a frozen world axis evaluated at time `t`.+ pub fn force_fixed_axis(&mut self, t: Real) {+ debug_assert!(self.ty == SeparationType::Edges);++ let xf_a = self.sweep_a.transform_at(t);+ let xf_b = self.sweep_b.transform_at(t);++ let edge_a = rotate_vec(&xf_a.rotation, self.witness1);+ let edge_b = rotate_vec(&xf_b.rotation, self.witness2);+ let axis = edge_a.cross(edge_b).normalize_or_zero();++ self.ty = SeparationType::Vertices;+ self.witness1 = axis;+ self.witness2 = Vector::ZERO;+ }+}diff --git a/renderer/third_party/parry3d/src/query/sweep_toi/sweep.rs b/renderer/third_party/parry3d/src/query/sweep_toi/sweep.rsnew file mode 100644index 0000000..c70b50e--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sweep_toi/sweep.rs@@ -0,0 +1,113 @@+use crate::math::{Pose, Real, Rotation, Vector};++/// Rotates a vector by a rotation.+#[inline]+pub(crate) fn rotate_vec(q: &Rotation, v: Vector) -> Vector {+ #[cfg(feature = "dim2")]+ {+ q.transform_vector(v)+ }+ #[cfg(feature = "dim3")]+ {+ *q * v+ }+}++/// Rotates a vector by the inverse of a rotation.+#[inline]+pub(crate) fn inv_rotate_vec(q: &Rotation, v: Vector) -> Vector {+ #[cfg(feature = "dim2")]+ {+ q.inverse_transform_vector(v)+ }+ #[cfg(feature = "dim3")]+ {+ q.inverse() * v+ }+}++/// Normalized linear interpolation between two rotations (3D: shortest arc).+#[inline]+pub(crate) fn nlerp(q1: &Rotation, q2: &Rotation, t: Real) -> Rotation {+ #[cfg(feature = "dim2")]+ {+ q1.lerp(*q2, t).normalize()+ }+ #[cfg(feature = "dim3")]+ {+ let q1 = if q1.dot(*q2) < 0.0 { -*q1 } else { *q1 };+ (q1 * (1.0 - t) + *q2 * t).normalize()+ }+}++/// Describes the motion of a rigid body over a timestep as linear interpolation between two+/// endpoint poses: the center of mass moves on a straight line while the rotation is+/// interpolated with a normalized lerp (nlerp).+///+/// This is a common motion model for continuous collision detection. It is exact+/// at both endpoints and a good approximation in between as long as the rotation delta stays+/// below ~45°.+#[derive(Copy, Clone, Debug, PartialEq)]+#[cfg_attr(+ feature = "serde-serialize",+ derive(serde::Serialize, serde::Deserialize)+)]+pub struct Sweep {+ /// The center of mass expressed in the shape’s local frame.+ pub local_center: Vector,+ /// The world-space center of mass at the start of the sweep.+ pub c1: Vector,+ /// The world-space center of mass at the end of the sweep.+ pub c2: Vector,+ /// The rotation at the start of the sweep.+ pub q1: Rotation,+ /// The rotation at the end of the sweep.+ pub q2: Rotation,+}++impl Sweep {+ /// Builds a sweep from the start and end poses of a shape’s local frame.+ pub fn from_poses(start: &Pose, end: &Pose, local_center: Vector) -> Self {+ Self {+ local_center,+ c1: start.transform_point(local_center),+ c2: end.transform_point(local_center),+ q1: start.rotation,+ q2: end.rotation,+ }+ }++ /// A degenerate sweep holding the shape stationary at the given pose.+ pub fn constant(pose: &Pose, local_center: Vector) -> Self {+ Self::from_poses(pose, pose, local_center)+ }++ /// The pose of the shape’s local frame at time `t ∈ [0, 1]`.+ ///+ /// The center of mass is lerped, the rotation is nlerped, and the local-frame origin is+ /// recovered by un-shifting the local center.+ pub fn transform_at(&self, t: Real) -> Pose {+ let q = nlerp(&self.q1, &self.q2, t);+ let p = self.c1.lerp(self.c2, t) - rotate_vec(&q, self.local_center);+ Pose::from_parts(p, q)+ }++ /// The pose of the shape’s local frame at the end of the sweep (`t = 1`), computed exactly.+ pub fn final_transform(&self) -> Pose {+ let p = self.c2 - rotate_vec(&self.q2, self.local_center);+ Pose::from_parts(p, self.q2)+ }++ /// Translates the entire sweep by `-origin`.+ ///+ /// Used to re-center the time-of-impact computation for better floating-point accuracy.+ pub fn shifted(&self, origin: Vector) -> Self {+ Self {+ local_center: self.local_center,+ c1: self.c1 - origin,+ c2: self.c2 - origin,+ q1: self.q1,+ q2: self.q2,+ }+ }+}diff --git a/renderer/third_party/parry3d/src/query/sweep_toi/sweep_toi.rs b/renderer/third_party/parry3d/src/query/sweep_toi/sweep_toi.rsnew file mode 100644index 0000000..6e55024--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sweep_toi/sweep_toi.rs@@ -0,0 +1,443 @@+//! Conservative-advancement time of impact on endpoint-interpolated sweeps.+//!+//! A GJK distance query (with a warm-started simplex cache) provides a separating axis, and a+//! push-back loop with a hybrid bisection/false-position root finder advances the earliest+//! time at which the shapes reach the target separation.++use super::proxy_distance::{proxy_distance, SimplexCache};+use super::separation::SeparationFunction;+use super::sweep::{rotate_vec, Sweep};+use super::toi_proxy::ToiProxy;+use crate::math::{Real, Vector};++/// The outcome of a [`sweep_time_of_impact`] computation.+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub enum SweepToiStatus {+ /// The shapes were overlapped at the start time; continuous collision gave up+ /// (`fraction == 0`).+ Overlapped,+ /// The shapes reach the target separation at `fraction`.+ Hit,+ /// The shapes never come within the target separation over the sweep+ /// (`fraction == max_fraction`).+ Separated,+ /// The root finder failed to converge; `fraction` holds the last safe time.+ Failed,+}++/// The result of a [`sweep_time_of_impact`] computation.+#[derive(Copy, Clone, Debug)]+pub struct SweepToiOutput {+ /// How the computation terminated.+ pub status: SweepToiStatus,+ /// The normalized time of impact in `[0, max_fraction]`.+ pub fraction: Real,+ /// The averaged world-space hit point (only meaningful on `Hit`/`Failed`).+ pub point: Vector,+ /// The world-space separating axis at the hit time, pointing from the first shape to the+ /// second (only meaningful on `Hit`/`Failed`).+ pub normal: Vector,+}++/// Computes the time of impact between two proxies following endpoint-interpolated sweeps.+///+/// The shapes are advanced to the earliest time in `[0, max_fraction]` at which their+/// core-shape separation drops to `max(linear_slop, radius_a + radius_b - linear_slop)`.+/// `linear_slop` is typically 0.005 length units.+pub fn sweep_time_of_impact(+ proxy_a: &ToiProxy,+ sweep_a: &Sweep,+ proxy_b: &ToiProxy,+ sweep_b: &Sweep,+ max_fraction: Real,+ linear_slop: Real,+) -> SweepToiOutput {+ let mut output = SweepToiOutput {+ status: SweepToiStatus::Separated,+ fraction: max_fraction,+ point: Vector::ZERO,+ normal: Vector::ZERO,+ };++ // Shift to the first sweep’s start center for better floating-point accuracy.+ let origin = sweep_a.c1;+ let sweep_a = sweep_a.shifted(origin);+ let sweep_b = sweep_b.shifted(origin);++ #[cfg(feature = "dim2")]+ let max_push_back_iterations = 8; // Maximum polygon vertex count.+ #[cfg(feature = "dim3")]+ let max_push_back_iterations = proxy_a.points().len() + proxy_b.points().len();++ #[cfg(feature = "dim2")]+ const MAX_DISTANCE_ITERATIONS: u32 = 20;+ #[cfg(feature = "dim3")]+ const MAX_DISTANCE_ITERATIONS: u32 = 25;++ let t_max = max_fraction;++ // Set up target distance and tolerance.+ let total_radius = proxy_a.radius + proxy_b.radius;+ let target = linear_slop.max(total_radius - linear_slop);+ let tolerance = 0.25 * linear_slop;+ debug_assert!(target > tolerance);++ let mut t1 = 0.0;+ let mut distance_iterations = 0u32;+ let mut cache = SimplexCache::default();++ // The outer loop progressively attempts to compute new separating axes.+ // This loop terminates when an axis is repeated (no progress is made).+ loop {+ // Get the distance between shapes. We can also use the results to get a separating+ // axis.+ let xf_a = sweep_a.transform_at(t1);+ let xf_b = sweep_b.transform_at(t1);+ let pos12 = xf_a.inv_mul(&xf_b);+ let distance_output = proxy_distance(&pos12, proxy_a, proxy_b, false, &mut cache);++ // The distance query runs in frame A, project the witness data back to the (shifted)+ // world.+ let world_normal = rotate_vec(&xf_a.rotation, distance_output.normal);+ let world_point_a = xf_a.transform_point(distance_output.point_a);+ let world_point_b = xf_a.transform_point(distance_output.point_b);++ distance_iterations += 1;++ let averaged_hit_point = || {+ let pa = world_point_a + proxy_a.radius * world_normal;+ let pb = world_point_b - proxy_b.radius * world_normal;+ 0.5 * (pa + pb) + origin+ };++ // If the shapes are overlapped, we give up on continuous collision.+ if distance_output.distance <= 0.0 {+ output.status = SweepToiStatus::Overlapped;+ output.fraction = 0.0;+ break;+ }++ if distance_output.distance <= target + tolerance {+ // Success!+ output.status = SweepToiStatus::Hit;+ output.point = averaged_hit_point();+ output.normal = world_normal;+ output.fraction = t1;+ break;+ }++ // In 3D, check for slow progress before running the push-back loop…+ #[cfg(feature = "dim3")]+ if distance_iterations == MAX_DISTANCE_ITERATIONS {+ // Progress too slow. This can happen when a capsule rotates around a triangle+ // vertex.+ output.status = SweepToiStatus::Failed;+ output.fraction = t1;+ output.point = averaged_hit_point();+ output.normal = world_normal;+ break;+ }++ // Initialize the separating axis.+ let mut fcn = SeparationFunction::new(+ &cache,+ proxy_a,+ &sweep_a,+ proxy_b,+ &sweep_b,+ world_normal,+ t1,+ );++ // Compute the TOI on the separating axis. We do this by successively resolving the+ // deepest point. This loop is bounded by the number of vertices.+ let mut done = false;+ let mut t2 = t_max;+ let mut push_back_iterations = 0;+ loop {+ // Find the deepest point at t2. Store the witness point indices.+ let (mut s2, index_a, index_b) = fcn.find_min_separation(t2);++ // Is the final configuration separated?+ if s2 - target > tolerance {+ // Victory!+ output.status = SweepToiStatus::Separated;+ output.fraction = t_max;+ done = true;+ break;+ }++ // Has the separation reached tolerance?+ if s2 >= target - tolerance {+ // Advance the sweeps.+ t1 = t2;+ break;+ }++ // Compute the initial separation of the witness points.+ let mut s1 = fcn.evaluate(index_a, index_b, t1);++ // Check for initial overlap. This might happen if the root finder runs out of+ // iterations.+ if s1 < target - tolerance {+ output.status = SweepToiStatus::Failed;+ output.fraction = t1;+ done = true;+ break;+ }++ // Check for touching.+ if s1 <= target + tolerance {+ // Success! t1 should hold the TOI (could be 0.0).+ output.status = SweepToiStatus::Hit;+ output.point = averaged_hit_point();+ output.normal = world_normal;+ output.fraction = t1;+ done = true;+ break;+ }++ // Compute 1D root of: f(t) - target = 0.+ let mut root_iteration_count = 0;+ const MAX_ROOT_ITERATIONS: u32 = 50;+ let mut a1 = t1;+ let mut a2 = t2;+ loop {+ // Use a mix of false position and bisection.+ let t = if root_iteration_count & 1 == 1 {+ // False position to improve convergence.+ a1 + (target - s1) * (a2 - a1) / (s2 - s1)+ } else {+ // Bisection to guarantee progress.+ 0.5 * (a1 + a2)+ };++ root_iteration_count += 1;++ let s = fcn.evaluate(index_a, index_b, t);++ // Has the separation reached tolerance?+ if (s - target).abs() <= tolerance {+ // t2 holds a tentative value for t1.+ t2 = t;+ break;+ }++ // Ensure we continue to bracket the root.+ if s > target {+ a1 = t;+ s1 = s;+ } else {+ a2 = t;+ s2 = s;+ }++ if root_iteration_count == MAX_ROOT_ITERATIONS {+ break;+ }+ }++ // Restart the inner loop if we have a failing edge case (3D edge/edge axis only).+ if root_iteration_count == MAX_ROOT_ITERATIONS - 1 && fcn.uses_edge_axis() {+ t2 = t_max;+ fcn.force_fixed_axis(t1);+ }++ push_back_iterations += 1;+ if push_back_iterations == max_push_back_iterations {+ break;+ }+ }++ if done {+ break;+ }++ // …while in 2D it is checked after the push-back loop, letting the last distance+ // iteration still resolve an impact.+ #[cfg(feature = "dim2")]+ if distance_iterations == MAX_DISTANCE_ITERATIONS {+ // Root finder got stuck. Semi-victory.+ output.status = SweepToiStatus::Failed;+ output.point = averaged_hit_point();+ output.normal = world_normal;+ output.fraction = t1;+ break;+ }+ }++ output+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::math::{Pose, Rotation};++ fn slop() -> Real {+ 0.005+ }++ #[cfg(feature = "dim2")]+ fn pose(x: Real, y: Real) -> Pose {+ Pose::from_parts(Vector::new(x, y), Rotation::identity())+ }+ #[cfg(feature = "dim3")]+ fn pose(x: Real, y: Real) -> Pose {+ Pose::from_parts(Vector::new(x, y, 0.0), Rotation::IDENTITY)+ }++ fn ball_proxy(radius: Real) -> ToiProxy<'static> {+ ToiProxy::point(Vector::ZERO, radius)+ }++ fn cuboid_proxy(half_extent: Real) -> ToiProxy<'static> {+ #[cfg(feature = "dim2")]+ {+ ToiProxy::from_array(+ [+ Vector::new(-half_extent, -half_extent),+ Vector::new(half_extent, -half_extent),+ Vector::new(half_extent, half_extent),+ Vector::new(-half_extent, half_extent),+ ],+ 0.0,+ )+ }+ #[cfg(feature = "dim3")]+ {+ let h = half_extent;+ ToiProxy::from_array(+ [+ Vector::new(-h, -h, -h),+ Vector::new(h, -h, -h),+ Vector::new(h, h, -h),+ Vector::new(-h, h, -h),+ Vector::new(-h, -h, h),+ Vector::new(h, -h, h),+ Vector::new(h, h, h),+ Vector::new(-h, h, h),+ ],+ 0.0,+ )+ }+ }++ #[test]+ fn ball_hits_static_box() {+ // Static unit box at the origin; ball of radius 0.1 sweeping from x = -3 to x = +3.+ let wall = cuboid_proxy(0.5);+ let wall_sweep = Sweep::constant(&pose(0.0, 0.0), Vector::ZERO);+ let ball = ball_proxy(0.1);+ let ball_sweep = Sweep::from_poses(&pose(-3.0, 0.0), &pose(3.0, 0.0), Vector::ZERO);++ let result = sweep_time_of_impact(&wall, &wall_sweep, &ball, &ball_sweep, 1.0, slop());+ assert_eq!(result.status, SweepToiStatus::Hit);++ // The ball is stopped when its core (center) is `target = radius - slop` away from+ // the box surface: center_x = -0.5 - (0.1 - 0.005), fraction = (start - x) / travel.+ let expected = (3.0 - 0.5 - (0.1 - slop())) / 6.0;+ assert!(+ (result.fraction - expected).abs() < 0.001,+ "fraction {} vs expected {expected}",+ result.fraction+ );+ }++ #[test]+ fn ball_misses_box() {+ // Ball sweeping parallel to the box, far away.+ let wall = cuboid_proxy(0.5);+ let wall_sweep = Sweep::constant(&pose(0.0, 0.0), Vector::ZERO);+ let ball = ball_proxy(0.1);+ let ball_sweep = Sweep::from_poses(&pose(-3.0, 5.0), &pose(3.0, 5.0), Vector::ZERO);++ let result = sweep_time_of_impact(&wall, &wall_sweep, &ball, &ball_sweep, 1.0, slop());+ assert_eq!(result.status, SweepToiStatus::Separated);+ assert_eq!(result.fraction, 1.0);+ }++ #[test]+ fn overlapped_at_start_returns_fraction_zero() {+ let wall = cuboid_proxy(0.5);+ let wall_sweep = Sweep::constant(&pose(0.0, 0.0), Vector::ZERO);+ let ball = ball_proxy(0.1);+ let ball_sweep = Sweep::from_poses(&pose(0.0, 0.0), &pose(3.0, 0.0), Vector::ZERO);++ let result = sweep_time_of_impact(&wall, &wall_sweep, &ball, &ball_sweep, 1.0, slop());+ assert_eq!(result.status, SweepToiStatus::Overlapped);+ assert_eq!(result.fraction, 0.0);+ }++ #[test]+ fn box_vs_box_face_impact() {+ // Two unit boxes; one sweeps into the other along x.+ let a = cuboid_proxy(0.5);+ let a_sweep = Sweep::constant(&pose(0.0, 0.0), Vector::ZERO);+ let b = cuboid_proxy(0.5);+ let b_sweep = Sweep::from_poses(&pose(-4.0, 0.0), &pose(4.0, 0.0), Vector::ZERO);++ let result = sweep_time_of_impact(&a, &a_sweep, &b, &b_sweep, 1.0, slop());+ assert_eq!(result.status, SweepToiStatus::Hit);++ // Faces meet when the gap reaches target = slop: center_x = -(0.5 + 0.5 + slop).+ let expected = (4.0 - 1.0 - slop()) / 8.0;+ assert!(+ (result.fraction - expected).abs() < 0.001,+ "fraction {} vs expected {expected}",+ result.fraction+ );+ }++ #[test]+ fn rotating_bar_hits_ball() {+ // A long thin bar rotating 90° about the origin must catch a ball placed along its+ // swept arc even though the bar’s endpoint poses don’t overlap the ball.+ let half_length = 2.0;+ #[cfg(feature = "dim2")]+ let (bar, start, end) = (+ ToiProxy::from_array(+ [+ Vector::new(-half_length, 0.0),+ Vector::new(half_length, 0.0),+ ],+ 0.05,+ ),+ Pose::from_parts(Vector::ZERO, Rotation::identity()),+ Pose::from_parts(+ Vector::ZERO,+ Rotation::from_angle(core::f32::consts::FRAC_PI_2 as Real),+ ),+ );+ #[cfg(feature = "dim3")]+ let (bar, start, end) = (+ ToiProxy::from_array(+ [+ Vector::new(-half_length, 0.0, 0.0),+ Vector::new(half_length, 0.0, 0.0),+ ],+ 0.05,+ ),+ Pose::from_parts(Vector::ZERO, Rotation::IDENTITY),+ Pose::from_parts(+ Vector::ZERO,+ Rotation::from_rotation_z(core::f32::consts::FRAC_PI_2 as Real),+ ),+ );++ let bar_sweep = Sweep::from_poses(&start, &end, Vector::ZERO);+ let ball = ball_proxy(0.1);+ // Place the ball at 45° on the arc of radius 1.5.+ let d = 1.5 * (0.5_f64.sqrt() as Real);+ let ball_sweep = Sweep::constant(&pose(d, d), Vector::ZERO);++ let result = sweep_time_of_impact(&bar, &bar_sweep, &ball, &ball_sweep, 1.0, slop());+ assert_eq!(result.status, SweepToiStatus::Hit);+ // The bar reaches 45° at t = 0.5; it should hit slightly before.+ assert!(+ result.fraction > 0.3 && result.fraction < 0.5,+ "fraction {}",+ result.fraction+ );+ }+}diff --git a/renderer/third_party/parry3d/src/query/sweep_toi/toi_proxy.rs b/renderer/third_party/parry3d/src/query/sweep_toi/toi_proxy.rsnew file mode 100644index 0000000..4d91f1e--- /dev/null+++ b/renderer/third_party/parry3d/src/query/sweep_toi/toi_proxy.rs@@ -0,0 +1,179 @@+use crate::bounding_volume::Aabb;+use crate::math::{Pose, Real, Vector};+use crate::shape::{Shape, TypedShape};++/// Maximum number of proxy points stored inline (cuboid corners).+#[cfg(feature = "dim2")]+pub const TOI_PROXY_INLINE_POINTS: usize = 4;+/// Maximum number of proxy points stored inline (cuboid corners).+#[cfg(feature = "dim3")]+pub const TOI_PROXY_INLINE_POINTS: usize = 8;++enum ProxyPoints<'a> {+ Inline([Vector; TOI_PROXY_INLINE_POINTS], u8),+ Borrowed(&'a [Vector]),+}++/// A point cloud with a radius, approximating a convex shape for sweep-based time-of-impact+/// computations.+///+/// Only shapes that decompose exactly into a point cloud plus an inflation radius can be+/// represented (balls, capsules, segments, triangles, cuboids, convex polygons/polyhedra and+/// their round variants). Other shapes (cylinders, cones, half-spaces, composites, custom+/// shapes) return `None` from [`ToiProxy::from_shape`].+pub struct ToiProxy<'a> {+ points: ProxyPoints<'a>,+ /// The inflation radius around the point cloud.+ pub radius: Real,+}++impl<'a> ToiProxy<'a> {+ /// A proxy made of a single point with a radius.+ pub fn point(point: Vector, radius: Real) -> Self {+ let mut buf = [Vector::ZERO; TOI_PROXY_INLINE_POINTS];+ buf[0] = point;+ Self {+ points: ProxyPoints::Inline(buf, 1),+ radius,+ }+ }++ /// A proxy borrowing its point cloud.+ pub fn from_points(points: &'a [Vector], radius: Real) -> Self {+ assert!(!points.is_empty());+ Self {+ points: ProxyPoints::Borrowed(points),+ radius,+ }+ }++ /// A proxy from an inline array of points.+ pub fn from_array<const N: usize>(points: [Vector; N], radius: Real) -> Self {+ assert!(N > 0 && N <= TOI_PROXY_INLINE_POINTS);+ let mut buf = [Vector::ZERO; TOI_PROXY_INLINE_POINTS];+ buf[..N].copy_from_slice(&points);+ Self {+ points: ProxyPoints::Inline(buf, N as u8),+ radius,+ }+ }++ /// Extracts a proxy from a shape, if the shape decomposes into points + radius.+ pub fn from_shape(shape: &'a dyn Shape) -> Option<Self> {+ match shape.as_typed_shape() {+ TypedShape::Ball(ball) => Some(Self::point(Vector::ZERO, ball.radius)),+ TypedShape::Cuboid(cuboid) => {+ Some(Self::from_cuboid_half_extents(cuboid.half_extents, 0.0))+ }+ TypedShape::RoundCuboid(round) => Some(Self::from_cuboid_half_extents(+ round.inner_shape.half_extents,+ round.border_radius,+ )),+ TypedShape::Capsule(capsule) => Some(Self::from_array(+ [capsule.segment.a, capsule.segment.b],+ capsule.radius,+ )),+ TypedShape::Segment(segment) => Some(Self::from_array([segment.a, segment.b], 0.0)),+ TypedShape::Triangle(tri) => Some(Self::from_array([tri.a, tri.b, tri.c], 0.0)),+ TypedShape::RoundTriangle(round) => {+ let tri = &round.inner_shape;+ Some(Self::from_array([tri.a, tri.b, tri.c], round.border_radius))+ }+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ TypedShape::ConvexPolygon(poly) => Some(Self::from_points(poly.points(), 0.0)),+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ TypedShape::RoundConvexPolygon(round) => Some(Self::from_points(+ round.inner_shape.points(),+ round.border_radius,+ )),+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ TypedShape::ConvexPolyhedron(poly) => Some(Self::from_points(poly.points(), 0.0)),+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ TypedShape::RoundConvexPolyhedron(round) => Some(Self::from_points(+ round.inner_shape.points(),+ round.border_radius,+ )),+ _ => None,+ }+ }++ fn from_cuboid_half_extents(he: Vector, radius: Real) -> Self {+ #[cfg(feature = "dim2")]+ {+ Self::from_array(+ [+ Vector::new(-he.x, -he.y),+ Vector::new(he.x, -he.y),+ Vector::new(he.x, he.y),+ Vector::new(-he.x, he.y),+ ],+ radius,+ )+ }+ #[cfg(feature = "dim3")]+ {+ Self::from_array(+ [+ Vector::new(-he.x, -he.y, -he.z),+ Vector::new(he.x, -he.y, -he.z),+ Vector::new(he.x, he.y, -he.z),+ Vector::new(-he.x, he.y, -he.z),+ Vector::new(-he.x, -he.y, he.z),+ Vector::new(he.x, -he.y, he.z),+ Vector::new(he.x, he.y, he.z),+ Vector::new(-he.x, he.y, he.z),+ ],+ radius,+ )+ }+ }++ /// The proxy’s point cloud.+ #[inline]+ pub fn points(&self) -> &[Vector] {+ match &self.points {+ ProxyPoints::Inline(buf, len) => &buf[..*len as usize],+ ProxyPoints::Borrowed(points) => points,+ }+ }++ /// The index of the proxy point with the greatest projection along `direction`.+ ///+ /// Projections are measured relative to the first point for better accuracy far from the+ /// origin.+ #[inline]+ pub fn support(&self, direction: Vector) -> u32 {+ let points = self.points();+ let origin = points[0];+ let mut best_index = 0;+ let mut best_value = 0.0;+ for (i, pt) in points.iter().enumerate().skip(1) {+ let value = direction.dot(*pt - origin);+ if value > best_value {+ best_index = i;+ best_value = value;+ }+ }+ best_index as u32+ }++ /// The axis-aligned bounding box of this proxy under the given pose.+ pub fn compute_aabb(&self, pose: &Pose) -> Aabb {+ let points = self.points();+ let mut mins = pose.transform_point(points[0]);+ let mut maxs = mins;+ for pt in &points[1..] {+ let p = pose.transform_point(*pt);+ mins = mins.min(p);+ maxs = maxs.max(p);+ }+ Aabb::new(+ mins - Vector::splat(self.radius),+ maxs + Vector::splat(self.radius),+ )+ }+}diff --git a/renderer/third_party/parry3d/src/shape/ball.rs b/renderer/third_party/parry3d/src/shape/ball.rsnew file mode 100644index 0000000..1eefb78--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/ball.rs@@ -0,0 +1,248 @@+use crate::math::{Pose, Real, Vector};+use crate::shape::SupportMap;++/// A ball shape, also known as a sphere in 3D or a circle in 2D.+///+/// A ball is one of the simplest shapes in collision detection, defined by a single+/// parameter: its radius. The center of the ball is always at the origin of its local+/// coordinate system.+///+/// # Properties+///+/// - **In 2D**: Represents a circle (all points at distance `radius` from the center)+/// - **In 3D**: Represents a sphere (all points at distance `radius` from the center)+/// - **Convex**: Yes, balls are always convex shapes+/// - **Support mapping**: Extremely efficient (constant time)+///+/// # Use Cases+///+/// Balls are ideal for:+/// - Projectiles (bullets, cannonballs)+/// - Spherical objects (planets, marbles, balls)+/// - Bounding volumes for fast collision detection+/// - Dynamic objects that need to roll+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Ball;+/// use parry3d::math::Vector;+///+/// // Create a ball with radius 2.0+/// let ball = Ball::new(2.0);+/// assert_eq!(ball.radius, 2.0);+/// # }+/// ```+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]+#[cfg_attr(feature = "encase", derive(encase::ShaderType))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(PartialEq, Debug, Copy, Clone)]+#[repr(C)]+pub struct Ball {+ /// The radius of the ball.+ ///+ /// This must be a positive value. A radius of 0.0 is valid but represents+ /// a degenerate ball (a single point).+ pub radius: Real,+}++impl Ball {+ /// Creates a new ball with the given radius.+ ///+ /// # Arguments+ ///+ /// * `radius` - The radius of the ball. Should be positive.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Ball;+ ///+ /// // Create a ball with radius 5.0+ /// let ball = Ball::new(5.0);+ /// assert_eq!(ball.radius, 5.0);+ ///+ /// // You can also create very small balls+ /// let tiny_ball = Ball::new(0.001);+ /// assert_eq!(tiny_ball.radius, 0.001);+ /// # }+ /// ```+ #[inline]+ pub fn new(radius: Real) -> Ball {+ Ball { radius }+ }++ /// Computes a scaled version of this ball.+ ///+ /// **Uniform scaling** (same scale factor on all axes) produces another ball.+ /// **Non-uniform scaling** (different scale factors) produces an ellipse, which+ /// is approximated as a convex polygon.+ ///+ /// # Arguments+ ///+ /// * `scale` - The scaling factors for each axis (x, y in 2D)+ /// * `nsubdivs` - Number of subdivisions for polygon approximation when scaling is non-uniform+ ///+ /// # Returns+ ///+ /// * `Some(Either::Left(Ball))` - If scaling is uniform, returns a scaled ball+ /// * `Some(Either::Right(ConvexPolygon))` - If scaling is non-uniform, returns a polygon approximation+ /// * `None` - If the approximation failed (e.g., zero scaling on an axis)+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "alloc", feature = "f32"))] {+ /// use parry2d::shape::Ball;+ /// use parry2d::math::Vector;+ /// use either::Either;+ ///+ /// let ball = Ball::new(2.0);+ ///+ /// // Uniform scaling: produces another ball+ /// let uniform_scale = Vector::new(3.0, 3.0);+ /// if let Some(Either::Left(scaled_ball)) = ball.scaled(uniform_scale, 32) {+ /// assert_eq!(scaled_ball.radius, 6.0); // 2.0 * 3.0+ /// }+ ///+ /// // Non-uniform scaling: produces a polygon (ellipse approximation)+ /// let non_uniform_scale = Vector::new(2.0, 1.0);+ /// if let Some(Either::Right(polygon)) = ball.scaled(non_uniform_scale, 32) {+ /// // The polygon approximates an ellipse with radii 4.0 and 2.0+ /// assert!(polygon.points().len() >= 32);+ /// }+ /// # }+ /// # #[cfg(all(feature = "dim2", feature = "alloc", feature = "f64"))] {+ /// use parry2d_f64::shape::Ball;+ /// use parry2d_f64::math::Vector;+ /// use either::Either;+ ///+ /// let ball = Ball::new(2.0);+ ///+ /// // Uniform scaling: produces another ball+ /// let uniform_scale = Vector::new(3.0, 3.0);+ /// if let Some(Either::Left(scaled_ball)) = ball.scaled(uniform_scale, 32) {+ /// assert_eq!(scaled_ball.radius, 6.0); // 2.0 * 3.0+ /// }+ ///+ /// // Non-uniform scaling: produces a polygon (ellipse approximation)+ /// let non_uniform_scale = Vector::new(2.0, 1.0);+ /// if let Some(Either::Right(polygon)) = ball.scaled(non_uniform_scale, 32) {+ /// // The polygon approximates an ellipse with radii 4.0 and 2.0+ /// assert!(polygon.points().len() >= 32);+ /// }+ /// # }+ /// ```+ #[cfg(all(feature = "dim2", feature = "alloc"))]+ #[inline]+ pub fn scaled(+ self,+ scale: Vector,+ nsubdivs: u32,+ ) -> Option<either::Either<Self, super::ConvexPolygon>> {+ if scale.x != scale.y {+ // The scaled shape isn't a ball.+ let mut vtx = self.to_polyline(nsubdivs);+ vtx.iter_mut().for_each(|pt| *pt *= scale);+ Some(either::Either::Right(+ super::ConvexPolygon::from_convex_polyline(vtx)?,+ ))+ } else {+ let uniform_scale = scale.x;+ Some(either::Either::Left(Self::new(+ self.radius * uniform_scale.abs(),+ )))+ }+ }++ /// Computes a scaled version of this ball.+ ///+ /// **Uniform scaling** (same scale factor on all axes) produces another ball.+ /// **Non-uniform scaling** (different scale factors) produces an ellipsoid, which+ /// is approximated as a convex polyhedron.+ ///+ /// # Arguments+ ///+ /// * `scale` - The scaling factors for each axis (x, y, z in 3D)+ /// * `nsubdivs` - Number of subdivisions for polyhedron approximation when scaling is non-uniform+ ///+ /// # Returns+ ///+ /// * `Some(Either::Left(Ball))` - If scaling is uniform, returns a scaled ball+ /// * `Some(Either::Right(ConvexPolyhedron))` - If scaling is non-uniform, returns a polyhedron approximation+ /// * `None` - If the approximation failed (e.g., zero scaling on an axis)+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32", feature = "alloc"))] {+ /// use parry3d::shape::Ball;+ /// use parry3d::math::Vector;+ /// use either::Either;+ ///+ /// let ball = Ball::new(5.0);+ ///+ /// // Uniform scaling: produces another ball+ /// let uniform_scale = Vector::new(2.0, 2.0, 2.0);+ /// if let Some(Either::Left(scaled_ball)) = ball.scaled(uniform_scale, 10) {+ /// assert_eq!(scaled_ball.radius, 10.0); // 5.0 * 2.0+ /// }+ ///+ /// // Non-uniform scaling: produces a polyhedron (ellipsoid approximation)+ /// let non_uniform_scale = Vector::new(2.0, 1.0, 1.5);+ /// if let Some(Either::Right(polyhedron)) = ball.scaled(non_uniform_scale, 10) {+ /// // The polyhedron approximates an ellipsoid+ /// assert!(polyhedron.points().len() > 0);+ /// }+ /// # }+ /// ```+ #[cfg(all(feature = "dim3", feature = "alloc"))]+ #[inline]+ pub fn scaled(+ self,+ scale: Vector,+ nsubdivs: u32,+ ) -> Option<either::Either<Self, super::ConvexPolyhedron>> {+ if scale.x != scale.y || scale.x != scale.z || scale.y != scale.z {+ // The scaled shape isn't a ball.+ let (mut vtx, idx) = self.to_trimesh(nsubdivs, nsubdivs);+ vtx.iter_mut().for_each(|pt| *pt *= scale);+ Some(either::Either::Right(+ super::ConvexPolyhedron::from_convex_mesh(vtx, &idx)?,+ ))+ } else {+ let uniform_scale = scale.x;+ Some(either::Either::Left(Self::new(+ self.radius * uniform_scale.abs(),+ )))+ }+ }+}++impl SupportMap for Ball {+ #[inline]+ fn support_point(&self, m: &Pose, dir: Vector) -> Vector {+ self.support_point_toward(m, dir.normalize())+ }++ #[inline]+ fn support_point_toward(&self, m: &Pose, dir: Vector) -> Vector {+ m.translation + dir * self.radius+ }++ #[inline]+ fn local_support_point(&self, dir: Vector) -> Vector {+ self.local_support_point_toward(dir.normalize())+ }++ #[inline]+ fn local_support_point_toward(&self, dir: Vector) -> Vector {+ dir * self.radius+ }+}diff --git a/renderer/third_party/parry3d/src/shape/capsule.rs b/renderer/third_party/parry3d/src/shape/capsule.rsnew file mode 100644index 0000000..7627a1e--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/capsule.rs@@ -0,0 +1,404 @@+use crate::math::{Pose, Real, Rotation, Vector};+use crate::shape::{Segment, SupportMap};++#[cfg(feature = "alloc")]+use either::Either;++#[derive(Copy, Clone, Debug)]+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]+#[cfg_attr(feature = "encase", derive(encase::ShaderType))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+/// A capsule shape, also known as a pill or capped cylinder.+///+/// A capsule is defined by a line segment (its central axis) and a radius. It can be+/// visualized as a cylinder with hemispherical (2D: semicircular) caps on both ends.+/// This makes it perfect for representing elongated round objects.+///+/// # Structure+///+/// - **Segment**: The central axis from point `a` to point `b`+/// - **Radius**: The thickness around the segment+/// - **In 2D**: Looks like a rounded rectangle or "stadium" shape+/// - **In 3D**: Looks like a cylinder with spherical caps (a pill)+///+/// # Properties+///+/// - **Convex**: Yes, capsules are always convex+/// - **Smooth**: Completely smooth surface (no edges or corners)+/// - **Support mapping**: Efficient (constant time)+/// - **Rolling**: Excellent for objects that need to roll smoothly+///+/// # Use Cases+///+/// Capsules are ideal for:+/// - Characters and humanoid figures (torso, limbs)+/// - Pills, medicine capsules+/// - Elongated projectiles (missiles, torpedoes)+/// - Smooth rolling objects+/// - Any object that's "cylinder-like" but needs smooth collision at ends+///+/// # Advantages Over Cylinders+///+/// - **No sharp edges**: Smoother collision response+/// - **Better for characters**: More natural movement and rotation+/// - **Simpler collision detection**: Easier to compute contacts than cylinders+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Capsule;+/// use parry3d::math::Vector;+///+/// // Create a vertical capsule (aligned with Y axis)+/// // Half-height of 2.0 means the segment is 4.0 units long+/// let capsule = Capsule::new_y(2.0, 0.5);+/// assert_eq!(capsule.radius, 0.5);+/// assert_eq!(capsule.height(), 4.0);+///+/// // Create a custom capsule between two points+/// let a = Vector::ZERO;+/// let b = Vector::new(3.0, 4.0, 0.0);+/// let custom = Capsule::new(a, b, 1.0);+/// assert_eq!(custom.height(), 5.0); // Distance from a to b+/// # }+/// ```+pub struct Capsule {+ /// The line segment forming the capsule's central axis.+ ///+ /// The capsule extends from `segment.a` to `segment.b`, with hemispherical+ /// caps centered at each endpoint.+ pub segment: Segment,++ /// The radius of the capsule.+ ///+ /// This is the distance from the central axis to the surface. Must be positive.+ /// The total "thickness" of the capsule is `2 * radius`.+ pub radius: Real,+}++impl Capsule {+ /// Creates a new capsule aligned with the X axis.+ ///+ /// The capsule is centered at the origin and extends along the X axis.+ ///+ /// # Arguments+ ///+ /// * `half_height` - Half the length of the central segment (total length = `2 * half_height`)+ /// * `radius` - The radius of the capsule+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Capsule;+ ///+ /// // Create a capsule extending 6 units along X axis (3 units in each direction)+ /// // with radius 0.5+ /// let capsule = Capsule::new_x(3.0, 0.5);+ /// assert_eq!(capsule.height(), 6.0);+ /// assert_eq!(capsule.radius, 0.5);+ ///+ /// // The center is at the origin+ /// let center = capsule.center();+ /// assert!(center.length() < 1e-6);+ /// # }+ /// ```+ pub fn new_x(half_height: Real, radius: Real) -> Self {+ let b = Vector::X * half_height;+ Self::new(-b, b, radius)+ }++ /// Creates a new capsule aligned with the Y axis.+ ///+ /// The capsule is centered at the origin and extends along the Y axis.+ /// This is the most common orientation for character capsules (standing upright).+ ///+ /// # Arguments+ ///+ /// * `half_height` - Half the length of the central segment+ /// * `radius` - The radius of the capsule+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Capsule;+ ///+ /// // Create a typical character capsule: 2 units tall with 0.3 radius+ /// let character = Capsule::new_y(1.0, 0.3);+ /// assert_eq!(character.height(), 2.0);+ /// assert_eq!(character.radius, 0.3);+ ///+ /// // Total height including the spherical caps: 2.0 + 2 * 0.3 = 2.6+ /// # }+ /// ```+ pub fn new_y(half_height: Real, radius: Real) -> Self {+ let b = Vector::Y * half_height;+ Self::new(-b, b, radius)+ }++ /// Creates a new capsule aligned with the Z axis.+ ///+ /// The capsule is centered at the origin and extends along the Z axis.+ ///+ /// # Arguments+ ///+ /// * `half_height` - Half the length of the central segment+ /// * `radius` - The radius of the capsule+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Capsule;+ ///+ /// // Create a capsule for a torpedo extending along Z axis+ /// let torpedo = Capsule::new_z(5.0, 0.4);+ /// assert_eq!(torpedo.height(), 10.0);+ /// assert_eq!(torpedo.radius, 0.4);+ /// # }+ /// ```+ #[cfg(feature = "dim3")]+ pub fn new_z(half_height: Real, radius: Real) -> Self {+ let b = Vector::Z * half_height;+ Self::new(-b, b, radius)+ }++ /// Creates a new capsule with custom endpoints and radius.+ ///+ /// This is the most flexible constructor, allowing you to create a capsule+ /// with any orientation and position.+ ///+ /// # Arguments+ ///+ /// * `a` - The first endpoint of the central segment+ /// * `b` - The second endpoint of the central segment+ /// * `radius` - The radius of the capsule+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Capsule;+ /// use parry3d::math::Vector;+ ///+ /// // Create a diagonal capsule+ /// let a = Vector::ZERO;+ /// let b = Vector::new(3.0, 4.0, 0.0);+ /// let capsule = Capsule::new(a, b, 0.5);+ ///+ /// // Height is the distance between a and b+ /// assert_eq!(capsule.height(), 5.0); // 3-4-5 triangle+ ///+ /// // Center is the midpoint+ /// let center = capsule.center();+ /// assert_eq!(center, Vector::new(1.5, 2.0, 0.0));+ /// # }+ /// ```+ pub fn new(a: Vector, b: Vector, radius: Real) -> Self {+ let segment = Segment::new(a, b);+ Self { segment, radius }+ }++ /// Returns the length of the capsule's central segment.+ ///+ /// This is the distance between the two endpoints, **not** including the+ /// hemispherical caps. The total length of the capsule including caps is+ /// `height() + 2 * radius`.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Capsule;+ ///+ /// let capsule = Capsule::new_y(3.0, 0.5);+ ///+ /// // Height of the central segment+ /// assert_eq!(capsule.height(), 6.0);+ ///+ /// // Total length including spherical caps+ /// let total_length = capsule.height() + 2.0 * capsule.radius;+ /// assert_eq!(total_length, 7.0);+ /// # }+ /// ```+ pub fn height(&self) -> Real {+ (self.segment.b - self.segment.a).length()+ }++ /// Returns half the length of the capsule's central segment.+ ///+ /// This is equivalent to `height() / 2.0`.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Capsule;+ ///+ /// let capsule = Capsule::new_y(3.0, 0.5);+ /// assert_eq!(capsule.half_height(), 3.0);+ /// assert_eq!(capsule.half_height(), capsule.height() / 2.0);+ /// # }+ /// ```+ pub fn half_height(&self) -> Real {+ self.height() / 2.0+ }++ /// Returns the center point of the capsule.+ ///+ /// This is the midpoint between the two endpoints of the central segment.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Capsule;+ /// use parry3d::math::Vector;+ ///+ /// let a = Vector::new(-2.0, 0.0, 0.0);+ /// let b = Vector::new(4.0, 0.0, 0.0);+ /// let capsule = Capsule::new(a, b, 1.0);+ ///+ /// let center = capsule.center();+ /// assert_eq!(center, Vector::new(1.0, 0.0, 0.0));+ /// # }+ /// ```+ pub fn center(&self) -> Vector {+ self.segment.a.midpoint(self.segment.b)+ }++ /// Creates a new capsule equal to `self` with all its endpoints transformed by `pos`.+ ///+ /// This applies a rigid transformation (translation and rotation) to the capsule.+ ///+ /// # Arguments+ ///+ /// * `pos` - The isometry (rigid transformation) to apply+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Capsule;+ /// use parry3d::math::{Pose, Vector};+ ///+ /// let capsule = Capsule::new_y(1.0, 0.5);+ ///+ /// // Translate the capsule 5 units along X axis+ /// let transform = Pose::translation(5.0, 0.0, 0.0);+ /// let transformed = capsule.transform_by(&transform);+ ///+ /// // Center moved by 5 units+ /// assert_eq!(transformed.center().x, 5.0);+ /// // Radius unchanged+ /// assert_eq!(transformed.radius, 0.5);+ /// # }+ /// ```+ pub fn transform_by(&self, pos: &Pose) -> Self {+ Self::new(pos * self.segment.a, pos * self.segment.b, self.radius)+ }++ /// The transformation such that `t * Y` is collinear with `b - a` and `t * origin` equals+ /// the capsule's center.+ pub fn canonical_transform(&self) -> Pose {+ let tra = self.center();+ let rot = self.rotation_wrt_y();+ Pose::from_parts(tra, rot)+ }++ /// The rotation `r` such that `r * Y` is collinear with `b - a`.+ pub fn rotation_wrt_y(&self) -> Rotation {+ let mut dir = self.segment.b - self.segment.a;+ if dir.y < 0.0 {+ dir = -dir;+ }+ let dir = dir.normalize_or(Vector::Y);+ Rotation::from_rotation_arc(Vector::Y, dir)+ }++ /// The transform `t` such that `t * Y` is collinear with `b - a` and such that `t * origin = (b + a) / 2.0`.+ pub fn transform_wrt_y(&self) -> Pose {+ let rot = self.rotation_wrt_y();+ Pose::from_parts(self.center(), rot)+ }++ /// Computes a scaled version of this capsule.+ ///+ /// If the scaling factor is non-uniform, then it can’t be represented as+ /// capsule. Instead, a convex polygon approximation (with `nsubdivs`+ /// subdivisions) is returned. Returns `None` if that approximation had degenerate+ /// normals (for example if the scaling factor along one axis is zero).+ #[cfg(all(feature = "dim2", feature = "alloc"))]+ pub fn scaled(+ self,+ scale: Vector,+ nsubdivs: u32,+ ) -> Option<Either<Self, super::ConvexPolygon>> {+ if scale.x != scale.y {+ // The scaled shape is not a capsule.+ let mut vtx = self.to_polyline(nsubdivs);+ vtx.iter_mut().for_each(|pt| *pt *= scale);+ Some(Either::Right(super::ConvexPolygon::from_convex_polyline(+ vtx,+ )?))+ } else {+ let uniform_scale = scale.x;+ Some(Either::Left(Self::new(+ self.segment.a * uniform_scale,+ self.segment.b * uniform_scale,+ self.radius * uniform_scale.abs(),+ )))+ }+ }++ /// Computes a scaled version of this capsule.+ ///+ /// If the scaling factor is non-uniform, then it can’t be represented as+ /// capsule. Instead, a convex polygon approximation (with `nsubdivs`+ /// subdivisions) is returned. Returns `None` if that approximation had degenerate+ /// normals (for example if the scaling factor along one axis is zero).+ #[cfg(all(feature = "dim3", feature = "alloc"))]+ pub fn scaled(+ self,+ scale: Vector,+ nsubdivs: u32,+ ) -> Option<Either<Self, super::ConvexPolyhedron>> {+ if scale.x != scale.y || scale.x != scale.z || scale.y != scale.z {+ // The scaled shape is not a capsule.+ let (mut vtx, idx) = self.to_trimesh(nsubdivs, nsubdivs);+ vtx.iter_mut().for_each(|pt| *pt *= scale);+ Some(Either::Right(super::ConvexPolyhedron::from_convex_mesh(+ vtx, &idx,+ )?))+ } else {+ let uniform_scale = scale.x;+ Some(Either::Left(Self::new(+ self.segment.a * uniform_scale,+ self.segment.b * uniform_scale,+ self.radius * uniform_scale.abs(),+ )))+ }+ }+}++impl SupportMap for Capsule {+ fn local_support_point(&self, dir: Vector) -> Vector {+ let dir = dir.normalize_or(Vector::Y);+ self.local_support_point_toward(dir)+ }++ fn local_support_point_toward(&self, dir: Vector) -> Vector {+ if dir.dot(self.segment.a) > dir.dot(self.segment.b) {+ self.segment.a + dir * self.radius+ } else {+ self.segment.b + dir * self.radius+ }+ }+}diff --git a/renderer/third_party/parry3d/src/shape/composite_shape.rs b/renderer/third_party/parry3d/src/shape/composite_shape.rsnew file mode 100644index 0000000..be3c70a--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/composite_shape.rs@@ -0,0 +1,119 @@+use crate::math::Pose;+use crate::partitioning::Bvh;+use crate::query::details::NormalConstraints;+use crate::shape::Shape;++/// Trait implemented by shapes composed of multiple simpler shapes.+///+/// A composite shape is composed of several shapes. For example, this can+/// be a convex decomposition of a concave shape; or a triangle-mesh.+///+/// This trait is mostly useful for using composite shapes as trait-objects.+/// For other use-cases, call methods from [`TypedCompositeShape`] to avoid+/// dynamic dispatches instead.+#[cfg(feature = "alloc")]+pub trait CompositeShape {+ /// Applies a function to one sub-shape of this composite shape.+ ///+ /// This method is mostly useful for using composite shapes as trait-objects.+ /// For other use-cases, call methods from [`TypedCompositeShape`] to avoid+ /// dynamic dispatches instead.+ ///+ /// Note that if your structure also implements `TypedCompositeShape`, this method+ /// can be implemented simply as:+ /// ```rust ignore+ /// self.map_untyped_part_at(shape_id, f);+ /// ```+ fn map_part_at(+ &self,+ shape_id: u32,+ f: &mut dyn FnMut(Option<&Pose>, &dyn Shape, Option<&dyn NormalConstraints>),+ );++ /// Gets the acceleration structure of the composite shape.+ fn bvh(&self) -> &Bvh;++ /// Whether the parts of this shape may change between two queries made at the same pose (a+ /// deformable mesh whose vertices move).+ ///+ /// The contact-manifold queries then never reuse the contact points cached from a previous+ /// call (see [`ContactManifold::mark_shapes_deformed`]); the caller must still make sure the+ /// [`Self::bvh`] is up to date. Defaults to `false`.+ ///+ /// [`ContactManifold::mark_shapes_deformed`]: crate::query::ContactManifold::mark_shapes_deformed+ fn is_deformable(&self) -> bool {+ false+ }+}++#[cfg(feature = "alloc")]+pub trait TypedCompositeShape: CompositeShape {+ type PartShape: ?Sized + Shape;+ type PartNormalConstraints: ?Sized + NormalConstraints;++ fn map_typed_part_at<T>(+ &self,+ shape_id: u32,+ f: impl FnMut(Option<&Pose>, &Self::PartShape, Option<&Self::PartNormalConstraints>) -> T,+ ) -> Option<T>;++ // TODO: we need this method because the compiler won't want+ // to cast `&Self::PartShape` to `&dyn Shape` because it complains+ // that `PartShape` is not `Sized`.+ fn map_untyped_part_at<T>(+ &self,+ shape_id: u32,+ f: impl FnMut(Option<&Pose>, &dyn Shape, Option<&dyn NormalConstraints>) -> T,+ ) -> Option<T>;+}++/// The [`TypedCompositeShape`] view of a [`CompositeShape`] trait object (with or without the+/// `Sync` marker: distinct trait-object types).+macro_rules! impl_typed_composite_shape_for_dyn {+ ($($object:tt)+) => {+ #[cfg(feature = "alloc")]+ impl TypedCompositeShape for $($object)+ {+ type PartShape = dyn Shape;+ type PartNormalConstraints = dyn NormalConstraints;++ fn map_typed_part_at<T>(+ &self,+ shape_id: u32,+ mut f: impl FnMut(+ Option<&Pose>,+ &Self::PartShape,+ Option<&Self::PartNormalConstraints>,+ ) -> T,+ ) -> Option<T> {+ let mut result = None;+ self.map_part_at(shape_id, &mut |pose, part, normals| {+ result = Some(f(pose, part, normals));+ });+ result+ }++ fn map_untyped_part_at<T>(+ &self,+ shape_id: u32,+ mut f: impl FnMut(Option<&Pose>, &dyn Shape, Option<&dyn NormalConstraints>) -> T,+ ) -> Option<T> {+ let mut result = None;+ self.map_part_at(shape_id, &mut |pose, part, normals| {+ result = Some(f(pose, part, normals));+ });+ result+ }+ }+ };+}++impl_typed_composite_shape_for_dyn!(dyn CompositeShape + '_);+impl_typed_composite_shape_for_dyn!(dyn CompositeShape + Sync + '_);++/// A helper struct that implements scene queries on any composite shapes.+///+/// For example, the `RayCast` implementation of a composite shape can use this wrapper or+/// provide its own implementation. This is for working around the lack of specialization in+/// (stable) rust. If we did have specialization, this would just be a blanket implementation+/// of all the geometric query traits for all `S: CompositeShape`.+pub struct CompositeShapeRef<'a, S: ?Sized>(pub &'a S);diff --git a/renderer/third_party/parry3d/src/shape/compound.rs b/renderer/third_party/parry3d/src/shape/compound.rsnew file mode 100644index 0000000..97580df--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/compound.rs@@ -0,0 +1,2050 @@+//!+//! Shape composed from the union of primitives.+//!++use crate::bounding_volume::{Aabb, BoundingSphere, BoundingVolume};+use crate::math::Pose;+use crate::math::{Real, Vector};+use crate::partitioning::{Bvh, BvhBuildStrategy};+use crate::query::details::NormalConstraints;+#[cfg(feature = "dim2")]+use crate::shape::compound_pseudo_normals::turns_clockwise;+#[cfg(feature = "dim2")]+use crate::shape::CompoundEdgeCone;+#[cfg(feature = "dim3")]+use crate::shape::CompoundFaceCone;+use crate::shape::CompoundPseudoNormals;+use crate::shape::{CompositeShape, Shape, SharedShape, TypedCompositeShape};+#[cfg(feature = "dim2")]+use crate::shape::{ConvexPolygon, TriMesh, Triangle};+#[cfg(feature = "dim2")]+use crate::transformation::hertel_mehlhorn;+use crate::utils::hashmap::HashMap;+use alloc::vec::Vec;++#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[repr(C)]+#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]+/// Controls how a [`Compound`] is loaded.+pub struct CompoundFlags(u8);++bitflags::bitflags! {+ impl CompoundFlags: u8 {+ /// If set, the edges (2D) or faces (3D) where two parts meet are treated as interior to+ /// the union, and contact normals are clamped to the surviving outline. This removes the+ /// ledge a body catches on when it slides across the cut between two parts of a convex+ /// decomposition.+ ///+ /// This is the [`Compound`] counterpart of `TriMeshFlags::FIX_INTERNAL_EDGES`, and like it+ /// costs a one-off pass over the parts' edges when set.+ const FIX_INTERNAL_EDGES = 1;+ }+}++/// A compound shape with an aabb bounding volume.+///+/// A compound shape is a shape composed of the union of several simpler shape. This is+/// the main way of creating a concave shape from convex parts. Each parts can have its own+/// delta transformation to shift or rotate it with regard to the other shapes.+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[derive(Clone, Debug)]+pub struct Compound {+ shapes: Vec<(Pose, SharedShape)>,+ bvh: Bvh,+ aabbs: Vec<Aabb>,+ aabb: Aabb,+ #[cfg_attr(feature = "serde", serde(default))]+ flags: CompoundFlags,+ /// `None` for a part that constrains nothing: one that is not polygonal, or any part at all+ /// while [`CompoundFlags::FIX_INTERNAL_EDGES`] is unset.+ #[cfg_attr(feature = "serde", serde(default))]+ pseudo_normals: Option<Vec<Option<CompoundPseudoNormals>>>,+}++impl Compound {+ /// The tolerance [`Compound::set_flags`] welds part corners with, in ULPs.+ ///+ /// Two spellings of the same corner drift by about one ULP per rounding, and a corner reaches+ /// the surface through a rotation and a translation, so a handful of ULPs covers the seams a+ /// shared grid produces while staying far below any real feature.+ pub const DEFAULT_WELD_TOLERANCE: Real = 4.0;++ /// Builds a new compound shape from a collection of sub-shapes.+ ///+ /// A compound shape combines multiple primitive shapes into a single composite shape,+ /// each with its own relative position and orientation. This is the primary way to+ /// create concave shapes from convex primitives. The compound internally builds a+ /// Bounding Volume Hierarchy (BVH) for efficient collision detection.+ ///+ /// # Arguments+ ///+ /// * `shapes` - A vector of (position, shape) pairs. Each pair defines:+ /// - An [`Pose`] representing the sub-shape's position and orientation relative to the compound's origin+ /// - A [`SharedShape`] containing the actual geometry+ ///+ /// # Panics+ ///+ /// - If the input vector is empty (a compound must contain at least one shape)+ /// - If any of the provided shapes are themselves composite shapes (nested composites are not allowed)+ ///+ /// # Performance+ ///+ /// The BVH is built using a binned construction strategy optimized for static scenes.+ /// For large compounds (100+ shapes), construction may take noticeable time but provides+ /// excellent query performance.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{Compound, Ball, Cuboid, SharedShape};+ /// use parry3d::math::Pose;+ /// use parry3d::math::Vector;+ ///+ /// // Create a compound shape resembling a dumbbell+ /// let shapes = vec![+ /// // Left sphere+ /// (+ /// Pose::translation(-2.0, 0.0, 0.0),+ /// SharedShape::new(Ball::new(0.5))+ /// ),+ /// // Center bar+ /// (+ /// Pose::identity(),+ /// SharedShape::new(Cuboid::new(Vector::new(2.0, 0.2, 0.2)))+ /// ),+ /// // Right sphere+ /// (+ /// Pose::translation(2.0, 0.0, 0.0),+ /// SharedShape::new(Ball::new(0.5))+ /// ),+ /// ];+ ///+ /// let compound = Compound::new(shapes);+ ///+ /// // The compound now contains all three shapes+ /// assert_eq!(compound.shapes().len(), 3);+ /// # }+ /// ```+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::shape::{Compound, Ball, Cuboid, SharedShape};+ /// # use parry2d::math::Pose;+ /// # use parry2d::math::Vector;+ ///+ /// // Create an L-shaped compound+ /// let shapes = vec![+ /// // Vertical rectangle+ /// (+ /// Pose::translation(0.0, 1.0),+ /// SharedShape::new(Cuboid::new(Vector::new(0.5, 1.0)))+ /// ),+ /// // Horizontal rectangle+ /// (+ /// Pose::translation(1.0, 0.0),+ /// SharedShape::new(Cuboid::new(Vector::new(1.0, 0.5)))+ /// ),+ /// ];+ ///+ /// let l_shape = Compound::new(shapes);+ /// assert_eq!(l_shape.shapes().len(), 2);+ /// # }+ /// ```+ pub fn new(shapes: Vec<(Pose, SharedShape)>) -> Compound {+ assert!(+ !shapes.is_empty(),+ "A compound shape must contain at least one shape."+ );+ let mut aabbs = Vec::new();+ let mut leaves = Vec::new();+ let mut aabb = Aabb::new_invalid();++ for (i, (delta, shape)) in shapes.iter().enumerate() {+ let bv = shape.compute_aabb(delta);++ aabb.merge(&bv);+ aabbs.push(bv);+ leaves.push((i, bv));++ if shape.as_composite_shape().is_some() {+ panic!("Nested composite shapes are not allowed.");+ }+ }++ // NOTE: we apply no dilation factor because we won't+ // update this tree dynamically.+ let bvh = Bvh::from_iter(BvhBuildStrategy::Binned, leaves);++ Compound {+ shapes,+ bvh,+ aabbs,+ aabb,+ flags: CompoundFlags::empty(),+ pseudo_normals: None,+ }+ }++ /// Builds a new compound shape from a collection of sub-shapes, with the given+ /// [`CompoundFlags`] already applied.+ ///+ /// `weld_tolerance` is [`Compound::set_flags`]'s, and `None` selects+ /// [`Compound::DEFAULT_WELD_TOLERANCE`].+ ///+ /// # Example+ ///+ /// ```rust+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::math::{Pose, Vector};+ /// use parry2d::shape::{Compound, CompoundFlags, Cuboid, SharedShape};+ ///+ /// // Two boxes meeting along one edge, as a decomposition or a voxel grid leaves them.+ /// let box_at = |x: f32| {+ /// (+ /// Pose::from_parts(Vector::new(x, 0.0), Default::default()),+ /// SharedShape::new(Cuboid::new(Vector::new(0.5, 0.5))),+ /// )+ /// };+ /// let compound = Compound::with_flags(+ /// vec![box_at(0.0), box_at(1.0)],+ /// CompoundFlags::FIX_INTERNAL_EDGES,+ /// None,+ /// );+ ///+ /// // The edge they share is interior to the union, so neither part reports it.+ /// assert_eq!(compound.part_normal_constraints(0).unwrap().boundary_edges.len(), 3);+ /// # }+ /// ```+ pub fn with_flags(+ shapes: Vec<(Pose, SharedShape)>,+ flags: CompoundFlags,+ weld_tolerance: Option<Real>,+ ) -> Compound {+ let mut compound = Self::new(shapes);+ compound.set_flags(flags, weld_tolerance);+ compound+ }++ /// Sets the [`CompoundFlags`], computing or discarding the compound's optional associated data.+ ///+ /// `weld_tolerance` says how far apart two part corners may be and still be treated as the same+ /// point, in ULPs; `None` selects [`Compound::DEFAULT_WELD_TOLERANCE`].+ ///+ /// Parts of a decomposition meet on corners each computes for itself, and two spellings of the+ /// same corner need not round to the same bits: a row of boxes on a shared grid, or any part+ /// placed through a rotation, routinely leaves its seams a few ULPs apart. Corners that far+ /// apart are welded so the edge or face between them is still recognized as shared.+ ///+ /// The tolerance is relative to each corner's own distance from the origin, not the whole+ /// compound's, so detail near the origin keeps a tolerance of its own magnitude however far the+ /// rest of the compound reaches. Zero leaves only corners at the very same coordinates welded.+ ///+ /// Only [`CompoundFlags::FIX_INTERNAL_EDGES`] reads the tolerance; without it nothing is+ /// computed and the value is ignored.+ pub fn set_flags(&mut self, flags: CompoundFlags, weld_tolerance: Option<Real>) {+ self.flags = flags;++ if flags.contains(CompoundFlags::FIX_INTERNAL_EDGES) {+ self.compute_pseudo_normals(weld_tolerance.unwrap_or(Self::DEFAULT_WELD_TOLERANCE));+ } else {+ self.pseudo_normals = None;+ }+ }++ /// The [`CompoundFlags`] controlling this compound's optional associated data.+ pub fn flags(&self) -> CompoundFlags {+ self.flags+ }++ /// The parts' outlines in the compound's frame, wound counter-clockwise. `None` for a part+ /// with no straight sides, which therefore shares none.+ #[cfg(feature = "dim2")]+ fn part_outlines(&self) -> Vec<Option<Vec<Vector>>> {+ self.shapes+ .iter()+ .map(|(part_pos, part)| {+ let corners: Vec<Vector> = if let Some(polygon) = part.as_convex_polygon() {+ polygon.points().to_vec()+ } else if let Some(cuboid) = part.as_cuboid() {+ cuboid.to_polyline().to_vec()+ } else {+ let triangle = part.as_triangle()?;+ alloc::vec![triangle.a, triangle.b, triangle.c]+ };++ let mut outline: Vec<Vector> = corners+ .into_iter()+ .map(|corner| part_pos.transform_point(corner))+ .collect();++ if signed_area(&outline) < 0.0 {+ outline.reverse();+ }++ Some(outline)+ })+ .collect()+ }++ /// Builds the normal cones every part may report contacts in, from the outline of the union+ /// rather than from each part's own faces.+ ///+ /// An edge two parts share is a cut, so it is dropped, and each surviving edge opens towards+ /// the edge next to it along the union's outline, which a cut may have left in another part.+ /// That closes the corner where a surface runs into a cut -- the ledge a body would otherwise+ /// catch on -- without closing one the cut merely passes through.+ #[cfg(feature = "dim2")]+ fn compute_pseudo_normals(&mut self, weld_tolerance: Real) {+ let outlines = self.part_outlines();++ // Weld every part's corners into one vertex numbering, so two parts meeting along an edge+ // key it on the same pair of vertices even though each rounded its own corners.+ let corners: Vec<Vector> = outlines.iter().flatten().flatten().copied().collect();+ let welded = weld_corners(&corners, weld_tolerance);++ let mut vertex_ids: Vec<Option<Vec<u32>>> = Vec::with_capacity(outlines.len());+ let mut next = 0;+ for outline in &outlines {+ match outline {+ Some(outline) => {+ vertex_ids.push(Some(welded[next..next + outline.len()].to_vec()));+ next += outline.len();+ }+ None => vertex_ids.push(None),+ }+ }++ let edge_key = |a: u32, b: u32| if a <= b { (a, b) } else { (b, a) };++ let mut parts_sharing_edge = HashMap::default();+ for ids in vertex_ids.iter().flatten() {+ for (a, b) in outline_edge_ids(ids) {+ *parts_sharing_edge.entry(edge_key(a, b)).or_insert(0u32) += 1;+ }+ }++ // Per part, the outward normal of every outline edge, or `None` where a sibling part covers+ // it: that edge is a cut, interior to the union.+ let boundary_normals: Vec<Option<Vec<Option<Vector>>>> = outlines+ .iter()+ .zip(vertex_ids.iter())+ .map(|(outline, ids)| {+ let (outline, ids) = (outline.as_ref()?, ids.as_ref()?);++ Some(+ outline_edges(outline)+ .zip(outline_edge_ids(ids))+ .map(|((a, b), (id_a, id_b))| {+ let shared = parts_sharing_edge+ .get(&edge_key(id_a, id_b))+ .is_some_and(|parts| *parts > 1);++ (!shared)+ .then(|| crate::utils::ccw_face_normal([a, b]))+ .flatten()+ })+ .collect(),+ )+ })+ .collect();++ // The union's boundary edge arriving at, and the one leaving, each corner. Gathered across+ // every part, so a corner a cut splits still finds the neighbour that continues the+ // outline into the sibling part. `None` marks a corner more than one edge claims, where no+ // single neighbour can be picked.+ let mut arriving = HashMap::default();+ let mut leaving = HashMap::default();+ for (ids, normals) in vertex_ids.iter().zip(boundary_normals.iter()) {+ let (Some(ids), Some(normals)) = (ids.as_ref(), normals.as_ref()) else {+ continue;+ };++ for ((a, b), normal) in outline_edge_ids(ids).zip(normals.iter()) {+ let Some(normal) = *normal else {+ continue;+ };++ let _ = arriving+ .entry(b)+ .and_modify(|slot| *slot = None)+ .or_insert(Some(normal));+ let _ = leaving+ .entry(a)+ .and_modify(|slot| *slot = None)+ .or_insert(Some(normal));+ }+ }++ let pseudo_normals = self+ .shapes+ .iter()+ .zip(vertex_ids.iter())+ .zip(boundary_normals.iter())+ .map(|(((part_pos, _), ids), normals)| {+ let (ids, normals) = (ids.as_ref()?, normals.as_ref()?);++ let into_part = part_pos.rotation.inverse();+ let mut boundary_edges = Vec::new();++ for ((a, b), face) in outline_edge_ids(ids).zip(normals.iter()) {+ let Some(face) = *face else {+ continue;+ };++ // Halfway, so the two edges at a corner split its range and neither cone grows+ // past a half turn, which the containment test could not represent.+ let halfway_to = |neighbour: Option<Vector>| match neighbour {+ Some(neighbour) => (face + neighbour).normalize_or(face),+ None => face,+ };++ // A concave corner has no outward range for its two edges to share, so the cone+ // stops on this edge's own normal, as it does where the surface runs into a cut.+ // Walking counter-clockwise turns the normals the same way, so the edge arriving+ // at a corner lies clockwise of the one leaving it.+ let clockwise = arriving+ .get(&a)+ .copied()+ .flatten()+ .filter(|previous| !turns_clockwise(*previous, face));+ let counter_clockwise = leaving+ .get(&b)+ .copied()+ .flatten()+ .filter(|next| !turns_clockwise(face, *next));++ // Cones are stated in the part's frame, which is where the narrow phase applies+ // them.+ boundary_edges.push(CompoundEdgeCone {+ face: into_part * face,+ clockwise_limit: into_part * halfway_to(clockwise),+ counter_clockwise_limit: into_part * halfway_to(counter_clockwise),+ });+ }++ Some(CompoundPseudoNormals { boundary_edges })+ })+ .collect();++ self.pseudo_normals = Some(pseudo_normals);+ }++ /// The parts' faces in the compound's frame, each an outward normal with its vertex loop wound+ /// counter-clockwise around it. `None` for a part with no flat faces, which therefore shares+ /// none.+ #[cfg(feature = "dim3")]+ #[allow(clippy::type_complexity)]+ fn part_faces(&self) -> Vec<Option<Vec<(Vector, Vec<Vector>)>>> {+ self.shapes+ .iter()+ .map(|(part_pos, part)| {+ let faces = if let Some(polyhedron) = part.as_convex_polyhedron() {+ let points = polyhedron.points();+ let corner_indices = polyhedron.vertices_adj_to_face();++ polyhedron+ .faces()+ .iter()+ .map(|face| {+ let first = face.first_vertex_or_edge as usize;+ let corners = corner_indices+ [first..first + face.num_vertices_or_edges as usize]+ .iter()+ .map(|index| points[*index as usize])+ .collect();+ (face.normal, corners)+ })+ .collect()+ } else {+ // A cuboid is a polyhedron the type system does not call one, and a row of them+ // is how a voxel grid reaches a compound.+ cuboid_faces(part.as_cuboid()?.half_extents)+ };++ Some(+ faces+ .into_iter()+ .map(|(normal, corners): (Vector, Vec<Vector>)| {+ (+ part_pos.rotation * normal,+ corners+ .into_iter()+ .map(|corner| part_pos.transform_point(corner))+ .collect(),+ )+ })+ .collect(),+ )+ })+ .collect()+ }++ /// Builds the normal cones every part may report contacts in, from the surface of the union+ /// rather than from each part's own faces.+ ///+ /// A face two parts share is a cut, so it is dropped, and each edge of a surviving face opens+ /// towards the boundary face across it, which a cut may have left in another part. That closes+ /// the corner where a surface runs into a cut -- the ledge a body would otherwise catch on --+ /// without closing one the cut merely passes through.+ #[cfg(feature = "dim3")]+ fn compute_pseudo_normals(&mut self, weld_tolerance: Real) {+ let part_faces = self.part_faces();++ // Weld every part's corners into one vertex numbering, so two parts meeting along a face+ // key it on the same set of vertices even though each rounded its own corners.+ let corners: Vec<Vector> = part_faces+ .iter()+ .flatten()+ .flatten()+ .flat_map(|(_, corners)| corners.iter().copied())+ .collect();+ let welded = weld_corners(&corners, weld_tolerance);++ let mut vertex_ids: Vec<Option<Vec<Vec<u32>>>> = Vec::with_capacity(part_faces.len());+ let mut next = 0;+ for faces in &part_faces {+ match faces {+ Some(faces) => {+ let mut per_face = Vec::with_capacity(faces.len());+ for (_, corners) in faces {+ per_face.push(welded[next..next + corners.len()].to_vec());+ next += corners.len();+ }+ vertex_ids.push(Some(per_face));+ }+ None => vertex_ids.push(None),+ }+ }++ // A shared face has the same vertices on both sides, in some rotation and possibly reversed,+ // so the key ignores their order.+ let face_key = |ids: &[u32]| {+ let mut key = ids.to_vec();+ key.sort_unstable();+ key+ };+ let edge_key = |a: u32, b: u32| if a <= b { (a, b) } else { (b, a) };++ let mut parts_sharing_face = HashMap::default();+ for ids in vertex_ids.iter().flatten() {+ for face in ids {+ *parts_sharing_face.entry(face_key(face)).or_insert(0u32) += 1;+ }+ }++ // Per part, whether each face lies on the union's outline rather than being a cut two+ // parts share.+ let is_boundary: Vec<Option<Vec<bool>>> = vertex_ids+ .iter()+ .map(|ids| {+ Some(+ ids.as_ref()?+ .iter()+ .map(|face| {+ parts_sharing_face+ .get(&face_key(face))+ .is_none_or(|parts| *parts <= 1)+ })+ .collect(),+ )+ })+ .collect();++ // The boundary faces meeting along each edge. Gathered across every part, so an edge a cut+ // splits still finds the face continuing the surface into the sibling part.+ let mut faces_along_edge = HashMap::default();+ for ((faces, ids), boundary) in part_faces+ .iter()+ .zip(vertex_ids.iter())+ .zip(is_boundary.iter())+ {+ let (Some(faces), Some(ids), Some(boundary)) =+ (faces.as_ref(), ids.as_ref(), boundary.as_ref())+ else {+ continue;+ };++ for (((normal, _), face), boundary) in faces.iter().zip(ids.iter()).zip(boundary.iter())+ {+ if !boundary {+ continue;+ }++ for i in 0..face.len() {+ faces_along_edge+ .entry(edge_key(face[i], face[(i + 1) % face.len()]))+ .or_insert_with(Vec::new)+ .push(*normal);+ }+ }+ }++ let pseudo_normals = self+ .shapes+ .iter()+ .zip(part_faces.iter())+ .zip(vertex_ids.iter())+ .zip(is_boundary.iter())+ .map(|((((part_pos, _), faces), ids), boundary)| {+ let (faces, ids, boundary) = (faces.as_ref()?, ids.as_ref()?, boundary.as_ref()?);++ let into_part = part_pos.rotation.inverse();+ let mut boundary_faces = Vec::new();++ for (((normal, corners), face), on_boundary) in+ faces.iter().zip(ids.iter()).zip(boundary.iter())+ {+ if !on_boundary {+ continue;+ }++ let edge_pseudo_normals = (0..corners.len())+ .map(|i| {+ let next = (i + 1) % corners.len();+ let (from, to) = (corners[i], corners[next]);+ // Halfway to the boundary face across the edge, which may belong to+ // another part where a cut splits the surface along it. A concave edge+ // has no outward range for its two faces to share, so the cone stops on+ // this face's own normal, as it does at an edge whose other face was+ // cut away. Faces are wound counter-clockwise around their normal, so+ // the edge is convex exactly when the two normals turn that way too.+ let across = faces_along_edge+ .get(&edge_key(face[i], face[next]))+ .and_then(|normals| {+ normals.iter().find(|other| **other != *normal).copied()+ })+ .filter(|across| normal.cross(*across).dot(to - from) >= 0.0)+ .unwrap_or(*normal);+ into_part * (*normal + across).normalize_or(*normal)+ })+ .collect();++ boundary_faces.push(CompoundFaceCone {+ face: into_part * *normal,+ edge_pseudo_normals,+ });+ }++ Some(CompoundPseudoNormals { boundary_faces })+ })+ .collect();++ self.pseudo_normals = Some(pseudo_normals);+ }++ /// Returns the [`CompoundPseudoNormals`] of the part with index `i`.+ ///+ /// `None` unless this compound was given [`CompoundFlags::FIX_INTERNAL_EDGES`] and the part is+ /// polygonal -- a part with curved sides has no edge that another part could cover, so it+ /// constrains nothing.+ pub fn part_normal_constraints(&self, i: u32) -> Option<&CompoundPseudoNormals> {+ self.pseudo_normals.as_ref()?[i as usize].as_ref()+ }++ /// Creates a compound shape by decomposing a triangle mesh into convex polygons.+ ///+ /// This 2D-only method takes a [`TriMesh`] and merges adjacent triangles into larger+ /// convex polygons using the Hertel-Mehlhorn algorithm. This is useful for creating+ /// efficient collision shapes from arbitrary 2D meshes, as the resulting compound+ /// has fewer sub-shapes than using individual triangles.+ ///+ /// The algorithm works by:+ /// 1. Starting with all triangles from the input mesh+ /// 2. Merging adjacent triangles if the result is still convex+ /// 3. Creating a compound from the resulting convex polygons+ ///+ /// # Arguments+ ///+ /// * `trimesh` - A reference to the triangle mesh to decompose+ ///+ /// # Returns+ ///+ /// * `Some(Compound)` - A compound shape containing the convex polygons+ /// * `None` - If any of the created shapes has zero or near-zero area+ ///+ /// # Performance+ ///+ /// This decomposition is typically much more efficient than using the raw triangle mesh,+ /// as it reduces the number of shapes from N triangles to potentially N/2 or fewer polygons.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::shape::{Compound, TriMesh};+ /// # use parry2d::math::Vector;+ ///+ /// // Create a simple square mesh (2 triangles)+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0),+ /// Vector::new(1.0, 1.0),+ /// Vector::new(0.0, 1.0),+ /// ];+ ///+ /// let indices = vec![+ /// [0, 1, 2], // First triangle+ /// [0, 2, 3], // Second triangle+ /// ];+ ///+ /// let trimesh = TriMesh::new(vertices, indices).unwrap();+ ///+ /// // Decompose into convex polygons+ /// if let Some(compound) = Compound::decompose_trimesh(&trimesh) {+ /// // The two triangles should be merged into one or two convex polygons+ /// assert!(compound.shapes().len() <= 2);+ /// }+ /// # }+ /// ```+ ///+ /// # Example: Complex Shape+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::shape::{Compound, TriMesh};+ /// # use parry2d::math::Vector;+ ///+ /// // Create an L-shaped mesh+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(2.0, 0.0),+ /// Vector::new(2.0, 1.0),+ /// Vector::new(1.0, 1.0),+ /// Vector::new(1.0, 2.0),+ /// Vector::new(0.0, 2.0),+ /// ];+ ///+ /// let indices = vec![+ /// [0, 1, 2],+ /// [0, 2, 3],+ /// [0, 3, 4],+ /// [0, 4, 5],+ /// ];+ ///+ /// let trimesh = TriMesh::new(vertices, indices).unwrap();+ ///+ /// // Decompose the L-shape into convex polygons+ /// if let Some(compound) = Compound::decompose_trimesh(&trimesh) {+ /// // The result will have fewer shapes than the original 4 triangles+ /// assert!(compound.shapes().len() > 0);+ /// println!("Decomposed into {} convex polygons", compound.shapes().len());+ /// }+ /// # }+ /// ```+ #[cfg(feature = "dim2")]+ pub fn decompose_trimesh(trimesh: &TriMesh) -> Option<Self> {+ let polygons = hertel_mehlhorn(trimesh.vertices(), trimesh.indices());+ let shapes: Option<Vec<_>> = polygons+ .into_iter()+ .map(|points| {+ match points.len() {+ 3 => {+ let triangle = Triangle::new(points[0], points[1], points[2]);+ Some(SharedShape::new(triangle))+ }+ _ => ConvexPolygon::from_convex_polyline(points).map(SharedShape::new),+ }+ .map(|shape| (Pose::IDENTITY, shape))+ })+ .collect();+ Some(Self::new(shapes?))+ }+}++impl Compound {+ /// Returns a slice containing all sub-shapes and their positions in this compound.+ ///+ /// Each element in the returned slice is a tuple containing:+ /// - The sub-shape's position and orientation ([`Pose`]) relative to the compound's origin+ /// - The sub-shape itself ([`SharedShape`])+ ///+ /// The order of shapes matches the order they were provided to [`Compound::new`].+ /// The index of each shape in this slice corresponds to its ID used in other operations+ /// like BVH traversal.+ ///+ /// # Returns+ ///+ /// A slice of (isometry, shape) pairs representing all sub-shapes in this compound.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{Compound, Ball, Cuboid, SharedShape};+ /// use parry3d::math::Pose;+ /// use parry3d::math::Vector;+ ///+ /// let shapes = vec![+ /// (Pose::translation(1.0, 0.0, 0.0), SharedShape::new(Ball::new(0.5))),+ /// (Pose::translation(-1.0, 0.0, 0.0), SharedShape::new(Ball::new(0.3))),+ /// (Pose::identity(), SharedShape::new(Cuboid::new(Vector::new(0.5, 0.5, 0.5)))),+ /// ];+ ///+ /// let compound = Compound::new(shapes);+ ///+ /// // Access all shapes+ /// assert_eq!(compound.shapes().len(), 3);+ ///+ /// // Inspect individual shapes+ /// for (i, (position, shape)) in compound.shapes().iter().enumerate() {+ /// println!("Shape {} at position: {:?}", i, position.translation);+ ///+ /// // Check if it's a ball+ /// if let Some(ball) = shape.as_ball() {+ /// println!(" Ball with radius: {}", ball.radius);+ /// }+ /// }+ /// # }+ /// ```+ ///+ /// # Example: Modifying Sub-Shape Positions+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{Compound, Ball, SharedShape};+ /// use parry3d::math::Pose;+ ///+ /// let shapes = vec![+ /// (Pose::translation(0.0, 0.0, 0.0), SharedShape::new(Ball::new(1.0))),+ /// (Pose::translation(2.0, 0.0, 0.0), SharedShape::new(Ball::new(1.0))),+ /// ];+ ///+ /// let compound = Compound::new(shapes);+ ///+ /// // Note: To modify positions, you need to create a new compound+ /// let mut new_shapes: Vec<_> = compound.shapes()+ /// .iter()+ /// .map(|(pos, shape)| {+ /// // Shift all shapes up by 1 unit+ /// let new_pos = pos * Pose::translation(0.0, 1.0, 0.0);+ /// (new_pos, shape.clone())+ /// })+ /// .collect();+ ///+ /// let shifted_compound = Compound::new(new_shapes);+ /// assert_eq!(shifted_compound.shapes().len(), 2);+ /// # }+ /// ```+ #[inline]+ pub fn shapes(&self) -> &[(Pose, SharedShape)] {+ &self.shapes[..]+ }++ /// Returns the Axis-Aligned Bounding Box (AABB) of this compound in local space.+ ///+ /// The local AABB is the smallest axis-aligned box that contains all sub-shapes+ /// in the compound, computed in the compound's local coordinate system. This AABB+ /// is automatically computed when the compound is created and encompasses all+ /// sub-shapes at their specified positions.+ ///+ /// # Returns+ ///+ /// A reference to the [`Aabb`] representing the compound's bounding box in local space.+ ///+ /// # Use Cases+ ///+ /// - **Broad-phase collision detection**: Quick rejection tests before detailed queries+ /// - **Spatial partitioning**: Organizing compounds in larger spatial structures+ /// - **Culling**: Determining if the compound is visible or relevant to a query+ /// - **Size estimation**: Getting approximate dimensions of the compound+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{Compound, Ball, SharedShape};+ /// use parry3d::math::Pose;+ /// use parry3d::math::Vector;+ ///+ /// let shapes = vec![+ /// (Pose::translation(-2.0, 0.0, 0.0), SharedShape::new(Ball::new(0.5))),+ /// (Pose::translation(2.0, 0.0, 0.0), SharedShape::new(Ball::new(0.5))),+ /// ];+ ///+ /// let compound = Compound::new(shapes);+ /// let aabb = compound.local_aabb();+ ///+ /// // The AABB should contain both balls+ /// // Left ball extends from -2.5 to -1.5 on X axis+ /// // Right ball extends from 1.5 to 2.5 on X axis+ /// assert!(aabb.mins.x <= -2.5);+ /// assert!(aabb.maxs.x >= 2.5);+ ///+ /// // Check if a point is inside the AABB+ /// assert!(aabb.contains_local_point(Vector::ZERO));+ /// assert!(!aabb.contains_local_point(Vector::new(10.0, 0.0, 0.0)));+ /// # }+ /// ```+ ///+ /// # Example: Computing Compound Dimensions+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{Compound, Cuboid, SharedShape};+ /// use parry3d::math::Pose;+ /// use parry3d::math::Vector;+ ///+ /// let shapes = vec![+ /// (Pose::identity(), SharedShape::new(Cuboid::new(Vector::new(1.0, 1.0, 1.0)))),+ /// (Pose::translation(3.0, 0.0, 0.0), SharedShape::new(Cuboid::new(Vector::new(0.5, 0.5, 0.5)))),+ /// ];+ ///+ /// let compound = Compound::new(shapes);+ /// let aabb = compound.local_aabb();+ ///+ /// // Calculate the total dimensions+ /// let dimensions = aabb.maxs - aabb.mins;+ /// println!("Compound dimensions: {:?}", dimensions);+ ///+ /// // The compound extends from -1.0 to 3.5 on the X axis (4.5 units total)+ /// assert!((dimensions.x - 4.5).abs() < 1e-5);+ /// # }+ /// ```+ #[inline]+ pub fn local_aabb(&self) -> &Aabb {+ &self.aabb+ }++ /// Returns the bounding sphere of this compound in local space.+ ///+ /// The bounding sphere is the smallest sphere that contains all sub-shapes in the+ /// compound. It is computed from the compound's AABB by finding the sphere that+ /// tightly encloses that box. This provides a simple, rotation-invariant bounding+ /// volume useful for certain collision detection algorithms.+ ///+ /// # Returns+ ///+ /// A [`BoundingSphere`] centered in local space that contains the entire compound.+ ///+ /// # Performance+ ///+ /// This method is very fast as it simply computes the bounding sphere from the+ /// pre-computed AABB. The bounding sphere is not cached - it's computed on each call.+ ///+ /// # Comparison with AABB+ ///+ /// - **Bounding Sphere**: Rotation-invariant, simpler intersection tests, but often looser fit+ /// - **AABB**: Tighter fit for axis-aligned objects, but must be recomputed when rotated+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{Compound, Ball, SharedShape};+ /// use parry3d::math::Pose;+ ///+ /// let shapes = vec![+ /// (Pose::translation(-1.0, 0.0, 0.0), SharedShape::new(Ball::new(0.5))),+ /// (Pose::translation(1.0, 0.0, 0.0), SharedShape::new(Ball::new(0.5))),+ /// ];+ ///+ /// let compound = Compound::new(shapes);+ /// let bounding_sphere = compound.local_bounding_sphere();+ ///+ /// // The bounding sphere should contain both balls+ /// println!("Center: {:?}", bounding_sphere.center());+ /// println!("Radius: {}", bounding_sphere.radius());+ ///+ /// // The center should be near the origin+ /// assert!(bounding_sphere.center().length() < 0.1);+ ///+ /// // The radius should be at least 1.5 (distance to ball edge: 1.0 + 0.5)+ /// assert!(bounding_sphere.radius() >= 1.5);+ /// # }+ /// ```+ ///+ /// # Example: Using Bounding Sphere for Quick Rejection+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{Compound, Cuboid, SharedShape};+ /// use parry3d::math::{Pose, Vector};+ ///+ /// let shapes = vec![+ /// (Pose::identity(), SharedShape::new(Cuboid::new(Vector::new(1.0, 1.0, 1.0)))),+ /// (Pose::translation(2.0, 0.0, 0.0), SharedShape::new(Cuboid::new(Vector::new(0.5, 0.5, 0.5)))),+ /// ];+ ///+ /// let compound = Compound::new(shapes);+ /// let sphere = compound.local_bounding_sphere();+ ///+ /// // Quick test: is a point potentially inside the compound?+ /// let test_point = Vector::new(5.0, 5.0, 5.0);+ /// let distance_to_center = (test_point - sphere.center()).length();+ ///+ /// if distance_to_center > sphere.radius() {+ /// println!("Vector is definitely outside the compound");+ /// assert!(distance_to_center > sphere.radius());+ /// } else {+ /// println!("Vector might be inside - need detailed check");+ /// }+ /// # }+ /// ```+ #[inline]+ pub fn local_bounding_sphere(&self) -> BoundingSphere {+ self.aabb.bounding_sphere()+ }++ /// Returns a slice of AABBs, one for each sub-shape in this compound.+ ///+ /// Each AABB in the returned slice corresponds to the bounding box of a sub-shape,+ /// transformed to the compound's local coordinate system. The AABBs are stored in+ /// the same order as the shapes returned by [`Compound::shapes`], so index `i` in+ /// this slice corresponds to shape `i`.+ ///+ /// These AABBs are used internally by the BVH for efficient spatial queries and+ /// collision detection. They are pre-computed during compound construction.+ ///+ /// # Returns+ ///+ /// A slice of [`Aabb`] representing the local-space bounding boxes of each sub-shape.+ ///+ /// # Use Cases+ ///+ /// - Inspecting individual sub-shape bounds without accessing the shapes themselves+ /// - Custom spatial queries or culling operations+ /// - Debugging and visualization of the compound's structure+ /// - Understanding the BVH's leaf nodes+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{Compound, Ball, Cuboid, SharedShape};+ /// use parry3d::math::Pose;+ /// use parry3d::math::Vector;+ ///+ /// let shapes = vec![+ /// (Pose::translation(-2.0, 0.0, 0.0), SharedShape::new(Ball::new(0.5))),+ /// (Pose::identity(), SharedShape::new(Cuboid::new(Vector::new(1.0, 1.0, 1.0)))),+ /// (Pose::translation(3.0, 0.0, 0.0), SharedShape::new(Ball::new(0.3))),+ /// ];+ ///+ /// let compound = Compound::new(shapes);+ ///+ /// // Get AABBs for all sub-shapes+ /// let aabbs = compound.aabbs();+ /// assert_eq!(aabbs.len(), 3);+ ///+ /// // Inspect each AABB+ /// for (i, aabb) in aabbs.iter().enumerate() {+ /// println!("Shape {} AABB:", i);+ /// println!(" Min: {:?}", aabb.mins);+ /// println!(" Max: {:?}", aabb.maxs);+ ///+ /// let center = aabb.center();+ /// let extents = aabb.half_extents();+ /// println!(" Center: {:?}", center);+ /// println!(" Half-extents: {:?}", extents);+ /// }+ /// # }+ /// ```+ ///+ /// # Example: Finding Sub-Shapes in a Region+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{Compound, Ball, SharedShape};+ /// use parry3d::math::Pose;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let shapes = vec![+ /// (Pose::translation(-5.0, 0.0, 0.0), SharedShape::new(Ball::new(0.5))),+ /// (Pose::translation(0.0, 0.0, 0.0), SharedShape::new(Ball::new(0.5))),+ /// (Pose::translation(5.0, 0.0, 0.0), SharedShape::new(Ball::new(0.5))),+ /// ];+ ///+ /// let compound = Compound::new(shapes);+ ///+ /// // Define a query point+ /// let query_point = Vector::ZERO;+ ///+ /// // Find which sub-shapes might contain this point+ /// let potentially_containing: Vec<usize> = compound.aabbs()+ /// .iter()+ /// .enumerate()+ /// .filter(|(_, aabb)| aabb.contains_local_point(query_point))+ /// .map(|(i, _)| i)+ /// .collect();+ ///+ /// // Only the middle shape (index 1) should contain the origin+ /// assert_eq!(potentially_containing.len(), 1);+ /// assert_eq!(potentially_containing[0], 1);+ /// # }+ /// ```+ #[inline]+ pub fn aabbs(&self) -> &[Aabb] {+ &self.aabbs[..]+ }++ /// Returns the Bounding Volume Hierarchy (BVH) used for efficient spatial queries.+ ///+ /// The BVH is an acceleration structure that organizes the sub-shapes hierarchically+ /// for fast collision detection and spatial queries. It enables logarithmic-time queries+ /// instead of linear searches through all sub-shapes. The BVH is automatically built+ /// when the compound is created using a binned construction strategy.+ ///+ /// # Returns+ ///+ /// A reference to the [`Bvh`] acceleration structure for this compound.+ ///+ /// # Use Cases+ ///+ /// - **Custom spatial queries**: Traverse the BVH for specialized collision detection+ /// - **Ray casting**: Efficiently find which sub-shapes intersect a ray+ /// - **AABB queries**: Find all sub-shapes intersecting a region+ /// - **Debugging**: Inspect the BVH structure and quality+ /// - **Performance analysis**: Understand query performance characteristics+ ///+ /// # Performance+ ///+ /// The BVH provides O(log n) query performance for most spatial operations, where n+ /// is the number of sub-shapes. For compounds with many shapes (100+), the BVH+ /// provides dramatic speedups compared to naive linear searches.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{Compound, Ball, SharedShape};+ /// use parry3d::math::Pose;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::Vector;+ ///+ /// let shapes = vec![+ /// (Pose::translation(-3.0, 0.0, 0.0), SharedShape::new(Ball::new(0.5))),+ /// (Pose::translation(0.0, 0.0, 0.0), SharedShape::new(Ball::new(0.5))),+ /// (Pose::translation(3.0, 0.0, 0.0), SharedShape::new(Ball::new(0.5))),+ /// ];+ ///+ /// let compound = Compound::new(shapes);+ /// let bvh = compound.bvh();+ ///+ /// // The BVH provides efficient hierarchical organization+ /// assert_eq!(bvh.leaf_count(), 3);+ /// println!("BVH root AABB: {:?}", bvh.root_aabb());+ /// # }+ /// ```+ ///+ /// # Example: Accessing BVH for Custom Queries+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{Compound, Ball, SharedShape};+ /// use parry3d::math::Pose;+ ///+ /// let mut shapes = vec![];+ /// for i in 0..10 {+ /// let x = i as f32 * 2.0;+ /// shapes.push((+ /// Pose::translation(x, 0.0, 0.0),+ /// SharedShape::new(Ball::new(0.5))+ /// ));+ /// }+ ///+ /// let compound = Compound::new(shapes);+ /// let bvh = compound.bvh();+ ///+ /// // The BVH organizes 10 shapes hierarchically+ /// assert_eq!(bvh.leaf_count(), 10);+ /// assert_eq!(compound.shapes().len(), 10);+ ///+ /// // Access the root AABB which bounds all shapes+ /// let root_aabb = bvh.root_aabb();+ /// println!("Root AABB spans from {:?} to {:?}", root_aabb.mins, root_aabb.maxs);+ /// # }+ /// ```+ #[inline]+ pub fn bvh(&self) -> &Bvh {+ &self.bvh+ }+}++impl CompositeShape for Compound {+ #[inline]+ fn map_part_at(+ &self,+ shape_id: u32,+ f: &mut dyn FnMut(Option<&Pose>, &dyn Shape, Option<&dyn NormalConstraints>),+ ) {+ if let Some(shape) = self.shapes.get(shape_id as usize) {+ let constraints = self+ .part_normal_constraints(shape_id)+ .map(|c| c as &dyn NormalConstraints);+ f(Some(&shape.0), &*shape.1, constraints)+ }+ }++ #[inline]+ fn bvh(&self) -> &Bvh {+ &self.bvh+ }+}++/// The six faces of a cuboid in its own frame, each an outward normal with its corner loop wound+/// counter-clockwise around it.+#[cfg(feature = "dim3")]+#[allow(clippy::type_complexity)]+fn cuboid_faces(half_extents: Vector) -> Vec<(Vector, Vec<Vector>)> {+ let (x, y, z) = (half_extents.x, half_extents.y, half_extents.z);+ let corner = |sx: Real, sy: Real, sz: Real| Vector::new(sx * x, sy * y, sz * z);++ alloc::vec![+ (+ Vector::X,+ alloc::vec![+ corner(1.0, -1.0, -1.0),+ corner(1.0, 1.0, -1.0),+ corner(1.0, 1.0, 1.0),+ corner(1.0, -1.0, 1.0),+ ]+ ),+ (+ -Vector::X,+ alloc::vec![+ corner(-1.0, -1.0, -1.0),+ corner(-1.0, -1.0, 1.0),+ corner(-1.0, 1.0, 1.0),+ corner(-1.0, 1.0, -1.0),+ ]+ ),+ (+ Vector::Y,+ alloc::vec![+ corner(-1.0, 1.0, -1.0),+ corner(-1.0, 1.0, 1.0),+ corner(1.0, 1.0, 1.0),+ corner(1.0, 1.0, -1.0),+ ]+ ),+ (+ -Vector::Y,+ alloc::vec![+ corner(-1.0, -1.0, -1.0),+ corner(1.0, -1.0, -1.0),+ corner(1.0, -1.0, 1.0),+ corner(-1.0, -1.0, 1.0),+ ]+ ),+ (+ Vector::Z,+ alloc::vec![+ corner(-1.0, -1.0, 1.0),+ corner(1.0, -1.0, 1.0),+ corner(1.0, 1.0, 1.0),+ corner(-1.0, 1.0, 1.0),+ ]+ ),+ (+ -Vector::Z,+ alloc::vec![+ corner(-1.0, -1.0, -1.0),+ corner(-1.0, 1.0, -1.0),+ corner(1.0, 1.0, -1.0),+ corner(1.0, -1.0, -1.0),+ ]+ ),+ ]+}++/// Assigns every corner the index of the vertex it welds onto, so parts that meet are keyed on+/// the same point even when each computed it for itself.+///+/// Two corners weld when no coordinate differs by more than `tolerance` ULPs, measured at the+/// scale of whichever of the two lies further from the origin. That scale has to come from the+/// point rather than the coordinate: a corner reaching the outline through a rotation can land+/// near an axis, leaving a coordinate whose own magnitude is pure cancellation and says nothing+/// about the error in it, while its siblings still carry the magnitude the rounding happened at.+///+/// A tolerance of zero leaves only corners at the very same coordinates welded, matching what a+/// shared vertex buffer produces and nothing else. The comparison stays numeric there rather than+/// dropping to raw bits, so the two signed zeros still meet.+fn weld_corners(corners: &[Vector], tolerance: Real) -> Vec<u32> {+ let radius = |corner: &Vector| tolerance * Real::EPSILON * corner.abs().max_element();++ // Union-find over the corners, so a chain of near-coincident corners collapses to one vertex+ // whichever order the pairs turn up in.+ let mut parent: Vec<u32> = (0..corners.len() as u32).collect();+ fn find(parent: &mut [u32], mut i: u32) -> u32 {+ while parent[i as usize] != i {+ parent[i as usize] = parent[parent[i as usize] as usize];+ i = parent[i as usize];+ }+ i+ }++ let leaves: Vec<Aabb> = corners+ .iter()+ .map(|corner| Aabb::new(*corner, *corner))+ .collect();+ let bvh = Bvh::from_leaves(BvhBuildStrategy::Binned, &leaves);++ for (i, corner) in corners.iter().enumerate() {+ // Querying every corner with its own radius finds every pair that should weld: the test is+ // symmetric and scaled by the larger of the two, so the larger corner's own query reaches+ // the smaller one even when the smaller one's radius would fall short.+ let reach = radius(corner);+ let query = Aabb::new(+ *corner - Vector::splat(reach),+ *corner + Vector::splat(reach),+ );++ for j in bvh.intersect_aabb(&query) {+ let other = corners[j as usize];+ let scale = corner.abs().max_element().max(other.abs().max_element());++ if (*corner - other).abs().max_element() <= tolerance * Real::EPSILON * scale {+ let (a, b) = (find(&mut parent, i as u32), find(&mut parent, j));+ parent[a as usize] = b;+ }+ }+ }++ // Number the roots so the ids are dense.+ let mut ids = HashMap::default();+ (0..corners.len() as u32)+ .map(|i| {+ let root = find(&mut parent, i);+ let next = ids.len() as u32;+ *ids.entry(root).or_insert(next)+ })+ .collect()+}++/// The edges of a closed outline, as consecutive vertex-index pairs wrapping back to the start.+#[cfg(feature = "dim2")]+fn outline_edge_ids(ids: &[u32]) -> impl Iterator<Item = (u32, u32)> + '_ {+ ids.iter()+ .enumerate()+ .map(move |(i, id)| (*id, ids[(i + 1) % ids.len()]))+}++/// The edges of a closed outline, as consecutive corner pairs wrapping back to the start.+#[cfg(feature = "dim2")]+fn outline_edges(outline: &[Vector]) -> impl Iterator<Item = (Vector, Vector)> + '_ {+ outline+ .iter()+ .enumerate()+ .map(move |(i, corner)| (*corner, outline[(i + 1) % outline.len()]))+}++/// Twice the area enclosed by a closed outline, negative when it is wound clockwise.+#[cfg(feature = "dim2")]+fn signed_area(outline: &[Vector]) -> Real {+ outline_edges(outline)+ .map(|(a, b)| a.x * b.y - a.y * b.x)+ .sum()+}++impl TypedCompositeShape for Compound {+ type PartShape = dyn Shape;+ type PartNormalConstraints = CompoundPseudoNormals;++ #[inline(always)]+ fn map_typed_part_at<T>(+ &self,+ i: u32,+ mut f: impl FnMut(Option<&Pose>, &Self::PartShape, Option<&Self::PartNormalConstraints>) -> T,+ ) -> Option<T> {+ let (part_pos, part) = &self.shapes[i as usize];+ Some(f(Some(part_pos), &**part, self.part_normal_constraints(i)))+ }++ #[inline(always)]+ fn map_untyped_part_at<T>(+ &self,+ i: u32,+ mut f: impl FnMut(Option<&Pose>, &Self::PartShape, Option<&dyn NormalConstraints>) -> T,+ ) -> Option<T> {+ let (part_pos, part) = &self.shapes[i as usize];+ let constraints = self+ .part_normal_constraints(i)+ .map(|c| c as &dyn NormalConstraints);+ Some(f(Some(part_pos), &**part, constraints))+ }+}++#[cfg(test)]+#[cfg(all(feature = "dim2", feature = "alloc", feature = "std"))]+mod test {+ use super::{Compound, CompoundFlags};+ use crate::math::{Pose, Real, Rotation, Vector};+ use crate::query::{ContactManifold, DefaultQueryDispatcher, PersistentQueryDispatcher};+ use crate::shape::{ConvexPolygon, Cuboid, SharedShape, Triangle};+ use alloc::{vec, vec::Vec};++ /// A flat run that turns into a ramp, decomposed the way a convex decomposition would leave it:+ /// a big piece below and a wedge above, meeting along a cut that runs right from the ramp foot+ /// at the origin. The ramp face and the cut leave the wedge with a tip pointing back along the+ /// flat run, which is what a body slides into.+ fn ramp_foot() -> Compound {+ let part = |points: &[[Real; 2]]| {+ let points = points.iter().map(|p| Vector::new(p[0], p[1])).collect();+ (+ Pose::IDENTITY,+ SharedShape::new(+ ConvexPolygon::from_convex_polyline_unmodified(points).expect("convex part"),+ ),+ )+ };++ Compound::new(vec![+ part(&[+ [-3.825, -0.015],+ [-11.913, -6.486],+ [5.166, -6.486],+ [5.165, -0.015],+ [0.0, 0.0],+ ]),+ part(&[[0.0, 0.0], [5.165, -0.015], [3.432, 1.912], [2.135, 1.891]]),+ ])+ }++ /// The normals the wedge reports against a box whose right edge sits `overshoot` past the tip.+ fn normals_against_the_wedge(compound: &Compound, overshoot: Real) -> Vec<Vector> {+ let slider = Cuboid::new(Vector::new(0.42, 0.20));+ let pos12 = Pose::from_parts(Vector::new(overshoot - 0.42, 0.198), Default::default());++ let mut manifolds: Vec<ContactManifold<(), ()>> = Vec::new();+ let mut workspace = None;+ DefaultQueryDispatcher+ .contact_manifolds(+ &pos12,+ compound,+ &slider,+ 0.02,+ &mut manifolds,+ &mut workspace,+ )+ .expect("dispatch");++ manifolds+ .iter()+ .filter(|manifold| manifold.subshape1 == 1 && !manifold.points.is_empty())+ .map(|manifold| manifold.local_n1)+ .collect()+ }++ #[test]+ fn cut_edges_are_dropped_and_close_the_corner_they_end_at() {+ let mut compound = ramp_foot();+ compound.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, None);++ // Each part loses exactly the cut it shares with the other.+ assert_eq!(+ compound+ .part_normal_constraints(0)+ .unwrap()+ .boundary_edges+ .len(),+ 4+ );+ let wedge = compound.part_normal_constraints(1).unwrap();+ assert_eq!(wedge.boundary_edges.len(), 3);++ // The ramp face runs into the cut at the tip, so its cone closes onto itself there.+ let ramp = wedge+ .boundary_edges+ .iter()+ .find(|cone| cone.face.x < -0.5)+ .expect("ramp face");+ assert_eq!(ramp.counter_clockwise_limit, ramp.face);+ }++ /// Nothing guarantees which way a part was wound, and a clockwise one would have every normal+ /// pointing into itself.+ #[test]+ fn a_clockwise_part_still_faces_outwards() {+ let clockwise = Triangle::new(+ Vector::new(0.0, 0.0),+ Vector::new(0.0, 1.0),+ Vector::new(1.0, 0.0),+ );+ let mut compound = Compound::new(vec![(Pose::IDENTITY, SharedShape::new(clockwise))]);+ compound.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, None);++ let cones = compound.part_normal_constraints(0).expect("polygonal part");+ assert_eq!(cones.boundary_edges.len(), 3);++ // Every face points away from the triangle's interior, which lies towards the origin.+ let interior = Vector::new(0.25, 0.25);+ for cone in &cones.boundary_edges {+ assert!(+ cone.face.dot(interior) < 0.0 || cone.face.dot(Vector::new(1.0, 1.0)) > 0.0,+ "inward face {:?}",+ cone.face+ );+ }++ // The hypotenuse is the only face pointing up and to the right.+ let hypotenuse = cones+ .boundary_edges+ .iter()+ .find(|cone| cone.face.x > 0.5 && cone.face.y > 0.5)+ .expect("outward hypotenuse");+ assert!(hypotenuse.face.dot(Vector::new(1.0, 1.0).normalize()) > 0.99);+ }++ #[test]+ fn a_body_running_into_the_tip_reports_no_contact_with_the_cut() {+ let plain = ramp_foot();+ let mut fixed = ramp_foot();+ fixed.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, None);++ // Against the bare compound the wedge answers with its tip axis: a wall across the flat run.+ let ghost = normals_against_the_wedge(&plain, 0.0);+ assert_eq!(ghost.len(), 1);+ assert!(+ ghost[0].x < -0.99,+ "expected a wall normal, got {:?}",+ ghost[0]+ );++ // The cut cannot be touched, so the wedge reports nothing until the ramp itself is reached.+ assert!(normals_against_the_wedge(&fixed, 0.0).is_empty());+ }++ /// An L wound counter-clockwise, split along the diagonal a convex decomposition would cut+ /// from its reflex corner. The cut lands on two corners of the union: the convex one at the+ /// origin, and the reflex one at `(1, 1)`.+ fn cut_ell() -> Compound {+ let part = |points: &[[Real; 2]]| {+ let points = points.iter().map(|p| Vector::new(p[0], p[1])).collect();+ (+ Pose::IDENTITY,+ SharedShape::new(+ ConvexPolygon::from_convex_polyline_unmodified(points).expect("convex part"),+ ),+ )+ };++ let mut compound = Compound::new(vec![+ part(&[[0.0, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0]]),+ part(&[[0.0, 0.0], [1.0, 1.0], [1.0, 2.0], [0.0, 2.0]]),+ ]);+ compound.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, None);+ compound+ }++ /// The cone of the boundary edge of `part` whose outward normal is `face`.+ fn cone_facing(compound: &Compound, part: u32, face: Vector) -> super::CompoundEdgeCone {+ *compound+ .part_normal_constraints(part)+ .expect("polygonal part")+ .boundary_edges+ .iter()+ .find(|cone| (cone.face - face).length() < 1.0e-5)+ .unwrap_or_else(|| panic!("no edge facing {face:?}"))+ }++ /// A corner a cut splits is still a corner of the union, so the two edges meeting there open+ /// towards each other even though they belong to different parts.+ #[test]+ fn a_convex_corner_split_by_a_cut_opens_across_the_parts() {+ let compound = cut_ell();++ // Each part keeps its three outline edges and loses the diagonal it shares.+ for part in 0..2 {+ assert_eq!(+ compound+ .part_normal_constraints(part)+ .unwrap()+ .boundary_edges+ .len(),+ 3,+ "part {part}"+ );+ }++ // The union turns 90 degrees at the origin, between the bottom edge of one part and the+ // left edge of the other. Both cones reach the bisector, splitting the corner between them.+ let bisector = Vector::new(-1.0, -1.0).normalize();+ let bottom = cone_facing(&compound, 0, -Vector::Y);+ let left = cone_facing(&compound, 1, -Vector::X);++ assert!(+ (bottom.clockwise_limit - bisector).length() < 1.0e-5,+ "bottom stopped at {:?}",+ bottom.clockwise_limit+ );+ assert!(+ (left.counter_clockwise_limit - bisector).length() < 1.0e-5,+ "left stopped at {:?}",+ left.counter_clockwise_limit+ );+ }++ /// A concave corner has no outward range for its edges to share, so each keeps its own normal+ /// -- the same thing that happens where a surface runs into a cut.+ #[test]+ fn a_concave_corner_split_by_a_cut_stays_closed() {+ let compound = cut_ell();++ // The reflex corner of the L, at `(1, 1)`: the upwards edge of one part meets the+ // rightwards edge of the other.+ let upwards = cone_facing(&compound, 0, Vector::Y);+ let rightwards = cone_facing(&compound, 1, Vector::X);++ assert_eq!(upwards.counter_clockwise_limit, upwards.face);+ assert_eq!(rightwards.clockwise_limit, rightwards.face);+ }++ /// A row of boxes on a shared grid, the way a voxel body reaches a compound, optionally+ /// rotated as a whole. Every part computes its own corners, so the seams are only found if+ /// corners that round differently still weld.+ fn voxel_row(n: u32, size: Real, origin: Real, angle: Real) -> Compound {+ let half = size / 2.0;+ let rotation = Rotation::from_angle(angle);+ let parts = (0..n)+ .map(|i| {+ let center = Vector::new(origin + i as Real * size, 0.0);+ (+ Pose::from_parts(rotation * center, rotation),+ SharedShape::new(Cuboid::new(Vector::new(half, half))),+ )+ })+ .collect();++ let mut compound = Compound::new(parts);+ compound.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, None);+ compound+ }++ /// How many boundary edges each part of a row kept. A welded row leaves the two ends with+ /// three and every box between them with two.+ fn boundary_edge_counts(compound: &Compound, n: u32) -> Vec<usize> {+ (0..n)+ .map(|i| {+ compound+ .part_normal_constraints(i)+ .map_or(99, |cones| cones.boundary_edges.len())+ })+ .collect()+ }++ /// Parts of a grid meet on corners each computes for itself, and the two spellings need not+ /// round alike. Every row here leaves at least one seam a few ULPs wide.+ #[test]+ fn a_voxel_row_finds_seams_its_parts_rounded_differently() {+ for &(size, origin, angle) in &[+ (1.0 as Real, 0.0 as Real, 0.1 as Real),+ (1.0, 0.0, 0.5236),+ (1.0, 0.0, 0.7854),+ (0.1, 0.0, 0.0),+ (0.7, 0.0, 0.0),+ (1.0, 0.05, 0.0),+ (0.1, 1000.0, 0.0),+ (1.0, 1000.0, 0.7854),+ ] {+ assert_eq!(+ boundary_edge_counts(&voxel_row(5, size, origin, angle), 5),+ alloc::vec![3, 2, 2, 2, 3],+ "size {size} origin {origin} angle {angle}"+ );+ }+ }++ /// A zero tolerance is the exact comparison, which only recognizes a seam whose two spellings+ /// round to the very same bits.+ #[test]+ fn a_zero_tolerance_welds_only_bit_identical_corners() {+ let mut rotated = voxel_row(5, 1.0, 0.0, 0.1);+ let welded = boundary_edge_counts(&rotated, 5);+ assert_eq!(welded, alloc::vec![3, 2, 2, 2, 3]);++ // Dropping the tolerance can only lose cuts, never find new ones, and this rotation puts+ // at least one seam beyond an exact comparison.+ rotated.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, Some(0.0));+ let exact = boundary_edge_counts(&rotated, 5);+ assert!(+ exact.iter().zip(welded.iter()).all(|(a, b)| a >= b),+ "exact found a cut the tolerance missed: {exact:?}"+ );+ assert!(+ exact.iter().sum::<usize>() > welded.iter().sum::<usize>(),+ "exact matched every seam: {exact:?}"+ );++ // A grid whose corners land on exact coordinates never needed the tolerance.+ let mut exact = voxel_row(5, 1.0, 0.0, 0.0);+ exact.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, Some(0.0));+ assert_eq!(boundary_edge_counts(&exact, 5), alloc::vec![3, 2, 2, 2, 3]);+ }++ /// Every interior seam of a full grid is found, and only the perimeter survives: an `n` by `n`+ /// grid of cells encloses exactly `4 * n` boundary edges. Four cells meet at every interior+ /// corner, so this also exercises welding more than two coincident corners at once.+ #[test]+ fn a_voxel_grid_keeps_only_its_perimeter() {+ for &(n, size, origin, angle) in &[+ (3u32, 1.0 as Real, 0.0 as Real, 0.1 as Real),+ (3, 0.1, 0.0, 0.0),+ (4, 0.7, 5.0, 0.7854),+ ] {+ let half = size / 2.0;+ let rotation = Rotation::from_angle(angle);+ let parts = (0..n)+ .flat_map(|i| {+ (0..n).map(move |j| {+ let center =+ Vector::new(origin + i as Real * size, origin + j as Real * size);+ (+ Pose::from_parts(rotation * center, rotation),+ SharedShape::new(Cuboid::new(Vector::new(half, half))),+ )+ })+ })+ .collect();++ let mut compound = Compound::new(parts);+ compound.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, None);++ let counts = boundary_edge_counts(&compound, n * n);+ assert_eq!(+ counts.iter().sum::<usize>(),+ (4 * n) as usize,+ "size {size} origin {origin} angle {angle}: {counts:?}"+ );+ }+ }++ /// The two signed zeros are the same point and hash apart, so a corner one part spells `0.0`+ /// and another `-0.0` has to weld even where no tolerance is allowed at all.+ #[test]+ fn signed_zero_corners_weld_at_zero_tolerance() {+ assert_ne!(+ (0.0 as Real).to_bits(),+ (-0.0 as Real).to_bits(),+ "the two zeros are meant to differ bitwise"+ );++ // Two triangles sharing the edge from the origin to `(1, 0)`, the second spelling its end+ // of that edge with negative zeros.+ let mut compound = Compound::new(vec![+ (+ Pose::IDENTITY,+ SharedShape::new(Triangle::new(+ Vector::new(0.0, 0.0),+ Vector::new(1.0, 0.0),+ Vector::new(0.5, 1.0),+ )),+ ),+ (+ Pose::IDENTITY,+ SharedShape::new(Triangle::new(+ Vector::new(-0.0, -0.0),+ Vector::new(0.5, -1.0),+ Vector::new(1.0, -0.0),+ )),+ ),+ ]);+ compound.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, Some(0.0));++ assert_eq!(boundary_edge_counts(&compound, 2), alloc::vec![2, 2]);+ }++ /// The tolerance follows each corner's own distance from the origin rather than the whole+ /// compound's, so a part placed far away does not coarsen detail near it.+ #[test]+ fn a_distant_part_does_not_coarsen_detail_near_the_origin() {+ let small = 1.0e-3;+ let box_at = |x: Real, half: Real| {+ (+ Pose::from_parts(Vector::new(x, 0.0), Default::default()),+ SharedShape::new(Cuboid::new(Vector::new(half, half))),+ )+ };++ // Two small boxes with a gap between them, and one part 1e5 away. Scaled to the distant+ // part the gap would vanish; scaled to the small boxes themselves it is enormous.+ let mut compound = Compound::new(vec![+ box_at(0.0, small),+ box_at(4.0 * small, small),+ box_at(1.0e5, 1.0),+ ]);+ compound.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, None);++ for part in 0..2 {+ assert_eq!(+ compound+ .part_normal_constraints(part)+ .unwrap()+ .boundary_edges+ .len(),+ 4,+ "part {part} lost an edge to the distant part's scale"+ );+ }+ }++ #[test]+ fn contacts_with_the_ramp_itself_are_left_alone() {+ let plain = ramp_foot();+ let mut fixed = ramp_foot();+ fixed.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, None);++ let expected = normals_against_the_wedge(&plain, 0.01);+ assert_eq!(expected.len(), 1);+ assert!(+ expected[0].y > 0.7,+ "expected the ramp face, got {:?}",+ expected[0]+ );+ assert_eq!(normals_against_the_wedge(&fixed, 0.01), expected);+ }+}++#[cfg(test)]+#[cfg(all(feature = "dim3", feature = "alloc", feature = "std"))]+mod dim3_test {+ use super::{Compound, CompoundFlags};+ use crate::math::{Pose, Real, Rotation, Vector};+ use crate::shape::{Cuboid, SharedShape};+ use alloc::{vec, vec::Vec};++ /// A flat run turning into a ramp, split along the diagonal a convex decomposition would cut:+ /// a slab and a wedge, extruded, sharing one quad exactly. Built through `convex_hull`, the+ /// way the Godot plugin builds every `ConvexPolygonShape3D`.+ fn ramp_foot() -> Compound {+ let prism = |outline: &[[Real; 2]]| {+ let corners: Vec<Vector> = outline+ .iter()+ .flat_map(|p| [Vector::new(p[0], p[1], -3.0), Vector::new(p[0], p[1], 3.0)])+ .collect();+ (+ Pose::IDENTITY,+ SharedShape::convex_hull(&corners).expect("convex prism"),+ )+ };++ Compound::new(vec![+ prism(&[[-6.0, 0.0], [5.0, 0.0], [11.0, -6.0], [-6.0, -6.0]]),+ prism(&[[5.0, 0.0], [9.0, 3.0], [11.0, 3.0], [11.0, -6.0]]),+ ])+ }++ #[test]+ fn cut_faces_are_dropped_from_both_parts() {+ let mut compound = ramp_foot();+ compound.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, None);++ // Each prism has 6 faces and loses the shared quad -- which only holds if `convex_hull`+ // produced the cut with the same corners on both sides, the premise everything rests on.+ for part in 0..2 {+ let cones = compound.part_normal_constraints(part).expect("polyhedron");+ assert_eq!(cones.boundary_faces.len(), 5, "part {part}");+ }+ }++ /// The 2D cut L, extruded. The cut is a quad, and it reaches the union's surface along two+ /// vertical edges: the convex one at the origin, and the reflex one above `(1, 1)`.+ fn cut_ell() -> Compound {+ let prism = |outline: &[[Real; 2]]| {+ let corners: Vec<Vector> = outline+ .iter()+ .flat_map(|p| [Vector::new(p[0], p[1], -1.0), Vector::new(p[0], p[1], 1.0)])+ .collect();+ (+ Pose::IDENTITY,+ SharedShape::convex_hull(&corners).expect("convex prism"),+ )+ };++ let mut compound = Compound::new(vec![+ prism(&[[0.0, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0]]),+ prism(&[[0.0, 0.0], [1.0, 1.0], [1.0, 2.0], [0.0, 2.0]]),+ ]);+ compound.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, None);+ compound+ }++ /// The pseudo-normal the cone of `part`'s face pointing along `face` carries at the vertical+ /// edge standing over `corner`.+ fn pseudo_normal_at_vertical_edge(+ compound: &Compound,+ part: u32,+ face: Vector,+ corner: [Real; 2],+ ) -> Vector {+ let (bottom, top) = (+ Vector::new(corner[0], corner[1], -1.0),+ Vector::new(corner[0], corner[1], 1.0),+ );++ let faces = compound.part_faces();+ let (_, corners) = faces[part as usize]+ .as_ref()+ .expect("polyhedron")+ .iter()+ .find(|(normal, _)| (*normal - face).length() < 1.0e-5)+ .unwrap_or_else(|| panic!("no face pointing along {face:?}"));++ // `edge_pseudo_normals[i]` describes the edge from `corners[i]` to its successor.+ let edge = (0..corners.len())+ .find(|i| {+ let ends = [corners[*i], corners[(*i + 1) % corners.len()]];+ ends.iter().any(|end| (*end - bottom).length() < 1.0e-5)+ && ends.iter().any(|end| (*end - top).length() < 1.0e-5)+ })+ .unwrap_or_else(|| panic!("no vertical edge over {corner:?}"));++ compound+ .part_normal_constraints(part)+ .expect("polyhedron")+ .boundary_faces+ .iter()+ .find(|cone| (cone.face - face).length() < 1.0e-5)+ .expect("cone")+ .edge_pseudo_normals[edge]+ }++ /// An edge a cut splits is still an edge of the union, so the two faces meeting along it open+ /// towards each other even though they belong to different parts.+ #[test]+ fn a_convex_edge_split_by_a_cut_opens_across_the_parts() {+ let compound = cut_ell();++ // Each prism keeps five faces and loses the cut quad it shares.+ for part in 0..2 {+ assert_eq!(+ compound+ .part_normal_constraints(part)+ .unwrap()+ .boundary_faces+ .len(),+ 5,+ "part {part}"+ );+ }++ // The union turns 90 degrees along the vertical edge over the origin, between the front+ // face of one prism and the left face of the other.+ let halfway = Vector::new(-1.0, -1.0, 0.0).normalize();+ for (part, face) in [(0, -Vector::Y), (1, -Vector::X)] {+ let pseudo_normal = pseudo_normal_at_vertical_edge(&compound, part, face, [0.0, 0.0]);+ assert!(+ (pseudo_normal - halfway).length() < 1.0e-5,+ "part {part} stopped at {pseudo_normal:?}"+ );+ }+ }++ /// A concave edge has no outward range for its faces to share, so each keeps its own normal --+ /// the same thing that happens along an edge whose other face was cut away.+ #[test]+ fn a_concave_edge_split_by_a_cut_stays_closed() {+ let compound = cut_ell();++ // The reflex edge over `(1, 1)`, where the step rises out of the lower arm of the L.+ for (part, face) in [(0, Vector::Y), (1, Vector::X)] {+ let pseudo_normal = pseudo_normal_at_vertical_edge(&compound, part, face, [1.0, 1.0]);+ assert!(+ (pseudo_normal - face).length() < 1.0e-5,+ "part {part} opened to {pseudo_normal:?}"+ );+ }+ }++ /// A row of cuboids on a shared grid, the way a voxel body reaches a compound, optionally+ /// rotated as a whole.+ fn voxel_row(n: u32, size: Real, origin: Real, angle: Real) -> Compound {+ let half = size / 2.0;+ let rotation = Rotation::from_rotation_z(angle);+ let parts = (0..n)+ .map(|i| {+ let center = Vector::new(origin + i as Real * size, 0.0, 0.0);+ (+ Pose::from_parts(rotation * center, rotation),+ SharedShape::new(Cuboid::new(Vector::new(half, half, half))),+ )+ })+ .collect();++ let mut compound = Compound::new(parts);+ compound.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, None);+ compound+ }++ /// How many boundary faces each part of a row kept. A welded row leaves the two ends with+ /// five and every box between them with four.+ fn boundary_face_counts(compound: &Compound, n: u32) -> Vec<usize> {+ (0..n)+ .map(|i| {+ compound+ .part_normal_constraints(i)+ .map_or(99, |cones| cones.boundary_faces.len())+ })+ .collect()+ }++ /// A cuboid is a polyhedron the type system does not call one, so a voxel body used to get no+ /// cones at all; and its parts compute their own corners, which need not round alike.+ #[test]+ fn a_row_of_cuboids_shares_its_faces() {+ for &(size, origin, angle) in &[+ (1.0 as Real, 0.0 as Real, 0.0 as Real),+ (0.1, 0.0, 0.0),+ (0.7, 0.0, 0.0),+ (1.0, 0.05, 0.0),+ (0.1, 1000.0, 0.0),+ (1.0, 0.0, 0.1),+ (1.0, 1000.0, 0.7854),+ ] {+ assert_eq!(+ boundary_face_counts(&voxel_row(5, size, origin, angle), 5),+ vec![5, 4, 4, 4, 5],+ "size {size} origin {origin} angle {angle}"+ );+ }+ }++ /// A zero tolerance is the exact comparison, which only recognizes a cut whose corners round+ /// to the very same bits on both sides.+ #[test]+ fn a_zero_tolerance_welds_only_bit_identical_corners() {+ let mut rotated = voxel_row(5, 1.0, 0.0, 0.1);+ let welded = boundary_face_counts(&rotated, 5);+ assert_eq!(welded, vec![5, 4, 4, 4, 5]);++ // Dropping the tolerance can only lose cuts, never find new ones, and this rotation puts+ // at least one seam beyond an exact comparison.+ rotated.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, Some(0.0));+ let exact = boundary_face_counts(&rotated, 5);+ assert!(+ exact.iter().zip(welded.iter()).all(|(a, b)| a >= b),+ "exact found a cut the tolerance missed: {exact:?}"+ );+ assert!(+ exact.iter().sum::<usize>() > welded.iter().sum::<usize>(),+ "exact matched every seam: {exact:?}"+ );++ // A grid whose corners land on exact coordinates never needed the tolerance.+ let mut exact = voxel_row(5, 1.0, 0.0, 0.0);+ exact.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, Some(0.0));+ assert_eq!(boundary_face_counts(&exact, 5), vec![5, 4, 4, 4, 5]);+ }++ /// A body pressed into the wedge tip reports a normal along its own face, not a surface of+ /// the union; the cones pull it onto the one face that is.+ #[test]+ fn a_tip_normal_is_clamped_onto_the_ramp_face() {+ use crate::query::details::NormalConstraints;++ let mut compound = ramp_foot();+ compound.set_flags(CompoundFlags::FIX_INTERNAL_EDGES, None);+ let wedge = compound.part_normal_constraints(1).expect("polyhedron");++ let ramp = Vector::new(-0.6, 0.8, 0.0);+ let clamped = wedge+ .project_local_normal(Vector::new(-1.0, 0.0, 0.0))+ .expect("tip direction faces the outline");+ assert!((clamped - ramp).length() < 1.0e-4, "clamped to {clamped:?}");++ // A direction the outline genuinely faces is left alone.+ let kept = wedge.project_local_normal(ramp).expect("faces the outline");+ assert!((kept - ramp).length() < 1.0e-4, "moved to {kept:?}");+ }+}diff --git a/renderer/third_party/parry3d/src/shape/compound_pseudo_normals.rs b/renderer/third_party/parry3d/src/shape/compound_pseudo_normals.rsnew file mode 100644index 0000000..3cec9f9--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/compound_pseudo_normals.rs@@ -0,0 +1,253 @@+use crate::math::{Real, Vector};++#[cfg(feature = "alloc")]+use crate::query::details::NormalConstraints;+#[cfg(feature = "alloc")]+use alloc::vec::Vec;++/// Whether the turn from `from` to `to` is clockwise.+#[cfg(all(feature = "alloc", feature = "dim2"))]+pub(crate) fn turns_clockwise(from: Vector, to: Vector) -> bool {+ from.x * to.y - from.y * to.x < 0.0+}++/// The directions one boundary edge of a [`Compound`](crate::shape::Compound) part may push along.+///+/// Each limit reaches halfway towards the boundary edge next to it along the union's outline, which+/// may belong to another part where a cut splits the outline at that corner, so the two edges+/// meeting there split its range between them. A limit stops at `face` where the corner is concave,+/// which leaves no range to share, or where the surface simply ends against a cut.+#[cfg(all(feature = "alloc", feature = "dim2"))]+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[derive(Clone, Copy, Debug)]+pub struct CompoundEdgeCone {+ /// The edge's outward normal.+ pub face: Vector,+ /// How far the cone reaches at the edge's clockwise end.+ pub clockwise_limit: Vector,+ /// How far the cone reaches at the edge's counter-clockwise end.+ pub counter_clockwise_limit: Vector,+}++#[cfg(all(feature = "alloc", feature = "dim2"))]+impl CompoundEdgeCone {+ fn contains(&self, dir: Vector) -> bool {+ dir.dot(self.face) > 0.0+ && !turns_clockwise(self.clockwise_limit, dir)+ && !turns_clockwise(dir, self.counter_clockwise_limit)+ }++ /// The direction in this cone closest to `dir`.+ fn clamped(&self, dir: Vector) -> Vector {+ if self.contains(dir) {+ dir+ } else if dir.dot(self.clockwise_limit) >= dir.dot(self.counter_clockwise_limit) {+ self.clockwise_limit+ } else {+ self.counter_clockwise_limit+ }+ }+}++/// The outward normal cones of one [`Compound`](crate::shape::Compound) part.+///+/// Parts of a decomposed outline meet along cut edges that lie inside the union, where nothing can+/// reach them -- but each part is convex and reports contacts against its own faces regardless, so+/// a body sliding across a join catches on a face that is not a surface. Dropping the edges a+/// sibling part covers leaves every part facing the way the union does.+///+/// The [`Compound`](crate::shape::Compound) counterpart of+/// [`SegmentPseudoNormals`](crate::shape::SegmentPseudoNormals) and+/// [`TrianglePseudoNormals`](crate::shape::TrianglePseudoNormals), which describe a part that is a+/// single face; a compound part is a whole polygon, so it carries one cone per boundary edge.+#[cfg(all(feature = "alloc", feature = "dim2"))]+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[derive(Clone, Debug, Default)]+pub struct CompoundPseudoNormals {+ /// One cone per boundary edge, in the part's local frame. Cut edges are absent.+ pub boundary_edges: Vec<CompoundEdgeCone>,+}++#[cfg(all(feature = "alloc", feature = "dim2"))]+impl NormalConstraints for CompoundPseudoNormals {+ /// Projects `dir` onto the closest direction the part's outline can face.+ ///+ /// Returns `false` when nothing faces that way, so a contact reached from inside the union is+ /// dropped rather than turned around.+ fn project_local_normal_mut(&self, dir: &mut Vector) -> bool {+ let mut nearest: Option<(Vector, Real)> = None;++ for edge in &self.boundary_edges {+ let candidate = edge.clamped(*dir);+ let alignment = dir.dot(candidate);++ match nearest {+ Some((_, best)) if alignment <= best => {}+ _ => nearest = Some((candidate, alignment)),+ }+ }++ match nearest {+ Some((direction, alignment)) if alignment > 0.0 => {+ *dir = direction;+ true+ }+ _ => false,+ }+ }+}++/// The directions one boundary face of a [`Compound`](crate::shape::Compound) part may push+/// along.+///+/// Each edge pseudo-normal reaches halfway towards the boundary face across that edge, which may+/// belong to another part where a cut splits the surface along it. It keeps the face's own normal+/// where the edge is concave, which leaves no range to share, or where the surface ends against a+/// cut.+#[cfg(all(feature = "alloc", feature = "dim3"))]+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[derive(Clone, Debug)]+pub struct CompoundFaceCone {+ /// The face's outward normal.+ pub face: Vector,+ /// The outward pseudo-normal at each edge of the face.+ pub edge_pseudo_normals: Vec<Vector>,+}++/// The outward normal cones of one [`Compound`](crate::shape::Compound) part.+///+/// The 3D counterpart of the 2D edge cones: faces two parts share are cuts made by a convex+/// decomposition, interior to the union where nothing can reach them, so they are absent and no+/// contact normal can be clamped onto one.+#[cfg(all(feature = "alloc", feature = "dim3"))]+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[derive(Clone, Debug, Default)]+pub struct CompoundPseudoNormals {+ /// One cone per boundary face of the part, in the part's local frame.+ pub boundary_faces: Vec<CompoundFaceCone>,+}++#[cfg(all(feature = "alloc", feature = "dim3"))]+impl NormalConstraints for CompoundPseudoNormals {+ /// Projects `dir` into the normal cone of the boundary face it points most directly out of,+ /// the way [`TrianglePseudoNormals`](crate::shape::TrianglePseudoNormals) does for one+ /// triangle.+ ///+ /// Returns `false` for a part with no boundary face at all: it is buried inside the union,+ /// where nothing can touch it.+ fn project_local_normal_mut(&self, dir: &mut Vector) -> bool {+ let mut best: Option<(&CompoundFaceCone, Real)> = None;++ for cone in &self.boundary_faces {+ let alignment = dir.dot(cone.face);+ match best {+ Some((_, best_alignment)) if alignment <= best_alignment => {}+ _ => best = Some((cone, alignment)),+ }+ }++ let Some((cone, _)) = best else {+ return false;+ };++ let closest_edge = cone+ .edge_pseudo_normals+ .iter()+ .copied()+ .max_by(|a, b| dir.dot(*a).total_cmp(&dir.dot(*b)))+ .unwrap_or(cone.face);+ crate::shape::pseudo_normals::project_into_cone(cone.face, closest_edge, dir)+ }+}++#[cfg(test)]+#[cfg(all(feature = "dim2", feature = "alloc"))]+mod test {+ use super::{CompoundEdgeCone, CompoundPseudoNormals, NormalConstraints};+ use crate::math::Vector;+ use alloc::vec;++ fn cone(face: Vector, clockwise: Vector, counter_clockwise: Vector) -> CompoundEdgeCone {+ CompoundEdgeCone {+ face,+ clockwise_limit: clockwise,+ counter_clockwise_limit: counter_clockwise,+ }+ }++ /// A cone with nowhere to open, as happens where a surface runs into a cut at both ends.+ fn pinned(face: Vector) -> CompoundEdgeCone {+ cone(face, face, face)+ }++ #[test]+ fn buried_part_rejects_everything() {+ let normals = CompoundPseudoNormals::default();++ assert!(normals.project_local_normal(Vector::Y).is_none());+ assert!(normals.project_local_normal(-Vector::Y).is_none());+ }++ #[test]+ fn a_direction_already_on_the_outline_is_left_alone() {+ let normals = CompoundPseudoNormals {+ boundary_edges: vec![cone(+ Vector::Y,+ Vector::new(1.0, 1.0).normalize(),+ Vector::new(-1.0, 1.0).normalize(),+ )],+ };++ assert_eq!(normals.project_local_normal(Vector::Y), Some(Vector::Y));++ let inside_the_cone = Vector::new(0.3, 1.0).normalize();+ assert_eq!(+ normals.project_local_normal(inside_the_cone),+ Some(inside_the_cone)+ );+ }++ #[test]+ fn a_direction_past_the_corner_is_pulled_back_to_it() {+ let corner = Vector::new(1.0, 1.0).normalize();+ let normals = CompoundPseudoNormals {+ boundary_edges: vec![cone(Vector::Y, corner, Vector::new(-1.0, 1.0).normalize())],+ };++ assert_eq!(normals.project_local_normal(Vector::X), Some(corner));+ }++ #[test]+ fn picks_the_edge_the_normal_points_out_of() {+ let normals = CompoundPseudoNormals {+ boundary_edges: vec![pinned(Vector::Y), pinned(Vector::X)],+ };++ assert_eq!(normals.project_local_normal(Vector::Y), Some(Vector::Y));+ assert_eq!(normals.project_local_normal(Vector::X), Some(Vector::X));+ }++ /// The case a convex decomposition creates: a wedge whose tip is a boundary edge running into a+ /// cut. A body driving into the tip reports a normal along the wedge axis, which is not a+ /// surface direction, and has to be pulled onto the one boundary edge that is.+ #[test]+ fn a_direction_reaching_the_part_from_behind_is_dropped() {+ let normals = CompoundPseudoNormals {+ boundary_edges: vec![pinned(Vector::Y)],+ };++ assert!(normals.project_local_normal(-Vector::Y).is_none());+ }++ #[test]+ fn clamps_a_wedge_tip_normal_onto_the_boundary_edge() {+ let ramp = Vector::new(-0.6, 0.8).normalize();+ let normals = CompoundPseudoNormals {+ boundary_edges: vec![pinned(ramp)],+ };++ let clamped = normals.project_local_normal(-Vector::X).unwrap();++ assert!((clamped - ramp).length() < 1.0e-5);+ }+}diff --git a/renderer/third_party/parry3d/src/shape/cone.rs b/renderer/third_party/parry3d/src/shape/cone.rsnew file mode 100644index 0000000..eb6fc90--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/cone.rs@@ -0,0 +1,174 @@+//! Support mapping based Cone shape.++use crate::math::{Real, Vector};+use crate::shape::SupportMap;+use crate::utils::WSign;++#[cfg(feature = "alloc")]+use either::Either;++/// A 3D cone shape with apex pointing upward along the Y axis.+///+/// A cone is a shape that tapers from a circular base to a point (apex). In Parry,+/// cones are always aligned with the Y axis, with the base at y = -half_height and+/// the apex at y = +half_height.+///+/// # Structure+///+/// - **Axis**: Always aligned with Y axis (apex points up)+/// - **Base**: Circular base at y = -half_height with the given radius+/// - **Apex**: Vector at y = +half_height+/// - **Total height**: `2 * half_height`+///+/// # Properties+///+/// - **3D only**: Only available with the `dim3` feature+/// - **Convex**: Yes, cones are convex shapes+/// - **Apex**: Sharp point at the top+/// - **Flat base**: Circular base (not rounded)+/// - **Sharp edge**: Rim where cone surface meets the base+///+/// # Coordinate System+///+/// The cone is centered at the origin with:+/// - Base center at `(0, -half_height, 0)`+/// - Apex at `(0, half_height, 0)`+/// - Circular base in the XZ plane+///+/// # Use Cases+///+/// - Projectile nose cones+/// - Traffic cones and markers+/// - Funnel shapes+/// - Spotlight or vision cone representations+/// - Conical collision bounds+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Cone;+///+/// // Create a cone: base radius 3.0, total height 8.0+/// let cone = Cone::new(4.0, 3.0);+///+/// assert_eq!(cone.half_height, 4.0);+/// assert_eq!(cone.radius, 3.0);+///+/// // The cone:+/// // - Base at y = -4.0 with radius 3.0+/// // - Apex at y = +4.0 (sharp point)+/// // - Total height = 8.0+/// # }+/// ```+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(PartialEq, Debug, Copy, Clone)]+#[repr(C)]+pub struct Cone {+ /// Half the total height of the cone.+ ///+ /// The cone extends from y = -half_height (base center) to+ /// y = +half_height (apex). Must be positive.+ pub half_height: Real,++ /// The radius of the circular base.+ ///+ /// The base is a circle in the XZ plane at y = -half_height.+ /// Must be positive.+ pub radius: Real,+}++impl Cone {+ /// Creates a new cone with apex pointing upward along the Y axis.+ ///+ /// # Arguments+ ///+ /// * `half_height` - Half the total height (apex to base center distance / 2)+ /// * `radius` - The radius of the circular base+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Cone;+ ///+ /// // Create a cone with height 6.0 and base radius 2.0+ /// let cone = Cone::new(3.0, 2.0);+ ///+ /// assert_eq!(cone.half_height, 3.0);+ /// assert_eq!(cone.radius, 2.0);+ ///+ /// // The cone structure:+ /// // - Apex at (0, 3, 0) - the top point+ /// // - Base center at (0, -3, 0)+ /// // - Base radius 2.0 in the XZ plane+ /// // - Total height from apex to base = 6.0+ /// # }+ /// ```+ pub fn new(half_height: Real, radius: Real) -> Cone {+ Cone {+ half_height,+ radius,+ }+ }++ /// Computes a scaled version of this cone.+ ///+ /// If the scaling factor is non-uniform, then it can’t be represented as+ /// cone. Instead, a convex polyhedral approximation (with `nsubdivs`+ /// subdivisions) is returned. Returns `None` if that approximation had degenerate+ /// normals (for example if the scaling factor along one axis is zero).+ #[cfg(feature = "alloc")]+ #[inline]+ pub fn scaled(+ self,+ scale: Vector,+ nsubdivs: u32,+ ) -> Option<Either<Self, super::ConvexPolyhedron>> {+ // NOTE: if the y scale is negative, the result cone points downwards,+ // which can’t be represented with this Cone (without a transform).+ if scale.x != scale.z || scale.y < 0.0 {+ // The scaled shape isn't a cone.+ let (mut vtx, idx) = self.to_trimesh(nsubdivs);+ vtx.iter_mut().for_each(|pt| *pt *= scale);+ Some(Either::Right(super::ConvexPolyhedron::from_convex_mesh(+ vtx, &idx,+ )?))+ } else {+ Some(Either::Left(Self::new(+ self.half_height * scale.y,+ self.radius * scale.x,+ )))+ }+ }+}++impl SupportMap for Cone {+ #[inline]+ fn local_support_point(&self, dir: Vector) -> Vector {+ let mut vres = dir;++ vres.y = 0.0;+ let (mut vres, length) = vres.normalize_and_length();++ if length == 0.0 {+ vres = Vector::ZERO;+ vres.y = dir.y.copy_sign_to(self.half_height);+ } else {+ vres *= self.radius;+ vres.y = -self.half_height;++ if dir.dot(vres) < dir.y * self.half_height {+ vres = Vector::ZERO;+ vres.y = self.half_height+ }+ }++ vres+ }+}diff --git a/renderer/third_party/parry3d/src/shape/convex_polygon.rs b/renderer/third_party/parry3d/src/shape/convex_polygon.rsnew file mode 100644index 0000000..0c36fdc--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/convex_polygon.rs@@ -0,0 +1,672 @@+use crate::math::{ComplexField, Real, RealField, Vector};+use crate::shape::{FeatureId, PackedFeatureId, PolygonalFeature, PolygonalFeatureMap, SupportMap};+use crate::utils;+use alloc::vec::Vec;++/// A 2D convex polygon.+///+/// A convex polygon is a closed 2D shape where all interior angles are less than 180 degrees,+/// and any line segment drawn between two points inside the polygon stays entirely within the polygon.+/// Common examples include triangles, rectangles, and regular polygons like hexagons.+///+/// # What is a convex polygon?+///+/// In 2D space, a polygon is **convex** if:+/// - Every interior angle is less than or equal to 180 degrees+/// - The line segment between any two points inside the polygon lies entirely inside the polygon+/// - All vertices "bulge outward" - there are no indentations or concave areas+///+/// Examples of **convex** polygons: triangle, square, regular pentagon, regular hexagon+/// Examples of **non-convex** (concave) polygons: star shapes, L-shapes, crescents+///+/// # Use cases+///+/// Convex polygons are widely used in:+/// - **Game development**: Character hitboxes, platform boundaries, simple building shapes+/// - **Physics simulations**: Rigid body collision detection (more efficient than arbitrary polygons)+/// - **Robotics**: Simplified environment representations, obstacle boundaries+/// - **Computer graphics**: Fast rendering primitives, clipping regions+/// - **Computational geometry**: As building blocks for more complex operations+///+/// # Representation+///+/// This structure stores:+/// - **Vectors**: The vertices of the polygon in counter-clockwise order+/// - **Normals**: Unit vectors perpendicular to each edge, pointing outward+///+/// The normals are pre-computed for efficient collision detection algorithms.+///+/// # Example: Creating a simple triangle+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::shape::ConvexPolygon;+/// use parry2d::math::Vector;+///+/// // Create a triangle from three vertices (counter-clockwise order)+/// let vertices = vec![+/// Vector::ZERO, // bottom-left+/// Vector::new(2.0, 0.0), // bottom-right+/// Vector::new(1.0, 2.0), // top+/// ];+///+/// let triangle = ConvexPolygon::from_convex_polyline(vertices)+/// .expect("Failed to create triangle");+///+/// // The polygon has 3 vertices+/// assert_eq!(triangle.points().len(), 3);+/// // and 3 edge normals (one per edge)+/// assert_eq!(triangle.normals().len(), 3);+/// # }+/// ```+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Clone, Debug)]+pub struct ConvexPolygon {+ points: Vec<Vector>,+ normals: Vec<Vector>,+}++impl ConvexPolygon {+ /// Creates a new 2D convex polygon from an arbitrary set of points by computing their convex hull.+ ///+ /// This is the most flexible constructor - it automatically computes the **convex hull** of the+ /// given points, which is the smallest convex polygon that contains all the input points.+ /// Think of it as wrapping a rubber band around the points.+ ///+ /// Use this when:+ /// - You have an arbitrary collection of points and want the convex boundary+ /// - You're not sure if your points form a convex shape+ /// - You want to simplify a point cloud to its convex outline+ ///+ /// # Returns+ ///+ /// - `Some(ConvexPolygon)` if successful+ /// - `None` if the convex hull computation failed (e.g., all points are collinear or coincident)+ ///+ /// # Example: Creating a convex polygon from arbitrary points+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::ConvexPolygon;+ /// use parry2d::math::Vector;+ ///+ /// // Some arbitrary points (including one inside the convex hull)+ /// let points = vec![+ /// Vector::ZERO,+ /// Vector::new(4.0, 0.0),+ /// Vector::new(2.0, 3.0),+ /// Vector::new(2.0, 1.0), // This point is inside the triangle+ /// ];+ ///+ /// let polygon = ConvexPolygon::from_convex_hull(&points)+ /// .expect("Failed to create convex hull");+ ///+ /// // The convex hull only has 3 vertices (the interior point was excluded)+ /// assert_eq!(polygon.points().len(), 3);+ /// # }+ /// ```+ ///+ /// # Example: Simplifying a point cloud+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::ConvexPolygon;+ /// use parry2d::math::Vector;+ ///+ /// // A cloud of points that roughly forms a circle+ /// let mut points = Vec::new();+ /// for i in 0..20 {+ /// let angle = (i as f32) * std::f32::consts::TAU / 20.0;+ /// points.push(Vector::new(angle.cos(), angle.sin()));+ /// }+ /// // Add some interior points+ /// points.push(Vector::ZERO);+ /// points.push(Vector::new(0.5, 0.5));+ ///+ /// let polygon = ConvexPolygon::from_convex_hull(&points)+ /// .expect("Failed to create convex hull");+ ///+ /// // The convex hull has 20 vertices (the boundary points)+ /// assert_eq!(polygon.points().len(), 20);+ /// # }+ /// ```+ pub fn from_convex_hull(points: &[Vector]) -> Option<Self> {+ let vertices = crate::transformation::convex_hull(points);+ Self::from_convex_polyline(vertices)+ }++ /// Creates a new 2D convex polygon from vertices that already form a convex shape.+ ///+ /// This constructor is more efficient than [`from_convex_hull`] because it **assumes** the input+ /// points already form a convex polygon in counter-clockwise order, and it doesn't compute the+ /// convex hull. The convexity is **not verified** - if you pass non-convex points, the resulting+ /// shape may behave incorrectly in collision detection.+ ///+ /// **Important**: Vectors must be ordered **counter-clockwise** (CCW). If you're unsure about the+ /// ordering or convexity, use [`from_convex_hull`] instead.+ ///+ /// This method automatically removes collinear vertices (points that lie on the line between+ /// their neighbors) to simplify the polygon. If you want to preserve all vertices exactly as given,+ /// use [`from_convex_polyline_unmodified`].+ ///+ /// # When to use this+ ///+ /// Use this constructor when:+ /// - You already know your points form a convex polygon+ /// - The points are ordered counter-clockwise around the shape+ /// - You want better performance by skipping convex hull computation+ ///+ /// # Returns+ ///+ /// - `Some(ConvexPolygon)` if successful+ /// - `None` if all points are nearly collinear (form an almost flat line) or there are fewer than 3 vertices after removing collinear points+ ///+ /// # Example: Creating a square+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::ConvexPolygon;+ /// use parry2d::math::Vector;+ ///+ /// // A square with vertices in counter-clockwise order+ /// let square = ConvexPolygon::from_convex_polyline(vec![+ /// Vector::ZERO, // bottom-left+ /// Vector::new(1.0, 0.0), // bottom-right+ /// Vector::new(1.0, 1.0), // top-right+ /// Vector::new(0.0, 1.0), // top-left+ /// ]).expect("Failed to create square");+ ///+ /// assert_eq!(square.points().len(), 4);+ /// # }+ /// ```+ ///+ /// # Example: Collinear points are automatically removed+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::ConvexPolygon;+ /// use parry2d::math::Vector;+ ///+ /// // A quadrilateral with one vertex on an edge (making it collinear)+ /// let polygon = ConvexPolygon::from_convex_polyline(vec![+ /// Vector::ZERO,+ /// Vector::new(2.0, 0.0),+ /// Vector::new(2.0, 1.0), // This point is on the line from (2,0) to (2,2)+ /// Vector::new(2.0, 2.0),+ /// Vector::new(0.0, 2.0),+ /// ]).expect("Failed to create polygon");+ ///+ /// // The collinear point at (2.0, 1.0) was removed, leaving a rectangle+ /// assert_eq!(polygon.points().len(), 4);+ /// # }+ /// ```+ ///+ /// [`from_convex_hull`]: ConvexPolygon::from_convex_hull+ /// [`from_convex_polyline_unmodified`]: ConvexPolygon::from_convex_polyline_unmodified+ pub fn from_convex_polyline(mut points: Vec<Vector>) -> Option<Self> {+ if points.is_empty() {+ return None;+ }+ let eps = <Real as ComplexField>::sqrt(crate::math::DEFAULT_EPSILON);+ let mut normals = Vec::with_capacity(points.len());+ // First, compute all normals.+ for i1 in 0..points.len() {+ let i2 = (i1 + 1) % points.len();+ normals.push(utils::ccw_face_normal([points[i1], points[i2]])?);+ }++ let mut nremoved = 0;+ // See if the first vertex must be removed.+ if normals[0].dot(normals[normals.len() - 1]) > 1.0 - eps {+ nremoved = 1;+ }++ // Second, find vertices that can be removed because+ // of collinearity of adjacent faces.+ for i2 in 1..points.len() {+ let i1 = i2 - 1;+ if normals[i1].dot(normals[i2]) > 1.0 - eps {+ // Remove+ nremoved += 1;+ } else {+ points[i2 - nremoved] = points[i2];+ normals[i2 - nremoved] = normals[i2];+ }+ }++ let new_length = points.len() - nremoved;+ points.truncate(new_length);+ normals.truncate(new_length);++ if points.len() > 2 {+ Some(ConvexPolygon { points, normals })+ } else {+ None+ }+ }++ /// Creates a new 2D convex polygon from a set of points assumed to+ /// describe a counter-clockwise convex polyline.+ ///+ /// This is the same as [`ConvexPolygon::from_convex_polyline`] but without removing any point+ /// from the input even if some are coplanar.+ ///+ /// Returns `None` if `points` doesn’t contain at least three points.+ pub fn from_convex_polyline_unmodified(points: Vec<Vector>) -> Option<Self> {+ if points.len() <= 2 {+ return None;+ }+ let mut normals = Vec::with_capacity(points.len());+ // First, compute all normals.+ for i1 in 0..points.len() {+ let i2 = (i1 + 1) % points.len();+ normals.push(utils::ccw_face_normal([points[i1], points[i2]])?);+ }++ Some(ConvexPolygon { points, normals })+ }++ /// Returns the vertices of this convex polygon.+ ///+ /// The vertices are stored in counter-clockwise order around the polygon.+ /// This is a slice reference to the internal vertex storage.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::ConvexPolygon;+ /// use parry2d::math::Vector;+ ///+ /// let triangle = ConvexPolygon::from_convex_polyline(vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0),+ /// Vector::new(0.5, 1.0),+ /// ]).unwrap();+ ///+ /// let vertices = triangle.points();+ /// assert_eq!(vertices.len(), 3);+ /// assert_eq!(vertices[0], Vector::ZERO);+ /// # }+ /// ```+ #[inline]+ pub fn points(&self) -> &[Vector] {+ &self.points+ }++ /// Returns the outward-pointing normals of the edges of this convex polygon.+ ///+ /// Each normal is a unit vector perpendicular to an edge, pointing outward from the polygon.+ /// The normals are stored in the same order as the edges, so `normals()[i]` is the normal+ /// for the edge from `points()[i]` to `points()[(i+1) % len]`.+ ///+ /// These pre-computed normals are used internally for efficient collision detection.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::ConvexPolygon;+ /// use parry2d::math::Vector;+ ///+ /// // Create a square aligned with the axes+ /// let square = ConvexPolygon::from_convex_polyline(vec![+ /// Vector::ZERO, // bottom-left+ /// Vector::new(1.0, 0.0), // bottom-right+ /// Vector::new(1.0, 1.0), // top-right+ /// Vector::new(0.0, 1.0), // top-left+ /// ]).unwrap();+ ///+ /// let normals = square.normals();+ /// assert_eq!(normals.len(), 4);+ ///+ /// // The first normal points downward (perpendicular to bottom edge)+ /// let bottom_normal = normals[0];+ /// assert!((bottom_normal.y - (-1.0)).abs() < 1e-5);+ /// assert!(bottom_normal.x.abs() < 1e-5);+ /// # }+ /// ```+ #[inline]+ pub fn normals(&self) -> &[Vector] {+ &self.normals+ }++ /// Computes a scaled version of this convex polygon.+ ///+ /// This method scales the polygon by multiplying each vertex coordinate by the corresponding+ /// component of the `scale` vector. This allows for non-uniform scaling (different scale factors+ /// for x and y axes).+ ///+ /// The normals are also updated to reflect the scaling transformation.+ ///+ /// # Returns+ ///+ /// - `Some(ConvexPolygon)` with the scaled shape+ /// - `None` if the scaling results in degenerate normals (e.g., if the scale factor along+ /// one axis is zero or nearly zero)+ ///+ /// # Example: Uniform scaling+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::ConvexPolygon;+ /// use parry2d::math::Vector;+ ///+ /// let triangle = ConvexPolygon::from_convex_polyline(vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0),+ /// Vector::new(0.5, 1.0),+ /// ]).unwrap();+ ///+ /// // Scale uniformly by 2x+ /// let scaled = triangle.scaled(Vector::new(2.0, 2.0))+ /// .expect("Failed to scale");+ ///+ /// // All coordinates are doubled+ /// assert_eq!(scaled.points()[1], Vector::new(2.0, 0.0));+ /// assert_eq!(scaled.points()[2], Vector::new(1.0, 2.0));+ /// # }+ /// ```+ ///+ /// # Example: Non-uniform scaling+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::ConvexPolygon;+ /// use parry2d::math::Vector;+ ///+ /// let square = ConvexPolygon::from_convex_polyline(vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0),+ /// Vector::new(1.0, 1.0),+ /// Vector::new(0.0, 1.0),+ /// ]).unwrap();+ ///+ /// // Scale to make it wider (2x) and taller (3x)+ /// let rectangle = square.scaled(Vector::new(2.0, 3.0))+ /// .expect("Failed to scale");+ ///+ /// assert_eq!(rectangle.points()[2], Vector::new(2.0, 3.0));+ /// # }+ /// ```+ pub fn scaled(mut self, scale: Vector) -> Option<Self> {+ self.points.iter_mut().for_each(|pt| *pt *= scale);++ for n in &mut self.normals {+ let scaled = *n * scale;+ *n = scaled.try_normalize()?;+ }++ Some(self)+ }++ /// Returns a mitered offset (expanded or contracted) version of the polygon.+ ///+ /// This method creates a new polygon by moving each edge outward (or inward for negative values)+ /// by the specified `amount`. The vertices are adjusted to maintain sharp corners (mitered joints).+ /// This is also known as "polygon dilation" or "Minkowski sum with a circle".+ ///+ /// # Use cases+ ///+ /// - Creating "safe zones" or margins around objects+ /// - Implementing "thick" polygon collision detection+ /// - Creating rounded rectangular shapes (when combined with rounding)+ /// - Growing or shrinking shapes for morphological operations+ ///+ /// # Arguments+ ///+ /// * `amount` - The distance to move each edge. Positive values expand the polygon outward,+ /// making it larger. Must be a non-negative finite number.+ ///+ /// # Panics+ ///+ /// Panics if `amount` is not a non-negative finite number (NaN, infinity, or negative).+ ///+ /// # Example: Expanding a triangle+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::ConvexPolygon;+ /// use parry2d::math::Vector;+ ///+ /// let triangle = ConvexPolygon::from_convex_polyline(vec![+ /// Vector::ZERO,+ /// Vector::new(2.0, 0.0),+ /// Vector::new(1.0, 2.0),+ /// ]).unwrap();+ ///+ /// // Expand the triangle by 0.5 units+ /// let expanded = triangle.offsetted(0.5);+ ///+ /// // The expanded triangle has the same number of vertices+ /// assert_eq!(expanded.points().len(), 3);+ /// // But the vertices have moved outward+ /// // (exact positions depend on the miter calculation)+ /// # }+ /// ```+ ///+ /// # Example: Creating a margin around a square+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::ConvexPolygon;+ /// use parry2d::math::Vector;+ ///+ /// let square = ConvexPolygon::from_convex_polyline(vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0),+ /// Vector::new(1.0, 1.0),+ /// Vector::new(0.0, 1.0),+ /// ]).unwrap();+ ///+ /// // Create a 0.2 unit margin around the square+ /// let margin = square.offsetted(0.2);+ ///+ /// // The shape is still a square (4 vertices)+ /// assert_eq!(margin.points().len(), 4);+ /// # }+ /// ```+ pub fn offsetted(&self, amount: Real) -> Self {+ if !amount.is_finite() || amount < 0. {+ panic!(+ "Offset amount must be a non-negative finite number, got {}.",+ amount+ );+ }++ let mut points = Vec::with_capacity(self.points.len());+ let normals = self.normals.clone();++ for i2 in 0..self.points.len() {+ let i1 = if i2 == 0 {+ self.points.len() - 1+ } else {+ i2 - 1+ };+ let normal_a = normals[i1];+ let direction = normal_a + normals[i2];+ points.push(self.points[i2] + (amount / direction.dot(normal_a)) * direction);+ }++ ConvexPolygon { points, normals }+ }++ /// Get the ID of the feature with a normal that maximizes the dot product with `local_dir`.+ pub fn support_feature_id_toward(&self, local_dir: Vector) -> FeatureId {+ let eps: Real = Real::pi() / 180.0;+ let ceps = <Real as ComplexField>::cos(eps);++ // Check faces.+ for i in 0..self.normals.len() {+ let normal = &self.normals[i];++ if normal.dot(local_dir) >= ceps {+ return FeatureId::Face(i as u32);+ }+ }++ // Support vertex.+ FeatureId::Vertex(utils::point_cloud_support_point_id(local_dir, &self.points) as u32)+ }++ /// The normal of the given feature.+ pub fn feature_normal(&self, feature: FeatureId) -> Option<Vector> {+ match feature {+ FeatureId::Face(id) => Some(self.normals[id as usize]),+ FeatureId::Vertex(id2) => {+ let id1 = if id2 == 0 {+ self.normals.len() - 1+ } else {+ id2 as usize - 1+ };+ let sum = self.normals[id1] + self.normals[id2 as usize];+ sum.try_normalize()+ }+ _ => None,+ }+ }+}++impl SupportMap for ConvexPolygon {+ #[inline]+ fn local_support_point(&self, dir: Vector) -> Vector {+ utils::point_cloud_support_point(dir, self.points())+ }+}++impl PolygonalFeatureMap for ConvexPolygon {+ fn local_support_feature(&self, dir: Vector, out_feature: &mut PolygonalFeature) {+ let cuboid = crate::shape::Cuboid::new(self.points[2]);+ cuboid.local_support_feature(dir, out_feature);+ let mut best_face = 0;+ let mut max_dot = self.normals[0].dot(dir);++ for i in 1..self.normals.len() {+ let dot = self.normals[i].dot(dir);++ if dot > max_dot {+ max_dot = dot;+ best_face = i;+ }+ }++ let i1 = best_face;+ let i2 = (best_face + 1) % self.points.len();+ *out_feature = PolygonalFeature {+ vertices: [self.points[i1], self.points[i2]],+ vids: PackedFeatureId::vertices([i1 as u32 * 2, i2 as u32 * 2]),+ fid: PackedFeatureId::face(i1 as u32 * 2 + 1),+ num_vertices: 2,+ };+ }+}++/*+impl ConvexPolyhedron for ConvexPolygon {+ fn vertex(&self, id: FeatureId) -> Vector {+ self.points[id.unwrap_vertex() as usize]+ }++ fn face(&self, id: FeatureId, out: &mut ConvexPolygonalFeature) {+ out.clear();++ let ia = id.unwrap_face() as usize;+ let ib = (ia + 1) % self.points.len();+ out.push(self.points[ia], FeatureId::Vertex(ia as u32));+ out.push(self.points[ib], FeatureId::Vertex(ib as u32));++ out.set_normal(self.normals[ia as usize]);+ out.set_feature_id(FeatureId::Face(ia as u32));+ }++++ fn support_face_toward(+ &self,+ m: &Pose,+ dir: Vector,+ out: &mut ConvexPolygonalFeature,+ ) {+ let ls_dir = m.inverse_transform_vector(dir);+ let mut best_face = 0;+ let mut max_dot = self.normals[0].dot(ls_dir);++ for i in 1..self.points.len() {+ let dot = self.normals[i].dot(ls_dir);++ if dot > max_dot {+ max_dot = dot;+ best_face = i;+ }+ }++ self.face(FeatureId::Face(best_face as u32), out);+ out.transform_by(m);+ }++ fn support_feature_toward(+ &self,+ transform: &Pose,+ dir: Vector,+ _angle: Real,+ out: &mut ConvexPolygonalFeature,+ ) {+ out.clear();+ // TODO: actually find the support feature.+ self.support_face_toward(transform, dir, out)+ }++ fn support_feature_id_toward(&self, local_dir: Vector) -> FeatureId {+ let eps: Real = (f64::consts::PI / 180.0) as Real;+ let ceps = <Real as ComplexField>::cos(eps);++ // Check faces.+ for i in 0..self.normals.len() {+ let normal = &self.normals[i];++ if normal.dot(local_dir.as_ref()) >= ceps {+ return FeatureId::Face(i as u32);+ }+ }++ // Support vertex.+ FeatureId::Vertex(+ utils::point_cloud_support_point_id(local_dir.as_ref(), &self.points) as u32,+ )+ }+}+*/++#[cfg(feature = "dim2")]+#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_dilation() {+ let polygon = ConvexPolygon::from_convex_polyline(vec![+ Vector::new(1., 0.),+ Vector::new(-1., 0.),+ Vector::new(0., -1.),+ ])+ .unwrap();++ let offsetted = polygon.offsetted(0.5);+ let expected = vec![+ Vector::new(2.207, 0.5),+ Vector::new(-2.207, 0.5),+ Vector::new(0., -1.707),+ ];++ assert_eq!(offsetted.points().len(), 3);+ assert!(offsetted+ .points()+ .iter()+ .zip(expected.iter())+ .all(|(a, b)| (a - b).length() < 0.001));+ }+}diff --git a/renderer/third_party/parry3d/src/shape/convex_polyhedron.rs b/renderer/third_party/parry3d/src/shape/convex_polyhedron.rsnew file mode 100644index 0000000..45fc1a1--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/convex_polyhedron.rs@@ -0,0 +1,1076 @@+use crate::math::{Real, Vector, DIM};+use crate::shape::{FeatureId, PackedFeatureId, PolygonalFeature, PolygonalFeatureMap, SupportMap};+// use crate::transformation;+#[cfg(not(feature = "std"))]+use crate::math::ComplexField;+use crate::utils::hashmap::{Entry, HashMap};+use crate::utils::{self, SortedPair};+#[cfg(feature = "alloc")]+use alloc::vec::Vec;+use core::f64; // for .abs(), .sqrt(), and .sin_cos()++#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(PartialEq, Debug, Copy, Clone)]+pub struct Vertex {+ pub first_adj_face_or_edge: u32,+ pub num_adj_faces_or_edge: u32,+}++#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(PartialEq, Debug, Copy, Clone)]+pub struct Edge {+ pub vertices: [u32; 2],+ pub faces: [u32; 2],+ pub dir: Vector,+ deleted: bool,+}++impl Edge {+ fn other_triangle(&self, id: u32) -> u32 {+ if id == self.faces[0] {+ self.faces[1]+ } else {+ self.faces[0]+ }+ }+}++#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(PartialEq, Debug, Copy, Clone)]+pub struct Face {+ pub first_vertex_or_edge: u32,+ pub num_vertices_or_edges: u32,+ pub normal: Vector,+}++#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(PartialEq, Debug, Copy, Clone)]+struct Triangle {+ vertices: [u32; 3],+ edges: [u32; 3],+ normal: Vector,+ parent_face: Option<u32>,+ is_degenerate: bool,+}++impl Triangle {+ fn next_edge_id(&self, id: u32) -> u32 {+ for i in 0..3 {+ if self.edges[i] == id {+ return (i as u32 + 1) % 3;+ }+ }++ unreachable!()+ }+}++#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(PartialEq, Debug, Clone)]+/// A 3D convex polyhedron without degenerate faces.+///+/// A convex polyhedron is a 3D solid shape where all faces are flat polygons, all interior angles+/// are less than 180 degrees, and any line segment drawn between two points inside the polyhedron+/// stays entirely within it. Common examples include cubes, tetrahedra (pyramids), and prisms.+///+/// # What is a convex polyhedron?+///+/// In 3D space, a polyhedron is **convex** if:+/// - All faces are flat, convex polygons+/// - All dihedral angles (angles between adjacent faces) are less than or equal to 180 degrees+/// - The line segment between any two points inside the polyhedron lies entirely inside+/// - All vertices "bulge outward" - there are no indentations or concave regions+///+/// Examples of **convex** polyhedra: cube, tetrahedron, octahedron, rectangular prism, pyramid+/// Examples of **non-convex** polyhedra: star shapes, torus, L-shapes, any shape with holes+///+/// # Use cases+///+/// Convex polyhedra are widely used in:+/// - **Game development**: Collision hulls for characters, vehicles, and complex objects+/// - **Physics simulations**: Rigid body dynamics (more efficient than arbitrary meshes)+/// - **Robotics**: Simplified robot link shapes, workspace boundaries+/// - **Computer graphics**: Level of detail (LOD) representations, occlusion culling+/// - **Computational geometry**: Building blocks for complex mesh operations+/// - **3D printing**: Simplified collision detection for print validation+///+/// # Representation+///+/// This structure stores the complete topological information:+/// - **Vectors**: The 3D coordinates of all vertices+/// - **Faces**: Polygonal faces with their outward-pointing normals+/// - **Edges**: Connections between vertices, shared by exactly two faces+/// - **Adjacency information**: Which faces/edges connect to each vertex, and vice versa+///+/// This rich topology enables efficient collision detection algorithms like GJK, EPA, and SAT.+///+/// # Important: No degenerate faces+///+/// This structure ensures that there are no degenerate (flat or zero-area) faces. Coplanar+/// adjacent triangles are automatically merged into larger polygonal faces during construction.+///+/// # Example: Creating a simple tetrahedron (pyramid)+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::ConvexPolyhedron;+/// use parry3d::math::Vector;+///+/// // Define the 4 vertices of a tetrahedron+/// let points = vec![+/// Vector::ZERO, // base vertex 1+/// Vector::new(1.0, 0.0, 0.0), // base vertex 2+/// Vector::new(0.5, 1.0, 0.0), // base vertex 3+/// Vector::new(0.5, 0.5, 1.0), // apex+/// ];+///+/// // Define the 4 triangular faces (indices into the points array)+/// let indices = vec![+/// [0u32, 1, 2], // base triangle+/// [0, 1, 3], // side 1+/// [1, 2, 3], // side 2+/// [2, 0, 3], // side 3+/// ];+///+/// let tetrahedron = ConvexPolyhedron::from_convex_mesh(points, &indices)+/// .expect("Failed to create tetrahedron");+///+/// // A tetrahedron has 4 vertices and 4 faces+/// assert_eq!(tetrahedron.points().len(), 4);+/// assert_eq!(tetrahedron.faces().len(), 4);+/// # }+/// ```+pub struct ConvexPolyhedron {+ points: Vec<Vector>,+ vertices: Vec<Vertex>,+ faces: Vec<Face>,+ edges: Vec<Edge>,+ // Faces adjacent to a vertex.+ faces_adj_to_vertex: Vec<u32>,+ // Edges adjacent to a vertex.+ edges_adj_to_vertex: Vec<u32>,+ // Edges adjacent to a face.+ edges_adj_to_face: Vec<u32>,+ // Vertices adjacent to a face.+ vertices_adj_to_face: Vec<u32>,+}++impl ConvexPolyhedron {+ /// Creates a new convex polyhedron from an arbitrary set of points by computing their convex hull.+ ///+ /// This is the most flexible constructor - it automatically computes the **convex hull** of the+ /// given 3D points, which is the smallest convex polyhedron that contains all the input points.+ /// Think of it as shrink-wrapping the points with an elastic surface.+ ///+ /// Use this when:+ /// - You have an arbitrary collection of 3D points and want the convex boundary+ /// - You're not sure if your points form a convex shape+ /// - You want to simplify a point cloud to its convex outer surface+ /// - You need to create a collision hull from a detailed mesh+ ///+ /// # Returns+ ///+ /// - `Some(ConvexPolyhedron)` if successful+ /// - `None` if the convex hull computation failed (e.g., all points are coplanar, collinear,+ /// or coincident, or if the mesh is not manifold)+ ///+ /// # Example: Creating a convex hull from point cloud+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::ConvexPolyhedron;+ /// use parry3d::math::Vector;+ ///+ /// // Vectors defining a cube, plus some interior points+ /// let points = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(1.0, 1.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 1.0),+ /// Vector::new(1.0, 0.0, 1.0),+ /// Vector::new(1.0, 1.0, 1.0),+ /// Vector::new(0.0, 1.0, 1.0),+ /// Vector::new(0.5, 0.5, 0.5), // Interior point - will be excluded+ /// ];+ ///+ /// let polyhedron = ConvexPolyhedron::from_convex_hull(&points)+ /// .expect("Failed to create convex hull");+ ///+ /// // The cube has 8 vertices (interior point excluded)+ /// assert_eq!(polyhedron.points().len(), 8);+ /// // And 6 faces (one per side of the cube)+ /// assert_eq!(polyhedron.faces().len(), 6);+ /// # }+ /// ```+ ///+ /// # Example: Simplifying a complex mesh+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::ConvexPolyhedron;+ /// use parry3d::math::Vector;+ ///+ /// // Imagine these are vertices from a detailed character mesh+ /// let detailed_mesh_vertices = vec![+ /// Vector::new(-1.0, -1.0, -1.0),+ /// Vector::new(1.0, -1.0, -1.0),+ /// Vector::new(1.0, 1.0, -1.0),+ /// Vector::new(-1.0, 1.0, -1.0),+ /// Vector::new(-1.0, -1.0, 1.0),+ /// Vector::new(1.0, -1.0, 1.0),+ /// Vector::new(1.0, 1.0, 1.0),+ /// Vector::new(-1.0, 1.0, 1.0),+ /// // ... many more vertices in the original mesh+ /// ];+ ///+ /// // Create a simplified collision hull+ /// let collision_hull = ConvexPolyhedron::from_convex_hull(&detailed_mesh_vertices)+ /// .expect("Failed to create collision hull");+ ///+ /// // The hull is much simpler than the original mesh+ /// println!("Simplified to {} vertices", collision_hull.points().len());+ /// # }+ /// ```+ pub fn from_convex_hull(points: &[Vector]) -> Option<ConvexPolyhedron> {+ crate::transformation::try_convex_hull(points)+ .ok()+ .and_then(|(vertices, indices)| Self::from_convex_mesh(vertices, &indices))+ }++ /// Creates a new convex polyhedron from vertices and face indices, assuming the mesh is already convex.+ ///+ /// This constructor is more efficient than [`from_convex_hull`] because it **assumes** the input+ /// mesh is already convex and manifold. The convexity is **not verified** - if you pass a non-convex+ /// mesh, the resulting shape may behave incorrectly in collision detection.+ ///+ /// The method automatically:+ /// - Merges coplanar adjacent triangular faces into larger polygonal faces+ /// - Removes degenerate (zero-area) faces+ /// - Builds complete topological connectivity information (vertices, edges, faces)+ ///+ /// # Important requirements+ ///+ /// The input mesh must be:+ /// - **Manifold**: Each edge is shared by exactly 2 faces, no T-junctions, no holes+ /// - **Closed**: The mesh completely encloses a volume with no gaps+ /// - **Convex** (not enforced, but assumed): All faces bulge outward+ /// - **Valid**: Faces use counter-clockwise winding when viewed from outside+ ///+ /// # When to use this+ ///+ /// Use this constructor when:+ /// - You already have a triangulated convex mesh+ /// - The mesh comes from a trusted source (e.g., generated procedurally)+ /// - You want better performance by skipping convex hull computation+ /// - You're converting from another 3D format (OBJ, STL, etc.)+ ///+ /// # Arguments+ ///+ /// * `points` - The vertex positions (3D coordinates)+ /// * `indices` - The face triangles, each containing 3 indices into the `points` array+ ///+ /// # Returns+ ///+ /// - `Some(ConvexPolyhedron)` if successful+ /// - `None` if the mesh is not manifold, has T-junctions, is not closed, or has invalid topology+ ///+ /// # Example: Creating a cube from vertices and faces+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::ConvexPolyhedron;+ /// use parry3d::math::Vector;+ ///+ /// // Define the 8 vertices of a unit cube+ /// let vertices = vec![+ /// Vector::ZERO, // 0: bottom-left-front+ /// Vector::new(1.0, 0.0, 0.0), // 1: bottom-right-front+ /// Vector::new(1.0, 1.0, 0.0), // 2: bottom-right-back+ /// Vector::new(0.0, 1.0, 0.0), // 3: bottom-left-back+ /// Vector::new(0.0, 0.0, 1.0), // 4: top-left-front+ /// Vector::new(1.0, 0.0, 1.0), // 5: top-right-front+ /// Vector::new(1.0, 1.0, 1.0), // 6: top-right-back+ /// Vector::new(0.0, 1.0, 1.0), // 7: top-left-back+ /// ];+ ///+ /// // Define the faces as triangles (2 triangles per cube face)+ /// let indices = vec![+ /// // Bottom face (z = 0)+ /// [0, 2, 1], [0, 3, 2],+ /// // Top face (z = 1)+ /// [4, 5, 6], [4, 6, 7],+ /// // Front face (y = 0)+ /// [0, 1, 5], [0, 5, 4],+ /// // Back face (y = 1)+ /// [2, 3, 7], [2, 7, 6],+ /// // Left face (x = 0)+ /// [0, 4, 7], [0, 7, 3],+ /// // Right face (x = 1)+ /// [1, 2, 6], [1, 6, 5],+ /// ];+ ///+ /// let cube = ConvexPolyhedron::from_convex_mesh(vertices, &indices)+ /// .expect("Failed to create cube");+ ///+ /// // The cube has 8 vertices+ /// assert_eq!(cube.points().len(), 8);+ /// // The 12 triangles are merged into 6 square faces+ /// assert_eq!(cube.faces().len(), 6);+ /// # }+ /// ```+ ///+ /// # Example: Creating a triangular prism+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::ConvexPolyhedron;+ /// use parry3d::math::Vector;+ ///+ /// // 6 vertices: 3 on bottom, 3 on top+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.5, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 2.0),+ /// Vector::new(1.0, 0.0, 2.0),+ /// Vector::new(0.5, 1.0, 2.0),+ /// ];+ ///+ /// let indices = vec![+ /// // Bottom triangle+ /// [0, 2, 1],+ /// // Top triangle+ /// [3, 4, 5],+ /// // Side faces (2 triangles each)+ /// [0, 1, 4], [0, 4, 3],+ /// [1, 2, 5], [1, 5, 4],+ /// [2, 0, 3], [2, 3, 5],+ /// ];+ ///+ /// let prism = ConvexPolyhedron::from_convex_mesh(vertices, &indices)+ /// .expect("Failed to create prism");+ ///+ /// assert_eq!(prism.points().len(), 6);+ /// // 2 triangular faces + 3 rectangular faces = 5 faces+ /// assert_eq!(prism.faces().len(), 5);+ /// # }+ /// ```+ ///+ /// [`from_convex_hull`]: ConvexPolyhedron::from_convex_hull+ pub fn from_convex_mesh(+ points: Vec<Vector>,+ indices: &[[u32; DIM]],+ ) -> Option<ConvexPolyhedron> {+ let eps = crate::math::DEFAULT_EPSILON.sqrt();++ let mut vertices = Vec::new();+ let mut edges = Vec::<Edge>::new();+ let mut faces = Vec::<Face>::new();+ let mut triangles = Vec::new();+ let mut edge_map = HashMap::default();++ let mut faces_adj_to_vertex = Vec::new();+ let mut edges_adj_to_vertex = Vec::new();+ let mut edges_adj_to_face = Vec::new();+ let mut vertices_adj_to_face = Vec::new();++ if points.len() + indices.len() <= 2 {+ return None;+ }++ //// Euler characteristic.+ let nedges = points.len() + indices.len() - 2;+ edges.reserve(nedges);++ /*+ * Initialize triangles and edges adjacency information.+ */+ for idx in indices {+ let mut edges_id = [u32::MAX; DIM];+ let face_id = triangles.len();++ if idx[0] == idx[1] || idx[0] == idx[2] || idx[1] == idx[2] {+ return None;+ }++ for i1 in 0..3 {+ // Deal with edges.+ let i2 = (i1 + 1) % 3;+ let key = SortedPair::new(idx[i1], idx[i2]);++ match edge_map.entry(key) {+ Entry::Occupied(e) => {+ let edge = &mut edges[*e.get() as usize];+ let out_face_id = &mut edge.faces[1];++ if *out_face_id == u32::MAX {+ edges_id[i1] = *e.get();+ *out_face_id = face_id as u32+ } else {+ // We have a t-junction.+ return None;+ }+ }+ Entry::Vacant(e) => {+ edges_id[i1] = *e.insert(edges.len() as u32);++ let dir =+ (points[idx[i2] as usize] - points[idx[i1] as usize]).try_normalize();++ edges.push(Edge {+ vertices: [idx[i1], idx[i2]],+ faces: [face_id as u32, u32::MAX],+ dir: dir.unwrap_or(Vector::X),+ deleted: dir.is_none(),+ });+ }+ }+ }++ let normal = utils::ccw_face_normal([+ points[idx[0] as usize],+ points[idx[1] as usize],+ points[idx[2] as usize],+ ]);+ let triangle = Triangle {+ vertices: *idx,+ edges: edges_id,+ normal: normal.unwrap_or(Vector::ZERO),+ parent_face: None,+ is_degenerate: normal.is_none(),+ };++ triangles.push(triangle);+ }++ // Find edges that must be deleted.++ for e in &mut edges {+ let tri1 = triangles.get(e.faces[0] as usize)?;+ let tri2 = triangles.get(e.faces[1] as usize)?;+ if tri1.normal.dot(tri2.normal) > 1.0 - eps {+ e.deleted = true;+ }+ }++ /*+ * Extract faces by following contours.+ */+ for i in 0..triangles.len() {+ if triangles[i].parent_face.is_none() {+ for j1 in 0..3 {+ if !edges[triangles[i].edges[j1] as usize].deleted {+ // Create a new face, setup its first edge/vertex and construct it.+ let new_face_id = faces.len();+ let mut new_face = Face {+ first_vertex_or_edge: edges_adj_to_face.len() as u32,+ num_vertices_or_edges: 1,+ normal: triangles[i].normal,+ };++ edges_adj_to_face.push(triangles[i].edges[j1]);+ vertices_adj_to_face.push(triangles[i].vertices[j1]);++ let j2 = (j1 + 1) % 3;+ let start_vertex = triangles[i].vertices[j1];++ // NOTE: variables ending with _id are identifier on the+ // fields of a triangle. Other variables are identifier on+ // the triangles/edges/vertices arrays.+ let mut curr_triangle = i;+ let mut curr_edge_id = j2;++ while triangles[curr_triangle].vertices[curr_edge_id] != start_vertex {+ let curr_edge = triangles[curr_triangle].edges[curr_edge_id];+ let curr_vertex = triangles[curr_triangle].vertices[curr_edge_id];+ // NOTE: we should use this assertion. However, it can currently+ // happen if there are some isolated non-deleted edges due to+ // rounding errors.+ //+ // assert!(triangles[curr_triangle].parent_face.is_none());+ triangles[curr_triangle].parent_face = Some(new_face_id as u32);++ if !edges[curr_edge as usize].deleted {+ edges_adj_to_face.push(curr_edge);+ vertices_adj_to_face.push(curr_vertex);+ new_face.num_vertices_or_edges += 1;++ curr_edge_id = (curr_edge_id + 1) % 3;+ } else {+ // Find adjacent edge on the next triangle.+ curr_triangle = edges[curr_edge as usize]+ .other_triangle(curr_triangle as u32)+ as usize;+ curr_edge_id =+ triangles[curr_triangle].next_edge_id(curr_edge) as usize;+ assert!(+ triangles[curr_triangle].vertices[curr_edge_id] == curr_vertex+ );+ }+ }++ if new_face.num_vertices_or_edges > 2 {+ // Sometimes degenerate faces may be generated+ // due to numerical errors resulting in an isolated+ // edge not being deleted.+ //+ // This kind of degenerate faces are not valid.+ faces.push(new_face);+ }+ break;+ }+ }+ }+ }++ // Update face ids inside edges so that they point to the faces instead of the triangles.+ for e in &mut edges {+ if let Some(fid) = triangles.get(e.faces[0] as usize)?.parent_face {+ e.faces[0] = fid;+ }++ if let Some(fid) = triangles.get(e.faces[1] as usize)?.parent_face {+ e.faces[1] = fid;+ }+ }++ /*+ * Initialize vertices+ */+ let empty_vertex = Vertex {+ first_adj_face_or_edge: 0,+ num_adj_faces_or_edge: 0,+ };++ vertices.resize(points.len(), empty_vertex);++ // First, find their multiplicities.+ for face in &faces {+ let first_vid = face.first_vertex_or_edge;+ let last_vid = face.first_vertex_or_edge + face.num_vertices_or_edges;++ for i in &vertices_adj_to_face[first_vid as usize..last_vid as usize] {+ vertices[*i as usize].num_adj_faces_or_edge += 1;+ }+ }++ // Now, find their starting id.+ let mut total_num_adj_faces = 0;+ for v in &mut vertices {+ v.first_adj_face_or_edge = total_num_adj_faces;+ total_num_adj_faces += v.num_adj_faces_or_edge;+ }+ faces_adj_to_vertex.resize(total_num_adj_faces as usize, 0);+ edges_adj_to_vertex.resize(total_num_adj_faces as usize, 0);++ // Reset the number of adjacent faces.+ // It will be set again to the right value as+ // the adjacent face list is filled.+ for v in &mut vertices {+ v.num_adj_faces_or_edge = 0;+ }++ for (face_id, face) in faces.iter().enumerate() {+ let first_vid = face.first_vertex_or_edge;+ let last_vid = face.first_vertex_or_edge + face.num_vertices_or_edges;++ for vid in first_vid..last_vid {+ let v = &mut vertices[vertices_adj_to_face[vid as usize] as usize];+ faces_adj_to_vertex+ [(v.first_adj_face_or_edge + v.num_adj_faces_or_edge) as usize] =+ face_id as u32;+ edges_adj_to_vertex+ [(v.first_adj_face_or_edge + v.num_adj_faces_or_edge) as usize] =+ edges_adj_to_face[vid as usize];+ v.num_adj_faces_or_edge += 1;+ }+ }++ // Note numerical errors may throw off the Euler characteristic.+ // So we don't check it right now.++ let res = ConvexPolyhedron {+ points,+ vertices,+ faces,+ edges,+ faces_adj_to_vertex,+ edges_adj_to_vertex,+ edges_adj_to_face,+ vertices_adj_to_face,+ };++ // TODO: for debug.+ // res.check_geometry();++ Some(res)+ }++ /// Verify if this convex polyhedron is actually convex.+ #[inline]+ pub fn check_geometry(&self) {+ for face in &self.faces {+ let p0 =+ self.points[self.vertices_adj_to_face[face.first_vertex_or_edge as usize] as usize];++ for v in &self.points {+ assert!((v - p0).dot(face.normal) <= crate::math::DEFAULT_EPSILON);+ }+ }+ }++ /// Returns the 3D coordinates of all vertices in this convex polyhedron.+ ///+ /// Each point represents a corner of the polyhedron where three or more edges meet.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::ConvexPolyhedron;+ /// use parry3d::math::Vector;+ ///+ /// let points = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.5, 1.0, 0.0),+ /// Vector::new(0.5, 0.5, 1.0),+ /// ];+ /// let indices = vec![[0u32, 1, 2], [0, 1, 3], [1, 2, 3], [2, 0, 3]];+ ///+ /// let tetrahedron = ConvexPolyhedron::from_convex_mesh(points, &indices).unwrap();+ ///+ /// assert_eq!(tetrahedron.points().len(), 4);+ /// assert_eq!(tetrahedron.points()[0], Vector::ZERO);+ /// # }+ /// ```+ #[inline]+ pub fn points(&self) -> &[Vector] {+ &self.points[..]+ }++ /// Returns the topology information for all vertices.+ ///+ /// Each `Vertex` contains indices into the adjacency arrays, telling you which+ /// faces and edges are connected to that vertex. This is useful for advanced+ /// topological queries and mesh processing algorithms.+ ///+ /// Most users will want [`points()`] instead to get the 3D coordinates.+ ///+ /// [`points()`]: ConvexPolyhedron::points+ #[inline]+ pub fn vertices(&self) -> &[Vertex] {+ &self.vertices[..]+ }++ /// Returns the topology information for all edges.+ ///+ /// Each `Edge` contains:+ /// - The two vertex indices it connects+ /// - The two face indices it borders+ /// - The edge direction as a unit vector+ ///+ /// This is useful for advanced geometric queries and rendering wireframes.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::ConvexPolyhedron;+ /// use parry3d::math::Vector;+ ///+ /// let points = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.5, 1.0, 0.0),+ /// Vector::new(0.5, 0.5, 1.0),+ /// ];+ /// let indices = vec![[0u32, 1, 2], [0, 1, 3], [1, 2, 3], [2, 0, 3]];+ ///+ /// let tetrahedron = ConvexPolyhedron::from_convex_mesh(points, &indices).unwrap();+ ///+ /// // A tetrahedron has 6 edges (4 vertices choose 2)+ /// assert_eq!(tetrahedron.edges().len(), 6);+ ///+ /// // Each edge connects two vertices+ /// let edge = &tetrahedron.edges()[0];+ /// println!("Edge connects vertices {} and {}", edge.vertices[0], edge.vertices[1]);+ /// # }+ /// ```+ #[inline]+ pub fn edges(&self) -> &[Edge] {+ &self.edges[..]+ }++ /// Returns the topology information for all faces.+ ///+ /// Each `Face` contains:+ /// - Indices into the vertex and edge adjacency arrays+ /// - The number of vertices/edges in the face (faces can be triangles, quads, or larger polygons)+ /// - The outward-pointing unit normal vector+ ///+ /// Faces are polygonal and can have 3 or more vertices. Adjacent coplanar triangles+ /// are automatically merged into larger polygonal faces.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::ConvexPolyhedron;+ /// use parry3d::math::Vector;+ ///+ /// // Create a cube (8 vertices, 12 triangular input faces)+ /// let vertices = vec![+ /// Vector::ZERO, Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(1.0, 1.0, 0.0), Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 1.0), Vector::new(1.0, 0.0, 1.0),+ /// Vector::new(1.0, 1.0, 1.0), Vector::new(0.0, 1.0, 1.0),+ /// ];+ /// let indices = vec![+ /// [0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7],+ /// [0, 1, 5], [0, 5, 4], [2, 3, 7], [2, 7, 6],+ /// [0, 4, 7], [0, 7, 3], [1, 2, 6], [1, 6, 5],+ /// ];+ ///+ /// let cube = ConvexPolyhedron::from_convex_mesh(vertices, &indices).unwrap();+ ///+ /// // The 12 triangles are merged into 6 square faces+ /// assert_eq!(cube.faces().len(), 6);+ ///+ /// // Each face has 4 vertices (it's a square)+ /// assert_eq!(cube.faces()[0].num_vertices_or_edges, 4);+ /// # }+ /// ```+ #[inline]+ pub fn faces(&self) -> &[Face] {+ &self.faces[..]+ }++ /// The array containing the indices of the vertices adjacent to each face.+ #[inline]+ pub fn vertices_adj_to_face(&self) -> &[u32] {+ &self.vertices_adj_to_face[..]+ }++ /// The array containing the indices of the edges adjacent to each face.+ #[inline]+ pub fn edges_adj_to_face(&self) -> &[u32] {+ &self.edges_adj_to_face[..]+ }++ /// The array containing the indices of the faces adjacent to each vertex.+ #[inline]+ pub fn faces_adj_to_vertex(&self) -> &[u32] {+ &self.faces_adj_to_vertex[..]+ }++ /// Computes a scaled version of this convex polyhedron.+ ///+ /// This method scales the polyhedron by multiplying each vertex coordinate by the corresponding+ /// component of the `scale` vector. This allows for non-uniform scaling (different scale factors+ /// for x, y, and z axes).+ ///+ /// The face normals and edge directions are also updated to reflect the scaling transformation.+ ///+ /// # Returns+ ///+ /// - `Some(ConvexPolyhedron)` with the scaled shape+ /// - `None` if the scaling results in degenerate normals (e.g., if the scale factor along+ /// one axis is zero or nearly zero)+ ///+ /// # Example: Uniform scaling+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::ConvexPolyhedron;+ /// use parry3d::math::Vector;+ ///+ /// let points = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.5, 1.0, 0.0),+ /// Vector::new(0.5, 0.5, 1.0),+ /// ];+ /// let indices = vec![[0u32, 1, 2], [0, 1, 3], [1, 2, 3], [2, 0, 3]];+ ///+ /// let tetrahedron = ConvexPolyhedron::from_convex_mesh(points, &indices).unwrap();+ ///+ /// // Scale uniformly by 2x+ /// let scaled = tetrahedron.scaled(Vector::new(2.0, 2.0, 2.0))+ /// .expect("Failed to scale");+ ///+ /// // All coordinates are doubled+ /// assert_eq!(scaled.points()[1], Vector::new(2.0, 0.0, 0.0));+ /// assert_eq!(scaled.points()[3], Vector::new(1.0, 1.0, 2.0));+ /// # }+ /// ```+ ///+ /// # Example: Non-uniform scaling to create a rectangular prism+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::ConvexPolyhedron;+ /// use parry3d::math::Vector;+ ///+ /// // Start with a unit cube+ /// let vertices = vec![+ /// Vector::ZERO, Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(1.0, 1.0, 0.0), Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 1.0), Vector::new(1.0, 0.0, 1.0),+ /// Vector::new(1.0, 1.0, 1.0), Vector::new(0.0, 1.0, 1.0),+ /// ];+ /// let indices = vec![+ /// [0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7],+ /// [0, 1, 5], [0, 5, 4], [2, 3, 7], [2, 7, 6],+ /// [0, 4, 7], [0, 7, 3], [1, 2, 6], [1, 6, 5],+ /// ];+ ///+ /// let cube = ConvexPolyhedron::from_convex_mesh(vertices, &indices).unwrap();+ ///+ /// // Scale to make it wider (3x), deeper (2x), and taller (4x)+ /// let box_shape = cube.scaled(Vector::new(3.0, 2.0, 4.0))+ /// .expect("Failed to scale");+ ///+ /// assert_eq!(box_shape.points()[6], Vector::new(3.0, 2.0, 4.0));+ /// # }+ /// ```+ pub fn scaled(mut self, scale: Vector) -> Option<Self> {+ self.points.iter_mut().for_each(|pt| *pt *= scale);++ for f in &mut self.faces {+ f.normal = (f.normal * scale).try_normalize().unwrap_or(f.normal);+ }++ for e in &mut self.edges {+ e.dir = (e.dir * scale).try_normalize().unwrap_or(e.dir);+ }++ Some(self)+ }++ fn support_feature_id_toward_eps(&self, local_dir: Vector, eps: Real) -> FeatureId {+ let (seps, ceps) = eps.sin_cos();+ let support_pt_id = utils::point_cloud_support_point_id(local_dir, &self.points);+ let vertex = &self.vertices[support_pt_id];++ // Check faces.+ for i in 0..vertex.num_adj_faces_or_edge {+ let face_id = self.faces_adj_to_vertex[(vertex.first_adj_face_or_edge + i) as usize];+ let face = &self.faces[face_id as usize];++ if face.normal.dot(local_dir) >= ceps {+ return FeatureId::Face(face_id);+ }+ }++ // Check edges.+ for i in 0..vertex.num_adj_faces_or_edge {+ let edge_id = self.edges_adj_to_vertex[(vertex.first_adj_face_or_edge + i) as usize];+ let edge = &self.edges[edge_id as usize];++ if edge.dir.dot(local_dir).abs() <= seps {+ return FeatureId::Edge(edge_id);+ }+ }++ // The vertex is the support feature.+ FeatureId::Vertex(support_pt_id as u32)+ }++ /// Computes the ID of the features with a normal that maximize the dot-product with `local_dir`.+ pub fn support_feature_id_toward(&self, local_dir: Vector) -> FeatureId {+ #[cfg_attr(feature = "f64", expect(clippy::unnecessary_cast))]+ let eps: Real = (f64::consts::PI / 180.0) as Real;+ self.support_feature_id_toward_eps(local_dir, eps)+ }++ /// The normal of the given feature.+ pub fn feature_normal(&self, feature: FeatureId) -> Option<Vector> {+ match feature {+ FeatureId::Face(id) => Some(self.faces[id as usize].normal),+ FeatureId::Edge(id) => {+ let edge = &self.edges[id as usize];+ Some(+ (self.faces[edge.faces[0] as usize].normal+ + self.faces[edge.faces[1] as usize].normal)+ .normalize(),+ )+ }+ FeatureId::Vertex(id) => {+ let vertex = &self.vertices[id as usize];+ let first = vertex.first_adj_face_or_edge;+ let last = vertex.first_adj_face_or_edge + vertex.num_adj_faces_or_edge;+ let mut normal = Vector::ZERO;++ for face in &self.faces_adj_to_vertex[first as usize..last as usize] {+ normal += self.faces[*face as usize].normal+ }++ Some((normal).normalize())+ }+ FeatureId::Unknown => None,+ }+ }+}++impl SupportMap for ConvexPolyhedron {+ #[inline]+ fn local_support_point(&self, dir: Vector) -> Vector {+ utils::point_cloud_support_point(dir, self.points())+ }+}++impl PolygonalFeatureMap for ConvexPolyhedron {+ fn local_support_feature(&self, dir: Vector, out_feature: &mut PolygonalFeature) {+ let mut best_fid = 0;+ let mut best_dot = self.faces[0].normal.dot(dir);++ for (fid, face) in self.faces[1..].iter().enumerate() {+ let new_dot = face.normal.dot(dir);++ if new_dot > best_dot {+ best_fid = fid + 1;+ best_dot = new_dot;+ }+ }++ let face = &self.faces[best_fid];+ let i1 = face.first_vertex_or_edge;+ // TODO: if there are more than 4 vertices, we need to select four vertices that maximize the area.+ let num_vertices = face.num_vertices_or_edges.min(4);+ let i2 = i1 + num_vertices;++ for (i, (vid, eid)) in self.vertices_adj_to_face[i1 as usize..i2 as usize]+ .iter()+ .zip(self.edges_adj_to_face[i1 as usize..i2 as usize].iter())+ .enumerate()+ {+ out_feature.vertices[i] = self.points[*vid as usize];+ out_feature.vids[i] = PackedFeatureId::vertex(*vid);+ out_feature.eids[i] = PackedFeatureId::edge(*eid);+ }++ out_feature.fid = PackedFeatureId::face(best_fid as u32);+ out_feature.num_vertices = num_vertices as usize;+ }++ fn is_convex_polyhedron(&self) -> bool {+ true+ }+}++/*+impl ConvexPolyhedron for ConvexPolyhedron {+ fn vertex(&self, id: FeatureId) -> Vector {+ self.points[id.unwrap_vertex() as usize]+ }++ fn edge(&self, id: FeatureId) -> (Vector, Vector, FeatureId, FeatureId) {+ let edge = &self.edges[id.unwrap_edge() as usize];+ let v1 = edge.vertices[0];+ let v2 = edge.vertices[1];++ (+ self.points[v1 as usize],+ self.points[v2 as usize],+ FeatureId::Vertex(v1),+ FeatureId::Vertex(v2),+ )+ }++ fn face(&self, id: FeatureId, out: &mut ConvexPolygonalFeature) {+ out.clear();++ let face = &self.faces[id.unwrap_face() as usize];+ let first_vertex = face.first_vertex_or_edge;+ let last_vertex = face.first_vertex_or_edge + face.num_vertices_or_edges;++ for i in first_vertex..last_vertex {+ let vid = self.vertices_adj_to_face[i];+ let eid = self.edges_adj_to_face[i];+ out.push(self.points[vid], FeatureId::Vertex(vid));+ out.push_edge_feature_id(FeatureId::Edge(eid));+ }++ out.set_normal(face.normal);+ out.set_feature_id(id);+ out.recompute_edge_normals();+ }++ fn support_face_toward(+ &self,+ m: &Pose,+ dir: Vector,+ out: &mut ConvexPolygonalFeature,+ ) {+ let ls_dir = m.inverse_transform_vector(dir);+ let mut best_face = 0;+ let mut max_dot = self.faces[0].normal.dot(ls_dir);++ for i in 1..self.faces.len() {+ let face = &self.faces[i];+ let dot = face.normal.dot(ls_dir);++ if dot > max_dot {+ max_dot = dot;+ best_face = i;+ }+ }++ self.face(FeatureId::Face(best_face), out);+ out.transform_by(m);+ }++ fn support_feature_toward(+ &self,+ transform: &Pose,+ dir: Vector,+ angle: Real,+ out: &mut ConvexPolygonalFeature,+ ) {+ out.clear();+ let local_dir = transform.inverse_transform_unit_vector(dir);+ let fid = self.support_feature_id_toward_eps(&local_dir, angle);++ match fid {+ FeatureId::Vertex(_) => {+ let v = self.vertex(fid);+ out.push(v, fid);+ out.set_feature_id(fid);+ }+ FeatureId::Edge(_) => {+ let edge = self.edge(fid);+ out.push(edge.0, edge.2);+ out.push(edge.1, edge.3);+ out.set_feature_id(fid);+ out.push_edge_feature_id(fid);+ }+ FeatureId::Face(_) => self.face(fid, out),+ FeatureId::Unknown => unreachable!(),+ }++ out.transform_by(transform);+ }+}+*/diff --git a/renderer/third_party/parry3d/src/shape/cuboid.rs b/renderer/third_party/parry3d/src/shape/cuboid.rsnew file mode 100644index 0000000..2e4ad00--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/cuboid.rs@@ -0,0 +1,821 @@+//! Support mapping based Cuboid shape.++#[cfg(feature = "dim3")]+use crate::math::Real;+use crate::math::{Vector, VectorExt};+#[cfg(feature = "dim3")]+use crate::shape::Segment;+use crate::shape::{FeatureId, PackedFeatureId, PolygonalFeature, SupportMap};+use crate::utils::WSign;++/// A cuboid shape, also known as a box or rectangle.+///+/// A cuboid is defined by its **half-extents**, which are half the width, height+/// (and depth in 3D) along each axis. The cuboid is always axis-aligned in its+/// local coordinate system and centered at the origin.+///+/// # Properties+///+/// - **In 2D**: Represents a rectangle with dimensions `2 * half_extents.x` by `2 * half_extents.y`+/// - **In 3D**: Represents a box with dimensions `2 * half_extents.x/y/z`+/// - **Convex**: Yes, cuboids are always convex shapes+/// - **Axis-aligned**: In local space, yes (but can be rotated via transformation)+///+/// # Why Half-Extents?+///+/// Using half-extents instead of full dimensions makes many calculations simpler+/// and more efficient. For example, checking if a point is inside a cuboid becomes:+/// `abs(point.x) <= half_extents.x && abs(point.y) <= half_extents.y`+///+/// # Use Cases+///+/// Cuboids are ideal for:+/// - Boxes, crates, and containers+/// - Walls, floors, and platforms+/// - Simple collision bounds for complex objects+/// - AABB (Axis-Aligned Bounding Box) representations+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Cuboid;+/// use parry3d::math::Vector;+///+/// // Create a box that is 4 units wide, 2 units tall, and 6 units deep+/// // (half-extents are half of each dimension)+/// let cuboid = Cuboid::new(Vector::new(2.0, 1.0, 3.0));+///+/// assert_eq!(cuboid.half_extents.x, 2.0);+/// assert_eq!(cuboid.half_extents.y, 1.0);+/// assert_eq!(cuboid.half_extents.z, 3.0);+///+/// // Full dimensions would be:+/// // width = 4.0, height = 2.0, depth = 6.0+/// # }+/// ```+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]+#[cfg_attr(feature = "encase", derive(encase::ShaderType))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(PartialEq, Debug, Copy, Clone)]+#[repr(C)]+pub struct Cuboid {+ /// The half-extents of the cuboid along each axis.+ ///+ /// Each component represents half the dimension along that axis:+ /// - `half_extents.x`: Half the width+ /// - `half_extents.y`: Half the height+ /// - `half_extents.z`: Half the depth (3D only)+ ///+ /// All components should be positive.+ pub half_extents: Vector,+}++impl Cuboid {+ /// Creates a new cuboid from its half-extents.+ ///+ /// Half-extents represent half the width along each axis. To create a cuboid+ /// with full dimensions (width, height, depth), divide each by 2.+ ///+ /// # Arguments+ ///+ /// * `half_extents` - Half the dimensions along each axis. All components should be positive.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Cuboid;+ /// use parry3d::math::Vector;+ ///+ /// // Create a 10x6x4 box (full dimensions)+ /// let cuboid = Cuboid::new(Vector::new(5.0, 3.0, 2.0));+ ///+ /// // Verify the half-extents+ /// assert_eq!(cuboid.half_extents.x, 5.0);+ /// assert_eq!(cuboid.half_extents.y, 3.0);+ /// assert_eq!(cuboid.half_extents.z, 2.0);+ /// # }+ /// ```+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// // In 2D:+ /// use parry2d::shape::Cuboid;+ /// use parry2d::math::Vector;+ ///+ /// // Create a 20x10 rectangle+ /// let rect = Cuboid::new(Vector::new(10.0, 5.0));+ /// assert_eq!(rect.half_extents.x, 10.0);+ /// assert_eq!(rect.half_extents.y, 5.0);+ /// # }+ /// ```+ #[inline]+ pub fn new(half_extents: Vector) -> Cuboid {+ Cuboid { half_extents }+ }++ /// Computes a scaled version of this cuboid.+ ///+ /// Each dimension is multiplied by the corresponding component of the `scale` vector.+ /// Unlike balls, cuboids can be scaled non-uniformly (different scale factors per axis)+ /// and still remain valid cuboids.+ ///+ /// # Arguments+ ///+ /// * `scale` - The scaling factors for each axis+ ///+ /// # Returns+ ///+ /// A new cuboid with scaled dimensions+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Cuboid;+ /// use parry3d::math::Vector;+ ///+ /// let cuboid = Cuboid::new(Vector::new(1.0, 2.0, 3.0));+ ///+ /// // Uniform scaling: double all dimensions+ /// let scaled_uniform = cuboid.scaled(Vector::new(2.0, 2.0, 2.0));+ /// assert_eq!(scaled_uniform.half_extents, Vector::new(2.0, 4.0, 6.0));+ ///+ /// // Non-uniform scaling: different scale per axis+ /// let scaled_non_uniform = cuboid.scaled(Vector::new(2.0, 1.0, 0.5));+ /// assert_eq!(scaled_non_uniform.half_extents, Vector::new(2.0, 2.0, 1.5));+ /// # }+ /// ```+ pub fn scaled(self, scale: Vector) -> Self {+ let new_hext = self.half_extents * scale;+ Self {+ half_extents: new_hext,+ }+ }++ /// Return the id of the vertex of this cuboid with a normal that maximizes+ /// the dot product with `dir`.+ #[cfg(feature = "dim2")]+ pub fn vertex_feature_id(vertex: Vector) -> u32 {+ // TODO: is this still correct with the f64 version?+ #[allow(clippy::unnecessary_cast)] // Unnecessary for f32 but necessary for f64.+ {+ ((vertex.x.to_bits() >> 31) & 0b001 | (vertex.y.to_bits() >> 30) & 0b010) as u32+ }+ }++ /// Return the feature of this cuboid with a normal that maximizes+ /// the dot product with `dir`.+ #[cfg(feature = "dim2")]+ pub fn support_feature(&self, local_dir: Vector) -> PolygonalFeature {+ // In 2D, it is best for stability to always return a face.+ // It won't have any notable impact on performances anyway.+ self.support_face(local_dir)+ }++ /// Return the face of this cuboid with a normal that maximizes+ /// the dot product with `local_dir`.+ #[cfg(feature = "dim2")]+ pub fn support_face(&self, local_dir: Vector) -> PolygonalFeature {+ let he = self.half_extents;+ let i = local_dir.abs().min_position();++ let vertices = match i {+ 0 => [+ Vector::new(he.x, local_dir.y.copy_sign_to(he.y)),+ Vector::new(-he.x, local_dir.y.copy_sign_to(he.y)),+ ],+ _ => [+ Vector::new(local_dir.x.copy_sign_to(he.x), he.y),+ Vector::new(local_dir.x.copy_sign_to(he.x), -he.y),+ ],+ };++ let vid1 = Self::vertex_feature_id(vertices[0]);+ let vid2 = Self::vertex_feature_id(vertices[1]);+ let fid = (vid1.max(vid2) << 2) | vid1.min(vid2) | 0b11_00_00;++ PolygonalFeature {+ vertices,+ vids: PackedFeatureId::vertices([vid1, vid2]),+ fid: PackedFeatureId::face(fid),+ num_vertices: 2,+ }+ }++ /// Return the face of this cuboid with a normal that maximizes+ /// the dot product with `local_dir`.+ #[cfg(feature = "dim3")]+ pub fn support_feature(&self, local_dir: Vector) -> PolygonalFeature {+ // TODO: this should actually return the feature.+ // And we should change all the callers of this method to use+ // `.support_face` instead of this method to preserve their old behavior.+ self.support_face(local_dir)+ /*+ const MAX_DOT_THRESHOLD: Real = crate::utils::COS_10_DEGREES;+ const MIN_DOT_THRESHOLD: Real = 1.0 - MAX_DOT_THRESHOLD;++ let amax = local_dir.amax();+ let amin = local_dir.amin();++ if amax > MAX_DOT_THRESHOLD {+ // Support face.+ CuboidFeature::Face(support_face(self, local_dir))+ } else if amin < MIN_DOT_THRESHOLD {+ // Support edge.+ CuboidFeature::Edge(support_edge(self, local_dir))+ } else {+ // Support vertex.+ CuboidFeature::Vertex(support_vertex(self, local_dir))+ }+ */+ }++ // #[cfg(feature = "dim3")+ // pub(crate) fn support_vertex(&self, local_dir: Vector) -> CuboidFeatureVertex {+ // let vertex = local_support_point(self, local_dir);+ // let vid = vertex_feature_id(vertex);+ //+ // CuboidFeatureVertex { vertex, vid }+ // }++ /// Return the edge segment of this cuboid with a normal cone containing+ /// a direction that that maximizes the dot product with `local_dir`.+ #[cfg(feature = "dim3")]+ pub fn local_support_edge_segment(&self, local_dir: Vector) -> Segment {+ let he = self.half_extents;+ let i = local_dir.abs().min_position();+ let j = (i + 1) % 3;+ let k = (i + 2) % 3;+ let mut a = Vector::ZERO;+ a.vset(i, he.vget(i));+ a.vset(j, local_dir.vget(j).copy_sign_to(he.vget(j)));+ a.vset(k, local_dir.vget(k).copy_sign_to(he.vget(k)));++ let mut b = a;+ b.vset(i, -he.vget(i));++ Segment::new(a, b)+ }++ /// Computes the face with a normal that maximizes the dot-product with `local_dir`.+ #[cfg(feature = "dim3")]+ // The identity ors/shifts below are kept so the bit patterns line up with the comments+ // documenting the vertex/edge numbering.+ #[allow(clippy::identity_op)]+ pub fn support_face(&self, local_dir: Vector) -> PolygonalFeature {+ // NOTE: can we use the orthonormal basis of local_dir+ // to make this AoSoA friendly?+ let he = self.half_extents;+ let imax = local_dir.abs().max_position();+ #[expect(clippy::unnecessary_cast)]+ let sign = match imax {+ 0 => local_dir.x.copy_sign_to(1.0 as Real),+ 1 => local_dir.y.copy_sign_to(1.0 as Real),+ _ => local_dir.z.copy_sign_to(1.0 as Real),+ };++ let vertices = match imax {+ 0 => [+ Vector::new(he.x * sign, he.y, he.z),+ Vector::new(he.x * sign, -he.y, he.z),+ Vector::new(he.x * sign, -he.y, -he.z),+ Vector::new(he.x * sign, he.y, -he.z),+ ],+ 1 => [+ Vector::new(he.x, he.y * sign, he.z),+ Vector::new(-he.x, he.y * sign, he.z),+ Vector::new(-he.x, he.y * sign, -he.z),+ Vector::new(he.x, he.y * sign, -he.z),+ ],+ _ => [+ Vector::new(he.x, he.y, he.z * sign),+ Vector::new(he.x, -he.y, he.z * sign),+ Vector::new(-he.x, -he.y, he.z * sign),+ Vector::new(-he.x, he.y, he.z * sign),+ ],+ };++ pub fn vid(i: u32) -> u32 {+ // Each vertex has an even feature id.+ i * 2+ }++ let sign_index = ((sign as isize + 1) / 2) as u32;+ // The vertex id as numbered depending on the sign of the vertex+ // component. A + sign means the corresponding bit is 0 while a -+ // sign means the corresponding bit is 1.+ // For example the vertex [2.0, -1.0, -3.0] has the id 0b011+ let vids = match imax {+ 0 => {+ let sbit = sign_index << 2;+ [+ vid(0b000 | sbit),+ vid(0b010 | sbit),+ vid(0b011 | sbit),+ vid(0b001 | sbit),+ ]+ }+ 1 => {+ let sbit = sign_index << 1;+ [+ vid(0b000 | sbit),+ vid(0b100 | sbit),+ vid(0b101 | sbit),+ vid(0b001 | sbit),+ ]+ }+ _ => {+ let sbit = sign_index;+ [+ vid(0b000 | sbit),+ vid(0b010 | sbit),+ vid(0b110 | sbit),+ vid(0b100 | sbit),+ ]+ }+ };++ // The feature ids of edges is obtained from the vertex ids+ // of their endpoints.+ // Assuming vid1 > vid2, we do: (vid1 << 3) | vid2 | 0b11000000+ //+ let eids = match imax {+ 0 => {+ let sbits = (sign_index << 2) | (sign_index << 5); // 0b00_100_100+ [+ 0b11_010_000 | sbits,+ 0b11_011_010 | sbits,+ 0b11_011_001 | sbits,+ 0b11_001_000 | sbits,+ ]+ }+ 1 => {+ let sbits = (sign_index << 1) | (sign_index << 4); // 0b00_010_010+ [+ 0b11_100_000 | sbits,+ 0b11_101_100 | sbits,+ 0b11_101_001 | sbits,+ 0b11_001_000 | sbits,+ ]+ }+ _ => {+ let sbits = (sign_index << 0) | (sign_index << 3); // 0b00_001_001+ [+ 0b11_010_000 | sbits,+ 0b11_110_010 | sbits,+ 0b11_110_100 | sbits,+ 0b11_100_000 | sbits,+ ]+ }+ };++ // The face with normals [x, y, z] are numbered [10, 11, 12].+ // The face with negated normals are numbered [13, 14, 15].+ let fid = imax as u32 + sign_index * 3 + 10;++ PolygonalFeature {+ vertices,+ vids: PackedFeatureId::vertices(vids),+ eids: PackedFeatureId::edges(eids),+ fid: PackedFeatureId::face(fid),+ num_vertices: 4,+ }+ }++ /// The normal of the given feature of this shape.+ #[cfg(feature = "dim2")]+ pub fn feature_normal(&self, feature: FeatureId) -> Option<Vector> {+ match feature {+ FeatureId::Face(id) => {+ let mut dir: Vector = Vector::ZERO;++ if id < 2 {+ dir.vset(id as usize, 1.0);+ } else {+ dir.vset(id as usize - 2, -1.0);+ }+ Some(dir)+ }+ FeatureId::Vertex(id) => {+ let mut dir: Vector = Vector::ZERO;++ match id {+ 0b00 => {+ dir.x = 1.0;+ dir.y = 1.0;+ }+ 0b01 => {+ dir.y = 1.0;+ dir.x = -1.0;+ }+ 0b11 => {+ dir.x = -1.0;+ dir.y = -1.0;+ }+ 0b10 => {+ dir.y = -1.0;+ dir.x = 1.0;+ }+ _ => return None,+ }++ Some(dir.normalize())+ }+ _ => None,+ }+ }++ /// The normal of the given feature of this shape.+ #[cfg(feature = "dim3")]+ pub fn feature_normal(&self, feature: FeatureId) -> Option<Vector> {+ match feature {+ FeatureId::Face(id) => {+ let mut dir: Vector = Vector::ZERO;++ if id < 3 {+ dir.vset(id as usize, 1.0);+ } else {+ dir.vset(id as usize - 3, -1.0);+ }+ Some(dir)+ }+ FeatureId::Edge(id) => {+ let edge = id & 0b011;+ let face1 = (edge + 1) % 3;+ let face2 = (edge + 2) % 3;+ let signs = id >> 2;++ let mut dir: Vector = Vector::ZERO;++ if signs & (1 << face1) != 0 {+ dir.vset(face1 as usize, -1.0)+ } else {+ dir.vset(face1 as usize, 1.0)+ }++ if signs & (1 << face2) != 0 {+ dir.vset(face2 as usize, -1.0)+ } else {+ dir.vset(face2 as usize, 1.0);+ }++ Some(dir.normalize())+ }+ FeatureId::Vertex(id) => {+ let mut dir: Vector = Vector::ZERO;+ for i in 0..3 {+ if id & (1 << i) != 0 {+ dir.vset(i, -1.0);+ } else {+ dir.vset(i, 1.0)+ }+ }++ Some(dir.normalize())+ }+ _ => None,+ }+ }+}++impl SupportMap for Cuboid {+ #[inline]+ fn local_support_point(&self, dir: Vector) -> Vector {+ dir.copy_sign_to(self.half_extents)+ }+}++/*+impl ConvexPolyhedron for Cuboid {+ fn vertex(&self, id: FeatureId) -> Vector {+ let vid = id.unwrap_vertex();+ let mut res = self.half_extents;++ for i in 0..DIM {+ if vid & (1 << i) != 0 {+ res.vset(i, -res.vget(i))+ }+ }++ res+ }++ #[cfg(feature = "dim3")]+ fn edge(&self, id: FeatureId) -> (Vector, Vector, FeatureId, FeatureId) {+ let eid = id.unwrap_edge();+ let mut res = self.half_extents;++ let edge_i = eid & 0b11;+ let vertex_i = eid >> 2;++ for i in 0..DIM {+ if i as u32 != edge_i && (vertex_i & (1 << i) != 0) {+ res.vset(i, -res.vget(i))+ }+ }++ let p1 = res;+ res.vset(edge_i as usize, -res.vget(edge_i as usize));+ let p2 = res;+ let vid1 = FeatureId::Vertex(vertex_i & !(1 << edge_i));+ let vid2 = FeatureId::Vertex(vertex_i | (1 << edge_i));++ (p1, p2, vid1, vid2)+ }++ fn face(&self, id: FeatureId, out: &mut ConvexPolygonalFeature) {+ out.clear();++ let i = id.unwrap_face() as usize;+ let i1;+ let sign;++ if i < DIM {+ i1 = i;+ sign = 1.0;+ } else {+ i1 = i - DIM;+ sign = -1.0;+ }++ #[cfg(feature = "dim2")]+ {+ let i2 = (i1 + 1) % 2;++ let mut vertex = self.half_extents;+ vertex.vset(i1, vertex.vget(i1) * sign);+ vertex.vset(i2, vertex.vget(i2) * if i1 == 0 { -sign } else { sign });++ let p1 = vertex;+ vertex.vset(i2, -vertex.vget(i2));+ let p2 = vertex;++ let mut vertex_id1 = if sign < 0.0 {+ 1 << i1+ } else {+ 0+ };+ let mut vertex_id2 = vertex_id1;+ if p1.vget(i2) < 0.0 {+ vertex_id1 |= 1 << i2;+ } else {+ vertex_id2 |= 1 << i2;+ }++ out.push(p1, FeatureId::Vertex(vertex_id1));+ out.push(p2, FeatureId::Vertex(vertex_id2));++ let mut normal: Vector = Vector::ZERO;+ normal.vset(i1, sign);+ out.set_normal(normal);+ out.set_feature_id(FeatureId::Face(i as u32));+ }+ #[cfg(feature = "dim3")]+ {+ let i2 = (i1 + 1) % 3;+ let i3 = (i1 + 2) % 3;+ let (edge_i2, edge_i3) = if sign > 0.0 {+ (i2, i3)+ } else {+ (i3, i2)+ };+ let mask_i2 = !(1 << edge_i2); // The masks are for ensuring each edge has a unique ID.+ let mask_i3 = !(1 << edge_i3);+ let mut vertex = self.half_extents;+ vertex.vset(i1, vertex.vget(i1) * sign);++ let (sbit, msbit) = if sign < 0.0 {+ (1, 0)+ } else {+ (0, 1)+ };+ let mut vertex_id = sbit << i1;+ out.push(vertex, FeatureId::Vertex(vertex_id));+ out.push_edge_feature_id(FeatureId::Edge(+ edge_i2 as u32 | ((vertex_id & mask_i2) << 2),+ ));++ vertex.vset(i2, -sign * self.half_extents.vget(i2));+ vertex.vset(i3, sign * self.half_extents.vget(i3));+ vertex_id |= msbit << i2 | sbit << i3;+ out.push(vertex, FeatureId::Vertex(vertex_id));+ out.push_edge_feature_id(FeatureId::Edge(+ edge_i3 as u32 | ((vertex_id & mask_i3) << 2),+ ));++ vertex.vset(i2, -self.half_extents.vget(i2));+ vertex.vset(i3, -self.half_extents.vget(i3));+ vertex_id |= 1 << i2 | 1 << i3;+ out.push(vertex, FeatureId::Vertex(vertex_id));+ out.push_edge_feature_id(FeatureId::Edge(+ edge_i2 as u32 | ((vertex_id & mask_i2) << 2),+ ));++ vertex.vset(i2, sign * self.half_extents.vget(i2));+ vertex.vset(i3, -sign * self.half_extents.vget(i3));+ vertex_id = sbit << i1 | sbit << i2 | msbit << i3;+ out.push(vertex, FeatureId::Vertex(vertex_id));+ out.push_edge_feature_id(FeatureId::Edge(+ edge_i3 as u32 | ((vertex_id & mask_i3) << 2),+ ));++ let mut normal: Vector = Vector::ZERO;+ normal.vset(i1, sign);+ out.set_normal(normal);++ if sign > 0.0 {+ out.set_feature_id(FeatureId::Face(i1 as u32));+ } else {+ out.set_feature_id(FeatureId::Face(i1 as u32 + 3));+ }++ out.recompute_edge_normals();+ }+ }++ fn support_face_toward(+ &self,+ m: &Pose,+ dir: Vector,+ out: &mut ConvexPolygonalFeature,+ ) {+ out.clear();+ let local_dir = m.inverse_transform_vector(dir);+ let imax = iamax(local_dir);++ if local_dir.vget(imax) > 0.0 {+ self.face(FeatureId::Face(imax as u32), out);+ out.transform_by(m);+ } else {+ self.face(FeatureId::Face((imax + DIM) as u32), out);+ out.transform_by(m);+ }+ }++ fn support_feature_toward(+ &self,+ m: &Pose,+ dir: Vector,+ angle: Real,+ out: &mut ConvexPolygonalFeature,+ ) {+ let local_dir = m.inverse_transform_vector(dir);+ let cang = <Real as ComplexField>::cos(angle);+ let mut support_point = self.half_extents;++ out.clear();++ #[cfg(feature = "dim2")]+ {+ let mut support_point_id = 0;+ for i1 in 0..2 {+ let sign = local_dir.vget(i1).signum();+ if sign * local_dir.vget(i1) >= cang {+ if sign > 0.0 {+ self.face(FeatureId::Face(i1 as u32), out);+ out.transform_by(m);+ } else {+ self.face(FeatureId::Face(i1 as u32 + 2), out);+ out.transform_by(m);+ }+ return;+ } else {+ if sign < 0.0 {+ support_point_id |= 1 << i1;+ }+ support_point.vset(i1, support_point.vget(i1) * sign);+ }+ }++ // We are not on a face, return the support vertex.+ out.push(+ m * support_point,+ FeatureId::Vertex(support_point_id),+ );+ out.set_feature_id(FeatureId::Vertex(support_point_id));+ }++ #[cfg(feature = "dim3")]+ {+ let sang = <Real as ComplexField>::sin(angle);+ let mut support_point_id = 0;++ // Check faces.+ for i1 in 0..3 {+ let sign = local_dir.vget(i1).signum();+ if sign * local_dir.vget(i1) >= cang {+ if sign > 0.0 {+ self.face(FeatureId::Face(i1 as u32), out);+ out.transform_by(m);+ } else {+ self.face(FeatureId::Face(i1 as u32 + 3), out);+ out.transform_by(m);+ }+ return;+ } else {+ if sign < 0.0 {+ support_point.vset(i1, support_point.vget(i1) * sign);+ support_point_id |= 1 << i1;+ }+ }+ }++ // Check edges.+ for i in 0..3 {+ let sign = local_dir.vget(i).signum();++ // sign * local_dir.vget(i) <= cos(pi / 2 - angle)+ if sign * local_dir.vget(i) <= sang {+ support_point.vset(i, -self.half_extents.vget(i));+ let p1 = support_point;+ support_point.vset(i, self.half_extents.vget(i));+ let p2 = support_point;+ let p2_id = support_point_id & !(1 << i);+ out.push(m * p1, FeatureId::Vertex(support_point_id | (1 << i)));+ out.push(m * p2, FeatureId::Vertex(p2_id));++ let edge_id = FeatureId::Edge(i as u32 | (p2_id << 2));+ out.push_edge_feature_id(edge_id);+ out.set_feature_id(edge_id);+ return;+ }+ }++ // We are not on a face or edge, return the support vertex.+ out.push(+ m * support_point,+ FeatureId::Vertex(support_point_id),+ );+ out.set_feature_id(FeatureId::Vertex(support_point_id));+ }+ }++ fn support_feature_id_toward(&self, local_dir: Vector) -> FeatureId {+ let one_degree: Real = (f64::consts::PI / 180.0) as Real;+ let cang = <Real as ComplexField>::cos(one_degree);++ #[cfg(feature = "dim2")]+ {+ let mut support_point_id = 0;+ for i1 in 0..2 {+ let sign = local_dir.vget(i1).signum();+ if sign * local_dir.vget(i1) >= cang {+ if sign > 0.0 {+ return FeatureId::Face(i1 as u32);+ } else {+ return FeatureId::Face(i1 as u32 + 2);+ }+ } else {+ if sign < 0.0 {+ support_point_id |= 1 << i1;+ }+ }+ }++ // We are not on a face, return the support vertex.+ FeatureId::Vertex(support_point_id)+ }++ #[cfg(feature = "dim3")]+ {+ let sang = <Real as ComplexField>::sin(one_degree);+ let mut support_point_id = 0;++ // Check faces.+ for i1 in 0..3 {+ let sign = local_dir.vget(i1).signum();+ if sign * local_dir.vget(i1) >= cang {+ if sign > 0.0 {+ return FeatureId::Face(i1 as u32);+ } else {+ return FeatureId::Face(i1 as u32 + 3);+ }+ } else {+ if sign < 0.0 {+ support_point_id |= 1 << i1;+ }+ }+ }++ // Check edges.+ for i in 0..3 {+ let sign = local_dir.vget(i).signum();++ // sign * local_dir.vget(i) <= cos(pi / 2 - angle)+ if sign * local_dir.vget(i) <= sang {+ let mask_i = !(1 << i); // To ensure each edge has a unique id.+ return FeatureId::Edge(i as u32 | ((support_point_id & mask_i) << 2));+ }+ }++ FeatureId::Vertex(support_point_id)+ }+ }+}+*/diff --git a/renderer/third_party/parry3d/src/shape/cylinder.rs b/renderer/third_party/parry3d/src/shape/cylinder.rsnew file mode 100644index 0000000..317fc1b--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/cylinder.rs@@ -0,0 +1,206 @@+//! Support mapping based Cylinder shape.++use crate::math::{Real, Vector};+use crate::shape::SupportMap;+use crate::utils::WSign;++#[cfg(feature = "alloc")]+use either::Either;++/// A 3D cylinder shape with axis aligned along the Y axis.+///+/// A cylinder is a shape with circular cross-sections perpendicular to its axis.+/// In Parry, cylinders are always aligned with the Y axis in their local coordinate+/// system and centered at the origin.+///+/// # Structure+///+/// - **Axis**: Always aligned with Y axis (up/down)+/// - **half_height**: Half the length along the Y axis+/// - **radius**: The radius of the circular cross-section+/// - **Height**: Total height = `2 * half_height`+///+/// # Properties+///+/// - **3D only**: Only available with the `dim3` feature+/// - **Convex**: Yes, cylinders are convex shapes+/// - **Flat caps**: The top and bottom are flat circles (not rounded)+/// - **Sharp edges**: The rim where cap meets side is a sharp edge+///+/// # vs Capsule+///+/// If you need rounded ends instead of flat caps, use [`Capsule`](super::Capsule):+/// - **Cylinder**: Flat circular caps, sharp edges at rims+/// - **Capsule**: Hemispherical caps, completely smooth (no edges)+/// - **Capsule**: Better for characters and rolling objects+/// - **Cylinder**: Better for columns, cans, pipes+///+/// # Use Cases+///+/// - Pillars and columns+/// - Cans and barrels+/// - Wheels and disks+/// - Pipes and tubes+/// - Any object with flat circular ends+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Cylinder;+///+/// // Create a cylinder: radius 2.0, total height 10.0+/// let cylinder = Cylinder::new(5.0, 2.0);+///+/// assert_eq!(cylinder.half_height, 5.0);+/// assert_eq!(cylinder.radius, 2.0);+///+/// // Total height is 2 * half_height+/// let total_height = cylinder.half_height * 2.0;+/// assert_eq!(total_height, 10.0);+/// # }+/// ```+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]+#[cfg_attr(feature = "encase", derive(encase::ShaderType))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(PartialEq, Debug, Copy, Clone)]+#[repr(C)]+pub struct Cylinder {+ /// Half the length of the cylinder along the Y axis.+ ///+ /// The cylinder extends from `-half_height` to `+half_height` along Y.+ /// Total height = `2 * half_height`. Must be positive.+ pub half_height: Real,++ /// The radius of the circular cross-section.+ ///+ /// All points on the cylindrical surface are at this distance from the Y axis.+ /// Must be positive.+ pub radius: Real,+}++impl Cylinder {+ /// Creates a new cylinder aligned with the Y axis.+ ///+ /// # Arguments+ ///+ /// * `half_height` - Half the total height along the Y axis+ /// * `radius` - The radius of the circular cross-section+ ///+ /// # Panics+ ///+ /// Panics if `half_height` or `radius` is not positive.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Cylinder;+ ///+ /// // Create a cylinder with radius 3.0 and height 8.0+ /// let cylinder = Cylinder::new(4.0, 3.0);+ ///+ /// assert_eq!(cylinder.half_height, 4.0);+ /// assert_eq!(cylinder.radius, 3.0);+ ///+ /// // The cylinder:+ /// // - Extends from y = -4.0 to y = 4.0 (total height 8.0)+ /// // - Has circular cross-section with radius 3.0 in the XZ plane+ /// # }+ /// ```+ pub fn new(half_height: Real, radius: Real) -> Cylinder {+ assert!(half_height.is_sign_positive() && radius.is_sign_positive());++ Cylinder {+ half_height,+ radius,+ }+ }++ /// Computes a scaled version of this cylinder.+ ///+ /// Scaling a cylinder can produce different results depending on the scale factors:+ ///+ /// - **Uniform scaling** (all axes equal): Produces another cylinder+ /// - **Y different from X/Z**: Produces another cylinder (if X == Z)+ /// - **Non-uniform X/Z**: Produces an elliptical cylinder approximated as a convex mesh+ ///+ /// # Arguments+ ///+ /// * `scale` - Scaling factors for X, Y, Z axes+ /// * `nsubdivs` - Number of subdivisions for mesh approximation (if needed)+ ///+ /// # Returns+ ///+ /// * `Some(Either::Left(Cylinder))` - If X and Z scales are equal+ /// * `Some(Either::Right(ConvexPolyhedron))` - If X and Z scales differ (elliptical)+ /// * `None` - If mesh approximation failed (e.g., zero scale on an axis)+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32", feature = "alloc"))] {+ /// use parry3d::shape::Cylinder;+ /// use parry3d::math::Vector;+ /// use either::Either;+ ///+ /// let cylinder = Cylinder::new(2.0, 1.0);+ ///+ /// // Uniform scaling: produces a larger cylinder+ /// let scale1 = Vector::splat(2.0);+ /// if let Some(Either::Left(scaled)) = cylinder.scaled(scale1, 20) {+ /// assert_eq!(scaled.radius, 2.0); // 1.0 * 2.0+ /// assert_eq!(scaled.half_height, 4.0); // 2.0 * 2.0+ /// }+ ///+ /// // Different Y scale: still a cylinder+ /// let scale2 = Vector::new(1.5, 3.0, 1.5);+ /// if let Some(Either::Left(scaled)) = cylinder.scaled(scale2, 20) {+ /// assert_eq!(scaled.radius, 1.5); // 1.0 * 1.5+ /// assert_eq!(scaled.half_height, 6.0); // 2.0 * 3.0+ /// }+ ///+ /// // Non-uniform X/Z: produces elliptical cylinder (mesh approximation)+ /// let scale3 = Vector::new(2.0, 1.0, 1.0);+ /// if let Some(Either::Right(polyhedron)) = cylinder.scaled(scale3, 20) {+ /// // Result is a convex mesh approximating an elliptical cylinder+ /// assert!(polyhedron.points().len() > 0);+ /// }+ /// # }+ /// ```+ #[cfg(feature = "alloc")]+ #[inline]+ pub fn scaled(+ self,+ scale: Vector,+ nsubdivs: u32,+ ) -> Option<Either<Self, super::ConvexPolyhedron>> {+ if scale.x != scale.z {+ // The scaled shape isn't a cylinder.+ let (mut vtx, idx) = self.to_trimesh(nsubdivs);+ vtx.iter_mut().for_each(|pt| *pt *= scale);+ Some(Either::Right(super::ConvexPolyhedron::from_convex_mesh(+ vtx, &idx,+ )?))+ } else {+ Some(Either::Left(Self::new(+ self.half_height * scale.y,+ self.radius * scale.x,+ )))+ }+ }+}++impl SupportMap for Cylinder {+ fn local_support_point(&self, dir: Vector) -> Vector {+ let mut vres = dir;+ vres.y = 0.0;+ vres = vres.normalize_or_zero() * self.radius;+ vres.y = dir.y.copy_sign_to(self.half_height);+ vres+ }+}diff --git a/renderer/third_party/parry3d/src/shape/feature_id.rs b/renderer/third_party/parry3d/src/shape/feature_id.rsnew file mode 100644index 0000000..1f89743--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/feature_id.rs@@ -0,0 +1,752 @@+/// The index of a sub-shape within a shape that has several.+///+/// Identifies a part of a [`Compound`](crate::shape::Compound), a triangle of a+/// [`TriMesh`](crate::shape::TriMesh), a segment of a [`Polyline`](crate::shape::Polyline), a cell+/// of a [`HeightField`](crate::shape::HeightField), or a voxel of a+/// [`Voxels`](crate::shape::Voxels) shape.+///+/// Query results carry the sub-shape they came from, so a hit against a composite shape says which+/// part answered. A shape with no sub-shapes, like a [`Ball`](crate::shape::Ball) or a+/// [`Cuboid`](crate::shape::Cuboid), always reports `0`.+pub type SubShapeId = u32;++/// An identifier of a geometric feature (vertex, edge, or face) of a shape.+///+/// Feature IDs are used throughout Parry to identify specific geometric features on shapes+/// during collision detection, contact generation, and other geometric queries. They allow+/// algorithms to track which parts of shapes are interacting, which is essential for:+///+/// - **Contact manifold generation**: Tracking persistent contact points between frames+/// - **Collision response**: Determining which features are colliding+/// - **Debug visualization**: Highlighting specific geometric elements+/// - **Feature-based queries**: Retrieving geometric data for specific shape features+///+/// # Feature Types+///+/// - **Vertex**: A corner point of the shape (0-dimensional feature)+/// - **Edge**: A line segment connecting two vertices (1-dimensional feature, 3D only)+/// - **Face**: A flat surface bounded by edges (2-dimensional feature)+/// - **Unknown**: Used when the feature type cannot be determined or is not applicable+///+/// # Shape-Specific Identifiers+///+/// The numeric ID within each feature type is shape-dependent. For example:+/// - For a cuboid, vertex IDs might range from 0-7 (8 corners)+/// - For a triangle, face ID 0 typically refers to the triangle itself+/// - For composite shapes, IDs might encode both the sub-shape and the feature within it+///+/// The exact meaning of these IDs depends on the shape's internal representation, but they+/// are guaranteed to allow efficient retrieval of the feature's geometric information.+///+/// # Examples+///+/// Basic usage of feature IDs in 2D:+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::shape::FeatureId;+///+/// // Create a vertex feature identifier+/// let vertex_id = FeatureId::Vertex(5);+/// assert_eq!(vertex_id.unwrap_vertex(), 5);+///+/// // Create a face feature identifier (in 2D, faces are edges of the polygon)+/// let face_id = FeatureId::Face(2);+/// assert_eq!(face_id.unwrap_face(), 2);+///+/// // Unknown feature (used as default)+/// let unknown = FeatureId::Unknown;+/// assert_eq!(unknown, FeatureId::default());+/// # }+/// ```+///+/// Basic usage of feature IDs in 3D:+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::FeatureId;+///+/// // Create a vertex feature identifier+/// let vertex_id = FeatureId::Vertex(5);+/// assert_eq!(vertex_id.unwrap_vertex(), 5);+///+/// // Create an edge feature identifier (only available in 3D)+/// let edge_id = FeatureId::Edge(3);+/// assert_eq!(edge_id.unwrap_edge(), 3);+///+/// // Create a face feature identifier+/// let face_id = FeatureId::Face(2);+/// assert_eq!(face_id.unwrap_face(), 2);+///+/// // Unknown feature (used as default)+/// let unknown = FeatureId::Unknown;+/// assert_eq!(unknown, FeatureId::default());+/// # }+/// ```+///+/// Pattern matching on feature types in 3D:+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::FeatureId;+///+/// fn describe_feature(feature: FeatureId) -> String {+/// match feature {+/// FeatureId::Vertex(id) => format!("Vertex #{}", id),+/// FeatureId::Edge(id) => format!("Edge #{}", id),+/// FeatureId::Face(id) => format!("Face #{}", id),+/// FeatureId::Unknown => "Unknown feature".to_string(),+/// }+/// }+///+/// assert_eq!(describe_feature(FeatureId::Vertex(3)), "Vertex #3");+/// assert_eq!(describe_feature(FeatureId::Edge(5)), "Edge #5");+/// assert_eq!(describe_feature(FeatureId::Face(1)), "Face #1");+/// # }+/// ```+///+/// # 2D vs 3D+///+/// In 2D mode (`dim2` feature), the `Edge` variant is not available since edges in 2D+/// are effectively the same as faces (line segments). In 2D:+/// - Vertices represent corner points+/// - Faces represent edges of the polygon+///+/// In 3D mode (`dim3` feature), all three types are available:+/// - Vertices are 0D points+/// - Edges are 1D line segments+/// - Faces are 2D polygons+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, Default)]+pub enum FeatureId {+ /// Shape-dependent identifier of a vertex (0-dimensional corner point).+ ///+ /// The numeric ID is specific to each shape type and allows efficient lookup+ /// of the vertex's position and other geometric properties.+ Vertex(u32),+ #[cfg(feature = "dim3")]+ /// Shape-dependent identifier of an edge (1-dimensional line segment).+ ///+ /// Available only in 3D mode. The numeric ID is specific to each shape type+ /// and allows efficient lookup of the edge's endpoints and direction.+ Edge(u32),+ /// Shape-dependent identifier of a face (2-dimensional flat surface).+ ///+ /// In 2D, faces represent the edges of polygons (line segments).+ /// In 3D, faces represent polygonal surfaces. The numeric ID is specific+ /// to each shape type and allows efficient lookup of the face's vertices,+ /// normal vector, and other properties.+ Face(u32),+ // XXX: remove this variant.+ /// Unknown or unidentified feature.+ ///+ /// Used as a default value or when the specific feature cannot be determined.+ /// This variant should generally be avoided in production code.+ #[default]+ Unknown,+}++impl FeatureId {+ /// Retrieves the numeric ID if this is a vertex feature.+ ///+ /// # Panics+ ///+ /// Panics if the feature is not a vertex (i.e., if it's an edge, face, or unknown).+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::FeatureId;+ ///+ /// let vertex = FeatureId::Vertex(42);+ /// assert_eq!(vertex.unwrap_vertex(), 42);+ /// # }+ /// ```+ ///+ /// This will panic:+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::FeatureId;+ ///+ /// let face = FeatureId::Face(5);+ /// face.unwrap_vertex(); // Panics!+ /// # }+ /// # #[cfg(all(feature = "dim2", feature = "f64"))] {+ /// use parry2d_f64::shape::FeatureId;+ ///+ /// let face = FeatureId::Face(5);+ /// face.unwrap_vertex(); // Panics!+ /// # }+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::FeatureId;+ ///+ /// let face = FeatureId::Face(5);+ /// face.unwrap_vertex(); // Panics!+ /// # }+ /// # #[cfg(all(feature = "dim3", feature = "f64"))] {+ /// use parry3d_f64::shape::FeatureId;+ ///+ /// let face = FeatureId::Face(5);+ /// face.unwrap_vertex(); // Panics!+ /// # }+ /// ```+ pub fn unwrap_vertex(self) -> u32 {+ match self {+ FeatureId::Vertex(id) => id,+ _ => panic!("The feature id does not identify a vertex."),+ }+ }++ /// Retrieves the numeric ID if this is an edge feature.+ ///+ /// Available only in 3D mode (`dim3` feature).+ ///+ /// # Panics+ ///+ /// Panics if the feature is not an edge (i.e., if it's a vertex, face, or unknown).+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::FeatureId;+ ///+ /// let edge = FeatureId::Edge(7);+ /// assert_eq!(edge.unwrap_edge(), 7);+ /// # }+ /// ```+ ///+ /// This will panic:+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::FeatureId;+ ///+ /// let vertex = FeatureId::Vertex(3);+ /// vertex.unwrap_edge(); // Panics!+ /// # }+ /// ```+ #[cfg(feature = "dim3")]+ pub fn unwrap_edge(self) -> u32 {+ match self {+ FeatureId::Edge(id) => id,+ _ => panic!("The feature id does not identify an edge."),+ }+ }++ /// Retrieves the numeric ID if this is a face feature.+ ///+ /// # Panics+ ///+ /// Panics if the feature is not a face (i.e., if it's a vertex, edge, or unknown).+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::FeatureId;+ ///+ /// let face = FeatureId::Face(12);+ /// assert_eq!(face.unwrap_face(), 12);+ /// # }+ /// ```+ ///+ /// This will panic:+ ///+ /// ```should_panic+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::FeatureId;+ ///+ /// let vertex = FeatureId::Vertex(0);+ /// vertex.unwrap_face(); // Panics!+ /// # }+ /// # #[cfg(all(feature = "dim2", feature = "f64"))] {+ /// use parry2d_f64::shape::FeatureId;+ ///+ /// let vertex = FeatureId::Vertex(0);+ /// vertex.unwrap_face(); // Panics!+ /// # }+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::FeatureId;+ ///+ /// let vertex = FeatureId::Vertex(0);+ /// vertex.unwrap_face(); // Panics!+ /// # }+ /// # #[cfg(all(feature = "dim3", feature = "f64"))] {+ /// use parry3d_f64::shape::FeatureId;+ ///+ /// let vertex = FeatureId::Vertex(0);+ /// vertex.unwrap_face(); // Panics!+ /// # }+ /// ```+ pub fn unwrap_face(self) -> u32 {+ match self {+ FeatureId::Face(id) => id,+ _ => panic!("The feature id does not identify a face."),+ }+ }+}++/// A memory-efficient feature ID where the type and index are packed into a single `u32`.+///+/// `PackedFeatureId` is a space-optimized version of [`FeatureId`] that encodes both the+/// feature type (vertex, edge, or face) and its numeric identifier in a single 32-bit value.+/// This is particularly useful when storing large numbers of feature IDs, as it uses half+/// the memory of a standard enum representation.+///+/// # Memory Layout+///+/// The packing scheme uses the upper 2 bits to encode the feature type, leaving 30 bits+/// (0-1,073,741,823) for the feature index:+///+/// ```text+/// ┌──┬──┬────────────────────────────────┐+/// │31│30│29 0│+/// ├──┴──┴────────────────────────────────┤+/// │Type │ Feature Index │+/// │(2b) │ (30 bits) │+/// └─────┴────────────────────────────────┘+///+/// Type encoding:+/// - 00: Unknown+/// - 01: Vertex+/// - 10: Edge (3D only)+/// - 11: Face+/// ```+///+/// # Use Cases+///+/// Use `PackedFeatureId` when:+/// - Storing feature IDs in large data structures (e.g., contact manifolds)+/// - Passing feature IDs across FFI boundaries where a fixed size is required+/// - Memory usage is a concern and you have many feature IDs+///+/// Use regular [`FeatureId`] when:+/// - Code clarity is more important than memory usage+/// - You need to pattern match on feature types frequently+/// - Working with small numbers of feature IDs+///+/// # Examples+///+/// Creating and unpacking feature IDs in 2D:+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::shape::{FeatureId, PackedFeatureId};+///+/// // Create a packed vertex ID+/// let packed_vertex = PackedFeatureId::vertex(10);+/// assert!(packed_vertex.is_vertex());+/// assert!(!packed_vertex.is_face());+///+/// // Create a packed face ID+/// let packed_face = PackedFeatureId::face(5);+/// assert!(packed_face.is_face());+///+/// // Unpack to get the full enum+/// let unpacked = packed_face.unpack();+/// assert_eq!(unpacked, FeatureId::Face(5));+/// # }+/// ```+///+/// Creating and unpacking feature IDs in 3D:+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{FeatureId, PackedFeatureId};+///+/// // Create a packed vertex ID+/// let packed_vertex = PackedFeatureId::vertex(10);+/// assert!(packed_vertex.is_vertex());+/// assert!(!packed_vertex.is_face());+///+/// // Create a packed edge ID (3D only)+/// let packed_edge = PackedFeatureId::edge(7);+/// assert!(packed_edge.is_edge());+///+/// // Create a packed face ID+/// let packed_face = PackedFeatureId::face(5);+/// assert!(packed_face.is_face());+///+/// // Unpack to get the full enum+/// let unpacked = packed_face.unpack();+/// assert_eq!(unpacked, FeatureId::Face(5));+/// # }+/// ```+///+/// Converting between packed and unpacked forms:+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::shape::{FeatureId, PackedFeatureId};+///+/// // From FeatureId to PackedFeatureId+/// let feature = FeatureId::Vertex(42);+/// let packed: PackedFeatureId = feature.into();+/// assert!(packed.is_vertex());+///+/// // From PackedFeatureId back to FeatureId+/// let unpacked = packed.unpack();+/// assert_eq!(unpacked, FeatureId::Vertex(42));+/// # }+/// ```+///+/// Working with the unknown feature:+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::shape::PackedFeatureId;+///+/// let unknown = PackedFeatureId::UNKNOWN;+/// assert!(unknown.is_unknown());+/// assert!(!unknown.is_vertex());+/// assert!(!unknown.is_face());+/// # }+/// ```+///+/// Checking feature types efficiently in 3D:+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::PackedFeatureId;+///+/// let vertex = PackedFeatureId::vertex(100);+/// let edge = PackedFeatureId::edge(50);+/// let face = PackedFeatureId::face(25);+///+/// // Type checking is very fast (just bit masking)+/// assert!(vertex.is_vertex());+/// assert!(edge.is_edge());+/// assert!(face.is_face());+///+/// // Different types are not equal+/// assert_ne!(vertex, edge);+/// assert_ne!(edge, face);+/// # }+/// ```+///+/// # Performance+///+/// `PackedFeatureId` provides several performance benefits:+/// - **Memory**: Uses 4 bytes vs 8 bytes for `FeatureId` (on 64-bit systems)+/// - **Cache efficiency**: Better cache utilization when storing many IDs+/// - **Type checking**: Very fast (single bitwise AND operation)+/// - **Conversion**: Converting to/from `FeatureId` is essentially free+///+/// # Limitations+///+/// The packing scheme limits feature indices to 30 bits (max value: 1,073,741,823).+/// Attempting to create a packed feature ID with a larger index will panic in debug+/// mode due to the assertion checks in the constructor methods.+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]+pub struct PackedFeatureId(pub u32);++impl PackedFeatureId {+ /// Constant representing an unknown or unidentified feature.+ ///+ /// This is the default value and corresponds to `FeatureId::Unknown`.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::{PackedFeatureId, FeatureId};+ ///+ /// let unknown = PackedFeatureId::UNKNOWN;+ /// assert!(unknown.is_unknown());+ /// assert_eq!(unknown.unpack(), FeatureId::Unknown);+ /// # }+ /// ```+ pub const UNKNOWN: Self = Self(0);++ const CODE_MASK: u32 = 0x3fff_ffff;+ const HEADER_MASK: u32 = !Self::CODE_MASK;+ const HEADER_VERTEX: u32 = 0b01 << 30;+ #[cfg(feature = "dim3")]+ const HEADER_EDGE: u32 = 0b10 << 30;+ const HEADER_FACE: u32 = 0b11 << 30;++ /// Creates a packed feature ID for a vertex with the given index.+ ///+ /// # Panics+ ///+ /// Panics in debug mode if `code` uses any of the upper 2 bits (i.e., if `code >= 2^30`).+ /// The maximum valid value is 1,073,741,823 (0x3FFFFFFF).+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::{PackedFeatureId, FeatureId};+ ///+ /// let packed = PackedFeatureId::vertex(5);+ /// assert!(packed.is_vertex());+ /// assert_eq!(packed.unpack(), FeatureId::Vertex(5));+ /// # }+ /// ```+ pub fn vertex(code: u32) -> Self {+ #[cfg(not(target_arch = "spirv"))]+ assert_eq!(code & Self::HEADER_MASK, 0);+ Self(Self::HEADER_VERTEX | code)+ }++ /// Creates a packed feature ID for an edge with the given index.+ ///+ /// Available only in 3D mode (`dim3` feature).+ ///+ /// # Panics+ ///+ /// Panics in debug mode if `code` uses any of the upper 2 bits (i.e., if `code >= 2^30`).+ /// The maximum valid value is 1,073,741,823 (0x3FFFFFFF).+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{PackedFeatureId, FeatureId};+ ///+ /// let packed = PackedFeatureId::edge(10);+ /// assert!(packed.is_edge());+ /// assert_eq!(packed.unpack(), FeatureId::Edge(10));+ /// # }+ /// ```+ #[cfg(feature = "dim3")]+ pub fn edge(code: u32) -> Self {+ #[cfg(not(target_arch = "spirv"))]+ assert_eq!(code & Self::HEADER_MASK, 0);+ Self(Self::HEADER_EDGE | code)+ }++ /// Creates a packed feature ID for a face with the given index.+ ///+ /// # Panics+ ///+ /// Panics in debug mode if `code` uses any of the upper 2 bits (i.e., if `code >= 2^30`).+ /// The maximum valid value is 1,073,741,823 (0x3FFFFFFF).+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::{PackedFeatureId, FeatureId};+ ///+ /// let packed = PackedFeatureId::face(15);+ /// assert!(packed.is_face());+ /// assert_eq!(packed.unpack(), FeatureId::Face(15));+ /// # }+ /// ```+ pub fn face(code: u32) -> Self {+ #[cfg(not(target_arch = "spirv"))]+ assert_eq!(code & Self::HEADER_MASK, 0);+ Self(Self::HEADER_FACE | code)+ }++ #[cfg(feature = "dim2")]+ /// Converts an array of vertex feature ids into an array of packed feature ids.+ pub(crate) fn vertices(code: [u32; 2]) -> [Self; 2] {+ [Self::vertex(code[0]), Self::vertex(code[1])]+ }++ #[cfg(feature = "dim3")]+ /// Converts an array of vertex feature ids into an array of packed feature ids.+ pub(crate) fn vertices(code: [u32; 4]) -> [Self; 4] {+ [+ Self::vertex(code[0]),+ Self::vertex(code[1]),+ Self::vertex(code[2]),+ Self::vertex(code[3]),+ ]+ }++ #[cfg(feature = "dim3")]+ /// Converts an array of edge feature ids into an array of packed feature ids.+ pub(crate) fn edges(code: [u32; 4]) -> [Self; 4] {+ [+ Self::edge(code[0]),+ Self::edge(code[1]),+ Self::edge(code[2]),+ Self::edge(code[3]),+ ]+ }++ /// Unpacks this feature ID into the full `FeatureId` enum.+ ///+ /// This converts the compact packed representation back into the explicit enum form,+ /// allowing you to pattern match on the feature type.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::{FeatureId, PackedFeatureId};+ ///+ /// let packed = PackedFeatureId::vertex(42);+ /// let unpacked = packed.unpack();+ ///+ /// match unpacked {+ /// FeatureId::Vertex(id) => assert_eq!(id, 42),+ /// _ => panic!("Expected a vertex!"),+ /// }+ /// # }+ /// ```+ ///+ /// Round-trip conversion:+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::{FeatureId, PackedFeatureId};+ ///+ /// let original = FeatureId::Face(100);+ /// let packed: PackedFeatureId = original.into();+ /// let unpacked = packed.unpack();+ ///+ /// assert_eq!(original, unpacked);+ /// # }+ /// ```+ pub fn unpack(self) -> FeatureId {+ let header = self.0 & Self::HEADER_MASK;+ let code = self.0 & Self::CODE_MASK;+ match header {+ Self::HEADER_VERTEX => FeatureId::Vertex(code),+ #[cfg(feature = "dim3")]+ Self::HEADER_EDGE => FeatureId::Edge(code),+ Self::HEADER_FACE => FeatureId::Face(code),+ _ => FeatureId::Unknown,+ }+ }++ /// Checks if this feature ID identifies a face.+ ///+ /// This is a very fast operation (single bitwise AND and comparison).+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::PackedFeatureId;+ ///+ /// let face = PackedFeatureId::face(5);+ /// let vertex = PackedFeatureId::vertex(5);+ ///+ /// assert!(face.is_face());+ /// assert!(!vertex.is_face());+ /// # }+ /// ```+ pub fn is_face(self) -> bool {+ self.0 & Self::HEADER_MASK == Self::HEADER_FACE+ }++ /// Checks if this feature ID identifies a vertex.+ ///+ /// This is a very fast operation (single bitwise AND and comparison).+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::PackedFeatureId;+ ///+ /// let vertex = PackedFeatureId::vertex(10);+ /// let face = PackedFeatureId::face(10);+ ///+ /// assert!(vertex.is_vertex());+ /// assert!(!face.is_vertex());+ /// # }+ /// ```+ pub fn is_vertex(self) -> bool {+ self.0 & Self::HEADER_MASK == Self::HEADER_VERTEX+ }++ /// Checks if this feature ID identifies an edge.+ ///+ /// Available only in 3D mode (`dim3` feature).+ ///+ /// This is a very fast operation (single bitwise AND and comparison).+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::PackedFeatureId;+ ///+ /// let edge = PackedFeatureId::edge(7);+ /// let vertex = PackedFeatureId::vertex(7);+ ///+ /// assert!(edge.is_edge());+ /// assert!(!vertex.is_edge());+ /// # }+ /// ```+ #[cfg(feature = "dim3")]+ pub fn is_edge(self) -> bool {+ self.0 & Self::HEADER_MASK == Self::HEADER_EDGE+ }++ /// Checks if this feature ID is unknown.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::PackedFeatureId;+ ///+ /// let unknown = PackedFeatureId::UNKNOWN;+ /// let vertex = PackedFeatureId::vertex(0);+ ///+ /// assert!(unknown.is_unknown());+ /// assert!(!vertex.is_unknown());+ /// # }+ /// ```+ pub fn is_unknown(self) -> bool {+ self == Self::UNKNOWN+ }+}++impl From<FeatureId> for PackedFeatureId {+ /// Converts a `FeatureId` into its packed representation.+ ///+ /// This is a lossless conversion that encodes the feature type and index+ /// into a single `u32` value.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::{FeatureId, PackedFeatureId};+ ///+ /// // Explicit conversion+ /// let feature = FeatureId::Vertex(123);+ /// let packed = PackedFeatureId::from(feature);+ /// assert!(packed.is_vertex());+ ///+ /// // Using Into trait+ /// let feature = FeatureId::Face(456);+ /// let packed: PackedFeatureId = feature.into();+ /// assert!(packed.is_face());+ ///+ /// // Round-trip conversion preserves the value+ /// let original = FeatureId::Vertex(789);+ /// let packed: PackedFeatureId = original.into();+ /// assert_eq!(packed.unpack(), original);+ /// # }+ /// ```+ fn from(value: FeatureId) -> Self {+ match value {+ FeatureId::Face(fid) => Self::face(fid),+ #[cfg(feature = "dim3")]+ FeatureId::Edge(fid) => Self::edge(fid),+ FeatureId::Vertex(fid) => Self::vertex(fid),+ FeatureId::Unknown => Self::UNKNOWN,+ }+ }+}diff --git a/renderer/third_party/parry3d/src/shape/half_space.rs b/renderer/third_party/parry3d/src/shape/half_space.rsnew file mode 100644index 0000000..daf746f--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/half_space.rs@@ -0,0 +1,323 @@+//! Support mapping based HalfSpace shape.+use crate::math::Vector;++/// A half-space delimited by an infinite plane.+///+/// # What is a HalfSpace?+///+/// A half-space represents an infinite region of space on one side of a plane. It divides+/// space into two regions:+/// - The "inside" region (where the normal vector points away from)+/// - The "outside" region (where the normal vector points toward)+///+/// The plane itself passes through the origin of the shape's coordinate system and is defined+/// by its outward normal vector. All points in the direction opposite to the normal are+/// considered "inside" the half-space.+///+/// # When to Use HalfSpace+///+/// Half-spaces are useful for representing:+/// - **Ground planes**: A flat, infinite floor for collision detection+/// - **Walls**: Infinite vertical barriers+/// - **Bounding regions**: Constraining objects to one side of a plane+/// - **Clipping planes**: Cutting off geometry in one direction+///+/// Because half-spaces are infinite, they are very efficient for collision detection and+/// don't require complex shape representations.+///+/// # Coordinate System+///+/// The plane always passes through the origin `(0, 0)` in 2D or `(0, 0, 0)` in 3D of the+/// half-space's local coordinate system. To position the plane elsewhere in your world,+/// use a [`Pose`](crate::math::Pose) transformation when performing queries.+///+/// # Examples+///+/// ## Creating a Ground Plane (3D)+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::HalfSpace;+/// use parry3d::math::{Vector};+///+/// // Create a horizontal ground plane with normal pointing up (positive Y-axis)+/// let ground = HalfSpace::new((Vector::Y.normalize()));+///+/// // The ground plane is at Y = 0 in local coordinates+/// // Everything below (negative Y) is "inside" the half-space+/// # }+/// ```+///+/// ## Vertical Wall (2D)+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::shape::HalfSpace;+/// use parry2d::math::Vector;+///+/// // Create a vertical wall with normal pointing right (positive X-axis)+/// let wall = HalfSpace::new(Vector::X.normalize());+///+/// // The wall is at X = 0 in local coordinates+/// // Everything to the left (negative X) is "inside" the half-space+/// # }+/// ```+///+/// ## Collision Detection with a Ball (3D)+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{HalfSpace, Ball};+/// use parry3d::query;+/// use parry3d::math::{Pose, Vector};+///+/// // Create a ground plane at Y = 0, normal pointing up+/// let ground = HalfSpace::new((Vector::Y.normalize()));+/// let ground_pos = Pose::identity();+///+/// // Create a ball with radius 1.0 at position (0, 0.5, 0)+/// // The ball is resting on the ground, just touching it+/// let ball = Ball::new(1.0);+/// let ball_pos = Pose::translation(0.0, 0.5, 0.0);+///+/// // Check if they're in contact (with a small prediction distance)+/// let contact = query::contact(+/// &ground_pos,+/// &ground,+/// &ball_pos,+/// &ball,+/// 0.1+/// );+///+/// assert!(contact.unwrap().is_some());+/// # }+/// ```+///+/// ## Positioned Ground Plane (3D)+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::HalfSpace;+/// use parry3d::query::{PointQuery};+/// use parry3d::math::{Pose, Vector};+///+/// // Create a ground plane with normal pointing up+/// let ground = HalfSpace::new((Vector::Y.normalize()));+///+/// // Position the plane at Y = 5.0 using an isometry+/// let ground_pos = Pose::translation(0.0, 5.0, 0.0);+///+/// // Check if a point is below the ground (inside the half-space)+/// let point = Vector::new(0.0, 3.0, 0.0); // Vector at Y = 3.0 (below the plane)+///+/// // Project the point onto the ground plane+/// let proj = ground.project_point(&ground_pos, point, true);+///+/// // The point is below the ground (inside the half-space)+/// assert!(proj.is_inside);+/// # }+/// ```+///+/// ## Tilted Plane (3D)+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::HalfSpace;+/// use parry3d::math::{Vector};+///+/// // Create a plane tilted at 45 degrees+/// // Normal points up and to the right+/// let normal = Vector::new(1.0, 1.0, 0.0);+/// let tilted_plane = HalfSpace::new((normal).normalize());+///+/// // This plane passes through the origin and divides space diagonally+/// # }+/// ```+#[derive(PartialEq, Debug, Clone, Copy)]+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+pub struct HalfSpace {+ /// The halfspace planar boundary's outward normal.+ ///+ /// This unit vector points in the direction considered "outside" the half-space.+ /// All points in the direction opposite to this normal (when measured from the+ /// plane at the origin) are considered "inside" the half-space.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::HalfSpace;+ /// use parry3d::math::{Vector};+ ///+ /// let ground = HalfSpace::new(Vector::Y.normalize());+ ///+ /// // The normal points up (positive Y direction)+ /// assert_eq!(ground.normal, Vector::Y);+ /// # }+ /// ```+ pub normal: Vector,+}++impl HalfSpace {+ /// Builds a new half-space from its outward normal vector.+ ///+ /// The plane defining the half-space passes through the origin of the local coordinate+ /// system and is perpendicular to the given normal vector. The normal points toward+ /// the "outside" region, while the opposite direction is considered "inside."+ ///+ /// # Parameters+ ///+ /// * `normal` - A unit vector defining the plane's outward normal direction. This must+ /// be a normalized vector (use `.normalize()` on any vector to create one).+ ///+ /// # Examples+ ///+ /// ## Creating a Horizontal Ground Plane (3D)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::HalfSpace;+ /// use parry3d::math::{Vector};+ ///+ /// // Ground plane with normal pointing up+ /// let ground = HalfSpace::new((Vector::Y.normalize()));+ /// # }+ /// ```+ ///+ /// ## Creating a Vertical Wall (2D)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::HalfSpace;+ /// use parry2d::math::Vector;+ ///+ /// // Wall with normal pointing to the right+ /// let wall = HalfSpace::new(Vector::X.normalize());+ /// # }+ /// ```+ ///+ /// ## Custom Normal Direction (3D)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::HalfSpace;+ /// use parry3d::math::{Vector};+ ///+ /// // Plane with normal at 45-degree angle+ /// let custom_normal = Vector::new(1.0, 1.0, 0.0);+ /// let plane = HalfSpace::new((custom_normal).normalize());+ ///+ /// // Verify the normal is normalized+ /// assert!((plane.normal.length() - 1.0).abs() < 1e-5);+ /// # }+ /// ```+ #[inline]+ pub fn new(normal: Vector) -> HalfSpace {+ HalfSpace { normal }+ }++ /// Computes a scaled version of this half-space.+ ///+ /// Scaling a half-space applies non-uniform scaling to its normal vector. This is useful+ /// when transforming shapes in a scaled coordinate system. The resulting normal is+ /// re-normalized to maintain the half-space's validity.+ ///+ /// # Parameters+ ///+ /// * `scale` - A vector containing the scaling factors for each axis. For example,+ /// `Vector::new(2.0, 1.0, 1.0)` doubles the X-axis scaling.+ ///+ /// # Returns+ ///+ /// * `Some(HalfSpace)` - The scaled half-space with the transformed normal+ /// * `None` - If the scaled normal becomes zero (degenerate case), meaning the+ /// half-space cannot be represented after scaling+ ///+ /// # When This Returns None+ ///+ /// The method returns `None` when any component of the normal becomes zero after+ /// scaling AND that component was the only non-zero component. For example:+ /// - A horizontal plane (normal = `[0, 1, 0]`) scaled by `[1, 0, 1]` → `None`+ /// - A diagonal plane (normal = `[0.7, 0.7, 0]`) scaled by `[1, 0, 1]` → `Some(...)`+ ///+ /// # Examples+ ///+ /// ## Uniform Scaling (3D)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::HalfSpace;+ /// use parry3d::math::{Vector};+ ///+ /// let ground = HalfSpace::new(Vector::Y.normalize());+ ///+ /// // Uniform scaling doesn't change the normal direction+ /// let scaled = ground.scaled(Vector::splat(2.0)).unwrap();+ /// assert_eq!(scaled.normal, Vector::Y);+ /// # }+ /// ```+ ///+ /// ## Non-Uniform Scaling (3D)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::HalfSpace;+ /// use parry3d::math::{Vector};+ ///+ /// // Diagonal plane+ /// let plane = HalfSpace::new(+ /// (Vector::new(1.0, 1.0, 0.0).normalize())+ /// );+ ///+ /// // Scale X-axis by 2.0, Y-axis stays 1.0+ /// let scaled = plane.scaled(Vector::new(2.0, 1.0, 1.0)).unwrap();+ ///+ /// // The normal changes direction due to non-uniform scaling+ /// // It's no longer at 45 degrees+ /// assert!(scaled.normal.x != scaled.normal.y);+ /// # }+ /// ```+ ///+ /// ## Degenerate Case (3D)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::HalfSpace;+ /// use parry3d::math::{Vector};+ ///+ /// // Horizontal ground plane+ /// let ground = HalfSpace::new((Vector::Y.normalize()));+ ///+ /// // Scaling Y to zero makes the normal degenerate+ /// let scaled = ground.scaled(Vector::new(1.0, 0.0, 1.0));+ /// assert!(scaled.is_none()); // Returns None because normal becomes zero+ /// # }+ /// ```+ ///+ /// ## Practical Use Case (2D)+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::HalfSpace;+ /// use parry2d::math::Vector;+ ///+ /// // Create a wall in a 2D platformer+ /// let wall = HalfSpace::new(Vector::X.normalize());+ ///+ /// // Apply level scaling (e.g., for pixel-perfect rendering)+ /// let pixel_scale = Vector::new(16.0, 16.0);+ /// if let Some(scaled_wall) = wall.scaled(pixel_scale) {+ /// // Use the scaled wall for collision detection+ /// }+ /// # }+ /// ```+ pub fn scaled(self, scale: Vector) -> Option<Self> {+ let scaled = self.normal * scale;+ scaled.try_normalize().map(|normal| Self { normal })+ }+}diff --git a/renderer/third_party/parry3d/src/shape/heightfield2.rs b/renderer/third_party/parry3d/src/shape/heightfield2.rsnew file mode 100644index 0000000..7e13627--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/heightfield2.rs@@ -0,0 +1,256 @@+#[cfg(not(feature = "std"))]+use crate::math::ComplexField;+#[cfg(feature = "alloc")]+use alloc::{vec, vec::Vec};+use core::ops::Range;++use crate::math::Vector2;++use crate::bounding_volume::Aabb;+use crate::math::{Real, Vector};++use crate::shape::Segment;++/// Indicates if a cell of a heightfield is removed or not. Set this to `false` for+/// a removed cell.+pub type HeightFieldCellStatus = bool;++#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+// TODO: Archive isn’t implemented for VecStorage yet.+// #[cfg_attr(+// feature = "rkyv",+// derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize),+// archive(check_bytes)+// )]+#[derive(Debug, Clone)]+#[repr(C)]+/// A 2D heightfield with a generic storage buffer for its heights.+pub struct HeightField {+ heights: Vec<Real>,+ status: Vec<HeightFieldCellStatus>,++ scale: Vector,+ aabb: Aabb,+}++#[cfg(feature = "alloc")]+impl HeightField {+ /// Creates a new 2D heightfield with the given heights and scale factor.+ pub fn new(heights: Vec<Real>, scale: Vector) -> Self {+ assert!(+ heights.len() > 1,+ "A heightfield heights must have at least 2 elements."+ );++ let max = heights.iter().fold(Real::MIN, |a, b| a.max(*b));+ let min = heights.iter().fold(Real::MAX, |a, b| a.min(*b));+ let hscale = scale * 0.5;+ let aabb = Aabb::new(+ Vector2::new(-hscale.x, min * scale.y),+ Vector2::new(hscale.x, max * scale.y),+ );+ let num_segments = heights.len() - 1;++ HeightField {+ heights,+ status: vec![true; num_segments],+ scale,+ aabb,+ }+ }+}++impl HeightField {+ /// The number of cells of this heightfield.+ pub fn num_cells(&self) -> usize {+ self.heights.len() - 1+ }++ /// The height at each cell endpoint.+ pub fn heights(&self) -> &Vec<Real> {+ &self.heights+ }++ /// The scale factor applied to this heightfield.+ pub fn scale(&self) -> Vector {+ self.scale+ }++ /// Sets the scale factor applied to this heightfield.+ pub fn set_scale(&mut self, new_scale: Vector) {+ let ratio = new_scale / self.scale;+ self.aabb.mins *= ratio;+ self.aabb.maxs *= ratio;+ self.scale = new_scale;+ }++ /// Returns a scaled version of this heightfield.+ pub fn scaled(mut self, scale: Vector) -> Self {+ self.set_scale(self.scale * scale);+ self+ }++ /// The [`Aabb`] of this heightfield.+ pub fn root_aabb(&self) -> &Aabb {+ &self.aabb+ }++ /// The width of a single cell of this heightfield.+ pub fn cell_width(&self) -> Real {+ self.unit_cell_width() * self.scale.x+ }++ /// The width of a single cell of this heightfield, without taking the scale factor into account.+ pub fn unit_cell_width(&self) -> Real {+ 1.0 / (self.heights.len() as Real - 1.0)+ }++ /// The left-most x-coordinate of this heightfield.+ pub fn start_x(&self) -> Real {+ self.scale.x * -0.5+ }++ fn quantize_floor_unclamped(&self, val: Real, seg_length: Real) -> isize {+ ((val + 0.5) / seg_length).floor() as isize+ }++ fn quantize_ceil_unclamped(&self, val: Real, seg_length: Real) -> isize {+ ((val + 0.5) / seg_length).ceil() as isize+ }++ fn quantize_floor(&self, val: Real, seg_length: Real) -> usize {+ ((val + 0.5) / seg_length)+ .floor()+ .clamp(0.0, (self.num_cells() - 1) as Real) as usize+ }++ fn quantize_ceil(&self, val: Real, seg_length: Real) -> usize {+ ((val + 0.5) / seg_length)+ .ceil()+ .clamp(0.0, self.num_cells() as Real) as usize+ }++ /// Index of the cell a point is on after vertical projection.+ pub fn cell_at_point(&self, pt: Vector2) -> Option<usize> {+ let scaled_pt = pt / self.scale;+ let seg_length = self.unit_cell_width();++ if scaled_pt.x < -0.5 || scaled_pt.x > 0.5 {+ // Outside of the heightfield bounds.+ None+ } else {+ Some(self.quantize_floor(scaled_pt.x, seg_length))+ }+ }++ /// Height of the heightfield at the given point after vertical projection on the heightfield surface.+ pub fn height_at_point(&self, pt: Vector2) -> Option<Real> {+ let cell = self.cell_at_point(pt)?;+ let seg = self.segment_at(cell)?;+ let inter = crate::query::details::closest_points_line_line_parameters(+ seg.a,+ seg.scaled_direction(),+ pt,+ Vector::Y,+ );+ Some(seg.a.y + inter.1)+ }++ /// Iterator through all the segments of this heightfield.+ pub fn segments(&self) -> impl Iterator<Item = Segment> + '_ {+ // TODO: this is not very efficient since this will+ // recompute shared points twice.+ (0..self.num_cells()).filter_map(move |i| self.segment_at(i))+ }++ /// The i-th segment of the heightfield if it has not been removed.+ pub fn segment_at(&self, i: usize) -> Option<Segment> {+ if i >= self.num_cells() || self.is_segment_removed(i) {+ return None;+ }++ let seg_length = 1.0 / (self.heights.len() as Real - 1.0);++ let x0 = -0.5 + seg_length * (i as Real);+ let x1 = x0 + seg_length;++ let y0 = self.heights[i];+ let y1 = self.heights[i + 1];++ let mut p0 = Vector2::new(x0, y0);+ let mut p1 = Vector2::new(x1, y1);++ // Apply scales:+ p0 *= self.scale;+ p1 *= self.scale;++ Some(Segment::new(p0, p1))+ }++ /// Mark the i-th segment of this heightfield as removed or not.+ pub fn set_segment_removed(&mut self, i: usize, removed: bool) {+ self.status[i] = !removed+ }++ /// Checks if the i-th segment has been removed.+ pub fn is_segment_removed(&self, i: usize) -> bool {+ !self.status[i]+ }++ /// The range of segment ids that may intersect the given local Aabb.+ pub fn unclamped_elements_range_in_local_aabb(&self, aabb: &Aabb) -> Range<isize> {+ let ref_mins = aabb.mins / self.scale;+ let ref_maxs = aabb.maxs / self.scale;+ let seg_length = 1.0 / (self.heights.len() as Real - 1.0);++ let min_x = self.quantize_floor_unclamped(ref_mins.x, seg_length);+ let max_x = self.quantize_ceil_unclamped(ref_maxs.x, seg_length);+ min_x..max_x+ }++ /// Applies `f` to each segment of this heightfield that intersects the given `aabb`.+ pub fn map_elements_in_local_aabb(&self, aabb: &Aabb, f: &mut impl FnMut(u32, &Segment)) {+ let ref_mins = aabb.mins / self.scale;+ let ref_maxs = aabb.maxs / self.scale;+ let seg_length = 1.0 / (self.heights.len() as Real - 1.0);++ if ref_maxs.x < -0.5 || ref_mins.x > 0.5 {+ // Outside of the heightfield bounds.+ return;+ }++ let min_x = self.quantize_floor(ref_mins.x, seg_length);+ let max_x = self.quantize_ceil(ref_maxs.x, seg_length);++ // TODO: find a way to avoid recomputing the same vertices+ // multiple times.+ for i in min_x..max_x {+ if self.is_segment_removed(i) {+ continue;+ }++ let x0 = -0.5 + seg_length * (i as Real);+ let x1 = x0 + seg_length;++ let y0 = self.heights[i];+ let y1 = self.heights[i + 1];++ if (y0 > ref_maxs.y && y1 > ref_maxs.y) || (y0 < ref_mins.y && y1 < ref_mins.y) {+ continue;+ }++ let mut p0 = Vector2::new(x0, y0);+ let mut p1 = Vector2::new(x1, y1);++ // Apply scales:+ p0 *= self.scale;+ p1 *= self.scale;++ // Build the segment.+ let seg = Segment::new(p0, p1);++ // Call the callback.+ f(i as u32, &seg);+ }+ }+}diff --git a/renderer/third_party/parry3d/src/shape/heightfield3.rs b/renderer/third_party/parry3d/src/shape/heightfield3.rsnew file mode 100644index 0000000..8b19a5d--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/heightfield3.rs@@ -0,0 +1,940 @@+use core::ops::Range;+// TODO: Replace nalgebra Array2 with a custom Vec-based storage for heightfield data+#[cfg(feature = "alloc")]+use crate::utils::Array2;++use crate::bounding_volume::Aabb;+use crate::math::{Real, Vector};+use crate::shape::{FeatureId, SubShapeId, Triangle, TrianglePseudoNormals};++#[cfg(not(feature = "std"))]+use crate::math::ComplexField;++#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]+/// The status of the cell of a heightfield.+pub struct HeightFieldCellStatus(u8);++bitflags::bitflags! {+ impl HeightFieldCellStatus: u8 {+ /// If this bit is set, the concerned heightfield cell is subdivided using a Z pattern.+ const ZIGZAG_SUBDIVISION = 0b00000001;+ /// If this bit is set, the leftmost triangle of the concerned heightfield cell is removed.+ const LEFT_TRIANGLE_REMOVED = 0b00000010;+ /// If this bit is set, the rightmost triangle of the concerned heightfield cell is removed.+ const RIGHT_TRIANGLE_REMOVED = 0b00000100;+ /// If this bit is set, both triangles of the concerned heightfield cell are removed.+ const CELL_REMOVED = Self::LEFT_TRIANGLE_REMOVED.bits() | Self::RIGHT_TRIANGLE_REMOVED.bits();+ }+}++#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]+/// Flags controlling the behavior of some operations involving heightfields.+pub struct HeightFieldFlags(u8);++bitflags::bitflags! {+ impl HeightFieldFlags: u8 {+ /// If set, a special treatment will be applied to contact manifold calculation to eliminate+ /// or fix contacts normals that could lead to incorrect bumps in physics simulation (especially+ /// on flat surfaces).+ ///+ /// This is achieved by taking into account adjacent triangle normals when computing contact+ /// points for a given triangle.+ const FIX_INTERNAL_EDGES = 1 << 0;+ }+}++#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+// TODO: Archive isn’t implemented for VecStorage yet.+// #[cfg_attr(+// feature = "rkyv",+// derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize),+// archive(check_bytes)+// )]+#[derive(Debug, Clone)]+#[repr(C)]+/// A 3D heightfield.+pub struct HeightField {+ heights: Array2<Real>,+ status: Array2<HeightFieldCellStatus>,++ scale: Vector,+ aabb: Aabb,+ num_triangles: usize,+ flags: HeightFieldFlags,+}++#[cfg(feature = "alloc")]+impl HeightField {+ /// Initializes a new heightfield with the given heights, scaling factor, and flags.+ ///+ /// The heights are specified in such a way that the row index `i` of the array advances+ /// grid coordinates along the `z` axis, and the column index `j` of the array advances+ /// grid coordinates along the `x` axis.+ pub fn new(heights_zx: Array2<Real>, scale: Vector) -> Self {+ Self::with_flags(heights_zx, scale, HeightFieldFlags::empty())+ }++ /// Initializes a new heightfield with the given heights and a scaling factor.+ pub fn with_flags(heights_zx: Array2<Real>, scale: Vector, flags: HeightFieldFlags) -> Self {+ assert!(+ heights_zx.nrows() > 1 && heights_zx.ncols() > 1,+ "A heightfield heights must have at least 2 rows and columns."+ );+ let max = heights_zx.max();+ let min = heights_zx.min();+ let hscale = scale * 0.5;+ let aabb = Aabb::new(+ Vector::new(-hscale.x, min * scale.y, -hscale.z),+ Vector::new(hscale.x, max * scale.y, hscale.z),+ );+ let num_triangles = (heights_zx.nrows() - 1) * (heights_zx.ncols() - 1) * 2;+ let status = Array2::repeat(+ heights_zx.nrows() - 1,+ heights_zx.ncols() - 1,+ HeightFieldCellStatus::default(),+ );++ HeightField {+ heights: heights_zx,+ scale,+ aabb,+ num_triangles,+ status,+ flags,+ }+ }+}++impl HeightField {+ /// The number of rows of this heightfield.+ pub fn nrows(&self) -> usize {+ self.heights.nrows() - 1+ }++ /// The number of columns of this heightfield.+ pub fn ncols(&self) -> usize {+ self.heights.ncols() - 1+ }++ pub(crate) fn triangle_id(&self, i: usize, j: usize, left: bool) -> u32 {+ let tid = j * (self.heights.nrows() - 1) + i;+ if left {+ tid as u32+ } else {+ (tid + self.num_triangles / 2) as u32+ }+ }++ fn split_triangle_id(&self, id: u32) -> (usize, usize, bool) {+ let left = id < self.num_triangles as u32 / 2;+ let tri_id = if left {+ id as usize+ } else {+ id as usize - self.num_triangles / 2+ };+ let j = tri_id / (self.heights.nrows() - 1);+ let i = tri_id - j * (self.heights.nrows() - 1);+ (i, j, left)+ }++ fn face_id(&self, i: usize, j: usize, left: bool, front: bool) -> u32 {+ let tid = self.triangle_id(i, j, left);+ if front {+ tid+ } else {+ tid + self.num_triangles as u32+ }+ }++ fn quantize_floor_unclamped(&self, val: Real, cell_size: Real) -> isize {+ ((val + 0.5) / cell_size).floor() as isize+ }++ fn quantize_ceil_unclamped(&self, val: Real, cell_size: Real) -> isize {+ ((val + 0.5) / cell_size).ceil() as isize+ }++ fn quantize_floor(&self, val: Real, cell_size: Real, num_cells: usize) -> usize {+ ((val + 0.5) / cell_size)+ .floor()+ .clamp(0.0, (num_cells - 1) as Real) as usize+ }++ fn quantize_ceil(&self, val: Real, cell_size: Real, num_cells: usize) -> usize {+ ((val + 0.5) / cell_size)+ .ceil()+ .clamp(0.0, num_cells as Real) as usize+ }++ /// The pair of index of the cell containing the vertical projection of the given point.+ pub fn closest_cell_at_point(&self, pt: Vector) -> (usize, usize) {+ let scaled_pt = pt / self.scale;+ let cell_width = self.unit_cell_width();+ let cell_height = self.unit_cell_height();+ let ncells_x = self.ncols();+ let ncells_z = self.nrows();++ let j = self.quantize_floor(scaled_pt.x, cell_width, ncells_x);+ let i = self.quantize_floor(scaled_pt.z, cell_height, ncells_z);+ (i, j)+ }++ /// The pair of index of the cell containing the vertical projection of the given point.+ pub fn cell_at_point(&self, pt: Vector) -> Option<(usize, usize)> {+ let scaled_pt = pt / self.scale;+ let cell_width = self.unit_cell_width();+ let cell_height = self.unit_cell_height();+ let ncells_x = self.ncols();+ let ncells_z = self.nrows();++ if scaled_pt.x < -0.5 || scaled_pt.x > 0.5 || scaled_pt.z < -0.5 || scaled_pt.z > 0.5 {+ // Outside of the heightfield bounds.+ None+ } else {+ let j = self.quantize_floor(scaled_pt.x, cell_width, ncells_x);+ let i = self.quantize_floor(scaled_pt.z, cell_height, ncells_z);+ Some((i, j))+ }+ }++ /// The pair of index of the cell containing the vertical projection of the given point.+ pub fn unclamped_cell_at_point(&self, pt: Vector) -> (isize, isize) {+ let scaled_pt = pt / self.scale;+ let cell_width = self.unit_cell_width();+ let cell_height = self.unit_cell_height();++ let j = self.quantize_floor_unclamped(scaled_pt.x, cell_width);+ let i = self.quantize_floor_unclamped(scaled_pt.z, cell_height);+ (i, j)+ }++ /// The smallest x coordinate of the `j`-th column of this heightfield.+ pub fn x_at(&self, j: usize) -> Real {+ (-0.5 + self.unit_cell_width() * (j as Real)) * self.scale.x+ }++ /// The smallest z coordinate of the start of the `i`-th row of this heightfield.+ pub fn z_at(&self, i: usize) -> Real {+ (-0.5 + self.unit_cell_height() * (i as Real)) * self.scale.z+ }++ /// The smallest x coordinate of the `j`-th column of this heightfield.+ pub fn signed_x_at(&self, j: isize) -> Real {+ (-0.5 + self.unit_cell_width() * (j as Real)) * self.scale.x+ }++ /// The smallest z coordinate of the start of the `i`-th row of this heightfield.+ pub fn signed_z_at(&self, i: isize) -> Real {+ (-0.5 + self.unit_cell_height() * (i as Real)) * self.scale.z+ }++ /// An iterator through all the triangles of this heightfield.+ pub fn triangles(&self) -> impl Iterator<Item = Triangle> + '_ {+ HeightFieldTriangles {+ heightfield: self,+ curr: (0, 0),+ tris: self.triangles_at(0, 0),+ }+ }++ /// An iterator through all the triangles around the given point, after vertical projection on the heightfield.+ pub fn triangles_around_point(&self, point: Vector) -> HeightFieldRadialTriangles<'_> {+ let center = self.closest_cell_at_point(point);+ HeightFieldRadialTriangles {+ heightfield: self,+ center,+ curr_radius: 0,+ curr_element: 0,+ tris: self.triangles_at(center.0, center.1),+ }+ }++ /// Gets the vertices of the triangle identified by `id`.+ pub fn triangle_at_id(&self, id: u32) -> Option<Triangle> {+ let (i, j, left) = self.split_triangle_id(id);+ if left {+ self.triangles_at(i, j).0+ } else {+ self.triangles_at(i, j).1+ }+ }++ /// Gets the vertex indices of the triangle identified by `id`.+ pub fn triangle_vids_at_id(&self, id: u32) -> Option<[u32; 3]> {+ let (i, j, left) = self.split_triangle_id(id);+ if left {+ self.triangles_vids_at(i, j).0+ } else {+ self.triangles_vids_at(i, j).1+ }+ }++ /// Gets the indices of the vertices of the (up to) two triangles for the cell (i, j).+ pub fn triangles_vids_at(&self, i: usize, j: usize) -> (Option<[u32; 3]>, Option<[u32; 3]>) {+ if i >= self.heights.nrows() - 1 || j >= self.heights.ncols() - 1 {+ return (None, None);+ }++ let status = self.status[(i, j)];++ if status.contains(+ HeightFieldCellStatus::LEFT_TRIANGLE_REMOVED+ | HeightFieldCellStatus::RIGHT_TRIANGLE_REMOVED,+ ) {+ return (None, None);+ }++ let p00 = (i + j * self.heights.nrows()) as u32;+ let p10 = ((i + 1) + j * self.heights.nrows()) as u32;+ let p01 = (i + (j + 1) * self.heights.nrows()) as u32;+ let p11 = ((i + 1) + (j + 1) * self.heights.nrows()) as u32;++ if status.contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {+ let tri1 = if status.contains(HeightFieldCellStatus::LEFT_TRIANGLE_REMOVED) {+ None+ } else {+ Some([p00, p10, p11])+ };++ let tri2 = if status.contains(HeightFieldCellStatus::RIGHT_TRIANGLE_REMOVED) {+ None+ } else {+ Some([p00, p11, p01])+ };++ (tri1, tri2)+ } else {+ let tri1 = if status.contains(HeightFieldCellStatus::LEFT_TRIANGLE_REMOVED) {+ None+ } else {+ Some([p00, p10, p01])+ };++ let tri2 = if status.contains(HeightFieldCellStatus::RIGHT_TRIANGLE_REMOVED) {+ None+ } else {+ Some([p10, p11, p01])+ };++ (tri1, tri2)+ }+ }++ /// The two triangles at the cell (i, j) of this heightfield.+ ///+ /// Returns `None` fore triangles that have been removed because of their user-defined status+ /// flags (described by the `HeightFieldCellStatus` bitfield).+ pub fn triangles_at(&self, i: usize, j: usize) -> (Option<Triangle>, Option<Triangle>) {+ if i >= self.heights.nrows() - 1 || j >= self.heights.ncols() - 1 {+ return (None, None);+ }++ let status = self.status[(i, j)];++ if status.contains(+ HeightFieldCellStatus::LEFT_TRIANGLE_REMOVED+ | HeightFieldCellStatus::RIGHT_TRIANGLE_REMOVED,+ ) {+ return (None, None);+ }++ let cell_width = self.unit_cell_width();+ let cell_height = self.unit_cell_height();++ let z0 = -0.5 + cell_height * (i as Real);+ let z1 = -0.5 + cell_height * ((i + 1) as Real);++ let x0 = -0.5 + cell_width * (j as Real);+ let x1 = -0.5 + cell_width * ((j + 1) as Real);++ let y00 = self.heights[(i, j)];+ let y10 = self.heights[(i + 1, j)];+ let y01 = self.heights[(i, j + 1)];+ let y11 = self.heights[(i + 1, j + 1)];++ let mut p00 = Vector::new(x0, y00, z0);+ let mut p10 = Vector::new(x0, y10, z1);+ let mut p01 = Vector::new(x1, y01, z0);+ let mut p11 = Vector::new(x1, y11, z1);++ // Apply scales:+ p00 *= self.scale;+ p10 *= self.scale;+ p01 *= self.scale;+ p11 *= self.scale;++ if status.contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {+ let tri1 = if status.contains(HeightFieldCellStatus::LEFT_TRIANGLE_REMOVED) {+ None+ } else {+ Some(Triangle::new(p00, p10, p11))+ };++ let tri2 = if status.contains(HeightFieldCellStatus::RIGHT_TRIANGLE_REMOVED) {+ None+ } else {+ Some(Triangle::new(p00, p11, p01))+ };++ (tri1, tri2)+ } else {+ let tri1 = if status.contains(HeightFieldCellStatus::LEFT_TRIANGLE_REMOVED) {+ None+ } else {+ Some(Triangle::new(p00, p10, p01))+ };++ let tri2 = if status.contains(HeightFieldCellStatus::RIGHT_TRIANGLE_REMOVED) {+ None+ } else {+ Some(Triangle::new(p10, p11, p01))+ };++ (tri1, tri2)+ }+ }++ /// Computes the pseudo-normals of the triangle identified by the given id.+ ///+ /// Returns `None` if the heightfield’s [`HeightFieldFlags::FIX_INTERNAL_EDGES`] isn’t set, or+ /// if the triangle doesn’t exist due to it being removed by its status flag+ /// (`HeightFieldCellStatus::LEFT_TRIANGLE_REMOVED` or+ /// `HeightFieldCellStatus::RIGHT_TRIANGLE_REMOVED`).+ pub fn triangle_normal_constraints(&self, id: u32) -> Option<TrianglePseudoNormals> {+ if self.flags.contains(HeightFieldFlags::FIX_INTERNAL_EDGES) {+ let (i, j, left) = self.split_triangle_id(id);+ let status = self.status[(i, j)];++ let (tri_left, tri_right) = self.triangles_at(i, j);+ let tri_normal = if left {+ tri_left?.normal()?+ } else {+ tri_right?.normal()?+ };++ // TODO: we only compute bivectors where v is a specific direction+ // (+/-X, +/-Z, or a combination of both). So this bivector+ // calculation could be simplified/optimized quite a bit.+ // Computes the pseudo-normal of an edge where the adjacent triangle is missing.+ let bivector = |v: Vector| tri_normal.cross(v).cross(tri_normal).normalize();+ // Pseudo-normal computed from an adjacent triangle’s normal and the current triangle’s normal.+ let adj_pseudo_normal =+ |adj: Option<Triangle>| adj.map(|adj| adj.normal().unwrap_or(tri_normal));++ let diag_dir = if status.contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {+ Vector::new(-1.0, 0.0, 1.0)+ } else {+ Vector::new(1.0, 0.0, 1.0)+ };++ let (left_pseudo_normal, right_pseudo_normal) = if left {+ let adj_left = adj_pseudo_normal(self.triangles_at(i.overflowing_sub(1).0, j).1)+ .unwrap_or_else(|| bivector(-Vector::Z));+ let adj_right = adj_pseudo_normal(tri_right).unwrap_or_else(|| bivector(diag_dir));+ (adj_left, adj_right)+ } else {+ let adj_left = adj_pseudo_normal(tri_left).unwrap_or_else(|| bivector(-diag_dir));+ let adj_right = adj_pseudo_normal(self.triangles_at(i + 1, j).0)+ .unwrap_or_else(|| bivector(Vector::Z));+ (adj_left, adj_right)+ };++ // The third neighbor depends on the combination of zigzag scheme+ // and right/left position.+ let top_or_bottom_pseudo_normal = if left+ != status.contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION)+ {+ // The neighbor is below.+ let ((bot_left, bot_right), bot_status) = if j > 0 {+ (self.triangles_at(i, j - 1), self.status[(i, j - 1)])+ } else {+ ((None, None), HeightFieldCellStatus::empty())+ };++ let bot_tri = if bot_status.contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {+ bot_left+ } else {+ bot_right+ };++ adj_pseudo_normal(bot_tri).unwrap_or_else(|| bivector(-Vector::X))+ } else {+ // The neighbor is above.+ let ((top_left, top_right), top_status) = if j < self.heights.ncols() - 2 {+ (self.triangles_at(i, j + 1), self.status[(i, j + 1)])+ } else {+ ((None, None), HeightFieldCellStatus::empty())+ };++ let top_tri = if top_status.contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {+ top_right+ } else {+ top_left+ };++ adj_pseudo_normal(top_tri).unwrap_or_else(|| bivector(Vector::X))+ };++ // NOTE: the normalization can only succeed due to the heightfield's definition.+ let pseudo_normal1 = (tri_normal + left_pseudo_normal).normalize();+ let pseudo_normal2 = (tri_normal + right_pseudo_normal).normalize();+ let pseudo_normal3 = (tri_normal + top_or_bottom_pseudo_normal).normalize();++ Some(TrianglePseudoNormals {+ face: tri_normal, // No need to re-normalize.+ // TODO: the normals are given in no particular order. So they are **not**+ // guaranteed to be provided in the same order as the triangle’s edge.+ edges: [pseudo_normal1, pseudo_normal2, pseudo_normal3],+ two_sided: false,+ })+ } else {+ None+ }+ }++ /// The number of cells of this heightfield along each dimension.+ pub fn num_cells_ij(&self) -> (usize, usize) {+ (self.nrows(), self.ncols())+ }++ /// The status of the `(i, j)`-th cell.+ pub fn cell_status(&self, i: usize, j: usize) -> HeightFieldCellStatus {+ self.status[(i, j)]+ }++ /// Set the status of the `(i, j)`-th cell.+ pub fn set_cell_status(&mut self, i: usize, j: usize, status: HeightFieldCellStatus) {+ self.status[(i, j)] = status;+ }++ /// The statuses of all the cells of this heightfield.+ pub fn cells_statuses(&self) -> &Array2<HeightFieldCellStatus> {+ &self.status+ }++ /// The mutable statuses of all the cells of this heightfield.+ pub fn cells_statuses_mut(&mut self) -> &mut Array2<HeightFieldCellStatus> {+ &mut self.status+ }++ /// The heightfield’s flags controlling internal-edges handling.+ pub fn flags(&self) -> HeightFieldFlags {+ self.flags+ }++ /// Sets the heightfield’s flags controlling internal-edges handling.+ pub fn set_flags(&mut self, flags: HeightFieldFlags) {+ self.flags = flags;+ }++ /// The heights of this heightfield.+ pub fn heights(&self) -> &Array2<Real> {+ &self.heights+ }++ /// The scale factor applied to this heightfield.+ pub fn scale(&self) -> Vector {+ self.scale+ }++ /// Sets the scale factor applied to this heightfield.+ pub fn set_scale(&mut self, new_scale: Vector) {+ let ratio = new_scale / self.scale;+ self.aabb.mins *= ratio;+ self.aabb.maxs *= ratio;+ self.scale = new_scale;+ }++ /// Returns a scaled version of this heightfield.+ pub fn scaled(mut self, scale: Vector) -> Self {+ self.set_scale(self.scale * scale);+ self+ }++ /// The width (extent along its local `x` axis) of each cell of this heightmap, including the scale factor.+ pub fn cell_width(&self) -> Real {+ self.unit_cell_width() * self.scale.x+ }++ /// The height (extent along its local `z` axis) of each cell of this heightmap, including the scale factor.+ pub fn cell_height(&self) -> Real {+ self.unit_cell_height() * self.scale.z+ }++ /// The width (extent along its local `x` axis) of each cell of this heightmap, excluding the scale factor.+ pub fn unit_cell_width(&self) -> Real {+ 1.0 / (self.heights.ncols() as Real - 1.0)+ }++ /// The height (extent along its local `z` axis) of each cell of this heightmap, excluding the scale factor.+ pub fn unit_cell_height(&self) -> Real {+ 1.0 / (self.heights.nrows() as Real - 1.0)+ }++ /// The [`Aabb`] of this heightmap.+ pub fn root_aabb(&self) -> &Aabb {+ &self.aabb+ }++ /// Converts a FeatureId of the triangle `triangle_id` into a FeatureId of the whole+ /// heightfield.+ pub fn convert_triangle_feature_id(+ &self,+ triangle_id: SubShapeId,+ fid: FeatureId,+ ) -> FeatureId {+ let (i, j, left) = self.split_triangle_id(triangle_id);++ match fid {+ FeatureId::Vertex(ivertex) => {+ let nrows = self.heights.nrows();+ let ij = i + j * nrows;++ if self.status[(i, j)].contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {+ if left {+ FeatureId::Vertex([ij, ij + 1, ij + 1 + nrows][ivertex as usize] as u32)+ } else {+ FeatureId::Vertex([ij, ij + 1 + nrows, ij + nrows][ivertex as usize] as u32)+ }+ } else if left {+ FeatureId::Vertex([ij, ij + 1, ij + nrows][ivertex as usize] as u32)+ } else {+ FeatureId::Vertex([ij + 1, ij + 1 + nrows, ij + nrows][ivertex as usize] as u32)+ }+ }+ FeatureId::Edge(iedge) => {+ let (nrows, ncols) = (self.heights.nrows(), self.heights.ncols());+ let vshift = 0; // First vertical line index.+ let hshift = (nrows - 1) * ncols; // First horizontal line index.+ let dshift = hshift + nrows * (ncols - 1); // First diagonal line index.+ let idiag = dshift + i + j * (nrows - 1);+ let itop = hshift + i + j * nrows;+ let ibottom = itop + 1;+ let ileft = vshift + i + j * (nrows - 1);+ let iright = ileft + nrows - 1;++ if self.status[(i, j)].contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {+ if left {+ // Triangle:+ //+ // |\+ // |_\+ //+ FeatureId::Edge([ileft, ibottom, idiag][iedge as usize] as u32)+ } else {+ // Triangle:+ // ___+ // \ |+ // \|+ //+ FeatureId::Edge([idiag, iright, itop][iedge as usize] as u32)+ }+ } else if left {+ // Triangle:+ // ___+ // | /+ // |/+ //+ FeatureId::Edge([ileft, idiag, itop][iedge as usize] as u32)+ } else {+ // Triangle:+ //+ // /|+ // /_|+ //+ FeatureId::Edge([ibottom, iright, idiag][iedge as usize] as u32)+ }+ }+ FeatureId::Face(iface) => {+ if iface == 0 {+ FeatureId::Face(self.face_id(i, j, left, true))+ } else {+ FeatureId::Face(self.face_id(i, j, left, false))+ }+ }+ FeatureId::Unknown => FeatureId::Unknown,+ }+ }++ /// The range of segment ids that may intersect the given local Aabb.+ pub fn unclamped_elements_range_in_local_aabb(+ &self,+ aabb: &Aabb,+ ) -> (Range<isize>, Range<isize>) {+ let ref_mins = aabb.mins / self.scale;+ let ref_maxs = aabb.maxs / self.scale;+ let cell_width = self.unit_cell_width();+ let cell_height = self.unit_cell_height();++ let min_x = self.quantize_floor_unclamped(ref_mins.x, cell_width);+ let min_z = self.quantize_floor_unclamped(ref_mins.z, cell_height);++ let max_x = self.quantize_ceil_unclamped(ref_maxs.x, cell_width);+ let max_z = self.quantize_ceil_unclamped(ref_maxs.z, cell_height);+ (min_z..max_z, min_x..max_x)+ }++ /// Applies the function `f` to all the triangles of this heightfield intersecting the given Aabb.+ pub fn map_elements_in_local_aabb(&self, aabb: &Aabb, f: &mut impl FnMut(u32, &Triangle)) {+ let ncells_x = self.ncols();+ let ncells_z = self.nrows();++ let ref_mins = aabb.mins / self.scale;+ let ref_maxs = aabb.maxs / self.scale;+ let cell_width = self.unit_cell_width();+ let cell_height = self.unit_cell_height();++ if ref_maxs.x <= -0.5 || ref_maxs.z <= -0.5 || ref_mins.x >= 0.5 || ref_mins.z >= 0.5 {+ // Outside of the heightfield bounds.+ return;+ }++ let min_x = self.quantize_floor(ref_mins.x, cell_width, ncells_x);+ let min_z = self.quantize_floor(ref_mins.z, cell_height, ncells_z);++ let max_x = self.quantize_ceil(ref_maxs.x, cell_width, ncells_x);+ let max_z = self.quantize_ceil(ref_maxs.z, cell_height, ncells_z);++ // TODO: find a way to avoid recomputing the same vertices+ // multiple times.+ for j in min_x..max_x {+ for i in min_z..max_z {+ let status = self.status[(i, j)];++ if status.contains(HeightFieldCellStatus::CELL_REMOVED) {+ continue;+ }++ let z0 = -0.5 + cell_height * (i as Real);+ let z1 = z0 + cell_height;++ let x0 = -0.5 + cell_width * (j as Real);+ let x1 = x0 + cell_width;++ let y00 = self.heights[(i, j)];+ let y10 = self.heights[(i + 1, j)];+ let y01 = self.heights[(i, j + 1)];+ let y11 = self.heights[(i + 1, j + 1)];++ if (y00 > ref_maxs.y && y10 > ref_maxs.y && y01 > ref_maxs.y && y11 > ref_maxs.y)+ || (y00 < ref_mins.y+ && y10 < ref_mins.y+ && y01 < ref_mins.y+ && y11 < ref_mins.y)+ {+ continue;+ }++ let mut p00 = Vector::new(x0, y00, z0);+ let mut p10 = Vector::new(x0, y10, z1);+ let mut p01 = Vector::new(x1, y01, z0);+ let mut p11 = Vector::new(x1, y11, z1);++ // Apply scales:+ p00 *= self.scale;+ p10 *= self.scale;+ p01 *= self.scale;+ p11 *= self.scale;++ // Build the two triangles, contact processors and call f.+ if !status.contains(HeightFieldCellStatus::LEFT_TRIANGLE_REMOVED) {+ let tri1 = if status.contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {+ Triangle::new(p00, p10, p11)+ } else {+ Triangle::new(p00, p10, p01)+ };++ let tid = self.triangle_id(i, j, true);+ f(tid, &tri1);+ }++ if !status.contains(HeightFieldCellStatus::RIGHT_TRIANGLE_REMOVED) {+ let tri2 = if status.contains(HeightFieldCellStatus::ZIGZAG_SUBDIVISION) {+ Triangle::new(p00, p11, p01)+ } else {+ Triangle::new(p10, p11, p01)+ };+ let tid = self.triangle_id(i, j, false);+ f(tid, &tri2);+ }+ }+ }+ }+}++struct HeightFieldTriangles<'a> {+ heightfield: &'a HeightField,+ curr: (usize, usize),+ tris: (Option<Triangle>, Option<Triangle>),+}++impl Iterator for HeightFieldTriangles<'_> {+ type Item = Triangle;++ fn next(&mut self) -> Option<Triangle> {+ loop {+ if let Some(tri1) = self.tris.0.take() {+ return Some(tri1);+ } else if let Some(tri2) = self.tris.1.take() {+ return Some(tri2);+ } else {+ self.curr.0 += 1;++ if self.curr.0 >= self.heightfield.nrows() {+ if self.curr.1 >= self.heightfield.ncols() - 1 {+ return None;+ }++ self.curr.0 = 0;+ self.curr.1 += 1;+ }++ // tri1 and tri2 are None+ self.tris = self.heightfield.triangles_at(self.curr.0, self.curr.1);+ }+ }+ }+}++/// An iterator through all the triangles around the given point, after vertical projection on the heightfield.+pub struct HeightFieldRadialTriangles<'a> {+ heightfield: &'a HeightField,+ center: (usize, usize),+ curr_radius: usize,+ curr_element: usize,+ tris: (Option<Triangle>, Option<Triangle>),+}++impl HeightFieldRadialTriangles<'_> {+ /// Returns the next triangle in this iterator.+ ///+ /// Returns `None` no triangle closest than `max_dist` remain+ /// to be yielded. The `max_dist` can be modified at each iteration+ /// as long as the new value is smaller or equal to the previous value.+ pub fn next(&mut self, max_dist: Real) -> Option<Triangle> {+ let max_rad = if max_dist == Real::MAX {+ usize::MAX+ } else {+ (max_dist / self.heightfield.cell_width())+ .ceil()+ .max((max_dist / self.heightfield.cell_height()).ceil()) as usize+ };++ loop {+ if let Some(tri1) = self.tris.0.take() {+ return Some(tri1);+ } else if let Some(tri2) = self.tris.1.take() {+ return Some(tri2);+ } else {+ let mut curr_cell = (0, 0);++ loop {+ self.curr_element += 1;++ if self.curr_element >= 8 * self.curr_radius {+ if self.curr_radius >= max_rad {+ return None;+ }++ self.curr_element = 0;+ self.curr_radius += 1;+ }++ let side_max_index = self.curr_radius + self.curr_radius;+ let curr_index_in_side = self.curr_element % side_max_index;+ let curr_side = self.curr_element / side_max_index;++ let mins = (+ self.center.0 as isize - self.curr_radius as isize,+ self.center.1 as isize - self.curr_radius as isize,+ );+ let maxs = (+ self.center.0 as isize + self.curr_radius as isize,+ self.center.1 as isize + self.curr_radius as isize,+ );++ if curr_cell.0 < 0+ && curr_cell.1 < 0+ && (curr_cell.0 as usize) >= self.heightfield.nrows()+ && (curr_cell.1 as usize) >= self.heightfield.ncols()+ {+ // We already visited all the triangles of the heightfield.+ return None;+ }++ let side_origins = [+ (mins.0, mins.1),+ (maxs.0, mins.1),+ (maxs.0, maxs.1),+ (mins.0, maxs.1),+ ];+ let side_directions = [(1, 0), (0, 1), (-1, 0), (0, -1)];++ curr_cell = (+ side_origins[curr_side].0+ + side_directions[curr_side].0 * (curr_index_in_side as isize),+ side_origins[curr_side].1+ + side_directions[curr_side].1 * (curr_index_in_side as isize),+ );++ if curr_cell.0 >= 0+ && curr_cell.1 >= 0+ && (curr_cell.0 as usize) < self.heightfield.nrows()+ && (curr_cell.1 as usize) < self.heightfield.ncols()+ {+ break;+ }+ }++ self.tris = self+ .heightfield+ .triangles_at(curr_cell.0 as usize, curr_cell.1 as usize);+ }+ }+ }+}++#[cfg(test)]+#[cfg(all(feature = "dim3", feature = "alloc", feature = "std"))]+mod test {+ use super::HeightField;+ use crate::math::{Real, Vector};+ use crate::shape::FeatureId;+ use crate::utils::Array2;+ use alloc::vec::Vec;++ /// The conversion recovers the cell and side from the triangle id, so every triangle has to+ /// come out with a face of its own.+ #[test]+ fn every_triangle_converts_to_its_own_feature() {+ let (nrows, ncols) = (4, 5);+ let heights: Vec<Real> = (0..nrows * ncols).map(|k| k as Real * 0.13).collect();+ let heightfield = HeightField::new(+ Array2::new(nrows, ncols, heights),+ Vector::new(2.0, 1.0, 3.0),+ );++ let num_triangles = (nrows - 1) * (ncols - 1) * 2;+ let faces: Vec<_> = (0..num_triangles as u32)+ .map(|triangle| heightfield.convert_triangle_feature_id(triangle, FeatureId::Face(0)))+ .collect();++ for (triangle, face) in faces.iter().enumerate() {+ assert!(+ !faces[..triangle].contains(face),+ "triangle {triangle} reuses {face:?}"+ );+ }+ }+}diff --git a/renderer/third_party/parry3d/src/shape/mod.rs b/renderer/third_party/parry3d/src/shape/mod.rsnew file mode 100644index 0000000..00ad6ae--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/mod.rs@@ -0,0 +1,144 @@+//! Shapes supported by parry.++pub use self::ball::Ball;+pub use self::capsule::Capsule;+pub use self::cuboid::Cuboid;+pub use self::feature_id::{FeatureId, PackedFeatureId, SubShapeId};+pub use self::half_space::HalfSpace;+pub use self::polygonal_feature_map::PolygonalFeatureMap;+pub use self::round_shape::RoundShape;+pub use self::segment::{Segment, SegmentPointLocation};+#[cfg(feature = "serde-serialize")]+pub(crate) use self::shape::DeserializableTypedShape;+#[doc(inline)]+pub use self::shape::{Shape, ShapeType, TypedShape};+#[doc(inline)]+pub use self::support_map::SupportMap;+pub use self::triangle::{Triangle, TriangleOrientation, TrianglePointLocation};++#[cfg(feature = "alloc")]+pub use self::{+ composite_shape::{CompositeShape, CompositeShapeRef, TypedCompositeShape},+ compound::Compound,+ polyline::Polyline,+ shared_shape::SharedShape,+ voxels::{AxisMask, OctantPattern, VoxelData, VoxelState, VoxelType, Voxels, VoxelsChunkRef},+};++#[cfg(feature = "alloc")]+pub use self::polyline::PolylineFlags;++#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+pub use self::convex_polygon::ConvexPolygon;+#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+pub use self::heightfield2::*;+#[cfg(feature = "dim2")]+pub use self::polygonal_feature2d::PolygonalFeature;++#[cfg(feature = "alloc")]+pub use self::compound::CompoundFlags;+#[cfg(all(feature = "alloc", feature = "dim2"))]+pub use self::compound_pseudo_normals::CompoundEdgeCone;+#[cfg(all(feature = "alloc", feature = "dim3"))]+pub use self::compound_pseudo_normals::CompoundFaceCone;+#[cfg(feature = "alloc")]+pub use self::compound_pseudo_normals::CompoundPseudoNormals;+#[cfg(feature = "dim3")]+pub use self::cone::Cone;+#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+pub use self::convex_polyhedron::ConvexPolyhedron;+#[cfg(feature = "dim3")]+pub use self::cylinder::Cylinder;+#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+pub use self::heightfield3::*;+#[cfg(feature = "dim3")]+pub use self::polygonal_feature3d::PolygonalFeature;+pub use self::segment_pseudo_normals::SegmentPseudoNormals;+#[cfg(feature = "dim3")]+pub use self::tetrahedron::{Tetrahedron, TetrahedronPointLocation};+pub use self::triangle_pseudo_normals::TrianglePseudoNormals;+#[cfg(feature = "alloc")]+pub use self::trimesh::*;++/// A cylinder dilated by a sphere (so it has round corners).+#[cfg(feature = "dim3")]+pub type RoundCylinder = RoundShape<Cylinder>;+/// A cone dilated by a sphere (so it has round corners).+#[cfg(feature = "dim3")]+pub type RoundCone = RoundShape<Cone>;+/// A cuboid dilated by a sphere (so it has round corners).+pub type RoundCuboid = RoundShape<Cuboid>;+/// A triangle dilated by a sphere (so it has round corners).+pub type RoundTriangle = RoundShape<Triangle>;+/// A convex polyhedron dilated by a sphere (so it has round corners).+#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+pub type RoundConvexPolyhedron = RoundShape<ConvexPolyhedron>;+/// A convex polygon dilated by a sphere (so it has round corners).+#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+pub type RoundConvexPolygon = RoundShape<ConvexPolygon>;++pub(crate) use self::round_shape::RoundShapeRef;++mod ball;+mod capsule;+#[cfg(feature = "alloc")]+#[doc(hidden)]+pub mod composite_shape;+#[cfg(feature = "alloc")]+mod compound;+mod cuboid;+mod half_space;+#[cfg(feature = "alloc")]+mod polyline;+mod round_shape;+mod segment;+#[doc(hidden)]+pub mod shape;+#[doc(hidden)]+pub mod support_map;+mod triangle;++#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+mod convex_polygon;+#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+mod heightfield2;++#[cfg(feature = "dim3")]+mod cone;+#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+mod convex_polyhedron;+#[cfg(feature = "dim3")]+mod cylinder;+#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+mod heightfield3;+#[cfg(feature = "dim3")]+mod polygonal_feature3d;+mod polygonal_feature_map;+#[cfg(feature = "dim3")]+mod tetrahedron;+#[cfg(feature = "alloc")]+pub(crate) mod trimesh;+// TODO: move this elsewhere?+#[cfg(feature = "alloc")]+mod compound_pseudo_normals;+mod feature_id;+#[cfg(feature = "dim2")]+mod polygonal_feature2d;+#[cfg(feature = "alloc")]+mod pseudo_normals;+mod segment_pseudo_normals;+#[cfg(feature = "alloc")]+mod shared_shape;+mod triangle_pseudo_normals;+#[cfg(feature = "alloc")]+mod voxels;diff --git a/renderer/third_party/parry3d/src/shape/polygon.rs b/renderer/third_party/parry3d/src/shape/polygon.rsnew file mode 100644index 0000000..b37a352--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/polygon.rs@@ -0,0 +1,82 @@+#![allow(dead_code)] // TODO: remove this once we support polygons.++use crate::math::{Pose, Vector, Real, Vector};+use parry::bounding_volume::Aabb;++#[derive(Clone)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize),+)]+/// A convex planar polygon.+pub struct Polygon {+ pub(crate) vertices: Vec<Vector>,+ pub(crate) normals: Vec<Vector>,+}++impl Polygon {+ /// Builds a new polygon from a set of vertices and normals.+ ///+ /// The vertices must be ordered in such a way that two consecutive+ /// vertices determines an edge of the polygon. For example `vertices[0], vertices[1]`+ /// is an edge, `vertices[1], vertices[2]` is the next edge, etc. The last edge will+ /// be `vertices[vertices.len() - 1], vertices[0]`.+ /// The vertices must be given in counter-clockwise order.+ /// The vertices must form a convex polygon.+ ///+ /// One normal must be provided per edge and mut point towards the outside of the polygon.+ pub fn new(vertices: Vec<Vector>, normals: Vec<Vector>) -> Self {+ Self { vertices, normals }+ }++ /// Compute the axis-aligned bounding box of the polygon.+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ let p0 = pos * self.vertices[0];+ let mut mins = p0;+ let mut maxs = p0;++ for pt in &self.vertices[1..] {+ let pt = pos * pt;+ mins = mins.min(pt);+ maxs = maxs.max(pt);+ }++ Aabb::new(mins.into(), maxs.into())+ }++ /// The vertices of this polygon.+ pub fn vertices(&self) -> &[Vector] {+ &self.vertices+ }++ pub(crate) fn support_point(&self, dir: Vector) -> usize {+ let mut best_dot = -Real::MAX;+ let mut best_i = 0;++ for (i, pt) in self.vertices.iter().enumerate() {+ let dot = pt.dot(dir);+ if dot > best_dot {+ best_dot = dot;+ best_i = i;+ }+ }++ best_i+ }++ pub(crate) fn support_face(&self, dir: Vector) -> usize {+ let mut max_dot = -Real::MAX;+ let mut max_dot_i = 0;++ for (i, normal) in self.normals.iter().enumerate() {+ let dot = normal.dot(dir);+ if dot > max_dot {+ max_dot = dot;+ max_dot_i = i;+ }+ }++ max_dot_i+ }+}diff --git a/renderer/third_party/parry3d/src/shape/polygonal_feature2d.rs b/renderer/third_party/parry3d/src/shape/polygonal_feature2d.rsnew file mode 100644index 0000000..8fa9c42--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/polygonal_feature2d.rs@@ -0,0 +1,148 @@+use crate::math::{Pose, Vector};+#[cfg(feature = "alloc")]+use crate::query::{self, ContactManifold, TrackedContact};+use crate::shape::{PackedFeatureId, Segment};++/// A polygonal feature representing the local polygonal approximation of+/// a vertex, or face, of a convex shape.+#[derive(Debug)]+pub struct PolygonalFeature {+ /// Up to two vertices forming this polygonal feature.+ pub vertices: [Vector; 2],+ /// The feature IDs of this polygon's vertices.+ pub vids: [PackedFeatureId; 2],+ /// The feature ID of this polygonal feature.+ pub fid: PackedFeatureId,+ /// The number of vertices on this polygon (must be <= 4).+ pub num_vertices: usize,+}++impl Default for PolygonalFeature {+ fn default() -> Self {+ Self {+ vertices: [Vector::ZERO; 2],+ vids: [PackedFeatureId::UNKNOWN; 2],+ fid: PackedFeatureId::UNKNOWN,+ num_vertices: 0,+ }+ }+}++impl From<Segment> for PolygonalFeature {+ fn from(seg: Segment) -> Self {+ PolygonalFeature {+ vertices: [seg.a, seg.b],+ vids: PackedFeatureId::vertices([0, 2]),+ fid: PackedFeatureId::face(1),+ num_vertices: 2,+ }+ }+}++impl PolygonalFeature {+ /// Transforms the vertices of `self` by the given position `pos`.+ pub fn transform_by(&mut self, pos: &Pose) {+ self.vertices[0] = pos * self.vertices[0];+ self.vertices[1] = pos * self.vertices[1];+ }++ /// Computes the contacts between two polygonal features.+ #[cfg(feature = "alloc")]+ pub fn contacts<ManifoldData, ContactData: Default + Copy>(+ pos12: &Pose,+ pos21: &Pose,+ sep_axis1: Vector,+ sep_axis2: Vector,+ feature1: &Self,+ feature2: &Self,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+ flipped: bool,+ ) {+ match (feature1.num_vertices == 2, feature2.num_vertices == 2) {+ (true, true) => {+ Self::face_face_contacts(pos12, feature1, sep_axis1, feature2, manifold, flipped)+ }+ (true, false) => {+ Self::face_vertex_contacts(pos12, feature1, sep_axis1, feature2, manifold, flipped)+ }+ (false, true) => {+ Self::face_vertex_contacts(pos21, feature2, sep_axis2, feature1, manifold, !flipped)+ }+ (false, false) => unimplemented!(),+ }+ }++ /// Compute contacts points between a face and a vertex.+ ///+ /// This method assume we already know that at least one contact exists.+ #[cfg(feature = "alloc")]+ pub fn face_vertex_contacts<ManifoldData, ContactData: Default + Copy>(+ pos12: &Pose,+ face1: &Self,+ sep_axis1: Vector,+ vertex2: &Self,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+ flipped: bool,+ ) {+ let v2_1 = pos12 * vertex2.vertices[0];+ let tangent1 = face1.vertices[1] - face1.vertices[0];+ let normal1 = Vector::new(-tangent1.y, tangent1.x);+ let denom = -normal1.dot(sep_axis1);+ let dist = (face1.vertices[0] - v2_1).dot(normal1) / denom;+ let local_p2 = v2_1;+ let local_p1 = v2_1 - dist * normal1;++ let contact = TrackedContact::flipped(+ local_p1,+ pos12.inverse_transform_point(local_p2),+ face1.fid,+ vertex2.vids[0],+ dist,+ flipped,+ );++ manifold.points.push(contact);+ }++ /// Computes the contacts between two polygonal faces.+ #[cfg(feature = "alloc")]+ pub fn face_face_contacts<ManifoldData, ContactData: Default + Copy>(+ pos12: &Pose,+ face1: &Self,+ normal1: Vector,+ face2: &Self,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+ flipped: bool,+ ) {+ if let Some((clip_a, clip_b)) = query::details::clip_segment_segment_with_normal(+ (face1.vertices[0], face1.vertices[1]),+ (pos12 * face2.vertices[0], pos12 * face2.vertices[1]),+ normal1,+ ) {+ let fids1 = [face1.vids[0], face1.fid, face1.vids[1]];+ let fids2 = [face2.vids[0], face2.fid, face2.vids[1]];++ let dist = (clip_a.1 - clip_a.0).dot(normal1);+ let contact = TrackedContact::flipped(+ clip_a.0,+ pos12.inverse_transform_point(clip_a.1),+ fids1[clip_a.2],+ fids2[clip_a.3],+ dist,+ flipped,+ );+ manifold.points.push(contact);++ let dist = (clip_b.1 - clip_b.0).dot(normal1);+ let contact = TrackedContact::flipped(+ clip_b.0,+ pos12.inverse_transform_point(clip_b.1),+ fids1[clip_b.2],+ fids2[clip_b.3],+ dist,+ flipped,+ );+ manifold.points.push(contact);+ }+ }+}diff --git a/renderer/third_party/parry3d/src/shape/polygonal_feature3d.rs b/renderer/third_party/parry3d/src/shape/polygonal_feature3d.rsnew file mode 100644index 0000000..4a93873--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/polygonal_feature3d.rs@@ -0,0 +1,418 @@+use crate::math::{Pose, Vector};+use crate::shape::{PackedFeatureId, Segment, Triangle};+#[cfg(feature = "alloc")]+use crate::{+ math::{Real, Vector2},+ query::details::closest_points_segment_segment_2d,+ query::{ContactManifold, TrackedContact},+ utils::WBasis,+};++/// A polygonal feature representing the local polygonal approximation of+/// a vertex, face, or edge of a convex shape.+#[derive(Debug, Clone)]+pub struct PolygonalFeature {+ /// Up to four vertices forming this polygonal feature.+ pub vertices: [Vector; 4],+ /// The feature IDs of this polygon's vertices.+ pub vids: [PackedFeatureId; 4],+ /// The feature IDs of this polygon's edges.+ pub eids: [PackedFeatureId; 4],+ /// The feature ID of this polygonal feature.+ pub fid: PackedFeatureId,+ /// The number of vertices on this polygon (must be <= 4).+ pub num_vertices: usize,+}++impl Default for PolygonalFeature {+ fn default() -> Self {+ Self {+ vertices: [Vector::ZERO; 4],+ vids: [PackedFeatureId::UNKNOWN; 4],+ eids: [PackedFeatureId::UNKNOWN; 4],+ fid: PackedFeatureId::UNKNOWN,+ num_vertices: 0,+ }+ }+}++impl From<Triangle> for PolygonalFeature {+ fn from(tri: Triangle) -> Self {+ Self {+ vertices: [tri.a, tri.b, tri.c, tri.c],+ vids: PackedFeatureId::vertices([0, 1, 2, 2]),+ eids: PackedFeatureId::edges([0, 1, 2, 2]),+ fid: PackedFeatureId::face(0),+ num_vertices: 3,+ }+ }+}++impl From<Segment> for PolygonalFeature {+ fn from(seg: Segment) -> Self {+ Self {+ vertices: [seg.a, seg.b, seg.b, seg.b],+ vids: PackedFeatureId::vertices([0, 1, 1, 1]),+ eids: PackedFeatureId::edges([0, 0, 0, 0]),+ fid: PackedFeatureId::face(0),+ num_vertices: 2,+ }+ }+}++impl PolygonalFeature {+ /// Creates a new empty polygonal feature.+ pub fn new() -> Self {+ Self::default()+ }++ /// Transform each vertex of this polygonal feature by the given position `pos`.+ pub fn transform_by(&mut self, pos: &Pose) {+ for p in &mut self.vertices[0..self.num_vertices] {+ *p = pos * *p;+ }+ }++ /// Computes all the contacts between two polygonal features.+ #[cfg(feature = "alloc")]+ pub fn contacts<ManifoldData, ContactData: Default + Copy>(+ pos12: &Pose,+ _pos21: &Pose,+ sep_axis1: Vector,+ _sep_axis2: Vector,+ feature1: &Self,+ feature2: &Self,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+ flipped: bool,+ ) {+ match (feature1.num_vertices, feature2.num_vertices) {+ (2, 2) => {+ Self::contacts_edge_edge(pos12, feature1, sep_axis1, feature2, manifold, flipped)+ }+ _ => Self::contacts_face_face(pos12, feature1, sep_axis1, feature2, manifold, flipped),+ }+ }++ #[cfg(feature = "alloc")]+ fn contacts_edge_edge<ManifoldData, ContactData: Default + Copy>(+ pos12: &Pose,+ face1: &PolygonalFeature,+ sep_axis1: Vector,+ face2: &PolygonalFeature,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+ flipped: bool,+ ) {+ // Project the faces to a 2D plane for contact clipping.+ // The plane they are projected onto has normal sep_axis1+ // and contains the origin (this is numerically OK because+ // we are not working in world-space here).+ let basis = sep_axis1.orthonormal_basis();+ let projected_edge1 = [+ Vector2::new(+ face1.vertices[0].dot(basis[0]),+ face1.vertices[0].dot(basis[1]),+ ),+ Vector2::new(+ face1.vertices[1].dot(basis[0]),+ face1.vertices[1].dot(basis[1]),+ ),+ ];++ let vertices2_1 = [pos12 * face2.vertices[0], pos12 * face2.vertices[1]];+ let projected_edge2 = [+ Vector2::new(vertices2_1[0].dot(basis[0]), vertices2_1[0].dot(basis[1])),+ Vector2::new(vertices2_1[1].dot(basis[0]), vertices2_1[1].dot(basis[1])),+ ];++ let tangent1 = (projected_edge1[1] - projected_edge1[0]).try_normalize();+ let tangent2 = (projected_edge2[1] - projected_edge2[0]).try_normalize();++ // TODO: not sure what the best value for eps is.+ // Empirically, it appears that an epsilon smaller than 1.0e-3 is too small.+ if let (Some(tangent1), Some(tangent2)) = (tangent1, tangent2) {+ let parallel = tangent1.dot(tangent2) >= crate::utils::COS_FRAC_PI_8;++ if !parallel {+ let seg1 = (&projected_edge1[0], &projected_edge1[1]);+ let seg2 = (&projected_edge2[0], &projected_edge2[1]);+ let (loc1, loc2) = closest_points_segment_segment_2d(seg1, seg2);++ // Found a contact between the two edges.+ let bcoords1 = loc1.barycentric_coordinates();+ let bcoords2 = loc2.barycentric_coordinates();++ let edge1 = (face1.vertices[0], face1.vertices[1]);+ let edge2 = (vertices2_1[0], vertices2_1[1]);+ let local_p1 = edge1.0 * bcoords1[0] + edge1.1 * bcoords1[1];+ let local_p2_1 = edge2.0 * bcoords2[0] + edge2.1 * bcoords2[1];+ let dist = (local_p2_1 - local_p1).dot(sep_axis1);++ manifold.points.push(TrackedContact::flipped(+ local_p1,+ pos12.inverse_transform_point(local_p2_1),+ face1.eids[0],+ face2.eids[0],+ dist,+ flipped,+ ));++ return;+ }+ }++ // The lines are parallel so we are having a conformal contact.+ // Let's use a range-based clipping to extract two contact points.+ // TODO: would it be better and/or more efficient to do the+ //clipping in 2D?+ if let Some(clips) = crate::query::details::clip_segment_segment(+ (face1.vertices[0], face1.vertices[1]),+ (vertices2_1[0], vertices2_1[1]),+ ) {+ let feature_at = |face: &PolygonalFeature, id| match id {+ 0 => face.vids[0],+ 1 => face.eids[0],+ 2 => face.vids[1],+ _ => unreachable!(),+ };++ manifold.points.push(TrackedContact::flipped(+ (clips.0).0,+ pos12.inverse_transform_point((clips.0).1),+ feature_at(face1, (clips.0).2),+ feature_at(face2, (clips.0).3),+ ((clips.0).1 - (clips.0).0).dot(sep_axis1),+ flipped,+ ));++ manifold.points.push(TrackedContact::flipped(+ (clips.1).0,+ pos12.inverse_transform_point((clips.1).1),+ feature_at(face1, (clips.1).2),+ feature_at(face2, (clips.1).3),+ ((clips.1).1 - (clips.1).0).dot(sep_axis1),+ flipped,+ ));+ }+ }++ #[cfg(feature = "alloc")]+ fn contacts_face_face<ManifoldData, ContactData: Default + Copy>(+ pos12: &Pose,+ face1: &PolygonalFeature,+ sep_axis1: Vector,+ face2: &PolygonalFeature,+ manifold: &mut ContactManifold<ManifoldData, ContactData>,+ flipped: bool,+ ) {+ // Project the faces to a 2D plane for contact clipping.+ // The plane they are projected onto has normal sep_axis1+ // and contains the origin (this is numerically OK because+ // we are not working in world-space here).+ let basis = sep_axis1.orthonormal_basis();+ let projected_face1 = [+ Vector2::new(+ face1.vertices[0].dot(basis[0]),+ face1.vertices[0].dot(basis[1]),+ ),+ Vector2::new(+ face1.vertices[1].dot(basis[0]),+ face1.vertices[1].dot(basis[1]),+ ),+ Vector2::new(+ face1.vertices[2].dot(basis[0]),+ face1.vertices[2].dot(basis[1]),+ ),+ Vector2::new(+ face1.vertices[3].dot(basis[0]),+ face1.vertices[3].dot(basis[1]),+ ),+ ];++ let vertices2_1 = [+ pos12 * face2.vertices[0],+ pos12 * face2.vertices[1],+ pos12 * face2.vertices[2],+ pos12 * face2.vertices[3],+ ];+ let projected_face2 = [+ Vector2::new(vertices2_1[0].dot(basis[0]), vertices2_1[0].dot(basis[1])),+ Vector2::new(vertices2_1[1].dot(basis[0]), vertices2_1[1].dot(basis[1])),+ Vector2::new(vertices2_1[2].dot(basis[0]), vertices2_1[2].dot(basis[1])),+ Vector2::new(vertices2_1[3].dot(basis[0]), vertices2_1[3].dot(basis[1])),+ ];++ // Also find all the vertices located inside of the other projected face.+ if face2.num_vertices > 2 {+ let normal2_1 =+ (vertices2_1[2] - vertices2_1[1]).cross(vertices2_1[0] - vertices2_1[1]);+ let denom = normal2_1.dot(sep_axis1);++ if !relative_eq!(denom, 0.0) {+ let last_index2 = face2.num_vertices - 1;++ #[allow(clippy::needless_range_loop)] // Would make it much more verbose.+ 'point_loop1: for i in 0..face1.num_vertices {+ let p1 = projected_face1[i];++ let mut sign = (projected_face2[0] - projected_face2[last_index2])+ .perp_dot(p1 - projected_face2[last_index2]);+ for j in 0..last_index2 {+ let new_sign = (projected_face2[j + 1] - projected_face2[j])+ .perp_dot(p1 - projected_face2[j]);++ if sign == 0.0 {+ sign = new_sign;+ } else if sign * new_sign < 0.0 {+ // The point lies outside.+ continue 'point_loop1;+ }+ }++ // All the perp had the same sign: the point is inside of the other shapes projection.+ // Output the contact.+ let dist = (vertices2_1[0] - face1.vertices[i]).dot(normal2_1) / denom;+ let local_p1 = face1.vertices[i];+ let local_p2_1 = face1.vertices[i] + dist * sep_axis1;++ manifold.points.push(TrackedContact::flipped(+ local_p1,+ pos12.inverse_transform_point(local_p2_1),+ face1.vids[i],+ face2.fid,+ dist,+ flipped,+ ));+ }+ }+ }++ if face1.num_vertices > 2 {+ let normal1 = (face1.vertices[2] - face1.vertices[1])+ .cross(face1.vertices[0] - face1.vertices[1]);++ let denom = -normal1.dot(sep_axis1);+ if !relative_eq!(denom, 0.0) {+ let last_index1 = face1.num_vertices - 1;+ 'point_loop2: for i in 0..face2.num_vertices {+ let p2 = projected_face2[i];++ let mut sign = (projected_face1[0] - projected_face1[last_index1])+ .perp_dot(p2 - projected_face1[last_index1]);+ for j in 0..last_index1 {+ let new_sign = (projected_face1[j + 1] - projected_face1[j])+ .perp_dot(p2 - projected_face1[j]);++ if sign == 0.0 {+ sign = new_sign;+ } else if sign * new_sign < 0.0 {+ // The point lies outside.+ continue 'point_loop2;+ }+ }++ // All the perp had the same sign: the point is inside of the other shapes projection.+ // Output the contact.+ let dist = (face1.vertices[0] - vertices2_1[i]).dot(normal1) / denom;+ let local_p2_1 = vertices2_1[i];+ let local_p1 = vertices2_1[i] - dist * sep_axis1;++ manifold.points.push(TrackedContact::flipped(+ local_p1,+ pos12.inverse_transform_point(local_p2_1),+ face1.fid,+ face2.vids[i],+ dist,+ flipped,+ ));+ }+ }+ }++ // Now we have to compute the intersection between all pairs of+ // edges from the face 1 and from the face2.+ for j in 0..face2.num_vertices {+ let projected_edge2 = [+ projected_face2[j],+ projected_face2[(j + 1) % face2.num_vertices],+ ];++ for i in 0..face1.num_vertices {+ let projected_edge1 = [+ projected_face1[i],+ projected_face1[(i + 1) % face1.num_vertices],+ ];+ if let Some(bcoords) = closest_points_line2d(projected_edge1, projected_edge2) {+ if bcoords.0 > 0.0 && bcoords.0 < 1.0 && bcoords.1 > 0.0 && bcoords.1 < 1.0 {+ // Found a contact between the two edges.+ let edge1 = (+ face1.vertices[i],+ face1.vertices[(i + 1) % face1.num_vertices],+ );+ let edge2 = (vertices2_1[j], vertices2_1[(j + 1) % face2.num_vertices]);+ let local_p1 = edge1.0 * (1.0 - bcoords.0) + edge1.1 * bcoords.0;+ let local_p2_1 = edge2.0 * (1.0 - bcoords.1) + edge2.1 * bcoords.1;+ let dist = (local_p2_1 - local_p1).dot(sep_axis1);++ manifold.points.push(TrackedContact::flipped(+ local_p1,+ pos12.inverse_transform_point(local_p2_1),+ face1.eids[i],+ face2.eids[j],+ dist,+ flipped,+ ));+ }+ }+ }+ }+ }+}++/// Compute the barycentric coordinates of the intersection between the two given lines.+/// Returns `None` if the lines are parallel.+#[cfg(feature = "alloc")]+fn closest_points_line2d(edge1: [Vector2; 2], edge2: [Vector2; 2]) -> Option<(Real, Real)> {+ use crate::approx::AbsDiffEq;++ // Inspired by Real-time collision detection by Christer Ericson.+ let dir1 = edge1[1] - edge1[0];+ let dir2 = edge2[1] - edge2[0];+ let r = edge1[0] - edge2[0];++ let a = dir1.length_squared();+ let e = dir2.length_squared();+ let f = dir2.dot(r);++ let eps = Real::default_epsilon();++ if a <= eps && e <= eps {+ Some((0.0, 0.0))+ } else if a <= eps {+ Some((0.0, f / e))+ } else {+ let c = dir1.dot(r);+ if e <= eps {+ Some((-c / a, 0.0))+ } else {+ let b = dir1.dot(dir2);+ let ae = a * e;+ let bb = b * b;+ let denom = ae - bb;++ // Use absolute and ulps error to test collinearity.+ let parallel = denom <= eps || approx::ulps_eq!(ae, bb);++ let s = if !parallel {+ (b * f - c * e) / denom+ } else {+ 0.0+ };++ if parallel {+ None+ } else {+ Some((s, (b * s + f) / e))+ }+ }+ }+}diff --git a/renderer/third_party/parry3d/src/shape/polygonal_feature_map.rs b/renderer/third_party/parry3d/src/shape/polygonal_feature_map.rsnew file mode 100644index 0000000..6b50400--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/polygonal_feature_map.rs@@ -0,0 +1,207 @@+use crate::math::Vector;+#[cfg(feature = "dim3")]+use crate::shape::{Cone, Cylinder, PackedFeatureId};+use crate::shape::{Cuboid, PolygonalFeature, Segment, SupportMap, Triangle};+#[cfg(feature = "dim3")]+use crate::utils::WSign;++/// Trait implemented by convex shapes with features with polyhedral approximations.+pub trait PolygonalFeatureMap: SupportMap {+ /// Compute the support polygonal face of `self` towards the `dir`.+ fn local_support_feature(&self, dir: Vector, out_feature: &mut PolygonalFeature);++ /// Compute the support polygonal face of `self` towards `dir`, oriented so that it best+ /// covers the neighborhood of the local-space point `hint`.+ ///+ /// The default implementation ignores `hint`, which is exact for genuine polygons.+ /// Shapes approximating a curved feature (like a cylinder cap by an inscribed square)+ /// must orient it from `hint`: a fixed azimuth misses up to ~36% of the cap near its+ /// rim, leaving contacts there with a single unclippable point.+ fn local_support_feature_toward(+ &self,+ dir: Vector,+ hint: Vector,+ out_feature: &mut PolygonalFeature,+ ) {+ let _ = hint;+ self.local_support_feature(dir, out_feature);+ }++ // TODO: this is currently just a workaround for https://github.com/dimforge/rapier/issues/417+ // until we get a better way to deal with the issue without breaking internal edges+ // handling.+ /// Is this shape a `ConvexPolyhedron`?+ fn is_convex_polyhedron(&self) -> bool {+ false+ }+}++impl PolygonalFeatureMap for Segment {+ fn local_support_feature(&self, _: Vector, out_feature: &mut PolygonalFeature) {+ *out_feature = PolygonalFeature::from(*self);+ }+}++impl PolygonalFeatureMap for Triangle {+ fn local_support_feature(&self, dir: Vector, out_feature: &mut PolygonalFeature) {+ *out_feature = self.support_face(dir);+ }+}++impl PolygonalFeatureMap for Cuboid {+ fn local_support_feature(&self, dir: Vector, out_feature: &mut PolygonalFeature) {+ *out_feature = self.support_face(dir);+ }+}++/// Azimuth (unit `xz` direction) orienting the polygonal approximation of a cylinder's or+/// cone's curved features, taken from `hint` if it lies off the axis, else from `dir`.+#[cfg(feature = "dim3")]+fn feature_azimuth(dir: Vector, hint: Option<Vector>) -> crate::math::Vector2 {+ use crate::math::Vector2;+ hint.and_then(|hint| Vector2::new(hint.x, hint.z).try_normalize())+ .or_else(|| Vector2::new(dir.x, dir.z).try_normalize())+ .unwrap_or(Vector2::X)+}++#[cfg(feature = "dim3")]+impl PolygonalFeatureMap for Cylinder {+ fn local_support_feature(&self, dir: Vector, out_features: &mut PolygonalFeature) {+ self.support_feature_with_azimuth(dir, feature_azimuth(dir, None), out_features);+ }++ fn local_support_feature_toward(+ &self,+ dir: Vector,+ hint: Vector,+ out_features: &mut PolygonalFeature,+ ) {+ // Orienting the cap's square approximation so that one of its vertices (which lie on+ // the cap's rim) sits at the contact's azimuth guarantees the approximation covers+ // the cap's surface in the contact's neighborhood, wherever it lies on the cap.+ self.support_feature_with_azimuth(dir, feature_azimuth(dir, Some(hint)), out_features);+ }+}++#[cfg(feature = "dim3")]+impl Cylinder {+ fn support_feature_with_azimuth(+ &self,+ dir: Vector,+ dir2: crate::math::Vector2,+ out_features: &mut PolygonalFeature,+ ) {+ // About feature ids.+ // At all times, we consider our cylinder to be approximated as follows:+ // - The curved part is approximated by a single segment.+ // - Each flat cap of the cylinder is approximated by a square.+ // - The curved-part segment has a feature ID of 0, and its endpoint with negative+ // `y` coordinate has an ID of 1.+ // - The bottom cap has its vertices with feature ID of 1,3,5,7 (in counter-clockwise order+ // when looking at the cap with an eye looking towards +y).+ // - The bottom cap has its four edge feature IDs of 2,4,6,8, in counter-clockwise order.+ // - The bottom cap has its face feature ID of 9.+ // - The feature IDs of the top cap are the same as the bottom cap to which we add 10.+ // So its vertices have IDs 11,13,15,17, its edges 12,14,16,18, and its face 19.+ // - Note that at all times, one of each cap's vertices are the same as the curved-part+ // segment endpoints.+ if dir.y.abs() < 0.5 {+ // We return a segment lying on the cylinder's curved part.+ out_features.vertices[0] = Vector::new(+ dir2.x * self.radius,+ -self.half_height,+ dir2.y * self.radius,+ );+ out_features.vertices[1] =+ Vector::new(dir2.x * self.radius, self.half_height, dir2.y * self.radius);+ out_features.eids = PackedFeatureId::edges([0, 0, 0, 0]);+ out_features.fid = PackedFeatureId::face(0);+ out_features.num_vertices = 2;+ out_features.vids = PackedFeatureId::vertices([1, 11, 11, 11]);+ } else {+ // We return a square approximation of the cylinder cap.+ let y = dir.y.copy_sign_to(self.half_height);+ out_features.vertices[0] = Vector::new(dir2.x * self.radius, y, dir2.y * self.radius);+ out_features.vertices[1] = Vector::new(-dir2.y * self.radius, y, dir2.x * self.radius);+ out_features.vertices[2] = Vector::new(-dir2.x * self.radius, y, -dir2.y * self.radius);+ out_features.vertices[3] = Vector::new(dir2.y * self.radius, y, -dir2.x * self.radius);++ if dir.y < 0.0 {+ out_features.eids = PackedFeatureId::edges([2, 4, 6, 8]);+ out_features.fid = PackedFeatureId::face(9);+ out_features.num_vertices = 4;+ out_features.vids = PackedFeatureId::vertices([1, 3, 5, 7]);+ } else {+ out_features.eids = PackedFeatureId::edges([12, 14, 16, 18]);+ out_features.fid = PackedFeatureId::face(19);+ out_features.num_vertices = 4;+ out_features.vids = PackedFeatureId::vertices([11, 13, 15, 17]);+ }+ }+ }+}++#[cfg(feature = "dim3")]+impl PolygonalFeatureMap for Cone {+ fn local_support_feature(&self, dir: Vector, out_features: &mut PolygonalFeature) {+ self.support_feature_with_azimuth(dir, feature_azimuth(dir, None), out_features);+ }++ fn local_support_feature_toward(+ &self,+ dir: Vector,+ hint: Vector,+ out_features: &mut PolygonalFeature,+ ) {+ // See the comment in the cylinder's implementation.+ self.support_feature_with_azimuth(dir, feature_azimuth(dir, Some(hint)), out_features);+ }+}++#[cfg(feature = "dim3")]+impl Cone {+ fn support_feature_with_azimuth(+ &self,+ dir: Vector,+ dir2: crate::math::Vector2,+ out_features: &mut PolygonalFeature,+ ) {+ // About feature ids. It is very similar to the feature ids of cylinders.+ // At all times, we consider our cone to be approximated as follows:+ // - The curved part is approximated by a single segment.+ // - The flat cap of the cone is approximated by a square.+ // - The curved-part segment has a feature ID of 0, and its endpoint with negative+ // `y` coordinate has an ID of 1.+ // - The bottom cap has its vertices with feature ID of 1,3,5,7 (in counter-clockwise order+ // when looking at the cap with an eye looking towards +y).+ // - The bottom cap has its four edge feature IDs of 2,4,6,8, in counter-clockwise order.+ // - The bottom cap has its face feature ID of 9.+ // - Note that at all times, one of the cap's vertices are the same as the curved-part+ // segment endpoints.+ if dir.y > 0.0 {+ // We return a segment lying on the cone's curved part.+ out_features.vertices[0] = Vector::new(+ dir2.x * self.radius,+ -self.half_height,+ dir2.y * self.radius,+ );+ out_features.vertices[1] = Vector::new(0.0, self.half_height, 0.0);+ out_features.eids = PackedFeatureId::edges([0, 0, 0, 0]);+ out_features.fid = PackedFeatureId::face(0);+ out_features.num_vertices = 2;+ out_features.vids = PackedFeatureId::vertices([1, 11, 11, 11]);+ } else {+ // We return a square approximation of the cone cap.+ let y = -self.half_height;+ out_features.vertices[0] = Vector::new(dir2.x * self.radius, y, dir2.y * self.radius);+ out_features.vertices[1] = Vector::new(-dir2.y * self.radius, y, dir2.x * self.radius);+ out_features.vertices[2] = Vector::new(-dir2.x * self.radius, y, -dir2.y * self.radius);+ out_features.vertices[3] = Vector::new(dir2.y * self.radius, y, -dir2.x * self.radius);++ out_features.eids = PackedFeatureId::edges([2, 4, 6, 8]);+ out_features.fid = PackedFeatureId::face(9);+ out_features.num_vertices = 4;+ out_features.vids = PackedFeatureId::vertices([1, 3, 5, 7]);+ }+ }+}diff --git a/renderer/third_party/parry3d/src/shape/polyline.rs b/renderer/third_party/parry3d/src/shape/polyline.rsnew file mode 100644index 0000000..a0cec20--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/polyline.rs@@ -0,0 +1,1210 @@+use crate::bounding_volume::Aabb;+use crate::math::{Pose, Vector};+use crate::partitioning::{Bvh, BvhBuildStrategy};+use crate::query::{PointProjection, PointQueryWithLocation};+use crate::shape::composite_shape::CompositeShape;+use crate::shape::{+ FeatureId, Segment, SegmentPointLocation, SegmentPseudoNormals, Shape, SubShapeId,+ TypedCompositeShape,+};+#[cfg(feature = "alloc")]+use alloc::vec::Vec;++use crate::query::details::NormalConstraints;++#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]+/// Controls how a [`Polyline`] is loaded.+pub struct PolylineFlags(u8);++bitflags::bitflags! {+ impl PolylineFlags: u8 {+ /// If set, the polyline is treated as one-sided: a pseudo-normal is computed at every+ /// vertex and contact normals are clamped to the outward side, the *right* of each+ /// segment's direction. The solid must be wound counter-clockwise, so the outward side is+ /// on the right. This removes the spurious sideways push a body gets at a convex corner of+ /// a double-sided polyline. This one flag covers what `TriMesh` splits across+ /// `TriMeshFlags::ORIENTED` (compute pseudo-normals) and `TriMeshFlags::FIX_INTERNAL_EDGES`+ /// (use them to clamp contacts).+ #[cfg(feature = "dim2")]+ const ORIENTED = 1;+ /// If set, the vertices of this polyline are expected to move between queries while its+ /// pose stays fixed (see [`Polyline::set_vertices`]).+ ///+ /// The contact-manifold queries then never reuse cached contact points (see+ /// [`CompositeShape::is_deformable`]).+ const DEFORMABLE = 1 << 1;+ }+}++#[derive(Clone, Debug)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+/// A polyline shape formed by connected line segments.+///+/// A polyline is a sequence of line segments (edges) connecting vertices. It can be open+/// (not forming a closed loop) or closed (where the last vertex connects back to the first).+/// Polylines are commonly used for paths, boundaries, and 2D/3D curves.+///+/// # Structure+///+/// A polyline consists of:+/// - **Vertices**: Vectors in 2D or 3D space+/// - **Indices**: Pairs of vertex indices defining each segment+/// - **BVH**: Bounding Volume Hierarchy for fast spatial queries+///+/// # Properties+///+/// - **Composite shape**: Made up of multiple segments+/// - **1-dimensional**: Has length but no volume+/// - **Flexible topology**: Can be open or closed, branching or linear+/// - **Accelerated queries**: Uses BVH for efficient collision detection+///+/// # Use Cases+///+/// Polylines are ideal for:+/// - **Paths and roads**: Navigation paths, road networks+/// - **Terrain boundaries**: Cliff edges, coastlines, level boundaries+/// - **Outlines**: 2D shape outlines, contours+/// - **Wire frames**: Simplified representations of complex shapes+/// - **Motion paths**: Character movement paths, camera rails+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Polyline;+/// use parry3d::math::Vector;+///+/// // Create a simple L-shaped polyline+/// let vertices = vec![+/// Vector::ZERO,+/// Vector::new(1.0, 0.0, 0.0),+/// Vector::new(1.0, 1.0, 0.0),+/// ];+///+/// // Indices are automatically generated to connect consecutive vertices+/// let polyline = Polyline::new(vertices, None);+///+/// // The polyline has 2 segments: (0,1) and (1,2)+/// assert_eq!(polyline.num_segments(), 2);+/// assert_eq!(polyline.vertices().len(), 3);+/// # }+/// ```+///+/// # Custom Connectivity+///+/// You can provide custom indices to create non-sequential connections:+///+/// ```rust+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::shape::Polyline;+/// use parry2d::math::Vector;+///+/// // Create a triangle polyline (closed loop)+/// let vertices = vec![+/// Vector::ZERO,+/// Vector::new(1.0, 0.0),+/// Vector::new(0.5, 1.0),+/// ];+///+/// // Manually specify edges to create a closed triangle+/// let indices = vec![+/// [0, 1], // Bottom edge+/// [1, 2], // Right edge+/// [2, 0], // Left edge (closes the loop)+/// ];+///+/// let polyline = Polyline::new(vertices, Some(indices));+/// assert_eq!(polyline.num_segments(), 3);+/// # }+/// ```+pub struct Polyline {+ bvh: Bvh,+ vertices: Vec<Vector>,+ indices: Vec<[u32; 2]>,+ /// Per-vertex outward pseudo-normals, present when [`PolylineFlags::ORIENTED`] is set; contact+ /// normals are then clamped to one side so the polyline acts as a one-sided surface.+ #[cfg(feature = "dim2")]+ pseudo_normals: Option<Vec<Vector>>,+ flags: PolylineFlags,+}++impl Polyline {+ /// Creates a new polyline from a vertex buffer and an optional index buffer.+ ///+ /// This is the main constructor for creating a polyline. If no indices are provided,+ /// the vertices will be automatically connected in sequence (vertex 0 to 1, 1 to 2, etc.).+ ///+ /// # Arguments+ ///+ /// * `vertices` - A vector of points defining the polyline vertices+ /// * `indices` - Optional vector of `[u32; 2]` pairs defining which vertices connect.+ /// If `None`, vertices are connected sequentially.+ ///+ /// # Returns+ ///+ /// A new `Polyline` with an internal BVH for accelerated queries.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Polyline;+ /// use parry3d::math::Vector;+ ///+ /// // Create a zigzag path with automatic sequential connections+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 1.0, 0.0),+ /// Vector::new(2.0, 0.0, 0.0),+ /// Vector::new(3.0, 1.0, 0.0),+ /// ];+ /// let polyline = Polyline::new(vertices, None);+ /// assert_eq!(polyline.num_segments(), 3);+ /// # }+ /// ```+ ///+ /// # Custom Connectivity Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::Polyline;+ /// use parry2d::math::Vector;+ ///+ /// // Create a square with custom indices+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0),+ /// Vector::new(1.0, 1.0),+ /// Vector::new(0.0, 1.0),+ /// ];+ ///+ /// // Define edges to form a closed square+ /// let indices = vec![+ /// [0, 1], [1, 2], [2, 3], [3, 0]+ /// ];+ ///+ /// let square = Polyline::new(vertices, Some(indices));+ /// assert_eq!(square.num_segments(), 4);+ ///+ /// // Each segment connects the correct vertices+ /// let first_segment = square.segment(0);+ /// assert_eq!(first_segment.a, Vector::ZERO);+ /// assert_eq!(first_segment.b, Vector::new(1.0, 0.0));+ /// # }+ /// ```+ pub fn new(vertices: Vec<Vector>, indices: Option<Vec<[u32; 2]>>) -> Self {+ // Index from 1 so empty input produces no segments instead of underflowing on `len - 1`.+ let indices =+ indices.unwrap_or_else(|| (1..vertices.len() as u32).map(|i| [i - 1, i]).collect());+ let leaves = indices.iter().enumerate().map(|(i, idx)| {+ let aabb =+ Segment::new(vertices[idx[0] as usize], vertices[idx[1] as usize]).local_aabb();+ (i, aabb)+ });++ // NOTE: we apply no dilation factor because we won't+ // update this tree dynamically.+ let bvh = Bvh::from_iter(BvhBuildStrategy::Binned, leaves);++ Self {+ bvh,+ vertices,+ indices,+ #[cfg(feature = "dim2")]+ pseudo_normals: None,+ flags: PolylineFlags::empty(),+ }+ }++ /// Creates a new polyline with the given [`PolylineFlags`] controlling its optional associated+ /// data, e.g. orientation via `PolylineFlags::ORIENTED` (2D only).+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::{Polyline, PolylineFlags};+ /// use parry2d::math::Vector;+ ///+ /// // A unit square wound counter-clockwise, so the solid is inside and outward points away.+ /// let vertices = vec![+ /// Vector::new(-1.0, -1.0),+ /// Vector::new(1.0, -1.0),+ /// Vector::new(1.0, 1.0),+ /// Vector::new(-1.0, 1.0),+ /// ];+ /// let indices = vec![[0, 1], [1, 2], [2, 3], [3, 0]];+ /// let polyline = Polyline::with_flags(vertices, Some(indices), PolylineFlags::ORIENTED);+ ///+ /// // The bottom edge's outward normal points down, away from the interior.+ /// let bottom = polyline.segment_normal_constraints(0).unwrap();+ /// assert!(bottom.face.abs_diff_eq(Vector::new(0.0, -1.0), 1.0e-5));+ /// # }+ /// ```+ pub fn with_flags(+ vertices: Vec<Vector>,+ indices: Option<Vec<[u32; 2]>>,+ flags: PolylineFlags,+ ) -> Self {+ let mut result = Self::new(vertices, indices);+ result.set_flags(flags);+ result+ }++ /// Sets the [`PolylineFlags`], computing or discarding the polyline's optional associated data.+ pub fn set_flags(&mut self, flags: PolylineFlags) {+ self.flags = flags;++ #[cfg(feature = "dim2")]+ if flags.contains(PolylineFlags::ORIENTED) {+ self.compute_pseudo_normals();+ } else {+ self.pseudo_normals = None;+ }+ }++ /// The [`PolylineFlags`] controlling this polyline's optional associated data.+ pub fn flags(&self) -> PolylineFlags {+ self.flags+ }++ /// Replaces the vertex positions in place, keeping the index buffer.+ ///+ /// The BVH is refitted (not rebuilt) and the pseudo-normals, if any, are recomputed. This+ /// is the update path of a deformable polyline: `vertices.len()` must equal+ /// [`Self::vertices`]`.len()`.+ ///+ /// # Panics+ ///+ /// Panics if `vertices.len()` differs from the current number of vertices.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::{Polyline, PolylineFlags};+ /// use parry2d::math::Vector;+ ///+ /// let vertices = vec![Vector::ZERO, Vector::new(1.0, 0.0), Vector::new(2.0, 0.0)];+ /// let mut polyline = Polyline::with_flags(vertices, None, PolylineFlags::DEFORMABLE);+ ///+ /// // Lift the middle vertex.+ /// polyline.set_vertices(&[Vector::ZERO, Vector::new(1.0, 1.0), Vector::new(2.0, 0.0)]);+ /// assert_eq!(polyline.local_aabb().maxs, Vector::new(2.0, 1.0));+ /// # }+ /// ```+ pub fn set_vertices(&mut self, vertices: &[Vector]) {+ assert_eq!(+ vertices.len(),+ self.vertices.len(),+ "Polyline::set_vertices: the number of vertices must not change."+ );+ self.update_vertices(|vtx| vtx.copy_from_slice(vertices));+ }++ /// Modifies the vertex positions in place through `f`, then refits the BVH and recomputes+ /// the pseudo-normals, if any (see [`Self::set_vertices`]).+ pub fn update_vertices(&mut self, f: impl FnOnce(&mut [Vector])) {+ f(&mut self.vertices);++ for (i, idx) in self.indices.iter().enumerate() {+ let aabb = Segment::new(+ self.vertices[idx[0] as usize],+ self.vertices[idx[1] as usize],+ )+ .local_aabb();+ let _ = self.bvh.insert_or_update_partially(aabb, i as u32, 0.0);+ }+ self.bvh.refit_without_opt();++ #[cfg(feature = "dim2")]+ if self.pseudo_normals.is_some() {+ self.compute_pseudo_normals();+ }+ }++ /// Computes the outward pseudo-normal at every vertex (the normalized sum of its incident+ /// segments' outward normals) for the one-sided behavior of [`PolylineFlags::ORIENTED`].+ #[cfg(feature = "dim2")]+ fn compute_pseudo_normals(&mut self) {+ let mut vertex_normals = Vec::new();+ vertex_normals.resize(self.vertices.len(), Vector::ZERO);++ // A 2D vertex has at most two incident segments, so the normalized sum is their exact+ // bisector -- no angle weighting (unlike the 3D `TrianglePseudoNormals`).+ for idx in &self.indices {+ let a = idx[0] as usize;+ let b = idx[1] as usize;+ let normal = crate::utils::ccw_face_normal([self.vertices[a], self.vertices[b]])+ .unwrap_or(Vector::ZERO);+ vertex_normals[a] += normal;+ vertex_normals[b] += normal;+ }++ for normal in &mut vertex_normals {+ *normal = normal.normalize_or_zero();+ }++ self.pseudo_normals = Some(vertex_normals);+ }++ /// The outward pseudo-normal of every vertex, if they have been computed (i.e. if this+ /// polyline was built with [`PolylineFlags::ORIENTED`]).+ ///+ /// The returned slice is indexed by vertex index, like [`Self::vertices`].+ #[cfg(feature = "dim2")]+ pub fn pseudo_normals(&self) -> Option<&[Vector]> {+ self.pseudo_normals.as_deref()+ }++ /// Returns the [`SegmentPseudoNormals`] for the segment with index `i`, or `None` unless this+ /// polyline was built with [`PolylineFlags::ORIENTED`].+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::{Polyline, PolylineFlags};+ /// use parry2d::math::Vector;+ ///+ /// let vertices = vec![Vector::new(0.0, 0.0), Vector::new(2.0, 0.0), Vector::new(2.0, 2.0)];+ /// let mut polyline = Polyline::new(vertices, Some(vec![[0, 1], [1, 2]]));+ ///+ /// // A double-sided polyline has no constraints...+ /// assert!(polyline.segment_normal_constraints(0).is_none());+ ///+ /// // ...until it is oriented.+ /// polyline.set_flags(PolylineFlags::ORIENTED);+ /// assert!(polyline.segment_normal_constraints(0).is_some());+ /// # }+ /// ```+ #[cfg(feature = "dim2")]+ pub fn segment_normal_constraints(&self, i: u32) -> Option<SegmentPseudoNormals> {+ let pseudo_normals = self.pseudo_normals.as_ref()?;+ let idx = self.indices[i as usize];+ let a = idx[0] as usize;+ let b = idx[1] as usize;+ let face = crate::utils::ccw_face_normal([self.vertices[a], self.vertices[b]])?;+ Some(SegmentPseudoNormals {+ face,+ edges: [pseudo_normals[a], pseudo_normals[b]],+ })+ }++ /// Pseudo-normals are a 2D-only feature; in 3D there are no segment normal constraints. 3D stub+ /// so the composite-shape impls compile; mirrors `TriMesh::triangle_normal_constraints`'s dim2+ /// stub.+ #[cfg(feature = "dim3")]+ #[doc(hidden)]+ pub fn segment_normal_constraints(&self, _i: u32) -> Option<SegmentPseudoNormals> {+ None+ }++ /// Computes the axis-aligned bounding box of this polyline in world space.+ ///+ /// The AABB is the smallest box aligned with the world axes that fully contains+ /// the polyline after applying the given position/rotation transformation.+ ///+ /// # Arguments+ ///+ /// * `pos` - The position and orientation (isometry) of the polyline in world space+ ///+ /// # Returns+ ///+ /// An `Aabb` that bounds the transformed polyline+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Polyline;+ /// use parry3d::math::{Vector, Pose};+ ///+ /// // Create a polyline along the X axis+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(2.0, 0.0, 0.0),+ /// ];+ /// let polyline = Polyline::new(vertices, None);+ ///+ /// // Compute AABB at the origin+ /// let identity = Pose::identity();+ /// let aabb = polyline.aabb(&identity);+ /// assert_eq!(aabb.mins.x, 0.0);+ /// assert_eq!(aabb.maxs.x, 2.0);+ ///+ /// // Compute AABB after translating by (10, 5, 0)+ /// let translated = Pose::translation(10.0, 5.0, 0.0);+ /// let aabb_translated = polyline.aabb(&translated);+ /// assert_eq!(aabb_translated.mins.x, 10.0);+ /// assert_eq!(aabb_translated.maxs.x, 12.0);+ /// # }+ /// ```+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ self.bvh.root_aabb().transform_by(pos)+ }++ /// Gets the local axis-aligned bounding box of this polyline.+ ///+ /// This returns the AABB in the polyline's local coordinate system (before any+ /// transformation is applied). It's more efficient than `aabb()` when you don't+ /// need to transform the polyline.+ ///+ /// # Returns+ ///+ /// An `Aabb` that bounds the polyline in local space+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::Polyline;+ /// use parry2d::math::Vector;+ ///+ /// // Create a rectangular polyline+ /// let vertices = vec![+ /// Vector::new(-1.0, -2.0),+ /// Vector::new(3.0, -2.0),+ /// Vector::new(3.0, 4.0),+ /// Vector::new(-1.0, 4.0),+ /// ];+ /// let polyline = Polyline::new(vertices, None);+ ///+ /// // Get the local AABB+ /// let aabb = polyline.local_aabb();+ ///+ /// // The AABB should contain all vertices+ /// assert_eq!(aabb.mins.x, -1.0);+ /// assert_eq!(aabb.mins.y, -2.0);+ /// assert_eq!(aabb.maxs.x, 3.0);+ /// assert_eq!(aabb.maxs.y, 4.0);+ /// # }+ /// ```+ pub fn local_aabb(&self) -> Aabb {+ self.bvh.root_aabb()+ }++ /// The BVH acceleration structure for this polyline.+ pub fn bvh(&self) -> &Bvh {+ &self.bvh+ }++ /// Returns the number of segments (edges) in this polyline.+ ///+ /// Each segment connects two vertices. For a polyline with `n` vertices and+ /// sequential connectivity, there are `n-1` segments. For custom connectivity,+ /// the number of segments equals the number of index pairs.+ ///+ /// # Returns+ ///+ /// The total number of line segments+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Polyline;+ /// use parry3d::math::Vector;+ ///+ /// // Sequential polyline: 5 vertices -> 4 segments+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(2.0, 0.0, 0.0),+ /// Vector::new(3.0, 0.0, 0.0),+ /// Vector::new(4.0, 0.0, 0.0),+ /// ];+ /// let polyline = Polyline::new(vertices.clone(), None);+ /// assert_eq!(polyline.num_segments(), 4);+ ///+ /// // Custom connectivity: can have different number of segments+ /// let indices = vec![[0, 4], [1, 3]]; // Only 2 segments+ /// let custom = Polyline::new(vertices, Some(indices));+ /// assert_eq!(custom.num_segments(), 2);+ /// # }+ /// ```+ pub fn num_segments(&self) -> usize {+ self.indices.len()+ }++ /// Returns an iterator over all segments in this polyline.+ ///+ /// Each segment is returned as a [`Segment`] object with two endpoints.+ /// The iterator yields exactly `num_segments()` items.+ ///+ /// # Returns+ ///+ /// An exact-size iterator that yields `Segment` instances+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::Polyline;+ /// use parry2d::math::Vector;+ ///+ /// // Create a triangle+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0),+ /// Vector::new(0.5, 1.0),+ /// ];+ /// let polyline = Polyline::new(vertices, None);+ ///+ /// // Iterate over all segments+ /// let mut total_length = 0.0;+ /// for segment in polyline.segments() {+ /// total_length += segment.length();+ /// }+ ///+ /// // Calculate expected perimeter (not closed, so 2 sides only)+ /// assert!(total_length > 2.0);+ ///+ /// // Collect all segments into a vector+ /// let segments: Vec<_> = polyline.segments().collect();+ /// assert_eq!(segments.len(), 2);+ /// # }+ /// ```+ pub fn segments(&self) -> impl ExactSizeIterator<Item = Segment> + '_ {+ self.indices.iter().map(move |ids| {+ Segment::new(+ self.vertices[ids[0] as usize],+ self.vertices[ids[1] as usize],+ )+ })+ }++ /// Returns the segment at the given index.+ ///+ /// This retrieves a specific segment by its index. Indices range from `0` to+ /// `num_segments() - 1`. If you need to access multiple segments, consider+ /// using the `segments()` iterator instead.+ ///+ /// # Arguments+ ///+ /// * `i` - The index of the segment to retrieve (0-based)+ ///+ /// # Returns+ ///+ /// A `Segment` representing the edge at index `i`+ ///+ /// # Panics+ ///+ /// Panics if `i >= num_segments()`+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Polyline;+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(2.0, 1.0, 0.0),+ /// ];+ /// let polyline = Polyline::new(vertices, None);+ ///+ /// // Get the first segment (connects vertex 0 to vertex 1)+ /// let seg0 = polyline.segment(0);+ /// assert_eq!(seg0.a, Vector::ZERO);+ /// assert_eq!(seg0.b, Vector::new(1.0, 0.0, 0.0));+ /// assert_eq!(seg0.length(), 1.0);+ ///+ /// // Get the second segment (connects vertex 1 to vertex 2)+ /// let seg1 = polyline.segment(1);+ /// assert_eq!(seg1.a, Vector::new(1.0, 0.0, 0.0));+ /// assert_eq!(seg1.b, Vector::new(2.0, 1.0, 0.0));+ /// # }+ /// ```+ pub fn segment(&self, i: u32) -> Segment {+ let idx = self.indices[i as usize];+ Segment::new(+ self.vertices[idx[0] as usize],+ self.vertices[idx[1] as usize],+ )+ }++ /// Converts a FeatureId of the segment `segment` into a FeatureId of the whole polyline.+ ///+ /// An endpoint becomes the polyline vertex it indexes, so the two segments meeting at a corner+ /// agree on it. In 2D a segment has a side facing each way, and they are numbered like the+ /// segments themselves: the second side of segment `i` is `i + self.indices().len()`.+ pub fn segment_feature_to_polyline_feature(+ &self,+ segment: SubShapeId,+ feature: FeatureId,+ ) -> FeatureId {+ match feature {+ FeatureId::Vertex(endpoint) => {+ FeatureId::Vertex(self.indices[segment as usize][endpoint as usize])+ }+ #[cfg(feature = "dim2")]+ FeatureId::Face(side) => FeatureId::Face(segment + side * self.indices.len() as u32),+ #[cfg(feature = "dim3")]+ FeatureId::Edge(_) => FeatureId::Edge(segment),+ _ => FeatureId::Unknown,+ }+ }++ /// Returns a slice containing all vertices of this polyline.+ ///+ /// Vertices are the points that define the polyline. Segments connect+ /// pairs of these vertices according to the index buffer.+ ///+ /// # Returns+ ///+ /// A slice of all vertex points+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::Polyline;+ /// use parry2d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0),+ /// Vector::new(1.0, 1.0),+ /// ];+ /// let polyline = Polyline::new(vertices.clone(), None);+ ///+ /// // Access all vertices+ /// let verts = polyline.vertices();+ /// assert_eq!(verts.len(), 3);+ /// assert_eq!(verts[0], Vector::ZERO);+ /// assert_eq!(verts[1], Vector::new(1.0, 0.0));+ /// assert_eq!(verts[2], Vector::new(1.0, 1.0));+ ///+ /// // You can iterate over vertices+ /// for (i, vertex) in polyline.vertices().iter().enumerate() {+ /// println!("Vertex {}: {:?}", i, vertex);+ /// }+ /// # }+ /// ```+ pub fn vertices(&self) -> &[Vector] {+ &self.vertices[..]+ }++ /// Returns a slice containing all segment indices.+ ///+ /// Each index is a pair `[u32; 2]` representing a segment connecting two vertices.+ /// The first element is the index of the segment's start vertex, and the second+ /// is the index of the end vertex.+ ///+ /// # Returns+ ///+ /// A slice of all segment index pairs+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Polyline;+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(2.0, 0.0, 0.0),+ /// ];+ ///+ /// // With automatic indices+ /// let polyline = Polyline::new(vertices.clone(), None);+ /// let indices = polyline.indices();+ /// assert_eq!(indices.len(), 2);+ /// assert_eq!(indices[0], [0, 1]); // First segment: vertex 0 -> 1+ /// assert_eq!(indices[1], [1, 2]); // Second segment: vertex 1 -> 2+ ///+ /// // With custom indices+ /// let custom_indices = vec![[0, 2], [1, 0]];+ /// let custom = Polyline::new(vertices, Some(custom_indices));+ /// assert_eq!(custom.indices()[0], [0, 2]);+ /// assert_eq!(custom.indices()[1], [1, 0]);+ /// # }+ /// ```+ pub fn indices(&self) -> &[[u32; 2]] {+ &self.indices+ }++ /// A flat view of the index buffer of this mesh.+ pub fn flat_indices(&self) -> &[u32] {+ unsafe {+ let len = self.indices.len() * 2;+ let data = self.indices.as_ptr() as *const u32;+ core::slice::from_raw_parts(data, len)+ }+ }++ /// Computes a scaled version of this polyline.+ ///+ /// This consumes the polyline and returns a new one with all vertices scaled+ /// component-wise by the given scale vector. The connectivity (indices) remains+ /// unchanged, but the BVH is rebuilt to reflect the new geometry.+ ///+ /// # Arguments+ ///+ /// * `scale` - The scaling factors for each axis+ ///+ /// # Returns+ ///+ /// A new polyline with scaled vertices+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::Polyline;+ /// use parry2d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::new(1.0, 2.0),+ /// Vector::new(3.0, 4.0),+ /// ];+ /// let polyline = Polyline::new(vertices, None);+ ///+ /// // Scale by 2x in X and 3x in Y+ /// let scaled = polyline.scaled(Vector::new(2.0, 3.0));+ ///+ /// // Check scaled vertices+ /// assert_eq!(scaled.vertices()[0], Vector::new(2.0, 6.0));+ /// assert_eq!(scaled.vertices()[1], Vector::new(6.0, 12.0));+ /// # }+ /// ```+ ///+ /// # Note+ ///+ /// This method consumes `self`. If you need to keep the original polyline,+ /// clone it first:+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Polyline;+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![Vector::ZERO, Vector::new(1.0, 0.0, 0.0)];+ /// let original = Polyline::new(vertices, None);+ ///+ /// // Clone before scaling if you need to keep the original+ /// let scaled = original.clone().scaled(Vector::new(2.0, 2.0, 2.0));+ ///+ /// // Both polylines still exist+ /// assert_eq!(original.vertices()[1].x, 1.0);+ /// assert_eq!(scaled.vertices()[1].x, 2.0);+ /// # }+ /// ```+ pub fn scaled(mut self, scale: Vector) -> Self {+ self.vertices.iter_mut().for_each(|pt| *pt *= scale);+ let mut bvh = self.bvh.clone();+ bvh.scale(scale);++ #[cfg(feature = "dim2")]+ {+ let mut result = Self {+ bvh,+ vertices: self.vertices,+ indices: self.indices,+ pseudo_normals: None,+ flags: PolylineFlags::empty(),+ };+ // Recompute the pseudo-normals from the scaled geometry.+ result.set_flags(self.flags);+ result+ }+ #[cfg(feature = "dim3")]+ {+ Self {+ bvh,+ vertices: self.vertices,+ indices: self.indices,+ flags: self.flags,+ }+ }+ }++ /// Reverses the orientation of this polyline.+ ///+ /// This operation:+ /// 1. Swaps the start and end vertex of each segment (reversing edge direction)+ /// 2. Reverses the order of segments in the index buffer+ /// 3. Rebuilds the BVH to maintain correct acceleration structure+ ///+ /// After reversing, traversing the polyline segments in order will visit+ /// the same geometry but in the opposite direction.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::Polyline;+ /// use parry2d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0),+ /// Vector::new(2.0, 0.0),+ /// ];+ /// let mut polyline = Polyline::new(vertices, None);+ ///+ /// // Original: segment 0 goes from vertex 0 to 1, segment 1 from 1 to 2+ /// assert_eq!(polyline.indices()[0], [0, 1]);+ /// assert_eq!(polyline.indices()[1], [1, 2]);+ ///+ /// // Reverse the polyline+ /// polyline.reverse();+ ///+ /// // After reversing: order is flipped and directions are swapped+ /// // The last segment becomes first, with swapped endpoints+ /// assert_eq!(polyline.indices()[0], [2, 1]);+ /// assert_eq!(polyline.indices()[1], [1, 0]);+ /// # }+ /// ```+ ///+ /// # Use Cases+ ///+ /// This is useful for:+ /// - Correcting winding order for 2D shapes+ /// - Reversing path direction for navigation+ /// - Ensuring consistent edge orientation in connected components+ pub fn reverse(&mut self) {+ for idx in &mut self.indices {+ idx.swap(0, 1);+ }++ self.indices.reverse();++ // Rebuild the bvh since the segment indices no longer map to the correct element.+ // TODO PERF: should the Bvh have a function for efficient leaf index remapping?+ // Probably not worth it unless this function starts showing up as a+ // bottleneck for someone.+ let leaves = self.segments().map(|seg| seg.local_aabb()).enumerate();+ let bvh = Bvh::from_iter(BvhBuildStrategy::Binned, leaves);+ self.bvh = bvh;++ // Reversing flips the winding, so recompute the outward side.+ #[cfg(feature = "dim2")]+ if self.flags.contains(PolylineFlags::ORIENTED) {+ self.compute_pseudo_normals();+ }+ }++ /// Extracts the connected components of this polyline, consuming `self`.+ ///+ /// This method is currently quite restrictive on the kind of allowed input. The polyline+ /// represented by `self` must already have an index buffer sorted such that:+ /// - Each connected component appears in the index buffer one after the other, i.e., a+ /// connected component of this polyline must be a contiguous range of this polyline’s+ /// index buffer.+ /// - Each connected component is closed, i.e., each range of this polyline index buffer+ /// `self.indices[i_start..=i_end]` forming a complete connected component, we must have+ /// `self.indices[i_start][0] == self.indices[i_end][1]`.+ /// - The indices for each component must already be in order, i.e., if the segments+ /// `self.indices[i]` and `self.indices[i + 1]` are part of the same connected component then+ /// we must have `self.indices[i][1] == self.indices[i + 1][0]`.+ ///+ /// # Output+ /// Returns the set of polylines. If the inputs fulfill the constraints mentioned above, each+ /// polyline will be a closed loop with consistent edge orientations, i.e., for all indices `i`,+ /// we have `polyline.indices[i][1] == polyline.indices[i + 1][0]`.+ ///+ /// The orientation of each closed loop (clockwise or counterclockwise) are identical to their+ /// original orientation in `self`.+ pub fn extract_connected_components(&self) -> Vec<Polyline> {+ let vertices = self.vertices();+ let indices = self.indices();++ if indices.is_empty() {+ // Polyline is empty, return empty Vec+ Vec::new()+ } else {+ let mut components = Vec::new();++ let mut start_i = 0; // Start position of component+ let mut start_node = indices[0][0]; // Start vertex index of component++ let mut component_vertices = Vec::new();+ let mut component_indices: Vec<[u32; 2]> = Vec::new();++ // Iterate over indices, building polylines as we go+ for (i, idx) in indices.iter().enumerate() {+ component_vertices.push(vertices[idx[0] as usize]);++ if idx[1] != start_node {+ // Keep scanning and adding data+ component_indices.push([(i - start_i) as u32, (i - start_i + 1) as u32]);+ } else {+ // Start node reached: build polyline and start next component+ component_indices.push([(i - start_i) as u32, 0]);+ components.push(Polyline::new(+ core::mem::take(&mut component_vertices),+ Some(core::mem::take(&mut component_indices)),+ ));++ if i + 1 < indices.len() {+ // More components to find+ start_node = indices[i + 1][0];+ start_i = i + 1;+ }+ }+ }++ components+ }+ }++ /// Perform a point projection assuming a solid interior based on a counter-clock-wise orientation.+ ///+ /// This is similar to `self.project_local_point_and_get_location` except that the resulting+ /// `PointProjection::is_inside` will be set to true if the point is inside of the area delimited+ /// by this polyline, assuming that:+ /// - This polyline isn’t self-crossing.+ /// - This polyline is closed with `self.indices[i][1] == self.indices[(i + 1) % num_indices][0]` where+ /// `num_indices == self.indices.len()`.+ /// - This polyline is oriented counter-clockwise.+ /// - In 3D, the polyline is assumed to be fully coplanar, on a plane with normal given by+ /// `axis`.+ ///+ /// These properties are not checked.+ pub fn project_local_point_assuming_solid_interior_ccw(+ &self,+ point: Vector,+ #[cfg(feature = "dim3")] axis: u8,+ ) -> (PointProjection, (u32, SegmentPointLocation)) {+ let mut proj = self.project_local_point_and_get_location(point, false);+ let segment1 = self.segment((proj.1).0);++ #[cfg(feature = "dim2")]+ let normal1 = segment1.normal();+ #[cfg(feature = "dim3")]+ let normal1 = segment1.planar_normal(axis);++ if let Some(normal1) = normal1 {+ proj.0.is_inside = match proj.1 .1 {+ SegmentPointLocation::OnVertex(i) => {+ let dir2 = if i == 0 {+ let adj_seg = if proj.1 .0 == 0 {+ self.indices().len() as u32 - 1+ } else {+ proj.1 .0 - 1+ };++ assert_eq!(segment1.a, self.segment(adj_seg).b);+ -self.segment(adj_seg).scaled_direction()+ } else {+ assert_eq!(i, 1);+ let adj_seg = (proj.1 .0 + 1) % self.indices().len() as u32;+ assert_eq!(segment1.b, self.segment(adj_seg).a);++ self.segment(adj_seg).scaled_direction()+ };++ let dot = normal1.dot(dir2);+ // TODO: is this threshold too big? This corresponds to an angle equal to+ // abs(acos(1.0e-3)) = (90 - 0.057) degrees.+ // We did encounter some cases where this was needed, but perhaps the+ // actual problem was an issue with the SegmentPointLocation (which should+ // perhaps have been Edge instead of Vertex)?+ let threshold = 1.0e-3 * dir2.length();+ if dot.abs() > threshold {+ // If the vertex is a reentrant vertex, then the point is+ // inside. Otherwise, it is outside.+ dot >= 0.0+ } else {+ // If the two edges are collinear, we can’t classify the vertex.+ // So check against the edge’s normal instead.+ (point - proj.0.point).dot(normal1) <= 0.0+ }+ }+ SegmentPointLocation::OnEdge(_) => (point - proj.0.point).dot(normal1) <= 0.0,+ };+ }++ proj+ }+}++impl CompositeShape for Polyline {+ fn map_part_at(+ &self,+ i: u32,+ f: &mut dyn FnMut(Option<&Pose>, &dyn Shape, Option<&dyn NormalConstraints>),+ ) {+ let seg = self.segment(i);+ let normals = self.segment_normal_constraints(i);+ f(+ None,+ &seg,+ normals.as_ref().map(|n| n as &dyn NormalConstraints),+ )+ }++ fn bvh(&self) -> &Bvh {+ &self.bvh+ }++ fn is_deformable(&self) -> bool {+ self.flags.contains(PolylineFlags::DEFORMABLE)+ }+}++impl TypedCompositeShape for Polyline {+ type PartShape = Segment;+ type PartNormalConstraints = SegmentPseudoNormals;++ #[inline(always)]+ fn map_typed_part_at<T>(+ &self,+ i: u32,+ mut f: impl FnMut(Option<&Pose>, &Self::PartShape, Option<&Self::PartNormalConstraints>) -> T,+ ) -> Option<T> {+ let seg = self.segment(i);+ let normals = self.segment_normal_constraints(i);+ Some(f(None, &seg, normals.as_ref()))+ }++ #[inline(always)]+ fn map_untyped_part_at<T>(+ &self,+ i: u32,+ mut f: impl FnMut(Option<&Pose>, &dyn Shape, Option<&dyn NormalConstraints>) -> T,+ ) -> Option<T> {+ let seg = self.segment(i);+ let normals = self.segment_normal_constraints(i);+ Some(f(+ None,+ &seg,+ normals.as_ref().map(|n| n as &dyn NormalConstraints),+ ))+ }+}++#[cfg(test)]+#[cfg(all(feature = "dim2", feature = "alloc"))]+mod pseudo_normal_tests {+ use crate::math::Vector;+ use crate::shape::{Polyline, PolylineFlags};++ fn ccw_square() -> Polyline {+ // CCW unit square: solid inside, outward away from the center.+ let vertices = vec![+ Vector::new(-1.0, -1.0),+ Vector::new(1.0, -1.0),+ Vector::new(1.0, 1.0),+ Vector::new(-1.0, 1.0),+ ];+ Polyline::new(vertices, Some(vec![[0, 1], [1, 2], [2, 3], [3, 0]]))+ }++ #[test]+ fn not_oriented_by_default() {+ assert!(ccw_square().segment_normal_constraints(0).is_none());+ }++ #[test]+ fn face_and_edge_normals_are_unit_and_outward() {+ let mut polyline = ccw_square();+ polyline.set_flags(PolylineFlags::ORIENTED);++ for i in 0..polyline.num_segments() as u32 {+ let segment = polyline.segment(i);+ let constraints = polyline.segment_normal_constraints(i).unwrap();++ assert!((constraints.face.length() - 1.0).abs() < 1.0e-5);+ for edge in constraints.edges {+ assert!((edge.length() - 1.0).abs() < 1.0e-5);+ }++ // The square is centered on the origin, so a midpoint doubles as its outward direction.+ let midpoint = (segment.a + segment.b) * 0.5;+ assert!(constraints.face.dot(midpoint) > 0.0);+ }+ }++ #[test]+ fn corner_pseudo_normal_bisects_its_two_faces() {+ let mut polyline = ccw_square();+ polyline.set_flags(PolylineFlags::ORIENTED);++ // Vertex 1's pseudo-normal bisects the bottom edge (-Y) and right edge (+X): (1, -1) normalized.+ let bottom = polyline.segment_normal_constraints(0).unwrap();+ assert!(bottom.edges[1].abs_diff_eq(Vector::new(1.0, -1.0).normalize(), 1.0e-5));+ }++ #[test]+ fn degenerate_input_yields_no_segments() {+ // Auto-generated indices must not underflow `len - 1` on 0- or 1-vertex input.+ assert_eq!(Polyline::new(vec![], None).num_segments(), 0);+ assert_eq!(Polyline::new(vec![Vector::ZERO], None).num_segments(), 0);+ }++ #[test]+ fn oriented_point_query_treats_interior_as_inside() {+ use crate::query::{PointQuery, PointQueryWithLocation};++ let mut polyline = ccw_square();+ polyline.set_flags(PolylineFlags::ORIENTED);+ let inside = Vector::new(0.25, -0.5);++ // Solid: an inside point is its own projection.+ let solid = polyline.project_local_point(inside, true);+ assert!(solid.is_inside);+ assert!(solid.point.abs_diff_eq(inside, 1.0e-5));++ // Non-solid: still inside, but projected to the boundary.+ let hollow = polyline.project_local_point(inside, false);+ assert!(hollow.is_inside);+ assert!(!hollow.point.abs_diff_eq(inside, 1.0e-5));++ assert!(polyline.contains_local_point(inside));+ assert!(+ polyline+ .project_local_point_and_get_location(inside, false)+ .0+ .is_inside+ );+ assert!(+ polyline+ .project_local_point_and_get_feature(inside)+ .0+ .is_inside+ );+ }++ #[test]+ fn oriented_point_query_leaves_exterior_outside() {+ use crate::query::PointQuery;++ let mut polyline = ccw_square();+ polyline.set_flags(PolylineFlags::ORIENTED);+ let outside = Vector::new(2.0, 0.0);++ let proj = polyline.project_local_point(outside, true);+ assert!(!proj.is_inside);+ assert!(proj.point.abs_diff_eq(Vector::new(1.0, 0.0), 1.0e-5));+ assert!(!polyline.contains_local_point(outside));+ }++ #[test]+ fn unoriented_polyline_has_no_interior() {+ use crate::query::PointQuery;++ // Unoriented: a hollow wireframe with no interior.+ let polyline = ccw_square();+ let center = Vector::ZERO;++ assert!(!polyline.project_local_point(center, true).is_inside);+ assert!(!polyline.contains_local_point(center));+ }+}diff --git a/renderer/third_party/parry3d/src/shape/pseudo_normals.rs b/renderer/third_party/parry3d/src/shape/pseudo_normals.rsnew file mode 100644index 0000000..de27ca1--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/pseudo_normals.rs@@ -0,0 +1,57 @@+use crate::math::Vector;++/// Projects `dir` into the outward cone formed by a feature's `face` normal and its `closest_edge`+/// pseudo-normal, shared by [`TrianglePseudoNormals`](crate::shape::TrianglePseudoNormals) and+/// [`SegmentPseudoNormals`](crate::shape::SegmentPseudoNormals).+///+/// Returns whether `dir` lies in the front half-space; a contact whose normal points into the back+/// is meant to be discarded by the caller.+pub(crate) fn project_into_cone(face: Vector, closest_edge: Vector, dir: &mut Vector) -> bool {+ let dot_face = dir.dot(face);++ // Apply the projection. Note that this isn’t 100% accurate since this approximates the+ // vertex normal cone using the closest edge’s normal cone instead of the+ // true polygonal cone on S² (but taking into account this polygonal cone exactly+ // would be quite computationally expensive).++ if closest_edge == face {+ // The normal cone is degenerate, there is only one possible direction.+ *dir = face;+ return dot_face >= 0.0;+ }++ // TODO: take into account the two closest edges instead for better continuity+ // of vertex normals?+ let dot_edge_face = face.dot(closest_edge);+ let dot_dir_face = face.dot(*dir);+ let dot_corrected_dir_face = 2.0 * dot_edge_face * dot_edge_face - 1.0; // cos(2 * angle(closest_edge, face))++ if dot_dir_face >= dot_corrected_dir_face {+ // The direction is in the pseudo-normal cone. No correction to apply.+ return true;+ }++ // We need to correct.+ let edge_on_normal = face * dot_edge_face;+ let edge_orthogonal_to_normal = closest_edge - edge_on_normal;++ let dir_on_normal = face * dot_dir_face;+ let dir_orthogonal_to_normal = *dir - dir_on_normal;+ let Some(unit_dir_orthogonal_to_normal) = dir_orthogonal_to_normal.try_normalize() else {+ return dot_face >= 0.0;+ };++ // NOTE: the normalization might be redundant as the result vector is guaranteed to be+ // unit sized. Though some rounding errors could throw it off.+ let adjusted_pseudo_normal =+ edge_on_normal + unit_dir_orthogonal_to_normal * edge_orthogonal_to_normal.length();+ let (adjusted_pseudo_normal, length) = adjusted_pseudo_normal.normalize_and_length();+ if length <= 1.0e-6 {+ return dot_face >= 0.0;+ };++ // The reflection of the face normal wrt. the adjusted pseudo-normal gives us the+ // second end of the pseudo-normal cone the direction is projected on.+ *dir = adjusted_pseudo_normal * (2.0 * face.dot(adjusted_pseudo_normal)) - face;+ dot_face >= 0.0+}diff --git a/renderer/third_party/parry3d/src/shape/round_shape.rs b/renderer/third_party/parry3d/src/shape/round_shape.rsnew file mode 100644index 0000000..b2cd8c5--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/round_shape.rs@@ -0,0 +1,345 @@+//! Rounded shapes are shapes with smoothed/rounded borders.+//!+//! This module provides the `RoundShape` wrapper that adds a border radius to any shape,+//! effectively creating a "padded" or "rounded" version of the original shape.++use crate::math::{Real, Vector};+use crate::shape::SupportMap;++#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Copy, Clone, Debug)]+#[repr(C)]+/// A shape with rounded borders.+///+/// # What is a Rounded Shape?+///+/// A `RoundShape` wraps an existing shape and adds a "border radius" around it. This creates+/// a smooth, rounded version of the original shape by effectively expanding it outward by+/// the border radius distance. Think of it as adding padding or a cushion around the shape.+///+/// The rounding is achieved by using Minkowski sum operations: any point on the surface of+/// the rounded shape is computed by taking a point on the original shape's surface and moving+/// it outward along the surface normal by the border radius distance.+///+/// # Common Use Cases+///+/// - **Creating softer collisions**: Rounded shapes can make collision detection more forgiving+/// and realistic, as sharp corners and edges are smoothed out.+/// - **Capsule-like shapes**: You can create capsule variations of any shape by adding a+/// border radius (e.g., a rounded cuboid becomes similar to a capsule).+/// - **Visual aesthetics**: Rounded shapes often look more pleasing and natural than sharp-edged+/// shapes.+/// - **Improved numerical stability**: Rounded shapes can sometimes be more numerically stable+/// in collision detection algorithms since they avoid sharp corners.+///+/// # Examples+///+/// ## Creating a Rounded Cuboid+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # #[cfg(feature = "f32")]+/// use parry3d::shape::{RoundShape, Cuboid};+/// # #[cfg(feature = "f64")]+/// use parry3d_f64::shape::{RoundShape, Cuboid};+/// use parry3d::math::Vector;+///+/// // Create a cuboid with half-extents of 1.0 in each direction+/// let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+///+/// // Add a border radius of 0.2 to create a rounded cuboid+/// let rounded_cuboid = RoundShape {+/// inner_shape: cuboid,+/// border_radius: 0.2,+/// };+///+/// // The effective size is now 1.2 in each direction from the center+/// // (1.0 from the cuboid + 0.2 from the border)+/// assert_eq!(rounded_cuboid.inner_shape.half_extents.x, 1.0);+/// assert_eq!(rounded_cuboid.border_radius, 0.2);+/// # }+/// ```+///+/// ## Creating a Rounded Triangle (2D)+///+/// ```rust+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # #[cfg(feature = "f32")]+/// use parry2d::shape::{RoundShape, Triangle};+/// # #[cfg(feature = "f64")]+/// use parry2d_f64::shape::{RoundShape, Triangle};+/// use parry2d::math::Vector;+///+/// // Create a triangle+/// let triangle = Triangle::new(+/// Vector::ZERO,+/// Vector::new(1.0, 0.0),+/// Vector::new(0.0, 1.0),+/// );+///+/// // Add rounding with a 0.1 border radius+/// let rounded_triangle = RoundShape {+/// inner_shape: triangle,+/// border_radius: 0.1,+/// };+///+/// // The rounded triangle will have smooth, curved edges instead of sharp corners+/// assert_eq!(rounded_triangle.border_radius, 0.1);+/// # }+/// ```+///+/// ## Comparing Support Vectors+///+/// This example shows how the border radius affects the support point calculation:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # #[cfg(feature = "f32")]+/// use parry3d::shape::{RoundShape, Cuboid, SupportMap};+/// # #[cfg(feature = "f64")]+/// use parry3d_f64::shape::{RoundShape, Cuboid, SupportMap};+/// use parry3d::math::Vector;+///+/// let cuboid = Cuboid::new(Vector::splat(1.0));+/// let rounded_cuboid = RoundShape {+/// inner_shape: cuboid,+/// border_radius: 0.5,+/// };+///+/// // Query the support point in the direction (1, 1, 1)+/// let direction = Vector::new(1.0, 1.0, 1.0);+/// let support_point = rounded_cuboid.local_support_point(direction);+///+/// // The support point will be further out than the original cuboid's support point+/// // due to the border radius+/// let cuboid_support = cuboid.local_support_point(direction);+///+/// // The rounded shape extends further in all directions+/// assert!(support_point.x > cuboid_support.x);+/// assert!(support_point.y > cuboid_support.y);+/// assert!(support_point.z > cuboid_support.z);+/// # }+/// ```+///+/// ## Using with Different Shape Types+///+/// `RoundShape` can wrap any shape that implements the `SupportMap` trait:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # #[cfg(feature = "f32")]+/// use parry3d::shape::{RoundShape, Ball, Segment, SupportMap};+/// # #[cfg(feature = "f64")]+/// use parry3d_f64::shape::{RoundShape, Ball, Segment, SupportMap};+/// use parry3d::math::Vector;+///+/// // Rounded ball (creates a slightly larger sphere)+/// let ball = Ball::new(1.0);+/// let rounded_ball = RoundShape {+/// inner_shape: ball,+/// border_radius: 0.1,+/// };+/// // Effective radius is now 1.1+///+/// // Rounded segment (creates a capsule)+/// let segment = Segment::new(+/// Vector::ZERO,+/// Vector::new(0.0, 2.0, 0.0),+/// );+/// let rounded_segment = RoundShape {+/// inner_shape: segment,+/// border_radius: 0.5,+/// };+/// // This creates a capsule with radius 0.5+/// # }+/// ```+///+/// # Performance Considerations+///+/// - The computational cost of queries on a `RoundShape` is essentially the same as for the+/// inner shape, plus a small constant overhead to apply the border radius.+/// - `RoundShape` is most efficient when used with shapes that already implement `SupportMap`+/// efficiently (like primitives: Ball, Cuboid, Capsule, etc.).+/// - The struct is `Copy` when the inner shape is `Copy`, making it efficient to pass around.+///+/// # Technical Details+///+/// The `RoundShape` implements the `SupportMap` trait by computing the support point of the+/// inner shape and then offsetting it by the border radius in the query direction. This is+/// mathematically equivalent to computing the Minkowski sum of the inner shape with a ball+/// of radius equal to the border radius.+pub struct RoundShape<S> {+ /// The shape being rounded.+ ///+ /// This is the original, "inner" shape before the border radius is applied.+ /// The rounded shape's surface will be at a distance of `border_radius` from+ /// this inner shape's surface.+ pub inner_shape: S,++ /// The radius of the rounded border.+ ///+ /// This value determines how much the shape is expanded outward. A larger border+ /// radius creates a more "padded" shape. Must be non-negative (typically positive).+ ///+ /// For example, if `border_radius` is 0.5, every point on the original shape's+ /// surface will be moved 0.5 units outward along its surface normal.+ pub border_radius: Real,+}++impl<S: SupportMap> SupportMap for RoundShape<S> {+ /// Computes the support point of the rounded shape in the given direction.+ ///+ /// The support point is the point on the shape's surface that is furthest in the+ /// given direction. For a rounded shape, this is computed by:+ /// 1. Finding the support point of the inner shape in the given direction+ /// 2. Moving that point outward by `border_radius` units along the direction+ ///+ /// # Parameters+ ///+ /// * `dir` - The direction vector (will be normalized internally)+ ///+ /// # Returns+ ///+ /// The point on the rounded shape's surface that is furthest in the given direction.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # #[cfg(feature = "f32")]+ /// use parry3d::shape::{RoundShape, Cuboid, SupportMap};+ /// # #[cfg(feature = "f64")]+ /// use parry3d_f64::shape::{RoundShape, Cuboid, SupportMap};+ /// use parry3d::math::Vector;+ ///+ /// let cuboid = Cuboid::new(Vector::splat(1.0));+ /// let rounded = RoundShape {+ /// inner_shape: cuboid,+ /// border_radius: 0.5,+ /// };+ ///+ /// // Support point in the positive X direction+ /// let dir = Vector::new(1.0, 0.0, 0.0);+ /// let support = rounded.local_support_point(dir);+ ///+ /// // The X coordinate is the cuboid's half-extent plus the border radius+ /// assert!((support.x - 1.5).abs() < 1e-6);+ /// # }+ /// ```+ fn local_support_point(&self, dir: Vector) -> Vector {+ self.local_support_point_toward(dir.normalize())+ }++ /// Computes the support point of the rounded shape toward the given unit direction.+ ///+ /// This is similar to `local_support_point` but takes a pre-normalized direction vector,+ /// which can be more efficient when the direction is already normalized.+ ///+ /// The implementation adds the border radius offset to the inner shape's support point:+ /// `support_point = inner_support_point + direction * border_radius`+ ///+ /// # Parameters+ ///+ /// * `dir` - A unit-length direction vector+ ///+ /// # Returns+ ///+ /// The point on the rounded shape's surface that is furthest in the given direction.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::{RoundShape, Ball, SupportMap};+ /// use parry2d::math::Vector;+ ///+ /// let ball = Ball::new(1.0);+ /// let rounded = RoundShape {+ /// inner_shape: ball,+ /// border_radius: 0.3,+ /// };+ ///+ /// // Create a unit direction+ /// let dir = Vector::new(1.0, 1.0).normalize();+ /// let support = rounded.local_support_point_toward(dir);+ ///+ /// // The distance from origin should be ball radius + border radius+ /// let distance = (support.x.powi(2) + support.y.powi(2)).sqrt();+ /// assert!((distance - 1.3).abs() < 1e-6);+ /// # }+ /// ```+ fn local_support_point_toward(&self, dir: Vector) -> Vector {+ self.inner_shape.local_support_point_toward(dir) + dir * self.border_radius+ }+}++/// A shape reference with rounded borders.+///+/// This is an internal helper struct that provides the same rounding functionality as+/// `RoundShape`, but works with a borrowed reference to a shape instead of owning the shape.+/// This is useful in contexts where you want to temporarily treat a shape reference as+/// a rounded shape without creating a new allocation.+///+/// # Differences from `RoundShape`+///+/// - `RoundShapeRef` stores a reference (`&'a S`) instead of owning the shape+/// - It's marked `pub(crate)`, meaning it's only used internally within the Parry library+/// - The lifetime `'a` ensures the reference remains valid for the duration of use+/// - Works with unsized types (`S: ?Sized`), allowing it to work with trait objects+///+/// # Internal Use+///+/// This struct is primarily used internally by Parry for implementing collision detection+/// algorithms efficiently, where creating temporary rounded views of shapes is needed without+/// the overhead of cloning or moving data.+pub(crate) struct RoundShapeRef<'a, S: ?Sized> {+ /// The shape being rounded (borrowed reference).+ ///+ /// This is a reference to the inner shape, allowing the rounded view to be created+ /// without taking ownership or cloning the shape data.+ pub inner_shape: &'a S,++ /// The radius of the rounded border.+ ///+ /// Same semantics as in `RoundShape` - determines how much the shape is expanded outward.+ pub border_radius: Real,+}++impl<S: ?Sized + SupportMap> SupportMap for RoundShapeRef<'_, S> {+ /// Computes the support point of the rounded shape reference in the given direction.+ ///+ /// Behaves identically to `RoundShape::local_support_point`, but operates on a+ /// borrowed shape reference.+ ///+ /// # Parameters+ ///+ /// * `dir` - The direction vector (will be normalized internally)+ ///+ /// # Returns+ ///+ /// The point on the rounded shape's surface that is furthest in the given direction.+ fn local_support_point(&self, dir: Vector) -> Vector {+ self.local_support_point_toward(dir.normalize())+ }++ /// Computes the support point of the rounded shape reference toward the given unit direction.+ ///+ /// Behaves identically to `RoundShape::local_support_point_toward`, but operates on a+ /// borrowed shape reference. The implementation is the same: add the border radius offset+ /// to the inner shape's support point.+ ///+ /// # Parameters+ ///+ /// * `dir` - A unit-length direction vector+ ///+ /// # Returns+ ///+ /// The point on the rounded shape's surface that is furthest in the given direction.+ fn local_support_point_toward(&self, dir: Vector) -> Vector {+ self.inner_shape.local_support_point_toward(dir) + dir * self.border_radius+ }+}diff --git a/renderer/third_party/parry3d/src/shape/segment.rs b/renderer/third_party/parry3d/src/shape/segment.rsnew file mode 100644index 0000000..bae9180--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/segment.rs@@ -0,0 +1,695 @@+//! Definition of the segment shape.++#[cfg(feature = "dim3")]+use crate::math::VectorExt;+use crate::math::{Pose, Real, Vector};+use crate::shape::{FeatureId, SupportMap};+use core::mem;++/// A line segment shape.+///+/// A segment is the simplest 1D shape, defined by two endpoints. It represents+/// a straight line between two points with no thickness or volume.+///+/// # Structure+///+/// - **a**: The first endpoint+/// - **b**: The second endpoint+/// - **Direction**: Vectors from `a` toward `b`+///+/// # Properties+///+/// - **1-dimensional**: Has length but no width or volume+/// - **Convex**: Always convex+/// - **No volume**: Mass properties are zero+/// - **Simple**: Very fast collision detection+///+/// # Use Cases+///+/// Segments are commonly used for:+/// - **Thin objects**: Ropes, wires, laser beams+/// - **Skeletal animation**: Bone connections+/// - **Path representation**: Straight-line paths+/// - **Geometry building block**: Part of polylines and meshes+/// - **Testing**: Simple shape for debugging+///+/// # Note+///+/// For shapes with thickness, consider using [`Capsule`](super::Capsule) instead,+/// which is a segment with a radius (rounded cylinder).+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Segment;+/// use parry3d::math::Vector;+///+/// // Create a horizontal segment of length 5+/// let a = Vector::ZERO;+/// let b = Vector::new(5.0, 0.0, 0.0);+/// let segment = Segment::new(a, b);+///+/// assert_eq!(segment.length(), 5.0);+/// assert_eq!(segment.a, a);+/// assert_eq!(segment.b, b);+/// # }+/// ```+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]+#[cfg_attr(feature = "encase", derive(encase::ShaderType))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(PartialEq, Debug, Copy, Clone)]+#[repr(C)]+pub struct Segment {+ /// The first endpoint of the segment.+ pub a: Vector,+ /// The second endpoint of the segment.+ pub b: Vector,+}++/// Describes where a point is located on a segment.+///+/// This enum is used by point projection queries to indicate whether the+/// projected point is at one of the endpoints or somewhere along the segment.+///+/// # Variants+///+/// - **OnVertex(id)**: Vector projects to an endpoint (0 = `a`, 1 = `b`)+/// - **OnEdge(bary)**: Vector projects to the interior with barycentric coordinates+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::SegmentPointLocation;+///+/// // Vector at first vertex+/// let loc = SegmentPointLocation::OnVertex(0);+/// assert_eq!(loc.barycentric_coordinates(), [1.0, 0.0]);+///+/// // Vector at second vertex+/// let loc = SegmentPointLocation::OnVertex(1);+/// assert_eq!(loc.barycentric_coordinates(), [0.0, 1.0]);+///+/// // Vector halfway along the segment+/// let loc = SegmentPointLocation::OnEdge([0.5, 0.5]);+/// assert_eq!(loc.barycentric_coordinates(), [0.5, 0.5]);+/// # }+/// ```+#[derive(PartialEq, Debug, Clone, Copy)]+pub enum SegmentPointLocation {+ /// The point lies on a vertex (endpoint).+ ///+ /// - `0` = Vector is at `segment.a`+ /// - `1` = Vector is at `segment.b`+ OnVertex(u32),++ /// The point lies on the segment interior.+ ///+ /// Contains barycentric coordinates `[u, v]` where:+ /// - `u + v = 1.0`+ /// - Vector = `a * u + b * v`+ /// - `0.0 < u, v < 1.0` (strictly between endpoints)+ OnEdge([Real; 2]),+}++impl SegmentPointLocation {+ /// Returns the barycentric coordinates corresponding to this location.+ ///+ /// Barycentric coordinates `[u, v]` satisfy:+ /// - `u + v = 1.0`+ /// - Vector = `a * u + b * v`+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{Segment, SegmentPointLocation};+ /// use parry3d::math::Vector;+ ///+ /// let segment = Segment::new(+ /// Vector::ZERO,+ /// Vector::new(10.0, 0.0, 0.0)+ /// );+ ///+ /// // Vector at endpoint a+ /// let loc_a = SegmentPointLocation::OnVertex(0);+ /// assert_eq!(loc_a.barycentric_coordinates(), [1.0, 0.0]);+ ///+ /// // Vector at endpoint b+ /// let loc_b = SegmentPointLocation::OnVertex(1);+ /// assert_eq!(loc_b.barycentric_coordinates(), [0.0, 1.0]);+ ///+ /// // Vector at 30% from a to b+ /// let loc_mid = SegmentPointLocation::OnEdge([0.7, 0.3]);+ /// let coords = loc_mid.barycentric_coordinates();+ /// assert_eq!(coords[0], 0.7);+ /// assert_eq!(coords[1], 0.3);+ /// # }+ /// ```+ pub fn barycentric_coordinates(&self) -> [Real; 2] {+ let mut bcoords = [0.0; 2];++ match self {+ SegmentPointLocation::OnVertex(i) => bcoords[*i as usize] = 1.0,+ SegmentPointLocation::OnEdge(uv) => {+ bcoords[0] = uv[0];+ bcoords[1] = uv[1];+ }+ }++ bcoords+ }+}++impl Segment {+ /// Creates a new segment from two endpoints.+ ///+ /// # Arguments+ ///+ /// * `a` - The first endpoint+ /// * `b` - The second endpoint+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Segment;+ /// use parry3d::math::Vector;+ ///+ /// let segment = Segment::new(+ /// Vector::ZERO,+ /// Vector::new(5.0, 0.0, 0.0)+ /// );+ /// assert_eq!(segment.length(), 5.0);+ /// # }+ /// ```+ #[inline]+ pub fn new(a: Vector, b: Vector) -> Segment {+ Segment { a, b }+ }++ /// Creates a segment reference from an array of two points.+ ///+ /// This is a zero-cost conversion using memory transmutation.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Segment;+ /// use parry3d::math::Vector;+ ///+ /// let points = [Vector::ZERO, Vector::new(1.0, 0.0, 0.0)];+ /// let segment = Segment::from_array(&points);+ /// assert_eq!(segment.a, points[0]);+ /// assert_eq!(segment.b, points[1]);+ /// # }+ /// ```+ pub fn from_array(arr: &[Vector; 2]) -> &Segment {+ unsafe { mem::transmute(arr) }+ }++ /// Computes a scaled version of this segment.+ ///+ /// Each endpoint is scaled component-wise by the scale vector.+ ///+ /// # Arguments+ ///+ /// * `scale` - The scaling factors for each axis+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Segment;+ /// use parry3d::math::Vector;+ ///+ /// let segment = Segment::new(+ /// Vector::new(1.0, 2.0, 3.0),+ /// Vector::new(4.0, 5.0, 6.0)+ /// );+ ///+ /// let scaled = segment.scaled(Vector::new(2.0, 2.0, 2.0));+ /// assert_eq!(scaled.a, Vector::new(2.0, 4.0, 6.0));+ /// assert_eq!(scaled.b, Vector::new(8.0, 10.0, 12.0));+ /// # }+ /// ```+ pub fn scaled(self, scale: Vector) -> Self {+ Self::new(self.a * scale, self.b * scale)+ }++ /// Returns the direction vector of this segment scaled by its length.+ ///+ /// This is equivalent to `b - a` and points from `a` toward `b`.+ /// The magnitude equals the segment length.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Segment;+ /// use parry3d::math::Vector;+ ///+ /// let segment = Segment::new(+ /// Vector::ZERO,+ /// Vector::new(3.0, 4.0, 0.0)+ /// );+ ///+ /// let dir = segment.scaled_direction();+ /// assert_eq!(dir, Vector::new(3.0, 4.0, 0.0));+ /// assert_eq!(dir.length(), 5.0); // Length of the segment+ /// # }+ /// ```+ pub fn scaled_direction(&self) -> Vector {+ self.b - self.a+ }++ /// Returns the length of this segment.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Segment;+ /// use parry3d::math::Vector;+ ///+ /// // 3-4-5 right triangle+ /// let segment = Segment::new(+ /// Vector::ZERO,+ /// Vector::new(3.0, 4.0, 0.0)+ /// );+ /// assert_eq!(segment.length(), 5.0);+ /// # }+ /// ```+ pub fn length(&self) -> Real {+ self.scaled_direction().length()+ }++ /// Swaps the two endpoints of this segment.+ ///+ /// After swapping, `a` becomes `b` and `b` becomes `a`.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Segment;+ /// use parry3d::math::Vector;+ ///+ /// let mut segment = Segment::new(+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(5.0, 0.0, 0.0)+ /// );+ ///+ /// segment.swap();+ /// assert_eq!(segment.a, Vector::new(5.0, 0.0, 0.0));+ /// assert_eq!(segment.b, Vector::new(1.0, 0.0, 0.0));+ /// # }+ /// ```+ pub fn swap(&mut self) {+ mem::swap(&mut self.a, &mut self.b)+ }++ /// Returns the unit direction vector of this segment.+ ///+ /// Vectors from `a` toward `b` with length 1.0.+ ///+ /// # Returns+ ///+ /// * `Some(direction)` - The normalized direction if the segment has non-zero length+ /// * `None` - If both endpoints are equal (degenerate segment)+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Segment;+ /// use parry3d::math::Vector;+ ///+ /// let segment = Segment::new(+ /// Vector::ZERO,+ /// Vector::new(3.0, 4.0, 0.0)+ /// );+ ///+ /// if let Some(dir) = segment.direction() {+ /// // Direction is normalized+ /// assert!((dir.length() - 1.0).abs() < 1e-6);+ /// // Vectors from a to b+ /// assert_eq!(dir, Vector::new(0.6, 0.8, 0.0));+ /// }+ ///+ /// // Degenerate segment (zero length)+ /// let degenerate = Segment::new(Vector::ZERO, Vector::ZERO);+ /// assert!(degenerate.direction().is_none());+ /// # }+ /// ```+ pub fn direction(&self) -> Option<Vector> {+ self.scaled_direction().try_normalize()+ }++ /// In 2D, the not-normalized counterclockwise normal of this segment.+ #[cfg(feature = "dim2")]+ pub fn scaled_normal(&self) -> Vector {+ let dir = self.scaled_direction();+ Vector::new(dir.y, -dir.x)+ }++ /// The not-normalized counterclockwise normal of this segment, assuming it lies on the plane+ /// with the normal collinear to the given axis (0 = X, 1 = Y, 2 = Z).+ #[cfg(feature = "dim3")]+ pub fn scaled_planar_normal(&self, plane_axis: u8) -> Vector {+ let dir = self.scaled_direction();+ match plane_axis {+ 0 => Vector::new(0.0, dir.z, -dir.y),+ 1 => Vector::new(-dir.z, 0.0, dir.x),+ 2 => Vector::new(dir.y, -dir.x, 0.0),+ _ => panic!("Invalid axis given: must be 0 (X axis), 1 (Y axis) or 2 (Z axis)"),+ }+ }++ /// In 2D, the normalized counterclockwise normal of this segment.+ #[cfg(feature = "dim2")]+ pub fn normal(&self) -> Option<Vector> {+ let (dir, length) = self.scaled_normal().normalize_and_length();+ (length > crate::math::DEFAULT_EPSILON).then_some(dir)+ }++ /// Returns `None`. Exists only for API similarity with the 2D parry.+ #[cfg(feature = "dim3")]+ pub fn normal(&self) -> Option<Vector> {+ None+ }++ /// The normalized counterclockwise normal of this segment, assuming it lies on the plane+ /// with the normal collinear to the given axis (0 = X, 1 = Y, 2 = Z).+ #[cfg(feature = "dim3")]+ pub fn planar_normal(&self, plane_axis: u8) -> Option<Vector> {+ self.scaled_planar_normal(plane_axis).try_normalize()+ }++ /// Applies the isometry `m` to the vertices of this segment and returns the resulting segment.+ pub fn transformed(&self, m: &Pose) -> Self {+ Segment::new(m * self.a, m * self.b)+ }++ /// Computes the point at the given location.+ pub fn point_at(&self, location: &SegmentPointLocation) -> Vector {+ match *location {+ SegmentPointLocation::OnVertex(0) => self.a,+ SegmentPointLocation::OnVertex(1) => self.b,+ SegmentPointLocation::OnEdge(bcoords) => self.a * bcoords[0] + self.b * bcoords[1],+ _ => panic!(),+ }+ }++ /// The normal of the given feature of this shape.+ pub fn feature_normal(&self, feature: FeatureId) -> Option<Vector> {+ if let Some(direction) = self.direction() {+ match feature {+ FeatureId::Vertex(id) => {+ if id == 0 {+ Some(direction)+ } else {+ Some(-direction)+ }+ }+ #[cfg(feature = "dim3")]+ FeatureId::Edge(_) => {+ let imin = direction.abs().min_position();+ let mut normal = Vector::ZERO;+ normal.vset(imin, 1.0);+ normal -= direction * direction.vget(imin);+ Some(normal.normalize())+ }+ FeatureId::Face(id) => {+ let mut dir = Vector::ZERO;+ if id == 0 {+ dir.x = direction.y;+ dir.y = -direction.x;+ } else {+ dir.x = -direction.y;+ dir.y = direction.x;+ }+ Some(dir)+ }+ _ => None,+ }+ } else {+ Some(Vector::Y)+ }+ }+}++impl SupportMap for Segment {+ #[inline]+ fn local_support_point(&self, dir: Vector) -> Vector {+ if self.a.dot(dir) > self.b.dot(dir) {+ self.a+ } else {+ self.b+ }+ }+}++impl From<[Vector; 2]> for Segment {+ fn from(arr: [Vector; 2]) -> Self {+ *Self::from_array(&arr)+ }+}++/*+impl ConvexPolyhedron for Segment {+ fn vertex(&self, id: FeatureId) -> Vector {+ if id.unwrap_vertex() == 0 {+ self.a+ } else {+ self.b+ }+ }++ #[cfg(feature = "dim3")]+ fn edge(&self, _: FeatureId) -> (Vector, Vector, FeatureId, FeatureId) {+ (self.a, self.b, FeatureId::Vertex(0), FeatureId::Vertex(1))+ }++ #[cfg(feature = "dim3")]+ fn face(&self, _: FeatureId, _: &mut ConvexPolygonalFeature) {+ panic!("A segment does not have any face in dimensions higher than 2.")+ }++ #[cfg(feature = "dim2")]+ fn face(&self, id: FeatureId, face: &mut ConvexPolygonalFeature) {+ face.clear();++ if let Some(normal) = utils::ccw_face_normal([&self.a, &self.b]) {+ face.set_feature_id(id);++ match id.unwrap_face() {+ 0 => {+ face.push(self.a, FeatureId::Vertex(0));+ face.push(self.b, FeatureId::Vertex(1));+ face.set_normal(normal);+ }+ 1 => {+ face.push(self.b, FeatureId::Vertex(1));+ face.push(self.a, FeatureId::Vertex(0));+ face.set_normal(-normal);+ }+ _ => unreachable!(),+ }+ } else {+ face.push(self.a, FeatureId::Vertex(0));+ face.set_feature_id(FeatureId::Vertex(0));+ }+ }++ #[cfg(feature = "dim2")]+ fn support_face_toward(+ &self,+ m: &Pose,+ dir: Vector,+ face: &mut ConvexPolygonalFeature,+ ) {+ let seg_dir = self.scaled_direction();++ if dir.perp(&seg_dir) >= 0.0 {+ self.face(FeatureId::Face(0), face);+ } else {+ self.face(FeatureId::Face(1), face);+ }+ face.transform_by(m)+ }++ #[cfg(feature = "dim3")]+ fn support_face_toward(+ &self,+ m: &Pose,+ _: Vector,+ face: &mut ConvexPolygonalFeature,+ ) {+ face.clear();+ face.push(self.a, FeatureId::Vertex(0));+ face.push(self.b, FeatureId::Vertex(1));+ face.push_edge_feature_id(FeatureId::Edge(0));+ face.set_feature_id(FeatureId::Edge(0));+ face.transform_by(m)+ }++ fn support_feature_toward(+ &self,+ transform: &Pose,+ dir: Vector,+ eps: Real,+ face: &mut ConvexPolygonalFeature,+ ) {+ face.clear();+ let seg = self.transformed(transform);+ let ceps = <Real as ComplexField>::sin(eps);++ if let Some(seg_dir) = seg.direction() {+ let cang = dir.dot(seg_dir);++ if cang > ceps {+ face.set_feature_id(FeatureId::Vertex(1));+ face.push(seg.b, FeatureId::Vertex(1));+ } else if cang < -ceps {+ face.set_feature_id(FeatureId::Vertex(0));+ face.push(seg.a, FeatureId::Vertex(0));+ } else {+ #[cfg(feature = "dim3")]+ {+ face.push(seg.a, FeatureId::Vertex(0));+ face.push(seg.b, FeatureId::Vertex(1));+ face.push_edge_feature_id(FeatureId::Edge(0));+ face.set_feature_id(FeatureId::Edge(0));+ }+ #[cfg(feature = "dim2")]+ {+ if dir.perp(&seg_dir) >= 0.0 {+ seg.face(FeatureId::Face(0), face);+ } else {+ seg.face(FeatureId::Face(1), face);+ }+ }+ }+ }+ }++ fn support_feature_id_toward(&self, local_dir: Vector) -> FeatureId {+ if let Some(seg_dir) = self.direction() {+ let eps: Real = (f64::consts::PI / 180.0) as Real;+ let seps = <Real as ComplexField>::sin(eps);+ let dot = seg_dir.dot(local_dir.as_ref());++ if dot <= seps {+ #[cfg(feature = "dim2")]+ {+ if local_dir.perp(seg_dir.as_ref()) >= 0.0 {+ FeatureId::Face(0)+ } else {+ FeatureId::Face(1)+ }+ }+ #[cfg(feature = "dim3")]+ {+ FeatureId::Edge(0)+ }+ } else if dot >= 0.0 {+ FeatureId::Vertex(1)+ } else {+ FeatureId::Vertex(0)+ }+ } else {+ FeatureId::Vertex(0)+ }+ }+}+*/++#[cfg(test)]+mod test {+ use crate::query::{Ray, RayCast};++ pub use super::*;+ #[test]+ fn segment_intersect_zero_length_issue_31() {+ // never intersect each other+ let ray = Ray::new(Vector::ZERO, Vector::X);+ let segment = Segment {+ a: Vector::new(+ 10.0,+ 10.0,+ #[cfg(feature = "dim3")]+ 10.0,+ ),+ b: Vector::new(+ 10.0,+ 10.0,+ #[cfg(feature = "dim3")]+ 10.0,+ ),+ };++ let hit = segment.intersects_ray(&Pose::identity(), &ray, Real::MAX);+ assert_eq!(hit, false);+ }+ #[test]+ fn segment_very_close_points_hit() {+ let epsilon = 1.1920929e-7;+ // intersect each other+ let ray = Ray::new(+ Vector::new(+ epsilon * 0.5,+ 0.3,+ #[cfg(feature = "dim3")]+ 0.0,+ ),+ -Vector::Y,+ );+ let segment = Segment {+ a: Vector::ZERO,+ b: Vector::new(+ // Theoretically, epsilon would suffice but imprecisions force us to add some more offset.+ epsilon * 1.01,+ 0.0,+ #[cfg(feature = "dim3")]+ 0.0,+ ),+ };++ let hit = segment.intersects_ray(&Pose::identity(), &ray, Real::MAX);+ assert_eq!(hit, true);+ }+ #[test]+ fn segment_very_close_points_no_hit() {+ let epsilon = 1.1920929e-7;+ // never intersect each other+ let ray = Ray::new(+ Vector::new(+ // Theoretically, epsilon would suffice but imprecisions force us to add some more offset.+ epsilon * 11.0,+ 0.1,+ #[cfg(feature = "dim3")]+ 0.0,+ ),+ -Vector::Y,+ );+ let segment = Segment {+ a: Vector::ZERO,+ b: Vector::new(+ epsilon * 0.9,+ 0.0,+ #[cfg(feature = "dim3")]+ 0.0,+ ),+ };++ let hit = segment.intersects_ray(&Pose::identity(), &ray, Real::MAX);+ assert_eq!(hit, false);+ }+}diff --git a/renderer/third_party/parry3d/src/shape/segment_pseudo_normals.rs b/renderer/third_party/parry3d/src/shape/segment_pseudo_normals.rsnew file mode 100644index 0000000..4a4296e--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/segment_pseudo_normals.rs@@ -0,0 +1,96 @@+use crate::math::Vector;++#[cfg(feature = "alloc")]+use crate::query::details::NormalConstraints;++/// The pseudo-normals of a polyline segment, approximating the outward normal cones of its+/// features.+///+/// This is the 2D segment analog of [`TrianglePseudoNormals`](crate::shape::TrianglePseudoNormals):+/// `face` is the segment's outward normal and `edges` are the outward pseudo-normals at its two+/// endpoints. An oriented polyline uses them to clamp contact normals to one side, so it acts as a+/// one-sided surface.+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[derive(Clone, Debug)]+pub struct SegmentPseudoNormals {+ /// The segment's outward normal.+ pub face: Vector,+ /// The outward pseudo-normals at the segment's two endpoints.+ pub edges: [Vector; 2],+}++#[cfg(feature = "alloc")]+impl NormalConstraints for SegmentPseudoNormals {+ /// Projects `dir` so it lies within the outward cone defined by `self`.+ fn project_local_normal_mut(&self, dir: &mut Vector) -> bool {+ // Find the closest pseudo-normal.+ let closest_edge = if dir.dot(self.edges[0]) >= dir.dot(self.edges[1]) {+ self.edges[0]+ } else {+ self.edges[1]+ };+ crate::shape::pseudo_normals::project_into_cone(self.face, closest_edge, dir)+ }+}++#[cfg(test)]+#[cfg(all(feature = "dim2", feature = "alloc"))]+mod test {+ use super::{NormalConstraints, SegmentPseudoNormals};+ use crate::math::Vector;++ fn bisector(v1: Vector, v2: Vector) -> Vector {+ (v1 + v2).normalize()+ }++ #[test]+ fn degenerate_cone_collapses_to_face() {+ let pn = SegmentPseudoNormals {+ face: Vector::Y,+ edges: [Vector::Y, Vector::Y],+ };++ assert_eq!(+ pn.project_local_normal(Vector::new(1.0, 1.0)),+ Some(Vector::Y)+ );+ assert!(pn.project_local_normal(-Vector::Y).is_none());+ }++ #[test]+ fn clamps_into_the_outward_cone() {+ // A cone centered on +Y, bounded at +-45 degrees (endpoint pseudo-normals at +-22.5 degrees).+ let ends = [+ bisector(Vector::Y, Vector::X),+ bisector(Vector::Y, -Vector::X),+ ];+ let edges = [bisector(Vector::Y, ends[0]), bisector(Vector::Y, ends[1])];+ let pn = SegmentPseudoNormals {+ face: Vector::Y,+ edges,+ };++ // Inside the cone: returned unchanged.+ assert_eq!(pn.project_local_normal(Vector::Y), Some(Vector::Y));+ for edge in edges {+ assert_eq!(pn.project_local_normal(edge), Some(edge));+ }+ let inside = Vector::new(0.2, 1.0).normalize();+ assert!(pn+ .project_local_normal(inside)+ .unwrap()+ .abs_diff_eq(inside, 1.0e-5));++ // Outside the cone but still outward: pulled onto the boundary, not left crossing the surface.+ let sideways = Vector::new(1.0, 0.2).normalize();+ let clamped = pn.project_local_normal(sideways).unwrap();+ assert!(clamped.dot(Vector::Y) > sideways.dot(Vector::Y));+ assert!(clamped.abs_diff_eq(ends[0], 1.0e-5));++ // Into the solid (-face half-space): rejected.+ assert!(pn.project_local_normal(-Vector::Y).is_none());+ assert!(pn+ .project_local_normal(Vector::new(0.3, -1.0).normalize())+ .is_none());+ }+}diff --git a/renderer/third_party/parry3d/src/shape/shape.rs b/renderer/third_party/parry3d/src/shape/shape.rsnew file mode 100644index 0000000..45a48c3--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/shape.rs@@ -0,0 +1,1729 @@+use crate::bounding_volume::{Aabb, BoundingSphere, BoundingVolume};+use crate::mass_properties::MassProperties;+use crate::math::{Pose, Real, RealField, Vector};+use crate::query::{PointQuery, RayCast};+#[cfg(feature = "serde-serialize")]+use crate::shape::SharedShape;+#[cfg(feature = "alloc")]+use crate::shape::{composite_shape::CompositeShape, Compound, HeightField, Polyline, TriMesh};+use crate::shape::{+ Ball, Capsule, Cuboid, FeatureId, HalfSpace, PolygonalFeatureMap, RoundCuboid, RoundShape,+ RoundTriangle, Segment, SubShapeId, SupportMap, Triangle,+};+#[cfg(feature = "dim3")]+use crate::shape::{Cone, Cylinder, RoundCone, RoundCylinder};+#[cfg(feature = "alloc")]+use alloc::{boxed::Box, vec::Vec};+use core::any::Any;+use core::fmt::Debug;++#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+use crate::shape::{ConvexPolyhedron, RoundConvexPolyhedron, Voxels};++#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+use crate::shape::{ConvexPolygon, RoundConvexPolygon, Voxels};+use num::Zero;+use num_derive::FromPrimitive;++#[derive(Copy, Clone, Debug, FromPrimitive, PartialEq, Eq, Hash)]+/// Enum representing the type of a shape.+pub enum ShapeType {+ /// A ball shape.+ Ball = 0,+ /// A cuboid shape.+ Cuboid,+ /// A capsule shape.+ Capsule,+ /// A segment shape.+ Segment,+ /// A triangle shape.+ Triangle,+ /// A shape defined as a voxel grid.+ Voxels,+ /// A triangle mesh shape.+ TriMesh,+ /// A set of segments.+ Polyline,+ /// A shape representing a full half-space.+ HalfSpace,+ /// A heightfield shape.+ HeightField,+ /// A Compound shape.+ Compound,+ #[cfg(feature = "dim2")]+ ConvexPolygon,+ #[cfg(feature = "dim3")]+ /// A convex polyhedron.+ ConvexPolyhedron,+ #[cfg(feature = "dim3")]+ /// A cylindrical shape.+ Cylinder,+ #[cfg(feature = "dim3")]+ /// A cone shape.+ Cone,+ // /// A custom shape type.+ // Custom(u8),+ /// A cuboid with rounded corners.+ RoundCuboid,+ /// A triangle with rounded corners.+ RoundTriangle,+ // /// A triangle-mesh with rounded corners.+ // RoundedTriMesh,+ // /// An heightfield with rounded corners.+ // RoundedHeightField,+ /// A cylinder with rounded corners.+ #[cfg(feature = "dim3")]+ RoundCylinder,+ /// A cone with rounded corners.+ #[cfg(feature = "dim3")]+ RoundCone,+ /// A convex polyhedron with rounded corners.+ #[cfg(feature = "dim3")]+ RoundConvexPolyhedron,+ /// A convex polygon with rounded corners.+ #[cfg(feature = "dim2")]+ RoundConvexPolygon,+ /// A custom user-defined shape.+ Custom,+}++#[derive(Copy, Clone)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize))]+/// Enum representing the shape with its actual type+pub enum TypedShape<'a> {+ /// A ball shape.+ Ball(&'a Ball),+ /// A cuboid shape.+ Cuboid(&'a Cuboid),+ /// A capsule shape.+ Capsule(&'a Capsule),+ /// A segment shape.+ Segment(&'a Segment),+ /// A triangle shape.+ Triangle(&'a Triangle),+ #[cfg(feature = "alloc")]+ /// A shape defined as a voxel grid.+ Voxels(&'a Voxels),+ /// A triangle mesh shape.+ #[cfg(feature = "alloc")]+ TriMesh(&'a TriMesh),+ /// A set of segments.+ #[cfg(feature = "alloc")]+ Polyline(&'a Polyline),+ /// A shape representing a full half-space.+ HalfSpace(&'a HalfSpace),+ /// A heightfield shape.+ #[cfg(feature = "alloc")]+ HeightField(&'a HeightField),+ /// A Compound shape.+ #[cfg(feature = "alloc")]+ Compound(&'a Compound),+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ ConvexPolygon(&'a ConvexPolygon),+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ /// A convex polyhedron.+ ConvexPolyhedron(&'a ConvexPolyhedron),+ #[cfg(feature = "dim3")]+ /// A cylindrical shape.+ Cylinder(&'a Cylinder),+ #[cfg(feature = "dim3")]+ /// A cone shape.+ Cone(&'a Cone),+ /// A cuboid with rounded corners.+ RoundCuboid(&'a RoundCuboid),+ /// A triangle with rounded corners.+ RoundTriangle(&'a RoundTriangle),+ // /// A triangle-mesh with rounded corners.+ // RoundedTriMesh,+ // /// An heightfield with rounded corners.+ // RoundedHeightField,+ /// A cylinder with rounded corners.+ #[cfg(feature = "dim3")]+ RoundCylinder(&'a RoundCylinder),+ /// A cone with rounded corners.+ #[cfg(feature = "dim3")]+ RoundCone(&'a RoundCone),+ /// A convex polyhedron with rounded corners.+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ RoundConvexPolyhedron(&'a RoundConvexPolyhedron),+ /// A convex polygon with rounded corners.+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ RoundConvexPolygon(&'a RoundConvexPolygon),+ /// A custom user-defined shape.+ #[cfg_attr(feature = "serde-serialize", serde(skip))]+ Custom(&'a dyn Shape),+}+impl Debug for TypedShape<'_> {+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {+ match self {+ Self::Ball(arg0) => f.debug_tuple("Ball").field(arg0).finish(),+ Self::Cuboid(arg0) => f.debug_tuple("Cuboid").field(arg0).finish(),+ Self::Capsule(arg0) => f.debug_tuple("Capsule").field(arg0).finish(),+ Self::Segment(arg0) => f.debug_tuple("Segment").field(arg0).finish(),+ Self::Triangle(arg0) => f.debug_tuple("Triangle").field(arg0).finish(),+ #[cfg(feature = "alloc")]+ Self::Voxels(arg0) => f.debug_tuple("Voxels").field(arg0).finish(),+ #[cfg(feature = "alloc")]+ Self::TriMesh(arg0) => f.debug_tuple("TriMesh").field(arg0).finish(),+ #[cfg(feature = "alloc")]+ Self::Polyline(arg0) => f.debug_tuple("Polyline").field(arg0).finish(),+ Self::HalfSpace(arg0) => f.debug_tuple("HalfSpace").field(arg0).finish(),+ #[cfg(feature = "alloc")]+ Self::HeightField(arg0) => f.debug_tuple("HeightField").field(arg0).finish(),+ #[cfg(feature = "alloc")]+ Self::Compound(arg0) => f.debug_tuple("Compound").field(arg0).finish(),+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ Self::ConvexPolygon(arg0) => f.debug_tuple("ConvexPolygon").field(arg0).finish(),+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ Self::ConvexPolyhedron(arg0) => f.debug_tuple("ConvexPolyhedron").field(arg0).finish(),+ #[cfg(feature = "dim3")]+ Self::Cylinder(arg0) => f.debug_tuple("Cylinder").field(arg0).finish(),+ #[cfg(feature = "dim3")]+ Self::Cone(arg0) => f.debug_tuple("Cone").field(arg0).finish(),+ Self::RoundCuboid(arg0) => f.debug_tuple("RoundCuboid").field(arg0).finish(),+ Self::RoundTriangle(arg0) => f.debug_tuple("RoundTriangle").field(arg0).finish(),+ #[cfg(feature = "dim3")]+ Self::RoundCylinder(arg0) => f.debug_tuple("RoundCylinder").field(arg0).finish(),+ #[cfg(feature = "dim3")]+ Self::RoundCone(arg0) => f.debug_tuple("RoundCone").field(arg0).finish(),+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ Self::RoundConvexPolyhedron(arg0) => {+ f.debug_tuple("RoundConvexPolyhedron").field(arg0).finish()+ }+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ Self::RoundConvexPolygon(arg0) => {+ f.debug_tuple("RoundConvexPolygon").field(arg0).finish()+ }+ Self::Custom(_) => f.debug_tuple("Custom").finish(),+ }+ }+}++#[cfg(feature = "serde-serialize")]+#[derive(Deserialize)]+// NOTE: This enum MUST match the `TypedShape` enum.+/// Enum representing the shape with its actual type+pub(crate) enum DeserializableTypedShape {+ /// A ball shape.+ Ball(Ball),+ /// A cuboid shape.+ Cuboid(Cuboid),+ /// A capsule shape.+ Capsule(Capsule),+ /// A segment shape.+ Segment(Segment),+ /// A triangle shape.+ Triangle(Triangle),+ /// A shape defined as a voxel grid.+ #[cfg(feature = "alloc")]+ Voxels(Voxels),+ /// A triangle mesh shape.+ #[cfg(feature = "alloc")]+ TriMesh(TriMesh),+ /// A set of segments.+ #[cfg(feature = "alloc")]+ Polyline(Polyline),+ /// A shape representing a full half-space.+ HalfSpace(HalfSpace),+ /// A heightfield shape.+ #[cfg(feature = "alloc")]+ HeightField(HeightField),+ /// A Compound shape.+ #[cfg(feature = "alloc")]+ Compound(Compound),+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ ConvexPolygon(ConvexPolygon),+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ /// A convex polyhedron.+ ConvexPolyhedron(ConvexPolyhedron),+ #[cfg(feature = "dim3")]+ /// A cylindrical shape.+ Cylinder(Cylinder),+ #[cfg(feature = "dim3")]+ /// A cone shape.+ Cone(Cone),+ // /// A custom shape type.+ // Custom(u8),+ /// A cuboid with rounded corners.+ RoundCuboid(RoundCuboid),+ /// A triangle with rounded corners.+ RoundTriangle(RoundTriangle),+ // /// A triangle-mesh with rounded corners.+ // RoundedTriMesh,+ // /// An heightfield with rounded corners.+ // RoundedHeightField,+ /// A cylinder with rounded corners.+ #[cfg(feature = "dim3")]+ RoundCylinder(RoundCylinder),+ /// A cone with rounded corners.+ #[cfg(feature = "dim3")]+ RoundCone(RoundCone),+ /// A convex polyhedron with rounded corners.+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ RoundConvexPolyhedron(RoundConvexPolyhedron),+ /// A convex polygon with rounded corners.+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ RoundConvexPolygon(RoundConvexPolygon),+ /// A custom user-defined shape.+ #[allow(dead_code)]+ Custom,+}++#[cfg(feature = "serde-serialize")]+impl DeserializableTypedShape {+ /// Converts `self` to a `SharedShape` if `self` isn't `Custom`.+ pub fn into_shared_shape(self) -> Option<SharedShape> {+ match self {+ DeserializableTypedShape::Ball(s) => Some(SharedShape::new(s)),+ DeserializableTypedShape::Cuboid(s) => Some(SharedShape::new(s)),+ DeserializableTypedShape::Capsule(s) => Some(SharedShape::new(s)),+ DeserializableTypedShape::Segment(s) => Some(SharedShape::new(s)),+ DeserializableTypedShape::Triangle(s) => Some(SharedShape::new(s)),+ #[cfg(feature = "alloc")]+ DeserializableTypedShape::Voxels(s) => Some(SharedShape::new(s)),+ #[cfg(feature = "alloc")]+ DeserializableTypedShape::TriMesh(s) => Some(SharedShape::new(s)),+ #[cfg(feature = "alloc")]+ DeserializableTypedShape::Polyline(s) => Some(SharedShape::new(s)),+ DeserializableTypedShape::HalfSpace(s) => Some(SharedShape::new(s)),+ #[cfg(feature = "alloc")]+ DeserializableTypedShape::HeightField(s) => Some(SharedShape::new(s)),+ #[cfg(feature = "alloc")]+ DeserializableTypedShape::Compound(s) => Some(SharedShape::new(s)),+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ DeserializableTypedShape::ConvexPolygon(s) => Some(SharedShape::new(s)),+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ DeserializableTypedShape::ConvexPolyhedron(s) => Some(SharedShape::new(s)),+ #[cfg(feature = "dim3")]+ DeserializableTypedShape::Cylinder(s) => Some(SharedShape::new(s)),+ #[cfg(feature = "dim3")]+ DeserializableTypedShape::Cone(s) => Some(SharedShape::new(s)),+ DeserializableTypedShape::RoundCuboid(s) => Some(SharedShape::new(s)),+ DeserializableTypedShape::RoundTriangle(s) => Some(SharedShape::new(s)),+ #[cfg(feature = "dim3")]+ DeserializableTypedShape::RoundCylinder(s) => Some(SharedShape::new(s)),+ #[cfg(feature = "dim3")]+ DeserializableTypedShape::RoundCone(s) => Some(SharedShape::new(s)),+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ DeserializableTypedShape::RoundConvexPolyhedron(s) => Some(SharedShape::new(s)),+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ DeserializableTypedShape::RoundConvexPolygon(s) => Some(SharedShape::new(s)),+ DeserializableTypedShape::Custom => None,+ }+ }+}++/// Trait implemented by shapes usable by Rapier.+pub trait Shape: RayCast + PointQuery + Any + Send + Sync {+ /// Computes the [`Aabb`] of this shape.+ fn compute_local_aabb(&self) -> Aabb;+ /// Computes the bounding-sphere of this shape.+ fn compute_local_bounding_sphere(&self) -> BoundingSphere;++ /// Clones this shape into a boxed trait-object.+ ///+ /// The boxed trait-object has the same concrete type as `Self`.+ #[cfg(feature = "alloc")]+ #[deprecated = "renamed to `clone_dyn`"]+ fn clone_box(&self) -> Box<dyn Shape> {+ self.clone_dyn()+ }++ /// Clones this shape into a boxed trait-object.+ ///+ /// The boxed trait-object has the same concrete type as `Self`.+ #[cfg(feature = "alloc")]+ fn clone_dyn(&self) -> Box<dyn Shape>;++ /// Scales this shape by `scale` into a boxed trait-object.+ ///+ /// In some cases, the resulting shape doesn’t have the same type as Self. For example,+ /// if a non-uniform scale is provided and Self as a [`Ball`], then the result will be discretized+ /// (based on the `num_subdivisions` parameter) as a `ConvexPolyhedron` (in 3D) or `ConvexPolygon` (in 2D).+ #[cfg(feature = "alloc")]+ fn scale_dyn(&self, scale: Vector, num_subdivisions: u32) -> Option<Box<dyn Shape>>;++ /// Computes the [`Aabb`] of this shape with the given position.+ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.compute_local_aabb().transform_by(position)+ }+ /// Computes the bounding-sphere of this shape with the given position.+ fn compute_bounding_sphere(&self, position: &Pose) -> BoundingSphere {+ self.compute_local_bounding_sphere().transform_by(position)+ }++ /// Compute the mass-properties of this shape given its uniform density.+ fn mass_properties(&self, density: Real) -> MassProperties;++ /// Gets the type tag of this shape.+ fn shape_type(&self) -> ShapeType;++ /// Gets the underlying shape as an enum.+ fn as_typed_shape(&self) -> TypedShape<'_>;++ fn ccd_thickness(&self) -> Real;++ // TODO: document this.+ // This should probably be the largest sharp edge angle (in radians) in [0; PI].+ // Though this isn't a very good description considering this is PI / 2+ // for capsule (which doesn't have any sharp angle). I guess a better way+ // to phrase this is: "the smallest angle such that rotating the shape by+ // that angle may result in different contact points".+ fn ccd_angular_thickness(&self) -> Real;++ /// Is this shape known to be convex?+ ///+ /// If this returns `true` then `self` is known to be convex.+ /// If this returns `false` then it is not known whether or+ /// not `self` is convex.+ fn is_convex(&self) -> bool {+ false+ }++ /// Converts this shape into its support mapping, if it has one.+ fn as_support_map(&self) -> Option<&dyn SupportMap> {+ None+ }++ #[cfg(feature = "alloc")]+ fn as_composite_shape(&self) -> Option<&(dyn CompositeShape + Sync)> {+ None+ }++ /// Converts this shape to a polygonal feature-map, if it is one.+ fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {+ None+ }++ // fn as_rounded(&self) -> Option<&Rounded<Box<AnyShape>>> {+ // None+ // }++ /// The shape's normal at the given point located on a specific feature.+ ///+ /// `subshape` identifies the sub-shape the feature belongs to, as a query result reports it;+ /// it is `0` for a shape with no sub-shapes. `feature` is that sub-shape's own feature.+ fn feature_normal_at_point(+ &self,+ _subshape: SubShapeId,+ _feature: FeatureId,+ _point: Vector,+ ) -> Option<Vector> {+ None+ }++ /// Computes the swept [`Aabb`] of this shape, i.e., the space it would occupy by moving from+ /// the given start position to the given end position.+ fn compute_swept_aabb(&self, start_pos: &Pose, end_pos: &Pose) -> Aabb {+ let aabb1 = self.compute_aabb(start_pos);+ let aabb2 = self.compute_aabb(end_pos);+ aabb1.merged(&aabb2)+ }+}++impl dyn Shape {+ /// Converts this abstract shape to the given shape, if it is one.+ pub fn as_shape<T: Shape>(&self) -> Option<&T> {+ (self as &dyn Any).downcast_ref()+ }+ /// Converts this abstract shape to the given mutable shape, if it is one.+ pub fn as_shape_mut<T: Shape>(&mut self) -> Option<&mut T> {+ (self as &mut dyn Any).downcast_mut()+ }++ /// Converts this abstract shape to a ball, if it is one.+ pub fn as_ball(&self) -> Option<&Ball> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable ball, if it is one.+ pub fn as_ball_mut(&mut self) -> Option<&mut Ball> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a cuboid, if it is one.+ pub fn as_cuboid(&self) -> Option<&Cuboid> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable cuboid, if it is one.+ pub fn as_cuboid_mut(&mut self) -> Option<&mut Cuboid> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a halfspace, if it is one.+ pub fn as_halfspace(&self) -> Option<&HalfSpace> {+ self.as_shape()+ }+ /// Converts this abstract shape to a halfspace, if it is one.+ pub fn as_halfspace_mut(&mut self) -> Option<&mut HalfSpace> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a segment, if it is one.+ pub fn as_segment(&self) -> Option<&Segment> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable segment, if it is one.+ pub fn as_segment_mut(&mut self) -> Option<&mut Segment> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a capsule, if it is one.+ pub fn as_capsule(&self) -> Option<&Capsule> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable capsule, if it is one.+ pub fn as_capsule_mut(&mut self) -> Option<&mut Capsule> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a triangle, if it is one.+ pub fn as_triangle(&self) -> Option<&Triangle> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable triangle, if it is one.+ pub fn as_triangle_mut(&mut self) -> Option<&mut Triangle> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to voxels, if it is one.+ #[cfg(feature = "alloc")]+ pub fn as_voxels(&self) -> Option<&Voxels> {+ self.as_shape()+ }+ /// Converts this abstract shape to mutable voxels, if it is one.+ #[cfg(feature = "alloc")]+ pub fn as_voxels_mut(&mut self) -> Option<&mut Voxels> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a compound shape, if it is one.+ #[cfg(feature = "alloc")]+ pub fn as_compound(&self) -> Option<&Compound> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable compound shape, if it is one.+ #[cfg(feature = "alloc")]+ pub fn as_compound_mut(&mut self) -> Option<&mut Compound> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a triangle mesh, if it is one.+ #[cfg(feature = "alloc")]+ pub fn as_trimesh(&self) -> Option<&TriMesh> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable triangle mesh, if it is one.+ #[cfg(feature = "alloc")]+ pub fn as_trimesh_mut(&mut self) -> Option<&mut TriMesh> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a polyline, if it is one.+ #[cfg(feature = "alloc")]+ pub fn as_polyline(&self) -> Option<&Polyline> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable polyline, if it is one.+ #[cfg(feature = "alloc")]+ pub fn as_polyline_mut(&mut self) -> Option<&mut Polyline> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a heightfield, if it is one.+ #[cfg(feature = "alloc")]+ pub fn as_heightfield(&self) -> Option<&HeightField> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable heightfield, if it is one.+ #[cfg(feature = "alloc")]+ pub fn as_heightfield_mut(&mut self) -> Option<&mut HeightField> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a round cuboid, if it is one.+ pub fn as_round_cuboid(&self) -> Option<&RoundCuboid> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable round cuboid, if it is one.+ pub fn as_round_cuboid_mut(&mut self) -> Option<&mut RoundCuboid> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a round triangle, if it is one.+ pub fn as_round_triangle(&self) -> Option<&RoundTriangle> {+ self.as_shape()+ }+ /// Converts this abstract shape to a round triangle, if it is one.+ pub fn as_round_triangle_mut(&mut self) -> Option<&mut RoundTriangle> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a convex polygon, if it is one.+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ pub fn as_convex_polygon(&self) -> Option<&ConvexPolygon> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable convex polygon, if it is one.+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ pub fn as_convex_polygon_mut(&mut self) -> Option<&mut ConvexPolygon> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a round convex polygon, if it is one.+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ pub fn as_round_convex_polygon(&self) -> Option<&RoundConvexPolygon> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable round convex polygon, if it is one.+ #[cfg(feature = "dim2")]+ #[cfg(feature = "alloc")]+ pub fn as_round_convex_polygon_mut(&mut self) -> Option<&mut RoundConvexPolygon> {+ self.as_shape_mut()+ }++ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ pub fn as_convex_polyhedron(&self) -> Option<&ConvexPolyhedron> {+ self.as_shape()+ }+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ pub fn as_convex_polyhedron_mut(&mut self) -> Option<&mut ConvexPolyhedron> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a cylinder, if it is one.+ #[cfg(feature = "dim3")]+ pub fn as_cylinder(&self) -> Option<&Cylinder> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable cylinder, if it is one.+ #[cfg(feature = "dim3")]+ pub fn as_cylinder_mut(&mut self) -> Option<&mut Cylinder> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a cone, if it is one.+ #[cfg(feature = "dim3")]+ pub fn as_cone(&self) -> Option<&Cone> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable cone, if it is one.+ #[cfg(feature = "dim3")]+ pub fn as_cone_mut(&mut self) -> Option<&mut Cone> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a round cylinder, if it is one.+ #[cfg(feature = "dim3")]+ pub fn as_round_cylinder(&self) -> Option<&RoundCylinder> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable round cylinder, if it is one.+ #[cfg(feature = "dim3")]+ pub fn as_round_cylinder_mut(&mut self) -> Option<&mut RoundCylinder> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a round cone, if it is one.+ #[cfg(feature = "dim3")]+ pub fn as_round_cone(&self) -> Option<&RoundCone> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable round cone, if it is one.+ #[cfg(feature = "dim3")]+ pub fn as_round_cone_mut(&mut self) -> Option<&mut RoundCone> {+ self.as_shape_mut()+ }++ /// Converts this abstract shape to a round convex polyhedron, if it is one.+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ pub fn as_round_convex_polyhedron(&self) -> Option<&RoundConvexPolyhedron> {+ self.as_shape()+ }+ /// Converts this abstract shape to a mutable round convex polyhedron, if it is one.+ #[cfg(feature = "dim3")]+ #[cfg(feature = "alloc")]+ pub fn as_round_convex_polyhedron_mut(&mut self) -> Option<&mut RoundConvexPolyhedron> {+ self.as_shape_mut()+ }+}++impl Shape for Ball {+ #[cfg(feature = "alloc")]+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(*self)+ }++ #[cfg(feature = "alloc")]+ fn scale_dyn(&self, scale: Vector, num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ let scaled = self.scaled(scale, num_subdivisions)?;+ Some(scaled.either::<_, _, Box<dyn Shape>>(|x| Box::new(x), |x| Box::new(x)))+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.aabb(position)+ }++ fn mass_properties(&self, density: Real) -> MassProperties {+ MassProperties::from_ball(density, self.radius)+ }++ fn ccd_thickness(&self) -> Real {+ self.radius+ }++ fn ccd_angular_thickness(&self) -> Real {+ Real::pi()+ }++ fn is_convex(&self) -> bool {+ true+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::Ball+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::Ball(self)+ }++ fn as_support_map(&self) -> Option<&dyn SupportMap> {+ Some(self as &dyn SupportMap)+ }++ /// The shape's normal at the given point located on a specific feature.+ #[inline]+ fn feature_normal_at_point(+ &self,+ _: SubShapeId,+ _: FeatureId,+ point: Vector,+ ) -> Option<Vector> {+ (point).try_normalize()+ }+}++impl Shape for Cuboid {+ #[cfg(feature = "alloc")]+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(*self)+ }++ #[cfg(feature = "alloc")]+ fn scale_dyn(&self, scale: Vector, _num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ Some(Box::new(self.scaled(scale)))+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.aabb(position)+ }++ fn mass_properties(&self, density: Real) -> MassProperties {+ MassProperties::from_cuboid(density, self.half_extents)+ }++ fn is_convex(&self) -> bool {+ true+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::Cuboid+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::Cuboid(self)+ }++ fn ccd_thickness(&self) -> Real {+ self.half_extents.min_element()+ }++ fn ccd_angular_thickness(&self) -> Real {+ Real::frac_pi_2()+ }++ fn as_support_map(&self) -> Option<&dyn SupportMap> {+ Some(self as &dyn SupportMap)+ }++ fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {+ Some((self as &dyn PolygonalFeatureMap, 0.0))+ }++ fn feature_normal_at_point(+ &self,+ _subshape: SubShapeId,+ feature: FeatureId,+ _point: Vector,+ ) -> Option<Vector> {+ self.feature_normal(feature)+ }+}++impl Shape for Capsule {+ #[cfg(feature = "alloc")]+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(*self)+ }++ #[cfg(feature = "alloc")]+ fn scale_dyn(&self, scale: Vector, num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ let scaled = self.scaled(scale, num_subdivisions)?;+ Some(scaled.either::<_, _, Box<dyn Shape>>(|x| Box::new(x), |x| Box::new(x)))+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.aabb(position)+ }++ fn mass_properties(&self, density: Real) -> MassProperties {+ MassProperties::from_capsule(density, self.segment.a, self.segment.b, self.radius)+ }++ fn is_convex(&self) -> bool {+ true+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::Capsule+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::Capsule(self)+ }++ fn ccd_thickness(&self) -> Real {+ self.radius+ }++ fn ccd_angular_thickness(&self) -> Real {+ Real::frac_pi_2()+ }++ fn as_support_map(&self) -> Option<&dyn SupportMap> {+ Some(self as &dyn SupportMap)+ }++ fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {+ Some((&self.segment as &dyn PolygonalFeatureMap, self.radius))+ }+}++impl Shape for Triangle {+ #[cfg(feature = "alloc")]+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(*self)+ }++ #[cfg(feature = "alloc")]+ fn scale_dyn(&self, scale: Vector, _num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ Some(Box::new(self.scaled(scale)))+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.aabb(position)+ }++ fn mass_properties(&self, _density: Real) -> MassProperties {+ #[cfg(feature = "dim2")]+ return MassProperties::from_triangle(_density, self.a, self.b, self.c);+ #[cfg(feature = "dim3")]+ return MassProperties::zero();+ }++ fn is_convex(&self) -> bool {+ true+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::Triangle+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::Triangle(self)+ }++ fn ccd_thickness(&self) -> Real {+ // TODO: in 2D use the smallest height of the triangle.+ 0.0+ }++ fn ccd_angular_thickness(&self) -> Real {+ Real::frac_pi_2()+ }++ fn as_support_map(&self) -> Option<&dyn SupportMap> {+ Some(self as &dyn SupportMap)+ }++ fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {+ Some((self as &dyn PolygonalFeatureMap, 0.0))+ }++ fn feature_normal_at_point(+ &self,+ _subshape: SubShapeId,+ _feature: FeatureId,+ _point: Vector,+ ) -> Option<Vector> {+ #[cfg(feature = "dim2")]+ return None;+ #[cfg(feature = "dim3")]+ return self.feature_normal(_feature);+ }+}++impl Shape for Segment {+ #[cfg(feature = "alloc")]+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(*self)+ }++ #[cfg(feature = "alloc")]+ fn scale_dyn(&self, scale: Vector, _num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ Some(Box::new(self.scaled(scale)))+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.aabb(position)+ }++ fn mass_properties(&self, _density: Real) -> MassProperties {+ MassProperties::zero()+ }++ fn is_convex(&self) -> bool {+ true+ }++ fn ccd_thickness(&self) -> Real {+ 0.0+ }++ fn ccd_angular_thickness(&self) -> Real {+ Real::frac_pi_2()+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::Segment+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::Segment(self)+ }++ fn as_support_map(&self) -> Option<&dyn SupportMap> {+ Some(self as &dyn SupportMap)+ }++ fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {+ Some((self as &dyn PolygonalFeatureMap, 0.0))+ }++ fn feature_normal_at_point(+ &self,+ _subshape: SubShapeId,+ feature: FeatureId,+ _point: Vector,+ ) -> Option<Vector> {+ self.feature_normal(feature)+ }+}++#[cfg(feature = "alloc")]+impl Shape for Compound {+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(self.clone())+ }++ fn scale_dyn(&self, scale: Vector, num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ use super::SharedShape;++ let scaled: Vec<_> = self+ .shapes()+ .iter()+ .map(|(pos, shape)| {+ let scaled_shape = shape.scale_dyn(scale, num_subdivisions)?;+ Some((+ Pose::from_parts(pos.translation * scale, pos.rotation),+ SharedShape(scaled_shape.into()),+ ))+ })+ .collect::<Option<Vec<_>>>()?;+ Some(Box::new(Compound::new(scaled)))+ }++ fn compute_local_aabb(&self) -> Aabb {+ *self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.local_aabb().transform_by(position)+ }++ fn mass_properties(&self, density: Real) -> MassProperties {+ MassProperties::from_compound(density, self.shapes())+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::Compound+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::Compound(self)+ }++ fn ccd_thickness(&self) -> Real {+ self.shapes()+ .iter()+ .fold(Real::MAX, |curr, (_, s)| curr.min(s.ccd_thickness()))+ }++ fn ccd_angular_thickness(&self) -> Real {+ self.shapes().iter().fold(Real::MAX, |curr, (_, s)| {+ curr.max(s.ccd_angular_thickness())+ })+ }++ #[cfg(feature = "alloc")]+ fn as_composite_shape(&self) -> Option<&(dyn CompositeShape + Sync)> {+ Some(self as &(dyn CompositeShape + Sync))+ }+}++#[cfg(feature = "alloc")]+impl Shape for Polyline {+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(self.clone())+ }++ fn scale_dyn(&self, scale: Vector, _num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ Some(Box::new(self.clone().scaled(scale)))+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.aabb(position)+ }++ fn mass_properties(&self, _density: Real) -> MassProperties {+ MassProperties::zero()+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::Polyline+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::Polyline(self)+ }++ fn ccd_thickness(&self) -> Real {+ 0.0+ }++ fn ccd_angular_thickness(&self) -> Real {+ // TODO: the value should depend on the angles between+ // adjacent segments of the polyline.+ Real::frac_pi_4()+ }++ #[cfg(feature = "alloc")]+ fn as_composite_shape(&self) -> Option<&(dyn CompositeShape + Sync)> {+ Some(self as &(dyn CompositeShape + Sync))+ }+}++#[cfg(feature = "alloc")]+impl Shape for TriMesh {+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(self.clone())+ }++ fn scale_dyn(&self, scale: Vector, _num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ Some(Box::new(self.clone().scaled(scale)))+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.aabb(position)+ }++ fn mass_properties(&self, density: Real) -> MassProperties {+ MassProperties::from_trimesh(density, self.vertices(), self.indices())+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::TriMesh+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::TriMesh(self)+ }++ fn ccd_thickness(&self) -> Real {+ // TODO: in 2D, return the smallest CCD thickness among triangles?+ 0.0+ }++ fn ccd_angular_thickness(&self) -> Real {+ // TODO: the value should depend on the angles between+ // adjacent triangles of the trimesh.+ Real::frac_pi_4()+ }++ /// Gets the normal of the triangle `subshape`.+ fn feature_normal_at_point(+ &self,+ _subshape: SubShapeId,+ _feature: FeatureId,+ _point: Vector,+ ) -> Option<Vector> {+ #[cfg(feature = "dim2")]+ return None;+ #[cfg(feature = "dim3")]+ return self.triangle_normal(_subshape);+ }++ #[cfg(feature = "alloc")]+ fn as_composite_shape(&self) -> Option<&(dyn CompositeShape + Sync)> {+ Some(self as &(dyn CompositeShape + Sync))+ }+}++#[cfg(feature = "alloc")]+impl Shape for HeightField {+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(self.clone())+ }++ fn scale_dyn(&self, scale: Vector, _num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ Some(Box::new(self.clone().scaled(scale)))+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.aabb(position)+ }++ fn mass_properties(&self, _density: Real) -> MassProperties {+ MassProperties::zero()+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::HeightField+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::HeightField(self)+ }++ fn ccd_thickness(&self) -> Real {+ 0.0+ }++ fn ccd_angular_thickness(&self) -> Real {+ // TODO: the value should depend on the angles between+ // adjacent triangles of the heightfield.+ Real::frac_pi_4()+ }+}++#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+impl Shape for ConvexPolygon {+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(self.clone())+ }++ fn scale_dyn(&self, scale: Vector, _num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ Some(Box::new(self.clone().scaled(scale)?))+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.aabb(position)+ }++ fn mass_properties(&self, density: Real) -> MassProperties {+ MassProperties::from_convex_polygon(density, self.points())+ }++ fn is_convex(&self) -> bool {+ true+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::ConvexPolygon+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::ConvexPolygon(self)+ }++ fn ccd_thickness(&self) -> Real {+ // TODO: we should use the OBB instead.+ self.compute_local_aabb().half_extents().min_element()+ }++ fn ccd_angular_thickness(&self) -> Real {+ // TODO: the value should depend on the angles between+ // adjacent segments of the convex polygon.+ Real::frac_pi_4()+ }++ fn as_support_map(&self) -> Option<&dyn SupportMap> {+ Some(self as &dyn SupportMap)+ }++ fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {+ Some((self as &dyn PolygonalFeatureMap, 0.0))+ }++ fn feature_normal_at_point(+ &self,+ _subshape: SubShapeId,+ feature: FeatureId,+ _point: Vector,+ ) -> Option<Vector> {+ self.feature_normal(feature)+ }+}++#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+impl Shape for ConvexPolyhedron {+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(self.clone())+ }++ fn scale_dyn(&self, scale: Vector, _num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ Some(Box::new(self.clone().scaled(scale)?))+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.aabb(position)+ }++ fn mass_properties(&self, density: Real) -> MassProperties {+ let (vertices, indices) = self.to_trimesh();+ MassProperties::from_convex_polyhedron(density, &vertices, &indices)+ }++ fn is_convex(&self) -> bool {+ true+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::ConvexPolyhedron+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::ConvexPolyhedron(self)+ }++ fn ccd_thickness(&self) -> Real {+ // TODO: we should use the OBB instead.+ self.compute_local_aabb().half_extents().min_element()+ }++ fn ccd_angular_thickness(&self) -> Real {+ // TODO: the value should depend on the angles between+ // adjacent segments of the convex polyhedron.+ Real::frac_pi_4()+ }++ fn as_support_map(&self) -> Option<&dyn SupportMap> {+ Some(self as &dyn SupportMap)+ }++ fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {+ Some((self as &dyn PolygonalFeatureMap, 0.0))+ }++ fn feature_normal_at_point(+ &self,+ _subshape: SubShapeId,+ feature: FeatureId,+ _point: Vector,+ ) -> Option<Vector> {+ self.feature_normal(feature)+ }+}++#[cfg(feature = "dim3")]+impl Shape for Cylinder {+ #[cfg(feature = "alloc")]+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(*self)+ }++ #[cfg(feature = "alloc")]+ fn scale_dyn(&self, scale: Vector, num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ let scaled = self.scaled(scale, num_subdivisions)?;+ Some(scaled.either::<_, _, Box<dyn Shape>>(|x| Box::new(x), |x| Box::new(x)))+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.aabb(position)+ }++ fn mass_properties(&self, density: Real) -> MassProperties {+ MassProperties::from_cylinder(density, self.half_height, self.radius)+ }++ fn is_convex(&self) -> bool {+ true+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::Cylinder+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::Cylinder(self)+ }++ fn ccd_thickness(&self) -> Real {+ self.radius+ }++ fn ccd_angular_thickness(&self) -> Real {+ Real::frac_pi_2()+ }++ fn as_support_map(&self) -> Option<&dyn SupportMap> {+ Some(self as &dyn SupportMap)+ }++ fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {+ Some((self as &dyn PolygonalFeatureMap, 0.0))+ }+}++#[cfg(feature = "dim3")]+impl Shape for Cone {+ #[cfg(feature = "alloc")]+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(*self)+ }++ #[cfg(feature = "alloc")]+ fn scale_dyn(&self, scale: Vector, num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ let scaled = self.scaled(scale, num_subdivisions)?;+ Some(scaled.either::<_, _, Box<dyn Shape>>(|x| Box::new(x), |x| Box::new(x)))+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.aabb(position)+ }++ fn mass_properties(&self, density: Real) -> MassProperties {+ MassProperties::from_cone(density, self.half_height, self.radius)+ }++ fn is_convex(&self) -> bool {+ true+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::Cone+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::Cone(self)+ }++ fn ccd_thickness(&self) -> Real {+ self.radius+ }++ fn ccd_angular_thickness(&self) -> Real {+ let apex_half_angle = RealField::atan2(self.radius, self.half_height);+ assert!(apex_half_angle >= 0.0);+ let basis_angle = Real::frac_pi_2() - apex_half_angle;+ basis_angle.min(apex_half_angle * 2.0)+ }++ fn as_support_map(&self) -> Option<&dyn SupportMap> {+ Some(self as &dyn SupportMap)+ }++ fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {+ Some((self as &dyn PolygonalFeatureMap, 0.0))+ }+}++impl Shape for HalfSpace {+ #[cfg(feature = "alloc")]+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(*self)+ }++ #[cfg(feature = "alloc")]+ fn scale_dyn(&self, scale: Vector, _num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ Some(Box::new(self.scaled(scale)?))+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.aabb(position)+ }++ fn is_convex(&self) -> bool {+ true+ }++ fn ccd_thickness(&self) -> Real {+ #[cfg_attr(feature = "f32", expect(clippy::unnecessary_cast))]+ let result = f32::MAX as Real;+ result+ }++ fn ccd_angular_thickness(&self) -> Real {+ Real::pi()+ }++ fn mass_properties(&self, _: Real) -> MassProperties {+ MassProperties::zero()+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::HalfSpace+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::HalfSpace(self)+ }+}++#[cfg(feature = "alloc")]+impl Shape for Voxels {+ fn compute_local_aabb(&self) -> Aabb {+ self.local_aabb()+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.local_bounding_sphere()+ }++ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(self.clone())+ }++ fn scale_dyn(&self, scale: Vector, _num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ Some(Box::new(self.clone().scaled(scale)))+ }++ fn mass_properties(&self, density: Real) -> MassProperties {+ MassProperties::from_voxels(density, self)+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::Voxels+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::Voxels(self)+ }++ fn ccd_thickness(&self) -> Real {+ self.voxel_size().min_element()+ }++ fn ccd_angular_thickness(&self) -> Real {+ Real::frac_pi_2()+ }+}++macro_rules! impl_shape_for_round_shape(+ ($S: ty, $Tag: ident, $t: tt) => {+ impl Shape for RoundShape<$S> {+ #[cfg(feature = "alloc")]+ fn clone_dyn(&self) -> Box<dyn Shape> {+ Box::new(self.clone())+ }++ #[cfg(feature = "alloc")]+ fn scale_dyn(&self, scale: Vector, num_subdivisions: u32) -> Option<Box<dyn Shape>> {+ $t(self, scale, num_subdivisions)+ }++ fn compute_local_aabb(&self) -> Aabb {+ self.inner_shape.local_aabb().loosened(self.border_radius)+ }++ fn compute_local_bounding_sphere(&self) -> BoundingSphere {+ self.inner_shape.local_bounding_sphere().loosened(self.border_radius)+ }++ fn compute_aabb(&self, position: &Pose) -> Aabb {+ self.inner_shape.aabb(position).loosened(self.border_radius)+ }++ fn mass_properties(&self, density: Real) -> MassProperties {+ self.inner_shape.mass_properties(density)+ }++ fn is_convex(&self) -> bool {+ self.inner_shape.is_convex()+ }++ fn shape_type(&self) -> ShapeType {+ ShapeType::$Tag+ }++ fn as_typed_shape(&self) -> TypedShape<'_> {+ TypedShape::$Tag(self)+ }++ fn ccd_thickness(&self) -> Real {+ self.inner_shape.ccd_thickness() + self.border_radius+ }++ fn ccd_angular_thickness(&self) -> Real {+ // The fact that the shape is round doesn't change anything+ // to the CCD angular thickness.+ self.inner_shape.ccd_angular_thickness()+ }++ fn as_support_map(&self) -> Option<&dyn SupportMap> {+ Some(self as &dyn SupportMap)+ }++ fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {+ Some((&self.inner_shape as &dyn PolygonalFeatureMap, self.border_radius))+ }+ }+ }+);++impl_shape_for_round_shape!(+ Cuboid,+ RoundCuboid,+ (|this: &Self, scale: Vector, _num_subdivisions: u32| {+ let shape = RoundShape {+ border_radius: this.border_radius,+ inner_shape: this.inner_shape.scaled(scale),+ };+ Some(Box::new(shape) as Box<dyn Shape>)+ })+);++impl_shape_for_round_shape!(+ Triangle,+ RoundTriangle,+ (|this: &Self, scale: Vector, _num_subdivisions: u32| {+ let shape = RoundShape {+ border_radius: this.border_radius,+ inner_shape: this.inner_shape.scaled(scale),+ };+ Some(Box::new(shape) as Box<dyn Shape>)+ })+);++#[cfg(feature = "dim2")]+#[cfg(feature = "alloc")]+impl_shape_for_round_shape!(+ ConvexPolygon,+ RoundConvexPolygon,+ (|this: &Self, scale: Vector, _num_subdivisions: u32| {+ let shape = RoundShape {+ border_radius: this.border_radius,+ inner_shape: this.inner_shape.clone().scaled(scale)?,+ };+ Some(Box::new(shape) as Box<dyn Shape>)+ })+);++#[cfg(feature = "dim3")]+impl_shape_for_round_shape!(+ Cylinder,+ RoundCylinder,+ (|this: &Self, scale: Vector, num_subdivisions: u32| {+ Some(+ this.inner_shape+ .scaled(scale, num_subdivisions)?+ .either::<_, _, Box<dyn Shape>>(+ |inner_shape| {+ Box::new(RoundShape {+ border_radius: this.border_radius,+ inner_shape,+ })+ },+ |inner_shape| {+ Box::new(RoundShape {+ border_radius: this.border_radius,+ inner_shape,+ })+ },+ ),+ )+ })+);+#[cfg(feature = "dim3")]+impl_shape_for_round_shape!(+ Cone,+ RoundCone,+ (|this: &Self, scale: Vector, num_subdivisions: u32| {+ Some(+ this.inner_shape+ .scaled(scale, num_subdivisions)?+ .either::<_, _, Box<dyn Shape>>(+ |inner_shape| {+ Box::new(RoundShape {+ border_radius: this.border_radius,+ inner_shape,+ })+ },+ |inner_shape| {+ Box::new(RoundShape {+ border_radius: this.border_radius,+ inner_shape,+ })+ },+ ),+ )+ })+);++#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+impl_shape_for_round_shape!(+ ConvexPolyhedron,+ RoundConvexPolyhedron,+ (|this: &Self, scale: Vector, _num_subdivisions: u32| {+ let shape = RoundShape {+ border_radius: this.border_radius,+ inner_shape: this.inner_shape.clone().scaled(scale)?,+ };+ Some(Box::new(shape) as Box<dyn Shape>)+ })+);diff --git a/renderer/third_party/parry3d/src/shape/shared_shape.rs b/renderer/third_party/parry3d/src/shape/shared_shape.rsnew file mode 100644index 0000000..b83c477--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/shared_shape.rs@@ -0,0 +1,715 @@+use super::TriMeshBuilderError;+use crate::math::{IVector, Pose, Real, Vector, DIM};+#[cfg(feature = "dim2")]+use crate::shape::ConvexPolygon;+#[cfg(feature = "serde-serialize")]+use crate::shape::DeserializableTypedShape;+#[cfg(feature = "dim3")]+use crate::shape::HeightFieldFlags;+use crate::shape::{+ Ball, Capsule, Compound, Cuboid, HalfSpace, HeightField, Polyline, RoundShape, Segment, Shape,+ TriMesh, TriMeshFlags, Triangle, TypedShape, Voxels,+};+#[cfg(feature = "dim3")]+use crate::shape::{Cone, ConvexPolyhedron, Cylinder};+use crate::transformation::vhacd::{VHACDParameters, VHACD};+use crate::transformation::voxelization::{FillMode, VoxelSet};+#[cfg(feature = "dim3")]+use crate::utils::Array2;+use alloc::sync::Arc;+use alloc::{vec, vec::Vec};+use core::fmt;+use core::ops::Deref;++/// A reference-counted, shareable geometric shape.+///+/// `SharedShape` is a wrapper around [`Arc<dyn Shape>`] that allows multiple parts of your+/// code to share ownership of the same shape without copying it. This is particularly useful+/// when the same geometric shape is used by multiple colliders or when you want to avoid+/// the memory overhead of duplicating complex shapes like triangle meshes.+///+/// # Why use SharedShape?+///+/// - **Memory efficiency**: Share expensive shapes (like [`TriMesh`] or [`HeightField`]) across multiple colliders+/// - **Performance**: Cloning a `SharedShape` only increments a reference count, not the shape data+/// - **Type erasure**: Store different shape types uniformly via the [`Shape`] trait+/// - **Flexibility**: Can be converted to a unique instance via [`make_mut`](Self::make_mut) when needed+///+/// # When to use SharedShape?+///+/// Use `SharedShape` when:+/// - You need multiple colliders with the same geometry+/// - You're working with large, complex shapes (meshes, compounds, heightfields)+/// - You want to store heterogeneous shape types in a collection+///+/// Use concrete shape types directly when:+/// - You have a single, simple shape that won't be shared+/// - You need direct access to shape-specific methods+///+/// # Examples+///+/// Creating and sharing a ball shape:+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::shape::SharedShape;+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::shape::SharedShape;+///+/// // Create a ball with radius 1.0+/// let shape = SharedShape::ball(1.0);+///+/// // Clone it cheaply - only the Arc is cloned, not the shape data+/// let shape_clone = shape.clone();+///+/// // Both shapes reference the same underlying ball+/// assert_eq!(shape.as_ball().unwrap().radius, 1.0);+/// assert_eq!(shape_clone.as_ball().unwrap().radius, 1.0);+/// # }+/// # }+/// ```+#[derive(Clone)]+pub struct SharedShape(pub Arc<dyn Shape>);++impl Deref for SharedShape {+ type Target = dyn Shape;+ fn deref(&self) -> &dyn Shape {+ &*self.0+ }+}++impl AsRef<dyn Shape> for SharedShape {+ fn as_ref(&self) -> &dyn Shape {+ &*self.0+ }+}++impl fmt::Debug for SharedShape {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ let typed_shape: TypedShape = (*self.0).as_typed_shape();+ write!(f, "SharedShape ( Arc<{typed_shape:?}> )")+ }+}++impl SharedShape {+ /// Wraps any shape type into a `SharedShape`.+ ///+ /// This constructor accepts any type that implements the [`Shape`] trait and wraps it+ /// in an `Arc` for shared ownership.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{SharedShape, Ball};+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::shape::{SharedShape, Ball};+ ///+ /// let ball = Ball::new(1.0);+ /// let shared = SharedShape::new(ball);+ /// # }+ /// # }+ /// ```+ pub fn new(shape: impl Shape) -> Self {+ Self(Arc::new(shape))+ }++ /// Returns a mutable reference to the underlying shape, cloning it if necessary.+ ///+ /// This method implements copy-on-write semantics. If the `Arc` has multiple references,+ /// it will clone the shape data to create a unique instance. Otherwise, no cloning occurs.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::SharedShape;+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::shape::SharedShape;+ ///+ /// let mut shape1 = SharedShape::ball(1.0);+ /// let shape2 = shape1.clone(); // Shares the same Arc+ ///+ /// // This will clone the shape because it's shared+ /// let ball = shape1.make_mut().as_ball_mut().unwrap();+ /// ball.radius = 2.0;+ ///+ /// // shape1 has been modified, shape2 still has the original value+ /// assert_eq!(shape1.as_ball().unwrap().radius, 2.0);+ /// assert_eq!(shape2.as_ball().unwrap().radius, 1.0);+ /// # }+ /// # }+ /// ```+ pub fn make_mut(&mut self) -> &mut dyn Shape {+ if Arc::get_mut(&mut self.0).is_none() {+ let unique_self = self.0.clone_dyn();+ self.0 = unique_self.into();+ }+ Arc::get_mut(&mut self.0).unwrap()+ }++ /// Creates a compound shape made of multiple subshapes.+ ///+ /// Each subshape has its own position and orientation relative to the compound's origin.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::SharedShape;+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::math::Pose;+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::shape::SharedShape;+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::math::Pose;+ ///+ /// let ball1 = SharedShape::ball(0.5);+ /// let ball2 = SharedShape::ball(0.5);+ ///+ /// #[cfg(feature = "dim3")]+ /// let compound = SharedShape::compound(vec![+ /// (Pose::translation(1.0, 0.0, 0.0), ball1),+ /// (Pose::translation(-1.0, 0.0, 0.0), ball2),+ /// ]);+ ///+ /// #[cfg(feature = "dim2")]+ /// let compound = SharedShape::compound(vec![+ /// (Pose::translation(1.0, 0.0), ball1),+ /// (Pose::translation(-1.0, 0.0), ball2),+ /// ]);+ /// # }+ /// # }+ /// # }+ /// # }+ /// ```+ pub fn compound(shapes: Vec<(Pose, SharedShape)>) -> Self {+ let raw_shapes = shapes.into_iter().map(|s| (s.0, s.1)).collect();+ let compound = Compound::new(raw_shapes);+ SharedShape(Arc::new(compound))+ }++ /// Creates a ball (sphere in 3D, circle in 2D) with the specified radius.+ ///+ /// A ball is the simplest and most efficient collision shape.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::SharedShape;+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::shape::SharedShape;+ ///+ /// let ball = SharedShape::ball(1.0);+ /// assert_eq!(ball.as_ball().unwrap().radius, 1.0);+ /// # }+ /// # }+ /// ```+ pub fn ball(radius: Real) -> Self {+ SharedShape(Arc::new(Ball::new(radius)))+ }++ /// Initialize a plane shape defined by its outward normal.+ pub fn halfspace(outward_normal: Vector) -> Self {+ SharedShape(Arc::new(HalfSpace::new(outward_normal)))+ }++ /// Initialize a cylindrical shape defined by its half-height+ /// (along the y axis) and its radius.+ #[cfg(feature = "dim3")]+ pub fn cylinder(half_height: Real, radius: Real) -> Self {+ SharedShape(Arc::new(Cylinder::new(half_height, radius)))+ }++ /// Initialize a rounded cylindrical shape defined by its half-height+ /// (along along the y axis), its radius, and its roundedness (the+ /// radius of the sphere used for dilating the cylinder).+ #[cfg(feature = "dim3")]+ pub fn round_cylinder(half_height: Real, radius: Real, border_radius: Real) -> Self {+ SharedShape(Arc::new(RoundShape {+ inner_shape: Cylinder::new(half_height, radius),+ border_radius,+ }))+ }++ /// Initialize a rounded cone shape defined by its half-height+ /// (along along the y axis), its radius, and its roundedness (the+ /// radius of the sphere used for dilating the cylinder).+ #[cfg(feature = "dim3")]+ pub fn round_cone(half_height: Real, radius: Real, border_radius: Real) -> Self {+ SharedShape(Arc::new(RoundShape {+ inner_shape: Cone::new(half_height, radius),+ border_radius,+ }))+ }++ /// Initialize a cone shape defined by its half-height+ /// (along along the y axis) and its basis radius.+ #[cfg(feature = "dim3")]+ pub fn cone(half_height: Real, radius: Real) -> Self {+ SharedShape(Arc::new(Cone::new(half_height, radius)))+ }++ /// Initialize a cuboid shape defined by its half-extents.+ #[cfg(feature = "dim2")]+ pub fn cuboid(hx: Real, hy: Real) -> Self {+ SharedShape(Arc::new(Cuboid::new(Vector::new(hx, hy))))+ }++ /// Initialize a round cuboid shape defined by its half-extents and border radius.+ #[cfg(feature = "dim2")]+ pub fn round_cuboid(hx: Real, hy: Real, border_radius: Real) -> Self {+ SharedShape(Arc::new(RoundShape {+ inner_shape: Cuboid::new(Vector::new(hx, hy)),+ border_radius,+ }))+ }++ /// Creates a cuboid (box) with specified half-extents.+ ///+ /// In 3D: creates a box defined by half-extents along X, Y, and Z axes.+ /// In 2D: creates a rectangle defined by half-extents along X and Y axes.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::SharedShape;+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::shape::SharedShape;+ ///+ /// #[cfg(feature = "dim3")]+ /// let cuboid = SharedShape::cuboid(1.0, 2.0, 3.0); // Box with dimensions 2x4x6+ /// #[cfg(feature = "dim2")]+ /// let cuboid = SharedShape::cuboid(1.0, 2.0); // Rectangle with dimensions 2x4+ /// # }+ /// # }+ /// ```+ #[cfg(feature = "dim3")]+ pub fn cuboid(hx: Real, hy: Real, hz: Real) -> Self {+ SharedShape(Arc::new(Cuboid::new(Vector::new(hx, hy, hz))))+ }++ /// Initialize a round cuboid shape defined by its half-extents and border radius.+ #[cfg(feature = "dim3")]+ pub fn round_cuboid(hx: Real, hy: Real, hz: Real, border_radius: Real) -> Self {+ SharedShape(Arc::new(RoundShape {+ inner_shape: Cuboid::new(Vector::new(hx, hy, hz)),+ border_radius,+ }))+ }++ /// Initialize a capsule shape from its endpoints and radius.+ pub fn capsule(a: Vector, b: Vector, radius: Real) -> Self {+ SharedShape(Arc::new(Capsule::new(a, b, radius)))+ }++ /// Initialize a capsule shape aligned with the `x` axis.+ pub fn capsule_x(half_height: Real, radius: Real) -> Self {+ let p = Vector::X * half_height;+ Self::capsule(-p, p, radius)+ }++ /// Creates a capsule aligned with the Y axis.+ ///+ /// A capsule is a line segment with rounded ends, commonly used for character controllers.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::SharedShape;+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::shape::SharedShape;+ ///+ /// // Create a character capsule: 1.8 units tall with 0.3 radius+ /// let character = SharedShape::capsule_y(0.9, 0.3);+ /// # }+ /// # }+ /// ```+ pub fn capsule_y(half_height: Real, radius: Real) -> Self {+ let p = Vector::Y * half_height;+ Self::capsule(-p, p, radius)+ }++ /// Initialize a capsule shape aligned with the `z` axis.+ #[cfg(feature = "dim3")]+ pub fn capsule_z(half_height: Real, radius: Real) -> Self {+ let p = Vector::Z * half_height;+ Self::capsule(-p, p, radius)+ }++ /// Initialize a segment shape from its endpoints.+ pub fn segment(a: Vector, b: Vector) -> Self {+ SharedShape(Arc::new(Segment::new(a, b)))+ }++ /// Initializes a triangle shape.+ pub fn triangle(a: Vector, b: Vector, c: Vector) -> Self {+ SharedShape(Arc::new(Triangle::new(a, b, c)))+ }+ /// Initializes a triangle shape with round corners.+ pub fn round_triangle(a: Vector, b: Vector, c: Vector, border_radius: Real) -> Self {+ SharedShape(Arc::new(RoundShape {+ inner_shape: Triangle::new(a, b, c),+ border_radius,+ }))+ }++ /// Initializes a polyline shape defined by its vertex and index buffers.+ ///+ /// If no index buffer is provided, the polyline is assumed to describe a line strip.+ pub fn polyline(vertices: Vec<Vector>, indices: Option<Vec<[u32; 2]>>) -> Self {+ SharedShape(Arc::new(Polyline::new(vertices, indices)))+ }++ /// Creates a triangle mesh shape from vertices and triangle indices.+ ///+ /// A triangle mesh represents a complex surface as a collection of triangles, useful for+ /// terrain, static geometry, or any shape that can't be represented by simpler primitives.+ ///+ /// # Returns+ ///+ /// Returns `Ok(SharedShape)` if the mesh is valid, or an error if indices are out of bounds.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::SharedShape;+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::math::Vector;+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::shape::SharedShape;+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::math::Vector;+ ///+ /// #[cfg(feature = "dim3")]+ /// let vertices = vec![+ /// Vector::new(0.0, 0.0, 0.0),+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// #[cfg(feature = "dim3")]+ /// let indices = vec![[0, 1, 2]];+ /// #[cfg(feature = "dim3")]+ /// let mesh = SharedShape::trimesh(vertices, indices).unwrap();+ /// # }+ /// # }+ /// # }+ /// # }+ /// ```+ pub fn trimesh(+ vertices: Vec<Vector>,+ indices: Vec<[u32; 3]>,+ ) -> Result<Self, TriMeshBuilderError> {+ Ok(SharedShape(Arc::new(TriMesh::new(vertices, indices)?)))+ }++ /// Initializes a triangle mesh shape defined by its vertex and index buffers and+ /// pre-processing flags.+ pub fn trimesh_with_flags(+ vertices: Vec<Vector>,+ indices: Vec<[u32; 3]>,+ flags: TriMeshFlags,+ ) -> Result<Self, TriMeshBuilderError> {+ Ok(SharedShape(Arc::new(TriMesh::with_flags(+ vertices, indices, flags,+ )?)))+ }++ /// Initializes a shape made of voxels.+ ///+ /// Each voxel has the size `voxel_size` and grid coordinate given by `grid_coords`.+ /// The `primitive_geometry` controls the behavior of collision detection at voxels boundaries.+ ///+ /// For initializing a voxels shape from points in space, see [`Self::voxels_from_points`].+ /// For initializing a voxels shape from a mesh to voxelize, see [`Self::voxelized_mesh`].+ /// For initializing multiple voxels shape from the convex decomposition of a mesh, see+ /// [`Self::voxelized_convex_decomposition`].+ pub fn voxels(voxel_size: Vector, grid_coords: &[IVector]) -> Self {+ let shape = Voxels::new(voxel_size, grid_coords);+ SharedShape::new(shape)+ }++ /// Initializes a shape made of voxels.+ ///+ /// Each voxel has the size `voxel_size` and contains at least one point from `centers`.+ /// The `primitive_geometry` controls the behavior of collision detection at voxels boundaries.+ pub fn voxels_from_points(voxel_size: Vector, points: &[Vector]) -> Self {+ let shape = Voxels::from_points(voxel_size, points);+ SharedShape::new(shape)+ }++ /// Initializes a voxels shape obtained from the decomposition of the given trimesh (in 3D)+ /// or polyline (in 2D) into voxelized convex parts.+ pub fn voxelized_mesh(+ vertices: &[Vector],+ indices: &[[u32; DIM]],+ voxel_size: Real,+ fill_mode: FillMode,+ ) -> Self {+ let mut voxels = VoxelSet::with_voxel_size(vertices, indices, voxel_size, fill_mode, true);+ voxels.compute_bb();+ Self::from_voxel_set(&voxels)+ }++ fn from_voxel_set(vox_set: &VoxelSet) -> Self {+ let centers: Vec<_> = vox_set+ .voxels()+ .iter()+ .map(|v| vox_set.get_voxel_point(v))+ .collect();+ let shape = Voxels::from_points(Vector::splat(vox_set.scale), ¢ers);+ SharedShape::new(shape)+ }++ /// Initializes a compound shape obtained from the decomposition of the given trimesh (in 3D)+ /// or polyline (in 2D) into voxelized convex parts.+ pub fn voxelized_convex_decomposition(+ vertices: &[Vector],+ indices: &[[u32; DIM]],+ ) -> Vec<Self> {+ Self::voxelized_convex_decomposition_with_params(+ vertices,+ indices,+ &VHACDParameters::default(),+ )+ }++ /// Initializes a compound shape obtained from the decomposition of the given trimesh (in 3D)+ /// or polyline (in 2D) into voxelized convex parts.+ pub fn voxelized_convex_decomposition_with_params(+ vertices: &[Vector],+ indices: &[[u32; DIM]],+ params: &VHACDParameters,+ ) -> Vec<Self> {+ let mut parts = vec![];+ let decomp = VHACD::decompose(params, vertices, indices, true);++ for vox_set in decomp.voxel_parts() {+ parts.push(Self::from_voxel_set(vox_set));+ }++ parts+ }++ /// Initializes a compound shape obtained from the decomposition of the given trimesh (in 3D) or+ /// polyline (in 2D) into convex parts.+ pub fn convex_decomposition(vertices: &[Vector], indices: &[[u32; DIM]]) -> Self {+ Self::convex_decomposition_with_params(vertices, indices, &VHACDParameters::default())+ }++ /// Initializes a compound shape obtained from the decomposition of the given trimesh (in 3D) or+ /// polyline (in 2D) into convex parts dilated with round corners.+ pub fn round_convex_decomposition(+ vertices: &[Vector],+ indices: &[[u32; DIM]],+ border_radius: Real,+ ) -> Self {+ Self::round_convex_decomposition_with_params(+ vertices,+ indices,+ &VHACDParameters::default(),+ border_radius,+ )+ }++ /// Initializes a compound shape obtained from the decomposition of the given trimesh (in 3D) or+ /// polyline (in 2D) into convex parts.+ pub fn convex_decomposition_with_params(+ vertices: &[Vector],+ indices: &[[u32; DIM]],+ params: &VHACDParameters,+ ) -> Self {+ let mut parts = vec![];+ let decomp = VHACD::decompose(params, vertices, indices, true);++ #[cfg(feature = "dim2")]+ for vertices in decomp.compute_exact_convex_hulls(vertices, indices) {+ if let Some(convex) = Self::convex_polyline(vertices) {+ parts.push((Pose::IDENTITY, convex));+ }+ }++ #[cfg(feature = "dim3")]+ for (vertices, indices) in decomp.compute_exact_convex_hulls(vertices, indices) {+ if let Some(convex) = Self::convex_mesh(vertices, &indices) {+ parts.push((Pose::IDENTITY, convex));+ }+ }++ Self::compound(parts)+ }++ /// Initializes a compound shape obtained from the decomposition of the given trimesh (in 3D) or+ /// polyline (in 2D) into convex parts dilated with round corners.+ pub fn round_convex_decomposition_with_params(+ vertices: &[Vector],+ indices: &[[u32; DIM]],+ params: &VHACDParameters,+ border_radius: Real,+ ) -> Self {+ let mut parts = vec![];+ let decomp = VHACD::decompose(params, vertices, indices, true);++ #[cfg(feature = "dim2")]+ for vertices in decomp.compute_exact_convex_hulls(vertices, indices) {+ if let Some(convex) = Self::round_convex_polyline(vertices, border_radius) {+ parts.push((Pose::IDENTITY, convex));+ }+ }++ #[cfg(feature = "dim3")]+ for (vertices, indices) in decomp.compute_exact_convex_hulls(vertices, indices) {+ if let Some(convex) = Self::round_convex_mesh(vertices, &indices, border_radius) {+ parts.push((Pose::IDENTITY, convex));+ }+ }++ Self::compound(parts)+ }++ /// Creates a new shared shape that is the convex-hull of the given points.+ pub fn convex_hull(points: &[Vector]) -> Option<Self> {+ #[cfg(feature = "dim2")]+ return ConvexPolygon::from_convex_hull(points).map(|ch| SharedShape(Arc::new(ch)));+ #[cfg(feature = "dim3")]+ return ConvexPolyhedron::from_convex_hull(points).map(|ch| SharedShape(Arc::new(ch)));+ }++ /// Creates a new shared shape that is a 2D convex polygon from a set of points assumed to+ /// describe a counter-clockwise convex polyline.+ ///+ /// This does **not** compute the convex-hull of the input points: convexity of the input is+ /// assumed and not checked. For a version that calculates the convex hull of the input points,+ /// use [`SharedShape::convex_hull`] instead.+ ///+ /// The generated [`ConvexPolygon`] will contain the given `points` with any point+ /// collinear to the previous and next ones removed. For a version that leaves the input+ /// `points` unmodified, use [`SharedShape::convex_polyline_unmodified`].+ ///+ /// Returns `None` if all points form an almost flat line.+ #[cfg(feature = "dim2")]+ pub fn convex_polyline(points: Vec<Vector>) -> Option<Self> {+ ConvexPolygon::from_convex_polyline(points).map(|ch| SharedShape(Arc::new(ch)))+ }++ /// Creates a new shared shape that is a 2D convex polygon from a set of points assumed to+ /// describe a counter-clockwise convex polyline.+ ///+ /// This is the same as [`SharedShape::convex_polyline`] but without removing any point+ /// from the input even if some are coplanar.+ ///+ /// Returns `None` if `points` doesn’t contain at least three points.+ #[cfg(feature = "dim2")]+ pub fn convex_polyline_unmodified(points: Vec<Vector>) -> Option<Self> {+ ConvexPolygon::from_convex_polyline_unmodified(points).map(|ch| SharedShape(Arc::new(ch)))+ }++ /// Creates a new shared shape that is a convex polyhedron formed by the+ /// given set of points assumed to form a convex mesh (no convex-hull will be automatically+ /// computed).+ #[cfg(feature = "dim3")]+ pub fn convex_mesh(points: Vec<Vector>, indices: &[[u32; 3]]) -> Option<Self> {+ ConvexPolyhedron::from_convex_mesh(points, indices).map(|ch| SharedShape(Arc::new(ch)))+ }++ /// Creates a new shared shape with rounded corners that is the+ /// convex-hull of the given points, dilated by `border_radius`.+ pub fn round_convex_hull(points: &[Vector], border_radius: Real) -> Option<Self> {+ #[cfg(feature = "dim2")]+ return ConvexPolygon::from_convex_hull(points).map(|ch| {+ SharedShape(Arc::new(RoundShape {+ inner_shape: ch,+ border_radius,+ }))+ });+ #[cfg(feature = "dim3")]+ return ConvexPolyhedron::from_convex_hull(points).map(|ch| {+ SharedShape(Arc::new(RoundShape {+ inner_shape: ch,+ border_radius,+ }))+ });+ }++ /// Creates a new shared shape with round corners that is a convex polygon formed by the+ /// given set of points assumed to form a convex polyline (no convex-hull will be automatically+ /// computed).+ #[cfg(feature = "dim2")]+ pub fn round_convex_polyline(points: Vec<Vector>, border_radius: Real) -> Option<Self> {+ ConvexPolygon::from_convex_polyline(points).map(|ch| {+ SharedShape(Arc::new(RoundShape {+ inner_shape: ch,+ border_radius,+ }))+ })+ }++ /// Creates a new shared shape with round corners that is a convex polyhedron formed by the+ /// given set of points assumed to form a convex mesh (no convex-hull will be automatically+ /// computed).+ #[cfg(feature = "dim3")]+ pub fn round_convex_mesh(+ points: Vec<Vector>,+ indices: &[[u32; 3]],+ border_radius: Real,+ ) -> Option<Self> {+ ConvexPolyhedron::from_convex_mesh(points, indices).map(|ch| {+ SharedShape(Arc::new(RoundShape {+ inner_shape: ch,+ border_radius,+ }))+ })+ }++ /// Initializes a heightfield shape defined by its set of height and a scale+ /// factor along each coordinate axis.+ #[cfg(feature = "dim2")]+ pub fn heightfield(heights: Vec<Real>, scale: Vector) -> Self {+ SharedShape(Arc::new(HeightField::new(heights, scale)))+ }++ /// Initializes a heightfield shape on the x-z plane defined by its set of height and a scale+ /// factor along each coordinate axis.+ #[cfg(feature = "dim3")]+ pub fn heightfield(heights: Array2<Real>, scale: Vector) -> Self {+ SharedShape(Arc::new(HeightField::new(heights, scale)))+ }++ /// Initializes a heightfield shape on the x-z plane defined by its set of height, a scale+ /// factor along each coordinate axis, and [`HeightFieldFlags`].+ #[cfg(feature = "dim3")]+ pub fn heightfield_with_flags(+ heights: Array2<Real>,+ scale: Vector,+ flags: HeightFieldFlags,+ ) -> Self {+ SharedShape(Arc::new(HeightField::with_flags(heights, scale, flags)))+ }+}++#[cfg(feature = "serde-serialize")]+impl serde::Serialize for SharedShape {+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: serde::Serializer,+ {+ self.0.as_typed_shape().serialize(serializer)+ }+}++#[cfg(feature = "serde-serialize")]+impl<'de> serde::Deserialize<'de> for SharedShape {+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>+ where+ D: serde::Deserializer<'de>,+ {+ use crate::serde::de::Error;+ DeserializableTypedShape::deserialize(deserializer)?+ .into_shared_shape()+ .ok_or(D::Error::custom("Cannot deserialize custom shape."))+ }+}diff --git a/renderer/third_party/parry3d/src/shape/support_map.rs b/renderer/third_party/parry3d/src/shape/support_map.rsnew file mode 100644index 0000000..262490f--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/support_map.rs@@ -0,0 +1,447 @@+//! Traits for support mapping based shapes.+//!+//! # What is a Support Map?+//!+//! A **support map** (or support function) is a fundamental concept in computational geometry that+//! describes a convex shape by answering a simple question: "What point on the shape is furthest+//! in a given direction?"+//!+//! More formally, for a convex shape `S` and a direction vector `d`, the support function returns:+//!+//! ```text+//! support(S, d) = argmax { p · d : p ∈ S }+//! ```+//!+//! Where `p · d` is the dot product between a point `p` on the shape and the direction `d`.+//!+//! ## Visual Intuition+//!+//! Imagine shining a light from infinity in direction `d` onto your shape. The support point+//! is where the "shadow" boundary would be - the point that sticks out furthest in that direction.+//!+//! For example, for a circle centered at the origin with radius `r`:+//! - If `d = (1, 0)` (pointing right), the support point is `(r, 0)` (rightmost point)+//! - If `d = (0, 1)` (pointing up), the support point is `(0, r)` (topmost point)+//! - If `d = (1, 1)` (diagonal), the support point is `(r/√2, r/√2)` (northeast point)+//!+//! ## Why Support Maps Matter for Collision Detection+//!+//! Support maps are the foundation of two powerful collision detection algorithms:+//!+//! ### 1. GJK Algorithm (Gilbert-Johnson-Keerthi)+//!+//! GJK is an iterative algorithm that determines:+//! - Whether two convex shapes intersect+//! - The distance between two separated shapes+//! - The closest points between two shapes+//!+//! GJK works by computing the **Minkowski difference** of two shapes using only their support+//! functions. It builds a simplex (a simple polytope) that converges toward the origin, allowing+//! it to answer collision queries without ever explicitly computing the shapes' geometry.+//!+//! **Key advantage**: GJK only needs the support function - it never needs to know the actual+//! vertices, faces, or internal structure of the shapes. This makes it incredibly flexible and+//! efficient.+//!+//! ### 2. EPA Algorithm (Expanding Polytope Algorithm)+//!+//! EPA is used when two shapes are penetrating (overlapping). It computes:+//! - The penetration depth (how much they overlap)+//! - The penetration normal (the direction to separate them)+//! - Contact points for physics simulation+//!+//! EPA starts with the final simplex from GJK and expands it into a polytope that approximates+//! the Minkowski difference, converging toward the shallowest penetration.+//!+//! ## Why Support Maps are Efficient+//!+//! 1. **Simple to implement**: For most convex shapes, the support function is straightforward+//! 2. **No geometry storage**: Implicit shapes (like spheres, capsules) don't need vertex data+//! 3. **Transform-friendly**: Easy to handle rotations and translations+//! 4. **Composable**: Can combine support functions for compound shapes+//! 5. **Fast queries**: Often just a few dot products and comparisons+//!+//! ## Examples of Support Functions+//!+//! Here are some common shapes and their support functions:+//!+//! ### Sphere/Ball+//! ```text+//! support(sphere, d) = center + normalize(d) * radius+//! ```+//!+//! ### Cuboid (Box)+//! ```text+//! support(box, d) = (sign(d.x) * half_width,+//! sign(d.y) * half_height,+//! sign(d.z) * half_depth)+//! ```+//!+//! ### Convex Polygon/Polyhedron+//! ```text+//! support(poly, d) = vertex with maximum dot product with d+//! ```+//!+//! ## Limitations+//!+//! Support maps only work for **convex** shapes. Concave shapes must be decomposed into+//! convex parts or handled with different algorithms. This is why Parry provides composite+//! shapes and specialized algorithms for triangle meshes.++use crate::math::{Pose, Vector};++/// Trait for convex shapes representable by a support mapping function.+///+/// A support map is a function that returns the point on a shape that is furthest in a given+/// direction. This is the fundamental building block for collision detection algorithms like+/// GJK (Gilbert-Johnson-Keerthi) and EPA (Expanding Polytope Algorithm).+///+/// # What You Need to Know+///+/// If you're implementing this trait for a custom shape, you only need to implement+/// [`local_support_point`](SupportMap::local_support_point). The other methods have default+/// implementations that handle transformations and normalized directions.+///+/// # Requirements+///+/// - The shape **must be convex**. Non-convex shapes will produce incorrect results.+/// - The support function should return a point on the surface of the shape (or inside it,+/// but surface points are preferred for better accuracy).+/// - For a given direction `d`, the returned point `p` should maximize `p · d` (dot product).+///+/// # Examples+///+/// ## Using Support Maps for Distance Queries+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Ball, Cuboid, SupportMap};+/// use parry3d::math::{Vector, Real};+///+/// // Create a ball (sphere) with radius 1.0+/// let ball = Ball::new(1.0);+///+/// // Get the support point in the direction (1, 0, 0) - pointing right+/// let dir = Vector::new(1.0, 0.0, 0.0);+/// let support_point = ball.local_support_point(dir);+///+/// // For a ball centered at origin, this should be approximately (1, 0, 0)+/// assert!((support_point.x - 1.0).abs() < 1e-6);+/// assert!(support_point.y.abs() < 1e-6);+/// assert!(support_point.z.abs() < 1e-6);+///+/// // Try another direction - diagonal up and right+/// let dir2 = Vector::new(1.0, 1.0, 0.0);+/// let support_point2 = ball.local_support_point(dir2);+///+/// // The point should be on the surface of the ball (distance = radius)+/// let distance = (support_point2.length() - 1.0).abs();+/// assert!(distance < 1e-6);+/// # }+/// ```+///+/// ## Support Vectors on a Cuboid+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Cuboid, SupportMap};+/// use parry3d::math::Vector;+///+/// // Create a cuboid (box) with half-extents 2x3x4+/// let cuboid = Cuboid::new(Vector::new(2.0, 3.0, 4.0));+///+/// // Support point in positive X direction should be at the right face+/// let dir_x = Vector::new(1.0, 0.0, 0.0);+/// let support_x = cuboid.local_support_point(dir_x);+/// assert!((support_x.x - 2.0).abs() < 1e-6);+///+/// // Support point in negative Y direction should be at the bottom face+/// let dir_neg_y = Vector::new(0.0, -1.0, 0.0);+/// let support_neg_y = cuboid.local_support_point(dir_neg_y);+/// assert!((support_neg_y.y + 3.0).abs() < 1e-6);+///+/// // Support point in diagonal direction should be at a corner+/// let dir_diag = Vector::new(1.0, 1.0, 1.0);+/// let support_diag = cuboid.local_support_point(dir_diag);+/// assert!((support_diag.x - 2.0).abs() < 1e-6);+/// assert!((support_diag.y - 3.0).abs() < 1e-6);+/// assert!((support_diag.z - 4.0).abs() < 1e-6);+/// # }+/// ```+///+/// ## Implementing SupportMap for a Custom Shape+///+/// Here's how you might implement `SupportMap` for a simple custom shape:+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # // Note: This example shows the concept but won't actually compile in doc tests+/// # // since we can't implement traits for external types in doc tests.+/// # // It's here for educational purposes.+/// use parry3d::shape::SupportMap;+/// use parry3d::math::{Vector, Real};+///+/// // A simple pill-shaped object aligned with the X axis+/// struct SimplePill {+/// half_length: Real, // Half the length of the cylindrical part+/// radius: Real, // Radius of the spherical ends+/// }+///+/// impl SupportMap for SimplePill {+/// fn local_support_point(&self, dir: Vector) -> Vector {+/// // Support point is on one of the spherical ends+/// // Choose the end that's in the direction of dir.x+/// let center_x = if dir.x >= 0.0 { self.half_length } else { -self.half_length };+///+/// // From that center, extend by radius in the direction of dir+/// let dir_normalized = dir.normalize();+/// Vector::new(+/// center_x + dir_normalized.x * self.radius,+/// dir_normalized.y * self.radius,+/// dir_normalized.z * self.radius,+/// )+/// }+/// }+/// # }+/// ```+pub trait SupportMap {+ /// Evaluates the support function of this shape in local space.+ ///+ /// The support function returns the point on the shape's surface (or interior) that is+ /// furthest in the given direction `dir`. More precisely, it finds the point `p` that+ /// maximizes the dot product `p · dir`.+ ///+ /// # Parameters+ ///+ /// - `dir`: The direction vector to query. Does not need to be normalized (unit length),+ /// but the result may be more intuitive with normalized directions.+ ///+ /// # Returns+ ///+ /// A point on (or inside) the shape that is furthest in the direction `dir`.+ ///+ /// # Implementation Notes+ ///+ /// When implementing this method:+ /// - The direction `dir` may have any length (including zero, though this is unusual)+ /// - For better numerical stability, consider normalizing `dir` if needed+ /// - The returned point should be in the shape's local coordinate system+ /// - If `dir` is zero or very small, a reasonable point (like the center) should be returned+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{Ball, SupportMap};+ /// use parry3d::math::Vector;+ ///+ /// let ball = Ball::new(2.5);+ ///+ /// // Support point pointing up (Z direction)+ /// let up = Vector::new(0.0, 0.0, 1.0);+ /// let support_up = ball.local_support_point(up);+ ///+ /// // Should be at the top of the ball+ /// assert!((support_up.z - 2.5).abs() < 1e-6);+ /// assert!(support_up.x.abs() < 1e-6);+ /// assert!(support_up.y.abs() < 1e-6);+ ///+ /// // Support point pointing in negative X direction+ /// let left = Vector::new(-1.0, 0.0, 0.0);+ /// let support_left = ball.local_support_point(left);+ ///+ /// // Should be at the left side of the ball+ /// assert!((support_left.x + 2.5).abs() < 1e-6);+ /// # }+ /// ```+ ///+ /// ## Why "local" support point?+ ///+ /// The "local" prefix means the point is in the shape's own coordinate system, before+ /// any rotation or translation is applied. For transformed shapes, use+ /// [`support_point`](SupportMap::support_point) instead.+ fn local_support_point(&self, dir: Vector) -> Vector;++ /// Same as [`local_support_point`](SupportMap::local_support_point) except that `dir` is+ /// guaranteed to be normalized (unit length).+ ///+ /// This can be more efficient for some shapes that can take advantage of the normalized+ /// direction vector. By default, this just forwards to `local_support_point`.+ ///+ /// # Parameters+ ///+ /// - `dir`: A unit-length direction vector (guaranteed by the type system)+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{Ball, SupportMap};+ /// use parry3d::math::Vector;+ ///+ /// let ball = Ball::new(1.5);+ ///+ /// // Create a normalized direction vector+ /// let dir = Vector::new(1.0, 1.0, 0.0).normalize();+ ///+ /// let support = ball.local_support_point_toward(dir);+ ///+ /// // The support point should be on the sphere's surface+ /// let distance_from_origin = support.length();+ /// assert!((distance_from_origin - 1.5).abs() < 1e-6);+ /// # }+ /// ```+ fn local_support_point_toward(&self, dir: Vector) -> Vector {+ self.local_support_point(dir)+ }++ /// Evaluates the support function of this shape transformed by `transform`.+ ///+ /// This is the world-space version of [`local_support_point`](SupportMap::local_support_point).+ /// It computes the support point for a shape that has been rotated and translated by the+ /// given isometry (rigid transformation).+ ///+ /// # How it Works+ ///+ /// The algorithm:+ /// 1. Transform the direction vector `dir` from world space to the shape's local space+ /// 2. Compute the support point in local space+ /// 3. Transform the support point from local space back to world space+ ///+ /// This is much more efficient than actually transforming the shape's geometry.+ ///+ /// # Parameters+ ///+ /// - `transform`: The rigid transformation (rotation + translation) applied to the shape+ /// - `dir`: The direction vector in world space+ ///+ /// # Returns+ ///+ /// A point in world space that is the furthest point on the transformed shape in direction `dir`.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{Ball, SupportMap};+ /// use parry3d::math::{Pose, Vector};+ ///+ /// let ball = Ball::new(1.0);+ ///+ /// // Create a transformation: translate the ball to (10, 0, 0)+ /// let transform = Pose::translation(10.0, 0.0, 0.0);+ ///+ /// // Get support point in the positive X direction+ /// let dir = Vector::new(1.0, 0.0, 0.0);+ /// let support = ball.support_point(&transform, dir);+ ///+ /// // The support point should be at (11, 0, 0) - the rightmost point of the translated ball+ /// assert!((support.x - 11.0).abs() < 1e-6);+ /// assert!(support.y.abs() < 1e-6);+ /// assert!(support.z.abs() < 1e-6);+ /// # }+ /// ```+ ///+ /// ## Example with Rotation+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{Cuboid, SupportMap};+ /// use parry3d::math::{Pose, Rotation, Vector};+ /// use core::f32::consts::PI;+ ///+ /// let cuboid = Cuboid::new(Vector::new(2.0, 1.0, 1.0));+ ///+ /// // Rotate the cuboid 90 degrees around the Z axis+ /// let rotation = Rotation::from_axis_angle(Vector::Z, PI / 2.0);+ /// let transform = Pose::from_parts(Vector::ZERO, rotation);+ ///+ /// // In world space, ask for support in the X direction+ /// let dir = Vector::new(1.0, 0.0, 0.0);+ /// let support = cuboid.support_point(&transform, dir);+ ///+ /// // After 90° rotation, the long axis (originally X) now points in Y direction+ /// // So the support in X direction comes from the short axis+ /// assert!(support.x.abs() <= 1.0 + 1e-5); // Should be around 1.0 (the short axis)+ /// # }+ /// ```+ fn support_point(&self, transform: &Pose, dir: Vector) -> Vector {+ let local_dir = transform.rotation.inverse() * dir;+ transform * self.local_support_point(local_dir)+ }++ /// Same as [`support_point`](SupportMap::support_point) except that `dir` is guaranteed+ /// to be normalized (unit length).+ ///+ /// This combines the benefits of both [`local_support_point_toward`](SupportMap::local_support_point_toward)+ /// (normalized direction) and [`support_point`](SupportMap::support_point) (world-space transform).+ ///+ /// # Parameters+ ///+ /// - `transform`: The rigid transformation applied to the shape+ /// - `dir`: A unit-length direction vector in world space+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{Ball, SupportMap};+ /// use parry3d::math::{Pose, Vector};+ ///+ /// let ball = Ball::new(2.0);+ ///+ /// // Translate the ball+ /// let transform = Pose::translation(5.0, 3.0, -2.0);+ ///+ /// // Create a normalized direction+ /// let dir = Vector::new(1.0, 1.0, 1.0).normalize();+ ///+ /// let support = ball.support_point_toward(&transform, dir);+ ///+ /// // The support point should be 2.0 units away from the center in the diagonal direction+ /// let center = Vector::new(5.0, 3.0, -2.0);+ /// let offset = support - center;+ /// let distance = offset.length();+ /// assert!((distance - 2.0).abs() < 1e-6);+ ///+ /// // The offset should be parallel to the direction+ /// let normalized_offset = offset.normalize();+ /// assert!((normalized_offset.dot(dir) - 1.0).abs() < 1e-6);+ /// # }+ /// ```+ ///+ /// ## Practical Use: GJK Algorithm+ ///+ /// This method is commonly used in the GJK algorithm, which needs to compute support points+ /// for transformed shapes with normalized directions for better numerical stability:+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{Ball, Cuboid, SupportMap};+ /// use parry3d::math::{Pose, Vector};+ ///+ /// // Two shapes at different positions+ /// let ball = Ball::new(1.0);+ /// let cuboid = Cuboid::new(Vector::new(0.5, 0.5, 0.5));+ ///+ /// let ball_pos = Pose::translation(0.0, 0.0, 0.0);+ /// let cuboid_pos = Pose::translation(3.0, 0.0, 0.0);+ ///+ /// // Direction from ball to cuboid+ /// let dir = Vector::new(1.0, 0.0, 0.0).normalize();+ ///+ /// // Get support points for the Minkowski difference (used in GJK)+ /// let support_ball = ball.support_point_toward(&ball_pos, dir);+ /// let support_cuboid = cuboid.support_point_toward(&cuboid_pos, -dir);+ ///+ /// // The Minkowski difference support point+ /// let minkowski_support = support_ball - support_cuboid;+ ///+ /// println!("Support point for Minkowski difference: {:?}", minkowski_support);+ /// # }+ /// ```+ fn support_point_toward(&self, transform: &Pose, dir: Vector) -> Vector {+ let local_dir = transform.rotation.inverse() * dir;+ transform * self.local_support_point_toward(local_dir)+ }+}diff --git a/renderer/third_party/parry3d/src/shape/tetrahedron.rs b/renderer/third_party/parry3d/src/shape/tetrahedron.rsnew file mode 100644index 0000000..504b178--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/tetrahedron.rs@@ -0,0 +1,722 @@+//! Definition of the tetrahedron shape.++use crate::math::{Matrix, Real, Vector};+use crate::shape::{Segment, Triangle};+use crate::utils;+use core::mem;++#[cfg(feature = "dim3")]+use crate::math::CrossMatrix; // Mat3 for glam++#[cfg(all(feature = "dim2", not(feature = "std")))]+use crate::math::ComplexField; // for .abs()++/// A tetrahedron with 4 vertices.+///+/// # What is a Tetrahedron?+///+/// A tetrahedron is the simplest 3D polyhedron, consisting of exactly **4 vertices**,+/// **6 edges**, and **4 triangular faces**. It's the 3D equivalent of a triangle in 2D.+/// Think of it as a pyramid with a triangular base.+///+/// # Structure+///+/// A tetrahedron has:+/// - **4 vertices** labeled `a`, `b`, `c`, and `d`+/// - **4 triangular faces**: ABC, ABD, ACD, and BCD+/// - **6 edges**: AB, AC, AD, BC, BD, and CD+///+/// # Common Use Cases+///+/// Tetrahedra are fundamental building blocks in many applications:+/// - **Mesh generation**: Tetrahedral meshes are used for finite element analysis (FEA)+/// - **Collision detection**: Simple convex shape for physics simulations+/// - **Volume computation**: Computing volumes of complex 3D shapes+/// - **Spatial partitioning**: Subdividing 3D space for games and simulations+/// - **Computer graphics**: Rendering and ray tracing acceleration structures+///+/// # Examples+///+/// ## Creating a Simple Tetrahedron+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Tetrahedron;+/// use parry3d::math::Vector;+///+/// // Create a tetrahedron with vertices at unit positions+/// let tetra = Tetrahedron::new(+/// Vector::new(0.0, 0.0, 0.0), // vertex a+/// Vector::new(1.0, 0.0, 0.0), // vertex b+/// Vector::new(0.0, 1.0, 0.0), // vertex c+/// Vector::new(0.0, 0.0, 1.0), // vertex d+/// );+///+/// println!("First vertex: {:?}", tetra.a);+/// # }+/// ```+///+/// ## Computing Volume+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Tetrahedron;+/// use parry3d::math::Vector;+///+/// // Create a regular tetrahedron+/// let tetra = Tetrahedron::new(+/// Vector::new(0.0, 0.0, 0.0),+/// Vector::new(1.0, 0.0, 0.0),+/// Vector::new(0.5, 0.866, 0.0),+/// Vector::new(0.5, 0.433, 0.816),+/// );+///+/// let volume = tetra.volume();+/// assert!(volume > 0.0);+/// println!("Volume: {}", volume);+/// # }+/// ```+///+/// ## Accessing Faces and Edges+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Tetrahedron;+/// use parry3d::math::Vector;+///+/// let tetra = Tetrahedron::new(+/// Vector::new(0.0, 0.0, 0.0),+/// Vector::new(1.0, 0.0, 0.0),+/// Vector::new(0.0, 1.0, 0.0),+/// Vector::new(0.0, 0.0, 1.0),+/// );+///+/// // Get the first face (triangle ABC)+/// let face = tetra.face(0);+/// println!("First face: {:?}", face);+///+/// // Get the first edge (segment AB)+/// let edge = tetra.edge(0);+/// println!("First edge: {:?}", edge);+/// # }+/// ```+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(Copy, Clone, Debug)]+#[repr(C)]+pub struct Tetrahedron {+ /// The tetrahedron's first vertex.+ pub a: Vector,+ /// The tetrahedron's second vertex.+ pub b: Vector,+ /// The tetrahedron's third vertex.+ pub c: Vector,+ /// The tetrahedron's fourth vertex.+ pub d: Vector,+}++/// Logical description of the location of a point on a tetrahedron.+///+/// This enum describes where a point is located relative to a tetrahedron's features+/// (vertices, edges, faces, or interior). It's commonly used in collision detection+/// and geometric queries to understand spatial relationships.+///+/// # Variants+///+/// - `OnVertex`: Vector is at one of the four vertices (0=a, 1=b, 2=c, 3=d)+/// - `OnEdge`: Vector lies on one of the six edges with barycentric coordinates+/// - `OnFace`: Vector lies on one of the four triangular faces with barycentric coordinates+/// - `OnSolid`: Vector is inside the tetrahedron volume+///+/// # Examples+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Tetrahedron, TetrahedronPointLocation};+/// use parry3d::math::Vector;+///+/// let tetra = Tetrahedron::new(+/// Vector::new(0.0, 0.0, 0.0),+/// Vector::new(1.0, 0.0, 0.0),+/// Vector::new(0.0, 1.0, 0.0),+/// Vector::new(0.0, 0.0, 1.0),+/// );+///+/// // Check location of vertex+/// let location = TetrahedronPointLocation::OnVertex(0);+/// if let Some(bcoords) = location.barycentric_coordinates() {+/// println!("Barycentric coordinates: {:?}", bcoords);+/// // For vertex 0, this will be [1.0, 0.0, 0.0, 0.0]+/// }+/// # }+/// ```+#[derive(Copy, Clone, Debug)]+pub enum TetrahedronPointLocation {+ /// The point lies on a vertex.+ ///+ /// The vertex index maps to: 0=a, 1=b, 2=c, 3=d+ OnVertex(u32),+ /// The point lies on an edge.+ ///+ /// Contains the edge index and barycentric coordinates `[u, v]` where:+ /// - `u` is the weight of the first vertex+ /// - `v` is the weight of the second vertex+ /// - `u + v = 1.0`+ ///+ /// Edge indices:+ /// - 0: segment AB+ /// - 1: segment AC+ /// - 2: segment AD+ /// - 3: segment BC+ /// - 4: segment BD+ /// - 5: segment CD+ OnEdge(u32, [Real; 2]),+ /// The point lies on a triangular face interior.+ ///+ /// Contains the face index and barycentric coordinates `[u, v, w]` where:+ /// - `u`, `v`, `w` are the weights of the three vertices+ /// - `u + v + w = 1.0`+ ///+ /// Face indices:+ /// - 0: triangle ABC+ /// - 1: triangle ABD+ /// - 2: triangle ACD+ /// - 3: triangle BCD+ OnFace(u32, [Real; 3]),+ /// The point lies inside of the tetrahedron.+ OnSolid,+}++impl TetrahedronPointLocation {+ /// The barycentric coordinates corresponding to this point location.+ ///+ /// Barycentric coordinates represent a point as a weighted combination of the+ /// tetrahedron's four vertices. The returned array `[wa, wb, wc, wd]` contains+ /// weights such that: `point = wa*a + wb*b + wc*c + wd*d` where `wa + wb + wc + wd = 1.0`.+ ///+ /// # Returns+ ///+ /// - `Some([wa, wb, wc, wd])`: The barycentric coordinates for points on features+ /// - `None`: If the location is `OnSolid` (point is in the interior)+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TetrahedronPointLocation;+ ///+ /// // A point on vertex 0 (vertex a)+ /// let location = TetrahedronPointLocation::OnVertex(0);+ /// let bcoords = location.barycentric_coordinates().unwrap();+ /// assert_eq!(bcoords, [1.0, 0.0, 0.0, 0.0]);+ ///+ /// // A point on edge 0 (segment AB) at midpoint+ /// let location = TetrahedronPointLocation::OnEdge(0, [0.5, 0.5]);+ /// let bcoords = location.barycentric_coordinates().unwrap();+ /// assert_eq!(bcoords, [0.5, 0.5, 0.0, 0.0]);+ ///+ /// // A point inside the tetrahedron+ /// let location = TetrahedronPointLocation::OnSolid;+ /// assert!(location.barycentric_coordinates().is_none());+ /// # }+ /// ```+ pub fn barycentric_coordinates(&self) -> Option<[Real; 4]> {+ let mut bcoords = [0.0; 4];++ match self {+ TetrahedronPointLocation::OnVertex(i) => bcoords[*i as usize] = 1.0,+ TetrahedronPointLocation::OnEdge(i, uv) => {+ let idx = Tetrahedron::edge_ids(*i);+ bcoords[idx.0 as usize] = uv[0];+ bcoords[idx.1 as usize] = uv[1];+ }+ TetrahedronPointLocation::OnFace(i, uvw) => {+ let idx = Tetrahedron::face_ids(*i);+ bcoords[idx.0 as usize] = uvw[0];+ bcoords[idx.1 as usize] = uvw[1];+ bcoords[idx.2 as usize] = uvw[2];+ }+ TetrahedronPointLocation::OnSolid => {+ return None;+ }+ }++ Some(bcoords)+ }++ /// Returns `true` if both `self` and `other` correspond to points on the same feature of a tetrahedron.+ ///+ /// Two point locations are considered to be on the same feature if they're both:+ /// - On the same vertex (same vertex index)+ /// - On the same edge (same edge index)+ /// - On the same face (same face index)+ /// - Both inside the tetrahedron (`OnSolid`)+ ///+ /// This is useful for determining if two points share a common geometric feature,+ /// which is important in collision detection and contact point generation.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TetrahedronPointLocation;+ ///+ /// let loc1 = TetrahedronPointLocation::OnVertex(0);+ /// let loc2 = TetrahedronPointLocation::OnVertex(0);+ /// let loc3 = TetrahedronPointLocation::OnVertex(1);+ ///+ /// assert!(loc1.same_feature_as(&loc2)); // Same vertex+ /// assert!(!loc1.same_feature_as(&loc3)); // Different vertices+ ///+ /// let edge1 = TetrahedronPointLocation::OnEdge(0, [0.5, 0.5]);+ /// let edge2 = TetrahedronPointLocation::OnEdge(0, [0.3, 0.7]);+ /// let edge3 = TetrahedronPointLocation::OnEdge(1, [0.5, 0.5]);+ ///+ /// assert!(edge1.same_feature_as(&edge2)); // Same edge, different coords+ /// assert!(!edge1.same_feature_as(&edge3)); // Different edges+ /// # }+ /// ```+ pub fn same_feature_as(&self, other: &TetrahedronPointLocation) -> bool {+ match (*self, *other) {+ (TetrahedronPointLocation::OnVertex(i), TetrahedronPointLocation::OnVertex(j)) => {+ i == j+ }+ (TetrahedronPointLocation::OnEdge(i, _), TetrahedronPointLocation::OnEdge(j, _)) => {+ i == j+ }+ (TetrahedronPointLocation::OnFace(i, _), TetrahedronPointLocation::OnFace(j, _)) => {+ i == j+ }+ (TetrahedronPointLocation::OnSolid, TetrahedronPointLocation::OnSolid) => true,+ _ => false,+ }+ }+}++impl Tetrahedron {+ /// Creates a tetrahedron from four points.+ ///+ /// The vertices can be specified in any order, but the order affects the+ /// orientation and signed volume. For a tetrahedron with positive volume,+ /// vertex `d` should be on the positive side of the plane defined by the+ /// counter-clockwise triangle `(a, b, c)`.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Tetrahedron;+ /// use parry3d::math::Vector;+ ///+ /// // Create a simple tetrahedron+ /// let tetra = Tetrahedron::new(+ /// Vector::new(0.0, 0.0, 0.0),+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 1.0),+ /// );+ ///+ /// assert!(tetra.volume() > 0.0);+ /// # }+ /// ```+ #[inline]+ pub fn new(a: Vector, b: Vector, c: Vector, d: Vector) -> Tetrahedron {+ Tetrahedron { a, b, c, d }+ }++ /// Creates the reference to a tetrahedron from the reference to an array of four points.+ ///+ /// This is a zero-cost conversion that reinterprets the array as a tetrahedron.+ /// The array elements correspond to vertices `[a, b, c, d]`.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Tetrahedron;+ /// use parry3d::math::Vector;+ ///+ /// let points = [+ /// Vector::new(0.0, 0.0, 0.0),+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 1.0),+ /// ];+ ///+ /// let tetra = Tetrahedron::from_array(&points);+ /// assert_eq!(tetra.a, points[0]);+ /// assert_eq!(tetra.b, points[1]);+ /// # }+ /// ```+ pub fn from_array(arr: &[Vector; 4]) -> &Tetrahedron {+ unsafe { mem::transmute(arr) }+ }++ /// Returns the i-th face of this tetrahedron.+ ///+ /// A tetrahedron has 4 triangular faces indexed from 0 to 3:+ /// - Face 0: triangle ABC+ /// - Face 1: triangle ABD+ /// - Face 2: triangle ACD+ /// - Face 3: triangle BCD+ ///+ /// # Panics+ ///+ /// Panics if `i >= 4`.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Tetrahedron;+ /// use parry3d::math::Vector;+ ///+ /// let tetra = Tetrahedron::new(+ /// Vector::new(0.0, 0.0, 0.0),+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 1.0),+ /// );+ ///+ /// // Get the first face (triangle ABC)+ /// let face = tetra.face(0);+ /// assert_eq!(face.a, tetra.a);+ /// assert_eq!(face.b, tetra.b);+ /// assert_eq!(face.c, tetra.c);+ ///+ /// // Get the last face (triangle BCD)+ /// let face = tetra.face(3);+ /// assert_eq!(face.a, tetra.b);+ /// assert_eq!(face.b, tetra.c);+ /// assert_eq!(face.c, tetra.d);+ /// # }+ /// ```+ pub fn face(&self, i: usize) -> Triangle {+ match i {+ 0 => Triangle::new(self.a, self.b, self.c),+ 1 => Triangle::new(self.a, self.b, self.d),+ 2 => Triangle::new(self.a, self.c, self.d),+ 3 => Triangle::new(self.b, self.c, self.d),+ _ => panic!("Tetrahedron face index out of bounds (must be < 4."),+ }+ }++ /// Returns the indices of the vertices of the i-th face of this tetrahedron.+ ///+ /// Returns a tuple `(v1, v2, v3)` where each value is a vertex index (0=a, 1=b, 2=c, 3=d).+ ///+ /// Face to vertex index mapping:+ /// - Face 0: (0, 1, 2) = triangle ABC+ /// - Face 1: (0, 1, 3) = triangle ABD+ /// - Face 2: (0, 2, 3) = triangle ACD+ /// - Face 3: (1, 2, 3) = triangle BCD+ ///+ /// # Panics+ ///+ /// Panics if `i >= 4`.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Tetrahedron;+ ///+ /// // Get indices for face 0 (triangle ABC)+ /// let (v1, v2, v3) = Tetrahedron::face_ids(0);+ /// assert_eq!((v1, v2, v3), (0, 1, 2)); // vertices a, b, c+ ///+ /// // Get indices for face 3 (triangle BCD)+ /// let (v1, v2, v3) = Tetrahedron::face_ids(3);+ /// assert_eq!((v1, v2, v3), (1, 2, 3)); // vertices b, c, d+ /// # }+ /// ```+ pub fn face_ids(i: u32) -> (u32, u32, u32) {+ match i {+ 0 => (0, 1, 2),+ 1 => (0, 1, 3),+ 2 => (0, 2, 3),+ 3 => (1, 2, 3),+ _ => panic!("Tetrahedron face index out of bounds (must be < 4."),+ }+ }++ /// Returns the i-th edge of this tetrahedron.+ ///+ /// A tetrahedron has 6 edges indexed from 0 to 5:+ /// - Edge 0: segment AB+ /// - Edge 1: segment AC+ /// - Edge 2: segment AD+ /// - Edge 3: segment BC+ /// - Edge 4: segment BD+ /// - Edge 5: segment CD+ ///+ /// # Panics+ ///+ /// Panics if `i >= 6`.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Tetrahedron;+ /// use parry3d::math::Vector;+ ///+ /// let tetra = Tetrahedron::new(+ /// Vector::new(0.0, 0.0, 0.0),+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 1.0),+ /// );+ ///+ /// // Get edge 0 (segment AB)+ /// let edge = tetra.edge(0);+ /// assert_eq!(edge.a, tetra.a);+ /// assert_eq!(edge.b, tetra.b);+ ///+ /// // Get edge 5 (segment CD)+ /// let edge = tetra.edge(5);+ /// assert_eq!(edge.a, tetra.c);+ /// assert_eq!(edge.b, tetra.d);+ /// # }+ /// ```+ pub fn edge(&self, i: u32) -> Segment {+ match i {+ 0 => Segment::new(self.a, self.b),+ 1 => Segment::new(self.a, self.c),+ 2 => Segment::new(self.a, self.d),+ 3 => Segment::new(self.b, self.c),+ 4 => Segment::new(self.b, self.d),+ 5 => Segment::new(self.c, self.d),+ _ => panic!("Tetrahedron edge index out of bounds (must be < 6)."),+ }+ }++ /// Returns the indices of the vertices of the i-th edge of this tetrahedron.+ ///+ /// Returns a tuple `(v1, v2)` where each value is a vertex index (0=a, 1=b, 2=c, 3=d).+ ///+ /// Edge to vertex index mapping:+ /// - Edge 0: (0, 1) = segment AB+ /// - Edge 1: (0, 2) = segment AC+ /// - Edge 2: (0, 3) = segment AD+ /// - Edge 3: (1, 2) = segment BC+ /// - Edge 4: (1, 3) = segment BD+ /// - Edge 5: (2, 3) = segment CD+ ///+ /// # Panics+ ///+ /// Panics if `i >= 6`.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Tetrahedron;+ ///+ /// // Get indices for edge 0 (segment AB)+ /// let (v1, v2) = Tetrahedron::edge_ids(0);+ /// assert_eq!((v1, v2), (0, 1)); // vertices a, b+ ///+ /// // Get indices for edge 5 (segment CD)+ /// let (v1, v2) = Tetrahedron::edge_ids(5);+ /// assert_eq!((v1, v2), (2, 3)); // vertices c, d+ /// # }+ /// ```+ pub fn edge_ids(i: u32) -> (u32, u32) {+ match i {+ 0 => (0, 1),+ 1 => (0, 2),+ 2 => (0, 3),+ 3 => (1, 2),+ 4 => (1, 3),+ 5 => (2, 3),+ _ => panic!("Tetrahedron edge index out of bounds (must be < 6)."),+ }+ }++ /// Computes the barycentric coordinates of the given point in the coordinate system of this tetrahedron.+ ///+ /// Barycentric coordinates express a point as a weighted combination of the tetrahedron's+ /// vertices. For point `p`, the returned array `[wa, wb, wc, wd]` satisfies:+ /// `p = wa*a + wb*b + wc*c + wd*d` where `wa + wb + wc + wd = 1.0`.+ ///+ /// These coordinates are useful for:+ /// - Interpolating values defined at vertices+ /// - Determining if a point is inside the tetrahedron (all weights are non-negative)+ /// - Computing distances and projections+ ///+ /// # Returns+ ///+ /// - `Some([wa, wb, wc, wd])`: The barycentric coordinates+ /// - `None`: If the tetrahedron is degenerate (zero volume, coplanar vertices)+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Tetrahedron;+ /// use parry3d::math::Vector;+ ///+ /// let tetra = Tetrahedron::new(+ /// Vector::new(0.0, 0.0, 0.0),+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 1.0),+ /// );+ ///+ /// // Vector at vertex a+ /// let bcoords = tetra.barycentric_coordinates(tetra.a).unwrap();+ /// assert!((bcoords[0] - 1.0).abs() < 1e-6);+ /// assert!(bcoords[1].abs() < 1e-6);+ ///+ /// // Vector at center+ /// let center = tetra.center();+ /// let bcoords = tetra.barycentric_coordinates(center).unwrap();+ /// // All coordinates should be approximately 0.25+ /// for coord in &bcoords {+ /// assert!((coord - 0.25).abs() < 1e-6);+ /// }+ /// # }+ /// ```+ pub fn barycentric_coordinates(&self, p: Vector) -> Option<[Real; 4]> {+ let ab = self.b - self.a;+ let ac = self.c - self.a;+ let ad = self.d - self.a;+ let m = Matrix::from_cols_array(&[ab.x, ab.y, ab.z, ac.x, ac.y, ac.z, ad.x, ad.y, ad.z]);++ m.try_inverse().map(|im| {+ let bcoords = im * (p - self.a);+ [+ 1.0 - bcoords.x - bcoords.y - bcoords.z,+ bcoords.x,+ bcoords.y,+ bcoords.z,+ ]+ })+ }++ /// Computes the volume of this tetrahedron.+ ///+ /// The volume is always non-negative, regardless of vertex ordering.+ /// For the signed volume (which can be negative), use [`signed_volume`](Self::signed_volume).+ ///+ /// # Formula+ ///+ /// Volume = |det(b-a, c-a, d-a)| / 6+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Tetrahedron;+ /// use parry3d::math::Vector;+ ///+ /// let tetra = Tetrahedron::new(+ /// Vector::new(0.0, 0.0, 0.0),+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 1.0),+ /// );+ ///+ /// let volume = tetra.volume();+ /// assert!((volume - 1.0/6.0).abs() < 1e-6);+ /// # }+ /// ```+ #[inline]+ pub fn volume(&self) -> Real {+ self.signed_volume().abs()+ }++ /// Computes the signed volume of this tetrahedron.+ ///+ /// The sign of the volume depends on the vertex ordering:+ /// - **Positive**: Vertex `d` is on the positive side of the plane defined by+ /// the counter-clockwise triangle `(a, b, c)`+ /// - **Negative**: Vertex `d` is on the negative side (opposite orientation)+ /// - **Zero**: The tetrahedron is degenerate (all vertices are coplanar)+ ///+ /// # Formula+ ///+ /// Signed Volume = det(b-a, c-a, d-a) / 6+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Tetrahedron;+ /// use parry3d::math::Vector;+ ///+ /// let tetra = Tetrahedron::new(+ /// Vector::new(0.0, 0.0, 0.0),+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 1.0),+ /// );+ ///+ /// let signed_vol = tetra.signed_volume();+ /// assert!(signed_vol > 0.0); // Positive orientation+ ///+ /// // Swap two vertices to flip orientation+ /// let tetra_flipped = Tetrahedron::new(+ /// tetra.a, tetra.c, tetra.b, tetra.d+ /// );+ /// let signed_vol_flipped = tetra_flipped.signed_volume();+ /// assert!(signed_vol_flipped < 0.0); // Negative orientation+ /// assert!((signed_vol + signed_vol_flipped).abs() < 1e-6); // Same magnitude+ /// # }+ /// ```+ #[inline]+ pub fn signed_volume(&self) -> Real {+ let p1p2 = self.b - self.a;+ let p1p3 = self.c - self.a;+ let p1p4 = self.d - self.a;++ let mat = CrossMatrix::from_cols(p1p2, p1p3, p1p4);++ mat.determinant() / 6.0+ }++ /// Computes the center of this tetrahedron.+ ///+ /// The center (also called centroid or barycenter) is the average of all four vertices.+ /// It's the point where all barycentric coordinates are equal to 0.25.+ ///+ /// # Formula+ ///+ /// Center = (a + b + c + d) / 4+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Tetrahedron;+ /// use parry3d::math::Vector;+ ///+ /// let tetra = Tetrahedron::new(+ /// Vector::new(0.0, 0.0, 0.0),+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 1.0),+ /// );+ ///+ /// let center = tetra.center();+ /// assert!((center.x - 0.25).abs() < 1e-6);+ /// assert!((center.y - 0.25).abs() < 1e-6);+ /// assert!((center.z - 0.25).abs() < 1e-6);+ ///+ /// // The center has equal barycentric coordinates+ /// let bcoords = tetra.barycentric_coordinates(center).unwrap();+ /// for coord in &bcoords {+ /// assert!((coord - 0.25).abs() < 1e-6);+ /// }+ /// # }+ /// ```+ #[inline]+ pub fn center(&self) -> Vector {+ utils::center(&[self.a, self.b, self.c, self.d])+ }+}diff --git a/renderer/third_party/parry3d/src/shape/triangle.rs b/renderer/third_party/parry3d/src/shape/triangle.rsnew file mode 100644index 0000000..d7e5d16--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/triangle.rs@@ -0,0 +1,943 @@+//! Definition of the triangle shape.++use crate::math::{ComplexField, Pose, Real, Vector};+use crate::shape::SupportMap;+use crate::shape::{PolygonalFeature, Segment};+use crate::utils;++use core::mem;+use num::Zero;++#[cfg(feature = "dim3")]+use crate::shape::FeatureId;++#[cfg(feature = "dim2")]+use crate::shape::PackedFeatureId;++/// A triangle shape defined by three vertices.+///+/// A triangle is one of the most fundamental shapes in computational geometry.+/// It's the simplest 2D polygon and the building block for triangle meshes.+///+/// # Structure+///+/// - **a, b, c**: The three vertices of the triangle+/// - **Edges**: AB (from a to b), BC (from b to c), CA (from c to a)+/// - **Orientation**: Counter-clockwise (CCW) is the standard convention+///+/// # Properties+///+/// - **Convex**: Always convex+/// - **2D/3D**: Can be used in both dimensions+/// - **In 2D**: A filled triangular region with area+/// - **In 3D**: A flat surface embedded in 3D space (zero volume)+///+/// # Orientation Convention+///+/// Triangles are typically defined with counter-clockwise vertex order:+/// - Looking at the triangle from the "front", vertices go a → b → c in CCW order+/// - The normal vector (3D) points toward the observer+/// - Right-hand rule: Curl fingers from a→b→c, thumb points along normal+///+/// # Use Cases+///+/// - **Mesh building block**: Fundamental unit of triangle meshes+/// - **Simple collision shapes**: Fast collision detection+/// - **Terrain representation**: Ground planes and surfaces+/// - **Testing and debugging**: Simple shape for verification+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Triangle;+/// use parry3d::math::Vector;+///+/// // Create a right triangle in the XY plane+/// let triangle = Triangle::new(+/// Vector::ZERO, // a: origin+/// Vector::new(3.0, 0.0, 0.0), // b: along +X+/// Vector::new(0.0, 4.0, 0.0) // c: along +Y+/// );+///+/// // Area of 3-4-5 right triangle is 6.0+/// assert_eq!(triangle.area(), 6.0);+///+/// // Check if a point is inside+/// let inside = Vector::new(1.0, 1.0, 0.0);+/// assert!(triangle.contains_point(inside));+/// # }+/// ```+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]+#[cfg_attr(feature = "encase", derive(encase::ShaderType))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[derive(PartialEq, Debug, Copy, Clone, Default)]+#[repr(C)]+pub struct Triangle {+ /// The first vertex of the triangle.+ pub a: Vector,+ /// The second vertex of the triangle.+ pub b: Vector,+ /// The third vertex of the triangle.+ pub c: Vector,+}++/// Description of the location of a point on a triangle.+#[derive(Copy, Clone, Debug)]+pub enum TrianglePointLocation {+ /// The point lies on a vertex.+ OnVertex(u32),+ /// The point lies on an edge.+ ///+ /// The 0-st edge is the segment AB.+ /// The 1-st edge is the segment BC.+ /// The 2-nd edge is the segment AC.+ // XXX: it appears the conversion of edge indexing here does not match the+ // convention of edge indexing for the `fn edge` method (from the ConvexPolyhedron impl).+ OnEdge(u32, [Real; 2]),+ /// The point lies on the triangle interior.+ ///+ /// The integer indicates on which side of the face the point is. 0 indicates the point+ /// is on the half-space toward the CW normal of the triangle. 1 indicates the point is on the other+ /// half-space. This is always set to 0 in 2D.+ OnFace(u32, [Real; 3]),+ /// The point lies on the triangle interior (for "solid" point queries).+ OnSolid,+}++impl TrianglePointLocation {+ /// The barycentric coordinates corresponding to this point location.+ ///+ /// Returns `None` if the location is `TrianglePointLocation::OnSolid`.+ pub fn barycentric_coordinates(&self) -> Option<[Real; 3]> {+ let mut bcoords = [0.0; 3];++ match self {+ TrianglePointLocation::OnVertex(i) => bcoords[*i as usize] = 1.0,+ TrianglePointLocation::OnEdge(i, uv) => {+ let idx = match i {+ 0 => (0, 1),+ 1 => (1, 2),+ 2 => (0, 2),+ _ => unreachable!(),+ };++ bcoords[idx.0] = uv[0];+ bcoords[idx.1] = uv[1];+ }+ TrianglePointLocation::OnFace(_, uvw) => {+ bcoords[0] = uvw[0];+ bcoords[1] = uvw[1];+ bcoords[2] = uvw[2];+ }+ TrianglePointLocation::OnSolid => {+ return None;+ }+ }++ Some(bcoords)+ }++ /// Returns `true` if the point is located on the relative interior of the triangle.+ pub fn is_on_face(&self) -> bool {+ matches!(*self, TrianglePointLocation::OnFace(..))+ }+}++/// Orientation of a triangle.+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub enum TriangleOrientation {+ /// Orientation with a clockwise orientation, i.e., with a positive signed area.+ Clockwise,+ /// Orientation with a clockwise orientation, i.e., with a negative signed area.+ CounterClockwise,+ /// Degenerate triangle.+ Degenerate,+}++impl From<[Vector; 3]> for Triangle {+ fn from(arr: [Vector; 3]) -> Self {+ *Self::from_array(&arr)+ }+}++impl Triangle {+ /// Creates a triangle from three vertices.+ ///+ /// # Arguments+ ///+ /// * `a` - The first vertex+ /// * `b` - The second vertex+ /// * `c` - The third vertex+ ///+ /// # Convention+ ///+ /// For proper normal calculation and consistent collision detection, vertices+ /// should be ordered counter-clockwise when viewed from the "front" side.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Triangle;+ /// use parry3d::math::Vector;+ ///+ /// // Create a triangle in the XY plane+ /// let tri = Triangle::new(+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0)+ /// );+ ///+ /// assert_eq!(tri.area(), 0.5);+ /// # }+ /// ```+ #[inline]+ pub fn new(a: Vector, b: Vector, c: Vector) -> Triangle {+ Triangle { a, b, c }+ }++ /// Creates the reference to a triangle from the reference to an array of three points.+ pub fn from_array(arr: &[Vector; 3]) -> &Triangle {+ unsafe { mem::transmute(arr) }+ }++ /// Reference to an array containing the three vertices of this triangle.+ #[inline]+ pub fn vertices(&self) -> &[Vector; 3] {+ unsafe { mem::transmute(self) }+ }++ /// The normal of this triangle assuming it is oriented ccw.+ ///+ /// The normal points such that it is collinear to `AB × AC` (where `×` denotes the cross+ /// product).+ #[inline]+ #[cfg(feature = "dim3")]+ pub fn normal(&self) -> Option<Vector> {+ self.scaled_normal().try_normalize()+ }++ /// The three edges of this triangle: [AB, BC, CA].+ #[inline]+ pub fn edges(&self) -> [Segment; 3] {+ [+ Segment::new(self.a, self.b),+ Segment::new(self.b, self.c),+ Segment::new(self.c, self.a),+ ]+ }++ /// Computes a scaled version of this triangle.+ pub fn scaled(self, scale: Vector) -> Self {+ Self::new(self.a * scale, self.b * scale, self.c * scale)+ }++ /// Returns a new triangle with vertices transformed by `m`.+ #[inline]+ pub fn transformed(&self, m: &Pose) -> Self {+ Triangle::new(m * self.a, m * self.b, m * self.c)+ }++ /// The three edges scaled directions of this triangle: [B - A, C - B, A - C].+ #[inline]+ pub fn edges_scaled_directions(&self) -> [Vector; 3] {+ [self.b - self.a, self.c - self.b, self.a - self.c]+ }++ /// Return the edge segment of this cuboid with a normal cone containing+ /// a direction that that maximizes the dot product with `local_dir`.+ pub fn local_support_edge_segment(&self, dir: Vector) -> Segment {+ let dots = [dir.dot(self.a), dir.dot(self.b), dir.dot(self.c)];++ let imin = if dots[0] <= dots[1] && dots[0] <= dots[2] {+ 0+ } else if dots[1] <= dots[2] {+ 1+ } else {+ 2+ };++ match imin {+ 0 => Segment::new(self.b, self.c),+ 1 => Segment::new(self.c, self.a),+ _ => Segment::new(self.a, self.b),+ }+ }++ /// Return the face of this triangle with a normal that maximizes+ /// the dot product with `dir`.+ #[cfg(feature = "dim3")]+ pub fn support_face(&self, _dir: Vector) -> PolygonalFeature {+ PolygonalFeature::from(*self)+ }++ /// Return the face of this triangle with a normal that maximizes+ /// the dot product with `dir`.+ #[cfg(feature = "dim2")]+ pub fn support_face(&self, dir: Vector) -> PolygonalFeature {+ let mut best = 0;+ let mut best_dot = -Real::MAX;++ for (i, tangent) in self.edges_scaled_directions().iter().enumerate() {+ let normal = Vector::new(tangent.y, -tangent.x);+ if let Some(normal) = normal.try_normalize() {+ let dot = normal.dot(dir);+ if normal.dot(dir) > best_dot {+ best = i;+ best_dot = dot;+ }+ }+ }++ let pts = self.vertices();+ let i1 = best;+ let i2 = (best + 1) % 3;++ PolygonalFeature {+ vertices: [pts[i1], pts[i2]],+ vids: PackedFeatureId::vertices([i1 as u32, i2 as u32]),+ fid: PackedFeatureId::face(i1 as u32),+ num_vertices: 2,+ }+ }++ /// A vector normal of this triangle.+ ///+ /// The vector points such that it is collinear to `AB × AC` (where `×` denotes the cross+ /// product).+ ///+ /// Note that on thin triangles the calculated normals can suffer from numerical issues.+ /// For a more robust (but more computationally expensive) normal calculation, see+ /// [`Triangle::robust_scaled_normal`].+ #[inline]+ #[cfg(feature = "dim3")]+ pub fn scaled_normal(&self) -> Vector {+ let ab = self.b - self.a;+ let ac = self.c - self.a;+ ab.cross(ac)+ }++ /// Find a triangle normal more robustly than with [`Triangle::scaled_normal`].+ ///+ /// Thin triangles can cause numerical issues when computing its normal. This method accounts+ /// for these numerical issues more robustly than [`Triangle::scaled_normal`], but is more+ /// computationally expensive.+ #[inline]+ #[cfg(feature = "dim3")]+ pub fn robust_scaled_normal(&self) -> Vector {+ let pts = self.vertices();+ let best_vertex = self.angle_closest_to_90();+ let d1 = pts[(best_vertex + 2) % 3] - pts[(best_vertex + 1) % 3];+ let d2 = pts[best_vertex] - pts[(best_vertex + 1) % 3];++ d1.cross(d2)+ }++ /// Similar to [`Triangle::robust_scaled_normal`], but returns the unit length normal.+ #[inline]+ #[cfg(feature = "dim3")]+ pub fn robust_normal(&self) -> Vector {+ self.robust_scaled_normal().normalize()+ }++ /// Computes the extents of this triangle on the given direction.+ ///+ /// This computes the min and max values of the dot products between each+ /// vertex of this triangle and `dir`.+ #[inline]+ pub fn extents_on_dir(&self, dir: Vector) -> (Real, Real) {+ let a = self.a.dot(dir);+ let b = self.b.dot(dir);+ let c = self.c.dot(dir);++ if a > b {+ if b > c {+ (c, a)+ } else if a > c {+ (b, a)+ } else {+ (b, c)+ }+ } else {+ // b >= a+ if a > c {+ (c, b)+ } else if b > c {+ (a, b)+ } else {+ (a, c)+ }+ }+ }+ //+ // #[cfg(feature = "dim3")]+ // fn support_feature_id_toward(&self, local_dir: Vector, eps: Real) -> FeatureId {+ // if let Some(normal) = self.normal() {+ // let (seps, ceps) = ComplexField::sin_cos(eps);+ //+ // let normal_dot = local_dir.dot(*normal);+ // if normal_dot >= ceps {+ // FeatureId::Face(0)+ // } else if normal_dot <= -ceps {+ // FeatureId::Face(1)+ // } else {+ // let edges = self.edges();+ // let mut dots = [0.0; 3];+ //+ // let dir1 = edges[0].direction();+ // if let Some(dir1) = dir1 {+ // dots[0] = dir1.dot(local_dir);+ //+ // if dots[0].abs() < seps {+ // return FeatureId::Edge(0);+ // }+ // }+ //+ // let dir2 = edges[1].direction();+ // if let Some(dir2) = dir2 {+ // dots[1] = dir2.dot(local_dir);+ //+ // if dots[1].abs() < seps {+ // return FeatureId::Edge(1);+ // }+ // }+ //+ // let dir3 = edges[2].direction();+ // if let Some(dir3) = dir3 {+ // dots[2] = dir3.dot(local_dir);+ //+ // if dots[2].abs() < seps {+ // return FeatureId::Edge(2);+ // }+ // }+ //+ // if dots[0] > 0.0 && dots[1] < 0.0 {+ // FeatureId::Vertex(1)+ // } else if dots[1] > 0.0 && dots[2] < 0.0 {+ // FeatureId::Vertex(2)+ // } else {+ // FeatureId::Vertex(0)+ // }+ // }+ // } else {+ // FeatureId::Vertex(0)+ // }+ // }++ /// The area of this triangle.+ #[inline]+ pub fn area(&self) -> Real {+ // Half the cross-product magnitude, which unlike Kahan's formula on the rounded+ // side lengths is exactly 0.0 for bitwise-collinear vertices.+ let ab = self.b - self.a;+ let ac = self.c - self.a;++ #[cfg(feature = "dim2")]+ return ab.perp_dot(ac).abs() * 0.5;++ #[cfg(feature = "dim3")]+ return ab.cross(ac).length() * 0.5;+ }++ /// Computes the unit angular inertia of this triangle.+ #[cfg(feature = "dim2")]+ pub fn unit_angular_inertia(&self) -> Real {+ let factor = 1.0 / 6.0;++ // Algorithm adapted from Box2D+ let e1 = self.b - self.a;+ let e2 = self.c - self.a;++ let intx2 = e1.x * e1.x + e2.x * e1.x + e2.x * e2.x;+ let inty2 = e1.y * e1.y + e2.y * e1.y + e2.y * e2.y;+ factor * (intx2 + inty2)+ }++ /// The geometric center of this triangle.+ #[inline]+ pub fn center(&self) -> Vector {+ utils::center(&[self.a, self.b, self.c])+ }++ /// The perimeter of this triangle.+ #[inline]+ pub fn perimeter(&self) -> Real {+ self.b.distance(self.a) + self.c.distance(self.b) + self.a.distance(self.c)+ }++ /// The circumcircle of this triangle.+ pub fn circumcircle(&self) -> (Vector, Real) {+ let a = self.a - self.c;+ let b = self.b - self.c;++ let na = a.length_squared();+ let nb = b.length_squared();++ let dab = a.dot(b);++ let denom = 2.0 * (na * nb - dab * dab);++ if denom.is_zero() {+ // The triangle is degenerate (the three points are collinear).+ // So we find the longest segment and take its center.+ let c = self.a - self.b;+ let nc = c.length_squared();++ if nc >= na && nc >= nb {+ // Longest segment: [&self.a, &self.b]+ (+ self.a.midpoint(self.b),+ <Real as ComplexField>::sqrt(nc) / 2.0,+ )+ } else if na >= nb && na >= nc {+ // Longest segment: [&self.a, pc]+ (+ self.a.midpoint(self.c),+ <Real as ComplexField>::sqrt(na) / 2.0,+ )+ } else {+ // Longest segment: [&self.b, &self.c]+ (+ self.b.midpoint(self.c),+ <Real as ComplexField>::sqrt(nb) / 2.0,+ )+ }+ } else {+ let k = b * na - a * nb;++ let center = self.c + (a * k.dot(b) - b * k.dot(a)) / denom;+ let radius = center.distance(self.a);++ (center, radius)+ }+ }++ /// Tests if this triangle is affinely dependent, i.e., its points are almost aligned.+ #[cfg(feature = "dim3")]+ pub fn is_affinely_dependent(&self) -> bool {+ const EPS: Real = crate::math::DEFAULT_EPSILON * 100.0;++ let p1p2 = self.b - self.a;+ let p1p3 = self.c - self.a;+ relative_eq!(p1p2.cross(p1p3).length_squared(), 0.0, epsilon = EPS * EPS)++ // relative_eq!(+ // self.area(),+ // 0.0,+ // epsilon = EPS * self.perimeter()+ // )+ }++ /// Is this triangle degenerate or almost degenerate?+ #[cfg(feature = "dim3")]+ pub fn is_affinely_dependent_eps(&self, eps: Real) -> bool {+ let p1p2 = self.b - self.a;+ let p1p3 = self.c - self.a;+ relative_eq!(+ p1p2.cross(p1p3).length(),+ 0.0,+ epsilon = eps * p1p2.length().max(p1p3.length())+ )++ // relative_eq!(+ // self.area(),+ // 0.0,+ // epsilon = EPS * self.perimeter()+ // )+ }++ /// Tests if a point is inside of this triangle.+ #[cfg(feature = "dim2")]+ pub fn contains_point(&self, p: Vector) -> bool {+ let ab = self.b - self.a;+ let bc = self.c - self.b;+ let ca = self.a - self.c;+ let sgn1 = ab.perp_dot(p - self.a);+ let sgn2 = bc.perp_dot(p - self.b);+ let sgn3 = ca.perp_dot(p - self.c);+ sgn1.signum() * sgn2.signum() >= 0.0+ && sgn1.signum() * sgn3.signum() >= 0.0+ && sgn2.signum() * sgn3.signum() >= 0.0+ }++ /// Tests if a point is inside of this triangle.+ #[cfg(feature = "dim3")]+ pub fn contains_point(&self, p: Vector) -> bool {+ const EPS: Real = crate::math::DEFAULT_EPSILON;++ let vb = self.b - self.a;+ let vc = self.c - self.a;+ let vp = p - self.a;++ let n = vc.cross(vb);+ let n_norm = n.length_squared();+ if n_norm < EPS || vp.dot(n).abs() > EPS * n_norm {+ // the triangle is degenerate or the+ // point does not lie on the same plane as the triangle.+ return false;+ }++ // We are seeking B, C such that vp = vb * B + vc * C .+ // If B and C are both in [0, 1] and B + C <= 1 then p is in the triangle.+ //+ // We can project this equation along a vector nb coplanar to the triangle+ // and perpendicular to vb:+ // vp.dot(nb) = vb.dot(nb) * B + vc.dot(nb) * C+ // => C = vp.dot(nb) / vc.dot(nb)+ // and similarly for B.+ //+ // In order to avoid divisions and sqrts we scale both B and C - so+ // b = vb.dot(nc) * B and c = vc.dot(nb) * C - this results in harder-to-follow math but+ // hopefully fast code.++ let nb = vb.cross(n);+ let nc = vc.cross(n);++ let signed_blim = vb.dot(nc);+ let b = vp.dot(nc) * signed_blim.signum();+ let blim = signed_blim.abs();++ let signed_clim = vc.dot(nb);+ let c = vp.dot(nb) * signed_clim.signum();+ let clim = signed_clim.abs();++ c >= 0.0 && c <= clim && b >= 0.0 && b <= blim && c * blim + b * clim <= blim * clim+ }++ /// The normal of the given feature of this shape.+ #[cfg(feature = "dim3")]+ pub fn feature_normal(&self, _: FeatureId) -> Option<Vector> {+ self.normal()+ }++ /// The orientation of the triangle, based on its signed area.+ ///+ /// Returns `TriangleOrientation::Degenerate` if the triangle’s area is+ /// smaller than `epsilon`.+ #[cfg(feature = "dim2")]+ pub fn orientation(&self, epsilon: Real) -> TriangleOrientation {+ let area2 = (self.b - self.a).perp_dot(self.c - self.a);+ // println!("area2: {}", area2);+ if area2 > epsilon {+ TriangleOrientation::CounterClockwise+ } else if area2 < -epsilon {+ TriangleOrientation::Clockwise+ } else {+ TriangleOrientation::Degenerate+ }+ }++ /// The orientation of the 2D triangle, based on its signed area.+ ///+ /// Returns `TriangleOrientation::Degenerate` if the triangle's area is+ /// smaller than `epsilon`.+ pub fn orientation2d(+ a: crate::math::Vector2,+ b: crate::math::Vector2,+ c: crate::math::Vector2,+ epsilon: Real,+ ) -> TriangleOrientation {+ let area2 = (b - a).perp_dot(c - a);+ // println!("area2: {}", area2);+ if area2 > epsilon {+ TriangleOrientation::CounterClockwise+ } else if area2 < -epsilon {+ TriangleOrientation::Clockwise+ } else {+ TriangleOrientation::Degenerate+ }+ }++ /// Find the index of a vertex in this triangle, such that the two+ /// edges incident in that vertex form the angle closest to 90+ /// degrees in the triangle.+ pub fn angle_closest_to_90(&self) -> usize {+ let points = self.vertices();+ let mut best_cos = 2.0;+ let mut selected_i = 0;++ for i in 0..3 {+ let d1 = (points[i] - points[(i + 1) % 3]).normalize();+ let d2 = (points[(i + 2) % 3] - points[(i + 1) % 3]).normalize();++ let cos_abs = d1.dot(d2).abs();++ if cos_abs < best_cos {+ best_cos = cos_abs;+ selected_i = i;+ }+ }++ selected_i+ }++ /// Reverse the orientation of this triangle by swapping b and c.+ pub fn reverse(&mut self) {+ mem::swap(&mut self.b, &mut self.c);+ }+}++impl SupportMap for Triangle {+ #[inline]+ fn local_support_point(&self, dir: Vector) -> Vector {+ let d1 = self.a.dot(dir);+ let d2 = self.b.dot(dir);+ let d3 = self.c.dot(dir);++ if d1 > d2 {+ if d1 > d3 {+ self.a+ } else {+ self.c+ }+ } else if d2 > d3 {+ self.b+ } else {+ self.c+ }+ }+}++/*+#[cfg(feature = "dim3")]+impl ConvexPolyhedron for Triangle {+ fn vertex(&self, id: FeatureId) -> Vector {+ match id.unwrap_vertex() {+ 0 => self.a,+ 1 => self.b,+ 2 => self.c,+ _ => panic!("Triangle vertex index out of bounds."),+ }+ }+ fn edge(&self, id: FeatureId) -> (Vector, Vector, FeatureId, FeatureId) {+ match id.unwrap_edge() {+ 0 => (self.a, self.b, FeatureId::Vertex(0), FeatureId::Vertex(1)),+ 1 => (self.b, self.c, FeatureId::Vertex(1), FeatureId::Vertex(2)),+ 2 => (self.c, self.a, FeatureId::Vertex(2), FeatureId::Vertex(0)),+ _ => panic!("Triangle edge index out of bounds."),+ }+ }++ fn face(&self, id: FeatureId, face: &mut ConvexPolygonalFeature) {+ face.clear();++ if let Some(normal) = self.normal() {+ face.set_feature_id(id);++ match id.unwrap_face() {+ 0 => {+ face.push(self.a, FeatureId::Vertex(0));+ face.push(self.b, FeatureId::Vertex(1));+ face.push(self.c, FeatureId::Vertex(2));+ face.push_edge_feature_id(FeatureId::Edge(0));+ face.push_edge_feature_id(FeatureId::Edge(1));+ face.push_edge_feature_id(FeatureId::Edge(2));+ face.set_normal(normal);+ }+ 1 => {+ face.push(self.a, FeatureId::Vertex(0));+ face.push(self.c, FeatureId::Vertex(2));+ face.push(self.b, FeatureId::Vertex(1));+ face.push_edge_feature_id(FeatureId::Edge(2));+ face.push_edge_feature_id(FeatureId::Edge(1));+ face.push_edge_feature_id(FeatureId::Edge(0));+ face.set_normal(-normal);+ }+ _ => unreachable!(),+ }++ face.recompute_edge_normals();+ } else {+ face.push(self.a, FeatureId::Vertex(0));+ face.set_feature_id(FeatureId::Vertex(0));+ }+ }++ fn support_face_toward(+ &self,+ m: &Pose,+ dir: Vector,+ face: &mut ConvexPolygonalFeature,+ ) {+ let normal = self.scaled_normal();++ if normal.dot(*dir) >= 0.0 {+ ConvexPolyhedron::face(self, FeatureId::Face(0), face);+ } else {+ ConvexPolyhedron::face(self, FeatureId::Face(1), face);+ }+ face.transform_by(m)+ }++ fn support_feature_toward(+ &self,+ transform: &Pose,+ dir: Vector,+ eps: Real,+ out: &mut ConvexPolygonalFeature,+ ) {+ out.clear();+ let tri = self.transformed(transform);+ let feature = tri.support_feature_id_toward(dir, eps);++ match feature {+ FeatureId::Vertex(_) => {+ let v = tri.vertex(feature);+ out.push(v, feature);+ out.set_feature_id(feature);+ }+ FeatureId::Edge(_) => {+ let (a, b, fa, fb) = tri.edge(feature);+ out.push(a, fa);+ out.push(b, fb);+ out.push_edge_feature_id(feature);+ out.set_feature_id(feature);+ }+ FeatureId::Face(_) => tri.face(feature, out),+ _ => unreachable!(),+ }+ }++ fn support_feature_id_toward(&self, local_dir: Vector) -> FeatureId {+ self.support_feature_id_toward(local_dir, (f64::consts::PI / 180.0) as Real)+ }+}+*/++#[cfg(feature = "dim2")]+#[cfg(test)]+mod test {+ use crate::math::Vector;+ use crate::shape::Triangle;++ #[test]+ fn test_triangle_area() {+ let pa = Vector::new(5.0, 0.0);+ let pb = Vector::ZERO;+ let pc = Vector::new(0.0, 4.0);++ assert!(relative_eq!(Triangle::new(pa, pb, pc).area(), 10.0));+ }++ #[test]+ fn test_triangle_contains_point() {+ let tri = Triangle::new(Vector::new(5.0, 0.0), Vector::ZERO, Vector::new(0.0, 4.0));++ assert!(tri.contains_point(Vector::new(1.0, 1.0)));+ assert!(!tri.contains_point(Vector::new(-1.0, 1.0)));+ }++ #[test]+ fn test_obtuse_triangle_contains_point() {+ let tri = Triangle::new(+ Vector::new(-10.0, 10.0),+ Vector::ZERO,+ Vector::new(20.0, 0.0),+ );++ assert!(tri.contains_point(Vector::new(-3.0, 5.0)));+ assert!(tri.contains_point(Vector::new(5.0, 1.0)));+ assert!(!tri.contains_point(Vector::new(0.0, -1.0)));+ }+}++#[cfg(feature = "dim3")]+#[cfg(test)]+mod test {+ use crate::math::{Real, Vector};+ use crate::shape::Triangle;++ #[test]+ fn test_triangle_area() {+ let pa = Vector::new(0.0, 5.0, 0.0);+ let pb = Vector::ZERO;+ let pc = Vector::new(0.0, 0.0, 4.0);++ assert!(relative_eq!(Triangle::new(pa, pb, pc).area(), 10.0));+ }++ #[test]+ fn test_triangle_contains_point() {+ let tri = Triangle::new(+ Vector::new(0.0, 5.0, 0.0),+ Vector::ZERO,+ Vector::new(0.0, 0.0, 4.0),+ );++ assert!(tri.contains_point(Vector::new(0.0, 1.0, 1.0)));+ assert!(!tri.contains_point(Vector::new(0.0, -1.0, 1.0)));+ }++ #[test]+ fn test_obtuse_triangle_contains_point() {+ let tri = Triangle::new(+ Vector::new(-10.0, 10.0, 0.0),+ Vector::ZERO,+ Vector::new(20.0, 0.0, 0.0),+ );++ assert!(tri.contains_point(Vector::new(-3.0, 5.0, 0.0)));+ assert!(tri.contains_point(Vector::new(5.0, 1.0, 0.0)));+ assert!(!tri.contains_point(Vector::new(0.0, -1.0, 0.0)));+ }++ #[test]+ fn test_3dtriangle_contains_point() {+ let o = Vector::ZERO;+ let pa = Vector::new(1.2, 1.4, 5.6);+ let pb = Vector::new(1.5, 6.7, 1.9);+ let pc = Vector::new(5.0, 2.1, 1.3);++ let tri = Triangle::new(pa, pb, pc);++ let va = pa - o;+ let vb = pb - o;+ let vc = pc - o;++ let n = (pa - pb).cross(pb - pc);++ // This is a simple algorithm for generating points that are inside the+ // triangle: o + (va * alpha + vb * beta + vc * gamma) is always inside the+ // triangle if:+ // * each of alpha, beta, gamma is in (0, 1)+ // * alpha + beta + gamma = 1+ let contained_p = o + (va * 0.2 + vb * 0.3 + vc * 0.5);+ let not_contained_coplanar_p = o + (va * -0.5 + vb * 0.8 + vc * 0.7);+ let not_coplanar_p = o + (va * 0.2 + vb * 0.3 + vc * 0.5) + n * 0.1;+ let not_coplanar_p2 = o + (va * -0.5 + vb * 0.8 + vc * 0.7) + n * 0.1;+ assert!(tri.contains_point(contained_p));+ assert!(!tri.contains_point(not_contained_coplanar_p));+ assert!(!tri.contains_point(not_coplanar_p));+ assert!(!tri.contains_point(not_coplanar_p2));++ // Test that points that are clearly within the triangle as seen as such, by testing+ // a number of points along a line intersecting the triangle.+ for i in -50i16..150 {+ let a = 0.15;+ let b = 0.01 * Real::from(i); // b ranges from -0.5 to 1.5+ let c = 1.0 - a - b;+ let p = o + (va * a + vb * b + vc * c);++ match i {+ ii if ii < 0 || ii > 85 => assert!(+ !tri.contains_point(p),+ "Should not contain: i = {}, b = {}",+ i,+ b+ ),+ ii if ii > 0 && ii < 85 => assert!(+ tri.contains_point(p),+ "Should contain: i = {}, b = {}",+ i,+ b+ ),+ _ => (), // Vectors at the edge may be seen as inside or outside+ }+ }+ }+}diff --git a/renderer/third_party/parry3d/src/shape/triangle_pseudo_normals.rs b/renderer/third_party/parry3d/src/shape/triangle_pseudo_normals.rsnew file mode 100644index 0000000..a74f4fc--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/triangle_pseudo_normals.rs@@ -0,0 +1,239 @@+use crate::math::Vector;++#[cfg(feature = "alloc")]+use crate::{math::Vector3, query::details::NormalConstraints};++// NOTE: ideally, the normal cone should take into account the point where the normal cone is+// considered. But as long as we assume that the triangles are one-way we can get away with+// just relying on the normal directions.+// Taking the point into account would be technically doable (and desirable if we wanted+// to define, e.g., a one-way mesh) but requires:+// 1. To make sure the edge pseudo-normals are given in the correct edge order.+// 2. To have access to the contact feature.+// We can have access to both during the narrow-phase, but leave that as a future+// potential improvements.+// NOTE: this isn’t equal to the "true" normal cones since concave edges will have pseudo-normals+// still pointing outward (instead of inward or being empty).+/// The pseudo-normals of a triangle providing approximations of its feature’s normal cones.+#[derive(Clone, Debug)]+pub struct TrianglePseudoNormals {+ /// The triangle’s face normal.+ pub face: Vector,+ // TODO: if we switch this to providing pseudo-normals in a specific order+ // (e.g. in the same order as the triangle’s edges), then we should+ // think of fixing that order in the heightfield+ // triangle_pseudo_normals code.+ /// The edges pseudo-normals, in no particular order.+ pub edges: [Vector; 3],+ /// If `true`, a direction pointing to the back of the triangle is projected into the+ /// mirrored cone (`-face`, `-edges`) and kept, instead of being discarded.+ pub two_sided: bool,+}++#[cfg(feature = "alloc")]+impl NormalConstraints for TrianglePseudoNormals {+ /// Projects the given direction to it is contained in the polygonal+ /// cone defined `self`.+ fn project_local_normal_mut(&self, dir: &mut Vector) -> bool {+ if self.two_sided && dir.dot(self.face) < 0.0 {+ // The back cone is the front cone mirrored through the triangle's plane.+ let mut mirrored = -*dir;+ let _ = self.project_front(&mut mirrored);+ *dir = -mirrored;+ return true;+ }++ self.project_front(dir)+ }+}++#[cfg(feature = "alloc")]+impl TrianglePseudoNormals {+ fn project_front(&self, dir: &mut Vector) -> bool {+ // Find the closest pseudo-normal.+ let dots = Vector3::new(+ dir.dot(self.edges[0]),+ dir.dot(self.edges[1]),+ dir.dot(self.edges[2]),+ );+ let closest_edge = self.edges[dots.max_position()];+ crate::shape::pseudo_normals::project_into_cone(self.face, closest_edge, dir)+ }+}++#[cfg(test)]+#[cfg(all(feature = "dim3", feature = "alloc"))]+mod test {+ use super::NormalConstraints;+ use crate::math::{Real, Vector};+ use crate::shape::TrianglePseudoNormals;++ fn bisector(v1: Vector, v2: Vector) -> Vector {+ (v1 + v2).normalize()+ }++ fn bisector_y(v: Vector) -> Vector {+ bisector(v, Vector::Y)+ }++ #[test]+ fn trivial_pseudo_normals_projection() {+ let pn = TrianglePseudoNormals {+ face: Vector::Y,+ edges: [Vector::Y; 3],+ two_sided: false,+ };++ assert_eq!(+ pn.project_local_normal(Vector::new(1.0, 1.0, 1.0)),+ Some(Vector::Y)+ );+ assert!(pn.project_local_normal(-Vector::Y).is_none());+ }++ #[test]+ fn edge_pseudo_normals_projection_strictly_positive() {+ let bisector = |v1: Vector, v2: Vector| (v1 + v2).normalize();+ let bisector_y = |v: Vector| bisector(v, Vector::Y);++ // The normal cones for this test will be fully contained in the +Y half-space.+ let cones_ref_dir = [+ -Vector::Z,+ -Vector::X,+ Vector::new(1.0, 0.0, 1.0).normalize(),+ ];+ let cones_ends = cones_ref_dir.map(bisector_y);+ let cones_axes = cones_ends.map(bisector_y);++ let pn = TrianglePseudoNormals {+ face: Vector::Y,+ edges: cones_axes.map(|v| v.normalize()),+ two_sided: false,+ };++ for i in 0..3 {+ assert!(pn+ .project_local_normal(cones_ends[i])+ .unwrap()+ .abs_diff_eq(cones_ends[i], 1.0e-5));+ assert_eq!(pn.project_local_normal(cones_axes[i]), Some(cones_axes[i]));++ // Guaranteed to be inside the normal cone of edge i.+ let subdivs = 100;++ for k in 1..100 {+ let v = Vector::Y+ .lerp(cones_ends[i], k as Real / (subdivs as Real))+ .normalize();+ assert_eq!(pn.project_local_normal(v).unwrap(), v);+ }++ // Guaranteed to be outside the normal cone of edge i.+ for k in 1..subdivs {+ let v = cones_ref_dir[i]+ .lerp(cones_ends[i], k as Real / (subdivs as Real))+ .normalize();+ assert!(pn+ .project_local_normal(v)+ .unwrap()+ .abs_diff_eq(cones_ends[i], 1.0e-5));+ }++ // Guaranteed to be outside the normal cone, and in the -Y half-space.+ for k in 1..subdivs {+ let v = cones_ref_dir[i]+ .lerp(-Vector::Y, k as Real / (subdivs as Real))+ .normalize();+ assert!(pn.project_local_normal(v).is_none(),);+ }+ }+ }++ #[test]+ fn edge_pseudo_normals_projection_negative() {+ // The normal cones for this test will be fully contained in the +Y half-space.+ let cones_ref_dir = [+ -Vector::Z,+ -Vector::X,+ Vector::new(1.0, 0.0, 1.0).normalize(),+ ];+ let cones_ends = cones_ref_dir.map(|v| bisector(v, -Vector::Y));+ let cones_axes = [+ bisector(bisector_y(cones_ref_dir[0]), cones_ref_dir[0]),+ bisector(bisector_y(cones_ref_dir[1]), cones_ref_dir[1]),+ bisector(bisector_y(cones_ref_dir[2]), cones_ref_dir[2]),+ ];++ let pn = TrianglePseudoNormals {+ face: Vector::Y,+ edges: cones_axes.map(|v| v.normalize()),+ two_sided: false,+ };++ for i in 0..3 {+ assert_eq!(pn.project_local_normal(cones_axes[i]), Some(cones_axes[i]));++ // Guaranteed to be inside the normal cone of edge i.+ let subdivs = 100;++ for k in 1..subdivs {+ let v = Vector::Y+ .lerp(cones_ends[i], k as Real / (subdivs as Real))+ .normalize();+ assert_eq!(pn.project_local_normal(v).unwrap(), v);+ }++ // Guaranteed to be outside the normal cone of edge i.+ // Since it is additionally guaranteed to be in the -Y half-space, we should get None.+ for k in 1..subdivs {+ let v = (-Vector::Y)+ .lerp(cones_ends[i], k as Real / (subdivs as Real))+ .normalize();+ assert!(pn.project_local_normal(v).is_none());+ }+ }+ }++ #[test]+ fn two_sided_pseudo_normals_mirror_the_cone() {+ let one_sided = TrianglePseudoNormals {+ face: Vector::Y,+ edges: [Vector::Y; 3],+ two_sided: false,+ };+ let two_sided = TrianglePseudoNormals {+ two_sided: true,+ ..one_sided.clone()+ };++ // Front directions behave the same.+ let front = Vector::new(1.0, 1.0, 1.0);+ assert_eq!(two_sided.project_local_normal(front), Some(Vector::Y));++ // Back directions are kept and constrained to the mirrored cone.+ let back = Vector::new(1.0, -1.0, 1.0);+ assert!(one_sided.project_local_normal(back).is_none());+ assert_eq!(two_sided.project_local_normal(back), Some(-Vector::Y));++ // The mirrored projection is the negation of the front projection.+ let cone_axes = [+ bisector_y(-Vector::Z),+ bisector_y(-Vector::X),+ bisector_y(Vector::new(1.0, 0.0, 1.0).normalize()),+ ];+ let pn = TrianglePseudoNormals {+ face: Vector::Y,+ edges: cone_axes,+ two_sided: true,+ };+ for dir in [+ Vector::new(0.3, 1.0, -0.8).normalize(),+ Vector::new(-1.0, 0.2, 0.1).normalize(),+ Vector::new(0.9, 0.5, 0.9).normalize(),+ ] {+ let front = pn.project_local_normal(dir).unwrap();+ let back = pn.project_local_normal(-dir).unwrap();+ assert!(back.abs_diff_eq(-front, 1.0e-6));+ }+ }+}diff --git a/renderer/third_party/parry3d/src/shape/trimesh.rs b/renderer/third_party/parry3d/src/shape/trimesh.rsnew file mode 100644index 0000000..8215214--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/trimesh.rs@@ -0,0 +1,2303 @@+use crate::bounding_volume::Aabb;+#[cfg(feature = "dim3")]+use crate::math::VectorExt;+use crate::math::{Pose, Vector};+use crate::partitioning::{Bvh, BvhBuildStrategy};+#[cfg(feature = "dim3")]+use crate::shape::SubShapeId;+use crate::shape::{FeatureId, Shape, Triangle, TrianglePseudoNormals, TypedCompositeShape};+use crate::utils::HashablePartialEq;+use alloc::{vec, vec::Vec};+use core::fmt;+#[cfg(feature = "dim3")]+use {crate::shape::Cuboid, crate::utils::SortedPair};++use {+ crate::shape::composite_shape::CompositeShape,+ crate::utils::hashmap::{Entry, HashMap},+ crate::utils::hashset::HashSet,+};++#[cfg(feature = "dim2")]+use crate::transformation::ear_clipping::triangulate_ear_clipping;++use crate::query::details::NormalConstraints;++/// Errors that occur when computing or validating triangle mesh topology.+///+/// Triangle mesh topology describes the connectivity and adjacency relationships between+/// vertices, edges, and triangles. When constructing a mesh with [`TriMeshFlags::HALF_EDGE_TOPOLOGY`],+/// Parry validates these relationships and returns this error if inconsistencies are found.+///+/// # When This Occurs+///+/// Topology errors typically occur when:+/// - The mesh is non-manifold (edges with more than 2 adjacent faces)+/// - Adjacent triangles have inconsistent winding order+/// - Triangles have degenerate geometry (duplicate vertices)+///+/// [`TriMeshFlags::HALF_EDGE_TOPOLOGY`]: crate::shape::TriMeshFlags::HALF_EDGE_TOPOLOGY+#[derive(thiserror::Error, Copy, Clone, Debug, PartialEq, Eq)]+pub enum TopologyError {+ /// A triangle has two or three identical vertices (degenerate triangle).+ ///+ /// This error indicates that a triangle in the mesh references the same vertex+ /// multiple times, creating a degenerate triangle (zero area). For example,+ /// a triangle with indices `[5, 5, 7]` or `[1, 2, 1]`.+ ///+ /// Degenerate triangles cannot be part of a valid mesh topology because they+ /// don't have proper edges or face normals.+ ///+ // /// TODO: figure out why this doc-test fails.+ // /// # How to Fix+ // ///+ // /// ```+ // /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ // /// # use parry3d::shape::{TriMesh, TriMeshFlags};+ // /// # use parry3d::math::Vector;+ // /// let vertices = vec![+ // /// Vector::ZERO,+ // /// Vector::new(1.0, 0.0, 0.0),+ // /// Vector::new(0.0, 1.0, 0.0),+ // /// ];+ // ///+ // /// // BAD: Triangle with duplicate vertices+ // /// let bad_indices = vec![[0, 0, 1]]; // vertex 0 appears twice!+ // ///+ // /// let result = TriMesh::with_flags(+ // /// vertices.clone(),+ // /// bad_indices,+ // /// TriMeshFlags::HALF_EDGE_TOPOLOGY+ // /// );+ // /// assert!(result.is_err());+ // ///+ // /// // GOOD: All three vertices are distinct+ // /// let good_indices = vec![[0, 1, 2]];+ // /// let mesh = TriMesh::with_flags(+ // /// vertices,+ // /// good_indices,+ // /// TriMeshFlags::HALF_EDGE_TOPOLOGY+ // /// ).expect("Valid mesh");+ // /// # }+ // /// ```+ ///+ /// Alternatively, use [`TriMeshFlags::DELETE_DEGENERATE_TRIANGLES`] to automatically+ /// remove degenerate triangles:+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{TriMesh, TriMeshFlags};+ /// # use parry3d::math::Vector;+ /// # let vertices = vec![Vector::ZERO, Vector::new(1.0, 0.0, 0.0), Vector::new(0.0, 1.0, 0.0)];+ /// # let indices = vec![[0, 0, 1], [0, 1, 2]];+ /// let flags = TriMeshFlags::HALF_EDGE_TOPOLOGY+ /// | TriMeshFlags::DELETE_BAD_TOPOLOGY_TRIANGLES;+ ///+ /// let mesh = TriMesh::with_flags(vertices, indices, flags)+ /// .expect("Bad triangles removed");+ /// # }+ /// ```+ #[error("the triangle {0} has at least two identical vertices.")]+ BadTriangle(u32),++ /// Two adjacent triangles have opposite orientations (inconsistent winding).+ ///+ /// For a manifold mesh with consistent normals, adjacent triangles must have+ /// compatible orientations. If two triangles share an edge, they must traverse+ /// that edge in opposite directions.+ ///+ /// This error reports:+ /// - `triangle1`, `triangle2`: The indices of the two conflicting triangles+ /// - `edge`: The shared edge as a pair of vertex indices `(v1, v2)`+ ///+ /// # Example of the Problem+ ///+ /// ```text+ /// CORRECT (opposite winding on shared edge):+ /// Triangle 1: [a, b, c] -> edge (a,b)+ /// Triangle 2: [b, a, d] -> edge (b,a) ✓ opposite direction+ ///+ /// INCORRECT (same winding on shared edge):+ /// Triangle 1: [a, b, c] -> edge (a,b)+ /// Triangle 2: [a, b, d] -> edge (a,b) ✗ same direction!+ /// ```+ ///+ // /// TODO: figure out why this doc test fails?+ // /// # How to Fix+ // ///+ // /// You need to reverse the winding order of one of the triangles:+ // ///+ // /// ```+ // /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ // /// # use parry3d::shape::{TriMesh, TriMeshFlags};+ // /// # use parry3d::math::Vector;+ // /// let vertices = vec![+ // /// Vector::ZERO, // vertex 0+ // /// Vector::new(1.0, 0.0, 0.0), // vertex 1+ // /// Vector::new(0.5, 1.0, 0.0), // vertex 2+ // /// Vector::new(0.5, -1.0, 0.0), // vertex 3+ // /// ];+ // ///+ // /// // BAD: Both triangles traverse edge (0,1) in the same direction+ // /// let bad_indices = vec![+ // /// [0, 1, 2], // edge (0,1)+ // /// [0, 1, 3], // edge (0,1) - same direction!+ // /// ];+ // ///+ // /// let result = TriMesh::with_flags(+ // /// vertices.clone(),+ // /// bad_indices,+ // /// TriMeshFlags::HALF_EDGE_TOPOLOGY+ // /// );+ // /// assert!(result.is_err());+ // ///+ // /// // GOOD: Second triangle reversed to [1, 0, 3]+ // /// let good_indices = vec![+ // /// [0, 1, 2], // edge (0,1)+ // /// [1, 0, 3], // edge (1,0) - opposite direction!+ // /// ];+ // ///+ // /// let mesh = TriMesh::with_flags(+ // /// vertices,+ // /// good_indices,+ // /// TriMeshFlags::HALF_EDGE_TOPOLOGY+ // /// ).expect("Valid mesh");+ // /// # }+ // /// ```+ ///+ /// # Common Causes+ ///+ /// - Mixing clockwise and counter-clockwise triangle definitions+ /// - Incorrectly constructed mesh from modeling software+ /// - Manual mesh construction with inconsistent winding+ /// - Merging separate meshes with different conventions+ #[error("the triangles {triangle1} and {triangle2} sharing the edge {edge:?} have opposite orientations.")]+ BadAdjacentTrianglesOrientation {+ /// The first triangle, with an orientation opposite to the second triangle.+ triangle1: u32,+ /// The second triangle, with an orientation opposite to the first triangle.+ triangle2: u32,+ /// The edge shared between the two triangles.+ edge: (u32, u32),+ },+}++/// Errors that occur when creating a triangle mesh.+///+/// When constructing a [`TriMesh`] using [`TriMesh::new`] or [`TriMesh::with_flags`],+/// various validation checks are performed. This error type describes what went wrong.+///+/// # Common Usage+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::shape::{TriMesh, TriMeshBuilderError, TopologyError};+/// # use parry3d::math::Vector;+/// let vertices = vec![Vector::ZERO];+/// let indices = vec![]; // Empty!+///+/// match TriMesh::new(vertices, indices) {+/// Err(TriMeshBuilderError::EmptyIndices) => {+/// println!("Cannot create a mesh with no triangles");+/// }+/// Err(TriMeshBuilderError::TopologyError(topo_err)) => {+/// println!("Mesh topology is invalid: {}", topo_err);+/// }+/// Ok(mesh) => {+/// println!("Mesh created successfully");+/// }+/// }+/// # }+/// ```+///+/// [`TriMesh`]: crate::shape::TriMesh+/// [`TriMesh::new`]: crate::shape::TriMesh::new+/// [`TriMesh::with_flags`]: crate::shape::TriMesh::with_flags+#[derive(thiserror::Error, Copy, Clone, Debug, PartialEq, Eq)]+pub enum TriMeshBuilderError {+ /// The index buffer is empty (no triangles provided).+ ///+ /// A triangle mesh must contain at least one triangle. An empty index buffer+ /// is not valid because there's nothing to render or use for collision detection.+ ///+ /// # How to Fix+ ///+ /// Ensure your index buffer has at least one triangle:+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::TriMesh;+ /// # use parry3d::math::Vector;+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ ///+ /// // BAD: No triangles+ /// let empty_indices = vec![];+ /// assert!(TriMesh::new(vertices.clone(), empty_indices).is_err());+ ///+ /// // GOOD: At least one triangle+ /// let indices = vec![[0, 1, 2]];+ /// assert!(TriMesh::new(vertices, indices).is_ok());+ /// # }+ /// ```+ #[error("A triangle mesh must contain at least one triangle.")]+ EmptyIndices,++ /// The mesh topology is invalid.+ ///+ /// This wraps a [`TopologyError`] that provides details about the specific+ /// topology problem. This only occurs when creating a mesh with topology+ /// validation enabled (e.g., [`TriMeshFlags::HALF_EDGE_TOPOLOGY`]).+ ///+ /// See [`TopologyError`] for details on specific topology problems and how+ /// to fix them.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{TriMesh, TriMeshFlags, TriMeshBuilderError};+ /// # use parry3d::math::Vector;+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ ///+ /// // Triangle with duplicate vertices+ /// let bad_indices = vec![[0, 0, 1]];+ ///+ /// match TriMesh::with_flags(vertices, bad_indices, TriMeshFlags::HALF_EDGE_TOPOLOGY) {+ /// Err(TriMeshBuilderError::TopologyError(topo_err)) => {+ /// println!("Topology error: {}", topo_err);+ /// // Handle the specific topology issue+ /// }+ /// _ => {}+ /// }+ /// # }+ /// ```+ ///+ /// [`TriMeshFlags::HALF_EDGE_TOPOLOGY`]: crate::shape::TriMeshFlags::HALF_EDGE_TOPOLOGY+ #[error("Topology Error: {0}")]+ TopologyError(TopologyError),+}++/// The set of pseudo-normals of a triangle mesh.+///+/// These pseudo-normals are used for the inside-outside test of a+/// point on the triangle, as described in the paper:+/// "Signed distance computation using the angle weighted pseudonormal", Baerentzen, et al.+/// DOI: 10.1109/TVCG.2005.49+#[derive(Default, Clone)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+#[cfg(feature = "dim3")]+pub struct TriMeshPseudoNormals {+ /// The pseudo-normals of the vertices.+ pub vertices_pseudo_normal: Vec<Vector>,+ /// The pseudo-normals of the edges.+ pub edges_pseudo_normal: Vec<[Vector; 3]>,+}++/// The connected-components of a triangle mesh.+#[derive(Debug, Clone)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+pub struct TriMeshConnectedComponents {+ /// The `face_colors[i]` gives the connected-component index+ /// of the i-th face.+ pub face_colors: Vec<u32>,+ /// The set of faces grouped by connected components.+ pub grouped_faces: Vec<u32>,+ /// The range of connected components. `self.grouped_faces[self.ranges[i]..self.ranges[i + 1]]`+ /// contains the indices of all the faces part of the i-th connected component.+ pub ranges: Vec<usize>,+}++impl TriMeshConnectedComponents {+ /// The total number of connected components.+ pub fn num_connected_components(&self) -> usize {+ self.ranges.len() - 1+ }++ /// Convert the connected-component description into actual meshes (returned as raw index and+ /// vertex buffers).+ ///+ /// The `mesh` must be the one used to generate `self`, otherwise it might panic or produce an+ /// unexpected result.+ pub fn to_mesh_buffers(&self, mesh: &TriMesh) -> Vec<(Vec<Vector>, Vec<[u32; 3]>)> {+ let mut result = vec![];+ let mut new_vtx_index: Vec<_> = vec![u32::MAX; mesh.vertices.len()];++ for ranges in self.ranges.windows(2) {+ let num_faces = ranges[1] - ranges[0];++ if num_faces == 0 {+ continue;+ }++ let mut vertices = Vec::with_capacity(num_faces);+ let mut indices = Vec::with_capacity(num_faces);++ for fid in ranges[0]..ranges[1] {+ let vids = mesh.indices[self.grouped_faces[fid] as usize];+ let new_vids = vids.map(|id| {+ if new_vtx_index[id as usize] == u32::MAX {+ vertices.push(mesh.vertices[id as usize]);+ new_vtx_index[id as usize] = vertices.len() as u32 - 1;+ }++ new_vtx_index[id as usize]+ });+ indices.push(new_vids);+ }++ result.push((vertices, indices));+ }++ result+ }++ /// Convert the connected-component description into actual meshes.+ ///+ /// The `mesh` must be the one used to generate `self`, otherwise it might panic or produce an+ /// unexpected result.+ ///+ /// All the meshes are constructed with the given `flags`.+ pub fn to_meshes(+ &self,+ mesh: &TriMesh,+ flags: TriMeshFlags,+ ) -> Vec<Result<TriMesh, TriMeshBuilderError>> {+ self.to_mesh_buffers(mesh)+ .into_iter()+ .map(|(vtx, idx)| TriMesh::with_flags(vtx, idx, flags))+ .collect()+ }+}++/// A vertex of a triangle-mesh’s half-edge topology.+#[derive(Clone, Copy, Debug)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+pub struct TopoVertex {+ /// One of the half-edge with this vertex as endpoint.+ pub half_edge: u32,+}++/// A face of a triangle-mesh’s half-edge topology.+#[derive(Clone, Copy, Debug)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+pub struct TopoFace {+ /// The half-edge adjacent to this face, with a starting point equal+ /// to the first point of this face.+ pub half_edge: u32,+}++/// A half-edge of a triangle-mesh’s half-edge topology.+#[derive(Clone, Copy, Debug)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+pub struct TopoHalfEdge {+ /// The next half-edge.+ pub next: u32,+ /// This half-edge twin on the adjacent triangle.+ ///+ /// This is `u32::MAX` if there is no twin.+ pub twin: u32,+ /// The first vertex of this edge.+ pub vertex: u32,+ /// The face associated to this half-edge.+ pub face: u32,+}++/// The half-edge topology information of a triangle mesh.+#[derive(Default, Clone)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+pub struct TriMeshTopology {+ /// The vertices of this half-edge representation.+ pub vertices: Vec<TopoVertex>,+ /// The faces of this half-edge representation.+ pub faces: Vec<TopoFace>,+ /// The half-edges of this half-edge representation.+ pub half_edges: Vec<TopoHalfEdge>,+}++#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]+/// Controls how a [`TriMesh`] should be loaded.+pub struct TriMeshFlags(u16);++bitflags::bitflags! {+ impl TriMeshFlags: u16 {+ /// If set, the half-edge topology of the trimesh will be computed if possible.+ const HALF_EDGE_TOPOLOGY = 1;+ /// If set, the connected components of the trimesh will be computed.+ const CONNECTED_COMPONENTS = 1 << 1;+ /// If set, any triangle that results in a failing half-hedge topology computation will be deleted.+ const DELETE_BAD_TOPOLOGY_TRIANGLES = 1 << 2;+ /// If set, the trimesh will be assumed to be oriented (with outward normals).+ ///+ /// The pseudo-normals of its vertices and edges will be computed.+ const ORIENTED = 1 << 3;+ /// If set, the duplicate vertices of the trimesh will be merged.+ ///+ /// Two vertices with the exact same coordinates will share the same entry on the+ /// vertex buffer and the index buffer is adjusted accordingly.+ const MERGE_DUPLICATE_VERTICES = 1 << 4;+ /// If set, the triangles sharing two vertices with identical index values will be removed.+ ///+ /// Because of the way it is currently implemented, this methods implies that duplicate+ /// vertices will be merged. It will no longer be the case in the future once we decouple+ /// the computations.+ const DELETE_DEGENERATE_TRIANGLES = 1 << 5;+ /// If set, two triangles sharing three vertices with identical index values (in any order)+ /// will be removed.+ ///+ /// Because of the way it is currently implemented, this methods implies that duplicate+ /// vertices will be merged. It will no longer be the case in the future once we decouple+ /// the computations.+ const DELETE_DUPLICATE_TRIANGLES = 1 << 6;+ /// If set, a special treatment will be applied to contact manifold calculation to eliminate+ /// or fix contacts normals that could lead to incorrect bumps in physics simulation+ /// (especially on flat surfaces).+ ///+ /// This is achieved by taking into account adjacent triangle normals when computing contact+ /// points for a given triangle.+ const FIX_INTERNAL_EDGES = (1 << 7) | Self::MERGE_DUPLICATE_VERTICES.bits();+ /// If set, the vertices of this mesh are expected to move between queries while its pose+ /// stays fixed (see [`TriMesh::set_vertices`]).+ ///+ /// The contact-manifold queries then recompute the triangles interfering with the other+ /// shape at every call and never reuse cached contact points (see+ /// [`CompositeShape::is_deformable`]).+ const DEFORMABLE = 1 << 8;+ /// Same as [`Self::FIX_INTERNAL_EDGES`] but treating the mesh as two-sided: a contact+ /// coming from the back of a triangle is kept and its normal is constrained by the+ /// mirrored pseudo-normal cone instead of being discarded.+ const FIX_INTERNAL_EDGES_TWO_SIDED = (1 << 9) | Self::FIX_INTERNAL_EDGES.bits();+ }+}++#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+#[repr(C)]+#[derive(Clone)]+/// A triangle mesh.+pub struct TriMesh {+ bvh: Bvh,+ vertices: Vec<Vector>,+ indices: Vec<[u32; 3]>,+ #[cfg(feature = "dim3")]+ pub(crate) pseudo_normals: Option<TriMeshPseudoNormals>,+ topology: Option<TriMeshTopology>,+ connected_components: Option<TriMeshConnectedComponents>,+ flags: TriMeshFlags,+}++// NOTE: can't be derived because of the `Bvh` and topology fields; print a+// summary useful for quickly validating the mesh instead.+impl fmt::Debug for TriMesh {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ let mut dbg = f.debug_struct("TriMesh");+ let dbg = dbg+ .field("num_vertices", &self.vertices.len())+ .field("num_triangles", &self.indices.len())+ .field("local_aabb", &self.local_aabb())+ .field("flags", &self.flags);++ #[cfg(feature = "dim3")]+ let dbg = dbg.field("has_pseudo_normals", &self.pseudo_normals.is_some());++ dbg.field("has_topology", &self.topology.is_some())+ .field(+ "has_connected_components",+ &self.connected_components.is_some(),+ )+ .finish_non_exhaustive()+ }+}++impl TriMesh {+ /// Creates a new triangle mesh from a vertex buffer and an index buffer.+ ///+ /// This is the most common way to construct a `TriMesh`. The mesh is created with+ /// default settings (no topology computation, no pseudo-normals, etc.). For more+ /// control over these optional features, use [`TriMesh::with_flags`] instead.+ ///+ /// # Arguments+ ///+ /// * `vertices` - A vector of 3D points representing the mesh vertices+ /// * `indices` - A vector of triangles, where each triangle is represented by+ /// three indices into the vertex buffer. Indices should be in counter-clockwise+ /// order for outward-facing normals.+ ///+ /// # Returns+ ///+ /// * `Ok(TriMesh)` - If the mesh was successfully created+ /// * `Err(TriMeshBuilderError)` - If the mesh is invalid (e.g., empty index buffer)+ ///+ /// # Errors+ ///+ /// This function returns an error if:+ /// - The index buffer is empty (at least one triangle is required)+ ///+ /// # Performance+ ///+ /// This function builds a BVH (Bounding Volume Hierarchy) acceleration structure+ /// for the mesh, which takes O(n log n) time where n is the number of triangles.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::Vector;+ ///+ /// // Create a simple triangle mesh (a single triangle)+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2]];+ ///+ /// let trimesh = TriMesh::new(vertices, indices).expect("Invalid mesh");+ /// assert_eq!(trimesh.num_triangles(), 1);+ /// # }+ /// ```+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::TriMesh;+ /// use parry2d::math::Vector;+ ///+ /// // Create a quad (two triangles) in 2D+ /// let vertices = vec![+ /// Vector::ZERO, // bottom-left+ /// Vector::new(1.0, 0.0), // bottom-right+ /// Vector::new(1.0, 1.0), // top-right+ /// Vector::new(0.0, 1.0), // top-left+ /// ];+ /// let indices = vec![+ /// [0, 1, 2], // first triangle+ /// [0, 2, 3], // second triangle+ /// ];+ ///+ /// let quad = TriMesh::new(vertices, indices).unwrap();+ /// assert_eq!(quad.num_triangles(), 2);+ /// assert_eq!(quad.vertices().len(), 4);+ /// # }+ /// ```+ pub fn new(vertices: Vec<Vector>, indices: Vec<[u32; 3]>) -> Result<Self, TriMeshBuilderError> {+ Self::with_flags(vertices, indices, TriMeshFlags::empty())+ }++ /// Creates a new triangle mesh from a vertex buffer and an index buffer, and flags controlling optional properties.+ ///+ /// This is the most flexible way to create a `TriMesh`, allowing you to specify exactly+ /// which optional features should be computed. Use this when you need:+ /// - Half-edge topology for adjacency information+ /// - Connected components analysis+ /// - Pseudo-normals for robust inside/outside tests+ /// - Automatic merging of duplicate vertices+ /// - Removal of degenerate or duplicate triangles+ ///+ /// # Arguments+ ///+ /// * `vertices` - A vector of 3D points representing the mesh vertices+ /// * `indices` - A vector of triangles, where each triangle is represented by+ /// three indices into the vertex buffer+ /// * `flags` - A combination of [`TriMeshFlags`] controlling which optional features to compute+ ///+ /// # Returns+ ///+ /// * `Ok(TriMesh)` - If the mesh was successfully created+ /// * `Err(TriMeshBuilderError)` - If the mesh is invalid or topology computation failed+ ///+ /// # Errors+ ///+ /// This function returns an error if:+ /// - The index buffer is empty+ /// - [`TriMeshFlags::HALF_EDGE_TOPOLOGY`] is set but the topology is invalid+ /// (e.g., non-manifold edges or inconsistent orientations)+ ///+ /// # Performance+ ///+ /// - Base construction: O(n log n) for BVH building+ /// - `HALF_EDGE_TOPOLOGY`: O(n) where n is the number of triangles+ /// - `CONNECTED_COMPONENTS`: O(n) with union-find+ /// - `ORIENTED` or `FIX_INTERNAL_EDGES`: O(n) for pseudo-normal computation+ /// - `MERGE_DUPLICATE_VERTICES`: O(n) with hash map lookups+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{TriMesh, TriMeshFlags};+ /// use parry3d::math::Vector;+ ///+ /// // Create vertices for a simple mesh+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(1.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2], [1, 3, 2]];+ ///+ /// // Create a mesh with half-edge topology+ /// let flags = TriMeshFlags::HALF_EDGE_TOPOLOGY;+ /// let mesh = TriMesh::with_flags(vertices.clone(), indices.clone(), flags)+ /// .expect("Failed to create mesh");+ ///+ /// // The topology information is now available+ /// assert!(mesh.topology().is_some());+ /// # }+ /// ```+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{TriMesh, TriMeshFlags};+ /// use parry3d::math::Vector;+ ///+ /// # let vertices = vec![+ /// # Vector::ZERO,+ /// # Vector::new(1.0, 0.0, 0.0),+ /// # Vector::new(0.0, 1.0, 0.0),+ /// # ];+ /// # let indices = vec![[0, 1, 2]];+ /// // Combine multiple flags for advanced features+ /// let flags = TriMeshFlags::HALF_EDGE_TOPOLOGY+ /// | TriMeshFlags::MERGE_DUPLICATE_VERTICES+ /// | TriMeshFlags::DELETE_DEGENERATE_TRIANGLES;+ ///+ /// let mesh = TriMesh::with_flags(vertices, indices, flags)+ /// .expect("Failed to create mesh");+ /// # }+ /// ```+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{TriMesh, TriMeshFlags};+ /// use parry3d::math::Vector;+ ///+ /// # let vertices = vec![+ /// # Vector::ZERO,+ /// # Vector::new(1.0, 0.0, 0.0),+ /// # Vector::new(0.0, 1.0, 0.0),+ /// # ];+ /// # let indices = vec![[0, 1, 2]];+ /// // For robust point containment tests in 3D+ /// let flags = TriMeshFlags::ORIENTED;+ /// let mesh = TriMesh::with_flags(vertices, indices, flags)+ /// .expect("Failed to create mesh");+ ///+ /// // Pseudo-normals are now computed for accurate inside/outside tests+ /// assert!(mesh.pseudo_normals().is_some());+ /// # }+ /// ```+ pub fn with_flags(+ vertices: Vec<Vector>,+ indices: Vec<[u32; 3]>,+ flags: TriMeshFlags,+ ) -> Result<Self, TriMeshBuilderError> {+ if indices.is_empty() {+ return Err(TriMeshBuilderError::EmptyIndices);+ }++ let mut result = Self {+ bvh: Bvh::new(),+ vertices,+ indices,+ #[cfg(feature = "dim3")]+ pseudo_normals: None,+ topology: None,+ connected_components: None,+ flags: TriMeshFlags::empty(),+ };++ let _ = result.set_flags(flags);++ if result.bvh.is_empty() {+ // The BVH hasn’t been computed by `.set_flags`.+ result.rebuild_bvh();+ }++ Ok(result)+ }++ /// Sets the flags of this triangle mesh, controlling its optional associated data.+ pub fn set_flags(&mut self, flags: TriMeshFlags) -> Result<(), TopologyError> {+ let mut result = Ok(());+ let prev_indices_len = self.indices.len();++ if !flags.contains(TriMeshFlags::HALF_EDGE_TOPOLOGY) {+ self.topology = None;+ }++ #[cfg(feature = "dim3")]+ if !flags.intersects(TriMeshFlags::ORIENTED | TriMeshFlags::FIX_INTERNAL_EDGES) {+ self.pseudo_normals = None;+ }++ if !flags.contains(TriMeshFlags::CONNECTED_COMPONENTS) {+ self.connected_components = None;+ }++ let difference = flags & !self.flags;++ if difference.intersects(+ TriMeshFlags::MERGE_DUPLICATE_VERTICES+ | TriMeshFlags::DELETE_DEGENERATE_TRIANGLES+ | TriMeshFlags::DELETE_DUPLICATE_TRIANGLES,+ ) {+ self.merge_duplicate_vertices(+ flags.contains(TriMeshFlags::DELETE_DEGENERATE_TRIANGLES),+ flags.contains(TriMeshFlags::DELETE_DUPLICATE_TRIANGLES),+ )+ }++ if difference.intersects(+ TriMeshFlags::HALF_EDGE_TOPOLOGY | TriMeshFlags::DELETE_BAD_TOPOLOGY_TRIANGLES,+ ) {+ result =+ self.compute_topology(flags.contains(TriMeshFlags::DELETE_BAD_TOPOLOGY_TRIANGLES));+ }++ #[cfg(feature = "std")]+ if difference.intersects(TriMeshFlags::CONNECTED_COMPONENTS) {+ self.compute_connected_components();+ }++ #[cfg(feature = "dim3")]+ if difference.intersects(TriMeshFlags::ORIENTED | TriMeshFlags::FIX_INTERNAL_EDGES) {+ self.compute_pseudo_normals();+ }++ if prev_indices_len != self.indices.len() {+ self.rebuild_bvh();+ }++ self.flags = flags;+ result+ }++ // TODO: support a crate like get_size2 (will require support on nalgebra too)?+ /// An approximation of the memory usage (in bytes) for this struct plus+ /// the memory it allocates dynamically.+ pub fn total_memory_size(&self) -> usize {+ size_of::<Self>() + self.heap_memory_size()+ }++ /// An approximation of the memory dynamically-allocated by this struct.+ pub fn heap_memory_size(&self) -> usize {+ // NOTE: if a new field is added to `Self`, adjust this function result.+ let Self {+ bvh,+ vertices,+ indices,+ topology,+ connected_components,+ flags: _,+ #[cfg(feature = "dim3")]+ pseudo_normals,+ } = self;+ let sz_bvh = bvh.heap_memory_size();+ let sz_vertices = vertices.capacity() * size_of::<Vector>();+ let sz_indices = indices.capacity() * size_of::<[u32; 3]>();+ #[cfg(feature = "dim3")]+ let sz_pseudo_normals = pseudo_normals+ .as_ref()+ .map(|pn| {+ pn.vertices_pseudo_normal.capacity() * size_of::<Vector>()+ + pn.edges_pseudo_normal.capacity() * size_of::<[Vector; 3]>()+ })+ .unwrap_or(0);+ #[cfg(feature = "dim2")]+ let sz_pseudo_normals = 0;+ let sz_topology = topology+ .as_ref()+ .map(|t| {+ t.vertices.capacity() * size_of::<TopoVertex>()+ + t.faces.capacity() * size_of::<TopoFace>()+ + t.half_edges.capacity() * size_of::<TopoHalfEdge>()+ })+ .unwrap_or(0);+ let sz_connected_components = connected_components+ .as_ref()+ .map(|c| {+ c.face_colors.capacity() * size_of::<u32>()+ + c.grouped_faces.capacity() * size_of::<f32>()+ + c.ranges.capacity() * size_of::<usize>()+ })+ .unwrap_or(0);++ sz_bvh+ + sz_vertices+ + sz_indices+ + sz_pseudo_normals+ + sz_topology+ + sz_connected_components+ }++ /// Transforms in-place the vertices of this triangle mesh.+ ///+ /// Applies a rigid transformation (rotation and translation) to all vertices+ /// of the mesh. This is useful for positioning or orienting a mesh in world space.+ /// The transformation also updates the BVH and pseudo-normals (if present).+ ///+ /// # Arguments+ ///+ /// * `transform` - The isometry (rigid transformation) to apply to all vertices+ ///+ /// # Performance+ ///+ /// This operation is O(n) for transforming vertices, plus O(n log n) for+ /// rebuilding the BVH, where n is the number of triangles.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::{Vector, Pose};+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2]];+ /// let mut mesh = TriMesh::new(vertices, indices).unwrap();+ ///+ /// // Translate the mesh by (10, 0, 0)+ /// let transform = Pose::translation(10.0, 0.0, 0.0);+ /// mesh.transform_vertices(&transform);+ ///+ /// // All vertices are now shifted+ /// assert_eq!(mesh.vertices()[0], Vector::new(10.0, 0.0, 0.0));+ /// assert_eq!(mesh.vertices()[1], Vector::new(11.0, 0.0, 0.0));+ /// assert_eq!(mesh.vertices()[2], Vector::new(10.0, 1.0, 0.0));+ /// # }+ /// ```+ pub fn transform_vertices(&mut self, transform: &Pose) {+ self.vertices+ .iter_mut()+ .for_each(|pt| *pt = transform * *pt);+ self.rebuild_bvh();++ // The pseudo-normals must be rotated too.+ #[cfg(feature = "dim3")]+ if let Some(pseudo_normals) = &mut self.pseudo_normals {+ pseudo_normals+ .vertices_pseudo_normal+ .iter_mut()+ .for_each(|n| *n = transform.rotation * *n);+ pseudo_normals.edges_pseudo_normal.iter_mut().for_each(|n| {+ n[0] = transform.rotation * n[0];+ n[1] = transform.rotation * n[1];+ n[2] = transform.rotation * n[2];+ });+ }+ }++ /// Replaces the vertex positions in place, keeping the index buffer and topology.+ ///+ /// The BVH is refitted (not rebuilt) and the pseudo-normals, if any, are recomputed. This+ /// is the update path of a deformable mesh: `vertices.len()` must equal+ /// [`Self::vertices`]`.len()`.+ ///+ /// The refit keeps the tree structure built for the original vertices; after very large+ /// deformations, rebuilding the mesh gives a tighter tree.+ ///+ /// # Panics+ ///+ /// Panics if `vertices.len()` differs from the current number of vertices.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{TriMesh, TriMeshFlags};+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2]];+ /// let mut mesh = TriMesh::with_flags(vertices, indices, TriMeshFlags::DEFORMABLE).unwrap();+ ///+ /// // Lift the third vertex.+ /// mesh.set_vertices(&[+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 2.0),+ /// ]);+ /// assert_eq!(mesh.local_aabb().maxs, Vector::new(1.0, 1.0, 2.0));+ /// # }+ /// ```+ pub fn set_vertices(&mut self, vertices: &[Vector]) {+ assert_eq!(+ vertices.len(),+ self.vertices.len(),+ "TriMesh::set_vertices: the number of vertices must not change."+ );+ self.update_vertices(|vtx| vtx.copy_from_slice(vertices));+ }++ /// Modifies the vertex positions in place through `f`, then refits the BVH and recomputes+ /// the pseudo-normals, if any (see [`Self::set_vertices`]).+ pub fn update_vertices(&mut self, f: impl FnOnce(&mut [Vector])) {+ f(&mut self.vertices);+ self.refit_bvh();++ #[cfg(feature = "dim3")]+ if self.pseudo_normals.is_some() {+ self.compute_pseudo_normals();+ }+ }++ /// Updates every triangle's leaf AABB and refits the BVH in place, keeping its structure.+ fn refit_bvh(&mut self) {+ for (i, idx) in self.indices.iter().enumerate() {+ let aabb = Triangle::new(+ self.vertices[idx[0] as usize],+ self.vertices[idx[1] as usize],+ self.vertices[idx[2] as usize],+ )+ .local_aabb();+ let _ = self.bvh.insert_or_update_partially(aabb, i as u32, 0.0);+ }+ self.bvh.refit_without_opt();+ }++ /// Returns a scaled version of this triangle mesh.+ ///+ /// Creates a new mesh with all vertices scaled by the given per-axis scale factors.+ /// Unlike rigid transformations, scaling can change the shape of the mesh (when+ /// scale factors differ between axes).+ ///+ /// The scaling also updates pseudo-normals (if present) to remain valid after+ /// the transformation, and efficiently scales the BVH structure.+ ///+ /// # Arguments+ ///+ /// * `scale` - The scale factors for each axis (x, y, z in 3D)+ ///+ /// # Returns+ ///+ /// A new `TriMesh` with scaled vertices+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2]];+ /// let mesh = TriMesh::new(vertices, indices).unwrap();+ ///+ /// // Uniform scaling: double all dimensions+ /// let scaled = mesh.clone().scaled(Vector::new(2.0, 2.0, 2.0));+ /// assert_eq!(scaled.vertices()[1], Vector::new(2.0, 0.0, 0.0));+ ///+ /// // Non-uniform scaling: stretch along X axis+ /// let stretched = mesh.scaled(Vector::new(3.0, 1.0, 1.0));+ /// assert_eq!(stretched.vertices()[1], Vector::new(3.0, 0.0, 0.0));+ /// assert_eq!(stretched.vertices()[2], Vector::new(0.0, 1.0, 0.0));+ /// # }+ /// ```+ pub fn scaled(mut self, scale: Vector) -> Self {+ self.vertices.iter_mut().for_each(|pt| *pt *= scale);++ #[cfg(feature = "dim3")]+ if let Some(pn) = &mut self.pseudo_normals {+ pn.vertices_pseudo_normal.iter_mut().for_each(|n| {+ *n *= scale;+ *n = n.normalize_or(*n);+ });+ pn.edges_pseudo_normal.iter_mut().for_each(|n| {+ n[0] *= scale;+ n[1] *= scale;+ n[2] *= scale;++ n[0] = n[0].normalize_or(n[0]);+ n[1] = n[1].normalize_or(n[1]);+ n[2] = n[2].normalize_or(n[2]);+ });+ }++ let mut bvh = self.bvh.clone();+ bvh.scale(scale);++ Self {+ bvh,+ vertices: self.vertices,+ indices: self.indices,+ #[cfg(feature = "dim3")]+ pseudo_normals: self.pseudo_normals,+ topology: self.topology,+ connected_components: self.connected_components,+ flags: self.flags,+ }+ }++ /// Appends a second triangle mesh to this triangle mesh.+ ///+ /// This combines two meshes into one by adding all vertices and triangles from+ /// the `rhs` mesh to this mesh. The vertex indices in the appended triangles+ /// are automatically adjusted to reference the correct vertices in the combined+ /// vertex buffer.+ ///+ /// After appending, all optional features (topology, pseudo-normals, etc.) are+ /// recomputed according to this mesh's current flags.+ ///+ /// # Arguments+ ///+ /// * `rhs` - The mesh to append to this mesh+ ///+ /// # Performance+ ///+ /// This operation rebuilds the entire mesh with all its features, which can be+ /// expensive for large meshes. Time complexity is O(n log n) where n is the+ /// total number of triangles after appending.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::Vector;+ ///+ /// // Create first mesh (a triangle)+ /// let vertices1 = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// let indices1 = vec![[0, 1, 2]];+ /// let mut mesh1 = TriMesh::new(vertices1, indices1).unwrap();+ ///+ /// // Create second mesh (another triangle, offset in space)+ /// let vertices2 = vec![+ /// Vector::new(2.0, 0.0, 0.0),+ /// Vector::new(3.0, 0.0, 0.0),+ /// Vector::new(2.0, 1.0, 0.0),+ /// ];+ /// let indices2 = vec![[0, 1, 2]];+ /// let mesh2 = TriMesh::new(vertices2, indices2).unwrap();+ ///+ /// // Append second mesh to first+ /// mesh1.append(&mesh2);+ ///+ /// assert_eq!(mesh1.num_triangles(), 2);+ /// assert_eq!(mesh1.vertices().len(), 6);+ /// # }+ /// ```+ pub fn append(&mut self, rhs: &TriMesh) {+ let base_id = self.vertices.len() as u32;+ self.vertices.extend_from_slice(rhs.vertices());+ self.indices.extend(+ rhs.indices()+ .iter()+ .map(|idx| [idx[0] + base_id, idx[1] + base_id, idx[2] + base_id]),+ );++ let vertices = core::mem::take(&mut self.vertices);+ let indices = core::mem::take(&mut self.indices);+ *self = TriMesh::with_flags(vertices, indices, self.flags).unwrap();+ }++ /// Create a `TriMesh` from a set of points assumed to describe a counter-clockwise non-convex polygon.+ ///+ /// This function triangulates a 2D polygon using ear clipping algorithm. The polygon+ /// can be convex or concave, but must be simple (no self-intersections) and have+ /// counter-clockwise winding order.+ ///+ /// # Arguments+ ///+ /// * `vertices` - The vertices of the polygon in counter-clockwise order+ ///+ /// # Returns+ ///+ /// * `Some(TriMesh)` - If triangulation succeeded+ /// * `None` - If the polygon is invalid (self-intersecting, degenerate, etc.)+ ///+ /// # Requirements+ ///+ /// - Polygon must be simple (no self-intersections)+ /// - Vertices must be in counter-clockwise order+ /// - Polygon must have non-zero area+ /// - Only available in 2D (`dim2` feature)+ ///+ /// # Performance+ ///+ /// Ear clipping has O(n²) time complexity in the worst case, where n is the+ /// number of vertices.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::shape::TriMesh;+ /// use parry2d::math::Vector;+ ///+ /// // Create a simple concave polygon (L-shape)+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(2.0, 0.0),+ /// Vector::new(2.0, 1.0),+ /// Vector::new(1.0, 1.0),+ /// Vector::new(1.0, 2.0),+ /// Vector::new(0.0, 2.0),+ /// ];+ ///+ /// let mesh = TriMesh::from_polygon(vertices)+ /// .expect("Failed to triangulate polygon");+ ///+ /// // The polygon has been triangulated+ /// assert!(mesh.num_triangles() > 0);+ /// # }+ /// ```+ #[cfg(feature = "dim2")]+ pub fn from_polygon(vertices: Vec<Vector>) -> Option<Self> {+ triangulate_ear_clipping(&vertices).map(|indices| Self::new(vertices, indices).unwrap())+ }++ /// A flat view of the index buffer of this mesh.+ ///+ /// Returns the triangle indices as a flat array of `u32` values, where every+ /// three consecutive values form a triangle. This is useful for interfacing+ /// with graphics APIs that expect flat index buffers.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(1.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2], [1, 3, 2]];+ /// let mesh = TriMesh::new(vertices, indices).unwrap();+ ///+ /// let flat = mesh.flat_indices();+ /// assert_eq!(flat, &[0, 1, 2, 1, 3, 2]);+ /// assert_eq!(flat.len(), mesh.num_triangles() * 3);+ /// # }+ /// ```+ pub fn flat_indices(&self) -> &[u32] {+ unsafe {+ let len = self.indices.len() * 3;+ let data = self.indices.as_ptr() as *const u32;+ core::slice::from_raw_parts(data, len)+ }+ }++ fn rebuild_bvh(&mut self) {+ let leaves = self.indices.iter().enumerate().map(|(i, idx)| {+ let aabb = Triangle::new(+ self.vertices[idx[0] as usize],+ self.vertices[idx[1] as usize],+ self.vertices[idx[2] as usize],+ )+ .local_aabb();+ (i, aabb)+ });++ self.bvh = Bvh::from_iter(BvhBuildStrategy::Binned, leaves)+ }++ /// Reverse the orientation of the triangle mesh.+ ///+ /// This flips the winding order of all triangles, effectively turning the mesh+ /// "inside-out". If triangles had counter-clockwise winding (outward normals),+ /// they will have clockwise winding (inward normals) after this operation.+ ///+ /// This is useful when:+ /// - A mesh was imported with incorrect orientation+ /// - You need to flip normals for rendering or physics+ /// - Creating the "back side" of a mesh+ ///+ /// # Performance+ ///+ /// This operation modifies triangles in-place (O(n)), but recomputes topology+ /// and pseudo-normals if they were present, which can be expensive for large meshes.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2]];+ ///+ /// let mut mesh = TriMesh::new(vertices, indices).unwrap();+ /// let original_triangle = mesh.triangle(0);+ ///+ /// // Reverse the mesh orientation+ /// mesh.reverse();+ ///+ /// let reversed_triangle = mesh.triangle(0);+ ///+ /// // The first two vertices are swapped+ /// assert_eq!(original_triangle.a, reversed_triangle.b);+ /// assert_eq!(original_triangle.b, reversed_triangle.a);+ /// assert_eq!(original_triangle.c, reversed_triangle.c);+ /// # }+ /// ```+ pub fn reverse(&mut self) {+ self.indices.iter_mut().for_each(|idx| idx.swap(0, 1));++ // NOTE: the BVH, and connected components are not changed by this operation.+ // The pseudo-normals just have to be flipped.+ // The topology must be recomputed.++ #[cfg(feature = "dim3")]+ if let Some(pseudo_normals) = &mut self.pseudo_normals {+ for n in &mut pseudo_normals.vertices_pseudo_normal {+ *n = -*n;+ }++ for n in pseudo_normals.edges_pseudo_normal.iter_mut() {+ n[0] = -n[0];+ n[1] = -n[1];+ n[2] = -n[2];+ }+ }++ if self.flags.contains(TriMeshFlags::HALF_EDGE_TOPOLOGY) {+ // TODO: this could be done more efficiently.+ let _ = self.compute_topology(false);+ }+ }++ /// Merge all duplicate vertices and adjust the index buffer accordingly.+ ///+ /// If `delete_degenerate_triangles` is set to true, any triangle with two+ /// identical vertices will be removed.+ ///+ /// This is typically used to recover a vertex buffer from which we can deduce+ /// adjacency information. between triangles by observing how the vertices are+ /// shared by triangles based on the index buffer.+ fn merge_duplicate_vertices(+ &mut self,+ delete_degenerate_triangles: bool,+ delete_duplicate_triangles: bool,+ ) {+ let mut vtx_to_id = HashMap::default();+ let mut new_vertices = Vec::with_capacity(self.vertices.len());+ let mut new_indices = Vec::with_capacity(self.indices.len());+ let mut triangle_set = HashSet::default();++ fn resolve_coord_id(+ coord: Vector,+ vtx_to_id: &mut HashMap<HashablePartialEq<Vector>, u32>,+ new_vertices: &mut Vec<Vector>,+ ) -> u32 {+ let key = HashablePartialEq::new(coord);+ let id = match vtx_to_id.entry(key) {+ Entry::Occupied(entry) => entry.into_mut(),+ Entry::Vacant(entry) => entry.insert(new_vertices.len() as u32),+ };++ if *id == new_vertices.len() as u32 {+ new_vertices.push(coord);+ }++ *id+ }++ for t in self.indices.iter() {+ let va = resolve_coord_id(+ self.vertices[t[0] as usize],+ &mut vtx_to_id,+ &mut new_vertices,+ );++ let vb = resolve_coord_id(+ self.vertices[t[1] as usize],+ &mut vtx_to_id,+ &mut new_vertices,+ );++ let vc = resolve_coord_id(+ self.vertices[t[2] as usize],+ &mut vtx_to_id,+ &mut new_vertices,+ );++ let is_degenerate = va == vb || va == vc || vb == vc;++ if !is_degenerate || !delete_degenerate_triangles {+ if delete_duplicate_triangles {+ let (c, b, a) = crate::utils::sort3(&va, &vb, &vc);+ if triangle_set.insert((*a, *b, *c)) {+ new_indices.push([va, vb, vc])+ }+ } else {+ new_indices.push([va, vb, vc]);+ }+ }+ }++ new_vertices.shrink_to_fit();++ self.vertices = new_vertices;+ self.indices = new_indices;++ // Vertices and indices changed: the pseudo-normals are no longer valid.+ #[cfg(feature = "dim3")]+ if self.pseudo_normals.is_some() {+ self.compute_pseudo_normals();+ }++ // Vertices and indices changed: the topology no longer valid.+ #[cfg(feature = "dim3")]+ if self.topology.is_some() {+ let _ = self.compute_topology(false);+ }+ }++ #[cfg(feature = "dim3")]+ /// Computes the pseudo-normals used for solid point-projection.+ ///+ /// This computes the pseudo-normals needed by the point containment test described in+ /// "Signed distance computation using the angle weighted pseudonormal", Baerentzen, et al.+ /// DOI: 10.1109/TVCG.2005.49+ ///+ /// For the point-containment test to properly detect the inside of the trimesh (i.e. to return+ /// `proj.is_inside = true`), the trimesh must:+ /// - Be manifold (closed, no t-junctions, etc.)+ /// - Be oriented with outward normals.+ ///+ /// If the trimesh is correctly oriented, but is manifold everywhere except at its boundaries,+ /// then the computed pseudo-normals will provide correct point-containment test results except+ /// for points closest to the boundary of the mesh.+ ///+ /// It may be useful to call `self.remove_duplicate_vertices()` before this method, in order to fix the+ /// index buffer if some of the vertices of this trimesh are duplicated.+ fn compute_pseudo_normals(&mut self) {+ let mut vertices_pseudo_normal = vec![Vector::ZERO; self.vertices().len()];+ let mut edges_pseudo_normal = HashMap::default();+ let mut edges_multiplicity = HashMap::default();++ for idx in self.indices() {+ let vtx = self.vertices();+ let tri = Triangle::new(+ vtx[idx[0] as usize],+ vtx[idx[1] as usize],+ vtx[idx[2] as usize],+ );++ if let Some(n) = tri.normal() {+ let ang1 = (tri.b - tri.a).angle(tri.c - tri.a);+ let ang2 = (tri.a - tri.b).angle(tri.c - tri.b);+ let ang3 = (tri.b - tri.c).angle(tri.a - tri.c);++ vertices_pseudo_normal[idx[0] as usize] += n * ang1;+ vertices_pseudo_normal[idx[1] as usize] += n * ang2;+ vertices_pseudo_normal[idx[2] as usize] += n * ang3;++ let edges = [+ SortedPair::new(idx[0], idx[1]),+ SortedPair::new(idx[0], idx[2]),+ SortedPair::new(idx[1], idx[2]),+ ];++ for edge in &edges {+ let edge_n = edges_pseudo_normal.entry(*edge).or_insert(Vector::ZERO);+ *edge_n += n; // NOTE: there is no need to multiply by the incident angle since it is always equal to PI for all the edges.+ let edge_mult = edges_multiplicity.entry(*edge).or_insert(0);+ *edge_mult += 1;+ }+ }+ }++ let edges_pseudo_normal = self+ .indices()+ .iter()+ .map(|idx| {+ let e0 = SortedPair::new(idx[0], idx[1]);+ let e1 = SortedPair::new(idx[1], idx[2]);+ let e2 = SortedPair::new(idx[2], idx[0]);+ let default = Vector::ZERO;+ [+ edges_pseudo_normal.get(&e0).copied().unwrap_or(default),+ edges_pseudo_normal.get(&e1).copied().unwrap_or(default),+ edges_pseudo_normal.get(&e2).copied().unwrap_or(default),+ ]+ })+ .collect();++ self.pseudo_normals = Some(TriMeshPseudoNormals {+ vertices_pseudo_normal,+ edges_pseudo_normal,+ })+ }++ fn delete_bad_topology_triangles(&mut self) {+ let mut half_edge_set = HashSet::default();+ let mut deleted_any = false;++ // First, create three half-edges for each face.+ self.indices.retain(|idx| {+ if idx[0] == idx[1] || idx[0] == idx[2] || idx[1] == idx[2] {+ deleted_any = true;+ return false;+ }++ for k in 0..3 {+ let edge_key = (idx[k as usize], idx[(k as usize + 1) % 3]);+ if half_edge_set.contains(&edge_key) {+ deleted_any = true;+ return false;+ }+ }++ for k in 0..3 {+ let edge_key = (idx[k as usize], idx[(k as usize + 1) % 3]);+ let _ = half_edge_set.insert(edge_key);+ }++ true+ });+ }++ /// Computes half-edge topological information for this triangle mesh, based on its index buffer only.+ ///+ /// This computes the half-edge representation of this triangle mesh’s topology. This is useful for advanced+ /// geometric operations like trimesh-trimesh intersection geometry computation.+ ///+ /// It may be useful to call `self.merge_duplicate_vertices(true, true)` before this method, in order to fix the+ /// index buffer if some of the vertices of this trimesh are duplicated.+ ///+ /// # Return+ /// Returns `true` if the computation succeeded. Returns `false` if this mesh can’t have an half-edge representation+ /// because at least three faces share the same edge.+ fn compute_topology(&mut self, delete_bad_triangles: bool) -> Result<(), TopologyError> {+ if delete_bad_triangles {+ self.delete_bad_topology_triangles();+ }++ let mut topology = TriMeshTopology::default();+ let mut half_edge_map = HashMap::default();++ topology.vertices.resize(+ self.vertices.len(),+ TopoVertex {+ half_edge: u32::MAX,+ },+ );++ // First, create three half-edges for each face.+ for (fid, idx) in self.indices.iter().enumerate() {+ let half_edge_base_id = topology.half_edges.len() as u32;++ if idx[0] == idx[1] || idx[0] == idx[2] || idx[1] == idx[2] {+ return Err(TopologyError::BadTriangle(fid as u32));+ }++ for k in 0u32..3 {+ let half_edge = TopoHalfEdge {+ next: half_edge_base_id + (k + 1) % 3,+ // We don’t know which one it is yet.+ // If the twin doesn’t exist, we use `u32::MAX` as+ // it’s (invalid) index. This value can be relied on+ // by other algorithms.+ twin: u32::MAX,+ vertex: idx[k as usize],+ face: fid as u32,+ };+ topology.half_edges.push(half_edge);++ let edge_key = (idx[k as usize], idx[(k as usize + 1) % 3]);++ if let Some(existing) = half_edge_map.insert(edge_key, half_edge_base_id + k) {+ // If the same edge already exists (with the same vertex order) then+ // we have two triangles sharing the same but with opposite incompatible orientations.+ return Err(TopologyError::BadAdjacentTrianglesOrientation {+ edge: edge_key,+ triangle1: topology.half_edges[existing as usize].face,+ triangle2: fid as u32,+ });+ }++ topology.vertices[idx[k as usize] as usize].half_edge = half_edge_base_id + k;+ }++ topology.faces.push(TopoFace {+ half_edge: half_edge_base_id,+ })+ }++ // Second, identify twins.+ for (key, he1) in &half_edge_map {+ if key.0 < key.1 {+ // Test, to avoid checking the same pair twice.+ if let Some(he2) = half_edge_map.get(&(key.1, key.0)) {+ topology.half_edges[*he1 as usize].twin = *he2;+ topology.half_edges[*he2 as usize].twin = *he1;+ }+ }+ }++ self.topology = Some(topology);++ Ok(())+ }++ // NOTE: this is private because that calculation is controlled by TriMeshFlags::CONNECTED_COMPONENTS+ // TODO: we should remove the CONNECTED_COMPONENTS flags and just have this be a free function.+ // TODO: this should be no_std compatible once ena is or once we have an alternative for it.+ #[cfg(feature = "std")]+ fn compute_connected_components(&mut self) {+ use ena::unify::{InPlaceUnificationTable, UnifyKey};++ #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]+ struct IntKey(u32);++ impl UnifyKey for IntKey {+ type Value = ();+ fn index(&self) -> u32 {+ self.0+ }+ fn from_index(u: u32) -> IntKey {+ IntKey(u)+ }+ fn tag() -> &'static str {+ "IntKey"+ }+ }++ let mut ufind: InPlaceUnificationTable<IntKey> = InPlaceUnificationTable::new();+ let mut face_colors = vec![u32::MAX; self.indices.len()];+ let mut ranges = vec![0];+ let mut vertex_to_range = vec![u32::MAX; self.vertices.len()];+ let mut grouped_faces = vec![u32::MAX; self.indices.len()];+ let mut vertex_to_key = vec![IntKey(u32::MAX); self.vertices.len()];++ let mut vertex_key = |id: u32, ufind: &mut InPlaceUnificationTable<IntKey>| {+ if vertex_to_key[id as usize].0 == u32::MAX {+ let new_key = ufind.new_key(());+ vertex_to_key[id as usize] = new_key;+ new_key+ } else {+ vertex_to_key[id as usize]+ }+ };++ for idx in self.indices() {+ let keys = idx.map(|i| vertex_key(i, &mut ufind));+ ufind.union(keys[0], keys[1]);+ ufind.union(keys[1], keys[2]);+ ufind.union(keys[2], keys[0]);+ }++ for (idx, face_color) in self.indices().iter().zip(face_colors.iter_mut()) {+ debug_assert_eq!(+ ufind.find(vertex_to_key[idx[0] as usize]),+ ufind.find(vertex_to_key[idx[1] as usize])+ );+ debug_assert_eq!(+ ufind.find(vertex_to_key[idx[0] as usize]),+ ufind.find(vertex_to_key[idx[2] as usize])+ );++ let group_index = ufind.find(vertex_to_key[idx[0] as usize]).0 as usize;++ if vertex_to_range[group_index] == u32::MAX {+ // Additional range+ ranges.push(0);+ vertex_to_range[group_index] = ranges.len() as u32 - 1;+ }++ let range_id = vertex_to_range[group_index];+ ranges[range_id as usize] += 1;+ // NOTE: the range_id points to the range upper bound. The face color is the range lower bound.+ *face_color = range_id - 1;+ }++ // Cumulated sum on range indices, to find the first index faces need to be inserted into+ // for each range.+ for i in 1..ranges.len() {+ ranges[i] += ranges[i - 1];+ }++ debug_assert_eq!(*ranges.last().unwrap(), self.indices().len());++ // Group faces.+ let mut insertion_in_range_index = ranges.clone();+ for (face_id, face_color) in face_colors.iter().enumerate() {+ let insertion_index = &mut insertion_in_range_index[*face_color as usize];+ grouped_faces[*insertion_index] = face_id as u32;+ *insertion_index += 1;+ }++ self.connected_components = Some(TriMeshConnectedComponents {+ face_colors,+ grouped_faces,+ ranges,+ })+ }++ #[allow(dead_code)] // Useful for testing.+ pub(crate) fn assert_half_edge_topology_is_valid(&self) {+ let topo = self+ .topology+ .as_ref()+ .expect("No topology information found.");+ assert_eq!(self.vertices.len(), topo.vertices.len());+ assert_eq!(self.indices.len(), topo.faces.len());++ for (face_id, (face, idx)) in topo.faces.iter().zip(self.indices.iter()).enumerate() {+ let he0 = topo.half_edges[face.half_edge as usize];+ assert_eq!(he0.face, face_id as u32);+ assert_eq!(he0.vertex, idx[0]);+ let he1 = topo.half_edges[he0.next as usize];+ assert_eq!(he1.face, face_id as u32);+ assert_eq!(he1.vertex, idx[1]);+ let he2 = topo.half_edges[he1.next as usize];+ assert_eq!(he2.face, face_id as u32);+ assert_eq!(he2.vertex, idx[2]);+ assert_eq!(he2.next, face.half_edge);+ }++ for he in &topo.half_edges {+ let idx = &self.indices[he.face as usize];+ assert!(he.vertex == idx[0] || he.vertex == idx[1] || he.vertex == idx[2]);+ }+ }++ /// An iterator through all the triangles of this mesh.+ ///+ /// Returns an iterator that yields [`Triangle`] shapes representing each+ /// triangle in the mesh. Each triangle contains the actual 3D coordinates+ /// of its three vertices (not indices).+ ///+ /// # Performance+ ///+ /// The iterator performs vertex lookups on-the-fly, so iterating through+ /// all triangles is O(n) where n is the number of triangles.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(1.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2], [1, 3, 2]];+ /// let mesh = TriMesh::new(vertices, indices).unwrap();+ ///+ /// // Iterate through all triangles+ /// for triangle in mesh.triangles() {+ /// println!("Triangle: {:?}, {:?}, {:?}", triangle.a, triangle.b, triangle.c);+ /// }+ ///+ /// // Count triangles with specific properties+ /// let count = mesh.triangles()+ /// .filter(|tri| tri.area() > 0.1)+ /// .count();+ /// # }+ /// ```+ pub fn triangles(&self) -> impl ExactSizeIterator<Item = Triangle> + '_ {+ self.indices.iter().map(move |ids| {+ Triangle::new(+ self.vertices[ids[0] as usize],+ self.vertices[ids[1] as usize],+ self.vertices[ids[2] as usize],+ )+ })+ }++ #[cfg(feature = "dim3")]+ /// Gets the normal of the triangle `triangle_id`.+ pub fn triangle_normal(&self, triangle_id: SubShapeId) -> Option<Vector> {+ self.triangle(triangle_id % self.num_triangles() as u32)+ .feature_normal(FeatureId::Face(0))+ }+}++impl TriMesh {+ /// The flags of this triangle mesh.+ ///+ /// Returns the [`TriMeshFlags`] that were used to construct this mesh,+ /// indicating which optional features are enabled.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{TriMesh, TriMeshFlags};+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2]];+ ///+ /// let flags = TriMeshFlags::HALF_EDGE_TOPOLOGY;+ /// let mesh = TriMesh::with_flags(vertices, indices, flags).unwrap();+ ///+ /// assert!(mesh.flags().contains(TriMeshFlags::HALF_EDGE_TOPOLOGY));+ /// # }+ /// ```+ pub fn flags(&self) -> TriMeshFlags {+ self.flags+ }++ /// Compute the axis-aligned bounding box of this triangle mesh.+ ///+ /// Returns the AABB that tightly bounds all triangles of the mesh after+ /// applying the given isometry transformation.+ ///+ /// # Arguments+ ///+ /// * `pos` - The position/orientation of the mesh in world space+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::{Vector, Pose};+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2]];+ /// let mesh = TriMesh::new(vertices, indices).unwrap();+ ///+ /// let identity = Pose::identity();+ /// let aabb = mesh.aabb(&identity);+ ///+ /// // The AABB contains all vertices+ /// assert!(aabb.contains_local_point(Vector::new(0.5, 0.5, 0.0)));+ /// # }+ /// ```+ pub fn aabb(&self, pos: &Pose) -> Aabb {+ self.bvh.root_aabb().transform_by(pos)+ }++ /// Gets the local axis-aligned bounding box of this triangle mesh.+ ///+ /// Returns the AABB in the mesh's local coordinate system (without any+ /// transformation applied). This is faster than [`TriMesh::aabb`] when+ /// no transformation is needed.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::new(-1.0, -1.0, 0.0),+ /// Vector::new(1.0, -1.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2]];+ /// let mesh = TriMesh::new(vertices, indices).unwrap();+ ///+ /// let aabb = mesh.local_aabb();+ /// assert_eq!(aabb.mins.x, -1.0);+ /// assert_eq!(aabb.maxs.x, 1.0);+ /// # }+ /// ```+ pub fn local_aabb(&self) -> Aabb {+ self.bvh.root_aabb()+ }++ /// The acceleration structure used by this triangle-mesh.+ ///+ /// Returns a reference to the BVH (Bounding Volume Hierarchy) that+ /// accelerates spatial queries on this mesh. The BVH is used internally+ /// for ray casting, collision detection, and other geometric queries.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2]];+ /// let mesh = TriMesh::new(vertices, indices).unwrap();+ ///+ /// let bvh = mesh.bvh();+ /// // The BVH can be used for advanced spatial queries+ /// assert!(!bvh.is_empty());+ /// # }+ /// ```+ pub fn bvh(&self) -> &Bvh {+ &self.bvh+ }++ /// The number of triangles forming this mesh.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(1.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2], [1, 3, 2]];+ /// let mesh = TriMesh::new(vertices, indices).unwrap();+ ///+ /// assert_eq!(mesh.num_triangles(), 2);+ /// # }+ /// ```+ pub fn num_triangles(&self) -> usize {+ self.indices.len()+ }++ /// Does the given feature ID identify a backface of this trimesh?+ pub fn is_backface(&self, feature: FeatureId) -> bool {+ // The feature is the hit triangle's own, which reports its back face as `Face(1)`; the+ // triangle itself is identified by the result's `subshape`.+ feature == FeatureId::Face(1)+ }++ /// Get the `i`-th triangle of this mesh.+ ///+ /// Returns a [`Triangle`] shape with the actual vertex coordinates (not indices)+ /// of the requested triangle. The triangle index must be less than the number+ /// of triangles in the mesh.+ ///+ /// # Arguments+ ///+ /// * `i` - The index of the triangle to retrieve (0-based)+ ///+ /// # Panics+ ///+ /// Panics if `i >= self.num_triangles()`.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2]];+ /// let mesh = TriMesh::new(vertices, indices).unwrap();+ ///+ /// let triangle = mesh.triangle(0);+ /// assert_eq!(triangle.a, Vector::ZERO);+ /// assert_eq!(triangle.b, Vector::new(1.0, 0.0, 0.0));+ /// assert_eq!(triangle.c, Vector::new(0.0, 1.0, 0.0));+ /// # }+ /// ```+ pub fn triangle(&self, i: u32) -> Triangle {+ let idx = self.indices[i as usize];+ Triangle::new(+ self.vertices[idx[0] as usize],+ self.vertices[idx[1] as usize],+ self.vertices[idx[2] as usize],+ )+ }++ /// Returns the pseudo-normals of one of this mesh’s triangles, if it was computed.+ ///+ /// This returns `None` if the pseudo-normals of this triangle were not computed.+ /// To have its pseudo-normals computed, be sure to set the [`TriMeshFlags`] so that+ /// they contain the [`TriMeshFlags::FIX_INTERNAL_EDGES`] flag.+ #[cfg(feature = "dim3")]+ pub fn triangle_normal_constraints(&self, i: u32) -> Option<TrianglePseudoNormals> {+ if self.flags.contains(TriMeshFlags::FIX_INTERNAL_EDGES) {+ let triangle = self.triangle(i);+ let pseudo_normals = self.pseudo_normals.as_ref()?;+ let edges_pseudo_normals = pseudo_normals.edges_pseudo_normal[i as usize];++ // TODO: could the pseudo-normal be pre-normalized instead of having to renormalize+ // every time we need them?+ Some(TrianglePseudoNormals {+ face: triangle.normal()?,+ edges: [+ (edges_pseudo_normals[0]).try_normalize()?,+ (edges_pseudo_normals[1]).try_normalize()?,+ (edges_pseudo_normals[2]).try_normalize()?,+ ],+ two_sided: self+ .flags+ .contains(TriMeshFlags::FIX_INTERNAL_EDGES_TWO_SIDED),+ })+ } else {+ None+ }+ }++ #[cfg(feature = "dim2")]+ #[doc(hidden)]+ pub fn triangle_normal_constraints(&self, _i: u32) -> Option<TrianglePseudoNormals> {+ None+ }++ /// The vertex buffer of this mesh.+ ///+ /// Returns a slice containing all vertex positions as 3D points.+ /// The vertices are stored in the order they were provided during construction.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2]];+ /// let mesh = TriMesh::new(vertices, indices).unwrap();+ ///+ /// assert_eq!(mesh.vertices().len(), 3);+ /// assert_eq!(mesh.vertices()[0], Vector::ZERO);+ /// # }+ /// ```+ pub fn vertices(&self) -> &[Vector] {+ &self.vertices+ }++ /// The index buffer of this mesh.+ ///+ /// Returns a slice of triangles, where each triangle is represented as an+ /// array of three vertex indices. The indices reference positions in the+ /// vertex buffer returned by [`TriMesh::vertices`].+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::TriMesh;+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(1.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2], [1, 3, 2]];+ /// let mesh = TriMesh::new(vertices, indices).unwrap();+ ///+ /// assert_eq!(mesh.indices().len(), 2);+ /// assert_eq!(mesh.indices()[0], [0, 1, 2]);+ /// assert_eq!(mesh.indices()[1], [1, 3, 2]);+ /// # }+ /// ```+ pub fn indices(&self) -> &[[u32; 3]] {+ &self.indices+ }++ /// Returns the topology information of this trimesh, if it has been computed.+ ///+ /// Topology information includes half-edge data structures that describe+ /// adjacency relationships between vertices, edges, and faces. This is+ /// computed when the [`TriMeshFlags::HALF_EDGE_TOPOLOGY`] flag is set.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::{TriMesh, TriMeshFlags};+ /// use parry3d::math::Vector;+ ///+ /// let vertices = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2]];+ ///+ /// // Without topology flag+ /// let mesh = TriMesh::new(vertices.clone(), indices.clone()).unwrap();+ /// assert!(mesh.topology().is_none());+ ///+ /// // With topology flag+ /// let mesh = TriMesh::with_flags(+ /// vertices,+ /// indices,+ /// TriMeshFlags::HALF_EDGE_TOPOLOGY+ /// ).unwrap();+ /// assert!(mesh.topology().is_some());+ /// # }+ /// ```+ pub fn topology(&self) -> Option<&TriMeshTopology> {+ self.topology.as_ref()+ }++ /// Returns the connected-component information of this trimesh, if it has been computed.+ ///+ /// Connected components represent separate, non-connected parts of the mesh.+ /// This is computed when the [`TriMeshFlags::CONNECTED_COMPONENTS`] flag is set+ /// (requires the `std` feature).+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # #[cfg(feature = "std")] {+ /// use parry3d::shape::{TriMesh, TriMeshFlags};+ /// use parry3d::math::Vector;+ ///+ /// // Create two separate triangles (not connected)+ /// let vertices = vec![+ /// // First triangle+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// // Second triangle (separate)+ /// Vector::new(5.0, 0.0, 0.0),+ /// Vector::new(6.0, 0.0, 0.0),+ /// Vector::new(5.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![[0, 1, 2], [3, 4, 5]];+ ///+ /// let mesh = TriMesh::with_flags(+ /// vertices,+ /// indices,+ /// TriMeshFlags::CONNECTED_COMPONENTS+ /// ).unwrap();+ ///+ /// if let Some(cc) = mesh.connected_components() {+ /// assert_eq!(cc.num_connected_components(), 2);+ /// }+ /// # }+ /// # }+ /// ```+ pub fn connected_components(&self) -> Option<&TriMeshConnectedComponents> {+ self.connected_components.as_ref()+ }++ /// Returns the connected-component of this mesh.+ ///+ /// The connected-components are returned as a set of `TriMesh` build with the given `flags`.+ pub fn connected_component_meshes(+ &self,+ flags: TriMeshFlags,+ ) -> Option<Vec<Result<TriMesh, TriMeshBuilderError>>> {+ self.connected_components()+ .map(|cc| cc.to_meshes(self, flags))+ }++ /// The pseudo-normals of this triangle mesh, if they have been computed.+ #[cfg(feature = "dim3")]+ pub fn pseudo_normals(&self) -> Option<&TriMeshPseudoNormals> {+ self.pseudo_normals.as_ref()+ }++ /// The pseudo-normals of this triangle mesh, if they have been computed **and** this mesh was+ /// marked as [`TriMeshFlags::ORIENTED`].+ #[cfg(feature = "dim3")]+ pub fn pseudo_normals_if_oriented(&self) -> Option<&TriMeshPseudoNormals> {+ if self.flags.intersects(TriMeshFlags::ORIENTED) {+ self.pseudo_normals.as_ref()+ } else {+ None+ }+ }+}++#[cfg(feature = "dim3")]+impl From<crate::shape::HeightField> for TriMesh {+ fn from(heightfield: crate::shape::HeightField) -> Self {+ let (vtx, idx) = heightfield.to_trimesh();+ TriMesh::new(vtx, idx).unwrap()+ }+}++#[cfg(feature = "dim3")]+impl From<Cuboid> for TriMesh {+ fn from(cuboid: Cuboid) -> Self {+ let (vtx, idx) = cuboid.to_trimesh();+ TriMesh::new(vtx, idx).unwrap()+ }+}++impl CompositeShape for TriMesh {+ fn map_part_at(+ &self,+ i: u32,+ f: &mut dyn FnMut(Option<&Pose>, &dyn Shape, Option<&dyn NormalConstraints>),+ ) {+ let tri = self.triangle(i);+ let normals = self.triangle_normal_constraints(i);+ f(+ None,+ &tri,+ normals.as_ref().map(|n| n as &dyn NormalConstraints),+ )+ }++ fn bvh(&self) -> &Bvh {+ &self.bvh+ }++ fn is_deformable(&self) -> bool {+ self.flags.contains(TriMeshFlags::DEFORMABLE)+ }+}++impl TypedCompositeShape for TriMesh {+ type PartShape = Triangle;+ type PartNormalConstraints = TrianglePseudoNormals;++ #[inline(always)]+ fn map_typed_part_at<T>(+ &self,+ i: u32,+ mut f: impl FnMut(Option<&Pose>, &Self::PartShape, Option<&Self::PartNormalConstraints>) -> T,+ ) -> Option<T> {+ let tri = self.triangle(i);+ let pseudo_normals = self.triangle_normal_constraints(i);+ Some(f(None, &tri, pseudo_normals.as_ref()))+ }++ #[inline(always)]+ fn map_untyped_part_at<T>(+ &self,+ i: u32,+ mut f: impl FnMut(Option<&Pose>, &dyn Shape, Option<&dyn NormalConstraints>) -> T,+ ) -> Option<T> {+ let tri = self.triangle(i);+ let pseudo_normals = self.triangle_normal_constraints(i);+ Some(f(+ None,+ &tri,+ pseudo_normals.as_ref().map(|n| n as &dyn NormalConstraints),+ ))+ }+}++#[cfg(test)]+mod test {+ use crate::math::{Real, Vector};+ use crate::shape::{Cuboid, TriMesh, TriMeshFlags};++ #[test]+ fn trimesh_error_empty_indices() {+ assert!(+ TriMesh::with_flags(vec![], vec![], TriMeshFlags::empty()).is_err(),+ "A triangle mesh with no triangles is invalid."+ );+ }++ #[test]+ fn connected_components() {+ let (vtx, idx) = Cuboid::new(Vector::splat(0.5)).to_trimesh();++ // Push 10 copy of the mesh, each time pushed with an offset.+ let mut mesh = TriMesh::new(vtx.clone(), idx.clone()).unwrap();++ for i in 1..10 {+ let cc_vtx = vtx+ .iter()+ .map(|pt| *pt + Vector::splat(2.0 * i as Real))+ .collect();++ let to_append = TriMesh::new(cc_vtx, idx.clone()).unwrap();+ mesh.append(&to_append);+ }++ mesh.set_flags(TriMeshFlags::CONNECTED_COMPONENTS).unwrap();+ let connected_components = mesh.connected_components().unwrap();+ assert_eq!(connected_components.num_connected_components(), 10);++ let cc_meshes = connected_components.to_meshes(&mesh, TriMeshFlags::empty());++ for cc in cc_meshes {+ let cc = cc.unwrap();+ assert_eq!(cc.vertices.len(), vtx.len());+ assert_eq!(cc.indices.len(), idx.len());+ }+ }+}diff --git a/renderer/third_party/parry3d/src/shape/voxels/mod.rs b/renderer/third_party/parry3d/src/shape/voxels/mod.rsnew file mode 100644index 0000000..ea8b7c0--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/voxels/mod.rs@@ -0,0 +1,11 @@+pub use voxels::*;+pub use voxels_chunk::*;++use voxels_consts::*;++mod voxels;+mod voxels_chunk;+mod voxels_consts;+mod voxels_edition;+mod voxels_neighborhood;+mod voxels_sizeof;diff --git a/renderer/third_party/parry3d/src/shape/voxels/voxels.rs b/renderer/third_party/parry3d/src/shape/voxels/voxels.rsnew file mode 100644index 0000000..892b9f5--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/voxels/voxels.rs@@ -0,0 +1,1028 @@+use super::{+ VoxelIndex, EMPTY_FACE_MASK, FACES_TO_FEATURE_MASKS, FACES_TO_OCTANT_MASKS,+ FACES_TO_VOXEL_TYPES, INTERIOR_FACE_MASK,+};+use crate::bounding_volume::{Aabb, BoundingVolume};+#[cfg(not(feature = "std"))]+use crate::math::ComplexField;+use crate::math::{ivect_to_vect, vect_to_ivect, IVector, Int, Vector};+use crate::partitioning::{Bvh, BvhBuildStrategy, BvhNode};+use crate::shape::voxels::voxels_chunk::{VoxelsChunk, VoxelsChunkHeader};+use crate::shape::VoxelsChunkRef;+use crate::utils::hashmap::HashMap;+use alloc::{vec, vec::Vec};++/// Categorization of a voxel based on its neighbors.+///+/// This enum describes the local topology of a filled voxel by examining which of its+/// immediate neighbors (along coordinate axes) are also filled. This information is crucial+/// for collision detection to avoid the "internal edges problem" where objects can get+/// caught on edges between adjacent voxels.+///+/// # Type Classification+///+/// - **Empty**: The voxel is not filled.+/// - **Interior**: All axis-aligned neighbors are filled (safest for collision).+/// - **Face**: Missing neighbors in one coordinate direction (e.g., top face exposed).+/// - **Edge** (3D only): Missing neighbors in two coordinate directions (e.g., corner edge exposed).+/// - **Vertex**: Missing neighbors in all coordinate directions (isolated corner).+///+/// # Examples+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Voxels, VoxelType};+/// use parry3d::math::{Vector, IVector};+///+/// // Create a small 2x2x2 cube of voxels+/// let voxels = Voxels::new(+/// Vector::new(1.0, 1.0, 1.0),+/// &[+/// IVector::new(0, 0, 0),+/// IVector::new(1, 0, 0),+/// IVector::new(0, 1, 0),+/// IVector::new(1, 1, 0),+/// IVector::new(0, 0, 1),+/// IVector::new(1, 0, 1),+/// IVector::new(0, 1, 1),+/// IVector::new(1, 1, 1),+/// ],+/// );+///+/// // Check voxel type - interior voxels are fully surrounded+/// let state = voxels.voxel_state(IVector::new(0, 0, 0)).unwrap();+/// let voxel_type = state.voxel_type();+/// println!("Voxel type: {:?}", voxel_type);+/// # }+/// ```+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub enum VoxelType {+ /// The voxel is empty.+ Empty,+ /// The voxel is a vertex if all three coordinate axis directions have at+ /// least one empty neighbor.+ Vertex,+ /// The voxel is on an edge if it has non-empty neighbors in both directions of+ /// a single coordinate axis.+ #[cfg(feature = "dim3")]+ Edge,+ /// The voxel is on an edge if it has non-empty neighbors in both directions of+ /// two coordinate axes.+ Face,+ /// The voxel is on an edge if it has non-empty neighbors in both directions of+ /// all coordinate axes.+ Interior,+}++#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]+/// The status of the cell of an heightfield.+pub struct AxisMask(u8);++bitflags::bitflags! {+ /// Flags for identifying signed directions along coordinate axes, or faces of a voxel.+ impl AxisMask: u8 {+ /// The direction or face along the `+x` coordinate axis.+ const X_POS = 1 << 0;+ /// The direction or face along the `-x` coordinate axis.+ const X_NEG = 1 << 1;+ /// The direction or face along the `+y` coordinate axis.+ const Y_POS = 1 << 2;+ /// The direction or face along the `-y` coordinate axis.+ const Y_NEG = 1 << 3;+ /// The direction or face along the `+z` coordinate axis.+ #[cfg(feature= "dim3")]+ const Z_POS = 1 << 4;+ /// The direction or face along the `-z` coordinate axis.+ #[cfg(feature= "dim3")]+ const Z_NEG = 1 << 5;+ }+}++/// Indicates the local shape of a voxel on each octant.+///+/// This provides geometric information of the shape’s exposed features on each octant.+// This is an alternative to `FACES_TO_FEATURE_MASKS` that can be more convenient for some+// collision-detection algorithms.+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub struct OctantPattern;++// NOTE: it is important that the max value of any OctantPattern variant+// is 7 because we don’t allocate more than 3 bits to store it in+// `FACES_TO_OCTANT_MASKS`.+/// Indicates the local shape of a voxel on each octant.+///+/// This provides geometric information of the shape’s exposed features on each octant.+// This is an alternative to `FACES_TO_FEATURE_MASKS` that can be more convenient for some+// collision-detection algorithms.+#[cfg(feature = "dim3")]+impl OctantPattern {+ /// The voxel doesn't have any exposed feature on the octant with this mask.+ pub const INTERIOR: u32 = 0;+ /// The voxel has an exposed vertex on the octant with this mask.+ pub const VERTEX: u32 = 1;+ /// The voxel has an exposed edges with direction X on the octant with this mask.+ pub const EDGE_X: u32 = 2;+ /// The voxel has an exposed edges with direction Y on the octant with this mask.+ pub const EDGE_Y: u32 = 3;+ /// The voxel has an exposed edges with direction Z on the octant with this mask.+ pub const EDGE_Z: u32 = 4;+ /// The voxel has an exposed face with normal X on the octant with this mask.+ pub const FACE_X: u32 = 5;+ /// The voxel has an exposed face with normal Y on the octant with this mask.+ pub const FACE_Y: u32 = 6;+ /// The voxel has an exposed face with normal Z on the octant with this mask.+ pub const FACE_Z: u32 = 7;+}++// NOTE: it is important that the max value of any OctantPattern variant+// is 7 because we don’t allocate more than 3 bits to store it in+// `FACES_TO_OCTANT_MASKS`.+/// Indicates the local shape of a voxel on each octant.+///+/// This provides geometric information of the shape’s exposed features on each octant.+/// This is an alternative to `FACES_TO_FEATURE_MASKS` that can be more convenient for some+/// collision-detection algorithms.+#[cfg(feature = "dim2")]+impl OctantPattern {+ /// The voxel doesn't have any exposed feature on the octant with this mask.+ pub const INTERIOR: u32 = 0;+ /// The voxel has an exposed vertex on the octant with this mask.+ pub const VERTEX: u32 = 1;+ /// The voxel has an exposed face with normal X on the octant with this mask.+ pub const FACE_X: u32 = 2;+ /// The voxel has an exposed face with normal Y on the octant with this mask.+ pub const FACE_Y: u32 = 3;+}++// The local neighborhood information is encoded in a 8-bits number in groups of two bits+// per coordinate axis: `0bwwzzyyxx`. In each group of two bits, e.g. `xx`, the rightmost (resp.+// leftmost) bit set to 1 means that the neighbor voxel with coordinate `+1` (resp `-1`) relative+// to the current voxel along the `x` axis is filled. If the bit is 0, then the corresponding+// neighbor is empty. See the `AxisMask` bitflags.+// For example, in 2D, the mask `0b00_00_10_01` matches the following configuration (assuming +y goes+// up, and +x goes right):+//+// ```txt+// 0 0 0+// 0 x 1+// 0 1 0+// ```+//+// The special value `0b01000000` indicates that the voxel is empty.+// And the value `0b00111111` (`0b00001111` in 2D) indicates that the voxel is an interior voxel (its whole neighborhood+// is filled).+/// A description of the local neighborhood of a voxel.+///+/// This compact representation stores which immediate neighbors (along coordinate axes) of a+/// voxel are filled. This information is essential for proper collision detection between voxels+/// and other shapes, as it helps avoid the "internal edges problem."+///+/// The state is encoded as a single byte where each pair of bits represents one coordinate axis,+/// indicating whether neighbors in the positive and negative directions are filled.+///+/// # Special States+///+/// - [`VoxelState::EMPTY`]: The voxel itself is empty (not part of the shape).+/// - [`VoxelState::INTERIOR`]: All neighbors are filled (completely surrounded voxel).+///+/// # Examples+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::{Voxels, VoxelState, AxisMask};+/// use parry3d::math::{Vector, IVector};+///+/// // Create a simple voxel shape+/// let voxels = Voxels::new(+/// Vector::new(1.0, 1.0, 1.0),+/// &[IVector::new(0, 0, 0), IVector::new(1, 0, 0)],+/// );+///+/// // Query the state of a voxel+/// let state = voxels.voxel_state(IVector::new(0, 0, 0)).unwrap();+///+/// // Check if empty+/// assert!(!state.is_empty());+///+/// // Get which faces are exposed (not adjacent to other voxels)+/// let free_faces = state.free_faces();+/// if free_faces.contains(AxisMask::X_NEG) {+/// println!("The -X face is exposed");+/// }+///+/// // Get the voxel type based on neighborhood+/// println!("Voxel type: {:?}", state.voxel_type());+/// # }+/// ```+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+pub struct VoxelState(pub(super) u8);++impl VoxelState {+ /// The value of empty voxels.+ pub const EMPTY: VoxelState = VoxelState(EMPTY_FACE_MASK);+ /// The value of a voxel with non-empty neighbors in all directions.+ pub const INTERIOR: VoxelState = VoxelState(INTERIOR_FACE_MASK);++ pub(crate) const fn new(state: u8) -> Self {+ Self(state)+ }++ /// Is this voxel empty?+ pub const fn is_empty(self) -> bool {+ self.0 == EMPTY_FACE_MASK+ }++ /// A bit mask indicating which faces of the voxel don’t have any+ /// adjacent non-empty voxel.+ pub const fn free_faces(self) -> AxisMask {+ if self.0 == INTERIOR_FACE_MASK || self.0 == EMPTY_FACE_MASK {+ AxisMask::empty()+ } else {+ AxisMask::from_bits_truncate((!self.0) & INTERIOR_FACE_MASK)+ }+ }++ /// The [`VoxelType`] of this voxel.+ pub const fn voxel_type(self) -> VoxelType {+ FACES_TO_VOXEL_TYPES[self.0 as usize]+ }++ // Bitmask indicating what vertices, edges, or faces of the voxel are "free".+ pub(crate) const fn feature_mask(self) -> u16 {+ FACES_TO_FEATURE_MASKS[self.0 as usize]+ }++ pub(crate) const fn octant_mask(self) -> u32 {+ FACES_TO_OCTANT_MASKS[self.0 as usize]+ }+}++/// Information associated to a voxel.+///+/// This structure provides complete information about a single voxel including its position+/// in both grid coordinates and world space, as well as its state (empty/filled and neighborhood).+///+/// # Note+///+/// The `linear_id` field is an internal implementation detail that can become invalidated when+/// the voxel structure is modified (e.g., via [`Voxels::set_voxel`] or [`Voxels::crop`]).+/// For stable references to voxels, always use `grid_coords`.+///+/// # Examples+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Voxels;+/// use parry3d::math::{Vector, IVector};+///+/// let voxels = Voxels::new(+/// Vector::new(0.5, 0.5, 0.5),+/// &[IVector::new(0, 0, 0), IVector::new(1, 0, 0)],+/// );+///+/// // Iterate through all voxels+/// for voxel in voxels.voxels() {+/// if !voxel.state.is_empty() {+/// println!("Voxel at grid position {:?}", voxel.grid_coords);+/// println!(" World center: {:?}", voxel.center);+/// println!(" Type: {:?}", voxel.state.voxel_type());+/// }+/// }+/// # }+/// ```+#[derive(Copy, Clone, Debug, PartialEq)]+pub struct VoxelData {+ /// The temporary index in the internal voxels' storage.+ ///+ /// This index can be invalidated after a call to [`Voxels::set_voxel`], or+ /// [`Voxels::crop`].+ pub linear_id: VoxelIndex,+ /// The voxel's integer grid coordinates.+ pub grid_coords: IVector,+ /// The voxel's center position in the local-space of the [`Voxels`] shape it is part of.+ pub center: Vector,+ /// The voxel's state, indicating if it's empty or full.+ pub state: VoxelState,+}++/// A shape made of axis-aligned, uniformly sized cubes (aka. voxels).+///+/// # What are Voxels?+///+/// Voxels (volumetric pixels) are 3D cubes (or 2D squares) arranged on a regular grid. Think of+/// them as 3D building blocks, like LEGO bricks or Minecraft blocks. Each voxel has:+/// - A position on an integer grid (e.g., `(0, 0, 0)`, `(1, 2, 3)`)+/// - A uniform size (e.g., 1.0 × 1.0 × 1.0 meters)+/// - A state: filled (solid) or empty (air)+///+/// # When to Use Voxels?+///+/// Voxels are ideal for:+/// - **Minecraft-style worlds**: Block-based terrain and structures+/// - **Destructible environments**: Easy to add/remove individual blocks+/// - **Procedural generation**: Grid-based algorithms for caves, terrain, dungeons+/// - **Volumetric data**: Medical imaging, scientific simulations+/// - **Retro aesthetics**: Pixel art style in 3D+///+/// Voxels may NOT be ideal for:+/// - Smooth organic shapes (use meshes instead)+/// - Very large sparse worlds (consider octrees or chunk-based systems)+/// - Scenes requiring fine geometric detail at all scales+///+/// # The Internal Edges Problem+///+/// When an object slides across a flat surface made of voxels, it can snag on the edges between+/// adjacent voxels, causing jerky motion. Parry's `Voxels` shape solves this by tracking neighbor+/// relationships: it knows which voxel faces are internal (adjacent to another voxel) vs external+/// (exposed to air), allowing smooth collision response.+///+/// # Memory Efficiency+///+/// The internal storage uses sparse chunks, storing only one byte per voxel for neighborhood+/// information. Empty regions consume minimal memory. This is much more efficient than storing+/// a triangle mesh representation of all voxel surfaces.+///+/// # Examples+///+/// ## Basic Usage: Creating a Voxel Shape+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Voxels;+/// use parry3d::math::{Vector, IVector};+///+/// // Create a simple 3×3×3 cube of voxels+/// let voxel_size = Vector::new(1.0, 1.0, 1.0);+/// let mut coords = Vec::new();+/// for x in 0..3 {+/// for y in 0..3 {+/// for z in 0..3 {+/// coords.push(IVector::new(x, y, z));+/// }+/// }+/// }+///+/// let voxels = Voxels::new(voxel_size, &coords);+/// println!("Created voxel shape with {} voxels", coords.len());+/// # }+/// ```+///+/// ## Creating Voxels from World-Space Vectors+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Voxels;+/// use parry3d::math::Vector;+///+/// // Sample points in world space (e.g., from a point cloud)+/// let points = vec![+/// Vector::new(0.1, 0.2, 0.3),+/// Vector::new(1.5, 2.1, 3.7),+/// Vector::new(0.8, 0.9, 1.2),+/// ];+///+/// // Create voxels with 0.5 unit size - nearby points merge into same voxel+/// let voxels = Voxels::from_points(Vector::new(0.5, 0.5, 0.5), &points);+/// println!("Created voxel shape from {} points", points.len());+/// # }+/// ```+///+/// ## Querying Voxel State+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Voxels;+/// use parry3d::math::{Vector, IVector};+///+/// let voxels = Voxels::new(+/// Vector::new(1.0, 1.0, 1.0),+/// &[IVector::new(0, 0, 0), IVector::new(1, 0, 0)],+/// );+///+/// // Check if a specific grid position is filled+/// if let Some(state) = voxels.voxel_state(IVector::new(0, 0, 0)) {+/// println!("Voxel is filled!");+/// println!("Type: {:?}", state.voxel_type());+/// println!("Free faces: {:?}", state.free_faces());+/// } else {+/// println!("Voxel is empty or outside the domain");+/// }+///+/// // Convert world-space point to grid coordinates+/// let world_point = Vector::new(1.3, 0.7, 0.2);+/// let grid_coord = voxels.voxel_at_point(world_point);+/// println!("Vector at {:?} is in voxel {:?}", world_point, grid_coord);+/// # }+/// ```+///+/// ## Iterating Through Voxels+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Voxels;+/// use parry3d::math::{Vector, IVector};+///+/// let voxels = Voxels::new(+/// Vector::new(0.5, 0.5, 0.5),+/// &[IVector::new(0, 0, 0), IVector::new(1, 0, 0), IVector::new(0, 1, 0)],+/// );+///+/// // Iterate through all non-empty voxels+/// for voxel in voxels.voxels() {+/// if !voxel.state.is_empty() {+/// println!("Voxel at grid {:?}, world center {:?}",+/// voxel.grid_coords, voxel.center);+/// }+/// }+/// # }+/// ```+///+/// ## Modifying Voxels Dynamically+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Voxels;+/// use parry3d::math::{Vector, IVector};+///+/// let mut voxels = Voxels::new(+/// Vector::new(1.0, 1.0, 1.0),+/// &[IVector::new(0, 0, 0)],+/// );+///+/// // Add a new voxel+/// voxels.set_voxel(IVector::new(1, 0, 0), true);+///+/// // Remove a voxel+/// voxels.set_voxel(IVector::new(0, 0, 0), false);+///+/// // Check the result+/// assert!(voxels.voxel_state(IVector::new(0, 0, 0)).unwrap().is_empty());+/// assert!(!voxels.voxel_state(IVector::new(1, 0, 0)).unwrap().is_empty());+/// # }+/// ```+///+/// ## Spatial Queries+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Voxels;+/// use parry3d::bounding_volume::Aabb;+/// use parry3d::math::{Vector, IVector};+///+/// let voxels = Voxels::new(+/// Vector::new(1.0, 1.0, 1.0),+/// &[IVector::new(0, 0, 0), IVector::new(1, 0, 0), IVector::new(2, 0, 0)],+/// );+///+/// // Find voxels intersecting an AABB+/// let query_aabb = Aabb::new(Vector::new(-0.5, -0.5, -0.5), Vector::new(1.5, 1.5, 1.5));+/// let count = voxels.voxels_intersecting_local_aabb(&query_aabb)+/// .filter(|v| !v.state.is_empty())+/// .count();+/// println!("Found {} voxels in AABB", count);+///+/// // Get the overall domain bounds+/// let [mins, maxs] = voxels.domain();+/// println!("Voxel grid spans from {:?} to {:?}", mins, maxs);+/// # }+/// ```+///+/// # See Also+///+/// - [`VoxelState`]: Information about a voxel's neighbors+/// - [`VoxelType`]: Classification of voxels by their topology+/// - [`VoxelData`]: Complete information about a single voxel+/// - [`crate::transformation::voxelization`]: Convert meshes to voxels+#[derive(Clone, Debug)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+pub struct Voxels {+ /// A BVH of chunk keys.+ ///+ /// The bounding boxes are the ones of the chunk’s voxels **keys**. This is equivalent to a bvh+ /// of the chunks with a uniform voxel size of 1.+ pub(super) chunk_bvh: Bvh,+ pub(super) chunk_headers: HashMap<IVector, VoxelsChunkHeader>,+ pub(super) chunk_keys: Vec<IVector>,+ pub(super) chunks: Vec<VoxelsChunk>,+ pub(super) free_chunks: Vec<usize>,+ pub(super) voxel_size: Vector,+}++impl Voxels {+ /// Initializes a voxel shape from grid coordinates.+ ///+ /// This is the primary constructor for creating a `Voxels` shape. You provide:+ /// - `voxel_size`: The physical dimensions of each voxel (e.g., `1.0 × 1.0 × 1.0` meters)+ /// - `grid_coordinates`: Integer grid positions for each filled voxel+ ///+ /// # Coordinate System+ ///+ /// Each voxel with grid coordinates `(x, y, z)` will be positioned such that:+ /// - Its minimum corner (bottom-left-back) is at `(x, y, z) * voxel_size`+ /// - Its center is at `((x, y, z) + 0.5) * voxel_size`+ /// - Its maximum corner is at `((x, y, z) + 1) * voxel_size`+ ///+ /// For example, with `voxel_size = 2.0` and grid coord `(1, 0, 0)`:+ /// - Minimum corner: `(2.0, 0.0, 0.0)`+ /// - Center: `(3.0, 1.0, 1.0)`+ /// - Maximum corner: `(4.0, 2.0, 2.0)`+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// // Create a 2×2×2 cube of voxels with 1.0 unit size+ /// let voxels = Voxels::new(+ /// Vector::new(1.0, 1.0, 1.0),+ /// &[+ /// IVector::new(0, 0, 0), IVector::new(1, 0, 0),+ /// IVector::new(0, 1, 0), IVector::new(1, 1, 0),+ /// IVector::new(0, 0, 1), IVector::new(1, 0, 1),+ /// IVector::new(0, 1, 1), IVector::new(1, 1, 1),+ /// ],+ /// );+ ///+ /// // Verify the first voxel's center position+ /// let center = voxels.voxel_center(IVector::new(0, 0, 0));+ /// assert_eq!(center, Vector::new(0.5, 0.5, 0.5));+ /// # }+ /// ```+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// // Create a line of voxels along the X axis+ /// let voxels = Voxels::new(+ /// Vector::new(0.5, 0.5, 0.5),+ /// &[IVector::new(0, 0, 0), IVector::new(1, 0, 0), IVector::new(2, 0, 0)],+ /// );+ ///+ /// // Query the domain (bounding grid coordinates)+ /// // Note: domain is aligned to internal chunk boundaries for efficiency+ /// let [mins, maxs] = voxels.domain();+ /// assert_eq!(mins, IVector::new(0, 0, 0));+ /// // maxs will be chunk-aligned (chunks are 8x8x8), so it includes more space+ /// assert!(maxs.x >= 3 && maxs.y >= 1 && maxs.z >= 1);+ /// # }+ /// ```+ pub fn new(voxel_size: Vector, grid_coordinates: &[IVector]) -> Self {+ let mut result = Self {+ chunk_bvh: Bvh::new(),+ chunk_headers: HashMap::default(),+ chunk_keys: vec![],+ chunks: vec![],+ free_chunks: vec![],+ voxel_size,+ };++ for vox in grid_coordinates {+ let (chunk_key, id_in_chunk) = Self::chunk_key_and_id_in_chunk(*vox);+ let chunk_header = result.chunk_headers.entry(chunk_key).or_insert_with(|| {+ let id = result.chunks.len();+ result.chunks.push(VoxelsChunk::default());+ result.chunk_keys.push(chunk_key);+ VoxelsChunkHeader { id, len: 0 }+ });+ chunk_header.len += 1;+ result.chunks[chunk_header.id].states[id_in_chunk] = VoxelState::INTERIOR;+ }++ result.chunk_bvh = Bvh::from_iter(+ BvhBuildStrategy::Ploc,+ result.chunk_headers.iter().map(|(chunk_key, chunk_id)| {+ (chunk_id.id, VoxelsChunk::aabb(chunk_key, result.voxel_size))+ }),+ );++ result.recompute_all_voxels_states();+ result+ }++ /// Computes a voxel shape from a set of world-space points.+ ///+ /// This constructor converts continuous world-space coordinates into discrete grid coordinates+ /// by snapping each point to the voxel grid. Multiple points can map to the same voxel.+ ///+ /// # How it Works+ ///+ /// Each point is converted to grid coordinates by:+ /// 1. Dividing the point's coordinates by `voxel_size`+ /// 2. Taking the floor to get integer grid coordinates+ /// 3. Removing duplicates (multiple points in the same voxel become one voxel)+ ///+ /// For example, with `voxel_size = 1.0`:+ /// - Vector `(0.3, 0.7, 0.9)` → Grid `(0, 0, 0)`+ /// - Vector `(1.1, 0.2, 0.5)` → Grid `(1, 0, 0)`+ /// - Vector `(0.9, 0.1, 0.8)` → Grid `(0, 0, 0)` (merges with first)+ ///+ /// # Use Cases+ ///+ /// - Converting point clouds into voxel representations+ /// - Creating voxel shapes from scattered data+ /// - Simplifying complex point sets into uniform grids+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::Vector;+ ///+ /// // Sample points in world space+ /// let points = vec![+ /// Vector::new(0.1, 0.2, 0.3), // → Grid (0, 0, 0)+ /// Vector::new(0.7, 0.8, 0.9), // → Grid (0, 0, 0) - same voxel!+ /// Vector::new(1.2, 0.3, 0.1), // → Grid (1, 0, 0)+ /// Vector::new(0.5, 1.5, 0.2), // → Grid (0, 1, 0)+ /// ];+ ///+ /// // Create voxels with 1.0 unit size+ /// let voxels = Voxels::from_points(Vector::new(1.0, 1.0, 1.0), &points);+ ///+ /// // Only 3 unique voxels created (first two points merged)+ /// let filled_count = voxels.voxels()+ /// .filter(|v| !v.state.is_empty())+ /// .count();+ /// assert_eq!(filled_count, 3);+ /// # }+ /// ```+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// // Higher resolution voxelization+ /// let points = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 1.0, 1.0),+ /// ];+ ///+ /// // Smaller voxels = finer detail+ /// let voxels = Voxels::from_points(Vector::new(0.5, 0.5, 0.5), &points);+ ///+ /// // First point at grid (0,0,0), second at grid (2,2,2) due to smaller voxel size+ /// assert!(voxels.voxel_state(IVector::new(0, 0, 0)).is_some());+ /// assert!(voxels.voxel_state(IVector::new(2, 2, 2)).is_some());+ /// # }+ /// ```+ pub fn from_points(voxel_size: Vector, points: &[Vector]) -> Self {+ let voxels: Vec<_> = points+ .iter()+ .map(|pt| vect_to_ivect((*pt / voxel_size).floor()))+ .collect();+ Self::new(voxel_size, &voxels)+ }++ pub(crate) fn chunk_bvh(&self) -> &Bvh {+ &self.chunk_bvh+ }++ /// The semi-open range of grid coordinates covered by this voxel shape.+ ///+ /// Returns `[mins, maxs]` where the domain is the semi-open interval `[mins, maxs)`,+ /// meaning `mins` is included but `maxs` is excluded. This provides conservative bounds+ /// on the range of voxel grid coordinates that might be filled.+ ///+ /// This is useful for:+ /// - Determining the spatial extent of the voxel shape+ /// - Pre-allocating storage for processing voxels+ /// - Clipping operations to valid regions+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// let voxels = Voxels::new(+ /// Vector::new(1.0, 1.0, 1.0),+ /// &[IVector::new(0, 0, 0), IVector::new(2, 3, 1)],+ /// );+ ///+ /// let [mins, maxs] = voxels.domain();+ /// assert_eq!(mins, IVector::new(0, 0, 0));+ /// // Domain is conservative and chunk-aligned+ /// assert!(maxs.x > 2 && maxs.y > 3 && maxs.z > 1);+ ///+ /// // Iterate through filled voxels (more efficient than iterating domain)+ /// for voxel in voxels.voxels() {+ /// if !voxel.state.is_empty() {+ /// println!("Filled voxel at {:?}", voxel.grid_coords);+ /// }+ /// }+ /// # }+ /// ```+ pub fn domain(&self) -> [IVector; 2] {+ let aabb = self.chunk_bvh.root_aabb();++ // NOTE that we shift the AABB's bounds so the endpoint matches a voxel center+ // to avoid rounding errors.+ let half_sz = self.voxel_size() / 2.0;+ let mins = self.voxel_at_point(aabb.mins + half_sz);+ // + 1 because the range is semi-open.+ let maxs = self.voxel_at_point(aabb.maxs - half_sz);+ let one = IVector::splat(1);+ [mins, maxs + one]+ }++ // /// The number of voxels along each coordinate axis.+ // pub fn dimensions(&self) -> Vector<u32> {+ // (self.domain_maxs - self.domain_mins).map(|e| e as u32)+ // }++ /// The size of each voxel part this [`Voxels`] shape.+ pub fn voxel_size(&self) -> Vector {+ self.voxel_size+ }++ /// Scale this shape.+ pub fn scaled(mut self, scale: Vector) -> Self {+ self.voxel_size *= scale;+ self.chunk_bvh.scale(scale);+ self+ }++ /// A reference to the chunk with id `chunk_id`.+ ///+ /// Panics if the chunk doesn’t exist.+ pub fn chunk_ref(&self, chunk_id: u32) -> VoxelsChunkRef<'_> {+ VoxelsChunkRef {+ my_id: chunk_id as usize,+ parent: self,+ states: &self.chunks[chunk_id as usize].states,+ key: &self.chunk_keys[chunk_id as usize],+ }+ }++ /// The AABB of the voxel with the given quantized `key`.+ pub fn voxel_aabb(&self, key: IVector) -> Aabb {+ let center = self.voxel_center(key);+ let hext = self.voxel_size / 2.0;+ Aabb::from_half_extents(center, hext)+ }++ /// Returns the state of the voxel at the given grid coordinates.+ ///+ /// Returns `None` if the voxel doesn't exist in this shape's internal storage,+ /// or `Some(VoxelState)` containing information about whether the voxel is filled+ /// and which of its neighbors are also filled.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// let voxels = Voxels::new(+ /// Vector::new(1.0, 1.0, 1.0),+ /// &[IVector::new(0, 0, 0), IVector::new(1, 0, 0)],+ /// );+ ///+ /// // Query an existing voxel+ /// if let Some(state) = voxels.voxel_state(IVector::new(0, 0, 0)) {+ /// assert!(!state.is_empty());+ /// println!("Voxel type: {:?}", state.voxel_type());+ /// }+ ///+ /// // Query a non-existent voxel+ /// assert!(voxels.voxel_state(IVector::new(10, 10, 10)).is_none());+ /// # }+ /// ```+ pub fn voxel_state(&self, key: IVector) -> Option<VoxelState> {+ let vid = self.linear_index(key)?;+ Some(self.chunks[vid.chunk_id].states[vid.id_in_chunk])+ }++ /// Calculates the grid coordinates of the voxel containing the given world-space point.+ ///+ /// This conversion is independent of whether the voxel is actually filled or empty - it+ /// simply determines which grid cell the point falls into based on the voxel size.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// let voxels = Voxels::new(+ /// Vector::new(1.0, 1.0, 1.0),+ /// &[IVector::new(0, 0, 0)],+ /// );+ ///+ /// // Vector in first voxel (center at 0.5, 0.5, 0.5)+ /// assert_eq!(voxels.voxel_at_point(Vector::new(0.3, 0.7, 0.2)), IVector::new(0, 0, 0));+ ///+ /// // Vector just inside second voxel boundary+ /// assert_eq!(voxels.voxel_at_point(Vector::new(1.0, 0.0, 0.0)), IVector::new(1, 0, 0));+ ///+ /// // Negative coordinates work too+ /// assert_eq!(voxels.voxel_at_point(Vector::new(-0.5, -0.5, -0.5)), IVector::new(-1, -1, -1));+ /// # }+ /// ```+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// // With non-uniform voxel size+ /// let voxels = Voxels::new(+ /// Vector::new(2.0, 0.5, 1.0),+ /// &[],+ /// );+ ///+ /// // X coordinate divided by 2.0, Y by 0.5, Z by 1.0+ /// assert_eq!(voxels.voxel_at_point(Vector::new(3.0, 1.2, 0.8)), IVector::new(1, 2, 0));+ /// # }+ /// ```+ pub fn voxel_at_point(&self, point: Vector) -> IVector {+ vect_to_ivect((point / self.voxel_size).floor())+ }++ /// Gets the voxel at the given flat voxel index.+ pub fn voxel_at_flat_id(&self, id: u32) -> Option<IVector> {+ let vid = VoxelIndex::from_flat_id(id as usize);+ let chunk_key = self.chunk_keys.get(vid.chunk_id)?;+ if *chunk_key == VoxelsChunk::INVALID_CHUNK_KEY {+ return None;+ }++ Some(VoxelsChunk::voxel_key_at_id(+ *chunk_key,+ vid.id_in_chunk as u32,+ ))+ }++ /// The range of grid coordinates of voxels intersecting the given AABB.+ ///+ /// The returned range covers both empty and non-empty voxels, and is not limited to the+ /// bounds defined by [`Self::domain`].+ /// The range is semi, open, i.e., the range along each dimension `i` is understood as+ /// the semi-open interval: `range[0][i]..range[1][i]`.+ pub fn voxel_range_intersecting_local_aabb(&self, aabb: &Aabb) -> [IVector; 2] {+ let mins = vect_to_ivect((aabb.mins / self.voxel_size).floor());+ let maxs = vect_to_ivect((aabb.maxs / self.voxel_size).ceil());+ [mins, maxs]+ }++ /// The AABB of a given range of voxels.+ ///+ /// The AABB is computed independently of [`Self::domain`] and independently of whether+ /// the voxels contained within are empty or not.+ pub fn voxel_range_aabb(&self, mins: IVector, maxs: IVector) -> Aabb {+ Aabb {+ mins: ivect_to_vect(mins) * self.voxel_size,+ maxs: ivect_to_vect(maxs) * self.voxel_size,+ }+ }++ /// Aligns the given AABB with the voxelized grid.+ ///+ /// The aligned is calculated such that the returned AABB has corners lying at the grid+ /// intersections (i.e. matches voxel corners) and fully contains the input `aabb`.+ pub fn align_aabb_to_grid(&self, aabb: &Aabb) -> Aabb {+ let mins = (aabb.mins / self.voxel_size).floor() * self.voxel_size;+ let maxs = (aabb.maxs / self.voxel_size).ceil() * self.voxel_size;+ Aabb { mins, maxs }+ }++ /// Iterates through every voxel intersecting the given aabb.+ ///+ /// Returns the voxel’s linearized id, center, and state.+ pub fn voxels_intersecting_local_aabb(+ &self,+ aabb: &Aabb,+ ) -> impl Iterator<Item = VoxelData> + '_ {+ let [mins, maxs] = self.voxel_range_intersecting_local_aabb(aabb);+ self.voxels_in_range(mins, maxs)+ }++ /// The center point of all the non-empty voxels in this shape.+ ///+ /// The voxel data associated to each center is provided to determine what kind of voxel+ /// it is (in particular, its [`VoxelState`] indicating which of its faces are free).+ pub fn voxels(&self) -> impl Iterator<Item = VoxelData> + '_ {+ let aabb = self.chunk_bvh.root_aabb();+ self.voxels_in_range(+ self.voxel_at_point(aabb.mins),+ self.voxel_at_point(aabb.maxs),+ )+ }++ /// Iterate through the data of all the voxels within the given (semi-open) voxel grid indices.+ ///+ /// Note that this only yields non-empty voxels within the range. This does not+ /// include any voxel that falls outside [`Self::domain`].+ pub fn voxels_in_range(+ &self,+ mins: IVector,+ maxs: IVector,+ ) -> impl Iterator<Item = VoxelData> + '_ {+ let range_aabb = Aabb::new(self.voxel_center(mins), self.voxel_center(maxs));++ self.chunk_bvh+ .leaves(move |node: &BvhNode| node.aabb().intersects(&range_aabb))+ .flat_map(move |chunk_id| {+ let chunk = self.chunk_ref(chunk_id);+ chunk.voxels_in_range(mins, maxs)+ })+ }++ fn voxel_to_chunk_key(voxel_key: IVector) -> IVector {+ fn div_floor(a: Int, b: usize) -> Int {+ let sign = (a < 0) as Int;+ (a + sign) / b as Int - sign+ }++ #[cfg(feature = "dim2")]+ {+ IVector::new(+ div_floor(voxel_key.x, VoxelsChunk::VOXELS_PER_CHUNK_DIM),+ div_floor(voxel_key.y, VoxelsChunk::VOXELS_PER_CHUNK_DIM),+ )+ }+ #[cfg(feature = "dim3")]+ {+ IVector::new(+ div_floor(voxel_key.x, VoxelsChunk::VOXELS_PER_CHUNK_DIM),+ div_floor(voxel_key.y, VoxelsChunk::VOXELS_PER_CHUNK_DIM),+ div_floor(voxel_key.z, VoxelsChunk::VOXELS_PER_CHUNK_DIM),+ )+ }+ }++ /// Given a voxel key, returns the key of the voxel chunk that contains it, as well as the+ /// linear index of the voxel within that chunk.+ #[cfg(feature = "dim2")]+ pub(super) fn chunk_key_and_id_in_chunk(voxel_key: IVector) -> (IVector, usize) {+ let chunk_key = Self::voxel_to_chunk_key(voxel_key);+ // NOTE: always positive since we subtracted the smallest possible key on that chunk.+ let voxel_key_in_chunk = voxel_key - chunk_key * VoxelsChunk::VOXELS_PER_CHUNK_DIM as Int;+ let id_in_chunk = (voxel_key_in_chunk.x+ + voxel_key_in_chunk.y * VoxelsChunk::VOXELS_PER_CHUNK_DIM as Int)+ as usize;+ (chunk_key, id_in_chunk)+ }++ /// Given a voxel key, returns the key of the voxel chunk that contains it, as well as the+ /// linear index of the voxel within that chunk.+ #[cfg(feature = "dim3")]+ pub(super) fn chunk_key_and_id_in_chunk(voxel_key: IVector) -> (IVector, usize) {+ let chunk_key = Self::voxel_to_chunk_key(voxel_key);+ // NOTE: always positive since we subtracted the smallest possible key on that chunk.+ let voxel_key_in_chunk = voxel_key - chunk_key * VoxelsChunk::VOXELS_PER_CHUNK_DIM as Int;+ let id_in_chunk = (voxel_key_in_chunk.x+ + voxel_key_in_chunk.y * VoxelsChunk::VOXELS_PER_CHUNK_DIM as Int+ + voxel_key_in_chunk.z+ * VoxelsChunk::VOXELS_PER_CHUNK_DIM as Int+ * VoxelsChunk::VOXELS_PER_CHUNK_DIM as Int) as usize;+ (chunk_key, id_in_chunk)+ }++ /// The linearized index associated to the given voxel key.+ pub fn linear_index(&self, voxel_key: IVector) -> Option<VoxelIndex> {+ let (chunk_key, id_in_chunk) = Self::chunk_key_and_id_in_chunk(voxel_key);+ let chunk_id = self.chunk_headers.get(&chunk_key)?.id;+ Some(VoxelIndex {+ chunk_id,+ id_in_chunk,+ })+ }++ /// The world-space center position of the voxel with the given grid coordinates.+ ///+ /// Returns the center point regardless of whether the voxel is actually filled.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// let voxels = Voxels::new(+ /// Vector::new(1.0, 1.0, 1.0),+ /// &[IVector::new(0, 0, 0)],+ /// );+ ///+ /// // Center of voxel at origin+ /// assert_eq!(voxels.voxel_center(IVector::new(0, 0, 0)), Vector::new(0.5, 0.5, 0.5));+ ///+ /// // Center of voxel at (1, 2, 3)+ /// assert_eq!(voxels.voxel_center(IVector::new(1, 2, 3)), Vector::new(1.5, 2.5, 3.5));+ /// # }+ /// ```+ pub fn voxel_center(&self, key: IVector) -> Vector {+ (ivect_to_vect(key) + Vector::splat(0.5)) * self.voxel_size+ }+}diff --git a/renderer/third_party/parry3d/src/shape/voxels/voxels_chunk.rs b/renderer/third_party/parry3d/src/shape/voxels/voxels_chunk.rsnew file mode 100644index 0000000..47603f0--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/voxels/voxels_chunk.rs@@ -0,0 +1,315 @@+use crate::bounding_volume::Aabb;+use crate::math::{ivect_to_vect, IVector, Int, Real, Vector};+use crate::shape::{VoxelData, VoxelState, Voxels};++#[derive(Clone, Debug)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+pub(super) struct VoxelsChunkHeader {+ pub(super) id: usize,+ // The number of non-empty voxels in the chunk.+ // This is used for detecting when a chunk can be removed+ // if it becomes fully empty.+ pub(super) len: usize,+}++#[derive(Clone, Debug)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[repr(C)]+#[repr(align(64))]+pub(super) struct VoxelsChunk {+ #[cfg_attr(feature = "serde-serialize", serde(with = "serde_arrays"))]+ pub(super) states: [VoxelState; VoxelsChunk::VOXELS_PER_CHUNK],+}++impl Default for VoxelsChunk {+ fn default() -> Self {+ Self {+ states: [VoxelState::EMPTY; VoxelsChunk::VOXELS_PER_CHUNK],+ }+ }+}++#[derive(Copy, Clone, Debug, PartialEq)]+pub struct VoxelIndex {+ pub(super) chunk_id: usize,+ pub(super) id_in_chunk: usize,+}++impl VoxelIndex {+ pub fn flat_id(&self) -> usize {+ self.chunk_id * VoxelsChunk::VOXELS_PER_CHUNK + self.id_in_chunk+ }++ pub fn from_flat_id(id: usize) -> Self {+ Self {+ chunk_id: id / VoxelsChunk::VOXELS_PER_CHUNK,+ id_in_chunk: id % VoxelsChunk::VOXELS_PER_CHUNK,+ }+ }+}++impl VoxelsChunk {+ // TODO: find the ideal number. We want a good balance between cache locality+ // and number of BVH leaf nodes.+ #[cfg(feature = "dim2")]+ pub(super) const VOXELS_PER_CHUNK_DIM: usize = 16;+ #[cfg(feature = "dim3")]+ pub(super) const VOXELS_PER_CHUNK_DIM: usize = 8;+ #[cfg(feature = "dim2")]+ pub(super) const VOXELS_PER_CHUNK: usize =+ Self::VOXELS_PER_CHUNK_DIM * Self::VOXELS_PER_CHUNK_DIM;+ #[cfg(feature = "dim3")]+ pub(super) const VOXELS_PER_CHUNK: usize =+ Self::VOXELS_PER_CHUNK_DIM * Self::VOXELS_PER_CHUNK_DIM * Self::VOXELS_PER_CHUNK_DIM;++ #[cfg(feature = "dim2")]+ pub(super) const INVALID_CHUNK_KEY: IVector = IVector::new(Int::MAX, Int::MAX);+ #[cfg(feature = "dim3")]+ pub(super) const INVALID_CHUNK_KEY: IVector = IVector::new(Int::MAX, Int::MAX, Int::MAX);++ /// The key of the voxel at the given linearized index within this chunk.+ #[cfg(feature = "dim2")]+ pub(super) fn voxel_key_at_id(chunk_key: IVector, id_in_chunk: u32) -> IVector {+ let y = id_in_chunk as Int / Self::VOXELS_PER_CHUNK_DIM as Int;+ let x = id_in_chunk as Int % Self::VOXELS_PER_CHUNK_DIM as Int;+ chunk_key * (Self::VOXELS_PER_CHUNK_DIM as Int) + IVector::new(x, y)+ }++ /// The key of the voxel at the given linearized index.+ #[cfg(feature = "dim3")]+ pub(super) fn voxel_key_at_id(chunk_key: IVector, id_in_chunk: u32) -> IVector {+ let d0d1 = (Self::VOXELS_PER_CHUNK_DIM * Self::VOXELS_PER_CHUNK_DIM) as u32;+ let z = id_in_chunk / d0d1;+ let y = (id_in_chunk - z * d0d1) / Self::VOXELS_PER_CHUNK_DIM as u32;+ let x = id_in_chunk % Self::VOXELS_PER_CHUNK_DIM as u32;+ chunk_key * (Self::VOXELS_PER_CHUNK_DIM as Int) + IVector::new(x as Int, y as Int, z as Int)+ }++ /// The semi-open range of valid voxel keys for this chunk.+ pub(super) fn keys_bounds(chunk_key: &IVector) -> [IVector; 2] {+ let imins = chunk_key * Self::VOXELS_PER_CHUNK_DIM as Int;+ let imaxs = imins + IVector::splat(Self::VOXELS_PER_CHUNK_DIM as Int);+ [imins, imaxs]+ }++ pub(super) fn aabb(chunk_key: &IVector, voxel_size: Vector) -> Aabb {+ let [imins, imaxs] = Self::keys_bounds(chunk_key);+ let aabb = Aabb::new(ivect_to_vect(imins), ivect_to_vect(imaxs));+ Aabb::new(aabb.mins * voxel_size, aabb.maxs * voxel_size)+ }+}++/// A reference to a chunk of voxels within a [`Voxels`] shape.+///+/// # What is a Chunk?+///+/// To efficiently manage large voxel worlds, Parry internally divides the voxel grid into+/// fixed-size chunks. Each chunk contains a small region of voxels (e.g., 8×8×8 in 3D or+/// 16×16 in 2D). This chunking provides:+///+/// - **Spatial acceleration**: Quick queries using a BVH of chunks+/// - **Memory efficiency**: Empty chunks are not stored+/// - **Cache locality**: Nearby voxels are stored together+///+/// A `VoxelsChunkRef` provides read-only access to a single chunk's data, allowing you to+/// query voxels within that chunk without iterating through the entire voxel shape.+///+/// # When to Use+///+/// You typically don't create `VoxelsChunkRef` directly. Instead, you get them from:+/// - [`Voxels::chunk_ref`]: Get a specific chunk by ID+/// - BVH traversal for spatial queries on large voxel worlds+///+/// # Examples+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::shape::Voxels;+/// use parry3d::math::{Vector, IVector};+///+/// let voxels = Voxels::new(+/// Vector::new(1.0, 1.0, 1.0),+/// &[IVector::new(0, 0, 0), IVector::new(1, 0, 0)],+/// );+///+/// // Get a chunk reference (chunk IDs come from BVH traversal)+/// let chunk_ref = voxels.chunk_ref(0);+///+/// // Query voxels within this chunk+/// for voxel in chunk_ref.voxels() {+/// if !voxel.state.is_empty() {+/// println!("Voxel at {:?}", voxel.grid_coords);+/// }+/// }+///+/// // Get chunk's AABB+/// let aabb = chunk_ref.local_aabb();+/// println!("Chunk bounds: {:?}", aabb);+/// # }+/// ```+#[derive(Copy, Clone)]+pub struct VoxelsChunkRef<'a> {+ /// The linear index of this chunk within the `Voxels` shape.+ pub my_id: usize,+ /// The voxel shape this chunk is part of.+ pub parent: &'a Voxels,+ /// The fill status of each voxel from this chunk.+ pub states: &'a [VoxelState; VoxelsChunk::VOXELS_PER_CHUNK],+ /// The spatial index of this chunk.+ pub key: &'a IVector,+}++impl<'a> VoxelsChunkRef<'a> {+ /// The AABB of this chunk of voxels.+ ///+ /// Note that this return the AABB of the whole chunk, without taking into account the fact+ /// that some voxels are empty.+ pub fn local_aabb(&self) -> Aabb {+ VoxelsChunk::aabb(self.key, self.parent.voxel_size)+ }++ /// The domain of this chunk of voxels.+ pub fn domain(&self) -> [IVector; 2] {+ VoxelsChunk::keys_bounds(self.key)+ }++ /// Returns the spatial index of the voxel containing the given point.+ pub fn voxel_at_point_unchecked(&self, pt: Vector) -> IVector {+ self.parent.voxel_at_point(pt)+ }++ /// The state of the voxel with key `voxel_key`.+ pub fn voxel_state(&self, voxel_key: IVector) -> Option<VoxelState> {+ let (chunk_key, id_in_chunk) = Voxels::chunk_key_and_id_in_chunk(voxel_key);+ if &chunk_key != self.key {+ return None;+ }+ Some(self.states[id_in_chunk])+ }++ /// Clamps the `voxel_key` so it is within the bounds of `self`.+ pub fn clamp_voxel(&self, voxel_key: IVector) -> IVector {+ let [mins, maxs] = self.domain();+ voxel_key.clamp(mins, maxs)+ }++ /// The AABB of the voxel with this key.+ ///+ /// Returns a result even if the voxel doesn’t belong to this chunk.+ pub fn voxel_aabb_unchecked(&self, voxel_key: IVector) -> Aabb {+ self.parent.voxel_aabb(voxel_key)+ }++ /// Convert a voxel index (expressed relative to the main `Voxels` shape, not relative to the+ /// chunk alone) into a flat index within a voxel chunk.+ ///+ /// Returns `None` if the voxel isn’t part of this chunk.+ pub fn flat_id(&self, voxel_key: IVector) -> Option<u32> {+ let (chunk_key, id_in_chunk) = Voxels::chunk_key_and_id_in_chunk(voxel_key);+ if &chunk_key != self.key {+ return None;+ }++ Some(+ VoxelIndex {+ chunk_id: self.my_id,+ id_in_chunk,+ }+ .flat_id() as u32,+ )+ }++ /// Iterates through all the voxels in this chunk.+ ///+ /// Note that this only yields non-empty voxels within the range. This does not+ /// include any voxel that falls outside [`Self::domain`].+ pub fn voxels(&self) -> impl Iterator<Item = VoxelData> + '_ {+ let range = self.domain();+ self.voxels_in_range(range[0], range[1])+ }++ /// Iterate through the data of all the voxels within the given (semi-open) voxel grid indices.+ ///+ /// Note that this only yields non-empty voxels within the range. This does not+ /// include any voxel that falls outside [`Self::domain`].+ #[cfg(feature = "dim2")]+ pub fn voxels_in_range(+ self,+ mins: IVector,+ maxs: IVector,+ ) -> impl Iterator<Item = VoxelData> + use<'a> {+ let [chunk_mins, chunk_maxs] = VoxelsChunk::keys_bounds(self.key);+ let mins = mins.max(chunk_mins);+ let maxs = maxs.min(chunk_maxs);++ (mins.x..maxs.x).flat_map(move |ix| {+ (mins.y..maxs.y).flat_map(move |iy| {+ let id_in_chunk = (ix - chunk_mins.x) as usize+ + (iy - chunk_mins.y) as usize * VoxelsChunk::VOXELS_PER_CHUNK_DIM;+ let state = self.states[id_in_chunk];++ if state.is_empty() {+ return None;+ }++ let grid_coords = IVector::new(ix, iy);+ let center =+ Vector::new(ix as Real + 0.5, iy as Real + 0.5) * (self.parent.voxel_size);+ Some(VoxelData {+ linear_id: VoxelIndex {+ chunk_id: self.my_id,+ id_in_chunk,+ },+ grid_coords,+ center,+ state,+ })+ })+ })+ }++ /// Iterate through the data of all the voxels within the given (semi-open) voxel grid indices.+ ///+ /// Note that this only yields non-empty voxels within the range. This does not+ /// include any voxel that falls outside [`Self::domain`].+ #[cfg(feature = "dim3")]+ pub fn voxels_in_range(+ self,+ mins: IVector,+ maxs: IVector,+ ) -> impl Iterator<Item = VoxelData> + use<'a> {+ let [chunk_mins, chunk_maxs] = VoxelsChunk::keys_bounds(self.key);+ let mins = mins.max(chunk_mins);+ let maxs = maxs.min(chunk_maxs);++ (mins.x..maxs.x).flat_map(move |ix| {+ (mins.y..maxs.y).flat_map(move |iy| {+ (mins.z..maxs.z).filter_map(move |iz| {+ let id_in_chunk = (ix - chunk_mins.x) as usize+ + (iy - chunk_mins.y) as usize * VoxelsChunk::VOXELS_PER_CHUNK_DIM+ + (iz - chunk_mins.z) as usize+ * VoxelsChunk::VOXELS_PER_CHUNK_DIM+ * VoxelsChunk::VOXELS_PER_CHUNK_DIM;+ let state = self.states[id_in_chunk];++ if state.is_empty() {+ return None;+ }++ let grid_coords = IVector::new(ix, iy, iz);+ let center = Vector::new(ix as Real + 0.5, iy as Real + 0.5, iz as Real + 0.5)+ * (self.parent.voxel_size);+ Some(VoxelData {+ linear_id: VoxelIndex {+ chunk_id: self.my_id,+ id_in_chunk,+ },+ grid_coords,+ center,+ state,+ })+ })+ })+ })+ }+}diff --git a/renderer/third_party/parry3d/src/shape/voxels/voxels_consts.rs b/renderer/third_party/parry3d/src/shape/voxels/voxels_consts.rsnew file mode 100644index 0000000..a0b7556--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/voxels/voxels_consts.rs@@ -0,0 +1,639 @@+use super::VoxelType;++#[cfg(test)]+use {super::OctantPattern, crate::bounding_volume::Aabb};++// Index to the item of FACES_TO_VOXEL_TYPES which identifies interior voxels.+#[cfg(feature = "dim2")]+pub(super) const INTERIOR_FACE_MASK: u8 = 0b0000_1111;+#[cfg(feature = "dim3")]+pub(super) const INTERIOR_FACE_MASK: u8 = 0b0011_1111;+// Index to the item of FACES_TO_VOXEL_TYPES which identifies empty voxels.++#[cfg(feature = "dim2")]+pub(super) const EMPTY_FACE_MASK: u8 = 0b0001_0000;+#[cfg(feature = "dim3")]+pub(super) const EMPTY_FACE_MASK: u8 = 0b0100_0000;++/// The voxel type deduced from adjacency information.+///+/// See the documentation of [`VoxelType`] for additional information on what each enum variant+/// means.+///+/// In 3D there are 6 neighbor faces => 64 cases + 1 empty case.+#[cfg(feature = "dim3")]+pub(super) const FACES_TO_VOXEL_TYPES: [VoxelType; 65] = [+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Edge,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Edge,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Face,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Edge,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Edge,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Face,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Edge,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Edge,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Face,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Face,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Face,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Edge,+ VoxelType::Face,+ VoxelType::Face,+ VoxelType::Face,+ VoxelType::Face,+ VoxelType::Interior,+ VoxelType::Empty,+];++/// Indicates the convex features of each voxel that can lead to collisions.+///+/// The interpretation of each bit differs depending on the corresponding voxel type in+/// `FACES_TO_VOXEL_TYPES`:+/// - For `VoxelType::Vertex`: the i-th bit set to `1` indicates that the i-th AABB vertex is convex+/// and might lead to collisions.+/// - For `VoxelType::Edge`: the i-th bit set to `1` indicates that the i-th edge from `Aabb::EDGES_VERTEX_IDS`+/// is convex and might lead to collisions.+/// - For `VoxelType::Face`: the i-th bit set to `1` indicates that the i-th face from `Aabb::FACES_VERTEX_IDS`+/// is exposed and might lead to collisions.+#[cfg(feature = "dim3")]+pub(super) const FACES_TO_FEATURE_MASKS: [u16; 65] = [+ 0b11111111,+ 0b10011001,+ 0b1100110,+ 0b1010101,+ 0b110011,+ 0b10001,+ 0b100010,+ 0b10001,+ 0b11001100,+ 0b10001000,+ 0b1000100,+ 0b1000100,+ 0b10101010,+ 0b10001000,+ 0b100010,+ 0b110000,+ 0b1111,+ 0b1001,+ 0b110,+ 0b101,+ 0b11,+ 0b1,+ 0b10,+ 0b1,+ 0b1100,+ 0b1000,+ 0b100,+ 0b100,+ 0b1010,+ 0b1000,+ 0b10,+ 0b100000,+ 0b11110000,+ 0b10010000,+ 0b1100000,+ 0b1010000,+ 0b110000,+ 0b10000,+ 0b100000,+ 0b10000,+ 0b11000000,+ 0b10000000,+ 0b1000000,+ 0b1000000,+ 0b10100000,+ 0b10000000,+ 0b100000,+ 0b10000,+ 0b111100000000,+ 0b100100000000,+ 0b11000000000,+ 0b1100,+ 0b1100000000,+ 0b100000000,+ 0b1000000000,+ 0b1000,+ 0b110000000000,+ 0b100000000000,+ 0b10000000000,+ 0b100,+ 0b11,+ 0b10,+ 0b1,+ 0b1111111111111111,+ 0,+];++/// Each octant is assigned three contiguous bits.+#[cfg(feature = "dim3")]+pub(super) const FACES_TO_OCTANT_MASKS: [u32; 65] = [+ 0b1001001001001001001001,+ 0b1010010001001010010001,+ 0b10001001010010001001010,+ 0b10010010010010010010010,+ 0b11011001001011011001001,+ 0b11111010001011111010001,+ 0b111011001010111011001010,+ 0b111111010010111111010010,+ 0b1001011011001001011011,+ 0b1010111011001010111011,+ 0b10001011111010001011111,+ 0b10010111111010010111111,+ 0b11011011011011011011011,+ 0b11111111011011111111011,+ 0b111011011111111011011111,+ 0b111111111111111111111111,+ 0b100100100100001001001001,+ 0b100110110100001010010001,+ 0b110100100110010001001010,+ 0b110110110110010010010010,+ 0b101101100100011011001001,+ 0b101000110100011111010001,+ 0b101100110111011001010,+ 0b110110111111010010,+ 0b100100101101001001011011,+ 0b100110000101001010111011,+ 0b110100101000010001011111,+ 0b110110000000010010111111,+ 0b101101101101011011011011,+ 0b101000000101011111111011,+ 0b101101000111011011111,+ 0b111111111111,+ 0b1001001001100100100100,+ 0b1010010001100110110100,+ 0b10001001010110100100110,+ 0b10010010010110110110110,+ 0b11011001001101101100100,+ 0b11111010001101000110100,+ 0b111011001010000101100110,+ 0b111111010010000000110110,+ 0b1001011011100100101101,+ 0b1010111011100110000101,+ 0b10001011111110100101000,+ 0b10010111111110110000000,+ 0b11011011011101101101101,+ 0b11111111011101000000101,+ 0b111011011111000101101000,+ 0b111111111111000000000000,+ 0b100100100100100100100100,+ 0b100110110100100110110100,+ 0b110100100110110100100110,+ 0b110110110110110110110110,+ 0b101101100100101101100100,+ 0b101000110100101000110100,+ 0b101100110000101100110,+ 0b110110000000110110,+ 0b100100101101100100101101,+ 0b100110000101100110000101,+ 0b110100101000110100101000,+ 0b110110000000110110000000,+ 0b101101101101101101101101,+ 0b101000000101101000000101,+ 0b101101000000101101000,+ 0b0,+ 0,+];++#[cfg(feature = "dim2")]+pub(super) const FACES_TO_VOXEL_TYPES: [VoxelType; 17] = [+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Face,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Face,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Vertex,+ VoxelType::Face,+ VoxelType::Face,+ VoxelType::Face,+ VoxelType::Face,+ VoxelType::Interior,+ VoxelType::Empty,+];++#[cfg(feature = "dim2")]+pub(super) const FACES_TO_FEATURE_MASKS: [u16; 17] = [+ 0b1111,+ 0b1001,+ 0b110,+ 0b1100,+ 0b11,+ 0b1,+ 0b10,+ 0b1000,+ 0b1100,+ 0b1000,+ 0b100,+ 0b100,+ 0b11,+ 0b10,+ 0b1,+ 0b1111111111111111,+ 0,+];++// NOTE: in 2D we are also using 3 bits per octant even though we technically only need two.+// This keeps some collision-detection easier by avoiding some special-casing.+#[cfg(feature = "dim2")]+pub(super) const FACES_TO_OCTANT_MASKS: [u32; 17] = [+ 0b1001001001,+ 0b1011011001,+ 0b11001001011,+ 0b11011011011,+ 0b10010001001,+ 0b10000011001,+ 0b10001011,+ 0b11011,+ 0b1001010010,+ 0b1011000010,+ 0b11001010000,+ 0b11011000000,+ 0b10010010010,+ 0b10000000010,+ 0b10010000,+ 0b0,+ 0,+];++// NOTE: this code is used to generate the constant tables+// FACES_TO_VOXEL_TYPES, FACES_TO_FEATURE_MASKS, FACES_TO_OCTANT_MASKS.+#[allow(dead_code)]+#[cfg(feature = "dim2")]+#[cfg(test)]+fn gen_const_tables() {+ // The `j-th` bit of `faces_adj_to_vtx[i]` is set to 1, if the j-th face of the AABB (based on+ // the face order depicted in `AABB::FACES_VERTEX_IDS`) is adjacent to the `i` vertex of the AABB+ // (vertices are indexed as per the diagram depicted in the `FACES_VERTEX_IDS` doc.+ // Each entry of this will always have exactly 3 bits set.+ let mut faces_adj_to_vtx = [0usize; 4];++ for fid in 0..4 {+ let vids = Aabb::FACES_VERTEX_IDS[fid];+ let key = 1 << fid;+ faces_adj_to_vtx[vids.0] |= key;+ faces_adj_to_vtx[vids.1] |= key;+ }++ /*+ * FACES_TO_VOXEL_TYPES+ */+ std::println!("const FACES_TO_VOXEL_TYPES: [VoxelType; 17] = [");+ 'outer: for i in 0usize..16 {+ // If any vertex of the voxel has three faces with no adjacent voxels,+ // then the voxel type is Vertex.+ for adjs in faces_adj_to_vtx.iter() {+ if (*adjs & i) == 0 {+ std::println!("VoxelType::Vertex,");+ continue 'outer;+ }+ }++ // If one face doesn’t have any adjacent voxel,+ // then the voxel type is Face.+ for fid in 0..4 {+ if ((1 << fid) & i) == 0 {+ std::println!("VoxelType::Face,");+ continue 'outer;+ }+ }+ }++ // Add final entries for special values.+ std::println!("VoxelType::Interior,");+ std::println!("VoxelType::Empty,");+ std::println!("];");++ /*+ * FACES_TO_FEATURE_MASKS+ */+ std::println!("const FACES_TO_FEATURE_MASKS: [u16; 17] = [");+ for i in 0usize..16 {+ // Each bit set indicates a convex vertex that can lead to collisions.+ // The result will be nonzero only for `VoxelType::Vertex` voxels.+ let mut vtx_key = 0;+ for (vid, adjs) in faces_adj_to_vtx.iter().enumerate() {+ if (*adjs & i) == 0 {+ vtx_key |= 1 << vid;+ }+ }++ if vtx_key != 0 {+ std::println!("0b{:b},", vtx_key as u16);+ continue;+ }++ // Each bit set indicates an exposed face that can lead to collisions.+ // The result will be nonzero only for `VoxelType::Face` voxels.+ let mut face_key = 0;+ for fid in 0..4 {+ if ((1 << fid) & i) == 0 {+ face_key |= 1 << fid;+ }+ }++ if face_key != 0 {+ std::println!("0b{:b},", face_key as u16);+ continue;+ }+ }++ std::println!("0b{:b},", u16::MAX);+ std::println!("0,");+ std::println!("];");++ /*+ * Faces to octant masks.+ */+ std::println!("const FACES_TO_OCTANT_MASKS: [u32; 17] = [");+ for i in 0usize..16 {+ // First test if we have vertices.+ let mut octant_mask = 0;+ let mut set_mask = |mask, octant| {+ // NOTE: we don’t overwrite any mask already set for the octant.+ if (octant_mask >> (octant * 3)) & 0b0111 == 0 {+ octant_mask |= mask << (octant * 3);+ }+ };++ for (vid, adjs) in faces_adj_to_vtx.iter().enumerate() {+ if (*adjs & i) == 0 {+ set_mask(1, vid);+ }+ }++ // This is the index of the normal of the faces given by+ // Aabb::FACES_VERTEX_IDS.+ const FX: u32 = OctantPattern::FACE_X;+ const FY: u32 = OctantPattern::FACE_Y;+ const FACE_NORMALS: [u32; 4] = [FX, FX, FY, FY];++ #[allow(clippy::needless_range_loop)]+ for fid in 0..4 {+ if ((1 << fid) & i) == 0 {+ let vid = Aabb::FACES_VERTEX_IDS[fid];+ let mask = FACE_NORMALS[fid];++ set_mask(mask, vid.0);+ set_mask(mask, vid.1);+ }+ }+ std::println!("0b{:b},", octant_mask);+ }+ std::println!("0,");+ std::println!("];");+}++// NOTE: this code is used to generate the constant tables+// FACES_TO_VOXEL_TYPES, FACES_TO_FEATURE_MASKS, FACES_TO_OCTANT_MASKS.+#[allow(dead_code)]+#[cfg(feature = "dim3")]+#[cfg(test)]+fn gen_const_tables() {+ // The `j-th` bit of `faces_adj_to_vtx[i]` is set to 1, if the j-th face of the AABB (based on+ // the face order depicted in `AABB::FACES_VERTEX_IDS`) is adjacent to the `i` vertex of the AABB+ // (vertices are indexed as per the diagram depicted in the `FACES_VERTEX_IDS` doc.+ // Each entry of this will always have exactly 3 bits set.+ let mut faces_adj_to_vtx = [0usize; 8];++ // The `j-th` bit of `faces_adj_to_vtx[i]` is set to 1, if the j-th edge of the AABB (based on+ // the edge order depicted in `AABB::EDGES_VERTEX_IDS`) is adjacent to the `i` vertex of the AABB+ // (vertices are indexed as per the diagram depicted in the `FACES_VERTEX_IDS` doc.+ // Each entry of this will always have exactly 2 bits set.+ let mut faces_adj_to_edge = [0usize; 12];++ for fid in 0..6 {+ let vids = Aabb::FACES_VERTEX_IDS[fid];+ let key = 1 << fid;+ faces_adj_to_vtx[vids.0] |= key;+ faces_adj_to_vtx[vids.1] |= key;+ faces_adj_to_vtx[vids.2] |= key;+ faces_adj_to_vtx[vids.3] |= key;+ }++ #[allow(clippy::needless_range_loop)]+ for eid in 0..12 {+ let evids = Aabb::EDGES_VERTEX_IDS[eid];+ for fid in 0..6 {+ let fvids = Aabb::FACES_VERTEX_IDS[fid];+ if (fvids.0 == evids.0+ || fvids.1 == evids.0+ || fvids.2 == evids.0+ || fvids.3 == evids.0)+ && (fvids.0 == evids.1+ || fvids.1 == evids.1+ || fvids.2 == evids.1+ || fvids.3 == evids.1)+ {+ let key = 1 << fid;+ faces_adj_to_edge[eid] |= key;+ }+ }+ }++ /*+ * FACES_TO_VOXEL_TYPES+ */+ std::println!("const FACES_TO_VOXEL_TYPES: [VoxelType; 65] = [");+ 'outer: for i in 0usize..64 {+ // If any vertex of the voxel has three faces with no adjacent voxels,+ // then the voxel type is Vertex.+ for adjs in faces_adj_to_vtx.iter() {+ if (*adjs & i) == 0 {+ std::println!("VoxelType::Vertex,");+ continue 'outer;+ }+ }++ // If any vertex of the voxel has three faces with no adjacent voxels,+ // then the voxel type is Edge.+ for adjs in faces_adj_to_edge.iter() {+ if (*adjs & i) == 0 {+ std::println!("VoxelType::Edge,");+ continue 'outer;+ }+ }++ // If one face doesn’t have any adjacent voxel,+ // then the voxel type is Face.+ for fid in 0..6 {+ if ((1 << fid) & i) == 0 {+ std::println!("VoxelType::Face,");+ continue 'outer;+ }+ }+ }++ // Add final entries for special values.+ std::println!("VoxelType::Interior,");+ std::println!("VoxelType::Empty,");+ std::println!("];");++ /*+ * FACES_TO_FEATURE_MASKS+ */+ std::println!("const FACES_TO_FEATURE_MASKS: [u16; 65] = [");+ for i in 0usize..64 {+ // Each bit set indicates a convex vertex that can lead to collisions.+ // The result will be nonzero only for `VoxelType::Vertex` voxels.+ let mut vtx_key = 0;+ for (vid, adjs) in faces_adj_to_vtx.iter().enumerate() {+ if (*adjs & i) == 0 {+ vtx_key |= 1 << vid;+ }+ }++ if vtx_key != 0 {+ std::println!("0b{:b},", vtx_key as u16);+ continue;+ }++ // Each bit set indicates a convex edge that can lead to collisions.+ // The result will be nonzero only for `VoxelType::Edge` voxels.+ let mut edge_key = 0;+ for (eid, adjs) in faces_adj_to_edge.iter().enumerate() {+ if (*adjs & i) == 0 {+ edge_key |= 1 << eid;+ }+ }++ if edge_key != 0 {+ std::println!("0b{:b},", edge_key as u16);+ continue;+ }++ // Each bit set indicates an exposed face that can lead to collisions.+ // The result will be nonzero only for `VoxelType::Face` voxels.+ let mut face_key = 0;+ for fid in 0..6 {+ if ((1 << fid) & i) == 0 {+ face_key |= 1 << fid;+ }+ }++ if face_key != 0 {+ std::println!("0b{:b},", face_key as u16);+ continue;+ }+ }++ std::println!("0b{:b},", u16::MAX);+ std::println!("0,");+ std::println!("];");++ /*+ * Faces to octant masks.+ */+ std::println!("const FACES_TO_OCTANT_MASKS: [u32; 65] = [");+ for i in 0usize..64 {+ // First test if we have vertices.+ let mut octant_mask = 0;+ let mut set_mask = |mask, octant| {+ // NOTE: we don’t overwrite any mask already set for the octant.+ if (octant_mask >> (octant * 3)) & 0b0111 == 0 {+ octant_mask |= mask << (octant * 3);+ }+ };++ for (vid, adjs) in faces_adj_to_vtx.iter().enumerate() {+ if (*adjs & i) == 0 {+ set_mask(1, vid);+ }+ }++ // This is the index of the axis porting the edges given by+ // Aabb::EDGES_VERTEX_IDS.+ const EX: u32 = OctantPattern::EDGE_X;+ const EY: u32 = OctantPattern::EDGE_Y;+ const EZ: u32 = OctantPattern::EDGE_Z;+ const EDGE_AXIS: [u32; 12] = [EX, EY, EX, EY, EX, EY, EX, EY, EZ, EZ, EZ, EZ];+ for (eid, adjs) in faces_adj_to_edge.iter().enumerate() {+ if (*adjs & i) == 0 {+ let vid = Aabb::EDGES_VERTEX_IDS[eid];+ let mask = EDGE_AXIS[eid];++ set_mask(mask, vid.0);+ set_mask(mask, vid.1);+ }+ }++ // This is the index of the normal of the faces given by+ // Aabb::FACES_VERTEX_IDS.+ const FX: u32 = OctantPattern::FACE_X;+ const FY: u32 = OctantPattern::FACE_Y;+ const FZ: u32 = OctantPattern::FACE_Z;+ const FACE_NORMALS: [u32; 6] = [FX, FX, FY, FY, FZ, FZ];++ #[allow(clippy::needless_range_loop)]+ for fid in 0..6 {+ if ((1 << fid) & i) == 0 {+ let vid = Aabb::FACES_VERTEX_IDS[fid];+ let mask = FACE_NORMALS[fid];++ set_mask(mask, vid.0);+ set_mask(mask, vid.1);+ set_mask(mask, vid.2);+ set_mask(mask, vid.3);+ }+ }+ std::println!("0b{:b},", octant_mask);+ }+ std::println!("0,");+ std::println!("];");+}++#[cfg(test)]+mod test {+ #[test]+ fn gen_const_tables() {+ super::gen_const_tables();+ }+}diff --git a/renderer/third_party/parry3d/src/shape/voxels/voxels_edition.rs b/renderer/third_party/parry3d/src/shape/voxels/voxels_edition.rsnew file mode 100644index 0000000..3c962b0--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/voxels/voxels_edition.rs@@ -0,0 +1,319 @@+use crate::bounding_volume::Aabb;+use crate::math::{IVector, IVectorExt, Vector, DIM};+use crate::shape::voxels::voxels_chunk::{VoxelsChunk, VoxelsChunkHeader};+use crate::shape::{VoxelState, Voxels};+use crate::utils::hashmap::Entry;+use alloc::vec;++impl Voxels {+ /// Sets the size of each voxel along each local coordinate axis.+ ///+ /// Since the internal spatial acceleration structure needs to be updated, this+ /// operation runs in `O(n)` time, where `n` is the number of voxels.+ pub fn set_voxel_size(&mut self, new_size: Vector) {+ let scale = new_size / self.voxel_size;+ self.chunk_bvh.scale(scale);+ self.voxel_size = new_size;+ }++ /// Adds or removes a voxel at the specified grid coordinates.+ ///+ /// This is the primary method for dynamically modifying a voxel shape. It can:+ /// - Add a new voxel by setting `is_filled = true`+ /// - Remove an existing voxel by setting `is_filled = false`+ ///+ /// The method automatically updates the neighborhood information for the affected voxel+ /// and all its neighbors to maintain correct collision detection behavior.+ ///+ /// # Returns+ ///+ /// The previous [`VoxelState`] of the voxel before modification. This allows you to+ /// detect whether the operation actually changed anything.+ ///+ /// # Examples+ ///+ /// ## Adding Voxels+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// let mut voxels = Voxels::new(Vector::new(1.0, 1.0, 1.0), &[]);+ ///+ /// // Add a voxel at (0, 0, 0)+ /// let prev_state = voxels.set_voxel(IVector::new(0, 0, 0), true);+ /// assert!(prev_state.is_empty()); // Was empty before+ ///+ /// // Verify it was added+ /// let state = voxels.voxel_state(IVector::new(0, 0, 0)).unwrap();+ /// assert!(!state.is_empty());+ /// # }+ /// ```+ ///+ /// ## Removing Voxels+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// let mut voxels = Voxels::new(+ /// Vector::new(1.0, 1.0, 1.0),+ /// &[IVector::new(0, 0, 0), IVector::new(1, 0, 0)],+ /// );+ ///+ /// // Remove the voxel at (0, 0, 0)+ /// voxels.set_voxel(IVector::new(0, 0, 0), false);+ ///+ /// // Verify it was removed+ /// let state = voxels.voxel_state(IVector::new(0, 0, 0)).unwrap();+ /// assert!(state.is_empty());+ /// # }+ /// ```+ ///+ /// ## Building Shapes Dynamically+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// let mut voxels = Voxels::new(Vector::new(1.0, 1.0, 1.0), &[]);+ ///+ /// // Build a 3×3 floor+ /// for x in 0..3 {+ /// for z in 0..3 {+ /// voxels.set_voxel(IVector::new(x, 0, z), true);+ /// }+ /// }+ ///+ /// // Count filled voxels+ /// let filled = voxels.voxels()+ /// .filter(|v| !v.state.is_empty())+ /// .count();+ /// assert_eq!(filled, 9);+ /// # }+ /// ```+ ///+ /// ## Detecting Changes+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// let mut voxels = Voxels::new(+ /// Vector::new(1.0, 1.0, 1.0),+ /// &[IVector::new(0, 0, 0)],+ /// );+ ///+ /// // Try to add a voxel that already exists+ /// let prev = voxels.set_voxel(IVector::new(0, 0, 0), true);+ /// if !prev.is_empty() {+ /// println!("Voxel was already filled!");+ /// }+ /// # }+ /// ```+ pub fn set_voxel(&mut self, key: IVector, is_filled: bool) -> VoxelState {+ let (chunk_key, id_in_chunk) = Self::chunk_key_and_id_in_chunk(key);+ let header_entry = self.chunk_headers.entry(chunk_key);++ if !is_filled && matches!(header_entry, Entry::Vacant(_)) {+ // The voxel is already empty (it doesn’t exist at all).+ // Nothing more to do.+ return VoxelState::EMPTY;+ }++ let chunk_header = header_entry.or_insert_with(|| {+ let id = self.free_chunks.pop().unwrap_or_else(|| {+ self.chunks.push(VoxelsChunk::default());+ self.chunk_keys.push(chunk_key);+ self.chunks.len() - 1+ });++ self.chunk_keys[id] = chunk_key;+ self.chunk_bvh+ .insert(VoxelsChunk::aabb(&chunk_key, self.voxel_size), id as u32);+ VoxelsChunkHeader { id, len: 0 }+ });+ let chunk_id = chunk_header.id;++ let prev = self.chunks[chunk_id].states[id_in_chunk];+ let new_is_empty = !is_filled;++ if prev.is_empty() ^ new_is_empty {+ let can_remove_chunk = if new_is_empty {+ chunk_header.len -= 1;+ chunk_header.len == 0+ } else {+ chunk_header.len += 1;+ false+ };++ self.chunks[chunk_id].states[id_in_chunk] =+ self.update_neighbors_state(key, new_is_empty);++ if can_remove_chunk {+ self.chunk_bvh.remove(chunk_id as u32);++ #[cfg(feature = "enhanced-determinism")]+ let _ = self.chunk_headers.swap_remove(&chunk_key);+ #[cfg(not(feature = "enhanced-determinism"))]+ let _ = self.chunk_headers.remove(&chunk_key);++ self.free_chunks.push(chunk_id);+ self.chunk_keys[chunk_id] = VoxelsChunk::INVALID_CHUNK_KEY;+ }+ }++ prev+ }++ /// Crops the voxel shape in-place to a rectangular region.+ ///+ /// Removes all voxels outside the specified grid coordinate bounds `[domain_mins, domain_maxs]`+ /// (inclusive on both ends). This is useful for:+ /// - Extracting a sub-region of a larger voxel world+ /// - Removing voxels outside a region of interest+ /// - Implementing chunk-based world management+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// let mut voxels = Voxels::new(+ /// Vector::new(1.0, 1.0, 1.0),+ /// &[+ /// IVector::new(0, 0, 0),+ /// IVector::new(1, 0, 0),+ /// IVector::new(2, 0, 0),+ /// IVector::new(3, 0, 0),+ /// ],+ /// );+ ///+ /// // Keep only voxels in the range [1, 2]+ /// voxels.crop(IVector::new(1, 0, 0), IVector::new(2, 0, 0));+ ///+ /// // Only two voxels remain+ /// let count = voxels.voxels()+ /// .filter(|v| !v.state.is_empty())+ /// .count();+ /// assert_eq!(count, 2);+ /// # }+ /// ```+ pub fn crop(&mut self, domain_mins: IVector, domain_maxs: IVector) {+ // TODO PERF: this could be done more efficiently.+ if let Some(new_shape) = self.cropped(domain_mins, domain_maxs) {+ *self = new_shape;+ }+ }++ /// Returns a cropped version of this voxel shape with a rectangular domain.+ ///+ /// This removes every voxels out of the `[domain_mins, domain_maxs]` bounds.+ pub fn cropped(&self, domain_mins: IVector, domain_maxs: IVector) -> Option<Self> {+ // TODO PERF: can be optimized significantly.+ let mut in_box = vec![];+ for vox in self.voxels() {+ if !vox.state.is_empty()+ && grid_aabb_contains_point(&domain_mins, &domain_maxs, &vox.grid_coords)+ {+ in_box.push(vox.grid_coords);+ }+ }++ if !in_box.is_empty() {+ Some(Voxels::new(self.voxel_size, &in_box))+ } else {+ None+ }+ }++ /// Splits this voxel shape into two separate shapes based on an AABB.+ ///+ /// Partitions the voxels into two groups:+ /// - **Inside**: Voxels whose centers fall inside the given `aabb`+ /// - **Outside**: All remaining voxels+ ///+ /// Returns `(Some(inside), Some(outside))`, or `None` for either if that partition is empty.+ ///+ /// # Use Cases+ ///+ /// - Spatial partitioning for physics simulation+ /// - Implementing destructible objects (remove the "inside" part on explosion)+ /// - Chunk-based world management+ /// - Level-of-detail systems+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::shape::Voxels;+ /// use parry3d::bounding_volume::Aabb;+ /// use parry3d::math::{Vector, IVector};+ ///+ /// let voxels = Voxels::new(+ /// Vector::new(1.0, 1.0, 1.0),+ /// &[+ /// IVector::new(0, 0, 0), // Center at (0.5, 0.5, 0.5)+ /// IVector::new(2, 0, 0), // Center at (2.5, 0.5, 0.5)+ /// IVector::new(4, 0, 0), // Center at (4.5, 0.5, 0.5)+ /// ],+ /// );+ ///+ /// // Split at X = 3.0+ /// let split_box = Aabb::new(+ /// Vector::new(-10.0, -10.0, -10.0),+ /// Vector::new(3.0, 10.0, 10.0),+ /// );+ ///+ /// let (inside, outside) = voxels.split_with_box(&split_box);+ ///+ /// // First two voxels inside, last one outside+ /// assert!(inside.is_some());+ /// assert!(outside.is_some());+ /// # }+ /// ```+ pub fn split_with_box(&self, aabb: &Aabb) -> (Option<Self>, Option<Self>) {+ // TODO PERF: can be optimized significantly.+ let mut in_box = vec![];+ let mut rest = vec![];+ for vox in self.voxels() {+ if !vox.state.is_empty() {+ if aabb.contains_local_point(vox.center) {+ in_box.push(vox.grid_coords);+ } else {+ rest.push(vox.grid_coords);+ }+ }+ }++ let in_box = if !in_box.is_empty() {+ Some(Voxels::new(self.voxel_size, &in_box))+ } else {+ None+ };++ let rest = if !rest.is_empty() {+ Some(Voxels::new(self.voxel_size, &rest))+ } else {+ None+ };++ (in_box, rest)+ }+}++fn grid_aabb_contains_point(mins: &IVector, maxs: &IVector, point: &IVector) -> bool {+ for i in 0..DIM {+ if point.ivget(i) < mins.ivget(i) || point.ivget(i) > maxs.ivget(i) {+ return false;+ }+ }++ true+}diff --git a/renderer/third_party/parry3d/src/shape/voxels/voxels_neighborhood.rs b/renderer/third_party/parry3d/src/shape/voxels/voxels_neighborhood.rsnew file mode 100644index 0000000..659f8b0--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/voxels/voxels_neighborhood.rs@@ -0,0 +1,205 @@+use super::VoxelsChunk;+use crate::math::{ivect_to_vect, IVector, IVectorExt, DIM};+use crate::shape::{VoxelState, Voxels};++impl Voxels {+ /// Updates the state of the neighbors of the voxel `key`.+ ///+ /// Modifies the state of the neighbors of `key` to account for it being empty or full.+ /// Returns (but doesn’t modify) the new state of the voxel specified by `key`.+ #[must_use]+ pub(super) fn update_neighbors_state(+ &mut self,+ key: IVector,+ center_is_empty: bool,+ ) -> VoxelState {+ let mut key_data = 0;++ for k in 0..DIM {+ let mut left = key;+ let mut right = key;+ left.ivset(k, left.ivget(k) - 1);+ right.ivset(k, right.ivget(k) + 1);++ // TODO PERF: all the calls to `linear_index` result in a hashmap lookup each time.+ // We should instead be smarter and detect if left/right are in the same chunk+ // to only look it up once.+ if let Some(left_id) = self.linear_index(left) {+ let left_state = &mut self.chunks[left_id.chunk_id].states[left_id.id_in_chunk];+ if !left_state.is_empty() {+ if center_is_empty {+ left_state.0 &= !(1 << (k * 2));+ } else {+ left_state.0 |= 1 << (k * 2);+ key_data |= 1 << (k * 2 + 1);+ }+ }+ }++ if let Some(right_id) = self.linear_index(right) {+ let right_state = &mut self.chunks[right_id.chunk_id].states[right_id.id_in_chunk];+ if !right_state.is_empty() {+ if center_is_empty {+ right_state.0 &= !(1 << (k * 2 + 1));+ } else {+ right_state.0 |= 1 << (k * 2 + 1);+ key_data |= 1 << (k * 2);+ }+ }+ }+ }++ if center_is_empty {+ VoxelState::EMPTY+ } else {+ VoxelState::new(key_data)+ }+ }++ pub(super) fn recompute_all_voxels_states(&mut self) {+ for (chunk_key, chunk_header) in self.chunk_headers.iter() {+ for id_in_chunk in 0..VoxelsChunk::VOXELS_PER_CHUNK {+ let voxel_key = VoxelsChunk::voxel_key_at_id(*chunk_key, id_in_chunk as u32);+ self.chunks[chunk_header.id].states[id_in_chunk] =+ self.compute_voxel_state(voxel_key);+ }+ }+ }++ fn compute_voxel_state(&self, key: IVector) -> VoxelState {+ let Some(id) = self.linear_index(key) else {+ return VoxelState::EMPTY;+ };++ if self.chunks[id.chunk_id].states[id.id_in_chunk].is_empty() {+ return VoxelState::EMPTY;+ }++ self.compute_voxel_neighborhood_bits(key)+ }++ pub(super) fn compute_voxel_neighborhood_bits(&self, key: IVector) -> VoxelState {+ let mut occupied_faces = 0;++ for k in 0..DIM {+ let (mut prev, mut next) = (key, key);+ prev.ivset(k, prev.ivget(k) - 1);+ next.ivset(k, next.ivget(k) + 1);++ if let Some(next_id) = self.linear_index(next) {+ if !self.chunks[next_id.chunk_id].states[next_id.id_in_chunk].is_empty() {+ occupied_faces |= 1 << (k * 2);+ }+ }+ if let Some(prev_id) = self.linear_index(prev) {+ if !self.chunks[prev_id.chunk_id].states[prev_id.id_in_chunk].is_empty() {+ occupied_faces |= 1 << (k * 2 + 1);+ }+ }+ }++ VoxelState::new(occupied_faces)+ }++ /// Merges voxel state (neighborhood) information of a given voxel (and all its neighbors)+ /// from `self` and `other`, to account for a recent change to the given `voxel` in `self`.+ ///+ /// This is designed to be called after `self` was modified with [`Voxels::set_voxel`].+ ///+ /// This is the same as [`Voxels::combine_voxel_states`] but localized to a single voxel and its+ /// neighbors.+ pub fn propagate_voxel_change(+ &mut self,+ other: &mut Self,+ voxel: IVector,+ origin_shift: IVector,+ ) {+ let center_is_empty = self+ .voxel_state(voxel)+ .map(|vox| vox.is_empty())+ .unwrap_or(true);+ let center_state_delta =+ other.update_neighbors_state(voxel - origin_shift, center_is_empty);++ if let Some(vid) = self.linear_index(voxel) {+ self.chunks[vid.chunk_id].states[vid.id_in_chunk].0 |= center_state_delta.0;+ }+ }++ /// Merges voxel state (neighborhood) information of each voxel from `self` and `other`.+ ///+ /// This allows each voxel from one shape to be aware of the presence of neighbors belonging to+ /// the other so that collision detection is capable of transitioning between the boundaries of+ /// one shape to the other without hitting an internal edge.+ ///+ /// Both voxels shapes are assumed to have the same [`Self::voxel_size`].+ /// If `other` lives in a coordinate space with a different origin than `self`, then+ /// `origin_shift` represents the distance (as a multiple of the `voxel_size`) from the origin+ /// of `self` to the origin of `other`. Therefore, a voxel with coordinates `key` on `other`+ /// will have coordinates `key + origin_shift` on `self`.+ pub fn combine_voxel_states(&mut self, other: &mut Self, origin_shift: IVector) {+ let one = IVector::splat(1);+ let origin_shift_worldspace = ivect_to_vect(origin_shift) * self.voxel_size;++ for chunk_key in &self.chunk_keys {+ let mut aabb = VoxelsChunk::aabb(chunk_key, self.voxel_size);+ // Enlarge by one-half voxel so we detect cases where we also detect neighbor chunks from `other`.+ aabb.mins -= self.voxel_size / 2.0;+ aabb.maxs += self.voxel_size / 2.0;+ // Shift to the local coordinate system of `other`.+ let shifted_aabb = aabb.translated(-origin_shift_worldspace);++ if other.chunk_bvh.intersect_aabb(&shifted_aabb).any(|_| true) {+ // Check the voxels from this chunk against the other voxels shape.++ // Iterate on the domain intersection. If the voxel exists (and is non-empty) on both shapes, we+ // simply need to combine their bitmasks. If it doesn’t exist on both shapes, we need to+ // actually check the neighbors.+ //+ // The `domain` is expressed in the grid coordinate space of `self`.+ let mut domain = VoxelsChunk::keys_bounds(chunk_key);+ // Enlarge the domain by one voxel so that voxels from `other` but not existing in `self` are updated too.+ domain[0] -= one;+ domain[1] += one;++ for i in domain[0].x..domain[1].x {+ for j in domain[0].y..domain[1].y {+ #[cfg(feature = "dim2")]+ let k_range = 0..1;+ #[cfg(feature = "dim3")]+ let k_range = domain[0].z..domain[1].z;+ for _k in k_range {+ #[cfg(feature = "dim2")]+ let key0 = IVector::new(i, j);+ #[cfg(feature = "dim3")]+ let key0 = IVector::new(i, j, _k);+ let key1 = key0 - origin_shift;+ let vox0 = self+ .linear_index(key0)+ .map(|id| &mut self.chunks[id.chunk_id].states[id.id_in_chunk])+ .filter(|state| !state.is_empty());+ let vox1 = other+ .linear_index(key1)+ .map(|id| &mut other.chunks[id.chunk_id].states[id.id_in_chunk])+ .filter(|state| !state.is_empty());++ match (vox0, vox1) {+ (Some(vox0), Some(vox1)) => {+ vox0.0 |= vox1.0;+ vox1.0 |= vox0.0;+ }+ (Some(vox0), None) => {+ vox0.0 |= other.compute_voxel_neighborhood_bits(key1).0;+ }+ (None, Some(vox1)) => {+ vox1.0 |= self.compute_voxel_neighborhood_bits(key0).0;+ }+ (None, None) => { /* Nothing to adjust. */ }+ }+ }+ }+ }+ }+ }+ }+}diff --git a/renderer/third_party/parry3d/src/shape/voxels/voxels_sizeof.rs b/renderer/third_party/parry3d/src/shape/voxels/voxels_sizeof.rsnew file mode 100644index 0000000..83abc83--- /dev/null+++ b/renderer/third_party/parry3d/src/shape/voxels/voxels_sizeof.rs@@ -0,0 +1,29 @@+use super::{Voxels, VoxelsChunk, VoxelsChunkHeader};+use crate::math::IVector;++impl Voxels {+ // TODO: support a crate like get_size2 (will require support on nalgebra too)?+ /// An approximation of the memory usage (in bytes) for this struct plus+ /// the memory it allocates dynamically.+ pub fn total_memory_size(&self) -> usize {+ size_of::<Self>() + self.heap_memory_size()+ }++ /// An approximation of the memory dynamically-allocated by this struct.+ pub fn heap_memory_size(&self) -> usize {+ // NOTE: if a new field is added to `Self`, adjust this function result.+ let Self {+ chunk_bvh,+ chunk_headers,+ chunks,+ free_chunks,+ chunk_keys,+ voxel_size: _,+ } = self;+ chunks.capacity() * size_of::<VoxelsChunk>()+ + free_chunks.capacity() * size_of::<usize>()+ + chunk_keys.capacity() * size_of::<IVector>()+ + chunk_headers.capacity() * (size_of::<VoxelsChunkHeader>() + size_of::<IVector>())+ + chunk_bvh.heap_memory_size()+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/convex_hull2.rs b/renderer/third_party/parry3d/src/transformation/convex_hull2.rsnew file mode 100644index 0000000..50df9a5--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/convex_hull2.rs@@ -0,0 +1,262 @@+//! 2D convex hull computation.+//!+//! This module provides functions to compute 2D convex hulls.++use alloc::vec::Vec;++use crate::math::{Real, Vector2};+use num_traits::Zero;++// Local 2D-specific support point functions since the generic ones+// use dimension-agnostic types that don't match Vector2/Vector2.+fn support_point_id_2d(direction: Vector2, points: &[Vector2]) -> Option<usize> {+ let mut argmax = None;+ let mut max = -Real::MAX;++ for (id, pt) in points.iter().enumerate() {+ let dot = direction.dot(*pt);+ if dot > max {+ argmax = Some(id);+ max = dot;+ }+ }++ argmax+}++fn indexed_support_point_id_2d<I>(direction: Vector2, points: &[Vector2], idx: I) -> Option<usize>+where+ I: Iterator<Item = usize>,+{+ let mut argmax = None;+ let mut max = -Real::MAX;++ for i in idx {+ let dot = direction.dot(points[i]);+ if dot > max {+ argmax = Some(i);+ max = dot;+ }+ }++ argmax+}++/// Computes the convex hull of a set of 2d points.+///+/// The computed convex-hull have its points given in counter-clockwise order.+#[cfg(feature = "dim2")]+pub fn convex_hull2(points: &[Vector2]) -> Vec<Vector2> {+ convex_hull2_idx(points)+ .into_iter()+ .map(|id| points[id])+ .collect()+}++/// Computes the convex hull of a set of 2d points and returns only the indices of the hull+/// vertices.+///+/// The computed convex-hull have its points given in counter-clockwise order.+pub fn convex_hull2_idx(points: &[Vector2]) -> Vec<usize> {+ let mut undecidable_points = Vec::new();+ let mut segments = get_initial_polyline(points, &mut undecidable_points);++ let mut i = 0;+ while i != segments.len() {+ if !segments[i].valid {+ i += 1;+ continue;+ }++ let pt_id = indexed_support_point_id_2d(+ segments[i].normal,+ points,+ segments[i].visible_points.iter().copied(),+ );++ if let Some(point) = pt_id {+ segments[i].valid = false;++ attach_and_push_facets2(+ segments[i].prev,+ segments[i].next,+ point,+ points,+ &mut segments,+ i,+ &mut undecidable_points,+ );+ }++ i += 1;+ }++ let mut idx = Vec::new();+ let mut curr_facet = 0;++ while !segments[curr_facet].valid {+ curr_facet += 1+ }++ let first_facet = curr_facet;++ loop {+ let curr = &segments[curr_facet];++ if curr.valid {+ idx.push(curr.pts[0]);+ }++ curr_facet = curr.next;++ if curr_facet == first_facet {+ break;+ }+ }++ idx+}++fn get_initial_polyline(points: &[Vector2], undecidable: &mut Vec<usize>) -> Vec<SegmentFacet> {+ let mut res = Vec::new();++ assert!(points.len() >= 2);++ let p1 = support_point_id_2d(Vector2::X, points).unwrap();+ let mut p2 = p1;++ let direction = [-Vector2::X, -Vector2::Y, Vector2::Y];++ for dir in direction.iter() {+ p2 = support_point_id_2d(*dir, points).unwrap();++ let p1p2 = points[p2] - points[p1];++ if !p1p2.length_squared().is_zero() {+ break;+ }+ }++ assert!(+ p1 != p2,+ "Failed to build the 2d convex hull of this point cloud."+ );++ // Build two facets with opposite normals.+ let mut f1 = SegmentFacet::new(p1, p2, 1, 1, points);+ let mut f2 = SegmentFacet::new(p2, p1, 0, 0, points);++ // Attribute points to each facet.+ for i in 0..points.len() {+ if i == p1 || i == p2 {+ continue;+ }+ if f1.can_be_seen_by(i, points) {+ f1.visible_points.push(i);+ } else if f2.can_be_seen_by(i, points) {+ f2.visible_points.push(i);+ } else {+ // The point is collinear.+ undecidable.push(i);+ }+ }++ res.push(f1);+ res.push(f2);++ res+}++fn attach_and_push_facets2(+ prev_facet: usize,+ next_facet: usize,+ point: usize,+ points: &[Vector2],+ segments: &mut Vec<SegmentFacet>,+ removed_facet: usize,+ undecidable: &mut Vec<usize>,+) {+ let new_facet1_id = segments.len();+ let new_facet2_id = new_facet1_id + 1;+ let prev_pt = segments[prev_facet].pts[1];+ let next_pt = segments[next_facet].pts[0];++ let mut new_facet1 = SegmentFacet::new(prev_pt, point, prev_facet, new_facet2_id, points);+ let mut new_facet2 = SegmentFacet::new(point, next_pt, new_facet1_id, next_facet, points);++ segments[prev_facet].next = new_facet1_id;+ segments[next_facet].prev = new_facet2_id;++ // Assign to each facets some of the points which can see it.+ for visible_point in segments[removed_facet].visible_points.iter() {+ if *visible_point == point {+ continue;+ }++ if new_facet1.can_be_seen_by(*visible_point, points) {+ new_facet1.visible_points.push(*visible_point);+ } else if new_facet2.can_be_seen_by(*visible_point, points) {+ new_facet2.visible_points.push(*visible_point);+ }+ // If none of the facet can be seen from the point, it is naturally deleted.+ }++ // Try to assign collinear points to one of the new facets+ let mut i = 0;++ while i != undecidable.len() {+ if new_facet1.can_be_seen_by(undecidable[i], points) {+ new_facet1.visible_points.push(undecidable[i]);+ let _ = undecidable.swap_remove(i);+ } else if new_facet2.can_be_seen_by(undecidable[i], points) {+ new_facet2.visible_points.push(undecidable[i]);+ let _ = undecidable.swap_remove(i);+ } else {+ i += 1;+ }+ }++ segments.push(new_facet1);+ segments.push(new_facet2);+}++struct SegmentFacet {+ pub valid: bool,+ pub normal: Vector2,+ pub next: usize,+ pub prev: usize,+ pub pts: [usize; 2],+ pub visible_points: Vec<usize>,+}++impl SegmentFacet {+ pub fn new(p1: usize, p2: usize, prev: usize, next: usize, points: &[Vector2]) -> SegmentFacet {+ let p1p2 = points[p2] - points[p1];++ let normal = Vector2::new(p1p2.y, -p1p2.x);+ let norm = normal.length();+ let normalized = if norm > 0.0 {+ normal / norm+ } else {+ Vector2::ZERO+ };++ SegmentFacet {+ valid: norm != 0.0,+ normal: normalized,+ prev,+ next,+ pts: [p1, p2],+ visible_points: Vec::new(),+ }+ }++ pub fn can_be_seen_by(&self, point: usize, points: &[Vector2]) -> bool {+ let p0 = &points[self.pts[0]];+ let pt = &points[point];++ let _eps = crate::math::DEFAULT_EPSILON;++ (*pt - *p0).dot(self.normal) > _eps * 100.0+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/convex_hull3/convex_hull.rs b/renderer/third_party/parry3d/src/transformation/convex_hull3/convex_hull.rsnew file mode 100644index 0000000..e0667d4--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/convex_hull3/convex_hull.rs@@ -0,0 +1,541 @@+use super::InitialMesh;+use super::{ConvexHullError, TriangleFacet};+use crate::math::Vector3;+use crate::transformation::convex_hull_utils::indexed_support_point_nth;+use crate::transformation::convex_hull_utils::{indexed_support_point_id, normalize};+use crate::utils;+use alloc::{vec, vec::Vec};++/// Computes the convex hull of a set of 3D points.+///+/// The convex hull is the smallest convex shape that contains all input points.+/// Imagine wrapping a rubber band (2D) or shrink-wrap (3D) tightly around the points.+///+/// # Algorithm+///+/// Uses the **quickhull algorithm**, which is efficient for most inputs:+/// - Average case: O(n log n)+/// - Worst case: O(n²) for specially constructed inputs+///+/// # Returns+///+/// A tuple `(vertices, indices)`:+/// - **vertices**: The hull vertices (subset of input points, duplicates removed)+/// - **indices**: Triangle faces as triplets of vertex indices (CCW winding)+///+/// # Panics+///+/// Panics if the input is degenerate or the algorithm fails. For error handling,+/// use [`try_convex_hull`] instead.+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::convex_hull;+/// use parry3d::math::Vector;+///+/// // Vectors forming a tetrahedron+/// let points = vec![+/// Vector::ZERO,+/// Vector::new(1.0, 0.0, 0.0),+/// Vector::new(0.0, 1.0, 0.0),+/// Vector::new(0.0, 0.0, 1.0),+/// ];+///+/// let (vertices, indices) = convex_hull(&points);+///+/// // Hull has 4 vertices (all input points are on the hull)+/// assert_eq!(vertices.len(), 4);+///+/// // Hull has 4 triangular faces+/// assert_eq!(indices.len(), 4);+/// # }+/// ```+///+/// # See Also+///+/// - [`try_convex_hull`] - Returns `Result` instead of panicking+pub fn convex_hull(points: &[Vector3]) -> (Vec<Vector3>, Vec<[u32; 3]>) {+ try_convex_hull(points).unwrap()+}++/// Computes the convex hull of a set of 3D points, with error handling.+///+/// This is the safe version of [`convex_hull`] that returns a `Result` instead+/// of panicking on degenerate inputs.+///+/// # Arguments+///+/// * `points` - The input points (must have at least 3 points)+///+/// # Returns+///+/// * `Ok((vertices, indices))` - Successfully computed convex hull+/// * `Err(ConvexHullError::IncompleteInput)` - Less than 3 input points+/// * `Err(ConvexHullError::...)` - Other errors (degenerate geometry, numerical issues)+///+/// # Example+///+/// ```rust+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::try_convex_hull;+/// use parry3d::math::Vector;+///+/// // Valid input+/// let points = vec![+/// Vector::ZERO,+/// Vector::new(1.0, 0.0, 0.0),+/// Vector::new(0.0, 1.0, 0.0),+/// Vector::new(0.0, 0.0, 1.0),+/// ];+///+/// match try_convex_hull(&points) {+/// Ok((vertices, indices)) => {+/// println!("Hull: {} vertices, {} faces", vertices.len(), indices.len());+/// }+/// Err(e) => {+/// println!("Failed: {:?}", e);+/// }+/// }+///+/// // Degenerate input (too few points)+/// let bad_points = vec![Vector::ZERO, Vector::new(1.0, 0.0, 0.0)];+/// assert!(try_convex_hull(&bad_points).is_err());+/// # }+/// ```+pub fn try_convex_hull(+ points: &[Vector3],+) -> Result<(Vec<Vector3>, Vec<[u32; 3]>), ConvexHullError> {+ if points.len() < 3 {+ return Err(ConvexHullError::IncompleteInput);+ }++ // print_buildable_vec("input", points);++ let mut normalized_points = points.to_vec();+ let _ = normalize(&mut normalized_points[..]);++ let mut undecidable_points = Vec::new();+ let mut silhouette_loop_facets_and_idx = Vec::new();+ let mut removed_facets = Vec::new();++ let mut triangles;++ match super::try_get_initial_mesh(points, &mut normalized_points[..], &mut undecidable_points)?+ {+ InitialMesh::Facets(facets) => {+ triangles = facets;+ }+ InitialMesh::ResultMesh(vertices, indices) => {+ return Ok((vertices, indices));+ }+ }++ let mut i = 0;+ while i != triangles.len() {+ silhouette_loop_facets_and_idx.clear();++ if !triangles[i].valid || triangles[i].affinely_dependent {+ i += 1;+ continue;+ }++ // TODO: use triangles[i].furthest_point instead.+ let pt_id = indexed_support_point_id(+ triangles[i].normal,+ &normalized_points[..],+ triangles[i].visible_points[..].iter().copied(),+ );++ if let Some(point) = pt_id {+ triangles[i].valid = false;++ removed_facets.clear();+ removed_facets.push(i);++ for j in 0usize..3 {+ // println!(">> loop;");+ compute_silhouette(+ triangles[i].adj[j],+ triangles[i].indirect_adj_id[j],+ point,+ &mut silhouette_loop_facets_and_idx,+ &normalized_points[..],+ &mut removed_facets,+ &mut triangles[..],+ );+ }++ // In some degenerate cases (because of float rounding problems), the silhouette may:+ // 1. Contain self-intersections (i.e. a single vertex is used by more than two edges).+ // 2. Contain multiple disjoint (but nested) loops.+ fix_silhouette_topology(+ &normalized_points,+ &mut silhouette_loop_facets_and_idx,+ &mut removed_facets,+ &mut triangles[..],+ )?;++ // Check that the silhouette is valid.+ // TODO: remove this debug code.+ // {+ // for (facet, id) in &silhouette_loop_facets_and_idx {+ // assert!(triangles[*facet].valid);+ // assert!(!triangles[triangles[*facet].adj[*id]].valid);+ // }+ // }++ if silhouette_loop_facets_and_idx.is_empty() {+ // Due to inaccuracies, the silhouette could not be computed+ // (the point seems to be visible from… every triangle).+ let mut any_valid = false;+ for triangle in &triangles[i + 1..] {+ if triangle.valid && !triangle.affinely_dependent {+ any_valid = true;+ }+ }++ if any_valid {+ return Err(ConvexHullError::InternalError(+ "Internal error: exiting an unfinished work.",+ ));+ }++ // TODO: this is very harsh.+ triangles[i].valid = true;+ break;+ }++ attach_and_push_facets(+ &silhouette_loop_facets_and_idx[..],+ point,+ &normalized_points[..],+ &mut triangles,+ &removed_facets[..],+ &mut undecidable_points,+ );++ // println!("Verifying facets at iteration: {}, k: {}", i, k);+ // for i in 0..triangles.len() {+ // if triangles[i].valid {+ // super::check_facet_links(i, &triangles[..]);+ // }+ // }+ }++ i += 1;+ }++ let mut idx = Vec::new();++ for facet in triangles.iter() {+ if facet.valid {+ idx.push([+ facet.pts[0] as u32,+ facet.pts[1] as u32,+ facet.pts[2] as u32,+ ]);+ }+ }++ let mut points = points.to_vec();+ utils::remove_unused_points(&mut points, &mut idx[..]);+ // super::check_convex_hull(&points, &idx);++ Ok((points, idx))+}++fn compute_silhouette(+ facet: usize,+ indirect_id: usize,+ point: usize,+ out_facets_and_idx: &mut Vec<(usize, usize)>,+ points: &[Vector3],+ removed_facets: &mut Vec<usize>,+ triangles: &mut [TriangleFacet],+) {+ if triangles[facet].valid {+ if !triangles[facet].order_independent_can_be_seen_by_point(point, points) {+ // println!("triangles: {}, valid: true, keep: true", facet);+ // println!(+ // "Taking edge: [{}, {}]",+ // triangles[facet].second_point_from_edge(indirect_id),+ // triangles[facet].first_point_from_edge(indirect_id)+ // );+ out_facets_and_idx.push((facet, indirect_id));+ } else {+ triangles[facet].valid = false; // The facet must be removed from the convex hull.+ removed_facets.push(facet);+ // println!("triangles: {}, valid: true, keep: false", facet);++ compute_silhouette(+ triangles[facet].adj[(indirect_id + 1) % 3],+ triangles[facet].indirect_adj_id[(indirect_id + 1) % 3],+ point,+ out_facets_and_idx,+ points,+ removed_facets,+ triangles,+ );++ compute_silhouette(+ triangles[facet].adj[(indirect_id + 2) % 3],+ triangles[facet].indirect_adj_id[(indirect_id + 2) % 3],+ point,+ out_facets_and_idx,+ points,+ removed_facets,+ triangles,+ );+ }+ } else {+ // println!("triangles: {}, valid: false, keep: false", facet);+ }+}++fn fix_silhouette_topology(+ points: &[Vector3],+ out_facets_and_idx: &mut Vec<(usize, usize)>,+ removed_facets: &mut Vec<usize>,+ triangles: &mut [TriangleFacet],+) -> Result<(), ConvexHullError> {+ // TODO: don't allocate this everytime.+ let mut workspace = vec![0; points.len()];+ let mut needs_fixing = false;++ // NOTE: we wore with the second_point_from_edge instead+ // of the first one, because when we traverse the silhouette+ // we see the second edge point before the first.+ for (facet, adj_id) in &*out_facets_and_idx {+ let p = triangles[*facet].second_point_from_edge(*adj_id);+ workspace[p] += 1;++ if workspace[p] > 1 {+ needs_fixing = true;+ }+ }++ // We detected a topological problem, i.e., we have+ // multiple loops.+ if needs_fixing {+ // First, we need to know which loop is the one we+ // need to keep.+ let mut loop_start = 0;+ for (facet, adj_id) in &*out_facets_and_idx {+ let p1 = points[triangles[*facet].second_point_from_edge(*adj_id)];+ let p2 = points[triangles[*facet].first_point_from_edge(*adj_id)];+ let supp = indexed_support_point_nth(+ p2 - p1,+ points,+ out_facets_and_idx+ .iter()+ .map(|(f, ai)| triangles[*f].second_point_from_edge(*ai)),+ )+ .ok_or(ConvexHullError::MissingSupportPoint)?;+ let selected = &out_facets_and_idx[supp];+ if workspace[triangles[selected.0].second_point_from_edge(selected.1)] == 1 {+ // This is a valid point to start with.+ loop_start = supp;+ break;+ }+ }++ let mut removing = None;+ let old_facets_and_idx = core::mem::take(out_facets_and_idx);++ for i in 0..old_facets_and_idx.len() {+ let facet_id = (loop_start + i) % old_facets_and_idx.len();+ let (facet, adj_id) = old_facets_and_idx[facet_id];++ match removing {+ Some(p) => {+ let p1 = triangles[facet].second_point_from_edge(adj_id);+ if p == p1 {+ removing = None;+ }+ }+ _ => {+ let p1 = triangles[facet].second_point_from_edge(adj_id);+ if workspace[p1] > 1 {+ removing = Some(p1);+ }+ }+ }++ if removing.is_some() {+ if triangles[facet].valid {+ triangles[facet].valid = false;+ removed_facets.push(facet);+ }+ } else {+ out_facets_and_idx.push((facet, adj_id));+ }++ // // Debug+ // {+ // let p1 = triangles[facet].second_point_from_edge(adj_id);+ // let p2 = triangles[facet].first_point_from_edge(adj_id);+ // if removing.is_some() {+ // print!("/{}, {}\\ ", p1, p2);+ // } else {+ // print!("[{}, {}] ", p1, p2);+ // }+ // }+ }++ // println!();+ }++ Ok(())+}++fn attach_and_push_facets(+ silhouette_loop_facets_and_idx: &[(usize, usize)],+ point: usize,+ points: &[Vector3],+ triangles: &mut Vec<TriangleFacet>,+ removed_facets: &[usize],+ undecidable: &mut Vec<usize>,+) {+ // The silhouette is built to be in CCW order.+ let mut new_facets = Vec::with_capacity(silhouette_loop_facets_and_idx.len());++ // Create new facets.+ let mut adj_facet: usize;+ let mut indirect_id: usize;++ for silhouette_loop_facets_and_id in silhouette_loop_facets_and_idx {+ adj_facet = silhouette_loop_facets_and_id.0;+ indirect_id = silhouette_loop_facets_and_id.1;++ // print!(+ // "[{}, {}] ",+ // triangles[adj_facet].second_point_from_edge(indirect_id),+ // triangles[adj_facet].first_point_from_edge(indirect_id)+ // );++ let facet = TriangleFacet::new(+ point,+ triangles[adj_facet].second_point_from_edge(indirect_id),+ triangles[adj_facet].first_point_from_edge(indirect_id),+ points,+ );+ new_facets.push(facet);+ }+ // println!();++ // Link the facets together.+ for i in 0..silhouette_loop_facets_and_idx.len() {+ let prev_facet = if i == 0 {+ triangles.len() + silhouette_loop_facets_and_idx.len() - 1+ } else {+ triangles.len() + i - 1+ };++ let (middle_facet, middle_id) = silhouette_loop_facets_and_idx[i];+ let next_facet = triangles.len() + (i + 1) % silhouette_loop_facets_and_idx.len();++ new_facets[i].set_facets_adjascency(prev_facet, middle_facet, next_facet, 2, middle_id, 0);+ assert!(!triangles[triangles[middle_facet].adj[middle_id]].valid); // Check that we are not overwriting a valid link.+ triangles[middle_facet].adj[middle_id] = triangles.len() + i; // The future id of curr_facet.+ triangles[middle_facet].indirect_adj_id[middle_id] = 1;+ }++ // Assign to each facets some of the points which can see it.+ // TODO: refactor this with the others.+ for curr_facet in removed_facets.iter() {+ for visible_point in triangles[*curr_facet].visible_points.iter() {+ if points[*visible_point] == points[point] {+ continue;+ }++ let mut furthest = usize::MAX;+ let mut furthest_dist = 0.0;++ for (i, curr_facet) in new_facets.iter_mut().enumerate() {+ if !curr_facet.affinely_dependent {+ let distance = curr_facet.distance_to_point(*visible_point, points);++ if distance > furthest_dist {+ furthest = i;+ furthest_dist = distance;+ }+ }+ }++ if furthest != usize::MAX && new_facets[furthest].can_see_point(*visible_point, points)+ {+ new_facets[furthest].add_visible_point(*visible_point, points);+ }++ // If none of the facet can be seen from the point, it is implicitly+ // deleted because it won't be referenced by any facet.+ }+ }++ // Try to assign collinear points to one of the new facets.+ let mut i = 0;++ while i != undecidable.len() {+ let mut furthest = usize::MAX;+ let mut furthest_dist = 0.0;+ let undecidable_point = undecidable[i];++ for (j, curr_facet) in new_facets.iter_mut().enumerate() {+ if curr_facet.can_see_point(undecidable_point, points) {+ let distance = curr_facet.distance_to_point(undecidable_point, points);++ if distance > furthest_dist {+ furthest = j;+ furthest_dist = distance;+ }+ }+ }++ if furthest != usize::MAX {+ new_facets[furthest].add_visible_point(undecidable_point, points);+ let _ = undecidable.swap_remove(i);+ } else {+ i += 1;+ }+ }++ // Push facets.+ // TODO: can we avoid the tmp vector `new_facets` ?+ triangles.append(&mut new_facets);+}++#[cfg(test)]+mod test {+ #[cfg(feature = "dim2")]+ use crate::math::Vector2;+ use crate::transformation;++ #[cfg(feature = "dim2")]+ #[test]+ fn test_simple_convex_hull() {+ let points = [+ Vector::new(4.723881f32, 3.597233),+ Vector::new(3.333363, 3.429991),+ Vector::new(3.137215, 2.812263),+ ];++ let chull = transformation::convex_hull(points.as_slice());++ assert!(chull.len() == 3);+ }++ #[cfg(feature = "dim3")]+ #[test]+ fn test_ball_convex_hull() {+ use crate::shape::Ball;++ // This triggered a failure to an affinely dependent facet.+ let (points, _) = Ball::new(0.4).to_trimesh(20, 20);+ let (vertices, _) = transformation::convex_hull(points.as_slice());++ // dummy test, we are just checking that the construction did not fail.+ assert!(vertices.len() == vertices.len());+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/convex_hull3/error.rs b/renderer/third_party/parry3d/src/transformation/convex_hull3/error.rsnew file mode 100644index 0000000..e8c83af--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/convex_hull3/error.rs@@ -0,0 +1,248 @@+/// Errors that can occur during convex hull computation.+///+/// When computing the convex hull of a set of points using [`convex_hull`] or [`try_convex_hull`],+/// various problems can arise due to invalid input data or numerical issues. This enum describes+/// all possible error conditions.+///+/// # Overview+///+/// Convex hull computation uses incremental algorithms that build the hull by adding points one at a time.+/// The algorithm can fail if the input is degenerate (too few points, collinear/coplanar points) or+/// contains invalid data (NaN values, duplicates).+///+/// # Common Causes and Solutions+///+/// ## Input Validation Issues+///+/// - **Too few points**: Need at least 4 non-coplanar points for 3D, or 3 non-collinear points for 2D+/// - **Invalid coordinates**: Check for NaN or infinite values in your point data+/// - **Duplicate points**: Remove duplicate points before computing the hull+/// - **Degenerate geometry**: Ensure points are not all collinear (2D) or coplanar (3D)+///+/// ## How to Handle Errors+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::{try_convex_hull, ConvexHullError};+/// use parry3d::math::Vector;+///+/// let points = vec![+/// Vector::ZERO,+/// Vector::new(1.0, 0.0, 0.0),+/// Vector::new(0.0, 1.0, 0.0),+/// Vector::new(0.0, 0.0, 1.0),+/// ];+///+/// match try_convex_hull(&points) {+/// Ok((vertices, indices)) => {+/// println!("Successfully computed hull with {} faces", indices.len());+/// }+/// Err(ConvexHullError::IncompleteInput) => {+/// println!("Not enough points provided (need at least 4 in 3D)");+/// }+/// Err(ConvexHullError::MissingSupportPoint) => {+/// println!("Vectors are invalid (NaN) or nearly coplanar");+/// // Try removing duplicate points or checking for degeneracies+/// }+/// Err(ConvexHullError::DuplicatePoints(i, j)) => {+/// println!("Vectors {} and {} are duplicates", i, j);+/// // Remove duplicates and try again+/// }+/// Err(err) => {+/// println!("Unexpected error: {}", err);+/// }+/// }+/// # }+/// ```+///+/// [`convex_hull`]: crate::transformation::convex_hull+/// [`try_convex_hull`]: crate::transformation::try_convex_hull+#[derive(thiserror::Error, Debug, PartialEq)]+pub enum ConvexHullError {+ /// An internal error occurred during convex hull computation.+ ///+ /// This indicates a bug in the convex hull algorithm itself. If you encounter this error,+ /// please report it as a bug with a minimal reproducible example.+ ///+ /// # Example+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim3", feature = "f32", feature = "alloc"))] {+ /// # use parry3d::transformation::{try_convex_hull, ConvexHullError};+ /// # use parry3d::math::Vector;+ /// # let points = vec![Vector::ZERO];+ /// match try_convex_hull(&points) {+ /// Err(ConvexHullError::InternalError(msg)) => {+ /// eprintln!("Bug in convex hull algorithm: {}", msg);+ /// // This should not happen - please report this!+ /// }+ /// _ => {}+ /// }+ /// # }+ /// ```+ #[error("Internal error: {0}")]+ InternalError(&'static str),++ /// The algorithm could not find a valid support point.+ ///+ /// This error occurs when:+ /// 1. The input contains points with NaN or infinite coordinates+ /// 2. All points are nearly collinear (in 2D) or coplanar (in 3D)+ /// 3. The numerical precision is insufficient to distinguish between points+ ///+ /// # Common Causes+ ///+ /// - **NaN values**: Check your input data for NaN coordinates+ /// - **Nearly flat geometry**: Vectors lie almost on a line (2D) or plane (3D)+ /// - **Numerical precision**: Vectors are too close together relative to floating-point precision+ ///+ // /// TODO: check why this doc-test is failing.+ // /// # How to Fix+ // ///+ // /// ```+ // /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ // /// use parry3d::transformation::try_convex_hull;+ // /// use parry3d::math::Vector;+ // ///+ // /// let points = vec![+ // /// Vector::ZERO,+ // /// Vector::new(1.0, 0.0, 0.0),+ // /// Vector::new(2.0, 0.0, 0.0), // Collinear!+ // /// ];+ // ///+ // /// // This will fail because points are collinear+ // /// assert!(try_convex_hull(&points).is_err());+ // ///+ // /// // Add a point out of the line+ // /// let mut fixed_points = points.clone();+ // /// fixed_points.push(Vector::new(0.0, 1.0, 0.0));+ // /// fixed_points.push(Vector::new(0.0, 0.0, 1.0));+ // ///+ // /// // Now it should work+ // /// assert!(try_convex_hull(&fixed_points).is_ok());+ // /// # }+ // /// ```+ #[error("Input points are either invalid (NaN) or are almost coplanar.")]+ MissingSupportPoint,++ /// Not enough points were provided to compute a convex hull.+ ///+ /// A convex hull requires:+ /// - **3D (dim3)**: At least 4 non-coplanar points to form a tetrahedron+ /// - **2D (dim2)**: At least 3 non-collinear points to form a triangle+ ///+ /// Providing fewer points than this minimum results in this error.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::{try_convex_hull, ConvexHullError};+ /// use parry3d::math::Vector;+ ///+ /// // Only 2 points - not enough for 3D hull+ /// let points = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// ];+ ///+ /// match try_convex_hull(&points) {+ /// Err(ConvexHullError::IncompleteInput) => {+ /// println!("Need at least 4 points for 3D convex hull");+ /// }+ /// _ => {}+ /// }+ /// # }+ /// ```+ #[error("Less than 3 points were given to the convex-hull algorithm.")]+ IncompleteInput,++ /// Internal error: reached an unreachable code path.+ ///+ /// This should never happen and indicates a serious bug in the implementation.+ /// If you encounter this, please report it with your input data.+ #[error("Internal error: unreachable code path")]+ Unreachable,++ /// A triangle in the hull was not properly constructed.+ ///+ /// This is an internal consistency error that indicates the algorithm failed to+ /// maintain the correct half-edge topology during hull construction.+ ///+ /// This is likely caused by numerical precision issues or edge cases in the input geometry.+ #[error("Detected unfinished triangle")]+ UnfinishedTriangle,++ /// Detected a T-junction in the hull topology.+ ///+ /// A T-junction occurs when an edge has more than two adjacent faces, which violates+ /// the manifold property required for a valid convex hull. This is an internal error+ /// that shouldn't occur with valid convex hull computation.+ ///+ /// The error reports:+ /// - `0`: The triangle index where the T-junction was detected+ /// - `1`, `2`: The vertex indices forming the problematic edge+ ///+ /// # Example+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim3", feature = "f32", feature = "alloc"))] {+ /// # use parry3d::transformation::{try_convex_hull, ConvexHullError};+ /// # use parry3d::math::Vector;+ /// # let points = vec![Vector::ZERO];+ /// match try_convex_hull(&points) {+ /// Err(ConvexHullError::TJunction(tri_id, v1, v2)) => {+ /// eprintln!("T-junction at triangle {} on edge ({}, {})", tri_id, v1, v2);+ /// }+ /// _ => {}+ /// }+ /// # }+ /// ```+ #[error("Detected t-junction for triangle {0}, edge: ({1}, {2})")]+ TJunction(usize, u32, u32),++ /// The input contains duplicate points at the same location.+ ///+ /// This error is raised during validation when two points have identical coordinates.+ /// Duplicate points can cause issues with the hull topology and should be removed+ /// before computing the hull.+ ///+ /// The error reports the indices of the two duplicate points.+ ///+ /// # How to Fix+ ///+ /// Remove duplicate points from your input data:+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::try_convex_hull;+ /// use parry3d::math::Vector;+ ///+ /// let points = vec![+ /// Vector::ZERO,+ /// Vector::new(1.0, 0.0, 0.0),+ /// Vector::new(0.0, 1.0, 0.0),+ /// Vector::new(0.0, 0.0, 1.0),+ /// Vector::ZERO, // Duplicate!+ /// ];+ ///+ /// // Remove duplicates (note: this is a simple example, not production code)+ /// fn remove_duplicates(points: Vec<Vector>) -> Vec<Vector> {+ /// let mut seen: Vec<Vector> = Vec::new();+ /// let mut result = Vec::new();+ /// for pt in points {+ /// if !seen.iter().any(|p| (*p - pt).length() < 1e-6) {+ /// seen.push(pt);+ /// result.push(pt);+ /// }+ /// }+ /// result+ /// }+ ///+ /// let unique_points = remove_duplicates(points);+ /// assert!(try_convex_hull(&unique_points).is_ok());+ /// # }+ /// ```+ #[error("Detected duplicate points {0} and {1}")]+ DuplicatePoints(usize, usize),+}diff --git a/renderer/third_party/parry3d/src/transformation/convex_hull3/initial_mesh.rs b/renderer/third_party/parry3d/src/transformation/convex_hull3/initial_mesh.rsnew file mode 100644index 0000000..08e8776--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/convex_hull3/initial_mesh.rs@@ -0,0 +1,248 @@+use super::{ConvexHullError, TriangleFacet};+use crate::math::{MatExt, Vector2, Vector3};+use crate::shape::Triangle;+use crate::transformation;+use crate::transformation::convex_hull_utils::support_point_id;+use crate::utils;+use alloc::{vec, vec::Vec};+use core::cmp::Ordering;++#[derive(Debug)]+pub enum InitialMesh {+ Facets(Vec<TriangleFacet>),+ ResultMesh(Vec<Vector3>, Vec<[u32; 3]>),+}++fn build_degenerate_mesh_point(point: Vector3) -> (Vec<Vector3>, Vec<[u32; 3]>) {+ let ta = [0u32; 3];+ let tb = [0u32; 3];++ (vec![point], vec![ta, tb])+}++fn build_degenerate_mesh_segment(+ dir: Vector3,+ points: &[Vector3],+) -> (Vec<Vector3>, Vec<[u32; 3]>) {+ let a = utils::point_cloud_support_point(dir, points);+ let b = utils::point_cloud_support_point(-dir, points);++ let ta = [0u32, 1, 0];+ let tb = [1u32, 0, 0];++ (vec![a, b], vec![ta, tb])+}++pub fn try_get_initial_mesh(+ original_points: &[Vector3],+ normalized_points: &mut [Vector3],+ undecidable: &mut Vec<usize>,+) -> Result<InitialMesh, ConvexHullError> {+ /*+ * Compute the eigenvectors to see if the input data live on a subspace.+ */+ let eigvec;+ let eigval;++ #[cfg(not(feature = "improved_fixed_point_support"))]+ {+ let cov_mat = utils::cov(normalized_points);+ let eig = cov_mat.symmetric_eigen();+ eigvec = eig.eigenvectors;+ eigval = eig.eigenvalues;+ }++ #[cfg(feature = "improved_fixed_point_support")]+ {+ use crate::math::{Matrix3, MatrixExt};+ eigvec = Matrix3::identity();+ eigval = Vector3::splat(1.0);+ }++ let mut eigpairs = [+ (eigvec.x_axis, eigval[0]),+ (eigvec.y_axis, eigval[1]),+ (eigvec.z_axis, eigval[2]),+ ];++ /*+ * Sort in decreasing order wrt. eigenvalues.+ */+ eigpairs.sort_by(|a, b| {+ if a.1 > b.1 {+ Ordering::Less // `Less` and `Greater` are reversed.+ } else if a.1 < b.1 {+ Ordering::Greater+ } else {+ Ordering::Equal+ }+ });++ /*+ * Count the dimension the data lives in.+ */+ let mut dimension = 0;+ while dimension < 3 {+ if relative_eq!(eigpairs[dimension].1, 0.0, epsilon = 1.0e-7) {+ break;+ }++ dimension += 1;+ }++ match dimension {+ 0 => {+ // The hull is a point.+ let (vtx, idx) = build_degenerate_mesh_point(original_points[0]);+ Ok(InitialMesh::ResultMesh(vtx, idx))+ }+ 1 => {+ // The hull is a segment.+ let (vtx, idx) = build_degenerate_mesh_segment(eigpairs[0].0, original_points);+ Ok(InitialMesh::ResultMesh(vtx, idx))+ }+ 2 => {+ // The hull is a triangle.+ // Project into the principal halfspace…+ let axis1 = eigpairs[0].0;+ let axis2 = eigpairs[1].0;++ let mut subspace_points = Vec::with_capacity(normalized_points.len());++ for point in normalized_points.iter() {+ subspace_points.push(Vector2::new(point.dot(axis1), point.dot(axis2)))+ }++ // … and compute the 2d convex hull.+ let idx = transformation::convex_hull2_idx(&subspace_points[..]);++ // Finalize the result, triangulating the polyline.+ let npoints = idx.len();+ let coords = idx.into_iter().map(|i| original_points[i]).collect();+ let mut triangles = Vec::with_capacity(npoints + npoints - 4);++ for id in 1u32..npoints as u32 - 1 {+ triangles.push([0, id, id + 1]);+ }++ // NOTE: We use a different starting point for the triangulation+ // of the bottom faces in order to avoid bad topology where+ // and edge would end be being shared by more than two triangles.+ for id in 0u32..npoints as u32 - 2 {+ let a = npoints as u32 - 1;+ triangles.push([a, id + 1, id]);+ }++ Ok(InitialMesh::ResultMesh(coords, triangles))+ }+ 3 => {+ // The hull is a polyhedron.+ // Find a initial triangle lying on the principal halfspace…+ let center = utils::center(normalized_points);++ // Get the maximum absolute value from the eigenvalues+ let max_eigval = {+ let ax = eigval.x.abs();+ let ay = eigval.y.abs();+ let az = eigval.z.abs();+ ax.max(ay).max(az)+ };++ for point in normalized_points.iter_mut() {+ *point = Vector3::from((*point - center) / max_eigval);+ }++ let p1 = support_point_id(eigpairs[0].0, normalized_points)+ .ok_or(ConvexHullError::MissingSupportPoint)?;+ let p2 = support_point_id(-eigpairs[0].0, normalized_points)+ .ok_or(ConvexHullError::MissingSupportPoint)?;++ let mut max_area = 0.0;+ let mut p3 = usize::MAX;++ for (i, point) in normalized_points.iter().enumerate() {+ let area =+ Triangle::new(normalized_points[p1], normalized_points[p2], *point).area();++ if area > max_area {+ max_area = area;+ p3 = i;+ }+ }++ if p3 == usize::MAX {+ Err(ConvexHullError::InternalError("no triangle found."))+ } else {+ // Build two facets with opposite normals+ let mut f1 = TriangleFacet::new(p1, p2, p3, normalized_points);+ let mut f2 = TriangleFacet::new(p2, p1, p3, normalized_points);++ // Link the facets together+ f1.set_facets_adjascency(1, 1, 1, 0, 2, 1);+ f2.set_facets_adjascency(0, 0, 0, 0, 2, 1);++ let mut facets = vec![f1, f2];++ // … and attribute visible points to each one of them.+ // TODO: refactor this with the two others.+ for point in 0..normalized_points.len() {+ if normalized_points[point] == normalized_points[p1]+ || normalized_points[point] == normalized_points[p2]+ || normalized_points[point] == normalized_points[p3]+ {+ continue;+ }++ let mut furthest = usize::MAX;+ let mut furthest_dist = 0.0;++ for (i, curr_facet) in facets.iter().enumerate() {+ if curr_facet.can_see_point(point, normalized_points) {+ let distance = curr_facet.distance_to_point(point, normalized_points);++ if distance > furthest_dist {+ furthest = i;+ furthest_dist = distance;+ }+ }+ }++ if furthest != usize::MAX {+ facets[furthest].add_visible_point(point, normalized_points);+ } else {+ undecidable.push(point);+ }++ // If none of the facet can be seen from the point, it is naturally deleted.+ }++ super::check_facet_links(0, &facets[..]);+ super::check_facet_links(1, &facets[..]);++ Ok(InitialMesh::Facets(facets))+ }+ }+ _ => Err(ConvexHullError::Unreachable),+ }+}++#[cfg(test)]+mod tests {+ #[test]+ #[cfg(feature = "f32")]+ fn try_get_initial_mesh_should_fail_for_missing_support_points() {+ use super::*;+ use crate::math::Vector;+ use crate::transformation::try_convex_hull;++ let point_cloud = vec![+ Vector::new(103.05024, 303.44974, 106.125),+ Vector::new(103.21692, 303.44974, 106.125015),+ Vector::new(104.16538, 303.44974, 106.125),+ Vector::new(106.55025, 303.44974, 106.125),+ Vector::new(106.55043, 303.44974, 106.125),+ ];+ let result = try_convex_hull(&point_cloud);+ assert!(result.is_ok());+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/convex_hull3/mod.rs b/renderer/third_party/parry3d/src/transformation/convex_hull3/mod.rsnew file mode 100644index 0000000..9a87450--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/convex_hull3/mod.rs@@ -0,0 +1,13 @@+pub use self::error::ConvexHullError;+use self::initial_mesh::{try_get_initial_mesh, InitialMesh};+use self::triangle_facet::TriangleFacet;+use self::validation::check_facet_links;+pub use convex_hull::{convex_hull, try_convex_hull};+#[cfg(feature = "std")]+pub use validation::check_convex_hull;++mod convex_hull;+mod error;+mod initial_mesh;+mod triangle_facet;+mod validation;diff --git a/renderer/third_party/parry3d/src/transformation/convex_hull3/triangle_facet.rs b/renderer/third_party/parry3d/src/transformation/convex_hull3/triangle_facet.rsnew file mode 100644index 0000000..5524918--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/convex_hull3/triangle_facet.rs@@ -0,0 +1,118 @@+use crate::math::{Real, Vector3};+use crate::shape::Triangle;+use alloc::vec::Vec;+use num::Bounded;++#[derive(Debug)]+pub struct TriangleFacet {+ pub valid: bool,+ pub affinely_dependent: bool,+ pub normal: Vector3,+ pub adj: [usize; 3],+ pub indirect_adj_id: [usize; 3],+ pub pts: [usize; 3],+ pub visible_points: Vec<usize>,+ pub furthest_point: usize,+ pub furthest_distance: Real,+}++impl TriangleFacet {+ pub fn new(p1: usize, p2: usize, p3: usize, points: &[Vector3]) -> TriangleFacet {+ let p1p2 = points[p2] - points[p1];+ let p1p3 = points[p3] - points[p1];++ let normal = p1p2.cross(p1p3).normalize();++ TriangleFacet {+ valid: true,+ affinely_dependent: Triangle::new(points[p1], points[p2], points[p3])+ .is_affinely_dependent(),+ normal,+ adj: [0, 0, 0],+ indirect_adj_id: [0, 0, 0],+ pts: [p1, p2, p3],+ visible_points: Vec::new(),+ furthest_point: Bounded::max_value(),+ furthest_distance: 0.0,+ }+ }++ pub fn add_visible_point(&mut self, pid: usize, points: &[Vector3]) {+ let distance = self.distance_to_point(pid, points);+ assert!(distance > crate::math::DEFAULT_EPSILON);++ if distance > self.furthest_distance {+ self.furthest_distance = distance;+ self.furthest_point = pid;+ }++ self.visible_points.push(pid);+ }++ pub fn distance_to_point(&self, point: usize, points: &[Vector3]) -> Real {+ self.normal.dot(points[point] - points[self.pts[0]])+ }++ pub fn set_facets_adjascency(+ &mut self,+ adj1: usize,+ adj2: usize,+ adj3: usize,+ id_adj1: usize,+ id_adj2: usize,+ id_adj3: usize,+ ) {+ self.indirect_adj_id[0] = id_adj1;+ self.indirect_adj_id[1] = id_adj2;+ self.indirect_adj_id[2] = id_adj3;++ self.adj[0] = adj1;+ self.adj[1] = adj2;+ self.adj[2] = adj3;+ }++ pub fn first_point_from_edge(&self, id: usize) -> usize {+ self.pts[id]+ }++ pub fn second_point_from_edge(&self, id: usize) -> usize {+ self.pts[(id + 1) % 3]+ }++ pub fn can_see_point(&self, point: usize, points: &[Vector3]) -> bool {+ // An affinely-dependent triangle cannot see any point.+ if self.affinely_dependent {+ return false;+ }++ let p0 = points[self.pts[0]];+ let pt = points[point];++ if (pt - p0).dot(self.normal) < crate::math::DEFAULT_EPSILON * 100.0 {+ return false;+ }++ true+ }++ // Check that a given point can see this triangle,+ // making sure that the order of the three indices of+ // this triangle don't affect the test result.+ pub fn order_independent_can_be_seen_by_point(&self, point: usize, points: &[Vector3]) -> bool {+ // An affinely-dependent triangle can be seen by any point.+ if self.affinely_dependent {+ return true;+ }++ for i in 0..3 {+ let p0 = points[self.pts[i]];+ let pt = points[point];++ if (pt - p0).dot(self.normal) >= 0.0 {+ return true;+ }+ }++ false+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/convex_hull3/validation.rs b/renderer/third_party/parry3d/src/transformation/convex_hull3/validation.rsnew file mode 100644index 0000000..ef16fe5--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/convex_hull3/validation.rs@@ -0,0 +1,105 @@+#[cfg(feature = "std")]+use super::ConvexHullError;+use super::TriangleFacet;+#[cfg(feature = "std")]+use crate::math::Vector3;++pub fn check_facet_links(ifacet: usize, facets: &[TriangleFacet]) {+ let facet = &facets[ifacet];++ for i in 0..3 {+ assert!(facets[facet.adj[i]].valid);+ }++ for i in 0..3 {+ let adj_facet = &facets[facet.adj[i]];++ assert_eq!(adj_facet.adj[facet.indirect_adj_id[i]], ifacet);+ assert_eq!(adj_facet.indirect_adj_id[facet.indirect_adj_id[i]], i);+ assert_eq!(+ adj_facet.first_point_from_edge(facet.indirect_adj_id[i]),+ facet.second_point_from_edge(i)+ );+ assert_eq!(+ adj_facet.second_point_from_edge(facet.indirect_adj_id[i]),+ facet.first_point_from_edge(i)+ );+ }+}++/// Checks if a convex-hull is properly formed.+#[cfg(feature = "std")]+pub fn check_convex_hull(+ points: &[Vector3],+ triangles: &[[u32; 3]],+) -> Result<(), ConvexHullError> {+ use crate::utils::hashmap::{Entry, HashMap};+ use crate::utils::SortedPair;+ let mut edges = HashMap::default();++ struct EdgeData {+ adjacent_triangles: [usize; 2],+ }++ // println!(+ // "Investigating with {} triangles, and {} points.",+ // triangles.len(),+ // points.len()+ // );+ // print_buildable_vec("vertices", points);+ // print_buildable_vec("indices", triangles);++ for i in 0..points.len() {+ for j in i + 1..points.len() {+ if points[i] == points[j] {+ return Err(ConvexHullError::DuplicatePoints(i, j));+ }+ }+ }++ for (itri, tri) in triangles.iter().enumerate() {+ assert!(tri[0] != tri[1]);+ assert!(tri[0] != tri[2]);+ assert!(tri[2] != tri[1]);++ for i in 0..3 {+ let ivtx1 = tri[i as usize];+ let ivtx2 = tri[(i as usize + 1) % 3];+ let edge_key = SortedPair::new(ivtx1, ivtx2);++ match edges.entry(edge_key) {+ Entry::Vacant(e) => {+ let _ = e.insert(EdgeData {+ adjacent_triangles: [itri, usize::MAX],+ });+ }+ Entry::Occupied(mut e) => {+ if e.get().adjacent_triangles[1] != usize::MAX {+ return Err(ConvexHullError::TJunction(itri, ivtx1, ivtx2));+ }++ e.get_mut().adjacent_triangles[1] = itri;+ }+ }+ }+ }++ for edge in &edges {+ if edge.1.adjacent_triangles[1] == usize::MAX {+ return Err(ConvexHullError::UnfinishedTriangle);+ }+ }++ // Check Euler characteristic.+ assert_eq!(points.len() + triangles.len() - edges.len(), 2);++ Ok(())+}++// fn print_buildable_vec<T: core::fmt::Display + na::Scalar>(desc: &str, elts: &[Vector3<T>]) {+// print!("let {} = vec![", desc);+// for elt in elts {+// print!("Vector::new({},{},{}),", elt.x, elt.y, elt.z);+// }+// println!("];")+// }diff --git a/renderer/third_party/parry3d/src/transformation/convex_hull_utils.rs b/renderer/third_party/parry3d/src/transformation/convex_hull_utils.rsnew file mode 100644index 0000000..87af324--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/convex_hull_utils.rs@@ -0,0 +1,237 @@+#[cfg(feature = "dim3")]+use crate::math::{Real, Vector};++/// Returns the index of the support point of a list of points.+///+/// The support point is the point that extends furthest in the given direction.+/// This is a fundamental operation used in convex hull algorithms and collision+/// detection (especially GJK/EPA algorithms).+///+/// # Arguments+/// * `direction` - The direction vector to test against+/// * `points` - A slice of points to search+///+/// # Returns+/// * `Some(index)` - Index of the support point (furthest in the given direction)+/// * `None` - If the points slice is empty+///+/// # Example+///+/// ```ignore+/// # // This is a pub(crate) function. Can't really run it.+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::convex_hull_utils::support_point_id;+/// use parry3d::na::{Vector3, Vector3};+///+/// let points = vec![+/// Vector::ZERO,+/// Vector::new(1.0, 0.0, 0.0),+/// Vector::new(0.0, 1.0, 0.0),+/// Vector::new(0.0, 0.0, 1.0),+/// ];+///+/// // Find point furthest in the positive X direction+/// let dir = Vector::new(1.0, 0.0, 0.0);+/// let support_id = support_point_id(&dir, &points);+/// assert_eq!(support_id, Some(1)); // Vector at (1, 0, 0)+///+/// // Find point furthest in the positive Y direction+/// let dir = Vector::new(0.0, 1.0, 0.0);+/// let support_id = support_point_id(&dir, &points);+/// assert_eq!(support_id, Some(2)); // Vector at (0, 1, 0)+/// # }+/// ```+#[cfg(feature = "dim3")]+pub fn support_point_id(direction: Vector, points: &[Vector]) -> Option<usize> {+ let mut argmax = None;+ let mut max = -Real::MAX;++ for (id, pt) in points.iter().enumerate() {+ let dot = direction.dot(*pt);++ if dot > max {+ argmax = Some(id);+ max = dot;+ }+ }++ argmax+}++/// Returns the index of the support point of an indexed list of points.+///+/// This is similar to [`support_point_id`], but only considers points at the indices+/// provided by the iterator. This is useful when you want to find the support point+/// within a subset of points without creating a new array.+///+/// # Arguments+/// * `direction` - The direction vector to test against+/// * `points` - The full array of points+/// * `idx` - Iterator yielding indices of points to consider+///+/// # Returns+/// * `Some(index)` - Index into the original `points` array of the support point+/// * `None` - If the iterator is empty+///+/// # Example+///+/// ```ignore+/// # // This is a pub(crate) function. Can't really run it.+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::convex_hull_utils::indexed_support_point_id;+/// use parry3d::na::{Vector3, Vector3};+///+/// let points = vec![+/// Vector::ZERO,+/// Vector::new(1.0, 0.0, 0.0),+/// Vector::new(2.0, 0.0, 0.0),+/// Vector::new(0.0, 1.0, 0.0),+/// ];+///+/// // Only consider points at indices 0, 1, and 3 (skip index 2)+/// let subset = vec![0, 1, 3];+/// let dir = Vector::new(1.0, 0.0, 0.0);+///+/// let support_id = indexed_support_point_id(&dir, &points, subset.into_iter());+/// // Returns 1 (not 2, since we skipped that index)+/// assert_eq!(support_id, Some(1));+/// # }+/// ```+#[cfg(feature = "dim3")]+pub fn indexed_support_point_id<I>(direction: Vector, points: &[Vector], idx: I) -> Option<usize>+where+ I: Iterator<Item = usize>,+{+ let mut argmax = None;+ let mut max = -Real::MAX;++ for i in idx.into_iter() {+ let dot = direction.dot(points[i]);++ if dot > max {+ argmax = Some(i);+ max = dot;+ }+ }++ argmax+}++/// Returns the position in the iterator where the support point is found.+///+/// This is similar to [`indexed_support_point_id`], but returns the position within+/// the iterator rather than the index in the original points array. In other words,+/// if the iterator yields indices `[5, 7, 2, 9]` and the support point is at index 2,+/// this function returns `Some(2)` (the 3rd position in the iterator), not `Some(2)`.+///+/// # Arguments+/// * `direction` - The direction vector to test against+/// * `points` - The full array of points+/// * `idx` - Iterator yielding indices of points to consider+///+/// # Returns+/// * `Some(n)` - The `n`th element of the iterator corresponds to the support point+/// * `None` - If the iterator is empty+///+/// # Example+///+/// ```ignore+/// # // This is a pub(crate) function. Can’t really run it.+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::convex_hull_utils::indexed_support_point_nth;+/// use parry3d::na::{Vector3, Vector3};+///+/// let points = vec![+/// Vector::ZERO, // index 0+/// Vector::new(1.0, 0.0, 0.0), // index 1+/// Vector::new(5.0, 0.0, 0.0), // index 2+/// Vector::new(0.0, 1.0, 0.0), // index 3+/// ];+///+/// // Consider points at indices [3, 0, 2, 1]+/// let indices = vec![3, 0, 2, 1];+/// let dir = Vector::new(1.0, 0.0, 0.0);+///+/// let nth = indexed_support_point_nth(&dir, &points, indices.into_iter());+/// // The support point is at original index 2, which is position 2 in our iterator+/// assert_eq!(nth, Some(2));+/// # }+/// ```+#[cfg(feature = "dim3")] // We only use this in 3D right now.+pub fn indexed_support_point_nth<I>(direction: Vector, points: &[Vector], idx: I) -> Option<usize>+where+ I: Iterator<Item = usize>,+{+ let mut argmax = None;+ let mut max = -Real::MAX;++ for (k, i) in idx.into_iter().enumerate() {+ let dot = direction.dot(points[i]);++ if dot > max {+ argmax = Some(k);+ max = dot;+ }+ }++ argmax+}++/// Normalizes a point cloud by centering and scaling it to fit within a unit cube.+///+/// This function computes the axis-aligned bounding box (AABB) of the input points,+/// then translates all points so they're centered at the origin, and scales them+/// so the bounding box diagonal has length 1. This normalization is useful for+/// improving numerical stability in geometric algorithms like convex hull computation.+///+/// The transformation is reversible using the returned center and scale values.+///+/// # Arguments+/// * `coords` - Mutable slice of points to normalize in-place+///+/// # Returns+/// A tuple `(center, scale)` where:+/// * `center` - The original center point of the AABB (before normalization)+/// * `scale` - The original AABB diagonal length (before normalization)+///+/// To reverse the transformation: `original_point = normalized_point * scale + center`+///+/// # Example+///+/// ```ignore+/// # // This is a pub(crate) function. Can’t really run it.+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::convex_hull_utils::normalize;+/// use parry3d::math::Vector;+///+/// let mut points = vec![+/// Vector::new(10.0, 10.0, 10.0),+/// Vector::new(20.0, 20.0, 20.0),+/// Vector::new(15.0, 15.0, 15.0),+/// ];+///+/// let (center, scale) = normalize(&mut points);+///+/// // Vectors are now centered around origin and scaled+/// // The AABB diagonal is now approximately 1.0+/// println!("Original center: {:?}", center);+/// println!("Original scale: {}", scale);+///+/// // To recover original points:+/// for p in &mut points {+/// *p = *p * scale + center;+/// }+/// # }+/// ```+#[cfg(feature = "dim3")]+pub fn normalize(coords: &mut [Vector]) -> (Vector, Real) {+ let aabb = crate::bounding_volume::details::local_point_cloud_aabb_ref(&*coords);+ let diag = aabb.mins.distance(aabb.maxs);+ let center = aabb.center();++ for c in coords.iter_mut() {+ *c = (*c - center) / diag;+ }++ (center, diag)+}diff --git a/renderer/third_party/parry3d/src/transformation/ear_clipping.rs b/renderer/third_party/parry3d/src/transformation/ear_clipping.rsnew file mode 100644index 0000000..acde3c6--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/ear_clipping.rs@@ -0,0 +1,222 @@+//! Ear-clipping algorithm for creating a triangle mesh from a simple polygon.+//! Based on <https://github.com/ivanfratric/polypartition>, contributed by embotech AG.++use crate::{+ math::{Real, Vector},+ utils::point_in_triangle::{corner_direction, is_point_in_triangle, Orientation},+};+use alloc::{vec, vec::Vec};++/// The information stored for each vertex in the ear clipping algorithm.+#[derive(Clone, Default)]+struct VertexInfo {+ /// Whether the vertex is still active i.e. it has not been clipped yet.+ is_active: bool,+ /// Whether the vertex is the tip of an ear and should be clipped.+ is_ear: bool,+ /// How small the angle of the ear is. Ears with a smaller angle are clipped first.+ pointiness: Real,+ /// The index of the previous vertex.+ p_prev: usize,+ /// The index of the next vertex.+ p_next: usize,+}++/// Updates the fields `pointiness` and `is_ear` for a given vertex index.+fn update_vertex(idx: usize, vertex_info: &mut VertexInfo, points: &[Vector]) -> bool {+ // Get the point and its neighbors.+ let p = points[idx];+ let p1 = points[vertex_info.p_prev];+ let p3 = points[vertex_info.p_next];++ // Get the pointiness.+ let vec1 = (p1 - p).normalize();+ let vec3 = (p3 - p).normalize();+ vertex_info.pointiness = vec1.dot(vec3);+ if vertex_info.pointiness.is_nan() {+ return false;+ }++ // A point is considered an ear when it is convex and no other points are+ // inside the triangle spanned by it and its two neighbors.+ let mut error = false;+ vertex_info.is_ear = corner_direction(p1, p, p3) == Orientation::Ccw+ && (0..points.len())+ .filter(|&i| i != vertex_info.p_prev && i != idx && i != vertex_info.p_next)+ .all(|i| {+ if let Some(is) = is_point_in_triangle(points[i], p1, p, p3) {+ !is+ } else {+ error = true;+ true+ }+ });+ !error+}++/// Ear clipping triangulation algorithm.+pub(crate) fn triangulate_ear_clipping(vertices: &[Vector]) -> Option<Vec<[u32; 3]>> {+ let n_vertices = vertices.len();++ // Create a new vector to hold the information about vertices.+ let mut vertex_info = vec![VertexInfo::default(); n_vertices];++ // Initialize information for each vertex.+ let success = vertex_info.iter_mut().enumerate().all(|(i, info)| {+ info.is_active = true;+ info.p_prev = if i == 0 { n_vertices - 1 } else { i - 1 };+ info.p_next = if i == n_vertices - 1 { 0 } else { i + 1 };+ update_vertex(i, info, vertices)+ });+ if !success {+ return None;+ }++ // The output shapes+ let mut output_indices = Vec::new();++ for i in 0..n_vertices - 3 {+ // Search through all active ears and pick out the pointiest.+ let maybe_ear = vertex_info+ .iter()+ .enumerate()+ .filter(|(_, info)| info.is_active && info.is_ear)+ .max_by(|(_, info1), (_, info2)| {+ // The unwrap here is safe since we check for NaN when+ // we assign the pointiness value.+ info1.pointiness.partial_cmp(&info2.pointiness).unwrap()+ });++ // If we found an ear, clip it. Else the algorithm failed.+ let (ear_i, _) = maybe_ear?;++ // Deactivate the tip of the ear.+ vertex_info[ear_i].is_active = false;++ // Get the indices of the neighbors.+ let VertexInfo { p_prev, p_next, .. } = vertex_info[ear_i];++ // Extract the triangle that is the ear and add it to the index buffer.+ let triangle_points = [p_prev as u32, ear_i as u32, p_next as u32];+ output_indices.push(triangle_points);++ // Connect the remaining two vertices.+ vertex_info[p_prev].p_next = vertex_info[ear_i].p_next;+ vertex_info[p_next].p_prev = vertex_info[ear_i].p_prev;++ // Only three vertices remain and those are guaranteed to be convex so+ // there is no point in updating the remaining vertex information.+ if i == n_vertices - 4 {+ break;+ };++ // Update the info for the remaining two vertices.+ if !update_vertex(p_prev, &mut vertex_info[p_prev], vertices)+ || !update_vertex(p_next, &mut vertex_info[p_next], vertices)+ {+ return None;+ }+ }++ // Add the remaining triangle.+ if let Some((i, info)) = vertex_info+ .iter()+ .enumerate()+ .find(|(_, info)| info.is_active)+ {+ let triangle_points = [info.p_prev as u32, i as u32, info.p_next as u32];+ output_indices.push(triangle_points);+ }++ Some(output_indices)+}++// --- Unit tests ----------------------------------------------------------------------------+#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn triangle_ccw() {+ let vertices = vec![+ Vector::new(0., 0.),+ Vector::new(1., 0.),+ Vector::new(1., 1.),+ ];+ let triangles = triangulate_ear_clipping(&vertices);+ assert_eq!(triangles.unwrap(), vec![[2, 0, 1]]);+ }++ #[test]+ fn square_ccw() {+ let vertices = vec![+ Vector::new(0., 0.), // 0+ Vector::new(1., 0.), // 1+ Vector::new(1., 1.), // 2+ Vector::new(0., 1.), // 3+ ];+ let triangles = triangulate_ear_clipping(&vertices);+ assert_eq!(triangles.unwrap(), vec![[2, 3, 0], [2, 0, 1]]);+ }++ #[test]+ fn square_cw() {+ let vertices = vec![+ Vector::new(0., 1.), // 0+ Vector::new(1., 1.), // 1+ Vector::new(1., 0.), // 2+ Vector::new(0., 0.), // 3+ ];+ // This fails because we expect counter-clockwise ordering.+ let triangles = triangulate_ear_clipping(&vertices);+ assert!(triangles.is_none());+ }++ #[test]+ fn square_with_dent() {+ let vertices = vec![+ Vector::new(0., 0.), // 0+ Vector::new(1., 0.), // 1+ Vector::new(0.5, 0.5), // 2+ Vector::new(1., 1.), // 3+ Vector::new(0., 1.), // 4+ ];+ let triangles = triangulate_ear_clipping(&vertices);+ assert_eq!(triangles.unwrap(), vec![[2, 3, 4], [2, 4, 0], [2, 0, 1],]);+ }++ #[test]+ /// Checks the case where the origin is outside the shape.+ /// 4-----------------------3+ /// | |+ /// | |+ /// | 7-------0 |+ /// | | | |+ /// | | ° | |+ /// 5-------6 1-------2+ fn origin_outside_shape() {+ let vertices = vec![+ Vector::new(2.0, 2.0), // 0+ Vector::new(2.0, -2.0), // 1+ Vector::new(4.0, -2.0), // 2+ Vector::new(4.0, 4.0), // 3+ Vector::new(-4.0, 4.0), // 4+ Vector::new(-4.0, -2.0), // 5+ Vector::new(-2.0, -2.0), // 6+ Vector::new(-2.0, 2.0), // 7+ ];+ let triangles = triangulate_ear_clipping(&vertices).unwrap();++ assert_eq!(+ triangles,+ vec![+ [5, 6, 7],+ [4, 5, 7],+ [3, 4, 7],+ [3, 7, 0],+ [2, 3, 0],+ [2, 0, 1],+ ]+ );+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/hertel_mehlhorn.rs b/renderer/third_party/parry3d/src/transformation/hertel_mehlhorn.rsnew file mode 100644index 0000000..446f2a5--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/hertel_mehlhorn.rs@@ -0,0 +1,193 @@+//! Hertel-Mehlhorn algorithm for convex partitioning.+//! Based on <https://github.com/ivanfratric/polypartition>, contributed by embotech AG.++use alloc::vec::Vec;++use crate::math::Vector;+use crate::utils::point_in_triangle::{corner_direction, Orientation};++/// Checks if the counter-clockwise polygon `poly` has an edge going counter-clockwise from `p1` to `p2`.+/// Returns the edge point's indices in the second polygon. Returns `None` if none were found.+fn find_edge_index_in_polygon(p1: u32, p2: u32, indices: &[u32]) -> Option<(usize, usize)> {+ for i1 in 0..indices.len() {+ let i2 = (i1 + 1) % indices.len();+ if p1 == indices[i1] && p2 == indices[i2] {+ return Some((i1, i2));+ }+ }+ None+}++/// The Hertel-Mehlhorn algorithm.+///+/// Takes a set of triangles and returns a vector of convex polygons.+///+/// Time/Space complexity: O(n^2)/O(n) Where `n` is the number of points in the input polygon.+///+/// Quality of solution: This algorithm is a heuristic. At most four times the minimum number of convex+/// polygons is created. However, in practice it works much better than that and often returns the optimal+/// partitioning.+///+/// This algorithm is described in <https://people.mpi-inf.mpg.de/~mehlhorn/ftp/FastTriangulation.pdf>.+pub fn hertel_mehlhorn(vertices: &[Vector], indices: &[[u32; 3]]) -> Vec<Vec<Vector>> {+ hertel_mehlhorn_idx(vertices, indices)+ .into_iter()+ .map(|poly_indices| {+ poly_indices+ .into_iter()+ .map(|idx| vertices[idx as usize])+ .collect()+ })+ .collect()+}++/// Internal implementation of the Hertel-Mehlhorn algorithm that returns the polygon indices.+pub fn hertel_mehlhorn_idx(vertices: &[Vector], indices: &[[u32; 3]]) -> Vec<Vec<u32>> {+ let mut indices: Vec<Vec<u32>> = indices.iter().map(|indices| indices.to_vec()).collect();+ // Iterate over all polygons.+ let mut i_poly1 = 0;+ while i_poly1 < indices.len() {+ // Iterate over their points.+ let mut i11 = 0;+ while i11 < indices[i_poly1].len() {+ let polygon1 = &indices[i_poly1];++ // Get the next point index.+ let i12 = (i11 + 1) % polygon1.len();++ // Get the current edge.+ let edge_start = polygon1[i11];+ let edge_end = polygon1[i12];++ // Iterate over the remaining polygons and find an edge to the current polygon.+ let (i_poly2, edge_indices) = match indices+ .iter()+ .enumerate()+ .skip(i_poly1 + 1)+ .find_map(|(i, poly_indices)| {+ // Check if the edge is in the second polygon. Start and end are switched because+ // the edge direction is flipped in the second polygon.+ find_edge_index_in_polygon(edge_end, edge_start, poly_indices)+ .map(|edge_indices| (i, edge_indices))+ }) {+ Some(found) => found,+ None => {+ // Go to the next point if there was no common edge.+ i11 += 1;+ continue;+ }+ };++ // Check if the connections between the polygons are convex:+ let (i21, i22) = edge_indices;+ let polygon2 = &indices[i_poly2];++ // First connection:+ let i13 = (polygon1.len() + i11 - 1) % polygon1.len();+ let i23 = (i22 + 1) % polygon2.len();+ let p1 = vertices[polygon2[i23] as usize];+ let p2 = vertices[polygon1[i13] as usize];+ let p3 = vertices[polygon1[i11] as usize];+ // Go to the next point if this section isn't convex.+ if corner_direction(p1, p2, p3) == Orientation::Cw {+ i11 += 1;+ continue;+ }+ // Second connection:+ let i13 = (i12 + 1) % polygon1.len();+ let i23 = (polygon2.len() + i21 - 1) % polygon2.len();+ let p1 = vertices[polygon1[i13] as usize];+ let p2 = vertices[polygon2[i23] as usize];+ let p3 = vertices[polygon1[i12] as usize];+ // Go to the next point if this section isn't convex.+ if corner_direction(p1, p2, p3) == Orientation::Cw {+ i11 += 1;+ continue;+ }++ // Connection is convex, merge the polygons.+ let mut new_polygon = Vec::with_capacity(polygon1.len() + polygon2.len() - 2);+ new_polygon.extend(polygon1.iter().cycle().skip(i12).take(polygon1.len() - 1));+ new_polygon.extend(polygon2.iter().cycle().skip(i22).take(polygon2.len() - 1));++ // `swap_remove` is O(1) and safe here: it moves the last polygon into slot+ // `i_poly2 > i_poly1`, which the edge search above re-scans, so no merge+ // candidate is skipped — only the output order changes.+ let _ = indices.swap_remove(i_poly2);+ // Overwrite the first polygon with the new one.+ indices[i_poly1] = new_polygon;+ // Start from the first point.+ i11 = 0;+ }++ // Go to the next polygon.+ i_poly1 += 1;+ }++ indices+}++// --- Unit tests ----------------------------------------------------------------------------+#[cfg(test)]+mod tests {+ use super::hertel_mehlhorn_idx;+ use crate::math::Vector;+ use alloc::vec::Vec;++ /// Normalizes a decomposition for an order-insensitive comparison, since the+ /// algorithm's output order is unspecified.+ fn canonicalize(mut polygons: Vec<Vec<u32>>) -> Vec<Vec<u32>> {+ for poly in &mut polygons {+ let min_pos = (0..poly.len()).min_by_key(|&i| poly[i]).unwrap();+ poly.rotate_left(min_pos);+ }+ polygons.sort();+ polygons+ }++ #[test]+ fn origin_outside_shape() {+ // Expected result of convex decomposition:+ // 4-----------------------3+ // | . (2) . |+ // | . . |+ // | 7-------0 |+ // | (1) | | (3) |+ // | | ° | |+ // 5-------6 1-------2+ let vertices = vec![+ Vector::new(2.0, 2.0), // 0+ Vector::new(2.0, -2.0), // 1+ Vector::new(4.0, -2.0), // 2+ Vector::new(4.0, 4.0), // 3+ Vector::new(-4.0, 4.0), // 4+ Vector::new(-4.0, -2.0), // 5+ Vector::new(-2.0, -2.0), // 6+ Vector::new(-2.0, 2.0), // 7+ ];++ let triangles = [+ [5, 6, 7],+ [4, 5, 7],+ [3, 4, 7],+ [3, 7, 0],+ [2, 3, 0],+ [2, 0, 1],+ ];++ let indices = hertel_mehlhorn_idx(&vertices, &triangles);++ let expected_indices = vec![+ // (1)+ vec![5, 6, 7, 4],+ // (2)+ vec![3, 4, 7, 0],+ // (3)+ vec![2, 3, 0, 1],+ ];++ // Compare the decompositions as sets of (cyclic) polygons: the output order+ // is unspecified.+ assert_eq!(canonicalize(indices), canonicalize(expected_indices));+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/mesh_intersection/mesh_intersection.rs b/renderer/third_party/parry3d/src/transformation/mesh_intersection/mesh_intersection.rsnew file mode 100644index 0000000..4d271ab--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/mesh_intersection/mesh_intersection.rs@@ -0,0 +1,981 @@+use super::{MeshIntersectionError, TriangleTriangleIntersection};+use crate::bounding_volume::BoundingVolume;+use crate::math::{Pose, Real, Vector3};+use crate::partitioning::BvhNode;+use crate::query::point::point_query::PointQueryWithLocation;+use crate::query::PointQuery;+use crate::shape::{TriMesh, Triangle};+use crate::utils;+use crate::utils::hashmap::Entry;+use crate::utils::hashmap::HashMap;+use crate::utils::hashset::HashSet;+use alloc::collections::BTreeMap;+use alloc::{vec, vec::Vec};+use rstar::RTree;+use spade::{ConstrainedDelaunayTriangulation, InsertionError, Triangulation as _};+#[cfg(feature = "wavefront")]+use std::path::PathBuf;++/// A triangle with indices sorted in increasing order for deduplication in a hashmap.+///+/// Note that when converting a `[u32; 3]` into a `HashableTriangleIndices`, the result’s orientation+/// might not match the input’s.+#[derive(Copy, Clone, PartialEq, Eq, Hash)]+struct HashableTriangleIndices([u32; 3]);++impl From<[u32; 3]> for HashableTriangleIndices {+ fn from([a, b, c]: [u32; 3]) -> Self {+ let (sa, sb, sc) = utils::sort3(&a, &b, &c);+ HashableTriangleIndices([*sa, *sb, *sc])+ }+}++/// Metadata that specifies thresholds to use when making construction choices+/// in mesh intersections.+#[derive(Copy, Clone, PartialEq, Debug)]+pub struct MeshIntersectionTolerances {+ /// The smallest angle (in radians) that will be tolerated. A triangle with+ /// a smaller angle is considered degenerate and will be deleted.+ pub angle_epsilon: Real,+ /// The maximum distance at which two points are considered to overlap in space.+ /// If `||p1 - p2|| < global_insertion_epsilon` then p1 and p2 are considered+ /// to be the same point.+ pub global_insertion_epsilon: Real,+ /// A multiplier coefficient to scale [`Self::global_insertion_epsilon`] when checking for+ /// point duplication within a single triangle.+ ///+ /// Inside an individual triangle the distance at which two points are considered+ /// to be the same is `global_insertion_epsilon * local_insertion_epsilon_mod`.+ pub local_insertion_epsilon_scale: Real,+ /// Three points forming a triangle with an area smaller than this epsilon are considered collinear.+ pub collinearity_epsilon: Real,+}++impl Default for MeshIntersectionTolerances {+ fn default() -> Self {+ Self {+ #[expect(clippy::unnecessary_cast)]+ angle_epsilon: (0.005 as Real).to_radians(), // 0.005 degrees+ global_insertion_epsilon: Real::EPSILON * 100.0,+ local_insertion_epsilon_scale: 10.,+ collinearity_epsilon: Real::EPSILON * 100.0,+ }+ }+}++/// Computes the intersection of two meshes.+///+/// The meshes must be oriented, have their half-edge topology computed, and must not be self-intersecting.+/// The result mesh vertex coordinates are given in the local-space of `mesh1`.+pub fn intersect_meshes(+ pos1: &Pose,+ mesh1: &TriMesh,+ flip1: bool,+ pos2: &Pose,+ mesh2: &TriMesh,+ flip2: bool,+) -> Result<Option<TriMesh>, MeshIntersectionError> {+ intersect_meshes_with_tolerances(+ pos1,+ mesh1,+ flip1,+ pos2,+ mesh2,+ flip2,+ MeshIntersectionTolerances::default(),+ )+}++/// Similar to `intersect_meshes`.+///+/// It allows to specify epsilons for how the algorithm will behave.+/// See `MeshIntersectionTolerances` for details.+pub fn intersect_meshes_with_tolerances(+ pos1: &Pose,+ mesh1: &TriMesh,+ flip1: bool,+ pos2: &Pose,+ mesh2: &TriMesh,+ flip2: bool,+ tolerances: MeshIntersectionTolerances,+) -> Result<Option<TriMesh>, MeshIntersectionError> {+ if cfg!(debug_assertions) {+ mesh1.assert_half_edge_topology_is_valid();+ mesh2.assert_half_edge_topology_is_valid();+ }++ if mesh1.topology().is_none() || mesh2.topology().is_none() {+ return Err(MeshIntersectionError::MissingTopology);+ }++ if mesh1.pseudo_normals_if_oriented().is_none() || mesh2.pseudo_normals_if_oriented().is_none()+ {+ return Err(MeshIntersectionError::MissingPseudoNormals);+ }++ let pos12 = pos1.inv_mul(pos2);++ // 1: collect all the potential triangle-triangle intersections.+ let intersection_candidates: Vec<_> = mesh1+ .bvh()+ .leaf_pairs(mesh2.bvh(), |node1: &BvhNode, node2: &BvhNode| {+ let aabb1 = node1.aabb();+ let aabb2 = node2.aabb().transform_by(&pos12);+ aabb1.intersects(&aabb2)+ })+ .collect();++ let mut deleted_faces1: HashSet<u32> = HashSet::default();+ let mut deleted_faces2: HashSet<u32> = HashSet::default();+ let mut new_indices1 = vec![];+ let mut new_indices2 = vec![];++ // 2: Identify all triangles that do actually intersect.+ let mut intersections = vec![];+ for (fid1, fid2) in &intersection_candidates {+ let tri1 = mesh1.triangle(*fid1);+ let tri2 = mesh2.triangle(*fid2).transformed(&pos12);++ if super::triangle_triangle_intersection(&tri1, &tri2, tolerances.collinearity_epsilon)+ .is_some()+ {+ intersections.push((*fid1, *fid2));+ let _ = deleted_faces1.insert(*fid1);+ let _ = deleted_faces2.insert(*fid2);+ }+ }++ // 3: Grab all triangles that are inside the other mesh but do not intersect it.+ extract_connected_components(+ &pos12,+ mesh1,+ mesh2,+ flip2,+ &deleted_faces1,+ &mut new_indices1,+ );+ extract_connected_components(+ &pos12.inverse(),+ mesh2,+ mesh1,+ flip1,+ &deleted_faces2,+ &mut new_indices2,+ );++ // 4: Initialize a new mesh by inserting points into a set. Duplicate points should+ // hash to the same index.+ let mut point_set = RTree::<TreeVector, _>::new();+ let mut topology_indices = HashMap::default();+ {+ let mut insert_point = |position: Vector3| {+ insert_into_set(+ position,+ &mut point_set,+ tolerances.global_insertion_epsilon,+ ) as u32+ };+ // Add the inside vertices and triangles from mesh1+ for mut face in new_indices1 {+ if flip1 {+ face.swap(0, 1);+ }++ let idx = [+ insert_point(pos1 * mesh1.vertices()[face[0] as usize]),+ insert_point(pos1 * mesh1.vertices()[face[1] as usize]),+ insert_point(pos1 * mesh1.vertices()[face[2] as usize]),+ ];++ if !is_topologically_degenerate(idx) {+ insert_topology_indices(&mut topology_indices, idx);+ }+ }++ // Add the inside vertices and triangles from mesh2+ for mut face in new_indices2 {+ if flip2 {+ face.swap(0, 1);+ }+ let idx = [+ insert_point(pos2 * mesh2.vertices()[face[0] as usize]),+ insert_point(pos2 * mesh2.vertices()[face[1] as usize]),+ insert_point(pos2 * mesh2.vertices()[face[2] as usize]),+ ];++ if !is_topologically_degenerate(idx) {+ insert_topology_indices(&mut topology_indices, idx);+ }+ }+ }++ // 5: Associate constraint edges generated by a triangle-triangle intersection+ // to each intersecting triangle where they occur.+ let mut constraints1 = BTreeMap::<_, Vec<_>>::new();+ let mut constraints2 = BTreeMap::<_, Vec<_>>::new();+ for (fid1, fid2) in &intersections {+ let tri1 = mesh1.triangle(*fid1).transformed(pos1);+ let tri2 = mesh2.triangle(*fid2).transformed(pos2);++ let list1 = constraints1.entry(fid1).or_default();+ let list2 = constraints2.entry(fid2).or_default();++ let intersection =+ super::triangle_triangle_intersection(&tri1, &tri2, tolerances.collinearity_epsilon);+ if let Some(intersection) = intersection {+ match intersection {+ TriangleTriangleIntersection::Segment { a, b } => {+ // For both triangles, add the points in the intersection+ // and their associated edge to the set.+ // Note this necessarily introduces duplicate points to the+ // set that need to be filtered out.+ list1.push([a.p1, b.p1]);+ list2.push([a.p1, b.p1]);+ }+ TriangleTriangleIntersection::Polygon(polygon) => {+ for i in 0..polygon.len() {+ let a = polygon[i];+ let b = polygon[(i + 1) % polygon.len()];++ // Triangles overlap in space, so only one constraint is needed.+ list1.push([a.p1, b.p1]);+ }+ }+ }+ }+ }++ // 6: Collect all triangles that intersect and their associated constraint edges.+ // For each such triangle, compute a CDT of its constraints. For each face in this CDT,+ // if the face is contained in the opposite mesh, add it to the intersection mesh.+ merge_triangle_sets(+ mesh1,+ mesh2,+ &constraints1,+ pos1,+ pos2,+ flip1,+ flip2,+ &tolerances,+ &mut point_set,+ &mut topology_indices,+ )?;++ merge_triangle_sets(+ mesh2,+ mesh1,+ &constraints2,+ pos2,+ pos1,+ flip2,+ flip1,+ &tolerances,+ &mut point_set,+ &mut topology_indices,+ )?;++ // 7: Sort the output points by insertion order.+ let mut vertices: Vec<_> = point_set.iter().copied().collect();+ vertices.sort_by_key(|a| a.id);+ let vertices: Vec<_> = vertices.iter().map(|p| Vector3::from(p.point)).collect();++ if !topology_indices.is_empty() {+ Ok(Some(TriMesh::new(+ vertices,+ topology_indices.into_values().collect(),+ )?))+ } else {+ Ok(None)+ }+}++fn extract_connected_components(+ pos12: &Pose,+ mesh1: &TriMesh,+ mesh2: &TriMesh,+ flip2: bool,+ deleted_faces1: &HashSet<u32>,+ new_indices1: &mut Vec<[u32; 3]>,+) {+ let topo1 = mesh1.topology().unwrap();+ let mut visited: HashSet<u32> = HashSet::default();+ let mut to_visit = vec![];+ let mut visited_conn_comp = if let Some(cc) = mesh1.connected_components() {+ vec![false; cc.ranges.len()] // TODO: use a Vob instead?+ } else {+ vec![]+ };++ for face in deleted_faces1 {+ if let Some(cc) = mesh1.connected_components() {+ visited_conn_comp[cc.face_colors[*face as usize] as usize] = true;+ }++ let eid = topo1.faces[*face as usize].half_edge;+ let edge_a = &topo1.half_edges[eid as usize];+ let edge_b = &topo1.half_edges[edge_a.next as usize];+ let edge_c = &topo1.half_edges[edge_b.next as usize];+ let edges = [edge_a, edge_b, edge_c];++ for edge in edges {+ if let Some(twin) = topo1.half_edges.get(edge.twin as usize) {+ if !deleted_faces1.contains(&twin.face) {+ let tri1 = mesh1.triangle(twin.face);++ if flip2+ ^ mesh2.contains_local_point(pos12.inverse_transform_point(tri1.center()))+ {+ to_visit.push(twin.face);+ }+ }+ }+ }+ }++ // Propagate.+ while let Some(face) = to_visit.pop() {+ if !visited.insert(face) {+ continue; // Already visited.+ }++ new_indices1.push(mesh1.indices()[face as usize]);++ let eid = topo1.faces[face as usize].half_edge;+ let edge_a = &topo1.half_edges[eid as usize];+ let edge_b = &topo1.half_edges[edge_a.next as usize];+ let edge_c = &topo1.half_edges[edge_b.next as usize];+ let edges = [edge_a, edge_b, edge_c];++ for edge in edges {+ if let Some(twin) = topo1.half_edges.get(edge.twin as usize) {+ if !deleted_faces1.contains(&twin.face) {+ to_visit.push(twin.face);+ }+ }+ }+ }++ /*+ * Deal with connected components that don’t intersect the other mesh.+ */+ if let Some(cc) = mesh1.connected_components() {+ for (i, range) in cc.ranges.windows(2).enumerate() {+ if !visited_conn_comp[i] {+ // This connected component doesn’t intersect the second mesh.+ // Classify one of its face (the "representative face", can be any+ // face of the connected component) to determine+ // if the whole thing is inside or outside.+ let repr_face = cc.grouped_faces[range[0]];+ let repr_pt = mesh1.triangle(repr_face).center();+ let indices = mesh1.indices();++ if flip2 ^ mesh2.contains_local_point(pos12.inverse_transform_point(repr_pt)) {+ new_indices1.extend(+ cc.grouped_faces[range[0]..range[1]]+ .iter()+ .map(|fid| indices[*fid as usize]),+ )+ }+ }+ }+ } else if deleted_faces1.is_empty() {+ // Deal with the case where there is no intersection between the meshes.+ let repr_pt = mesh1.triangle(0).center();++ if flip2 ^ mesh2.contains_local_point(pos12.inverse_transform_point(repr_pt)) {+ new_indices1.extend_from_slice(mesh1.indices());+ }+ }+}++fn triangulate_constraints_and_merge_duplicates(+ tri: &Triangle,+ constraints: &[[Vector3; 2]],+ epsilon: Real,+) -> Result<+ (+ ConstrainedDelaunayTriangulation<spade::Point2<Real>>,+ Vec<Vector3>,+ ),+ InsertionError,+> {+ let mut constraints = constraints.to_vec();+ // Add the triangle points to the triangulation.+ let mut point_set = RTree::<TreeVector, _>::new();+ let _ = insert_into_set(tri.a, &mut point_set, epsilon);+ let _ = insert_into_set(tri.b, &mut point_set, epsilon);+ let _ = insert_into_set(tri.c, &mut point_set, epsilon);++ // Sometimes, points on the edge of a triangle are slightly off, and this makes+ // spade think that there is a super thin triangle. Project points close to an edge+ // onto the edge to get better results.+ let tri_vtx = tri.vertices();+ for point_pair in constraints.iter_mut() {+ let p1 = point_pair[0];+ let p2 = point_pair[1];++ for i in 0..3 {+ let q1 = tri_vtx[i];+ let q2 = tri_vtx[(i + 1) % 3];++ let proj1 = project_point_to_segment(p1, &[q1, q2]);+ if (p1 - proj1).length() < epsilon {+ point_pair[0] = Vector3::from(proj1);+ }++ let proj2 = project_point_to_segment(p2, &[q1, q2]);+ if (p2 - proj2).length() < epsilon {+ point_pair[1] = Vector3::from(proj2);+ }+ }+ }++ // Generate edge, taking care to merge duplicate vertices.+ let mut edges = Vec::new();+ for point_pair in constraints {+ let p1_id = insert_into_set(point_pair[0], &mut point_set, epsilon);+ let p2_id = insert_into_set(point_pair[1], &mut point_set, epsilon);++ if p1_id != p2_id {+ edges.push([p1_id, p2_id]);+ }+ }++ let mut points: Vec<_> = point_set.iter().cloned().collect();+ points.sort_by_key(|a| a.id);++ let tri_points = tri.vertices();+ let best_source = tri.angle_closest_to_90();+ let d1 = tri_points[(best_source + 2) % 3] - tri_points[(best_source + 1) % 3];+ let d2 = tri_points[best_source] - tri_points[(best_source + 1) % 3];+ let (e1, e2) = planar_gram_schmidt(d1, d2);++ let project = |p: Vector3| spade::Point2::new(e1.dot(p), e2.dot(p));++ // Project points into 2D and triangulate the resulting set.+ let planar_points: Vec<_> = points+ .iter()+ .copied()+ .map(|point| {+ let point_proj = project(point.point);+ utils::sanitize_spade_point(point_proj)+ })+ .collect();+ // NOTE: use the fallible `try_bulk_load_cdt` instead of `bulk_load_cdt`: the latter panics+ // when constraint edges overlap, which can legitimately happen for degenerate inputs+ // (e.g. co-planar triangles). Overlapping constraints are simply skipped.+ let cdt_triangulation =+ ConstrainedDelaunayTriangulation::try_bulk_load_cdt(planar_points, edges, |_conflict| {})?;+ debug_assert!(cdt_triangulation.vertices().len() == points.len());++ let points = points.into_iter().map(|p| Vector3::from(p.point)).collect();+ Ok((cdt_triangulation, points))+}++// We heavily recommend that this is left here in case one needs to debug the above code.+#[cfg(feature = "wavefront")]+fn _points_to_obj(mesh: &[Vector3], path: &PathBuf) {+ use std::io::Write;+ let mut file = std::fs::File::create(path).unwrap();++ for p in mesh {+ writeln!(file, "v {} {} {}", p.x, p.y, p.z).unwrap();+ }+}++// We heavily recommend that this is left here in case one needs to debug the above code.+#[cfg(feature = "wavefront")]+fn _points_and_edges_to_obj(mesh: &[Vector3], edges: &[[usize; 2]], path: &PathBuf) {+ use std::io::Write;+ let mut file = std::fs::File::create(path).unwrap();++ for p in mesh {+ writeln!(file, "v {} {} {}", p.x, p.y, p.z).unwrap();+ }++ for e in edges {+ writeln!(file, "l {} {}", e[0] + 1, e[1] + 1).unwrap();+ }+}++#[derive(Copy, Clone, PartialEq, Debug, Default)]+struct TreeVector {+ point: Vector3,+ id: usize,+}++impl rstar::Point for TreeVector {+ type Scalar = Real;+ const DIMENSIONS: usize = 3;++ fn generate(mut generator: impl FnMut(usize) -> Self::Scalar) -> Self {+ TreeVector {+ point: Vector3::new(generator(0), generator(1), generator(2)),+ id: usize::MAX,+ }+ }++ fn nth(&self, index: usize) -> Self::Scalar {+ self.point[index]+ }++ fn nth_mut(&mut self, index: usize) -> &mut Self::Scalar {+ &mut self.point[index]+ }+}++fn insert_into_set(position: Vector3, point_set: &mut RTree<TreeVector>, epsilon: Real) -> usize {+ let point_count = point_set.size();+ let point_to_insert = TreeVector {+ point: position,+ id: point_count,+ };++ match point_set.nearest_neighbor(point_to_insert) {+ Some(tree_point) if (tree_point.point - position).length_squared() <= epsilon => {+ tree_point.id+ }+ _ => {+ point_set.insert(point_to_insert);+ debug_assert!(point_set.size() == point_count + 1);+ point_count+ }+ }+}++fn smallest_angle(points: &[Vector3]) -> Real {+ let n = points.len();++ let mut worst_cos: Real = -2.0;+ for i in 0..points.len() {+ let d1 = (points[i] - points[(i + 1) % n]).normalize();+ let d2 = (points[(i + 2) % n] - points[(i + 1) % n]).normalize();++ let cos = d1.dot(d2);+ if cos > worst_cos {+ worst_cos = cos;+ }+ }++ worst_cos.acos()+}++fn planar_gram_schmidt(v1: Vector3, v2: Vector3) -> (Vector3, Vector3) {+ let u1 = v1;+ let u2 = v2 - (v2.dot(u1) / u1.length_squared()) * u1;++ let e1 = u1.normalize();+ let e2 = u2.normalize();++ (e1, e2)+}++fn project_point_to_segment(point: Vector3, segment: &[Vector3; 2]) -> Vector3 {+ let dir = segment[1] - segment[0];+ let local = point - segment[0];++ let norm = dir.length();+ // Restrict the result to the segment portion of the line.+ let coeff = (dir.dot(local) / norm).clamp(0., norm);++ segment[0] + coeff * dir.normalize()+}++/// No matter how smart we are about computing intersections. It is always possible+/// to create ultra thin triangles when a point lies on an edge of a triangle. These+/// are degenerate and need to be removed.+fn is_triangle_degenerate(+ triangle: &[Vector3; 3],+ epsilon_angle: Real,+ epsilon_distance: Real,+) -> bool {+ if smallest_angle(triangle) < epsilon_angle {+ return true;+ }++ for i in 0..3 {+ let (dir, dist) = (triangle[(i + 1) % 3] - triangle[(i + 2) % 3]).normalize_and_length();+ if dist < epsilon_distance {+ return true;+ }++ let proj = triangle[(i + 2) % 3] + (triangle[i] - triangle[(i + 2) % 3]).dot(dir) * dir;++ if (proj - triangle[i]).length() < epsilon_distance {+ return true;+ }+ }++ false+}++fn merge_triangle_sets(+ mesh1: &TriMesh,+ mesh2: &TriMesh,+ triangle_constraints: &BTreeMap<&u32, Vec<[Vector3; 2]>>,+ pos1: &Pose,+ pos2: &Pose,+ flip1: bool,+ flip2: bool,+ metadata: &MeshIntersectionTolerances,+ point_set: &mut RTree<TreeVector>,+ topology_indices: &mut HashMap<HashableTriangleIndices, [u32; 3]>,+) -> Result<(), MeshIntersectionError> {+ // For each triangle, and each constraint edge associated to that triangle,+ // make a triangulation of the face and sort whether each generated+ // sub-triangle is part of the intersection.+ // For each sub-triangle that is part of the intersection, add them to the+ // output mesh.+ for (triangle_id, constraints) in triangle_constraints.iter() {+ let tri = mesh1.triangle(**triangle_id).transformed(pos1);++ let (delaunay, points) = triangulate_constraints_and_merge_duplicates(+ &tri,+ constraints,+ metadata.global_insertion_epsilon * metadata.local_insertion_epsilon_scale,+ )+ .or(Err(MeshIntersectionError::TriangulationError))?;++ for face in delaunay.inner_faces() {+ let verts = face.vertices();+ let p1 = points[verts[0].index()];+ let p2 = points[verts[1].index()];+ let p3 = points[verts[2].index()];++ // Sometimes the triangulation is messed up due to numerical errors. If+ // a triangle does not survive this test it should be deleted.+ if is_triangle_degenerate(+ &[p1, p2, p3],+ metadata.angle_epsilon,+ metadata.global_insertion_epsilon,+ ) {+ continue;+ }++ let center = Triangle {+ a: p1,+ b: p2,+ c: p3,+ }+ .center();++ let epsilon = metadata.global_insertion_epsilon;+ let projection = mesh2+ .project_local_point_and_get_location(pos2.inverse_transform_point(center), true)+ .0;++ if flip2 ^ (projection.is_inside_eps(center, epsilon)) {+ let mut new_tri_idx = [+ insert_into_set(p1, point_set, epsilon) as u32,+ insert_into_set(p2, point_set, epsilon) as u32,+ insert_into_set(p3, point_set, epsilon) as u32,+ ];++ if flip1 {+ new_tri_idx.swap(0, 1)+ }++ // This should *never* trigger. If it does+ // it means the code has created a triangle with duplicate vertices,+ // which means we encountered an unaccounted for edge case.+ if is_topologically_degenerate(new_tri_idx) {+ return Err(MeshIntersectionError::DuplicateVertices);+ }++ insert_topology_indices(topology_indices, new_tri_idx);+ }+ }+ }++ Ok(())+}++// Insert in the hashmap with sorted indices to avoid adding duplicates.+//+// We also check if we don’t keep pairs of triangles that have the same+// set of indices but opposite orientations. If this happens, both the new triangle, and the one it+// matched with are removed (because they describe a degenerate piece of volume).+fn insert_topology_indices(+ topology_indices: &mut HashMap<HashableTriangleIndices, [u32; 3]>,+ new_tri_idx: [u32; 3],+) {+ match topology_indices.entry(new_tri_idx.into()) {+ Entry::Vacant(e) => {+ let _ = e.insert(new_tri_idx);+ }+ Entry::Occupied(e) => {+ fn same_orientation(a: &[u32; 3], b: &[u32; 3]) -> bool {+ let ib = if a[0] == b[0] {+ 0+ } else if a[0] == b[1] {+ 1+ } else {+ 2+ };+ a[1] == b[(ib + 1) % 3]+ }++ if !same_orientation(e.get(), &new_tri_idx) {+ // If we are inserting two identical triangles but with mismatching+ // orientations, we can just ignore both because they cover a degenerate+ // 2D plane.+ #[cfg(feature = "enhanced-determinism")]+ let _ = e.swap_remove();+ #[cfg(not(feature = "enhanced-determinism"))]+ let _ = e.remove();+ }+ }+ }+}++fn is_topologically_degenerate(tri_idx: [u32; 3]) -> bool {+ tri_idx[0] == tri_idx[1] || tri_idx[0] == tri_idx[2] || tri_idx[1] == tri_idx[2]+}++#[cfg(feature = "wavefront")]+#[cfg(test)]+mod tests {+ use super::*;+ use crate::math::Vector;+ use crate::shape::{Ball, Cuboid, TriMeshFlags};+ use obj::Obj;+ use obj::ObjData;++ #[test]+ fn test_same_mesh_intersection() {+ let Obj {+ data: ObjData {+ position, objects, ..+ },+ ..+ } = Obj::load("../../assets/tests/low_poly_bunny.obj").unwrap();++ let mesh = TriMesh::with_flags(+ position+ .iter()+ .map(|v| Vector::new(v[0] as Real, v[1] as Real, v[2] as Real))+ .collect::<Vec<_>>(),+ objects[0].groups[0]+ .polys+ .iter()+ .map(|p| [p.0[0].0 as u32, p.0[1].0 as u32, p.0[2].0 as u32])+ .collect::<Vec<_>>(),+ TriMeshFlags::all(),+ )+ .unwrap();++ let _ = intersect_meshes(+ &Pose::identity(),+ &mesh,+ false,+ &Pose::identity(),+ &mesh,+ false,+ )+ .unwrap()+ .unwrap();++ let _ = mesh.to_obj_file(&PathBuf::from("same_test.obj"));+ }++ #[test]+ fn test_non_origin_pos1_pos2_intersection() {+ let ball = Ball::new(2f32 as Real).to_trimesh(10, 10);+ let cuboid = Cuboid::new(Vector::new(2.0, 1.0, 1.0)).to_trimesh();+ let mut sphere_mesh = TriMesh::new(ball.0, ball.1).unwrap();+ sphere_mesh.set_flags(TriMeshFlags::all()).unwrap();+ let mut cuboid_mesh = TriMesh::new(cuboid.0, cuboid.1).unwrap();+ cuboid_mesh.set_flags(TriMeshFlags::all()).unwrap();++ let res = intersect_meshes(+ &Pose::translation(1.0, 0.0, 0.0),+ &cuboid_mesh,+ false,+ &Pose::translation(2.0, 0.0, 0.0),+ &sphere_mesh,+ false,+ )+ .unwrap()+ .unwrap();++ let _ = res.to_obj_file(&PathBuf::from("test_non_origin_pos1_pos2_intersection.obj"));++ let bounding_sphere = res.local_bounding_sphere();+ assert!(bounding_sphere.center == Vector::new(1.5, 0.0, 0.0));+ assert_relative_eq!(2.0615528, bounding_sphere.radius, epsilon = 1.0e-5);+ }++ #[test]+ fn test_offset_cylinder_intersection() {+ let Obj {+ data: ObjData {+ position, objects, ..+ },+ ..+ } = Obj::load("../../assets/tests/offset_cylinder.obj").unwrap();++ let offset_mesh = TriMesh::with_flags(+ position+ .iter()+ .map(|v| Vector::new(v[0] as Real, v[1] as Real, v[2] as Real))+ .collect::<Vec<_>>(),+ objects[0].groups[0]+ .polys+ .iter()+ .map(|p| [p.0[0].0 as u32, p.0[1].0 as u32, p.0[2].0 as u32])+ .collect::<Vec<_>>(),+ TriMeshFlags::all(),+ )+ .unwrap();++ let Obj {+ data: ObjData {+ position, objects, ..+ },+ ..+ } = Obj::load("../../assets/tests/center_cylinder.obj").unwrap();++ let center_mesh = TriMesh::with_flags(+ position+ .iter()+ .map(|v| Vector::new(v[0] as Real, v[1] as Real, v[2] as Real))+ .collect::<Vec<_>>(),+ objects[0].groups[0]+ .polys+ .iter()+ .map(|p| [p.0[0].0 as u32, p.0[1].0 as u32, p.0[2].0 as u32])+ .collect::<Vec<_>>(),+ TriMeshFlags::all(),+ )+ .unwrap();++ let res = intersect_meshes(+ &Pose::identity(),+ ¢er_mesh,+ false,+ &Pose::identity(),+ &offset_mesh,+ false,+ )+ .unwrap()+ .unwrap();++ let _ = res.to_obj_file(&PathBuf::from("offset_test.obj"));+ }++ #[test]+ fn test_stair_bar_intersection() {+ let Obj {+ data: ObjData {+ position, objects, ..+ },+ ..+ } = Obj::load("../../assets/tests/stairs.obj").unwrap();++ let stair_mesh = TriMesh::with_flags(+ position+ .iter()+ .map(|v| Vector::new(v[0] as Real, v[1] as Real, v[2] as Real))+ .collect::<Vec<_>>(),+ objects[0].groups[0]+ .polys+ .iter()+ .map(|p| [p.0[0].0 as u32, p.0[1].0 as u32, p.0[2].0 as u32])+ .collect::<Vec<_>>(),+ TriMeshFlags::all(),+ )+ .unwrap();++ let Obj {+ data: ObjData {+ position, objects, ..+ },+ ..+ } = Obj::load("../../assets/tests/bar.obj").unwrap();++ let bar_mesh = TriMesh::with_flags(+ position+ .iter()+ .map(|v| Vector::new(v[0] as Real, v[1] as Real, v[2] as Real))+ .collect::<Vec<_>>(),+ objects[0].groups[0]+ .polys+ .iter()+ .map(|p| [p.0[0].0 as u32, p.0[1].0 as u32, p.0[2].0 as u32])+ .collect::<Vec<_>>(),+ TriMeshFlags::all(),+ )+ .unwrap();++ let res = intersect_meshes(+ &Pose::identity(),+ &stair_mesh,+ false,+ &Pose::identity(),+ &bar_mesh,+ false,+ )+ .unwrap()+ .unwrap();++ let _ = res.to_obj_file(&PathBuf::from("stair_test.obj"));+ }++ #[test]+ fn test_complex_intersection() {+ let Obj {+ data: ObjData {+ position, objects, ..+ },+ ..+ } = Obj::load("../../assets/tests/low_poly_bunny.obj").unwrap();++ let bunny_mesh = TriMesh::with_flags(+ position+ .iter()+ .map(|v| Vector::new(v[0] as Real, v[1] as Real, v[2] as Real))+ .collect::<Vec<_>>(),+ objects[0].groups[0]+ .polys+ .iter()+ .map(|p| [p.0[0].0 as u32, p.0[1].0 as u32, p.0[2].0 as u32])+ .collect::<Vec<_>>(),+ TriMeshFlags::all(),+ )+ .unwrap();++ let Obj {+ data: ObjData {+ position, objects, ..+ },+ ..+ } = Obj::load("../../assets/tests/poly_cylinder.obj").unwrap();++ let cylinder_mesh = TriMesh::with_flags(+ position+ .iter()+ .map(|v| Vector::new(v[0] as Real, v[1] as Real, v[2] as Real))+ .collect::<Vec<_>>(),+ objects[0].groups[0]+ .polys+ .iter()+ .map(|p| [p.0[0].0 as u32, p.0[1].0 as u32, p.0[2].0 as u32])+ .collect::<Vec<_>>(),+ TriMeshFlags::all(),+ )+ .unwrap();++ let res = intersect_meshes(+ &Pose::identity(),+ &bunny_mesh,+ false,+ &Pose::identity(),+ &cylinder_mesh,+ true,+ )+ .unwrap()+ .unwrap();++ let _ = res.to_obj_file(&PathBuf::from("complex_test.obj"));+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/mesh_intersection/mesh_intersection_error.rs b/renderer/third_party/parry3d/src/transformation/mesh_intersection/mesh_intersection_error.rsnew file mode 100644index 0000000..623335b--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/mesh_intersection/mesh_intersection_error.rs@@ -0,0 +1,217 @@+use crate::shape::TriMeshBuilderError;++#[cfg(doc)]+use crate::shape::{TriMesh, TriMeshFlags};++/// Errors that can occur when computing the boolean intersection of two triangle meshes.+///+/// The [`intersect_meshes`] function computes the geometric intersection of two triangle meshes,+/// producing a new mesh that represents their overlapping volume. This operation requires both+/// input meshes to have certain properties and can fail for various reasons.+///+/// # Prerequisites for Mesh Intersection+///+/// Both input meshes must have:+/// 1. **Topology information**: Half-edge data structure for adjacency information+/// 2. **Pseudo-normals**: For robust inside/outside testing+///+/// These are enabled by setting the [`TriMeshFlags::ORIENTED`] flag when creating the mesh.+///+// /// TODO: figure out why this doc-test fails?+// /// # Common Usage Pattern+// ///+// /// ```+// /// # #[cfg(all(feature = "dim3", feature = "spade"))] {+// /// use parry3d::shape::{TriMesh, TriMeshFlags};+// /// use parry3d::transformation::{intersect_meshes, MeshIntersectionError};+// ///+// /// // Create two meshes with proper flags+// /// let vertices1 = vec![+// /// Vector::new(-1.0, -1.0, -1.0),+// /// Vector::new(1.0, -1.0, -1.0),+// /// Vector::new(1.0, 1.0, -1.0),+// /// Vector::new(-1.0, 1.0, -1.0),+// /// ];+// /// let indices1 = vec![[0, 1, 2], [0, 2, 3]];+// ///+// /// // IMPORTANT: Use ORIENTED flag to enable topology and pseudo-normals+// /// let mesh1 = TriMesh::with_flags(+// /// vertices1,+// /// indices1,+// /// TriMeshFlags::ORIENTED+// /// ).expect("Failed to create mesh");+// ///+// /// let vertices2 = vec![+// /// Vector::new(0.0, -1.0, -1.0),+// /// Vector::new(2.0, -1.0, -1.0),+// /// Vector::new(2.0, 1.0, -1.0),+// /// Vector::new(0.0, 1.0, -1.0),+// /// ];+// /// let indices2 = vec![[0, 1, 2], [0, 2, 3]];+// /// let mesh2 = TriMesh::with_flags(+// /// vertices2,+// /// indices2,+// /// TriMeshFlags::ORIENTED+// /// ).expect("Failed to create mesh");+// ///+// /// let pos1 = Pose::identity();+// /// let pos2 = Pose::identity();+// ///+// /// match intersect_meshes(&pos1, &mesh1, false, &pos2, &mesh2, false) {+// /// Ok(intersection_mesh) => {+// /// println!("Intersection computed successfully!");+// /// }+// /// Err(MeshIntersectionError::MissingTopology) => {+// /// println!("One or both meshes missing topology - use TriMeshFlags::ORIENTED");+// /// }+// /// Err(MeshIntersectionError::MissingPseudoNormals) => {+// /// println!("One or both meshes missing pseudo-normals - use TriMeshFlags::ORIENTED");+// /// }+// /// Err(err) => {+// /// println!("Intersection failed: {}", err);+// /// }+// /// }+// /// # }+// /// ```+///+/// [`intersect_meshes`]: crate::transformation::intersect_meshes+/// [`TriMeshFlags::ORIENTED`]: crate::shape::TriMeshFlags::ORIENTED+#[derive(thiserror::Error, Debug, Copy, Clone, Eq, PartialEq)]+pub enum MeshIntersectionError {+ /// One or both meshes are missing topology information.+ ///+ /// Mesh intersection requires half-edge topology data to determine adjacency+ /// relationships between triangles. This information is automatically computed+ /// when you create a mesh with the [`TriMeshFlags::ORIENTED`] flag.+ ///+ /// # How to Fix+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{TriMesh, TriMeshFlags};+ /// # use parry3d::math::Vector;+ /// # let vertices = vec![Vector::ZERO];+ /// # let indices = vec![[0, 0, 0]];+ /// // Instead of:+ /// // let mesh = TriMesh::new(vertices, indices)?;+ ///+ /// // Use ORIENTED flag:+ /// let mesh = TriMesh::with_flags(+ /// vertices,+ /// indices,+ /// TriMeshFlags::ORIENTED+ /// ).unwrap();+ /// # }+ /// ```+ ///+ /// # Alternative+ ///+ /// You can also add topology to an existing mesh:+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::shape::{TriMesh, TriMeshFlags};+ /// # use parry3d::math::Vector;+ /// # let vertices = vec![Vector::ZERO];+ /// # let indices = vec![[0, 0, 0]];+ /// let mut mesh = TriMesh::new(vertices, indices).unwrap();+ /// mesh.set_flags(TriMeshFlags::ORIENTED).unwrap();+ /// # }+ /// ```+ #[error("at least one of the meshes is missing its topology information. Ensure that the `TriMeshFlags::ORIENTED` flag is enabled on both meshes.")]+ MissingTopology,++ /// One or both meshes are missing pseudo-normal information.+ ///+ /// Pseudo-normals are weighted normals used for robust point-in-mesh testing,+ /// which is essential for determining which parts of the meshes are inside or+ /// outside each other during intersection. They are computed when using the+ /// [`TriMeshFlags::ORIENTED`] flag.+ ///+ /// # Background+ ///+ /// Mesh intersection needs to determine which triangles from each mesh are inside,+ /// outside, or intersecting the other mesh. This requires reliable point containment+ /// tests, which use pseudo-normals as described in:+ ///+ /// "Signed distance computation using the angle weighted pseudonormal"+ /// by Baerentzen et al., DOI: 10.1109/TVCG.2005.49+ ///+ /// # How to Fix+ ///+ /// Use the same solution as [`MissingTopology`](Self::MissingTopology) - create your+ /// meshes with [`TriMeshFlags::ORIENTED`].+ #[error("at least one of the meshes is missing its pseudo-normals. Ensure that the `TriMeshFlags::ORIENTED` flag is enabled on both meshes.")]+ MissingPseudoNormals,++ /// Internal failure while computing the intersection between two triangles.+ ///+ /// This error occurs when the triangle-triangle intersection algorithm encounters+ /// a case it cannot handle, typically due to:+ /// - Degenerate triangles (zero area, collinear vertices)+ /// - Numerical precision issues with nearly-parallel triangles+ /// - Edge cases in the intersection geometry+ ///+ /// # What to Try+ ///+ /// - Check your input meshes for degenerate triangles+ /// - Try using [`TriMeshFlags::DELETE_DEGENERATE_TRIANGLES`] when creating meshes+ /// - Ensure your mesh has reasonable numeric precision (not too small or too large coordinates)+ /// - Consider using [`intersect_meshes_with_tolerances`] with custom tolerances+ ///+ /// [`TriMeshFlags::DELETE_DEGENERATE_TRIANGLES`]: crate::shape::TriMeshFlags::DELETE_DEGENERATE_TRIANGLES+ /// [`intersect_meshes_with_tolerances`]: crate::transformation::intersect_meshes_with_tolerances+ #[error("internal failure while intersecting two triangles")]+ TriTriError,++ /// Internal failure while merging vertices from triangle intersections.+ ///+ /// After computing triangle-triangle intersections, the algorithm merges nearby+ /// vertices to create a clean mesh. This error occurs when the merging process+ /// detects inconsistencies, usually caused by:+ /// - Numerical precision issues causing vertices to appear in wrong positions+ /// - Complex intersection patterns that create ambiguous vertex relationships+ ///+ /// # What to Try+ ///+ /// - Use [`intersect_meshes_with_tolerances`] with larger tolerances+ /// - Simplify your input meshes if they have very high triangle counts+ /// - Check for and remove nearly-degenerate triangles+ ///+ /// [`intersect_meshes_with_tolerances`]: crate::transformation::intersect_meshes_with_tolerances+ #[error("internal failure while merging faces resulting from intersections")]+ DuplicateVertices,++ /// Internal failure while triangulating an intersection face.+ ///+ /// The intersection of two meshes can create non-triangular polygonal faces+ /// that must be triangulated. This error occurs when the triangulation algorithm+ /// fails, typically due to:+ /// - Self-intersecting intersection polygons+ /// - Numerical issues creating invalid polygon geometry+ /// - Very complex intersection patterns+ ///+ /// This often happens with grazing intersections or when meshes have very+ /// different triangle sizes at the intersection boundary.+ #[error("internal failure while triangulating an intersection face")]+ TriangulationError,++ /// The resulting intersection mesh could not be constructed.+ ///+ /// After computing all triangle intersections and creating the intersection geometry,+ /// the final mesh construction failed. This wraps errors from [`TriMeshBuilderError`]+ /// and typically indicates:+ /// - The intersection resulted in invalid mesh topology+ /// - No triangles in the intersection (meshes don't overlap)+ /// - Topology violations in the computed intersection+ ///+ /// See [`TriMeshBuilderError`] for details on the specific failure.+ #[error("TriMeshBuilderError: {0}")]+ TriMeshBuilderError(TriMeshBuilderError),+}++impl From<TriMeshBuilderError> for MeshIntersectionError {+ fn from(value: TriMeshBuilderError) -> Self {+ MeshIntersectionError::TriMeshBuilderError(value)+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/mesh_intersection/mod.rs b/renderer/third_party/parry3d/src/transformation/mesh_intersection/mod.rsnew file mode 100644index 0000000..a11d73b--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/mesh_intersection/mod.rs@@ -0,0 +1,13 @@+pub use self::mesh_intersection::{+ intersect_meshes, intersect_meshes_with_tolerances, MeshIntersectionTolerances,+};+pub use self::mesh_intersection_error::MeshIntersectionError;+use triangle_triangle_intersection::*;++use crate::math::Real;++mod mesh_intersection;+mod mesh_intersection_error;+mod triangle_triangle_intersection;++const EPS: Real = 1.0e-6;diff --git a/renderer/third_party/parry3d/src/transformation/mesh_intersection/triangle_triangle_intersection.rs b/renderer/third_party/parry3d/src/transformation/mesh_intersection/triangle_triangle_intersection.rsnew file mode 100644index 0000000..f3247b9--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/mesh_intersection/triangle_triangle_intersection.rs@@ -0,0 +1,295 @@+use super::EPS;+use crate::math::Vector2;+use crate::math::{Real, Vector};+use crate::query;+use crate::query::PointQuery;+use crate::shape::{FeatureId, Segment, Triangle};+use crate::transformation::polygon_intersection::{+ PolygonIntersectionTolerances, PolylinePointLocation,+};+use crate::utils::WBasis;+use alloc::{vec, vec::Vec};++#[derive(Copy, Clone, Debug, Default)]+pub struct TriangleTriangleIntersectionVector {+ pub p1: Vector,+}++#[derive(Clone, Debug)]+pub enum TriangleTriangleIntersection {+ Segment {+ a: TriangleTriangleIntersectionVector,+ b: TriangleTriangleIntersectionVector,+ },+ Polygon(Vec<TriangleTriangleIntersectionVector>),+}++impl Default for TriangleTriangleIntersection {+ fn default() -> Self {+ Self::Segment {+ a: Default::default(),+ b: Default::default(),+ }+ }+}++pub(crate) fn triangle_triangle_intersection(+ tri1: &Triangle,+ tri2: &Triangle,+ collinearity_epsilon: Real,+) -> Option<TriangleTriangleIntersection> {+ let normal1 = tri1.robust_normal();+ let normal2 = tri2.robust_normal();++ if let Some(intersection_dir) = normal1.cross(normal2).try_normalize() {+ let mut range1 = [+ (Real::MAX, Vector::ZERO, FeatureId::Unknown),+ (-Real::MAX, Vector::ZERO, FeatureId::Unknown),+ ];+ let mut range2 = [+ (Real::MAX, Vector::ZERO, FeatureId::Unknown),+ (-Real::MAX, Vector::ZERO, FeatureId::Unknown),+ ];++ let hits1 = [+ segment_plane_intersection(tri2.a, normal2, &Segment::new(tri1.a, tri1.b), 0, (0, 1))+ .map(|(p, feat)| (intersection_dir.dot(p), p, feat)),+ segment_plane_intersection(tri2.a, normal2, &Segment::new(tri1.b, tri1.c), 1, (1, 2))+ .map(|(p, feat)| (intersection_dir.dot(p), p, feat)),+ segment_plane_intersection(tri2.a, normal2, &Segment::new(tri1.c, tri1.a), 2, (2, 0))+ .map(|(p, feat)| (intersection_dir.dot(p), p, feat)),+ ];++ for hit1 in hits1.into_iter().flatten() {+ if hit1.0 < range1[0].0 {+ range1[0] = hit1;+ }+ if hit1.0 > range1[1].0 {+ range1[1] = hit1;+ }+ }++ if range1[0].0 >= range1[1].0 {+ // The first triangle doesn’t intersect the second plane.+ return None;+ }++ let hits2 = [+ segment_plane_intersection(tri1.a, normal1, &Segment::new(tri2.a, tri2.b), 0, (0, 1))+ .map(|(p, feat)| (intersection_dir.dot(p), p, feat)),+ segment_plane_intersection(tri1.a, normal1, &Segment::new(tri2.b, tri2.c), 1, (1, 2))+ .map(|(p, feat)| (intersection_dir.dot(p), p, feat)),+ segment_plane_intersection(tri1.a, normal1, &Segment::new(tri2.c, tri2.a), 2, (2, 0))+ .map(|(p, feat)| (intersection_dir.dot(p), p, feat)),+ ];++ for hit2 in hits2.into_iter().flatten() {+ if hit2.0 < range2[0].0 {+ range2[0] = hit2;+ }+ if hit2.0 > range2[1].0 {+ range2[1] = hit2;+ }+ }++ if range2[0].0 >= range2[1].0 {+ // The second triangle doesn’t intersect the first plane.+ return None;+ }++ if range1[1].0 <= range2[0].0 + EPS || range2[1].0 <= range1[0].0 + EPS {+ // The two triangles intersect each others’ plane, but these intersections are disjoint.+ return None;+ }++ let a = if range2[0].0 > range1[0].0 + EPS {+ TriangleTriangleIntersectionVector { p1: range2[0].1 }+ } else {+ TriangleTriangleIntersectionVector { p1: range1[0].1 }+ };++ let b = if range2[1].0 < range1[1].0 - EPS {+ TriangleTriangleIntersectionVector { p1: range2[1].1 }+ } else {+ TriangleTriangleIntersectionVector { p1: range1[1].1 }+ };++ Some(TriangleTriangleIntersection::Segment { a, b })+ } else {+ let unit_normal2 = normal2.normalize();+ if (tri1.a - tri2.a).dot(unit_normal2) < EPS {+ let basis = unit_normal2.orthonormal_basis();+ let proj = |vect: Vector| Vector2::new(vect.dot(basis[0]), vect.dot(basis[1]));++ let mut intersections = vec![];++ let pts1 = tri1.vertices();+ let pts2 = tri2.vertices();+ let poly1 = [+ proj(tri1.a - tri2.a),+ proj(tri1.b - tri2.a),+ proj(tri1.c - tri2.a),+ ];+ let poly2 = [+ proj(Vector::ZERO), // = proj(tri2.a - tri2.a)+ proj(tri2.b - tri2.a),+ proj(tri2.c - tri2.a),+ ];++ let convert_loc = |loc, pts: &[Vector; 3]| match loc {+ PolylinePointLocation::OnVertex(vid) => (FeatureId::Vertex(vid as u32), pts[vid]),+ PolylinePointLocation::OnEdge(vid1, vid2, bcoords) => (+ match (vid1, vid2) {+ (0, 1) | (1, 0) => FeatureId::Edge(0),+ (1, 2) | (2, 1) => FeatureId::Edge(1),+ (2, 0) | (0, 2) => FeatureId::Edge(2),+ _ => unreachable!(),+ },+ pts[vid1] * bcoords[0] + pts[vid2] * bcoords[1],+ ),+ };++ crate::transformation::convex_polygons_intersection_with_tolerances(+ &poly1,+ &poly2,+ PolygonIntersectionTolerances {+ collinearity_epsilon,+ },+ |pt1, pt2| {+ let intersection = match (pt1, pt2) {+ (Some(loc1), Some(loc2)) => {+ let (_f1, p1) = convert_loc(loc1, pts1);+ let (_f2, _p2) = convert_loc(loc2, pts2);+ TriangleTriangleIntersectionVector { p1 }+ }+ (Some(loc1), None) => {+ let (_f1, p1) = convert_loc(loc1, pts1);+ TriangleTriangleIntersectionVector { p1 }+ }+ (None, Some(loc2)) => {+ let (_f2, p2) = convert_loc(loc2, pts2);+ TriangleTriangleIntersectionVector { p1: p2 }+ }+ (None, None) => unreachable!(),+ };+ intersections.push(intersection);+ },+ );++ #[cfg(feature = "std")]+ {+ // NOTE: set this to `true` to automatically check if the computed intersection is+ // valid, and print debug infos if it is not.+ const DEBUG_INTERSECTIONS: bool = false;+ if DEBUG_INTERSECTIONS {+ debug_check_intersections(tri1, tri2, &basis, &poly1, &poly2, &intersections);+ }+ }++ Some(TriangleTriangleIntersection::Polygon(intersections))+ } else {+ None+ }+ }+}++fn segment_plane_intersection(+ plane_center: Vector,+ plane_normal: Vector,+ segment: &Segment,+ eid: u32,+ vids: (u32, u32),+) -> Option<(Vector, FeatureId)> {+ let dir = segment.b - segment.a;+ let dir_norm = dir.length();++ let time_of_impact =+ query::details::line_toi_with_halfspace(plane_center, plane_normal, segment.a, dir)?;+ let scaled_toi = time_of_impact * dir_norm;++ if scaled_toi < -EPS || scaled_toi > dir_norm + EPS {+ None+ } else if scaled_toi <= EPS {+ Some((segment.a, FeatureId::Vertex(vids.0)))+ } else if scaled_toi >= dir_norm - EPS {+ Some((segment.b, FeatureId::Vertex(vids.1)))+ } else {+ Some((segment.a + dir * time_of_impact, FeatureId::Edge(eid)))+ }+}++/// Prints debug information if the calculated intersection of two triangles is detected to be+/// invalid.+///+/// If the intersection is valid, this prints nothing. If it isn't valid, this will print a few+/// lines to copy/paste into the Desmos online graphing tool (for visual debugging), as well as+/// some rust code to add to the `tris` array in the `intersect_triangle_common_vertex` test for+/// regression checking.+#[cfg(feature = "std")]+fn debug_check_intersections(+ tri1: &Triangle,+ tri2: &Triangle,+ basis: &[Vector; 2],+ poly1: &[Vector2], // Projection of tri1 on the basis `basis1` with the origin at tri2.a.+ poly2: &[Vector2], // Projection of tri2 on the basis `basis2` with the origin at tri2.a.+ intersections: &[TriangleTriangleIntersectionVector],+) {+ use std::{print, println};++ let proj = |vect: Vector| Vector2::new(vect.dot(basis[0]), vect.dot(basis[1]));+ let mut incorrect = false;+ for pt in intersections {+ if !tri1+ .project_local_point(pt.p1, false)+ .is_inside_eps(pt.p1, 1.0e-5)+ {+ incorrect = true;+ break;+ }++ if !tri2+ .project_local_point(pt.p1, false)+ .is_inside_eps(pt.p1, 1.0e-5)+ {+ incorrect = true;+ break;+ }+ }++ if incorrect {+ let proj_inter: Vec<_> = intersections.iter().map(|p| proj(p.p1 - tri2.a)).collect();+ println!("-------- (copy/paste the following on Desmos graphing)");+ println!("A=({:.2},{:.2})", poly1[0].x, poly1[0].y);+ println!("B=({:.2},{:.2})", poly1[1].x, poly1[1].y);+ println!("C=({:.2},{:.2})", poly1[2].x, poly1[2].y);+ println!("D=({:.2},{:.2})", poly2[0].x, poly2[0].y);+ println!("E=({:.2},{:.2})", poly2[1].x, poly2[1].y);+ println!("F=({:.2},{:.2})", poly2[2].x, poly2[2].y);++ let lbls = ["G", "H", "I", "J", "K", "L", "M", "N", "O"];+ for (i, inter) in proj_inter.iter().enumerate() {+ println!("{}=({:.2},{:.2})", lbls[i], inter.x, inter.y);+ }++ // polygons+ println!("X=polygon(A,B,C)");+ println!("Y=polygon(D,E,F)");+ print!("Z=polygon({}", lbls[0]);+ for lbl in lbls.iter().skip(1) {+ print!(",{lbl}");+ }+ println!(")");++ println!("~~~~~~~ (copy/paste the following input in the `intersect_triangle_common_vertex` test)");+ println!("(Triangle::new(");+ for pt1 in poly1 {+ println!(" Vector::new({},{}),", pt1.x, pt1.y);+ }+ println!("),");+ println!("Triangle::new(");+ for pt2 in poly2 {+ println!(" Vector::new({},{}),", pt2.x, pt2.y);+ }+ println!("),),");+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/mod.rs b/renderer/third_party/parry3d/src/transformation/mod.rsnew file mode 100644index 0000000..cae58a1--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/mod.rs@@ -0,0 +1,58 @@+//! Transformation, simplification and decomposition of meshes.++#[cfg(feature = "dim3")]+pub(crate) use self::convex_hull2::convex_hull2_idx;+#[cfg(feature = "dim2")]+pub use self::convex_hull2::{convex_hull2 as convex_hull, convex_hull2_idx as convex_hull_idx};+#[cfg(all(feature = "dim3", feature = "std"))]+pub use self::convex_hull3::check_convex_hull;+#[cfg(feature = "dim3")]+pub use self::convex_hull3::{convex_hull, try_convex_hull, ConvexHullError};+#[cfg(all(feature = "dim3", feature = "spade"))]+pub use self::mesh_intersection::{+ intersect_meshes, intersect_meshes_with_tolerances, MeshIntersectionError,+ MeshIntersectionTolerances,+};+#[cfg(all(feature = "dim3", feature = "alloc"))]+pub use self::volume_mesh::MeshEnclosure;+#[cfg(all(feature = "alloc", any(feature = "dim3", feature = "spade")))]+pub use self::volume_mesh::{volume_mesh, VolumeMesh, VolumeMeshParameters};++pub use self::polygon_intersection::{+ convex_polygons_intersection, convex_polygons_intersection_points,+ convex_polygons_intersection_points_with_tolerances,+ convex_polygons_intersection_with_tolerances, polygons_intersection,+ polygons_intersection_points, PolygonIntersectionTolerances, PolygonsIntersectionError,+ PolylinePointLocation,+};++mod convex_hull2;+#[cfg(feature = "dim3")]+mod convex_hull3;+pub(crate) mod convex_hull_utils;++mod polygon_intersection;+/// Approximate convex decomposition using the VHACD algorithm.+pub mod vhacd;+#[cfg(all(feature = "alloc", any(feature = "dim3", feature = "spade")))]+mod volume_mesh;+/// Voxelization of a 2D polyline or 3D triangle mesh.+pub mod voxelization;++#[cfg(feature = "dim2")]+pub(crate) mod ear_clipping;+#[cfg(feature = "dim2")]+pub(crate) mod hertel_mehlhorn;+#[cfg(feature = "dim2")]+pub use hertel_mehlhorn::{hertel_mehlhorn, hertel_mehlhorn_idx};+#[cfg(all(feature = "dim3", feature = "spade"))]+mod mesh_intersection;+#[cfg(feature = "dim3")]+mod to_outline;+#[cfg(feature = "dim2")]+mod to_polyline;+mod to_trimesh;+pub mod utils;++#[cfg(feature = "wavefront")]+mod wavefront;diff --git a/renderer/third_party/parry3d/src/transformation/polygon_intersection.rs b/renderer/third_party/parry3d/src/transformation/polygon_intersection.rsnew file mode 100644index 0000000..e78c331--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/polygon_intersection.rs@@ -0,0 +1,1239 @@+use crate::math::Vector2;+use alloc::{vec, vec::Vec};+use ordered_float::OrderedFloat;++use crate::math::Real;+use crate::shape::{SegmentPointLocation, Triangle, TriangleOrientation};+use crate::utils::hashmap::HashMap;+use crate::utils::{self, SegmentsIntersection};++/// Tolerances for polygon intersection algorithms.+///+/// These tolerances control how the intersection algorithm handles numerical precision+/// issues when determining geometric relationships between points, lines, and polygons.+///+/// # Examples+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::transformation::PolygonIntersectionTolerances;+/// // Use default tolerances (recommended for most cases)+/// let default_tol = PolygonIntersectionTolerances::default();+///+/// // Or create custom tolerances for special cases+/// let custom_tol = PolygonIntersectionTolerances {+/// collinearity_epsilon: 1.0e-5,+/// };+/// # }+/// ```+#[derive(Copy, Clone, PartialEq, Debug)]+pub struct PolygonIntersectionTolerances {+ /// The epsilon given to [`Triangle::orientation2d`] for detecting if three points are collinear.+ ///+ /// Three points forming a triangle with an area smaller than this value are considered collinear.+ pub collinearity_epsilon: Real,+}++impl Default for PolygonIntersectionTolerances {+ fn default() -> Self {+ Self {+ collinearity_epsilon: Real::EPSILON * 100.0,+ }+ }+}++#[derive(Copy, Clone, Debug, PartialEq, Eq)]+enum InFlag {+ // The current neighborhood of the traversed point on poly1 is inside poly2.+ Poly1IsInside,+ // The current neighborhood of the traversed point on poly2 is inside poly1.+ Poly2IsInside,+ Unknown,+}++/// Location of a point on a polyline.+///+/// This enum represents where a point lies on a polygon's boundary. It's used by+/// the intersection algorithms to precisely describe intersection points.+///+/// # Variants+///+/// * `OnVertex(i)` - The point is exactly on vertex `i` of the polygon+/// * `OnEdge(i, j, bcoords)` - The point lies on the edge between vertices `i` and `j`,+/// with barycentric coordinates `bcoords` where `bcoords[0] + bcoords[1] = 1.0`+///+/// # Examples+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::transformation::PolylinePointLocation;+/// # use parry2d::math::Vector;+/// let polygon = vec![+/// Vector::ZERO,+/// Vector::new(2.0, 0.0),+/// Vector::new(2.0, 2.0),+/// Vector::new(0.0, 2.0),+/// ];+///+/// // A point on vertex 0+/// let loc1 = PolylinePointLocation::OnVertex(0);+/// let pt1 = loc1.to_point(&polygon);+/// assert_eq!(pt1, Vector::ZERO);+///+/// // A point halfway along the edge from vertex 0 to vertex 1+/// let loc2 = PolylinePointLocation::OnEdge(0, 1, [0.5, 0.5]);+/// let pt2 = loc2.to_point(&polygon);+/// assert_eq!(pt2, Vector::new(1.0, 0.0));+/// # }+/// ```+#[derive(Copy, Clone, Debug, PartialEq)]+pub enum PolylinePointLocation {+ /// Vector on a vertex.+ OnVertex(usize),+ /// Vector on an edge.+ OnEdge(usize, usize, [Real; 2]),+}++impl PolylinePointLocation {+ /// The barycentric coordinates such that the point in the intersected segment `[a, b]` is+ /// equal to `a + (b - a) * centered_bcoords`.+ fn centered_bcoords(&self, edge: [usize; 2]) -> Real {+ match self {+ Self::OnVertex(vid) => {+ if *vid == edge[0] {+ 0.0+ } else {+ 1.0+ }+ }+ Self::OnEdge(ia, ib, bcoords) => {+ assert_eq!([*ia, *ib], edge);+ bcoords[1]+ }+ }+ }++ /// Computes the point corresponding to this location.+ ///+ /// Given a polygon (as a slice of points), this method converts the location+ /// into an actual 2D point coordinate.+ ///+ /// # Arguments+ ///+ /// * `pts` - The vertices of the polygon+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::transformation::PolylinePointLocation;+ /// # use parry2d::math::Vector;+ /// let polygon = vec![+ /// Vector::ZERO,+ /// Vector::new(4.0, 0.0),+ /// Vector::new(4.0, 4.0),+ /// ];+ ///+ /// let loc = PolylinePointLocation::OnEdge(0, 1, [0.75, 0.25]);+ /// let point = loc.to_point(&polygon);+ /// assert_eq!(point, Vector::new(1.0, 0.0)); // 75% of vertex 0 + 25% of vertex 1+ /// # }+ /// ```+ pub fn to_point(self, pts: &[Vector2]) -> Vector2 {+ match self {+ PolylinePointLocation::OnVertex(i) => pts[i],+ PolylinePointLocation::OnEdge(i1, i2, bcoords) => {+ pts[i1] * bcoords[0] + pts[i2] * bcoords[1]+ }+ }+ }++ fn from_segment_point_location(a: usize, b: usize, loc: SegmentPointLocation) -> Self {+ match loc {+ SegmentPointLocation::OnVertex(0) => PolylinePointLocation::OnVertex(a),+ SegmentPointLocation::OnVertex(1) => PolylinePointLocation::OnVertex(b),+ SegmentPointLocation::OnVertex(_) => unreachable!(),+ SegmentPointLocation::OnEdge(bcoords) => PolylinePointLocation::OnEdge(a, b, bcoords),+ }+ }+}++/// Computes the intersection points of two convex polygons.+///+/// This function takes two convex polygons and computes their intersection, returning+/// the vertices of the resulting intersection polygon. The result is added to the `out` vector.+///+/// # Important Notes+///+/// - **Convex polygons only**: Both input polygons must be convex. For non-convex polygons,+/// use [`polygons_intersection_points`] instead.+/// - **Counter-clockwise winding**: Input polygons should be oriented counter-clockwise.+/// - **Default tolerances**: Uses default numerical tolerances. For custom tolerances,+/// use [`convex_polygons_intersection_points_with_tolerances`].+///+/// # Arguments+///+/// * `poly1` - First convex polygon as a slice of vertices+/// * `poly2` - Second convex polygon as a slice of vertices+/// * `out` - Output vector where intersection vertices will be appended+///+/// # Examples+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::transformation::convex_polygons_intersection_points;+/// # use parry2d::math::Vector;+/// // Define two overlapping squares+/// let square1 = vec![+/// Vector::ZERO,+/// Vector::new(2.0, 0.0),+/// Vector::new(2.0, 2.0),+/// Vector::new(0.0, 2.0),+/// ];+///+/// let square2 = vec![+/// Vector::new(1.0, 1.0),+/// Vector::new(3.0, 1.0),+/// Vector::new(3.0, 3.0),+/// Vector::new(1.0, 3.0),+/// ];+///+/// let mut intersection = Vec::new();+/// convex_polygons_intersection_points(&square1, &square2, &mut intersection);+///+/// // The intersection should be a square from (1,1) to (2,2)+/// assert_eq!(intersection.len(), 4);+/// # }+/// ```+///+/// # See Also+///+/// * [`convex_polygons_intersection`] - For closure-based output+/// * [`polygons_intersection_points`] - For non-convex polygons+pub fn convex_polygons_intersection_points(+ poly1: &[Vector2],+ poly2: &[Vector2],+ out: &mut Vec<Vector2>,+) {+ convex_polygons_intersection_points_with_tolerances(poly1, poly2, Default::default(), out);+}++/// Computes the intersection points of two convex polygons with custom tolerances.+///+/// This is the same as [`convex_polygons_intersection_points`] but allows you to specify+/// custom numerical tolerances for the intersection computation.+///+/// # Arguments+///+/// * `poly1` - First convex polygon as a slice of vertices+/// * `poly2` - Second convex polygon as a slice of vertices+/// * `tolerances` - Custom tolerances for numerical precision+/// * `out` - Output vector where intersection vertices will be appended+///+/// # Examples+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::transformation::{convex_polygons_intersection_points_with_tolerances, PolygonIntersectionTolerances};+/// # use parry2d::math::Vector;+/// let triangle1 = vec![+/// Vector::ZERO,+/// Vector::new(4.0, 0.0),+/// Vector::new(2.0, 3.0),+/// ];+///+/// let triangle2 = vec![+/// Vector::new(1.0, 0.5),+/// Vector::new(3.0, 0.5),+/// Vector::new(2.0, 2.5),+/// ];+///+/// let mut intersection = Vec::new();+/// let tolerances = PolygonIntersectionTolerances {+/// collinearity_epsilon: 1.0e-6,+/// };+///+/// convex_polygons_intersection_points_with_tolerances(+/// &triangle1,+/// &triangle2,+/// tolerances,+/// &mut intersection+/// );+///+/// // The triangles overlap, so we should get intersection points+/// assert!(intersection.len() >= 3);+/// # }+/// ```+pub fn convex_polygons_intersection_points_with_tolerances(+ poly1: &[Vector2],+ poly2: &[Vector2],+ tolerances: PolygonIntersectionTolerances,+ out: &mut Vec<Vector2>,+) {+ convex_polygons_intersection_with_tolerances(poly1, poly2, tolerances, |loc1, loc2| {+ if let Some(loc1) = loc1 {+ out.push(loc1.to_point(poly1))+ } else if let Some(loc2) = loc2 {+ out.push(loc2.to_point(poly2))+ }+ })+}++/// Computes the intersection of two convex polygons with closure-based output.+///+/// This function is similar to [`convex_polygons_intersection_points`] but provides more+/// flexibility by calling a closure for each intersection vertex. The closure receives+/// the location of the vertex on each polygon (if applicable).+///+/// This is useful when you need to track which polygon each intersection vertex comes from,+/// or when you want to process vertices as they're computed rather than collecting them all.+///+/// # Arguments+///+/// * `poly1` - First convex polygon as a slice of vertices+/// * `poly2` - Second convex polygon as a slice of vertices+/// * `out` - Closure called for each intersection vertex with its location on both polygons+///+/// # Closure Arguments+///+/// The closure receives `(Option<PolylinePointLocation>, Option<PolylinePointLocation>)`:+/// - If the point comes from `poly1`, the first option contains its location on `poly1`+/// - If the point comes from `poly2`, the second option contains its location on `poly2`+/// - At least one of the options will always be `Some`+///+/// # Examples+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::transformation::convex_polygons_intersection;+/// # use parry2d::math::Vector;+/// let square = vec![+/// Vector::ZERO,+/// Vector::new(2.0, 0.0),+/// Vector::new(2.0, 2.0),+/// Vector::new(0.0, 2.0),+/// ];+///+/// let diamond = vec![+/// Vector::new(1.0, -0.5),+/// Vector::new(2.5, 1.0),+/// Vector::new(1.0, 2.5),+/// Vector::new(-0.5, 1.0),+/// ];+///+/// let mut intersection_points = Vec::new();+/// convex_polygons_intersection(&square, &diamond, |loc1, loc2| {+/// if let Some(loc) = loc1 {+/// intersection_points.push(loc.to_point(&square));+/// } else if let Some(loc) = loc2 {+/// intersection_points.push(loc.to_point(&diamond));+/// }+/// });+///+/// // The intersection should have multiple vertices+/// assert!(intersection_points.len() >= 3);+/// # }+/// ```+///+/// # See Also+///+/// * [`convex_polygons_intersection_points`] - Simpler vector-based output+/// * [`convex_polygons_intersection_with_tolerances`] - With custom tolerances+pub fn convex_polygons_intersection(+ poly1: &[Vector2],+ poly2: &[Vector2],+ out: impl FnMut(Option<PolylinePointLocation>, Option<PolylinePointLocation>),+) {+ convex_polygons_intersection_with_tolerances(poly1, poly2, Default::default(), out)+}++/// Computes the intersection of two convex polygons with custom tolerances and closure-based output.+///+/// This is the most flexible version of the convex polygon intersection function, combining+/// custom tolerances with closure-based output for maximum control.+///+/// # Arguments+///+/// * `poly1` - First convex polygon as a slice of vertices+/// * `poly2` - Second convex polygon as a slice of vertices+/// * `tolerances` - Custom tolerances for numerical precision+/// * `out` - Closure called for each intersection vertex+///+/// # Algorithm+///+/// This function implements the Sutherland-Hodgman-like algorithm for convex polygon+/// intersection. It works by:+/// 1. Traversing the edges of both polygons simultaneously+/// 2. Detecting edge-edge intersections+/// 3. Determining which vertices are inside the other polygon+/// 4. Outputting the vertices of the intersection polygon in order+///+/// # Examples+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::transformation::{convex_polygons_intersection_with_tolerances, PolygonIntersectionTolerances};+/// # use parry2d::math::Vector;+/// let hexagon = vec![+/// Vector::new(2.0, 0.0),+/// Vector::new(1.0, 1.732),+/// Vector::new(-1.0, 1.732),+/// Vector::new(-2.0, 0.0),+/// Vector::new(-1.0, -1.732),+/// Vector::new(1.0, -1.732),+/// ];+///+/// let square = vec![+/// Vector::new(-1.0, -1.0),+/// Vector::new(1.0, -1.0),+/// Vector::new(1.0, 1.0),+/// Vector::new(-1.0, 1.0),+/// ];+///+/// let tolerances = PolygonIntersectionTolerances::default();+/// let mut intersection_points = Vec::new();+///+/// convex_polygons_intersection_with_tolerances(+/// &hexagon,+/// &square,+/// tolerances,+/// |loc1, loc2| {+/// if let Some(loc) = loc1 {+/// intersection_points.push(loc.to_point(&hexagon));+/// } else if let Some(loc) = loc2 {+/// intersection_points.push(loc.to_point(&square));+/// }+/// }+/// );+///+/// // The intersection should form a polygon+/// assert!(intersection_points.len() >= 3);+/// # }+/// ```+pub fn convex_polygons_intersection_with_tolerances(+ poly1: &[Vector2],+ poly2: &[Vector2],+ tolerances: PolygonIntersectionTolerances,+ mut out: impl FnMut(Option<PolylinePointLocation>, Option<PolylinePointLocation>),+) {+ // TODO: this does not handle correctly the case where the+ // first triangle of the polygon is degenerate.+ let rev1 = poly1.len() > 2+ && Triangle::orientation2d(+ poly1[0],+ poly1[1],+ poly1[2],+ tolerances.collinearity_epsilon,+ ) == TriangleOrientation::Clockwise;+ let rev2 = poly2.len() > 2+ && Triangle::orientation2d(+ poly2[0],+ poly2[1],+ poly2[2],+ tolerances.collinearity_epsilon,+ ) == TriangleOrientation::Clockwise;++ let len1 = poly1.len();+ let len2 = poly2.len();++ let mut i1 = 0; // Current index on the first polyline.+ let mut i2 = 0; // Current index on the second polyline.+ let mut nsteps1 = 0; // Number of times we advanced on the first polyline.+ let mut nsteps2 = 0; // Number of times we advanced on the second polyline.+ let mut inflag = InFlag::Unknown;+ let mut first_point_found = false;++ // Quit when both adv. indices have cycled, or one has cycled twice.+ while (nsteps1 < len1 || nsteps2 < len2) && nsteps1 < 2 * len1 && nsteps2 < 2 * len2 {+ let (a1, b1) = if rev1 {+ ((len1 - i1) % len1, len1 - i1 - 1)+ } else {+ // Vector before `i1`, and point at `i1`.+ ((i1 + len1 - 1) % len1, i1)+ };++ let (a2, b2) = if rev2 {+ ((len2 - i2) % len2, len2 - i2 - 1)+ } else {+ // Vector before `i2`, and point at `i2`.+ ((i2 + len2 - 1) % len2, i2)+ };++ let dir_edge1 = poly1[b1] - poly1[a1];+ let dir_edge2 = poly2[b2] - poly2[a2];++ // If there is an intersection, this will determine if the edge from poly2 is transitioning+ // Left -> Right (CounterClockwise) or Right -> Left (Clockwise) relative to the edge from+ // poly1.+ let cross = Triangle::orientation2d(+ Vector2::ZERO,+ Vector2::from(dir_edge1),+ Vector2::from(dir_edge2),+ tolerances.collinearity_epsilon,+ );+ // Determines if b1 is left (CounterClockwise) or right (Clockwise) of [a2, b2].+ let a2_b2_b1 = Triangle::orientation2d(+ poly2[a2],+ poly2[b2],+ poly1[b1],+ tolerances.collinearity_epsilon,+ );+ // Determines if b2 is left (CounterClockwise) or right (Clockwise) of [a1, b1].+ let a1_b1_b2 = Triangle::orientation2d(+ poly1[a1],+ poly1[b1],+ poly2[b2],+ tolerances.collinearity_epsilon,+ );++ // If edge1 & edge2 intersect, update inflag.+ if let Some(inter) = utils::segments_intersection2d(+ poly1[a1],+ poly1[b1],+ poly2[a2],+ poly2[b2],+ tolerances.collinearity_epsilon,+ ) {+ match inter {+ SegmentsIntersection::Point { loc1, loc2 } => {+ if a2_b2_b1 != TriangleOrientation::Degenerate+ && a1_b1_b2 != TriangleOrientation::Degenerate+ {+ let loc1 = PolylinePointLocation::from_segment_point_location(a1, b1, loc1);+ let loc2 = PolylinePointLocation::from_segment_point_location(a2, b2, loc2);+ out(Some(loc1), Some(loc2));++ if inflag == InFlag::Unknown && !first_point_found {+ // This is the first point, reset the number of steps since we are+ // effectively starting the actual traversal now.+ nsteps1 = 0;+ nsteps2 = 0;+ first_point_found = true;+ }++ if a2_b2_b1 == TriangleOrientation::CounterClockwise {+ // The point b1 is left of [a2, b2] so it is inside poly2 ???+ inflag = InFlag::Poly1IsInside;+ } else if a1_b1_b2 == TriangleOrientation::CounterClockwise {+ // The point b2 is left of [a1, b1] so it is inside poly1 ???+ inflag = InFlag::Poly2IsInside;+ }+ }+ }+ SegmentsIntersection::Segment {+ first_loc1,+ first_loc2,+ second_loc1,+ second_loc2,+ } => {+ if dir_edge1.dot(dir_edge2) < 0.0 {+ // Special case: edge1 & edge2 overlap and oppositely oriented. The+ // intersection is degenerate (equals to a segment). Output+ // the segment and exit.+ let loc1 =+ PolylinePointLocation::from_segment_point_location(a1, b1, first_loc1);+ let loc2 =+ PolylinePointLocation::from_segment_point_location(a2, b2, first_loc2);+ out(Some(loc1), Some(loc2));++ let loc1 =+ PolylinePointLocation::from_segment_point_location(a1, b1, second_loc1);+ let loc2 =+ PolylinePointLocation::from_segment_point_location(a2, b2, second_loc2);+ out(Some(loc1), Some(loc2));+ return;+ }+ }+ }+ }++ // Special case: edge1 & edge2 parallel and separated.+ if cross == TriangleOrientation::Degenerate+ && a2_b2_b1 == TriangleOrientation::Clockwise+ && a1_b1_b2 == TriangleOrientation::Clockwise+ // TODO: should this also include any case where a2_b2_b1 and a1_b1_b2 are both different from Degenerate?+ {+ return;+ }+ // Special case: edge1 & edge2 collinear.+ else if cross == TriangleOrientation::Degenerate+ && a2_b2_b1 == TriangleOrientation::Degenerate+ && a1_b1_b2 == TriangleOrientation::Degenerate+ {+ // Advance but do not output point.+ if inflag == InFlag::Poly1IsInside {+ i2 = advance(i2, &mut nsteps2, len2);+ } else {+ i1 = advance(i1, &mut nsteps1, len1);+ }+ }+ // Generic cases.+ else if cross == TriangleOrientation::CounterClockwise {+ if a1_b1_b2 == TriangleOrientation::CounterClockwise {+ if inflag == InFlag::Poly1IsInside {+ out(Some(PolylinePointLocation::OnVertex(b1)), None)+ }+ i1 = advance(i1, &mut nsteps1, len1);+ } else {+ if inflag == InFlag::Poly2IsInside {+ out(None, Some(PolylinePointLocation::OnVertex(b2)))+ }+ i2 = advance(i2, &mut nsteps2, len2);+ }+ } else {+ // We have cross == TriangleOrientation::Clockwise.+ if a2_b2_b1 == TriangleOrientation::CounterClockwise {+ if inflag == InFlag::Poly2IsInside {+ out(None, Some(PolylinePointLocation::OnVertex(b2)))+ }+ i2 = advance(i2, &mut nsteps2, len2);+ } else {+ if inflag == InFlag::Poly1IsInside {+ out(Some(PolylinePointLocation::OnVertex(b1)), None)+ }+ i1 = advance(i1, &mut nsteps1, len1);+ }+ }+ }++ if !first_point_found {+ // No intersection: test if one polygon completely encloses the other.+ let mut orient = TriangleOrientation::Degenerate;+ let mut ok = true;++ // TODO: avoid the O(n²) complexity.+ for a in 0..len1 {+ for p2 in poly2 {+ let a_minus_1 = (a + len1 - 1) % len1; // a - 1+ let new_orient = Triangle::orientation2d(+ poly1[a_minus_1],+ poly1[a],+ *p2,+ tolerances.collinearity_epsilon,+ );++ if orient == TriangleOrientation::Degenerate {+ orient = new_orient+ } else if new_orient != orient && new_orient != TriangleOrientation::Degenerate {+ ok = false;+ break;+ }+ }+ }++ if ok {+ for mut b in 0..len2 {+ if rev2 {+ b = len2 - b - 1;+ }+ out(None, Some(PolylinePointLocation::OnVertex(b)))+ }+ }++ let mut orient = TriangleOrientation::Degenerate;+ let mut ok = true;++ // TODO: avoid the O(n²) complexity.+ for b in 0..len2 {+ for p1 in poly1 {+ let b_minus_1 = (b + len2 - 1) % len2; // = b - 1+ let new_orient = Triangle::orientation2d(+ poly2[b_minus_1],+ poly2[b],+ *p1,+ tolerances.collinearity_epsilon,+ );++ if orient == TriangleOrientation::Degenerate {+ orient = new_orient+ } else if new_orient != orient && new_orient != TriangleOrientation::Degenerate {+ ok = false;+ break;+ }+ }+ }++ if ok {+ for mut a in 0..len1 {+ if rev1 {+ a = len1 - a - 1;+ }+ out(Some(PolylinePointLocation::OnVertex(a)), None)+ }+ }+ }+}++#[inline]+fn advance(a: usize, aa: &mut usize, n: usize) -> usize {+ *aa += 1;+ (a + 1) % n+}++/// Error type for polygon intersection operations.+///+/// This error can occur when computing intersections of non-convex polygons.+#[derive(thiserror::Error, Debug)]+pub enum PolygonsIntersectionError {+ /// An infinite loop was detected during intersection computation.+ ///+ /// This typically indicates that the input polygons are ill-formed, such as:+ /// - Self-intersecting polygons+ /// - Polygons with duplicate or degenerate edges+ /// - Polygons with inconsistent winding order+ #[error("Infinite loop detected; input polygons are ill-formed.")]+ InfiniteLoop,+}++/// Computes the intersection points of two possibly non-convex polygons.+///+/// This function handles both convex and **non-convex (concave)** polygons, making it more+/// general than [`convex_polygons_intersection_points`]. However, it requires that:+/// - Neither polygon self-intersects+/// - Both polygons are oriented counter-clockwise+///+/// The result is a vector of polygons, where each polygon represents one connected component+/// of the intersection. In most cases there will be only one component, but complex intersections+/// can produce multiple separate regions.+///+/// # Important Notes+///+/// - **Non-convex support**: This function works with concave polygons+/// - **Multiple components**: Returns a `Vec<Vec<Vector2>>` because the intersection+/// of two concave polygons can produce multiple separate regions+/// - **No self-intersection**: Input polygons must not self-intersect+/// - **Counter-clockwise winding**: Both polygons must be oriented counter-clockwise+/// - **Performance**: Slower than [`convex_polygons_intersection_points`]. If both polygons+/// are convex, use that function instead.+///+/// # Arguments+///+/// * `poly1` - First polygon as a slice of vertices+/// * `poly2` - Second polygon as a slice of vertices+///+/// # Returns+///+/// * `Ok(Vec<Vec<Vector2>>)` - A vector of intersection polygons (usually just one)+/// * `Err(PolygonsIntersectionError::InfiniteLoop)` - If the polygons are ill-formed+///+/// # Examples+///+/// ## Example 1: Two non-convex polygons+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::transformation::polygons_intersection_points;+/// # use parry2d::math::Vector;+/// // L-shaped polygon+/// let l_shape = vec![+/// Vector::ZERO,+/// Vector::new(3.0, 0.0),+/// Vector::new(3.0, 1.0),+/// Vector::new(1.0, 1.0),+/// Vector::new(1.0, 3.0),+/// Vector::new(0.0, 3.0),+/// ];+///+/// // Square overlapping the L-shape+/// let square = vec![+/// Vector::new(0.5, 0.5),+/// Vector::new(2.5, 0.5),+/// Vector::new(2.5, 2.5),+/// Vector::new(0.5, 2.5),+/// ];+///+/// let result = polygons_intersection_points(&l_shape, &square).unwrap();+///+/// // Should have intersection regions+/// assert!(!result.is_empty());+/// # }+/// ```+///+/// ## Example 2: Convex polygons (also works)+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::transformation::polygons_intersection_points;+/// # use parry2d::math::Vector;+/// let triangle = vec![+/// Vector::ZERO,+/// Vector::new(4.0, 0.0),+/// Vector::new(2.0, 3.0),+/// ];+///+/// let square = vec![+/// Vector::new(1.0, 0.5),+/// Vector::new(3.0, 0.5),+/// Vector::new(3.0, 2.0),+/// Vector::new(1.0, 2.0),+/// ];+///+/// let result = polygons_intersection_points(&triangle, &square).unwrap();+/// assert_eq!(result.len(), 1); // One intersection region+/// # }+/// ```+///+/// # Errors+///+/// Returns `PolygonsIntersectionError::InfiniteLoop` if:+/// - Either polygon self-intersects+/// - The polygons have degenerate or duplicate edges+/// - The winding order is inconsistent+///+/// # See Also+///+/// * [`convex_polygons_intersection_points`] - Faster version for convex polygons only+/// * [`polygons_intersection`] - Closure-based version with more control+pub fn polygons_intersection_points(+ poly1: &[Vector2],+ poly2: &[Vector2],+) -> Result<Vec<Vec<Vector2>>, PolygonsIntersectionError> {+ let mut result = vec![];+ let mut curr_poly = vec![];+ polygons_intersection(poly1, poly2, |loc1, loc2| {+ if let Some(loc1) = loc1 {+ curr_poly.push(loc1.to_point(poly1))+ } else if let Some(loc2) = loc2 {+ curr_poly.push(loc2.to_point(poly2))+ } else if !curr_poly.is_empty() {+ result.push(core::mem::take(&mut curr_poly));+ }+ })?;++ Ok(result)+}++/// Computes the intersection of two possibly non-convex polygons with closure-based output.+///+/// This is the closure-based version of [`polygons_intersection_points`], providing more+/// control over how intersection vertices are processed. It handles non-convex (concave)+/// polygons but requires they do not self-intersect.+///+/// # Arguments+///+/// * `poly1` - First polygon as a slice of vertices+/// * `poly2` - Second polygon as a slice of vertices+/// * `out` - Closure called for each intersection vertex or component separator+///+/// # Closure Arguments+///+/// The closure receives `(Option<PolylinePointLocation>, Option<PolylinePointLocation>)`:+/// - When **both are `Some`**: An edge-edge intersection point+/// - When **one is `Some`**: A vertex from one polygon inside the other+/// - When **both are `None`**: Marks the end of a connected component+///+/// # Algorithm+///+/// This function uses a graph-based traversal algorithm:+/// 1. Finds all edge-edge intersection points between the two polygons+/// 2. Builds a graph where vertices are intersection points+/// 3. Traverses the graph, alternating between polygons at intersection points+/// 4. Outputs vertices that form the intersection boundary+///+/// # Examples+///+/// ## Example 1: Collecting intersection points+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::transformation::polygons_intersection;+/// # use parry2d::math::Vector;+/// let pentagon = vec![+/// Vector::new(1.0, 0.0),+/// Vector::new(0.309, 0.951),+/// Vector::new(-0.809, 0.588),+/// Vector::new(-0.809, -0.588),+/// Vector::new(0.309, -0.951),+/// ];+///+/// let square = vec![+/// Vector::new(-0.5, -0.5),+/// Vector::new(0.5, -0.5),+/// Vector::new(0.5, 0.5),+/// Vector::new(-0.5, 0.5),+/// ];+///+/// let mut components = Vec::new();+/// let mut current_component = Vec::new();+///+/// polygons_intersection(&pentagon, &square, |loc1, loc2| {+/// if loc1.is_none() && loc2.is_none() {+/// // End of a component+/// if !current_component.is_empty() {+/// components.push(std::mem::take(&mut current_component));+/// }+/// } else if let Some(loc) = loc1 {+/// current_component.push(loc.to_point(&pentagon));+/// } else if let Some(loc) = loc2 {+/// current_component.push(loc.to_point(&square));+/// }+/// }).unwrap();+///+/// // Should have at least one intersection component+/// assert!(!components.is_empty());+/// # }+/// ```+///+/// ## Example 2: Counting intersection vertices+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::transformation::polygons_intersection;+/// # use parry2d::math::Vector;+/// let hexagon = vec![+/// Vector::new(2.0, 0.0),+/// Vector::new(1.0, 1.732),+/// Vector::new(-1.0, 1.732),+/// Vector::new(-2.0, 0.0),+/// Vector::new(-1.0, -1.732),+/// Vector::new(1.0, -1.732),+/// ];+///+/// let circle_approx = vec![+/// Vector::new(1.0, 0.0),+/// Vector::new(0.707, 0.707),+/// Vector::new(0.0, 1.0),+/// Vector::new(-0.707, 0.707),+/// Vector::new(-1.0, 0.0),+/// Vector::new(-0.707, -0.707),+/// Vector::new(0.0, -1.0),+/// Vector::new(0.707, -0.707),+/// ];+///+/// let mut vertex_count = 0;+/// polygons_intersection(&hexagon, &circle_approx, |loc1, loc2| {+/// if loc1.is_some() || loc2.is_some() {+/// vertex_count += 1;+/// }+/// }).unwrap();+///+/// assert!(vertex_count > 0);+/// # }+/// ```+///+/// # Errors+///+/// Returns `PolygonsIntersectionError::InfiniteLoop` if the polygons are ill-formed.+///+/// # See Also+///+/// * [`polygons_intersection_points`] - Simpler vector-based output+/// * [`convex_polygons_intersection`] - Faster version for convex polygons+pub fn polygons_intersection(+ poly1: &[Vector2],+ poly2: &[Vector2],+ mut out: impl FnMut(Option<PolylinePointLocation>, Option<PolylinePointLocation>),+) -> Result<(), PolygonsIntersectionError> {+ let tolerances = PolygonIntersectionTolerances::default();++ #[derive(Debug)]+ struct ToTraverse {+ poly: usize,+ edge: EdgeId,+ }++ let (intersections, num_intersections) =+ compute_sorted_edge_intersections(poly1, poly2, tolerances.collinearity_epsilon);+ let mut visited = vec![false; num_intersections];+ let segment = |eid: EdgeId, poly: &[Vector2]| [poly[eid], poly[(eid + 1) % poly.len()]];++ // Traverse all the intersections.+ for inters in intersections[0].values() {+ for inter in inters {+ if visited[inter.id] {+ continue;+ }++ // We found an intersection we haven’t visited yet, traverse the loop, alternating+ // between poly1 and poly2 when reaching an intersection.+ let [a1, b1] = segment(inter.edges[0], poly1);+ let [a2, b2] = segment(inter.edges[1], poly2);+ let poly_to_traverse =+ match Triangle::orientation2d(a1, b1, a2, tolerances.collinearity_epsilon) {+ TriangleOrientation::Clockwise => 1,+ TriangleOrientation::CounterClockwise => 0,+ TriangleOrientation::Degenerate => {+ match Triangle::orientation2d(a1, b1, b2, tolerances.collinearity_epsilon) {+ TriangleOrientation::Clockwise => 0,+ TriangleOrientation::CounterClockwise => 1,+ TriangleOrientation::Degenerate => {+ log::debug!("Unhandled edge-edge overlap case.");+ 0+ }+ }+ }+ };++ #[derive(Debug)]+ enum TraversalStatus {+ OnVertex,+ OnIntersection(usize),+ }++ let polys = [poly1, poly2];+ let mut to_traverse = ToTraverse {+ poly: poly_to_traverse,+ edge: inter.edges[poly_to_traverse],+ };++ let mut status = TraversalStatus::OnIntersection(inter.id);++ for loop_id in 0.. {+ if loop_id > poly1.len() * poly2.len() {+ return Err(PolygonsIntersectionError::InfiniteLoop);+ }++ let empty = Vec::new();+ let edge_inters = intersections[to_traverse.poly]+ .get(&to_traverse.edge)+ .unwrap_or(&empty);++ match status {+ TraversalStatus::OnIntersection(inter_id) => {+ let (curr_inter_pos, curr_inter) = edge_inters+ .iter()+ .enumerate()+ .find(|(_, inter)| inter.id == inter_id)+ .unwrap_or_else(|| unreachable!());++ if visited[curr_inter.id] {+ // We already saw this intersection: we looped back to the start of+ // the intersection polygon.+ out(None, None);+ break;+ }++ out(Some(curr_inter.locs[0]), Some(curr_inter.locs[1]));+ visited[curr_inter.id] = true;++ if curr_inter_pos + 1 < edge_inters.len() {+ // There are other intersections after this one.+ // Move forward to the next intersection point and move on to traversing+ // the other polygon.+ let next_inter = &edge_inters[curr_inter_pos + 1];+ to_traverse.poly = (to_traverse.poly + 1) % 2;+ to_traverse.edge = next_inter.edges[to_traverse.poly];+ status = TraversalStatus::OnIntersection(next_inter.id);+ } else {+ // This was the last intersection, move to the next vertex on the+ // same polygon.+ to_traverse.edge =+ (to_traverse.edge + 1) % polys[to_traverse.poly].len();+ status = TraversalStatus::OnVertex;+ }+ }+ TraversalStatus::OnVertex => {+ let location = PolylinePointLocation::OnVertex(to_traverse.edge);++ if to_traverse.poly == 0 {+ out(Some(location), None);+ } else {+ out(None, Some(location))+ };++ if let Some(first_intersection) = edge_inters.first() {+ // Jump on the first intersection and move on to the other polygon.+ to_traverse.poly = (to_traverse.poly + 1) % 2;+ to_traverse.edge = first_intersection.edges[to_traverse.poly];+ status = TraversalStatus::OnIntersection(first_intersection.id);+ } else {+ // Move forward to the next vertex/edge on the same polygon.+ to_traverse.edge =+ (to_traverse.edge + 1) % polys[to_traverse.poly].len();+ }+ }+ }+ }+ }+ }++ // If there are no intersection, check if one polygon is inside the other.+ if intersections[0].is_empty() {+ if utils::point_in_poly2d(poly1[0], poly2) {+ for pt_id in 0..poly1.len() {+ out(Some(PolylinePointLocation::OnVertex(pt_id)), None)+ }+ out(None, None);+ } else if utils::point_in_poly2d(poly2[0], poly1) {+ for pt_id in 0..poly2.len() {+ out(None, Some(PolylinePointLocation::OnVertex(pt_id)))+ }+ out(None, None);+ }+ }++ Ok(())+}++type EdgeId = usize;+type IntersectionId = usize;++#[derive(Copy, Clone, Debug)]+struct IntersectionVector {+ id: IntersectionId,+ edges: [EdgeId; 2],+ locs: [PolylinePointLocation; 2],+}++fn compute_sorted_edge_intersections(+ poly1: &[Vector2],+ poly2: &[Vector2],+ eps: Real,+) -> ([HashMap<EdgeId, Vec<IntersectionVector>>; 2], usize) {+ let mut inter1: HashMap<EdgeId, Vec<IntersectionVector>> = HashMap::default();+ let mut inter2: HashMap<EdgeId, Vec<IntersectionVector>> = HashMap::default();+ let mut id = 0;++ // Find the intersections.+ // TODO: this is a naive O(n²) check. Could use an acceleration structure for large polygons.+ for i1 in 0..poly1.len() {+ let j1 = (i1 + 1) % poly1.len();++ for i2 in 0..poly2.len() {+ let j2 = (i2 + 1) % poly2.len();++ let Some(inter) =+ utils::segments_intersection2d(poly1[i1], poly1[j1], poly2[i2], poly2[j2], eps)+ else {+ continue;+ };++ match inter {+ SegmentsIntersection::Point { loc1, loc2 } => {+ let loc1 = PolylinePointLocation::from_segment_point_location(i1, j1, loc1);+ let loc2 = PolylinePointLocation::from_segment_point_location(i2, j2, loc2);+ let intersection = IntersectionVector {+ id,+ edges: [i1, i2],+ locs: [loc1, loc2],+ };+ inter1.entry(i1).or_default().push(intersection);+ inter2.entry(i2).or_default().push(intersection);+ id += 1;+ }+ SegmentsIntersection::Segment { .. } => {+ // TODO+ log::debug!(+ "Collinear segment-segment intersections not properly handled yet."+ );+ }+ }+ }+ }++ // Sort the intersections.+ for inters in inter1.values_mut() {+ inters.sort_by_key(|a| {+ let edge = [a.edges[0], (a.edges[0] + 1) % poly1.len()];+ OrderedFloat(a.locs[0].centered_bcoords(edge))+ });+ }++ for inters in inter2.values_mut() {+ inters.sort_by_key(|a| {+ let edge = [a.edges[1], (a.edges[1] + 1) % poly2.len()];+ OrderedFloat(a.locs[1].centered_bcoords(edge))+ });+ }++ ([inter1, inter2], id)+}++#[cfg(all(test, feature = "dim2"))]+mod test {+ use crate::math::Vector;+ use crate::query::PointQuery;+ use crate::shape::Triangle;+ use crate::transformation::convex_polygons_intersection_points_with_tolerances;+ use crate::transformation::polygon_intersection::PolygonIntersectionTolerances;+ use alloc::vec::Vec;+ use std::println;++ #[test]+ fn intersect_triangle_common_vertex() {+ let tris = [+ (+ Triangle::new(+ Vector::new(-0.0008759537858568062, -2.0103871966663305),+ Vector::new(0.3903908709629763, -1.3421764825890266),+ Vector::new(1.3380817875388151, -2.0098007857739013),+ ),+ Triangle::new(+ Vector::new(0.0, -0.0),+ Vector::new(-0.0008759537858568062, -2.0103871966663305),+ Vector::new(1.9991979155226394, -2.009511242880474),+ ),+ ),+ (+ Triangle::new(+ Vector::new(0.7319315811016305, -0.00004046981523721891),+ Vector::new(2.0004914907008944, -0.00011061077714557787),+ Vector::new(1.1848406021956144, -0.8155712451545468),+ ),+ Triangle::new(+ Vector::ZERO,+ Vector::new(0.00011061077714557787, -2.000024893134292),+ Vector::new(2.0004914907008944, -0.00011061077714557787),+ ),+ ),+ (+ Triangle::new(+ Vector::new(-0.000049995168258705205, -0.9898801451981707),+ Vector::new(0.0, -0.0),+ Vector::new(0.583013294019752, -1.4170136900568633),+ ),+ Triangle::new(+ Vector::new(0.0, -0.0),+ Vector::new(-0.00010101395240669591, -2.000027389553894),+ Vector::new(2.000372544168497, 0.00010101395240669591),+ ),+ ),+ (+ Triangle::new(+ Vector::new(-0.940565646581769, -0.939804943675256),+ Vector::new(0.0, -0.0),+ Vector::new(-0.001533592366792066, -0.9283586484736431),+ ),+ Triangle::new(+ Vector::new(0.0, -0.0),+ Vector::new(-2.00752629829582, -2.0059026672784825),+ Vector::new(-0.0033081650580626698, -2.0025945022204197),+ ),+ ),+ ];++ for (tri1, tri2) in tris {+ let mut inter = Vec::new();+ let tolerances = PolygonIntersectionTolerances {+ collinearity_epsilon: 1.0e-5,+ };+ convex_polygons_intersection_points_with_tolerances(+ tri1.vertices(),+ tri2.vertices(),+ tolerances,+ &mut inter,+ );++ println!("----------");+ println!("inter: {:?}", inter);+ println!(+ "tri1 is in tri2: {}",+ tri1.vertices().iter().all(|pt| tri2+ .project_local_point(*pt, false)+ .is_inside_eps(*pt, 1.0e-5))+ );+ println!(+ "tri2 is in tri1: {}",+ tri2.vertices().iter().all(|pt| tri1+ .project_local_point(*pt, false)+ .is_inside_eps(*pt, 1.0e-5))+ );+ for pt in &inter {+ let proj1 = tri1.project_local_point(*pt, false);+ let proj2 = tri2.project_local_point(*pt, false);+ assert!(proj1.is_inside_eps(*pt, 1.0e-5));+ assert!(proj2.is_inside_eps(*pt, 1.0e-5));+ }+ }+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/ball_to_outline.rs b/renderer/third_party/parry3d/src/transformation/to_outline/ball_to_outline.rsnew file mode 100644index 0000000..d84bcef--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/ball_to_outline.rs@@ -0,0 +1,68 @@+use crate::math::{Pose, Real, RealField, Vector};+use crate::shape::Ball;+use crate::transformation::utils;+use alloc::vec::Vec;++impl Ball {+ /// Outlines this ball’s shape using polylines.+ pub fn to_outline(&self, nsubdiv: u32) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let diameter = self.radius * 2.0;+ let (vtx, idx) = unit_sphere_outline(nsubdiv);+ (utils::scaled(vtx, Vector::splat(diameter)), idx)+ }+}++fn unit_sphere_outline(nsubdiv: u32) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let two_pi = Real::two_pi();+ let dtheta = two_pi / (nsubdiv as Real);+ let mut coords = Vec::new();+ let mut indices = Vec::new();++ utils::push_circle(0.5, nsubdiv, dtheta, 0.0, &mut coords);+ utils::push_circle(0.5, nsubdiv, dtheta, 0.0, &mut coords);+ utils::push_circle(0.5, nsubdiv, dtheta, 0.0, &mut coords);++ let n = nsubdiv as usize;+ utils::transform(+ &mut coords[n..n * 2],+ Pose::rotation(Vector::X * Real::frac_pi_2()),+ );+ utils::transform(+ &mut coords[n * 2..n * 3],+ Pose::rotation(Vector::Z * Real::frac_pi_2()),+ );++ utils::push_circle_outline_indices(&mut indices, 0..nsubdiv);+ utils::push_circle_outline_indices(&mut indices, nsubdiv..nsubdiv * 2);+ utils::push_circle_outline_indices(&mut indices, nsubdiv * 2..nsubdiv * 3);++ (coords, indices)+}++/// Creates an hemisphere with a radius of 0.5.+pub(crate) fn push_unit_hemisphere_outline(+ nsubdiv: u32,+ pts: &mut Vec<Vector>,+ idx: &mut Vec<[u32; 2]>,+) {+ let base_idx = pts.len() as u32;+ let dtheta = Real::pi() / (nsubdiv as Real);+ let npoints = nsubdiv + 1;++ utils::push_circle(0.5, npoints, dtheta, 0.0, pts);+ utils::push_circle(0.5, npoints, dtheta, 0.0, pts);++ let n = npoints as usize;+ utils::transform(+ &mut pts[base_idx as usize..base_idx as usize + n],+ Pose::rotation(Vector::X * -Real::frac_pi_2()),+ );+ utils::transform(+ &mut pts[base_idx as usize + n..base_idx as usize + n * 2],+ Pose::rotation(Vector::Z * Real::frac_pi_2())+ * Pose::rotation(Vector::Y * Real::frac_pi_2()),+ );++ utils::push_open_circle_outline_indices(idx, base_idx..base_idx + npoints);+ utils::push_open_circle_outline_indices(idx, base_idx + npoints..base_idx + npoints * 2);+}diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/capsule_to_outline.rs b/renderer/third_party/parry3d/src/transformation/to_outline/capsule_to_outline.rsnew file mode 100644index 0000000..398600f--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/capsule_to_outline.rs@@ -0,0 +1,43 @@+use crate::math::{Real, Vector};+use crate::shape::{Capsule, Cylinder};+use crate::transformation::utils;+use alloc::vec::Vec;++impl Capsule {+ /// Outlines this capsule’s shape using polylines.+ pub fn to_outline(&self, nsubdiv: u32) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let (vtx, idx) = canonical_capsule_outline(self.radius, self.half_height(), nsubdiv);+ (utils::transformed(vtx, self.canonical_transform()), idx)+ }+}++/// Generates a capsule.+pub(crate) fn canonical_capsule_outline(+ caps_radius: Real,+ cylinder_half_height: Real,+ nsubdiv: u32,+) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let (mut vtx, mut idx) = Cylinder::new(cylinder_half_height, caps_radius).to_outline(nsubdiv);+ let shift = vtx.len() as u32;++ // Generate the hemispheres.+ super::ball_to_outline::push_unit_hemisphere_outline(nsubdiv / 2, &mut vtx, &mut idx);+ super::ball_to_outline::push_unit_hemisphere_outline(nsubdiv / 2, &mut vtx, &mut idx);++ let ncap_pts = (nsubdiv / 2 + 1) * 2;+ vtx[shift as usize..(shift + ncap_pts) as usize]+ .iter_mut()+ .for_each(|pt| {+ *pt *= caps_radius * 2.0;+ pt.y += cylinder_half_height+ });++ vtx[(shift + ncap_pts) as usize..]+ .iter_mut()+ .for_each(|pt| {+ *pt *= caps_radius * 2.0;+ pt.y = -pt.y - cylinder_half_height+ });++ (vtx, idx)+}diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/cone_to_outline.rs b/renderer/third_party/parry3d/src/transformation/to_outline/cone_to_outline.rsnew file mode 100644index 0000000..02ac651--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/cone_to_outline.rs@@ -0,0 +1,24 @@+use crate::math::Vector;+use crate::shape::Cone;+use crate::transformation::utils;+use alloc::{vec, vec::Vec};++impl Cone {+ /// Outlines this cone’s shape using polylines.+ pub fn to_outline(&self, nsubdiv: u32) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let diameter = self.radius * 2.0;+ let height = self.half_height * 2.0;+ let scale = Vector::new(diameter, height, diameter);+ let (vtx, idx) = unit_cone_outline(nsubdiv);+ (utils::scaled(vtx, scale), idx)+ }+}++/// Generates a cone with unit height and diameter.+fn unit_cone_outline(nsubdiv: u32) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let mut out_vtx = vec![Vector::new(-0.5, -0.5, 0.0), Vector::new(0.0, 0.5, 0.0)];+ let mut out_ptx = vec![];+ #[allow(clippy::single_range_in_vec_init)] // The single range is on purpose.+ utils::apply_revolution(false, true, &[0..1], nsubdiv, &mut out_vtx, &mut out_ptx);+ (out_vtx, out_ptx)+}diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/convex_polyhedron_to_outline.rs b/renderer/third_party/parry3d/src/transformation/to_outline/convex_polyhedron_to_outline.rsnew file mode 100644index 0000000..da81748--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/convex_polyhedron_to_outline.rs@@ -0,0 +1,22 @@+use crate::math::Real;+use crate::shape::ConvexPolyhedron;+use crate::math::Vector3;++impl ConvexPolyhedron {+ /// Outlines this convex polyhedron’s shape using polylines.+ pub fn to_outline(&self) -> (Vec<Vector>, Vec<[u32; 3]>) {+ let mut indices = Vec::new();++ for face in self.faces() {+ let i1 = face.first_vertex_or_edge;+ let i2 = i1 + face.num_vertices_or_edges;+ let first_id = self.vertices_adj_to_face()[i1 as usize] as u32;++ for idx in self.vertices_adj_to_face()[i1 as usize + 1..i2 as usize].windows(2) {+ indices.push([first_id, idx[0] as u32, idx[1] as u32]);+ }+ }++ (self.points().to_vec(), indices)+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/cuboid_to_outline.rs b/renderer/third_party/parry3d/src/transformation/to_outline/cuboid_to_outline.rsnew file mode 100644index 0000000..ceee3a8--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/cuboid_to_outline.rs@@ -0,0 +1,50 @@+use crate::bounding_volume::Aabb;+use crate::math::Vector;+use crate::shape::Cuboid;+use crate::transformation::utils;+use alloc::{vec, vec::Vec};++impl Aabb {+ /// Outlines this Aabb’s shape using polylines.+ pub fn to_outline(&self) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let center = self.center();+ let half_extents = self.half_extents();+ let mut cube_mesh = Cuboid::new(half_extents).to_outline();+ cube_mesh.0.iter_mut().for_each(|p| *p += center);+ cube_mesh+ }+}++impl Cuboid {+ /// Outlines this cuboid’s shape using polylines.+ pub fn to_outline(&self) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let (vtx, idx) = unit_cuboid_outline();+ (utils::scaled(vtx, self.half_extents * 2.0), idx)+ }+}++/**+ * Generates a cuboid shape with a split index buffer.+ *+ * The cuboid is centered at the origin, and has its half extents set to 0.5.+ */+fn unit_cuboid_outline() -> (Vec<Vector>, Vec<[u32; 2]>) {+ let aabb = Aabb::from_half_extents(Vector::ZERO, Vector::splat(0.5));+ (+ aabb.vertices().to_vec(),+ vec![+ [0, 1],+ [1, 2],+ [2, 3],+ [3, 0],+ [4, 5],+ [5, 6],+ [6, 7],+ [7, 4],+ [0, 4],+ [1, 5],+ [2, 6],+ [3, 7],+ ],+ )+}diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/cylinder_to_outline.rs b/renderer/third_party/parry3d/src/transformation/to_outline/cylinder_to_outline.rsnew file mode 100644index 0000000..ec232ae--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/cylinder_to_outline.rs@@ -0,0 +1,24 @@+use crate::math::Vector;+use crate::shape::Cylinder;+use crate::transformation::utils;+use alloc::{vec, vec::Vec};++impl Cylinder {+ /// Outlines this cylinder’s shape using polylines.+ pub fn to_outline(&self, nsubdiv: u32) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let diameter = self.radius * 2.0;+ let height = self.half_height * 2.0;+ let scale = Vector::new(diameter, height, diameter);+ let (vtx, idx) = unit_cylinder_outline(nsubdiv);+ (utils::scaled(vtx, scale), idx)+ }+}++/// Generates a cylinder with unit height and diameter.+fn unit_cylinder_outline(nsubdiv: u32) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let mut out_vtx = vec![Vector::new(-0.5, -0.5, 0.0), Vector::new(-0.5, 0.5, 0.0)];+ let mut out_idx = vec![];+ #[allow(clippy::single_range_in_vec_init)] // The single range is on purpose.+ utils::apply_revolution(false, false, &[0..2], nsubdiv, &mut out_vtx, &mut out_idx);+ (out_vtx, out_idx)+}diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/heightfield_to_outline.rs b/renderer/third_party/parry3d/src/transformation/to_outline/heightfield_to_outline.rsnew file mode 100644index 0000000..c04b2ee--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/heightfield_to_outline.rs@@ -0,0 +1,10 @@+use crate::math::Real;+use crate::shape::{HeightField, HeightFieldCellStatus};+use crate::math::Vector3;++impl HeightField {+ /// Outlines this heightfield’s shape using polylines.+ pub fn to_outline(&self) -> (Vec<Vector>, Vec<[u32; 2]>) {+ todo!()+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/mod.rs b/renderer/third_party/parry3d/src/transformation/to_outline/mod.rsnew file mode 100644index 0000000..c7a3668--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/mod.rs@@ -0,0 +1,13 @@+mod ball_to_outline;+mod capsule_to_outline;+mod cone_to_outline;+// mod convex_polyhedron_to_outline;+mod cuboid_to_outline;+mod cylinder_to_outline;+mod round_cone_to_outline;+mod round_convex_polyhedron_to_outline;+mod round_cuboid_to_outline;+mod round_cylinder_to_outline;+mod voxels_to_outline;+// mod round_triangle_to_outline;+// mod heightfield_to_outline;diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/round_cone_to_outline.rs b/renderer/third_party/parry3d/src/transformation/to_outline/round_cone_to_outline.rsnew file mode 100644index 0000000..e4ef868--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/round_cone_to_outline.rs@@ -0,0 +1,41 @@+use crate::math::Vector;+use crate::shape::RoundCone;+use crate::transformation::utils;+use alloc::{vec, vec::Vec};++impl RoundCone {+ /// Outlines this round cone’s shape using polylines.+ pub fn to_outline(&self, nsubdiv: u32, border_nsubdiv: u32) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let r = self.inner_shape.radius;+ let br = self.border_radius;+ let he = self.inner_shape.half_height;++ let mut out_vtx = vec![];+ let mut out_idx = vec![];++ // Compute the profile.+ let center_ab = Vector::new(-r, -he, 0.0);+ let center_cd = Vector::new(0.0, he, 0.0);+ let side_dir = Vector::new(-2.0 * he, r, 0.0).normalize();++ let a = Vector::new(-r, -he - br, 0.0);+ let b = Vector::new(-r, -he, 0.0) + side_dir * br;+ let c = Vector::new(0.0, he, 0.0) + side_dir * br;+ let d = Vector::new(0.0, he + br, 0.0);++ out_vtx.push(a);+ utils::push_arc(center_ab, a, b, border_nsubdiv, &mut out_vtx);+ out_vtx.push(b);+ out_vtx.push(c);+ utils::push_arc(center_cd, c, d, border_nsubdiv, &mut out_vtx);+ out_vtx.push(d);++ let circles = [+ 0..1,+ border_nsubdiv..border_nsubdiv + 2,+ border_nsubdiv * 2 + 1..border_nsubdiv * 2 + 2,+ ];+ utils::apply_revolution(false, true, &circles, nsubdiv, &mut out_vtx, &mut out_idx);+ (out_vtx, out_idx)+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/round_convex_polyhedron_to_outline.rs b/renderer/third_party/parry3d/src/transformation/to_outline/round_convex_polyhedron_to_outline.rsnew file mode 100644index 0000000..7ba4bba--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/round_convex_polyhedron_to_outline.rs@@ -0,0 +1,71 @@+use crate::math::Vector;+use crate::shape::RoundConvexPolyhedron;+use crate::transformation::utils;+use alloc::{vec, vec::Vec};++impl RoundConvexPolyhedron {+ /// Outlines this round convex polyhedron’s shape using polylines.+ pub fn to_outline(&self, nsubdivs: u32) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let mut out_vtx = vec![];+ let mut out_idx = vec![];+ let poly = &self.inner_shape;++ // 1. Compute the offset vertices.+ for (vid, ref_vtx) in poly.vertices().iter().enumerate() {+ let ref_pt = poly.points()[vid];+ let range = ref_vtx.first_adj_face_or_edge as usize+ ..(ref_vtx.first_adj_face_or_edge + ref_vtx.num_adj_faces_or_edge) as usize;+ let adj_faces = &poly.faces_adj_to_vertex()[range];++ for fid in adj_faces {+ let face = poly.faces()[*fid as usize];+ out_vtx.push(ref_pt + face.normal * self.border_radius);+ }+ }++ // 2. Compute the straight edges.+ // TODO: right now, each vertex of the final polyline will be duplicated+ // here, to simplify the index buffer generation for the straight edges.+ for face in poly.faces() {+ let i1 = face.first_vertex_or_edge;+ let i2 = i1 + face.num_vertices_or_edges;+ let base = out_vtx.len() as u32;++ for idx in &poly.vertices_adj_to_face()[i1 as usize..i2 as usize] {+ out_vtx.push(poly.points()[*idx as usize] + face.normal * self.border_radius);+ }++ for i in 0..face.num_vertices_or_edges - 1 {+ out_idx.push([base + i, base + i + 1]);+ }++ out_idx.push([base, base + face.num_vertices_or_edges - 1]);+ }++ // 3. Compute the arcs.+ let mut arc_base = 0;+ for (vid, ref_vtx) in poly.vertices().iter().enumerate() {+ let ref_pt = poly.points()[vid];+ let n = ref_vtx.num_adj_faces_or_edge;++ if n > 0 {+ for k1 in 0..n {+ for k2 in k1 + 1..n {+ utils::push_arc_and_idx(+ ref_pt,+ arc_base + k1,+ arc_base + k2,+ nsubdivs,+ &mut out_vtx,+ &mut out_idx,+ );+ }+ }++ arc_base += n;+ }+ }++ (out_vtx, out_idx)+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/round_cuboid_to_outline.rs b/renderer/third_party/parry3d/src/transformation/to_outline/round_cuboid_to_outline.rsnew file mode 100644index 0000000..4e8f4af--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/round_cuboid_to_outline.rs@@ -0,0 +1,62 @@+use crate::bounding_volume::Aabb;+use crate::math::Vector;+use crate::shape::RoundCuboid;+use crate::transformation::utils;+use alloc::{vec, vec::Vec};++impl RoundCuboid {+ /// Outlines this round cuboid’s surface with polylines.+ pub fn to_outline(&self, nsubdivs: u32) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let aabb = Aabb::from_half_extents(Vector::ZERO, self.inner_shape.half_extents);+ let aabb_vtx = aabb.vertices();+ let fidx = Aabb::FACES_VERTEX_IDS;+ let x = Vector::X * self.border_radius;+ let y = Vector::Y * self.border_radius;+ let z = Vector::Z * self.border_radius;++ #[rustfmt::skip]+ let mut vtx = vec![+ aabb_vtx[fidx[0].0] + x, aabb_vtx[fidx[0].1] + x, aabb_vtx[fidx[0].2] + x, aabb_vtx[fidx[0].3] + x,+ aabb_vtx[fidx[1].0] - x, aabb_vtx[fidx[1].1] - x, aabb_vtx[fidx[1].2] - x, aabb_vtx[fidx[1].3] - x,+ aabb_vtx[fidx[2].0] + y, aabb_vtx[fidx[2].1] + y, aabb_vtx[fidx[2].2] + y, aabb_vtx[fidx[2].3] + y,+ aabb_vtx[fidx[3].0] - y, aabb_vtx[fidx[3].1] - y, aabb_vtx[fidx[3].2] - y, aabb_vtx[fidx[3].3] - y,+ aabb_vtx[fidx[4].0] + z, aabb_vtx[fidx[4].1] + z, aabb_vtx[fidx[4].2] + z, aabb_vtx[fidx[4].3] + z,+ aabb_vtx[fidx[5].0] - z, aabb_vtx[fidx[5].1] - z, aabb_vtx[fidx[5].2] - z, aabb_vtx[fidx[5].3] - z,+ ];++ let mut idx = vec![];+ for i in 0..6 {+ idx.push([i * 4, i * 4 + 1]);+ idx.push([i * 4 + 1, i * 4 + 2]);+ idx.push([i * 4 + 2, i * 4 + 3]);+ idx.push([i * 4 + 3, i * 4]);+ }++ let arcs = [+ [4, 13, 20],+ [0, 12, 21],+ [1, 8, 22],+ [5, 9, 23],+ [7, 14, 16],+ [3, 15, 17],+ [2, 11, 18],+ [6, 10, 19],+ ];++ for (center, aidx) in arcs.iter().enumerate() {+ for ia in 0..3 {+ let ib = (ia + 1) % 3;+ utils::push_arc_and_idx(+ aabb_vtx[center],+ aidx[ia],+ aidx[ib],+ nsubdivs,+ &mut vtx,+ &mut idx,+ );+ }+ }++ (vtx, idx)+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/round_cylinder_to_outline.rs b/renderer/third_party/parry3d/src/transformation/to_outline/round_cylinder_to_outline.rsnew file mode 100644index 0000000..754d87c--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/round_cylinder_to_outline.rs@@ -0,0 +1,39 @@+use crate::math::Vector;+use crate::shape::RoundCylinder;+use crate::transformation::utils;+use alloc::{vec, vec::Vec};++impl RoundCylinder {+ /// Outlines this round cylinder’s shape using polylines.+ pub fn to_outline(&self, nsubdiv: u32, border_nsubdiv: u32) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let r = self.inner_shape.radius;+ let br = self.border_radius;+ let he = self.inner_shape.half_height;++ let mut out_vtx = vec![];+ let mut out_idx = vec![];++ // Compute the profile.+ let center_ab = Vector::new(-r, -he, 0.0);+ let center_cd = Vector::new(-r, he, 0.0);+ let a = Vector::new(-r, -he - br, 0.0);+ let b = Vector::new(-r - br, -he, 0.0);+ let c = Vector::new(-r - br, he, 0.0);+ let d = Vector::new(-r, he + br, 0.0);++ out_vtx.push(a);+ utils::push_arc(center_ab, a, b, border_nsubdiv, &mut out_vtx);+ out_vtx.push(b);+ out_vtx.push(c);+ utils::push_arc(center_cd, c, d, border_nsubdiv, &mut out_vtx);+ out_vtx.push(d);++ let circles = [+ 0..1,+ border_nsubdiv..border_nsubdiv + 2,+ border_nsubdiv * 2 + 1..border_nsubdiv * 2 + 2,+ ];+ utils::apply_revolution(false, false, &circles, nsubdiv, &mut out_vtx, &mut out_idx);+ (out_vtx, out_idx)+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/round_triangle_to_outline.rs b/renderer/third_party/parry3d/src/transformation/to_outline/round_triangle_to_outline.rsnew file mode 100644index 0000000..6691da8--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/round_triangle_to_outline.rs@@ -0,0 +1,33 @@+use crate::bounding_volume::Aabb;+use crate::math::{Vector, Real, Vector};+use crate::shape::RoundTriangle;+use crate::transformation::utils;++impl RoundTriangle {+ /// Outlines this round triangle’s surface with polylines.+ pub fn to_outline(&self, nsubdivs: u32) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let tri = &self.inner_shape;+ let n = tri+ .normal()+ .map(|n| n.into_inner())+ .unwrap_or_else(|| Vector::ZERO);+ let mut out_vtx = vec![+ tri.a + n * self.border_radius,+ tri.b + n * self.border_radius,+ tri.c + n * self.border_radius,+ tri.a - n * self.border_radius,+ tri.b - n * self.border_radius,+ tri.c - n * self.border_radius,+ ];+ let mut out_idx = vec![[0, 1], [1, 2], [2, 0], [3, 4], [4, 5], [5, 3]];+ let ab = tri.b - tri.a;+ let ac = tri.c - tri.a;+ let bc = tri.b - tri.c;++ utils::push_arc_and_idx(tri.a, 0, 3, nsubdivs, &mut out_vtx, &mut out_idx);+ utils::push_arc_and_idx(tri.b, 1, 4, nsubdivs, &mut out_vtx, &mut out_idx);+ utils::push_arc_and_idx(tri.c, 2, 5, nsubdivs, &mut out_vtx, &mut out_idx);++ (out_vtx, out_idx)+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_outline/voxels_to_outline.rs b/renderer/third_party/parry3d/src/transformation/to_outline/voxels_to_outline.rsnew file mode 100644index 0000000..dd9fb0f--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_outline/voxels_to_outline.rs@@ -0,0 +1,56 @@+use crate::bounding_volume::Aabb;+use crate::math::Vector;+use crate::shape::{VoxelType, Voxels};+use alloc::{vec, vec::Vec};++impl Voxels {+ /// Outlines this voxels shape as a set of polylines.+ ///+ /// The outline is such that only convex edges are output in the polyline.+ pub fn to_outline(&self) -> (Vec<Vector>, Vec<[u32; 2]>) {+ let mut points = vec![];+ self.iter_outline(|a, b| {+ points.push(a);+ points.push(b);+ });+ let indices = (0..points.len() as u32 / 2)+ .map(|i| [i * 2, i * 2 + 1])+ .collect();+ (points, indices)+ }++ /// Outlines this voxels shape using segments.+ ///+ /// The outline is such that only convex edges are output in the polyline.+ pub fn iter_outline(&self, mut f: impl FnMut(Vector, Vector)) {+ // TODO: move this as a new method: Voxels::to_outline?+ let radius = self.voxel_size() / 2.0;+ let aabb = Aabb::from_half_extents(Vector::ZERO, radius);+ let vtx = aabb.vertices();++ for vox in self.voxels() {+ match vox.state.voxel_type() {+ VoxelType::Vertex => {+ let mask = vox.state.feature_mask();++ for edge in Aabb::EDGES_VERTEX_IDS {+ if mask & (1 << edge.0) != 0 || mask & (1 << edge.1) != 0 {+ f(vox.center + vtx[edge.0], vox.center + vtx[edge.1]);+ }+ }+ }+ VoxelType::Edge => {+ let vtx = aabb.vertices();+ let mask = vox.state.feature_mask();++ for (i, edge) in Aabb::EDGES_VERTEX_IDS.iter().enumerate() {+ if mask & (1 << i) != 0 {+ f(vox.center + vtx[edge.0], vox.center + vtx[edge.1]);+ }+ }+ }+ _ => {}+ }+ }+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_polyline/ball_to_polyline.rs b/renderer/third_party/parry3d/src/transformation/to_polyline/ball_to_polyline.rsnew file mode 100644index 0000000..9a8b443--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_polyline/ball_to_polyline.rs@@ -0,0 +1,18 @@+use crate::math::{Real, RealField, Vector2};+use crate::shape::Ball;+use crate::transformation::utils;+use alloc::vec::Vec;++impl Ball {+ /// Discretize the boundary of this ball as a polygonal line.+ pub fn to_polyline(&self, nsubdivs: u32) -> Vec<Vector2> {+ let diameter = self.radius * 2.0;+ let two_pi = Real::two_pi();+ let dtheta = two_pi / (nsubdivs as Real);++ let mut pts = Vec::with_capacity(nsubdivs as usize);+ utils::push_xy_arc(diameter / 2.0, nsubdivs, dtheta, &mut pts);++ pts+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_polyline/capsule_to_polyline.rs b/renderer/third_party/parry3d/src/transformation/to_polyline/capsule_to_polyline.rsnew file mode 100644index 0000000..035bfe2--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_polyline/capsule_to_polyline.rs@@ -0,0 +1,27 @@+use crate::math::{Real, RealField, Vector, Vector2};+use crate::shape::Capsule;+use crate::transformation::utils;+use alloc::vec::Vec;++impl Capsule {+ /// Discretize the boundary of this capsule as a polygonal line.+ pub fn to_polyline(&self, nsubdiv: u32) -> Vec<Vector2> {+ let pi = Real::pi();+ let dtheta = pi / (nsubdiv as Real);++ let mut points: Vec<Vector2> = Vec::with_capacity(nsubdiv as usize);++ utils::push_xy_arc(self.radius, nsubdiv, dtheta, &mut points);++ let npoints = points.len();++ for i in 0..npoints {+ let new_point = points[i] + Vector::new(0.0, self.half_height());++ points.push(-new_point);+ points[i] = new_point;+ }++ utils::transformed(points, self.canonical_transform())+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_polyline/cuboid_to_polyline.rs b/renderer/third_party/parry3d/src/transformation/to_polyline/cuboid_to_polyline.rsnew file mode 100644index 0000000..f4056d2--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_polyline/cuboid_to_polyline.rs@@ -0,0 +1,21 @@+use crate::math::Vector2;+use crate::shape::Cuboid;+use crate::transformation::utils;+use alloc::{vec, vec::Vec};++impl Cuboid {+ /// Discretize the boundary of this cuboid as a polygonal line.+ pub fn to_polyline(&self) -> Vec<Vector2> {+ utils::scaled(unit_rectangle(), self.half_extents * 2.0)+ }+}++/// The contour of a unit cuboid lying on the x-y plane.+fn unit_rectangle() -> Vec<Vector2> {+ vec![+ Vector2::new(-0.5, -0.5),+ Vector2::new(0.5, -0.5),+ Vector2::new(0.5, 0.5),+ Vector2::new(-0.5, 0.5),+ ]+}diff --git a/renderer/third_party/parry3d/src/transformation/to_polyline/heightfield_to_polyline.rs b/renderer/third_party/parry3d/src/transformation/to_polyline/heightfield_to_polyline.rsnew file mode 100644index 0000000..9ecd221--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_polyline/heightfield_to_polyline.rs@@ -0,0 +1,25 @@+use crate::math::Vector2;+use crate::shape::HeightField;+use alloc::{vec, vec::Vec};++impl HeightField {+ /// Rasterize this heightfield as a (potentially discontinuous) polyline.+ pub fn to_polyline(&self) -> (Vec<Vector2>, Vec<[u32; 2]>) {+ let mut vertices = vec![];+ let mut indices = vec![];++ for seg in self.segments() {+ let base_id = vertices.len() as u32;+ if vertices.last().map(|pt| seg.a != *pt).unwrap_or(true) {+ indices.push([base_id, base_id + 1]);+ vertices.push(seg.a);+ } else {+ indices.push([base_id - 1, base_id]);+ }++ vertices.push(seg.b);+ }++ (vertices, indices)+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_polyline/mod.rs b/renderer/third_party/parry3d/src/transformation/to_polyline/mod.rsnew file mode 100644index 0000000..3be47d4--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_polyline/mod.rs@@ -0,0 +1,7 @@+mod ball_to_polyline;+mod capsule_to_polyline;+mod cuboid_to_polyline;+mod heightfield_to_polyline;+mod round_convex_polygon_to_polyline;+mod round_cuboid_to_polyline;+mod voxels_to_polyline;diff --git a/renderer/third_party/parry3d/src/transformation/to_polyline/round_convex_polygon_to_polyline.rs b/renderer/third_party/parry3d/src/transformation/to_polyline/round_convex_polygon_to_polyline.rsnew file mode 100644index 0000000..a208a2c--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_polyline/round_convex_polygon_to_polyline.rs@@ -0,0 +1,34 @@+use crate::math::Vector2;+use crate::shape::RoundConvexPolygon;+use crate::transformation::utils;+use alloc::{vec, vec::Vec};++impl RoundConvexPolygon {+ /// Discretize the boundary of this round convex polygon as a polygonal line.+ pub fn to_polyline(&self, border_subdivs: u32) -> Vec<Vector2> {+ let mut out_vtx = vec![];+ let pts = self.inner_shape.points();+ let ns = self.inner_shape.normals();+ let br = self.border_radius;++ out_vtx.push(pts[0] + *ns.last().unwrap() * br);++ for ia in 0..pts.len() - 1 {+ let ib = ia + 1;++ let arc_start = *out_vtx.last().unwrap();+ let arc_end = pts[ia] + ns[ia] * br;+ utils::push_arc(pts[ia], arc_start, arc_end, border_subdivs, &mut out_vtx);+ out_vtx.push(arc_end);+ out_vtx.push(pts[ib] + ns[ia] * br);+ }++ let arc_center = *pts.last().unwrap();+ let arc_start = *out_vtx.last().unwrap();+ let arc_end = arc_center + *ns.last().unwrap() * br;+ utils::push_arc(arc_center, arc_start, arc_end, border_subdivs, &mut out_vtx);+ out_vtx.push(arc_end);++ out_vtx+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_polyline/round_cuboid_to_polyline.rs b/renderer/third_party/parry3d/src/transformation/to_polyline/round_cuboid_to_polyline.rsnew file mode 100644index 0000000..f3c5b35--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_polyline/round_cuboid_to_polyline.rs@@ -0,0 +1,49 @@+use crate::math::Vector2;+use crate::shape::RoundCuboid;+use crate::transformation::utils;+use alloc::{vec, vec::Vec};++impl RoundCuboid {+ /// Discretize the boundary of this round cuboid as a polygonal line.+ pub fn to_polyline(&self, border_subdivs: u32) -> Vec<Vector2> {+ let mut out_vtx = vec![];+ let he = self.inner_shape.half_extents;+ let br = self.border_radius;++ let arc_centers = [+ Vector2::new(-he.x, -he.y),+ Vector2::new(he.x, -he.y),+ Vector2::new(he.x, he.y),+ Vector2::new(-he.x, he.y),+ ];+ let arc_vertices = [+ (+ Vector2::new(-he.x - br, -he.y),+ Vector2::new(-he.x, -he.y - br),+ ),+ (+ Vector2::new(he.x, -he.y - br),+ Vector2::new(he.x + br, -he.y),+ ),+ (Vector2::new(he.x + br, he.y), Vector2::new(he.x, he.y + br)),+ (+ Vector2::new(-he.x, he.y + br),+ Vector2::new(-he.x - br, he.y),+ ),+ ];++ for i in 0..4 {+ out_vtx.push(arc_vertices[i].0);+ utils::push_arc(+ arc_centers[i],+ arc_vertices[i].0,+ arc_vertices[i].1,+ border_subdivs,+ &mut out_vtx,+ );+ out_vtx.push(arc_vertices[i].1);+ }++ out_vtx+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_polyline/voxels_to_polyline.rs b/renderer/third_party/parry3d/src/transformation/to_polyline/voxels_to_polyline.rsnew file mode 100644index 0000000..727f3f4--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_polyline/voxels_to_polyline.rs@@ -0,0 +1,52 @@+use crate::bounding_volume::Aabb;+use crate::math::{Vector, Vector2};+use crate::shape::{VoxelType, Voxels};+use alloc::{vec, vec::Vec};++impl Voxels {+ /// Converts the outlines of this set of voxels as a polyline.+ pub fn to_polyline(&self) -> (Vec<Vector2>, Vec<[u32; 2]>) {+ let mut points = vec![];+ self.iter_outline(|a, b| {+ points.push(a);+ points.push(b);+ });+ let indices = (0..points.len() as u32 / 2)+ .map(|i| [i * 2, i * 2 + 1])+ .collect();+ (points, indices)+ }++ /// Outlines this voxels shape with segments.+ pub fn iter_outline(&self, mut f: impl FnMut(Vector, Vector)) {+ // TODO: move this as a new method: Voxels::to_outline?+ let radius = self.voxel_size() / 2.0;+ let aabb = Aabb::from_half_extents(Vector::ZERO, radius);+ let vtx = aabb.vertices();++ for vox in self.voxels() {+ match vox.state.voxel_type() {+ VoxelType::Vertex => {+ let mask = vox.state.feature_mask();++ for edge in Aabb::FACES_VERTEX_IDS {+ if mask & (1 << edge.0) != 0 || mask & (1 << edge.1) != 0 {+ f(vox.center + vtx[edge.0], vox.center + vtx[edge.1]);+ }+ }+ }+ VoxelType::Face => {+ let vtx = aabb.vertices();+ let mask = vox.state.feature_mask();++ for (i, edge) in Aabb::FACES_VERTEX_IDS.iter().enumerate() {+ if mask & (1 << i) != 0 {+ f(vox.center + vtx[edge.0], vox.center + vtx[edge.1]);+ }+ }+ }+ _ => {}+ }+ }+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_trimesh/ball_to_trimesh.rs b/renderer/third_party/parry3d/src/transformation/to_trimesh/ball_to_trimesh.rsnew file mode 100644index 0000000..f7def9a--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_trimesh/ball_to_trimesh.rs@@ -0,0 +1,110 @@+use crate::math::{ComplexField, Real, RealField, Vector, Vector3, DIM};+use crate::shape::Ball;+use crate::transformation::utils;+use alloc::vec::Vec;++impl Ball {+ /// Discretize the boundary of this ball as a triangle-mesh.+ pub fn to_trimesh(+ &self,+ ntheta_subdiv: u32,+ nphi_subdiv: u32,+ ) -> (Vec<Vector3>, Vec<[u32; 3]>) {+ let diameter = self.radius * 2.0;+ let (vtx, idx) = unit_sphere(ntheta_subdiv, nphi_subdiv);+ (utils::scaled(vtx, Vector::splat(diameter)), idx)+ }+}++fn unit_sphere(ntheta_subdiv: u32, nphi_subdiv: u32) -> (Vec<Vector3>, Vec<[u32; 3]>) {+ let dtheta = Real::two_pi() / (ntheta_subdiv as Real);+ let dphi = Real::pi() / (nphi_subdiv as Real);++ let mut coords = Vec::new();+ let mut curr_phi: Real = -Real::frac_pi_2() + dphi;++ coords.push(Vector::new(0.0, -1.0, 0.0));++ for _ in 1..nphi_subdiv {+ utils::push_circle(+ <Real as ComplexField>::cos(curr_phi),+ ntheta_subdiv,+ dtheta,+ <Real as ComplexField>::sin(curr_phi),+ &mut coords,+ );+ curr_phi += dphi;+ }++ coords.push(Vector::new(0.0, 1.0, 0.0));++ let mut idx = Vec::new();++ utils::push_degenerate_top_ring_indices(1, 0, ntheta_subdiv, &mut idx);+ utils::reverse_clockwising(&mut idx);++ for i in 0..nphi_subdiv - 2 {+ utils::push_ring_indices(+ 1 + i * ntheta_subdiv,+ 1 + (i + 1) * ntheta_subdiv,+ ntheta_subdiv,+ &mut idx,+ );+ }++ utils::push_degenerate_top_ring_indices(+ coords.len() as u32 - 1 - ntheta_subdiv,+ coords.len() as u32 - 1,+ ntheta_subdiv,+ &mut idx,+ );++ (utils::scaled(coords, Vector::splat(0.5)), idx)+}++/// Creates an hemisphere with a diameter of 1.+pub(crate) fn unit_hemisphere(+ ntheta_subdiv: u32,+ nphi_subdiv: u32,+) -> (Vec<Vector>, Vec<[u32; DIM]>) {+ let two_pi = Real::two_pi();+ let pi_two = Real::frac_pi_2();+ let dtheta = two_pi / (ntheta_subdiv as Real);+ let dphi = pi_two / (nphi_subdiv as Real);++ let mut coords = Vec::new();+ let mut curr_phi: Real = 0.0;++ for _ in 0..nphi_subdiv {+ utils::push_circle(+ <Real as ComplexField>::cos(curr_phi),+ ntheta_subdiv,+ dtheta,+ <Real as ComplexField>::sin(curr_phi),+ &mut coords,+ );+ curr_phi += dphi;+ }++ coords.push(Vector::new(0.0, 1.0, 0.0));++ let mut idx = Vec::new();++ for i in 0..nphi_subdiv - 1 {+ utils::push_ring_indices(+ i * ntheta_subdiv,+ (i + 1) * ntheta_subdiv,+ ntheta_subdiv,+ &mut idx,+ );+ }++ utils::push_degenerate_top_ring_indices(+ (nphi_subdiv - 1) * ntheta_subdiv,+ coords.len() as u32 - 1,+ ntheta_subdiv,+ &mut idx,+ );++ (utils::scaled(coords, Vector::splat(0.5)), idx)+}diff --git a/renderer/third_party/parry3d/src/transformation/to_trimesh/capsule_to_trimesh.rs b/renderer/third_party/parry3d/src/transformation/to_trimesh/capsule_to_trimesh.rsnew file mode 100644index 0000000..162f731--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_trimesh/capsule_to_trimesh.rs@@ -0,0 +1,68 @@+use crate::math::{Real, Vector3};+use crate::shape::Capsule;+use crate::transformation::utils;+use alloc::vec::Vec;++impl Capsule {+ /// Discretize the boundary of this capsule as a triangle-mesh.+ pub fn to_trimesh(+ &self,+ ntheta_subdiv: u32,+ nphi_subdiv: u32,+ ) -> (Vec<Vector3>, Vec<[u32; 3]>) {+ let diameter = self.radius * 2.0;+ let height = self.half_height() * 2.0;+ let (vtx, idx) = canonical_capsule(diameter, height, ntheta_subdiv, nphi_subdiv);+ (utils::transformed(vtx, self.canonical_transform()), idx)+ }+}++/// Generates a capsule.+pub(crate) fn canonical_capsule(+ caps_diameter: Real,+ cylinder_height: Real,+ ntheta_subdiv: u32,+ nphi_subdiv: u32,+) -> (Vec<Vector3>, Vec<[u32; 3]>) {+ let (coords, indices) = super::ball_to_trimesh::unit_hemisphere(ntheta_subdiv, nphi_subdiv / 2);+ let mut bottom_coords = coords.clone();+ let mut bottom_indices = indices.clone();+ utils::reverse_clockwising(&mut bottom_indices[..]);++ let mut top_coords = coords;+ let mut top_indices = indices;++ let half_height = cylinder_height * 0.5;++ // shift the top+ for coord in top_coords.iter_mut() {+ coord.x *= caps_diameter;+ coord.y = coord.y * caps_diameter + half_height;+ coord.z *= caps_diameter;+ }++ // flip + shift the bottom+ for coord in bottom_coords.iter_mut() {+ coord.x *= caps_diameter;+ coord.y = -(coord.y * caps_diameter) - half_height;+ coord.z *= caps_diameter;+ }++ // shift the top index buffer+ let base_top_coords = bottom_coords.len() as u32;++ for idx in top_indices.iter_mut() {+ idx[0] += base_top_coords;+ idx[1] += base_top_coords;+ idx[2] += base_top_coords;+ }++ // merge all buffers+ bottom_coords.extend(top_coords);+ bottom_indices.extend(top_indices);++ // attach the two caps+ utils::push_ring_indices(0, base_top_coords, ntheta_subdiv, &mut bottom_indices);++ (bottom_coords, bottom_indices)+}diff --git a/renderer/third_party/parry3d/src/transformation/to_trimesh/cone_to_trimesh.rs b/renderer/third_party/parry3d/src/transformation/to_trimesh/cone_to_trimesh.rsnew file mode 100644index 0000000..8fe1a7e--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_trimesh/cone_to_trimesh.rs@@ -0,0 +1,32 @@+use crate::math::{Real, RealField, Vector};+use crate::shape::Cone;+use crate::transformation::utils;+use alloc::vec::Vec;++impl Cone {+ /// Discretize the boundary of this cone as a triangle-mesh.+ pub fn to_trimesh(&self, nsubdiv: u32) -> (Vec<Vector>, Vec<[u32; 3]>) {+ let diameter = self.radius * 2.0;+ let height = self.half_height * 2.0;+ let scale = Vector::new(diameter, height, diameter);+ let (vtx, idx) = unit_cone(nsubdiv);+ (utils::scaled(vtx, scale), idx)+ }+}++/// Generates a cone with unit height and diameter.+fn unit_cone(nsubdiv: u32) -> (Vec<Vector>, Vec<[u32; 3]>) {+ let two_pi = Real::two_pi();+ let dtheta = two_pi / (nsubdiv as Real);+ let mut coords = Vec::new();+ let mut indices = Vec::new();++ utils::push_circle(0.5, nsubdiv, dtheta, -0.5, &mut coords);++ coords.push(Vector::new(0.0, 0.5, 0.0));++ utils::push_degenerate_top_ring_indices(0, coords.len() as u32 - 1, nsubdiv, &mut indices);+ utils::push_filled_circle_indices(0, nsubdiv, &mut indices);++ (coords, indices)+}diff --git a/renderer/third_party/parry3d/src/transformation/to_trimesh/convex_polyhedron_to_trimesh.rs b/renderer/third_party/parry3d/src/transformation/to_trimesh/convex_polyhedron_to_trimesh.rsnew file mode 100644index 0000000..c72d675--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_trimesh/convex_polyhedron_to_trimesh.rs@@ -0,0 +1,22 @@+use crate::math::Vector3;+use crate::shape::ConvexPolyhedron;+use alloc::vec::Vec;++impl ConvexPolyhedron {+ /// Discretize the boundary of this convex polyhedron as a triangle-mesh.+ pub fn to_trimesh(&self) -> (Vec<Vector3>, Vec<[u32; 3]>) {+ let mut indices = Vec::new();++ for face in self.faces() {+ let i1 = face.first_vertex_or_edge;+ let i2 = i1 + face.num_vertices_or_edges;+ let first_id = self.vertices_adj_to_face()[i1 as usize];++ for idx in self.vertices_adj_to_face()[i1 as usize + 1..i2 as usize].windows(2) {+ indices.push([first_id, idx[0], idx[1]]);+ }+ }++ (self.points().to_vec(), indices)+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_trimesh/cuboid_to_trimesh.rs b/renderer/third_party/parry3d/src/transformation/to_trimesh/cuboid_to_trimesh.rsnew file mode 100644index 0000000..65793e9--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_trimesh/cuboid_to_trimesh.rs@@ -0,0 +1,79 @@+use crate::bounding_volume::Aabb;+use crate::math::Vector;+use crate::shape::Cuboid;+use crate::transformation::utils;+use alloc::vec::Vec;++impl Aabb {+ /// Discretize the boundary of this Aabb as a triangle-mesh.+ pub fn to_trimesh(&self) -> (Vec<Vector>, Vec<[u32; 3]>) {+ let center = self.center();+ let half_extents = self.half_extents();+ let mut cube_mesh = Cuboid::new(half_extents).to_trimesh();+ cube_mesh.0.iter_mut().for_each(|p| *p += center);+ cube_mesh+ }+}++impl Cuboid {+ /// Discretize the boundary of this cuboid as a triangle-mesh.+ pub fn to_trimesh(&self) -> (Vec<Vector>, Vec<[u32; 3]>) {+ let (vtx, idx) = unit_cuboid();+ (utils::scaled(vtx, self.half_extents * 2.0), idx)+ }+}++/// Generates a cuboid shape with a split index buffer.+///+/// The cuboid is centered at the origin, and has its half extents set to 0.5.+fn unit_cuboid() -> (Vec<Vector>, Vec<[u32; 3]>) {+ #[cfg(feature = "dim3")]+ {+ let mut coords = Vec::with_capacity(8);+ let mut faces = Vec::with_capacity(12);++ coords.push(Vector::new(-0.5, -0.5, 0.5));+ coords.push(Vector::new(-0.5, -0.5, -0.5));+ coords.push(Vector::new(0.5, -0.5, -0.5));+ coords.push(Vector::new(0.5, -0.5, 0.5));+ coords.push(Vector::new(-0.5, 0.5, 0.5));+ coords.push(Vector::new(-0.5, 0.5, -0.5));+ coords.push(Vector::new(0.5, 0.5, -0.5));+ coords.push(Vector::new(0.5, 0.5, 0.5));++ faces.push([4, 5, 0]);+ faces.push([5, 1, 0]);++ faces.push([5, 6, 1]);+ faces.push([6, 2, 1]);++ faces.push([6, 7, 3]);+ faces.push([2, 6, 3]);++ faces.push([7, 4, 0]);+ faces.push([3, 7, 0]);++ faces.push([0, 1, 2]);+ faces.push([3, 0, 2]);++ faces.push([7, 6, 5]);+ faces.push([4, 7, 5]);++ (coords, faces)+ }+ #[cfg(feature = "dim2")]+ {+ let mut coords = Vec::with_capacity(8);+ let mut faces = Vec::with_capacity(12);++ coords.push(Vector::new(-0.5, -0.5));+ coords.push(Vector::new(0.5, -0.5));+ coords.push(Vector::new(-0.5, 0.5));+ coords.push(Vector::new(0.5, 0.5));++ faces.push([0, 1, 2]);+ faces.push([2, 1, 3]);++ (coords, faces)+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_trimesh/cylinder_to_trimesh.rs b/renderer/third_party/parry3d/src/transformation/to_trimesh/cylinder_to_trimesh.rsnew file mode 100644index 0000000..9786fdc--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_trimesh/cylinder_to_trimesh.rs@@ -0,0 +1,38 @@+use crate::math::{Real, RealField, Vector};+use crate::shape::Cylinder;+use crate::transformation::utils;+use alloc::vec::Vec;++impl Cylinder {+ /// Discretize the boundary of this cylinder as a triangle-mesh.+ pub fn to_trimesh(&self, nsubdiv: u32) -> (Vec<Vector>, Vec<[u32; 3]>) {+ let diameter = self.radius * 2.0;+ let height = self.half_height * 2.0;+ let scale = Vector::new(diameter, height, diameter);+ let (vtx, idx) = unit_cylinder(nsubdiv);+ (utils::scaled(vtx, scale), idx)+ }+}++/// Generates a cylinder with unit height and diameter.+fn unit_cylinder(nsubdiv: u32) -> (Vec<Vector>, Vec<[u32; 3]>) {+ let two_pi = Real::two_pi();+ let invsubdiv = 1.0 / (nsubdiv as Real);+ let dtheta = two_pi * invsubdiv;+ let mut coords = Vec::new();+ let mut indices = Vec::new();++ utils::push_circle(0.5, nsubdiv, dtheta, -0.5, &mut coords);++ utils::push_circle(0.5, nsubdiv, dtheta, 0.5, &mut coords);++ utils::push_ring_indices(0, nsubdiv, nsubdiv, &mut indices);+ utils::push_filled_circle_indices(0, nsubdiv, &mut indices);+ utils::push_filled_circle_indices(nsubdiv, nsubdiv, &mut indices);++ let len = indices.len();+ let bottom_start_id = len - (nsubdiv as usize - 2);+ utils::reverse_clockwising(&mut indices[bottom_start_id..]);++ (coords, indices)+}diff --git a/renderer/third_party/parry3d/src/transformation/to_trimesh/heightfield_to_trimesh.rs b/renderer/third_party/parry3d/src/transformation/to_trimesh/heightfield_to_trimesh.rsnew file mode 100644index 0000000..3178861--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_trimesh/heightfield_to_trimesh.rs@@ -0,0 +1,22 @@+use crate::math::Vector3;+use crate::shape::HeightField;+use alloc::vec::Vec;++impl HeightField {+ /// Discretize the boundary of this heightfield as a triangle-mesh.+ pub fn to_trimesh(&self) -> (Vec<Vector3>, Vec<[u32; 3]>) {+ let mut vertices = Vec::new();+ let mut indices = Vec::new();++ for (i, tri) in self.triangles().enumerate() {+ vertices.push(tri.a);+ vertices.push(tri.b);+ vertices.push(tri.c);++ let i = i as u32;+ indices.push([i * 3, i * 3 + 1, i * 3 + 2])+ }++ (vertices, indices)+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/to_trimesh/mod.rs b/renderer/third_party/parry3d/src/transformation/to_trimesh/mod.rsnew file mode 100644index 0000000..4dc5e80--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_trimesh/mod.rs@@ -0,0 +1,153 @@+//! Triangle mesh generation from geometric shapes.+//!+//! This module provides functionality to convert various geometric shapes into triangle meshes+//! (also called "trimesh" in Parry's nomenclature). A triangle mesh is represented as a pair+//! of vectors: `(Vec<Vector>, Vec<[u32; 3]>)` containing vertices and triangle indices.+//!+//! # Overview+//!+//! Each shape in Parry implements a `to_trimesh()` method that discretizes its boundary into+//! a triangle mesh. This is useful for:+//! - **Visualization**: Rendering shapes in graphics applications+//! - **Export**: Converting shapes to standard mesh formats (OBJ, STL, etc.)+//! - **Physics simulation**: Converting analytical shapes to mesh-based collision detection+//! - **Mesh processing**: Using shape primitives as building blocks for complex geometry+//!+//! # Supported Shapes+//!+//! ## 2D and 3D Shapes+//! - **Cuboid**: Axis-aligned box with rectangular faces+//! - **Aabb**: Axis-aligned bounding box (uses `Cuboid` internally)+//!+//! ## 3D-Only Shapes+//! - **Ball**: Sphere discretized into triangular patches+//! - **Capsule**: Cylinder with hemispherical caps+//! - **Cylinder**: Circular cylinder with flat caps+//! - **Cone**: Circular cone with flat base+//! - **ConvexPolyhedron**: Already a mesh, returns its triangles+//! - **HeightField**: Terrain height map converted to mesh+//! - **Voxels**: Voxel grid converted to boundary mesh+//!+//! # Mesh Quality Control+//!+//! Most curved shapes (Ball, Capsule, Cylinder, Cone) accept subdivision parameters that+//! control the mesh resolution. Higher subdivision values produce smoother but heavier meshes:+//! - **Low subdivision** (4-8): Fast, angular approximation+//! - **Medium subdivision** (16-32): Good balance for most uses+//! - **High subdivision** (64+): Smooth curves, high polygon count+//!+//! # Examples+//!+//! ## Basic Mesh Generation+//!+//! ```+//! # #[cfg(all(feature = "dim3", feature = "f32"))]+//! # {+//! use parry3d::shape::{Ball, Cuboid};+//! use parry3d::math::Vector;+//!+//! // Convert a cuboid to a triangle mesh+//! let cuboid = Cuboid::new(Vector::new(1.0, 2.0, 3.0));+//! let (vertices, indices) = cuboid.to_trimesh();+//!+//! // A cuboid has 8 vertices and 12 triangles (2 per face × 6 faces)+//! assert_eq!(vertices.len(), 8);+//! assert_eq!(indices.len(), 12);+//!+//! // Convert a sphere with medium resolution+//! let ball = Ball::new(5.0);+//! let (vertices, indices) = ball.to_trimesh(16, 32);+//! // 16 theta subdivisions × 32 phi subdivisions+//! println!("Ball mesh: {} vertices, {} triangles",+//! vertices.len(), indices.len());+//! # }+//! ```+//!+//! ## Controlling Subdivision Quality+//!+//! ```+//! # #[cfg(all(feature = "dim3", feature = "f32"))]+//! # {+//! use parry3d::shape::Cylinder;+//!+//! let cylinder = Cylinder::new(2.0, 1.0); // half-height=2.0, radius=1.0+//!+//! // Low quality - faster, fewer triangles+//! let (vertices_low, indices_low) = cylinder.to_trimesh(8);+//! println!("Low quality: {} triangles", indices_low.len());+//!+//! // High quality - slower, more triangles, smoother appearance+//! let (vertices_high, indices_high) = cylinder.to_trimesh(64);+//! println!("High quality: {} triangles", indices_high.len());+//! # }+//! ```+//!+//! ## Converting Height Fields+//!+//! ```+//! # #[cfg(all(feature = "dim3", feature = "f32"))]+//! # {+//! use parry3d::shape::HeightField;+//! use parry3d::math::Vector;+//! use parry3d::utils::Array2;+//!+//! // Create a simple 3×3 height field+//! // Column-major order: column 0 first, then column 1, then column 2+//! let heights = Array2::new(3, 3, vec![+//! 0.0, 1.0, 0.0, // column 0+//! 1.0, 2.0, 1.0, // column 1+//! 0.0, 1.0, 0.0, // column 2+//! ]);+//!+//! let heightfield = HeightField::new(heights, Vector::new(10.0, 10.0, 1.0));+//! let (vertices, indices) = heightfield.to_trimesh();+//!+//! // Height fields generate 2 triangles per grid cell+//! // (3-1) × (3-1) cells × 2 triangles = 8 triangles+//! assert_eq!(indices.len(), 8);+//! # }+//! ```+//!+//! # Return Format+//!+//! All `to_trimesh()` methods return a tuple `(Vec<Vector>, Vec<[u32; 3]>)`:+//!+//! - **Vertices** (`Vec<Vector>`): Array of 3D points (or 2D for `dim2` feature)+//! - **Indices** (`Vec<[u32; 3]>`): Array of triangle indices, where each `[u32; 3]` contains+//! three indices into the vertices array+//!+//! The triangles follow a **counter-clockwise winding order** when viewed from outside the shape,+//! which is the standard convention for outward-facing normals.+//!+//! # Performance Considerations+//!+//! - Triangle mesh generation allocates new memory each time+//! - For dynamic scenes, consider caching generated meshes+//! - Subdivision parameters have quadratic or cubic impact on triangle count+//! - Simple shapes (Cuboid, ConvexPolyhedron) have negligible generation cost+//! - Complex shapes (Ball, Capsule with high subdivision) can be expensive+//!+//! # See Also+//!+//! - \`to_polyline\` - 2D shape to polyline conversion (internal, not public API)+#![cfg_attr(+ feature = "dim3",+ doc = "//! - `to_outline` - 3D shape outline generation (edge wireframes)"+)]+//! - [`TriMesh`](crate::shape::TriMesh) - Triangle mesh shape type++#[cfg(feature = "dim3")]+mod ball_to_trimesh;+#[cfg(feature = "dim3")]+mod capsule_to_trimesh;+#[cfg(feature = "dim3")]+mod cone_to_trimesh;+#[cfg(feature = "dim3")]+mod convex_polyhedron_to_trimesh;+mod cuboid_to_trimesh;+#[cfg(feature = "dim3")]+mod cylinder_to_trimesh;+#[cfg(feature = "dim3")]+mod heightfield_to_trimesh;+#[cfg(feature = "dim3")]+mod voxels_to_trimesh;diff --git a/renderer/third_party/parry3d/src/transformation/to_trimesh/voxels_to_trimesh.rs b/renderer/third_party/parry3d/src/transformation/to_trimesh/voxels_to_trimesh.rsnew file mode 100644index 0000000..676cc68--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/to_trimesh/voxels_to_trimesh.rs@@ -0,0 +1,41 @@+use crate::bounding_volume::Aabb;+use crate::math::Vector;+use crate::shape::Voxels;+use alloc::{vec, vec::Vec};++impl Voxels {+ /// Computes an unoptimized mesh representation of this shape.+ ///+ /// Each free face of each voxel will result in two triangles. No effort is made to merge+ /// adjacent triangles on large flat areas.+ pub fn to_trimesh(&self) -> (Vec<Vector>, Vec<[u32; 3]>) {+ let aabb = Aabb::from_half_extents(Vector::ZERO, self.voxel_size() / 2.0);+ let aabb_vtx = aabb.vertices();++ let mut vtx = vec![];+ let mut idx = vec![];+ for vox in self.voxels() {+ let mask = vox.state.free_faces();+ for i in 0..6 {+ if mask.bits() & (1 << i) != 0 {+ let fvid = Aabb::FACES_VERTEX_IDS[i];+ let base_id = vtx.len() as u32;+ vtx.push(vox.center + aabb_vtx[fvid.0]);+ vtx.push(vox.center + aabb_vtx[fvid.1]);+ vtx.push(vox.center + aabb_vtx[fvid.2]);+ vtx.push(vox.center + aabb_vtx[fvid.3]);++ if i % 2 == 0 {+ idx.push([base_id, base_id + 1, base_id + 2]);+ idx.push([base_id, base_id + 2, base_id + 3]);+ } else {+ idx.push([base_id, base_id + 2, base_id + 1]);+ idx.push([base_id, base_id + 3, base_id + 2]);+ }+ }+ }+ }++ (vtx, idx)+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/utils.rs b/renderer/third_party/parry3d/src/transformation/utils.rsnew file mode 100644index 0000000..d84fbbc--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/utils.rs@@ -0,0 +1,832 @@+//! Low-level utilities for mesh and geometry generation.+//!+//! This module provides primitive building blocks for constructing triangle meshes and other+//! geometric structures. These functions are primarily used internally by Parry's shape-to-mesh+//! conversion utilities, but are exposed for users who need fine-grained control over mesh+//! generation.+//!+//! # Overview+//!+//! The utilities fall into several categories:+//!+//! ## Vector Transformations+//! - [`transform`] / [`transformed`] - Apply rigid transformations (rotation + translation)+//! - [`scaled`] - Apply non-uniform scaling+//!+//! ## Vertex Generation+//! - `push_circle` - Generate circle points in 3D (XZ plane)+#![cfg_attr(+ feature = "dim2",+ doc = "- [`push_xy_arc`] - Generate arc points in 2D (XY plane)"+)]+//! - [`push_arc`] - Generate arc points between two endpoints+//!+//! ## Index Buffer Generation+//! - `push_ring_indices` / `push_open_ring_indices` - Connect two circles into a tube+//! - `push_rectangle_indices` - Generate two triangles forming a quad+//! - `push_degenerate_top_ring_indices` - Connect circle to a single apex point+//! - `push_filled_circle_indices` - Fill a circle with triangles (fan triangulation)+//!+//! ## Edge/Outline Generation+//! - `push_circle_outline_indices` - Edge loop for a closed circle+//! - `push_open_circle_outline_indices` - Edge chain (not closed)+//! - `push_arc_idx` - Edge indices for an arc+//!+//! ## Advanced Operations+//! - `reverse_clockwising` - Flip triangle winding order (reverse normals)+//! - `apply_revolution` - Create surface of revolution from a profile curve+//! - `push_arc_and_idx` - Generate arc geometry and indices together+//!+//! # Usage Patterns+//!+//! ## Building a Cylinder+//!+//! ```+//! # #[cfg(all(feature = "dim3", feature = "f32"))]+//! # {+//! use parry3d::transformation::utils::{push_circle, push_ring_indices, push_filled_circle_indices};+//! use parry3d::math::Vector;+//! use std::f32::consts::PI;+//!+//! let mut vertices = Vec::new();+//! let mut indices = Vec::new();+//!+//! let radius = 2.0;+//! let height = 10.0;+//! let nsubdiv = 16;+//! let dtheta = 2.0 * PI / nsubdiv as f32;+//!+//! // Create bottom and top circles+//! push_circle(radius, nsubdiv, dtheta, 0.0, &mut vertices); // Bottom at y=0+//! push_circle(radius, nsubdiv, dtheta, height, &mut vertices); // Top at y=height+//!+//! // Connect the circles to form the cylinder body+//! push_ring_indices(0, nsubdiv, nsubdiv, &mut indices);+//!+//! // Cap the bottom+//! push_filled_circle_indices(0, nsubdiv, &mut indices);+//!+//! // Cap the top+//! push_filled_circle_indices(nsubdiv, nsubdiv, &mut indices);+//!+//! println!("Cylinder: {} vertices, {} triangles", vertices.len(), indices.len());+//! # }+//! ```+//!+//! ## Building a Cone+//!+//! ```+//! # #[cfg(all(feature = "dim3", feature = "f32"))]+//! # {+//! use parry3d::transformation::utils::{push_circle, push_degenerate_top_ring_indices, push_filled_circle_indices};+//! use parry3d::math::Vector;+//! use std::f32::consts::PI;+//!+//! let mut vertices = Vec::new();+//! let mut indices = Vec::new();+//!+//! let radius = 3.0;+//! let height = 5.0;+//! let nsubdiv = 20;+//! let dtheta = 2.0 * PI / nsubdiv as f32;+//!+//! // Create the base circle+//! push_circle(radius, nsubdiv, dtheta, 0.0, &mut vertices);+//!+//! // Add apex point at the top+//! vertices.push(Vector::new(0.0, height, 0.0));+//! let apex_idx = (vertices.len() - 1) as u32;+//!+//! // Connect base circle to apex+//! push_degenerate_top_ring_indices(0, apex_idx, nsubdiv, &mut indices);+//!+//! // Cap the base+//! push_filled_circle_indices(0, nsubdiv, &mut indices);+//!+//! println!("Cone: {} vertices, {} triangles", vertices.len(), indices.len());+//! # }+//! ```+//!+//! ## Transforming Existing Geometry+//!+//! ```+//! # #[cfg(all(feature = "dim3", feature = "f32"))]+//! # {+//! use parry3d::transformation::utils::{transform, scaled};+//! use parry3d::math::{Vector, Pose, Rotation};+//! use core::f32::consts::PI;+//!+//! let mut points = vec![+//! Vector::new(1.0, 0.0, 0.0),+//! Vector::new(0.0, 1.0, 0.0),+//! Vector::new(0.0, 0.0, 1.0),+//! ];+//!+//! // First, scale non-uniformly+//! let points = scaled(points, Vector::new(2.0, 1.0, 0.5));+//!+//! // Then rotate 45 degrees around Y axis+//! let rotation = Rotation::from_axis_angle(Vector::Y, PI / 4.0);+//! let translation = Vector::new(10.0, 5.0, 0.0);+//! let isometry = Pose::from_parts(translation, rotation);+//!+//! let final_points = parry3d::transformation::utils::transformed(points, isometry);+//! # }+//! ```+//!+//! # Design Philosophy+//!+//! These functions follow a "builder" pattern where:+//! 1. Vertices are pushed to a `Vec<Vector>`+//! 2. Indices are pushed to a `Vec<[u32; 3]>` (triangles) or `Vec<[u32; 2]>` (edges)+//! 3. Functions work with index offsets, allowing incremental construction+//! 4. No memory is allocated except for the output buffers+//!+//! This design allows for efficient, flexible mesh construction with minimal overhead.+//!+//! # Performance Notes+//!+//! - All functions use simple loops without SIMD (suitable for small to medium subdivisions)+//! - Index generation has O(n) complexity where n is the subdivision count+//! - Vector generation involves trigonometric functions (sin/cos) per subdivision+//! - For high subdivision counts (>1000), consider caching generated geometry+//!+//! # See Also+//!+//! - `to_trimesh` module - High-level shape to mesh conversion (see individual shape `to_trimesh()` methods)+//! - [`convex_hull`](crate::transformation::convex_hull) - Convex hull computation+//! - [`TriMesh`](crate::shape::TriMesh) - Triangle mesh shape++#[cfg(feature = "dim3")]+use crate::math::RealField;+#[cfg(feature = "dim2")]+use crate::math::VectorExt;+use crate::math::{ComplexField, Pose, Real, Vector};+use alloc::vec::Vec;+#[cfg(feature = "dim3")]+use {crate::math::DIM, num::Zero};++/// Applies in-place a transformation to an array of points.+///+/// This function modifies each point in the slice by applying the given isometry+/// (rigid transformation consisting of rotation and translation).+///+/// # Arguments+/// * `points` - A mutable slice of points to transform+/// * `m` - The isometry (rigid transformation) to apply+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::utils::transform;+/// use parry3d::math::{Vector, Pose, Rotation};+///+/// // Create some points+/// let mut points = vec![+/// Vector::new(1.0, 0.0, 0.0),+/// Vector::new(0.0, 1.0, 0.0),+/// Vector::new(0.0, 0.0, 1.0),+/// ];+///+/// // Create a translation+/// let transform_iso = Pose::from_parts(+/// Vector::new(10.0, 20.0, 30.0),+/// Rotation::IDENTITY+/// );+///+/// // Apply the transformation in-place+/// transform(&mut points, transform_iso);+///+/// assert_eq!(points[0], Vector::new(11.0, 20.0, 30.0));+/// assert_eq!(points[1], Vector::new(10.0, 21.0, 30.0));+/// assert_eq!(points[2], Vector::new(10.0, 20.0, 31.0));+/// # }+/// ```+pub fn transform(points: &mut [Vector], m: Pose) {+ points.iter_mut().for_each(|p| *p = m * *p);+}++/// Returns the transformed version of a vector of points.+///+/// This function takes ownership of a vector of points, applies the given isometry+/// transformation, and returns the transformed vector.+///+/// # Arguments+/// * `points` - A vector of points to transform (ownership is taken)+/// * `m` - The isometry (rigid transformation) to apply+///+/// # Returns+/// A new vector containing the transformed points+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::transformation::utils::transformed;+/// use parry2d::math::{Vector, Pose, Rotation};+/// use std::f32::consts::PI;+///+/// let points = vec![+/// Vector::new(1.0, 0.0),+/// Vector::new(0.0, 1.0),+/// ];+///+/// // Rotate 90 degrees counter-clockwise around origin+/// let rotation = Rotation::new(PI / 2.0);+/// let transform = Pose::from_parts(Vector::ZERO, rotation);+///+/// let result = transformed(points, transform);+///+/// // Vectors are now rotated+/// assert!((result[0].x - 0.0).abs() < 1e-6);+/// assert!((result[0].y - 1.0).abs() < 1e-6);+/// # }+/// ```+pub fn transformed(mut points: Vec<Vector>, m: Pose) -> Vec<Vector> {+ transform(&mut points, m);+ points+}++/// Returns the scaled version of a vector of points.+///+/// This function takes ownership of a vector of points and applies a non-uniform+/// scale factor to each component. Unlike [`transformed`], this is a non-rigid+/// transformation that can stretch or compress points along different axes.+///+/// # Arguments+/// * `points` - A vector of points to scale (ownership is taken)+/// * `scale` - The scale factor for each axis+///+/// # Returns+/// A new vector containing the scaled points+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::utils::scaled;+/// use parry3d::math::Vector;+///+/// let points = vec![+/// Vector::new(1.0, 2.0, 3.0),+/// Vector::new(4.0, 5.0, 6.0),+/// ];+///+/// // Scale x by 2, y by 3, z by 0.5+/// let scale = Vector::new(2.0, 3.0, 0.5);+/// let result = scaled(points, scale);+///+/// assert_eq!(result[0], Vector::new(2.0, 6.0, 1.5));+/// assert_eq!(result[1], Vector::new(8.0, 15.0, 3.0));+/// # }+/// ```+pub fn scaled(mut points: Vec<Vector>, scale: Vector) -> Vec<Vector> {+ points.iter_mut().for_each(|p| *p *= scale);+ points+}++// TODO: remove that in favor of `push_xy_circle` ?+/// Pushes a discretized counterclockwise circle to a buffer.+///+/// This function generates points along a circle in the XZ plane at a given Y coordinate.+/// Vectors are generated counter-clockwise when viewed from above (positive Y direction).+///+/// # Arguments+/// * `radius` - The radius of the circle+/// * `nsubdiv` - Number of subdivisions (points to generate)+/// * `dtheta` - Angle increment between consecutive points (in radians)+/// * `y` - The Y coordinate of the circle plane+/// * `out` - Output buffer where circle points will be pushed+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::utils::push_circle;+/// use parry3d::math::Vector;+/// use std::f32::consts::PI;+///+/// let mut points = Vec::new();+/// let radius = 5.0;+/// let nsubdiv = 8; // Octagon+/// let dtheta = 2.0 * PI / nsubdiv as f32;+/// let y_level = 10.0;+///+/// push_circle(radius, nsubdiv, dtheta, y_level, &mut points);+///+/// assert_eq!(points.len(), 8);+/// // All points are at Y = 10.0+/// assert!(points.iter().all(|p| (p.y - 10.0).abs() < 1e-6));+/// // First point is at (radius, y, 0)+/// assert!((points[0].x - radius).abs() < 1e-6);+/// assert!((points[0].z).abs() < 1e-6);+/// # }+/// ```+#[cfg(feature = "dim3")]+#[inline]+pub fn push_circle(radius: Real, nsubdiv: u32, dtheta: Real, y: Real, out: &mut Vec<Vector>) {+ let mut curr_theta = Real::zero();++ for _ in 0..nsubdiv {+ out.push(Vector::new(+ <Real as ComplexField>::cos(curr_theta) * radius,+ y,+ <Real as ComplexField>::sin(curr_theta) * radius,+ ));+ curr_theta += dtheta;+ }+}++/// Pushes a discretized counterclockwise arc to a buffer.+///+/// This function generates points along an arc in the XY plane (2D).+/// The arc is contained on the plane spanned by the X and Y axes.+/// Vectors are generated counter-clockwise starting from angle 0 (positive X axis).+///+/// # Arguments+/// * `radius` - The radius of the arc+/// * `nsubdiv` - Number of subdivisions (points to generate)+/// * `dtheta` - Angle increment between consecutive points (in radians)+/// * `out` - Output buffer where arc points will be pushed+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::transformation::utils::push_xy_arc;+/// use parry2d::math::Vector;+/// use std::f32::consts::PI;+///+/// let mut points = Vec::new();+/// let radius = 3.0;+/// let nsubdiv = 4; // Quarter circle+/// let dtheta = PI / 2.0 / (nsubdiv - 1) as f32;+///+/// push_xy_arc(radius, nsubdiv, dtheta, &mut points);+///+/// assert_eq!(points.len(), 4);+/// // First point is approximately at (radius, 0)+/// assert!((points[0].x - radius).abs() < 1e-6);+/// assert!((points[0].y).abs() < 1e-6);+/// # }+/// ```+#[inline]+#[cfg(feature = "dim2")]+pub fn push_xy_arc(radius: Real, nsubdiv: u32, dtheta: Real, out: &mut Vec<Vector>) {+ let mut curr_theta: Real = 0.0;++ for _ in 0..nsubdiv {+ let mut pt_coords = Vector::ZERO;++ pt_coords.x = <Real as ComplexField>::cos(curr_theta) * radius;+ pt_coords.y = <Real as ComplexField>::sin(curr_theta) * radius;+ out.push(pt_coords);++ curr_theta += dtheta;+ }+}++/// Creates the triangle faces connecting two circles with the same discretization.+///+/// This function generates triangle indices to form a closed ring (tube segment) between+/// two parallel circles. The circles must have the same number of points. The ring wraps+/// around completely, connecting the last points back to the first.+///+/// # Arguments+/// * `base_lower_circle` - Index of the first point of the lower circle+/// * `base_upper_circle` - Index of the first point of the upper circle+/// * `nsubdiv` - Number of points in each circle+/// * `out` - Output buffer where triangle indices will be pushed+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::utils::{push_circle, push_ring_indices};+/// use parry3d::math::Vector;+/// use std::f32::consts::PI;+///+/// let mut vertices = Vec::new();+/// let mut indices = Vec::new();+///+/// let nsubdiv = 8;+/// let dtheta = 2.0 * PI / nsubdiv as f32;+///+/// // Create two circles at different heights+/// push_circle(2.0, nsubdiv, dtheta, 0.0, &mut vertices); // Lower circle+/// push_circle(2.0, nsubdiv, dtheta, 5.0, &mut vertices); // Upper circle+///+/// // Connect them with triangles+/// push_ring_indices(0, nsubdiv, nsubdiv, &mut indices);+///+/// // A ring with n subdivisions creates 2*n triangles+/// assert_eq!(indices.len(), 2 * nsubdiv as usize);+/// # }+/// ```+#[cfg(feature = "dim3")]+#[inline]+pub fn push_ring_indices(+ base_lower_circle: u32,+ base_upper_circle: u32,+ nsubdiv: u32,+ out: &mut Vec<[u32; DIM]>,+) {+ push_open_ring_indices(base_lower_circle, base_upper_circle, nsubdiv, out);++ // adjust the last two triangles+ push_rectangle_indices(+ base_upper_circle,+ base_upper_circle + nsubdiv - 1,+ base_lower_circle,+ base_lower_circle + nsubdiv - 1,+ out,+ );+}++/// Creates the triangle faces connecting two circles, leaving the ring open.+///+/// This is similar to `push_ring_indices`, but doesn't close the ring. The connection+/// between the last point and the first point is not made, leaving a gap. This is useful+/// for creating open cylinders or partial tubes.+///+/// # Arguments+/// * `base_lower_circle` - Index of the first point of the lower circle+/// * `base_upper_circle` - Index of the first point of the upper circle+/// * `nsubdiv` - Number of points in each circle+/// * `out` - Output buffer where triangle indices will be pushed+///+/// # Panics+/// Panics if `nsubdiv` is 0.+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::utils::{push_circle, push_open_ring_indices};+/// use parry3d::math::Vector;+/// use std::f32::consts::PI;+///+/// let mut vertices = Vec::new();+/// let mut indices = Vec::new();+///+/// let nsubdiv = 8;+/// let dtheta = 2.0 * PI / nsubdiv as f32;+///+/// // Create two circles+/// push_circle(2.0, nsubdiv, dtheta, 0.0, &mut vertices);+/// push_circle(2.0, nsubdiv, dtheta, 5.0, &mut vertices);+///+/// // Connect them without closing the ring+/// push_open_ring_indices(0, nsubdiv, nsubdiv, &mut indices);+///+/// // Open ring has 2 fewer triangles than closed ring+/// assert_eq!(indices.len(), 2 * (nsubdiv - 1) as usize);+/// # }+/// ```+#[cfg(feature = "dim3")]+#[inline]+pub fn push_open_ring_indices(+ base_lower_circle: u32,+ base_upper_circle: u32,+ nsubdiv: u32,+ out: &mut Vec<[u32; DIM]>,+) {+ assert!(nsubdiv > 0);++ for i in 0..nsubdiv - 1 {+ let bli = base_lower_circle + i;+ let bui = base_upper_circle + i;+ push_rectangle_indices(bui + 1, bui, bli + 1, bli, out);+ }+}++/// Creates the faces from a circle and a point that is shared by all triangle.+#[cfg(feature = "dim3")]+#[inline]+pub fn push_degenerate_top_ring_indices(+ base_circle: u32,+ point: u32,+ nsubdiv: u32,+ out: &mut Vec<[u32; DIM]>,+) {+ push_degenerate_open_top_ring_indices(base_circle, point, nsubdiv, out);++ out.push([base_circle + nsubdiv - 1, point, base_circle]);+}++/// Creates the faces from a circle and a point that is shared by all triangle.+#[cfg(feature = "dim3")]+#[inline]+pub fn push_degenerate_open_top_ring_indices(+ base_circle: u32,+ point: u32,+ nsubdiv: u32,+ out: &mut Vec<[u32; DIM]>,+) {+ assert!(nsubdiv > 0);++ for i in 0..nsubdiv - 1 {+ out.push([base_circle + i, point, base_circle + i + 1]);+ }+}++/// Pushes indices so that a circle is filled with triangles. Each triangle will have the+/// `base_circle` point in common.+/// Pushes `nsubdiv - 2` elements to `out`.+#[cfg(feature = "dim3")]+#[inline]+pub fn push_filled_circle_indices(base_circle: u32, nsubdiv: u32, out: &mut Vec<[u32; DIM]>) {+ for i in base_circle + 1..base_circle + nsubdiv - 1 {+ out.push([base_circle, i, i + 1]);+ }+}++/// Pushes two triangles forming a rectangle to the index buffer.+///+/// Given four corner point indices, this function creates two counter-clockwise triangles+/// that form a rectangle (quad). The winding order ensures the normal points in the+/// consistent direction based on the right-hand rule.+///+/// # Arguments+/// * `ul` - Index of the upper-left point+/// * `ur` - Index of the upper-right point+/// * `dl` - Index of the down-left point+/// * `dr` - Index of the down-right point+/// * `out` - Output buffer where triangle indices will be pushed+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::utils::push_rectangle_indices;+///+/// let mut indices = Vec::new();+///+/// // Create a quad from points 0, 1, 2, 3+/// // Layout: 0 --- 1+/// // | |+/// // 2 --- 3+/// push_rectangle_indices(0, 1, 2, 3, &mut indices);+///+/// assert_eq!(indices.len(), 2); // Two triangles+/// assert_eq!(indices[0], [0, 2, 3]); // First triangle+/// assert_eq!(indices[1], [3, 1, 0]); // Second triangle+/// # }+/// ```+#[cfg(feature = "dim3")]+#[inline]+pub fn push_rectangle_indices(ul: u32, ur: u32, dl: u32, dr: u32, out: &mut Vec<[u32; DIM]>) {+ out.push([ul, dl, dr]);+ out.push([dr, ur, ul]);+}++/// Reverses the winding order of triangle faces.+///+/// This function flips the winding order of triangles from counter-clockwise to clockwise+/// or vice versa. This effectively flips the direction of face normals, which is useful+/// when you need to invert a mesh or correct winding order issues.+///+/// # Arguments+/// * `indices` - Mutable slice of triangle indices to reverse+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::utils::reverse_clockwising;+///+/// let mut triangles = vec![+/// [0, 1, 2],+/// [2, 3, 0],+/// ];+///+/// // Reverse the winding order+/// reverse_clockwising(&mut triangles);+///+/// // First two vertices of each triangle are swapped+/// assert_eq!(triangles[0], [1, 0, 2]);+/// assert_eq!(triangles[1], [3, 2, 0]);+/// # }+/// ```+#[cfg(feature = "dim3")]+#[inline]+pub fn reverse_clockwising(indices: &mut [[u32; DIM]]) {+ indices.iter_mut().for_each(|idx| idx.swap(0, 1));+}++/// Pushes the index buffer of a closed loop.+#[cfg(feature = "dim3")]+#[inline]+pub fn push_circle_outline_indices(indices: &mut Vec<[u32; 2]>, range: core::ops::Range<u32>) {+ indices.extend((range.start..range.end - 1).map(|i| [i, i + 1]));+ indices.push([range.end - 1, range.start]);+}++/// Pushes the index buffer of an open chain.+#[cfg(feature = "dim3")]+#[inline]+pub fn push_open_circle_outline_indices(indices: &mut Vec<[u32; 2]>, range: core::ops::Range<u32>) {+ indices.extend((range.start..range.end - 1).map(|i| [i, i + 1]));+}++/// Pushes to `out_vtx` a set of points forming an arc starting at `start`, ending at `end` with+/// revolution center at `center`. The curve is approximated by pushing `nsubdivs` points.+/// The `start` and `end` point are not pushed to `out_vtx`.+///+/// Also pushes to `out_idx` the appropriate index buffer to form the arc (including attaches to+/// the `start` and `end` points).+#[cfg(feature = "dim3")]+pub fn push_arc_and_idx(+ center: Vector,+ start: u32,+ end: u32,+ nsubdivs: u32,+ out_vtx: &mut Vec<Vector>,+ out_idx: &mut Vec<[u32; 2]>,+) {+ let base = out_vtx.len() as u32;+ push_arc(+ center,+ out_vtx[start as usize],+ out_vtx[end as usize],+ nsubdivs,+ out_vtx,+ );+ // Rely on the actual number of pushed vertices so the index buffer can never+ // reference vertices that were not pushed.+ let pushed = out_vtx.len() as u32 - base;+ push_arc_idx(start, base..base + pushed, end, out_idx);+}++/// Pushes points forming an arc between two points around a center.+///+/// This function generates intermediate points along a circular arc from `start` to `end`,+/// rotating around `center`. The arc is approximated by `nsubdivs` points. The `start` and+/// `end` points themselves are NOT added to the output buffer - only intermediate points.+///+/// The function interpolates both the angle and the radius, so it can handle arcs where+/// the start and end points are at different distances from the center (spiral-like paths).+/// On a degenerate arc (`start` and/or `end` coinciding with `center`), the intermediate+/// points are linearly interpolated instead, so exactly `nsubdivs - 1` points are pushed.+///+/// # Arguments+/// * `center` - The center point of rotation+/// * `start` - Starting point of the arc (not included in output)+/// * `end` - Ending point of the arc (not included in output)+/// * `nsubdivs` - Number of intermediate points to generate+/// * `out` - Output buffer where arc points will be pushed+///+/// # Panics+/// Panics if `nsubdivs` is 0.+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::transformation::utils::push_arc;+/// use parry2d::math::Vector;+///+/// let mut points = Vec::new();+/// let center = Vector::new(0.0, 0.0);+/// let start = Vector::new(5.0, 0.0); // 5 units to the right+/// let end = Vector::new(0.0, 5.0); // 5 units up (90 degree arc)+///+/// // Generate 3 intermediate points+/// push_arc(center, start, end, 3, &mut points);+///+/// // Should have 2 intermediate points (nsubdivs - 1)+/// assert_eq!(points.len(), 2);+/// # }+/// ```+pub fn push_arc(center: Vector, start: Vector, end: Vector, nsubdivs: u32, out: &mut Vec<Vector>) {+ assert!(nsubdivs > 0);+ let (start_dir, start_len) = (start - center).normalize_and_length();+ let (end_dir, end_len) = (end - center).normalize_and_length();++ if start_len > 0.0 && end_len > 0.0 {+ let len_inc = (end_len - start_len) / nsubdivs as Real;++ #[cfg(feature = "dim2")]+ let rot = {+ use crate::math::Rot2;+ let angle = start_dir.angle(end_dir);+ let angle_inc = angle / nsubdivs as Real;+ Rot2::new(angle_inc)+ };++ #[cfg(feature = "dim3")]+ let rot = {+ use crate::math::Rot3;+ // Compute rotation from start_dir to end_dir+ let rot = Rot3::from_rotation_arc(start_dir, end_dir);+ let axisangle = rot.to_scaled_axis();+ Rot3::from_scaled_axis(axisangle / nsubdivs as Real)+ };++ let mut curr_dir = start_dir;+ let mut curr_len = start_len;++ for _ in 0..nsubdivs - 1 {+ curr_dir = rot * curr_dir;+ curr_len += len_inc;++ out.push(center + curr_dir * curr_len);+ }+ } else {+ // Degenerate arc (e.g. a zero border radius): fall back to a straight line so the+ // callers' index bookkeeping still gets exactly `nsubdivs - 1` points.+ for i in 1..nsubdivs {+ let t = i as Real / nsubdivs as Real;+ out.push(start + (end - start) * t);+ }+ }+}++/// Pushes the index buffer for an arc between `start` and `end` and intermediate points in the+/// range `arc`.+#[cfg(feature = "dim3")]+pub fn push_arc_idx(start: u32, arc: core::ops::Range<u32>, end: u32, out: &mut Vec<[u32; 2]>) {+ if arc.is_empty() {+ out.push([start, end]);+ } else {+ out.push([start, arc.start]);+ for i in arc.start..arc.end - 1 {+ out.push([i, i + 1])+ }+ out.push([arc.end - 1, end])+ }+}++/// Applies a revolution, using the Y symmetry axis passing through the origin.+#[cfg(feature = "dim3")]+pub fn apply_revolution(+ collapse_bottom: bool,+ collapse_top: bool,+ circle_ranges: &[core::ops::Range<u32>],+ nsubdivs: u32,+ out_vtx: &mut Vec<Vector>, // Must be set to the half-profile.+ out_idx: &mut Vec<[u32; 2]>,+) {+ let ang_increment = Real::two_pi() / (nsubdivs as Real);+ let angles = [+ ang_increment * (nsubdivs / 4) as Real,+ ang_increment * (nsubdivs / 2) as Real,+ ang_increment * ((3 * nsubdivs) / 4) as Real,+ ];++ let half_profile_len = out_vtx.len();++ for k in 0..half_profile_len as u32 - 1 {+ out_idx.push([k, k + 1]);+ }++ let mut range = 0..half_profile_len;++ if collapse_bottom {+ range.start += 1;+ }+ if collapse_top {+ range.end -= 1;+ }++ // Push rotated profiles.+ for angle in angles {+ let base = out_vtx.len() as u32;+ let rot = crate::math::Rot3::from_axis_angle(Vector::Y, angle);++ if collapse_bottom {+ out_idx.push([0, base]);+ }++ for k in range.clone() {+ out_vtx.push(rot * out_vtx[k]);+ }++ for k in 0..range.len() as u32 - 1 {+ out_idx.push([base + k, base + k + 1]);+ }++ if collapse_top {+ out_idx.push([base + range.len() as u32 - 1, half_profile_len as u32 - 1]);+ }+ }++ // Push circles.+ // TODO: right now, this duplicates some points, to simplify the index+ // buffer construction.+ for circle_range in circle_ranges {+ for i in circle_range.clone() {+ let pt = out_vtx[i as usize];+ let base = out_vtx.len() as u32;+ push_circle(+ crate::math::Vector2::new(pt.x, pt.z).length(),+ nsubdivs,+ ang_increment,+ pt.y,+ out_vtx,+ );+ push_circle_outline_indices(out_idx, base..base + nsubdivs)+ }+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/vhacd/mod.rs b/renderer/third_party/parry3d/src/transformation/vhacd/mod.rsnew file mode 100644index 0000000..9c6eb59--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/vhacd/mod.rs@@ -0,0 +1,275 @@+//! Approximate Convex Decomposition using the V-HACD algorithm.+//!+//! # What is Convex Decomposition?+//!+//! Convex decomposition is the process of breaking down a complex, possibly concave shape into+//! multiple simpler convex shapes. A **convex** shape is one where any line segment connecting+//! two points inside the shape lies entirely within the shape (think of shapes without dents+//! or holes). For example:+//! - Convex: sphere, box, cone, tetrahedron+//! - Concave: bowl, donut, 'L' shape, 'C' shape, star+//!+//! # Why Use Convex Decomposition?+//!+//! Convex shapes are much more efficient for collision detection than concave shapes because:+//! 1. **Performance**: Collision algorithms like GJK work directly with convex shapes+//! 2. **Physics Simulation**: Physics engines (like Rapier) can only handle convex shapes+//! for dynamic objects+//! 3. **Accuracy**: Better than using a single bounding volume or triangle mesh for complex shapes+//!+//! **Example use cases:**+//! - Game character models with complex geometry (humanoids, creatures)+//! - Architectural elements (stairs, furniture, buildings)+//! - Vehicles (cars, planes, spaceships)+//! - Complex terrain features+//!+//! # When to Use Each Approach+//!+//! | Shape Type | Best Approach | Example |+//! |------------|---------------|---------|+//! | Already convex | Use [`convex_hull`](crate::transformation::convex_hull) | Box, sphere, simple pyramid |+//! | Simple concave | Use [`Compound`](crate::shape::Compound) of basic shapes | Two boxes in an 'L' shape |+//! | Complex concave | Use convex decomposition | Character mesh, furniture |+//! | Very detailed mesh | Use [`TriMesh`](crate::shape::TriMesh) for static objects | Detailed terrain, static level geometry |+//!+//! # The V-HACD Algorithm+//!+//! V-HACD (Volumetric Hierarchical Approximate Convex Decomposition) works by:+//! 1. **Voxelization**: Converting the input mesh into a 3D grid of voxels (or 2D pixels)+//! 2. **Decomposition**: Recursively splitting the voxelized shape along planes that minimize concavity+//! 3. **Convex Hull**: Computing the convex hull of each resulting part+//!+//! The algorithm balances:+//! - **Quality**: How closely the parts approximate the original shape (controlled by `concavity`)+//! - **Count**: How many convex parts to generate (controlled by `max_convex_hulls`)+//! - **Performance**: How long the decomposition takes (controlled by `resolution`)+//!+//! # Basic Usage+//!+//! ## Quick Start (Default Parameters)+//!+//! The simplest way to decompose a mesh is using default parameters:+//!+//! ```no_run+//! # #[cfg(all(feature = "dim3", feature = "f32"))] {+//! use parry3d::math::Vector;+//! use parry3d::transformation::vhacd::VHACD;+//! use parry3d::transformation::vhacd::VHACDParameters;+//!+//! // Define a simple concave mesh (an 'L' shape made of triangles)+//! let vertices = vec![+//! Vector::new(0.0, 0.0, 0.0), Vector::new(2.0, 0.0, 0.0),+//! Vector::new(2.0, 1.0, 0.0), Vector::new(1.0, 1.0, 0.0),+//! Vector::new(1.0, 2.0, 0.0), Vector::new(0.0, 2.0, 0.0),+//! // Add corresponding back face vertices+//! Vector::new(0.0, 0.0, 1.0), Vector::new(2.0, 0.0, 1.0),+//! Vector::new(2.0, 1.0, 1.0), Vector::new(1.0, 1.0, 1.0),+//! Vector::new(1.0, 2.0, 1.0), Vector::new(0.0, 2.0, 1.0),+//! ];+//! let indices = vec![+//! // Front face triangles+//! [0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5],+//! // Back face triangles+//! [6, 8, 7], [6, 9, 8], [6, 10, 9], [6, 11, 10],+//! // Connect front and back+//! [0, 6, 7], [0, 7, 1], [1, 7, 8], [1, 8, 2],+//! [2, 8, 9], [2, 9, 3], [3, 9, 10], [3, 10, 4],+//! [4, 10, 11], [4, 11, 5], [5, 11, 6], [5, 6, 0],+//! ];+//!+//! // Decompose with default parameters+//! let decomposition = VHACD::decompose(+//! &VHACDParameters::default(),+//! &vertices,+//! &indices,+//! false, // don't keep voxel-to-primitive mapping+//! );+//!+//! // Get the voxelized convex parts+//! let parts = decomposition.voxel_parts();+//! println!("Generated {} convex parts", parts.len());+//!+//! // Compute the convex hulls (for collision detection)+//! let convex_hulls = decomposition.compute_convex_hulls(4);+//! for (i, (vertices, indices)) in convex_hulls.iter().enumerate() {+//! println!("Part {}: {} vertices, {} triangles", i, vertices.len(), indices.len());+//! }+//! # }+//! ```+//!+//! ## Customizing Parameters+//!+//! For more control over the decomposition quality and performance:+//!+//! ```no_run+//! # #[cfg(all(feature = "dim3", feature = "f32"))] {+//! use parry3d::math::Vector;+//! use parry3d::transformation::vhacd::{VHACD, VHACDParameters};+//! use parry3d::transformation::voxelization::FillMode;+//!+//! # let vertices = vec![+//! # Vector::new(0.0, 0.0, 0.0), Vector::new(1.0, 0.0, 0.0),+//! # Vector::new(0.5, 1.0, 0.0), Vector::new(0.5, 0.0, 1.0),+//! # ];+//! # let indices = vec![[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]];+//! #+//! // Configure parameters for higher quality decomposition+//! let params = VHACDParameters {+//! resolution: 128, // Higher = more detail (but slower)+//! concavity: 0.001, // Lower = more parts but better fit+//! max_convex_hulls: 32, // Maximum number of convex parts+//! plane_downsampling: 4, // Precision of plane search+//! convex_hull_downsampling: 4, // Precision of convex hull generation+//! alpha: 0.05, // Bias toward symmetrical splits+//! beta: 0.05, // Bias toward revolution axis splits+//! convex_hull_approximation: true, // Approximate for speed+//! fill_mode: FillMode::FloodFill {+//! detect_cavities: false,+//! },+//! };+//!+//! let decomposition = VHACD::decompose(¶ms, &vertices, &indices, false);+//! # }+//! ```+//!+//! ## Working with Original Mesh Geometry+//!+//! By default, the convex hulls are computed from the voxelized representation. To get more+//! accurate hulls based on the original mesh:+//!+//! ```no_run+//! # #[cfg(all(feature = "dim3", feature = "f32"))] {+//! use parry3d::math::Vector;+//! use parry3d::transformation::vhacd::{VHACD, VHACDParameters};+//!+//! # let vertices = vec![+//! # Vector::new(0.0, 0.0, 0.0), Vector::new(1.0, 0.0, 0.0),+//! # Vector::new(0.5, 1.0, 0.0), Vector::new(0.5, 0.0, 1.0),+//! # ];+//! # let indices = vec![[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]];+//! #+//! // Enable voxel-to-primitive mapping+//! let decomposition = VHACD::decompose(+//! &VHACDParameters::default(),+//! &vertices,+//! &indices,+//! true, // <-- Keep mapping to original mesh primitives+//! );+//!+//! // Compute exact convex hulls using original mesh geometry+//! let exact_hulls = decomposition.compute_exact_convex_hulls(&vertices, &indices);+//! println!("Generated {} exact convex hulls", exact_hulls.len());+//! # }+//! ```+//!+//! ## 2D Convex Decomposition+//!+//! The same API works in 2D for decomposing polylines:+//!+//! ```no_run+//! # #[cfg(all(feature = "dim2", feature = "f32"))] {+//! use parry2d::math::Vector;+//! use parry2d::transformation::vhacd::{VHACD, VHACDParameters};+//!+//! // Define a concave polyline (e.g., an 'L' shape)+//! let vertices = vec![+//! Vector::new(0.0, 0.0), Vector::new(2.0, 0.0),+//! Vector::new(2.0, 1.0), Vector::new(1.0, 1.0),+//! Vector::new(1.0, 2.0), Vector::new(0.0, 2.0),+//! ];+//! let indices = vec![+//! [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0],+//! ];+//!+//! let decomposition = VHACD::decompose(+//! &VHACDParameters::default(),+//! &vertices,+//! &indices,+//! false,+//! );+//!+//! // Get convex polygons+//! let convex_polygons = decomposition.compute_convex_hulls(4);+//! for (i, polygon) in convex_polygons.iter().enumerate() {+//! println!("Polygon {}: {} vertices", i, polygon.len());+//! }+//! # }+//! ```+//!+//! # Integration with Physics Engines+//!+//! The decomposed convex parts can be used directly with physics engines:+//!+//! ```no_run+//! # #[cfg(all(feature = "dim3", feature = "f32"))] {+//! use parry3d::math::Vector;+//! use parry3d::shape::{SharedShape, Compound};+//! use parry3d::transformation::vhacd::VHACDParameters;+//! use parry3d::math::Pose;+//!+//! # let vertices = vec![+//! # Vector::new(0.0, 0.0, 0.0), Vector::new(1.0, 0.0, 0.0),+//! # Vector::new(0.5, 1.0, 0.0), Vector::new(0.5, 0.0, 1.0),+//! # ];+//! # let indices = vec![[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]];+//! #+//! // Use the high-level API for direct integration+//! let compound_shape = SharedShape::convex_decomposition(&vertices, &indices);+//!+//! // Or with custom parameters+//! let params = VHACDParameters {+//! concavity: 0.001,+//! max_convex_hulls: 32,+//! ..Default::default()+//! };+//! let compound_shape = SharedShape::convex_decomposition_with_params(+//! &vertices,+//! &indices,+//! ¶ms,+//! );+//!+//! // The resulting compound can be used as a collider shape+//! println!("Created compound shape with convex parts");+//! # }+//! ```+//!+//! # Performance Tips+//!+//! 1. **Resolution**: Start with lower values (32-64) for fast iteration, increase for final quality+//! 2. **Concavity**: Higher values (0.01-0.1) = fewer parts = faster but less accurate+//! 3. **Max Convex Hulls**: Limit to reasonable values (8-32) for game objects+//! 4. **Approximation**: Keep `convex_hull_approximation: true` for better performance+//! 5. **Preprocessing**: Simplify your mesh before decomposition if it has excessive detail+//!+//! # Debugging Tips+//!+//! If the decomposition doesn't look right:+//! - Visualize the voxelized parts using `voxel_parts()` to understand the algorithm's view+//! - Try adjusting `resolution` if details are lost or voxelization is too coarse+//! - Increase `max_convex_hulls` if the shape is still too concave+//! - Decrease `concavity` for tighter fitting convex parts+//! - Check that your mesh is manifold and has consistent winding order+//!+//! # Algorithm Details+//!+//! The V-HACD algorithm was developed by Khaled Mamou and is described in:+//! > "Volumetric Hierarchical Approximate Convex Decomposition"+//! > Khaled Mamou and Faouzi Ghorbel+//!+//! Implementation based on: <https://github.com/kmammou/v-hacd>+//!+//! # See Also+//!+//! - [`VHACDParameters`](crate::transformation::vhacd::VHACDParameters): Configuration parameters for the algorithm+//! - [`VHACD`](crate::transformation::vhacd::VHACD): The main decomposition structure+//! - [`SharedShape::convex_decomposition`](crate::shape::SharedShape::convex_decomposition): High-level API+//! - [`convex_hull`](crate::transformation::convex_hull): For computing convex hulls directly+//! - [`Compound`](crate::shape::Compound): For manually combining convex shapes++pub use self::parameters::VHACDParameters;+pub use self::vhacd::VHACD;++pub(crate) use self::vhacd::CutPlane;++mod parameters;+mod vhacd;diff --git a/renderer/third_party/parry3d/src/transformation/vhacd/parameters.rs b/renderer/third_party/parry3d/src/transformation/vhacd/parameters.rsnew file mode 100644index 0000000..b829059--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/vhacd/parameters.rs@@ -0,0 +1,491 @@+use crate::math::Real;+use crate::transformation::voxelization::FillMode;++/// Parameters controlling the VHACD convex decomposition algorithm.+///+/// These parameters control the trade-off between decomposition quality, performance,+/// and the number of resulting convex parts. Understanding these parameters helps you+/// achieve the desired balance for your specific use case.+///+/// # Quick Parameter Guide+///+/// | Parameter | Lower Values | Higher Values | Recommended For |+/// |-----------|-------------|---------------|-----------------|+/// | `concavity` | More parts, better fit | Fewer parts, faster | Games: 0.01-0.05, Simulation: 0.001-0.01 |+/// | `resolution` | Faster, less detail | Slower, more detail | Preview: 32-64, Final: 64-256 |+/// | `max_convex_hulls` | Simpler result | More accurate | Simple: 4-8, Complex: 16-32 |+///+/// # Examples+///+/// ## Default Parameters (Balanced)+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::vhacd::VHACDParameters;+///+/// let params = VHACDParameters::default();+/// // Resolution: 64 (3D) or 256 (2D)+/// // Concavity: 0.01 (3D) or 0.1 (2D)+/// // Max convex hulls: 1024+/// // Good starting point for most cases+/// # }+/// ```+///+/// ## High Quality (Slower, More Accurate)+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::vhacd::VHACDParameters;+/// use parry3d::transformation::voxelization::FillMode;+///+/// let params = VHACDParameters {+/// resolution: 256, // High detail voxelization+/// concavity: 0.001, // Very tight fit to original+/// max_convex_hulls: 64, // Allow many parts+/// plane_downsampling: 2, // More precise plane search+/// convex_hull_downsampling: 2, // More precise hulls+/// alpha: 0.05,+/// beta: 0.05,+/// convex_hull_approximation: false, // Exact hulls+/// fill_mode: FillMode::FloodFill {+/// detect_cavities: false,+/// },+/// };+/// // Best for: Critical collision accuracy, offline processing+/// # }+/// ```+///+/// ## Fast Preview (Quick Iteration)+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::vhacd::VHACDParameters;+/// use parry3d::transformation::voxelization::FillMode;+///+/// let params = VHACDParameters {+/// resolution: 32, // Low resolution for speed+/// concavity: 0.05, // Allow some approximation+/// max_convex_hulls: 16, // Limit part count+/// plane_downsampling: 8, // Coarse plane search+/// convex_hull_downsampling: 8, // Coarse hulls+/// alpha: 0.05,+/// beta: 0.05,+/// convex_hull_approximation: true, // Fast approximation+/// fill_mode: FillMode::FloodFill {+/// detect_cavities: false,+/// },+/// };+/// // Best for: Rapid prototyping, testing during development+/// # }+/// ```+///+/// ## Game-Ready (Performance & Quality)+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::vhacd::VHACDParameters;+/// use parry3d::transformation::voxelization::FillMode;+///+/// let params = VHACDParameters {+/// resolution: 128, // Good balance+/// concavity: 0.01, // Reasonably tight+/// max_convex_hulls: 32, // Practical limit+/// plane_downsampling: 4, // Default precision+/// convex_hull_downsampling: 4, // Default precision+/// alpha: 0.05,+/// beta: 0.05,+/// convex_hull_approximation: true,+/// fill_mode: FillMode::FloodFill {+/// detect_cavities: false,+/// },+/// };+/// // Best for: Game colliders, physics simulations+/// # }+/// ```+///+/// # See Also+///+/// - Original implementation: <https://github.com/kmammou/v-hacd>+/// - Unity documentation: <https://github.com/Unity-Technologies/VHACD#parameters>+/// - Module documentation: [`crate::transformation::vhacd`]+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct VHACDParameters {+ /// Maximum allowed concavity (deviation from convexity) for each part.+ ///+ /// This is the **most important parameter** controlling the quality vs. part count trade-off.+ /// It measures how much the volume of each convex part can deviate from the actual geometry.+ ///+ /// # Behavior+ ///+ /// - **Lower values** (0.001 - 0.01): More convex parts, tighter fit to original shape+ /// - **Higher values** (0.05 - 0.1): Fewer convex parts, more approximation+ ///+ /// # Typical Values+ ///+ /// - **Simulation/Robotics**: 0.001 - 0.005 (high accuracy)+ /// - **Games**: 0.01 - 0.03 (balanced)+ /// - **Prototyping**: 0.05 - 0.1 (fast preview)+ ///+ /// # Default+ ///+ /// - 2D: `0.1` (more tolerant due to simpler geometry)+ /// - 3D: `0.01` (tighter tolerance for complex meshes)+ ///+ /// # Range+ ///+ /// Valid range: `[0.0, 1.0]`+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::vhacd::VHACDParameters;+ ///+ /// // High precision (more parts)+ /// let high_quality = VHACDParameters {+ /// concavity: 0.001,+ /// ..Default::default()+ /// };+ ///+ /// // Low precision (fewer parts, faster)+ /// let low_quality = VHACDParameters {+ /// concavity: 0.05,+ /// ..Default::default()+ /// };+ /// # }+ /// ```+ pub concavity: Real,++ /// Bias toward splitting along symmetry planes (e.g., cutting a humanoid down the middle).+ ///+ /// This parameter influences the algorithm to prefer cutting planes that align with+ /// the shape's symmetry. Higher values make the algorithm more likely to choose+ /// symmetric splits, which can produce more aesthetically pleasing decompositions.+ ///+ /// # Behavior+ ///+ /// - **0.0**: No bias, purely based on concavity minimization+ /// - **0.05** (default): Slight preference for symmetric splits+ /// - **0.2+**: Strong preference for symmetric splits+ ///+ /// # When to Adjust+ ///+ /// - Increase for symmetric objects (characters, vehicles, buildings)+ /// - Decrease for asymmetric or organic shapes+ ///+ /// # Default+ ///+ /// `0.05`+ ///+ /// # Range+ ///+ /// Valid range: `[0.0, 1.0]`+ pub alpha: Real,++ /// Bias toward splitting along revolution axes (e.g., cutting a cylinder lengthwise).+ ///+ /// This parameter influences the algorithm to prefer cutting planes that align with+ /// axes of rotational symmetry. Useful for objects with cylindrical or rotational+ /// features.+ ///+ /// # Behavior+ ///+ /// - **0.0**: No bias, purely based on concavity minimization+ /// - **0.05** (default): Slight preference for revolution axis splits+ /// - **0.2+**: Strong preference for revolution axis splits+ ///+ /// # When to Adjust+ ///+ /// - Increase for objects with cylindrical features (wheels, bottles, tunnels)+ /// - Decrease for box-like or irregular shapes+ ///+ /// # Default+ ///+ /// `0.05`+ ///+ /// # Range+ ///+ /// Valid range: `[0.0, 1.0]`+ pub beta: Real,++ /// Resolution of the voxel grid used for decomposition.+ ///+ /// The input mesh is first converted to a voxel grid. This parameter determines+ /// how fine that grid is. Higher resolution captures more detail but is slower+ /// and uses more memory.+ ///+ /// # Behavior+ ///+ /// - **32-64**: Fast, suitable for simple shapes or preview+ /// - **64-128**: Balanced, good for most game objects+ /// - **128-256**: High quality, captures fine details+ /// - **256+**: Very high quality, slow, for critical objects+ ///+ /// # Memory Usage+ ///+ /// Memory scales as O(resolution³) in 3D or O(resolution²) in 2D.+ /// Resolution 64 ≈ 260KB, Resolution 128 ≈ 2MB, Resolution 256 ≈ 16MB+ ///+ /// # Default+ ///+ /// - 2D: `256` (2D voxelization is much cheaper)+ /// - 3D: `64` (balances quality and performance)+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::vhacd::VHACDParameters;+ ///+ /// // Quick preview+ /// let preview = VHACDParameters {+ /// resolution: 32,+ /// ..Default::default()+ /// };+ ///+ /// // Production quality+ /// let production = VHACDParameters {+ /// resolution: 128,+ /// ..Default::default()+ /// };+ /// # }+ /// ```+ pub resolution: u32,++ /// Granularity of the search for optimal clipping planes.+ ///+ /// During decomposition, the algorithm samples potential cutting planes along+ /// each axis. This parameter controls how many planes to skip between samples.+ /// Lower values mean more planes are tested (slower but more accurate).+ ///+ /// # Behavior+ ///+ /// - **1**: Test every possible plane (slowest, highest quality)+ /// - **4** (default): Test every 4th plane (good balance)+ /// - **8+**: Test fewer planes (faster, lower quality)+ ///+ /// # Performance Impact+ ///+ /// Reducing this value can significantly increase decomposition time, especially+ /// with high `resolution` values. Often doubled for the initial coarse pass.+ ///+ /// # Default+ ///+ /// `4`+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::vhacd::VHACDParameters;+ ///+ /// // Fast decomposition (coarse plane search)+ /// let fast = VHACDParameters {+ /// plane_downsampling: 8,+ /// ..Default::default()+ /// };+ ///+ /// // Precise decomposition (fine plane search)+ /// let precise = VHACDParameters {+ /// plane_downsampling: 1,+ /// ..Default::default()+ /// };+ /// # }+ /// ```+ pub plane_downsampling: u32,++ /// Precision of convex hull generation during plane selection.+ ///+ /// When evaluating potential cutting planes, the algorithm computes convex hulls+ /// of the resulting parts. This parameter controls how much to downsample the+ /// voxels before computing these hulls. Lower values = more precise but slower.+ ///+ /// # Behavior+ ///+ /// - **1**: Use all voxels (slowest, highest quality)+ /// - **4** (default): Use every 4th voxel (good balance)+ /// - **8+**: Use fewer voxels (faster, less precise)+ ///+ /// # Trade-off+ ///+ /// This primarily affects which cutting plane is chosen, not the final result.+ /// Higher downsampling can still produce good results much faster.+ ///+ /// # Default+ ///+ /// `4`+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::vhacd::VHACDParameters;+ ///+ /// // Faster hull computation+ /// let fast = VHACDParameters {+ /// convex_hull_downsampling: 8,+ /// ..Default::default()+ /// };+ /// # }+ /// ```+ pub convex_hull_downsampling: u32,++ /// How to fill the voxel grid from the input mesh or polyline.+ ///+ /// This controls the voxelization process, including how to handle the interior+ /// of the shape and whether to detect special features like cavities.+ ///+ /// # Options+ ///+ /// - `FloodFill { detect_cavities: false, detect_self_intersections: false }` (default):+ /// Fast flood-fill from outside, works for most closed meshes+ /// - `FloodFill { detect_cavities: true, ... }`:+ /// Also detect and preserve internal cavities (slower)+ /// - `SurfaceOnly`:+ /// Only voxelize the surface, not the interior (for hollow shapes)+ ///+ /// # Default+ ///+ /// ```text+ /// FillMode::FloodFill {+ /// detect_cavities: false,+ /// detect_self_intersections: false, // 2D only+ /// }+ /// ```+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::vhacd::VHACDParameters;+ /// use parry3d::transformation::voxelization::FillMode;+ ///+ /// // For meshes with internal cavities (e.g., a bottle)+ /// let with_cavities = VHACDParameters {+ /// fill_mode: FillMode::FloodFill {+ /// detect_cavities: true,+ /// },+ /// ..Default::default()+ /// };+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// [`FillMode`] for detailed documentation on voxelization modes.+ pub fill_mode: FillMode,++ /// Whether to use approximate convex hulls during decomposition.+ ///+ /// When `true`, the algorithm uses a faster but less precise method to compute+ /// convex hulls during the decomposition process. This significantly speeds up+ /// decomposition with minimal impact on the final quality.+ ///+ /// # Behavior+ ///+ /// - **`true`** (default): Clip the parent's convex hull and add sample points+ /// (fast, good quality)+ /// - **`false`**: Compute exact convex hulls from all voxels+ /// (slower, slightly better quality)+ ///+ /// # Performance Impact+ ///+ /// Setting this to `false` can increase decomposition time by 2-5x, with often+ /// negligible quality improvement. Recommended to keep `true` for most cases.+ ///+ /// # Default+ ///+ /// `true`+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::vhacd::VHACDParameters;+ ///+ /// // Absolute highest quality (slow)+ /// let exact = VHACDParameters {+ /// convex_hull_approximation: false,+ /// ..Default::default()+ /// };+ /// # }+ /// ```+ pub convex_hull_approximation: bool,++ /// Maximum number of convex parts to generate.+ ///+ /// This acts as an upper limit on the number of convex hulls the algorithm will+ /// produce. The actual number may be less if the shape can be decomposed with+ /// fewer parts while meeting the `concavity` threshold.+ ///+ /// # Behavior+ ///+ /// The algorithm uses a binary tree decomposition with depth calculated to potentially+ /// produce up to `max_convex_hulls` parts. If parts are already approximately convex+ /// (concavity below threshold), they won't be split further.+ ///+ /// # Typical Values+ ///+ /// - **4-8**: Simple objects, performance-critical+ /// - **16-32**: Standard game objects, good balance+ /// - **32-64**: Complex objects, high quality+ /// - **64+**: Very complex objects, offline processing+ ///+ /// # Performance Note+ ///+ /// More parts = more collision checks during physics simulation. Keep this+ /// reasonable for dynamic objects (8-32). Static objects can afford more.+ ///+ /// # Default+ ///+ /// `1024` (effectively unlimited for most practical cases)+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::vhacd::VHACDParameters;+ ///+ /// // Limit to reasonable number for game character+ /// let game_character = VHACDParameters {+ /// max_convex_hulls: 16,+ /// concavity: 0.02,+ /// ..Default::default()+ /// };+ ///+ /// // Allow many parts for static environment+ /// let environment = VHACDParameters {+ /// max_convex_hulls: 128,+ /// concavity: 0.005,+ /// ..Default::default()+ /// };+ /// # }+ /// ```+ pub max_convex_hulls: u32,+}++impl Default for VHACDParameters {+ fn default() -> Self {+ Self {+ #[cfg(feature = "dim3")]+ resolution: 64,+ #[cfg(feature = "dim3")]+ concavity: 0.01,+ #[cfg(feature = "dim2")]+ resolution: 256,+ #[cfg(feature = "dim2")]+ concavity: 0.1,+ plane_downsampling: 4,+ convex_hull_downsampling: 4,+ alpha: 0.05,+ beta: 0.05,+ convex_hull_approximation: true,+ max_convex_hulls: 1024,+ fill_mode: FillMode::FloodFill {+ detect_cavities: false,+ #[cfg(feature = "dim2")]+ detect_self_intersections: false,+ },+ }+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/vhacd/vhacd.rs b/renderer/third_party/parry3d/src/transformation/vhacd/vhacd.rsnew file mode 100644index 0000000..6ab6f05--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/vhacd/vhacd.rs@@ -0,0 +1,1219 @@+// Rust port, with modifications, of https://github.com/kmammou/v-hacd/blob/master/src/VHACD_Lib/src/VHACD.cpp+// By Khaled Mamou+//+// # License of the original C++ code:+// > Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)+// > All rights reserved.+// >+// >+// > Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:+// >+// > 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.+// >+// > 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.+// >+// > 3. The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission.+// >+// > THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++use crate::math::{Int, Real, Vector, VectorExt, DIM};+use crate::transformation::vhacd::VHACDParameters;+use crate::transformation::voxelization::{VoxelSet, VoxelizedVolume};+use alloc::sync::Arc;+use alloc::vec::Vec;++#[cfg(feature = "dim2")]+type ConvexHull = Vec<Vector>;+#[cfg(feature = "dim3")]+type ConvexHull = (Vec<Vector>, Vec<[u32; 3]>);++#[derive(Copy, Clone, Debug)]+pub(crate) struct CutPlane {+ pub abc: Vector,+ pub d: Real,+ pub axis: u8,+ pub index: u32,+}++/// Approximate convex decomposition using the VHACD algorithm.+///+/// This structure holds the result of the V-HACD (Volumetric Hierarchical Approximate+/// Convex Decomposition) algorithm, which decomposes a concave shape into multiple+/// approximately-convex parts.+///+/// # Overview+///+/// The `VHACD` struct stores the decomposition result as a collection of voxelized parts,+/// where each part is approximately convex. These parts can be converted to convex hulls+/// for use in collision detection and physics simulation.+///+/// # Basic Workflow+///+/// 1. **Decompose**: Create a `VHACD` instance using [`VHACD::decompose`] or [`VHACD::from_voxels`]+/// 2. **Access Parts**: Get the voxelized parts using [`voxel_parts`](VHACD::voxel_parts)+/// 3. **Generate Hulls**: Compute convex hulls with [`compute_convex_hulls`](VHACD::compute_convex_hulls)+/// or [`compute_exact_convex_hulls`](VHACD::compute_exact_convex_hulls)+///+/// # Examples+///+/// ## Basic Usage+///+/// ```no_run+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::math::Vector;+/// use parry3d::transformation::vhacd::{VHACD, VHACDParameters};+///+/// // Define a simple mesh (tetrahedron)+/// let vertices = vec![+/// Vector::new(0.0, 0.0, 0.0),+/// Vector::new(1.0, 0.0, 0.0),+/// Vector::new(0.5, 1.0, 0.0),+/// Vector::new(0.5, 0.5, 1.0),+/// ];+/// let indices = vec![+/// [0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2],+/// ];+///+/// // Decompose with default parameters+/// let decomposition = VHACD::decompose(+/// &VHACDParameters::default(),+/// &vertices,+/// &indices,+/// false,+/// );+///+/// // Access the results+/// println!("Generated {} parts", decomposition.voxel_parts().len());+///+/// // Get convex hulls for collision detection+/// let hulls = decomposition.compute_convex_hulls(4);+/// # }+/// ```+///+/// ## With Custom Parameters+///+/// ```no_run+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::math::Vector;+/// use parry3d::transformation::vhacd::{VHACD, VHACDParameters};+///+/// # let vertices = vec![+/// # Vector::new(0.0, 0.0, 0.0), Vector::new(1.0, 0.0, 0.0),+/// # Vector::new(0.5, 1.0, 0.0), Vector::new(0.5, 0.5, 1.0),+/// # ];+/// # let indices = vec![[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]];+/// #+/// // High-quality decomposition settings+/// let params = VHACDParameters {+/// resolution: 128,+/// concavity: 0.001,+/// max_convex_hulls: 32,+/// ..Default::default()+/// };+///+/// let decomposition = VHACD::decompose(¶ms, &vertices, &indices, false);+/// # }+/// ```+///+/// # See Also+///+/// - [`VHACDParameters`]: Configuration for the decomposition algorithm+/// - [`compute_convex_hulls`](VHACD::compute_convex_hulls): Generate convex hulls from voxels+/// - [`compute_exact_convex_hulls`](VHACD::compute_exact_convex_hulls): Generate hulls from original mesh+/// - Module documentation: [`crate::transformation::vhacd`]+pub struct VHACD {+ // raycast_mesh: Option<RaycastMesh>,+ voxel_parts: Vec<VoxelSet>,+ volume_ch0: Real,+ max_concavity: Real,+}++impl VHACD {+ /// Decompose the given polyline (in 2D) or triangle mesh (in 3D).+ ///+ /// This is the primary method for performing approximate convex decomposition. It takes+ /// a mesh defined by vertices and indices, voxelizes it, and decomposes it into+ /// approximately-convex parts using the V-HACD algorithm.+ ///+ /// # Parameters+ ///+ /// * `params` - Configuration parameters controlling the decomposition process.+ /// See [`VHACDParameters`] for details on each parameter.+ ///+ /// * `points` - The vertex positions of your mesh (3D) or polyline (2D).+ /// Each point represents a vertex in world space.+ ///+ /// * `indices` - The connectivity information:+ /// - **3D**: Triangle indices `[u32; 3]` - each entry defines a triangle using 3 vertex indices+ /// - **2D**: Segment indices `[u32; 2]` - each entry defines a line segment using 2 vertex indices+ ///+ /// * `keep_voxel_to_primitives_map` - Whether to maintain a mapping between voxels and+ /// the original mesh primitives (triangles/segments) they intersect.+ /// - **`true`**: Enables [`compute_exact_convex_hulls`](VHACD::compute_exact_convex_hulls)+ /// which uses original mesh geometry for more accurate results. Uses more memory.+ /// - **`false`**: Only voxel-based hulls available via [`compute_convex_hulls`](VHACD::compute_convex_hulls).+ /// More memory efficient.+ ///+ /// # Returns+ ///+ /// A `VHACD` instance containing the decomposition results. Use [`voxel_parts`](VHACD::voxel_parts)+ /// to access the raw voxelized parts, or [`compute_convex_hulls`](VHACD::compute_convex_hulls)+ /// to generate convex hull geometry.+ ///+ /// # Performance+ ///+ /// Decomposition time depends primarily on:+ /// - **`resolution`**: Higher = slower (cubic scaling in 3D)+ /// - **`max_convex_hulls`**: More parts = more splits = longer time+ /// - **Mesh complexity**: More vertices/triangles = slower voxelization+ ///+ /// Typical times (on modern CPU):+ /// - Simple mesh (1K triangles, resolution 64): 100-500ms+ /// - Complex mesh (10K triangles, resolution 128): 1-5 seconds+ /// - Very complex (100K triangles, resolution 256): 10-60 seconds+ ///+ /// # Examples+ ///+ /// ## Basic Decomposition+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::math::Vector;+ /// use parry3d::transformation::vhacd::{VHACD, VHACDParameters};+ ///+ /// // Simple L-shaped mesh+ /// let vertices = vec![+ /// Vector::new(0.0, 0.0, 0.0), Vector::new(2.0, 0.0, 0.0),+ /// Vector::new(2.0, 1.0, 0.0), Vector::new(1.0, 1.0, 0.0),+ /// ];+ /// let indices = vec![+ /// [0, 1, 2], [0, 2, 3],+ /// ];+ ///+ /// let decomposition = VHACD::decompose(+ /// &VHACDParameters::default(),+ /// &vertices,+ /// &indices,+ /// false, // Don't need exact hulls+ /// );+ ///+ /// println!("Parts: {}", decomposition.voxel_parts().len());+ /// # }+ /// ```+ ///+ /// ## With Exact Hull Generation+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::math::Vector;+ /// use parry3d::transformation::vhacd::{VHACD, VHACDParameters};+ ///+ /// # let vertices = vec![+ /// # Vector::new(0.0, 0.0, 0.0), Vector::new(1.0, 0.0, 0.0),+ /// # Vector::new(0.5, 1.0, 0.0), Vector::new(0.5, 0.5, 1.0),+ /// # ];+ /// # let indices = vec![[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]];+ /// #+ /// // Enable voxel-to-primitive mapping for exact hulls+ /// let decomposition = VHACD::decompose(+ /// &VHACDParameters::default(),+ /// &vertices,+ /// &indices,+ /// true, // <-- Enable for exact hulls+ /// );+ ///+ /// // Now we can compute exact hulls using original mesh+ /// let exact_hulls = decomposition.compute_exact_convex_hulls(&vertices, &indices);+ /// # }+ /// ```+ ///+ /// ## Custom Parameters+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::math::Vector;+ /// use parry3d::transformation::vhacd::{VHACD, VHACDParameters};+ ///+ /// # let vertices = vec![+ /// # Vector::new(0.0, 0.0, 0.0), Vector::new(1.0, 0.0, 0.0),+ /// # Vector::new(0.5, 1.0, 0.0), Vector::new(0.5, 0.5, 1.0),+ /// # ];+ /// # let indices = vec![[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]];+ /// #+ /// // High-quality settings for important objects+ /// let params = VHACDParameters {+ /// resolution: 128, // High detail+ /// concavity: 0.001, // Tight fit+ /// max_convex_hulls: 32, // Allow many parts+ /// ..Default::default()+ /// };+ ///+ /// let decomposition = VHACD::decompose(¶ms, &vertices, &indices, false);+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`VHACDParameters`]: Detailed parameter documentation+ /// - [`from_voxels`](VHACD::from_voxels): Decompose pre-voxelized data+ /// - [`compute_convex_hulls`](VHACD::compute_convex_hulls): Generate voxel-based hulls+ /// - [`compute_exact_convex_hulls`](VHACD::compute_exact_convex_hulls): Generate mesh-based hulls+ pub fn decompose(+ params: &VHACDParameters,+ points: &[Vector],+ indices: &[[u32; DIM]],+ keep_voxel_to_primitives_map: bool,+ ) -> Self {+ // if params.project_hull_vertices || params.fill_mode == FillMode::RAYCAST_FILL {+ // self.raycast_mesh =+ // RaycastMesh::create_raycast_mesh(num_points, points, num_triangles, triangles);+ // }++ let voxelized = VoxelizedVolume::voxelize(+ points,+ indices,+ params.resolution,+ params.fill_mode,+ keep_voxel_to_primitives_map,+ // &self.raycast_mesh,+ );++ let mut result = Self::from_voxels(params, voxelized.into());++ let primitive_classes = Arc::new(result.classify_primitives(indices.len()));+ for part in &mut result.voxel_parts {+ part.primitive_classes = primitive_classes.clone();+ }++ result+ }++ /// Perform an approximate convex decomposition of a pre-voxelized set of voxels.+ ///+ /// This method allows you to decompose a shape that has already been voxelized,+ /// bypassing the voxelization step. This is useful if you:+ /// - Already have voxelized data from another source+ /// - Want to decompose the same voxelization with different parameters+ /// - Need more control over the voxelization process+ ///+ /// # Parameters+ ///+ /// * `params` - Configuration parameters for the decomposition algorithm.+ /// See [`VHACDParameters`] for details.+ ///+ /// * `voxels` - A pre-voxelized volume represented as a [`VoxelSet`].+ /// You can create this using [`VoxelizedVolume::voxelize`] or other voxelization methods.+ ///+ /// # Returns+ ///+ /// A `VHACD` instance containing the decomposition results.+ ///+ /// # Examples+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::math::Vector;+ /// use parry3d::transformation::vhacd::{VHACD, VHACDParameters};+ /// use parry3d::transformation::voxelization::{VoxelizedVolume, FillMode};+ ///+ /// # let vertices = vec![+ /// # Vector::new(0.0, 0.0, 0.0), Vector::new(1.0, 0.0, 0.0),+ /// # Vector::new(0.5, 1.0, 0.0), Vector::new(0.5, 0.5, 1.0),+ /// # ];+ /// # let indices = vec![[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]];+ /// #+ /// // First, voxelize the mesh manually+ /// let voxelized = VoxelizedVolume::voxelize(+ /// &vertices,+ /// &indices,+ /// 64, // resolution+ /// FillMode::FloodFill {+ /// detect_cavities: false,+ /// },+ /// false, // don't keep primitive mapping+ /// );+ ///+ /// // Then decompose the voxels+ /// let decomposition = VHACD::from_voxels(+ /// &VHACDParameters::default(),+ /// voxelized.into(),+ /// );+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`decompose`](VHACD::decompose): Decompose directly from mesh (includes voxelization)+ /// - [`VoxelizedVolume`]: For manual voxelization+ /// - [`VoxelSet`]: The voxel data structure+ ///+ /// [`VoxelizedVolume::voxelize`]: crate::transformation::voxelization::VoxelizedVolume::voxelize+ /// [`VoxelSet`]: crate::transformation::voxelization::VoxelSet+ /// [`VoxelizedVolume`]: crate::transformation::voxelization::VoxelizedVolume+ pub fn from_voxels(params: &VHACDParameters, voxels: VoxelSet) -> Self {+ let mut result = Self {+ // raycast_mesh: None,+ voxel_parts: Vec::new(),+ volume_ch0: 0.0,+ max_concavity: -Real::MAX,+ };++ result.do_compute_acd(params, voxels);+ result+ }++ /// Returns the approximately-convex voxelized parts computed by the VHACD algorithm.+ ///+ /// Each part in the returned slice represents an approximately-convex region of the+ /// original shape, stored as a set of voxels. These voxelized parts are the direct+ /// result of the decomposition algorithm.+ ///+ /// # Returns+ ///+ /// A slice of [`VoxelSet`] structures, where each set represents one convex part.+ /// The number of parts depends on the shape's complexity and the parameters used+ /// (especially `concavity` and `max_convex_hulls`).+ ///+ /// # Usage+ ///+ /// You typically don't use the voxel parts directly for collision detection. Instead:+ /// - Use [`compute_convex_hulls`](VHACD::compute_convex_hulls) for voxel-based convex hulls+ /// - Use [`compute_exact_convex_hulls`](VHACD::compute_exact_convex_hulls) for mesh-based hulls+ ///+ /// However, accessing voxel parts directly is useful for:+ /// - Debugging and visualization of the decomposition+ /// - Custom processing of the voxelized representation+ /// - Understanding how the algorithm divided the shape+ ///+ /// # Examples+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::math::Vector;+ /// use parry3d::transformation::vhacd::{VHACD, VHACDParameters};+ ///+ /// # let vertices = vec![+ /// # Vector::new(0.0, 0.0, 0.0), Vector::new(1.0, 0.0, 0.0),+ /// # Vector::new(0.5, 1.0, 0.0), Vector::new(0.5, 0.5, 1.0),+ /// # ];+ /// # let indices = vec![[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]];+ /// #+ /// let decomposition = VHACD::decompose(+ /// &VHACDParameters::default(),+ /// &vertices,+ /// &indices,+ /// false,+ /// );+ ///+ /// let parts = decomposition.voxel_parts();+ /// println!("Generated {} convex parts", parts.len());+ ///+ /// // Inspect individual parts+ /// for (i, part) in parts.iter().enumerate() {+ /// println!("Part {}: {} voxels", i, part.voxels().len());+ /// }+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`VoxelSet`]: The voxel data structure+ /// - [`compute_convex_hulls`](VHACD::compute_convex_hulls): Convert to collision-ready convex hulls+ ///+ /// [`VoxelSet`]: crate::transformation::voxelization::VoxelSet+ pub fn voxel_parts(&self) -> &[VoxelSet] {+ &self.voxel_parts+ }++ #[cfg(feature = "dim2")]+ fn compute_preferred_cutting_direction(eigenvalues: Vector) -> (Vector, Real) {+ let vx = eigenvalues.y * eigenvalues.y;+ let vy = eigenvalues.x * eigenvalues.x;++ if vx < vy {+ let e = eigenvalues.y * eigenvalues.y;+ let dir = Vector::X;++ if e == 0.0 {+ (dir, 0.0)+ } else {+ (dir, 1.0 - vx / e)+ }+ } else {+ let e = eigenvalues.x * eigenvalues.x;+ let dir = Vector::Y;++ if e == 0.0 {+ (dir, 0.0)+ } else {+ (dir, 1.0 - vy / e)+ }+ }+ }++ #[cfg(feature = "dim3")]+ fn compute_preferred_cutting_direction(eigenvalues: Vector) -> (Vector, Real) {+ let vx = (eigenvalues.y - eigenvalues.z) * (eigenvalues.y - eigenvalues.z);+ let vy = (eigenvalues.x - eigenvalues.z) * (eigenvalues.x - eigenvalues.z);+ let vz = (eigenvalues.x - eigenvalues.y) * (eigenvalues.x - eigenvalues.y);++ if vx < vy && vx < vz {+ let e = eigenvalues.y * eigenvalues.y + eigenvalues.z * eigenvalues.z;+ let dir = Vector::X;++ if e == 0.0 {+ (dir, 0.0)+ } else {+ (dir, 1.0 - vx / e)+ }+ } else if vy < vx && vy < vz {+ let e = eigenvalues.x * eigenvalues.x + eigenvalues.z * eigenvalues.z;+ let dir = Vector::Y;++ if e == 0.0 {+ (dir, 0.0)+ } else {+ (dir, 1.0 - vy / e)+ }+ } else {+ let e = eigenvalues.x * eigenvalues.x + eigenvalues.y * eigenvalues.y;+ let dir = Vector::Z;++ if e == 0.0 {+ (dir, 0.0)+ } else {+ (dir, 1.0 - vz / e)+ }+ }+ }++ fn refine_axes_aligned_clipping_planes(+ vset: &VoxelSet,+ best_plane: &CutPlane,+ downsampling: u32,+ planes: &mut Vec<CutPlane>,+ ) {+ let min_v = vset.min_bb_voxels();+ let max_v = vset.max_bb_voxels();++ let best_id = best_plane.axis as usize;+ let i0 = min_v[best_id].max(best_plane.index.saturating_sub(downsampling) as Int);+ let i1 = max_v[best_id].min((best_plane.index + downsampling) as Int);++ for i in i0..=i1 {+ let plane = CutPlane {+ abc: Vector::ith(best_id, 1.0),+ axis: best_plane.axis,+ d: -(vset.origin[best_id] + (i as Real + 0.5) * vset.scale),+ index: i as u32,+ };+ planes.push(plane);+ }+ }++ // Returns the best plane, and the min concavity.+ fn compute_best_clipping_plane(+ &self,+ input_voxels: &VoxelSet,+ input_voxels_ch: &ConvexHull,+ planes: &[CutPlane],+ preferred_cutting_direction: Vector,+ w: Real,+ alpha: Real,+ beta: Real,+ convex_hull_downsampling: u32,+ params: &VHACDParameters,+ ) -> (CutPlane, Real) {+ let mut best_plane = planes[0];+ let mut min_concavity = Real::MAX;+ let mut i_best = -1;+ let mut min_total = Real::MAX;++ let mut left_ch;+ let mut right_ch;+ let mut left_ch_pts = Vec::new();+ let mut right_ch_pts = Vec::new();+ let mut left_voxels = VoxelSet::new();+ let mut right_voxels = VoxelSet::new();+ let mut on_surface_voxels = VoxelSet::new();++ input_voxels.select_on_surface(&mut on_surface_voxels);++ for (x, plane) in planes.iter().enumerate() {+ // Compute convex hulls.+ if params.convex_hull_approximation {+ right_ch_pts.clear();+ left_ch_pts.clear();++ on_surface_voxels.intersect(+ plane,+ &mut right_ch_pts,+ &mut left_ch_pts,+ convex_hull_downsampling * 32,+ );++ clip_mesh(+ #[cfg(feature = "dim2")]+ input_voxels_ch,+ #[cfg(feature = "dim3")]+ &input_voxels_ch.0,+ plane,+ &mut right_ch_pts,+ &mut left_ch_pts,+ );+ right_ch = convex_hull(&right_ch_pts);+ left_ch = convex_hull(&left_ch_pts);+ } else {+ on_surface_voxels.clip(plane, &mut right_voxels, &mut left_voxels);+ right_ch = right_voxels.compute_convex_hull(convex_hull_downsampling);+ left_ch = left_voxels.compute_convex_hull(convex_hull_downsampling);+ }++ let volume_left_ch = compute_volume(&left_ch);+ let volume_right_ch = compute_volume(&right_ch);++ // compute clipped volumes+ let (volume_left, volume_right) = input_voxels.compute_clipped_volumes(plane);+ let concavity_left = compute_concavity(volume_left, volume_left_ch, self.volume_ch0);+ let concavity_right = compute_concavity(volume_right, volume_right_ch, self.volume_ch0);+ let concavity = concavity_left + concavity_right;++ // compute cost+ let balance = alpha * (volume_left - volume_right).abs() / self.volume_ch0;+ let d = w * plane.abc.dot(preferred_cutting_direction);+ let symmetry = beta * d;+ let total = concavity + balance + symmetry;++ if total < min_total || (total == min_total && (x as Int) < i_best) {+ min_concavity = concavity;+ best_plane = *plane;+ min_total = total;+ i_best = x as Int;+ }+ }++ (best_plane, min_concavity)+ }++ fn process_primitive_set(+ &mut self,+ params: &VHACDParameters,+ first_iteration: bool,+ parts: &mut Vec<VoxelSet>,+ temp: &mut Vec<VoxelSet>,+ mut voxels: VoxelSet,+ ) {+ let volume = voxels.compute_volume(); // Compute the volume for this primitive set+ voxels.compute_bb(); // Compute the bounding box for this primitive set.+ let voxels_convex_hull = voxels.compute_convex_hull(params.convex_hull_downsampling); // Generate the convex hull for this primitive set.++ // Compute the volume of the convex hull+ let volume_ch = compute_volume(&voxels_convex_hull);++ // If this is the first iteration, store the volume of the base+ if first_iteration {+ self.volume_ch0 = volume_ch;+ }++ // Compute the concavity of this volume+ let concavity = compute_concavity(volume, volume_ch, self.volume_ch0);++ // Compute the volume error.+ if concavity > params.concavity {+ let eigenvalues = voxels.compute_principal_axes();+ let (preferred_cutting_direction, w) =+ Self::compute_preferred_cutting_direction(eigenvalues);++ let mut planes = Vec::new();+ voxels.compute_axes_aligned_clipping_planes(params.plane_downsampling, &mut planes);++ let (mut best_plane, mut min_concavity) = self.compute_best_clipping_plane(+ &voxels,+ &voxels_convex_hull,+ &planes,+ preferred_cutting_direction,+ w,+ concavity * params.alpha,+ concavity * params.beta,+ params.convex_hull_downsampling,+ params,+ );++ if params.plane_downsampling > 1 || params.convex_hull_downsampling > 1 {+ let mut planes_ref = Vec::new();++ Self::refine_axes_aligned_clipping_planes(+ &voxels,+ &best_plane,+ params.plane_downsampling,+ &mut planes_ref,+ );++ let best = self.compute_best_clipping_plane(+ &voxels,+ &voxels_convex_hull,+ &planes_ref,+ preferred_cutting_direction,+ w,+ concavity * params.alpha,+ concavity * params.beta,+ 1, // convex_hull_downsampling = 1+ params,+ );++ best_plane = best.0;+ min_concavity = best.1;+ }++ if min_concavity > self.max_concavity {+ self.max_concavity = min_concavity;+ }++ let mut best_left = VoxelSet::new();+ let mut best_right = VoxelSet::new();++ voxels.clip(&best_plane, &mut best_right, &mut best_left);++ temp.push(best_left);+ temp.push(best_right);+ } else {+ parts.push(voxels);+ }+ }++ fn do_compute_acd(&mut self, params: &VHACDParameters, mut voxels: VoxelSet) {+ let intersections = voxels.intersections.clone();+ let mut input_parts = Vec::new();+ let mut parts = Vec::new();+ let mut temp = Vec::new();+ input_parts.push(core::mem::take(&mut voxels));++ let mut first_iteration = true;+ self.volume_ch0 = 1.0;++ // Compute the decomposition depth based on the number of convex hulls being requested.+ let mut hull_count = 2;+ let mut depth = 1;++ while params.max_convex_hulls > hull_count {+ depth += 1;+ hull_count *= 2;+ }++ // We must always increment the decomposition depth one higher than the maximum number of hulls requested.+ // The reason for this is as follows.+ // Say, for example, the user requests 32 convex hulls exactly. This would be a decomposition depth of 5.+ // However, when we do that, we do *not* necessarily get 32 hulls as a result. This is because, during+ // the recursive descent of the binary tree, one or more of the leaf nodes may have no concavity and+ // will not be split. So, in this way, even with a decomposition depth of 5, you can produce fewer than+ // 32 hulls. So, in this case, we would set the decomposition depth to 6 (producing up to as high as 64 convex+ // hulls). Then, the merge step which combines over-described hulls down to the user requested amount, we will end+ // up getting exactly 32 convex hulls as a result. We could just allow the artist to directly control the+ // decomposition depth directly, but this would be a bit too complex and the preference is simply to let them+ // specify how many hulls they want and derive the solution from that.+ depth += 1;++ for _ in 0..depth {+ if input_parts.is_empty() {+ break;+ }++ for input_part in input_parts.drain(..) {+ self.process_primitive_set(+ params,+ first_iteration,+ &mut parts,+ &mut temp,+ input_part,+ );+ first_iteration = false;+ }++ core::mem::swap(&mut input_parts, &mut temp);+ // Note that temp is already clear because our previous for+ // loop used `drain`. However we call `clear` here explicitly+ // to make sure it still works if we remove the `drain` in the+ // future.+ temp.clear();+ }++ parts.append(&mut input_parts);+ self.voxel_parts = parts;++ for part in &mut self.voxel_parts {+ part.intersections = intersections.clone();+ }+ }++ // Returns a vector such that `result[i]` gives the index of the voxelized convex part that+ // intersects it.+ //+ // If multiple convex parts intersect the same primitive, then `result[i]` is set to `u32::MAX`.+ // This is used to avoid some useless triangle/segment cutting when computing the exact convex hull+ // of a voxelized convex part.+ fn classify_primitives(&self, num_primitives: usize) -> Vec<u32> {+ if num_primitives == 0 {+ return Vec::new();+ }++ const NO_CLASS: u32 = u32::MAX - 1;+ const MULTICLASS: u32 = u32::MAX;++ let mut primitive_classes = Vec::new();+ primitive_classes.resize(num_primitives, NO_CLASS);++ for (ipart, part) in self.voxel_parts.iter().enumerate() {+ for voxel in &part.voxels {+ let range = voxel.intersections_range.0..voxel.intersections_range.1;+ for inter in &part.intersections[range] {+ let class = &mut primitive_classes[*inter as usize];+ if *class == NO_CLASS {+ *class = ipart as u32;+ } else if *class != ipart as u32 {+ *class = MULTICLASS;+ }+ }+ }+ }++ primitive_classes+ }++ /// Compute the intersections between the voxelized convex part of this decomposition,+ /// and all the primitives from the original decomposed polyline/trimesh,+ ///+ /// This will panic if `keep_voxel_to_primitives_map` was set to `false` when initializing+ /// `self`.+ pub fn compute_primitive_intersections(+ &self,+ points: &[Vector],+ indices: &[[u32; DIM]],+ ) -> Vec<Vec<Vector>> {+ self.voxel_parts+ .iter()+ .map(|part| part.compute_primitive_intersections(points, indices))+ .collect()+ }++ /// Compute exact convex hulls using the original mesh geometry (2D version).+ ///+ /// This method generates convex hulls for each decomposed part by computing the convex+ /// hull of the intersection between the voxelized part and the **original polyline primitives**.+ /// This produces more accurate hulls than the voxel-based method, preserving the original+ /// geometry's detail.+ ///+ /// # Requirements+ ///+ /// This method requires that `keep_voxel_to_primitives_map` was set to `true` when calling+ /// [`VHACD::decompose`]. If it was `false`, this method will **panic**.+ ///+ /// # Parameters+ ///+ /// * `points` - The same vertex buffer used when calling [`VHACD::decompose`]+ /// * `indices` - The same index buffer (segment indices `[u32; 2]`) used when calling+ /// [`VHACD::decompose`]+ ///+ /// # Returns+ ///+ /// A vector of convex polygons (one per decomposed part), where each polygon is+ /// represented as a `Vec<Vector>` containing the hull vertices in order.+ ///+ /// # Performance+ ///+ /// This is more expensive than [`compute_convex_hulls`](VHACD::compute_convex_hulls) because+ /// it needs to compute intersections with the original primitives and then compute convex hulls.+ /// However, it produces more accurate results.+ ///+ /// # Examples+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::math::Vector;+ /// use parry2d::transformation::vhacd::{VHACD, VHACDParameters};+ ///+ /// // Define an L-shaped polyline+ /// let vertices = vec![+ /// Vector::new(0.0, 0.0), Vector::new(2.0, 0.0),+ /// Vector::new(2.0, 1.0), Vector::new(1.0, 1.0),+ /// Vector::new(1.0, 2.0), Vector::new(0.0, 2.0),+ /// ];+ /// let indices = vec![+ /// [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0],+ /// ];+ ///+ /// // IMPORTANT: Set keep_voxel_to_primitives_map to true+ /// let decomposition = VHACD::decompose(+ /// &VHACDParameters::default(),+ /// &vertices,+ /// &indices,+ /// true, // <-- Required for exact hulls+ /// );+ ///+ /// // Compute exact convex hulls using original geometry+ /// let exact_hulls = decomposition.compute_exact_convex_hulls(&vertices, &indices);+ ///+ /// for (i, hull) in exact_hulls.iter().enumerate() {+ /// println!("Hull {}: {} vertices", i, hull.len());+ /// }+ /// # }+ /// ```+ ///+ /// # Panics+ ///+ /// Panics if `keep_voxel_to_primitives_map` was `false` during decomposition.+ ///+ /// # See Also+ ///+ /// - [`compute_convex_hulls`](VHACD::compute_convex_hulls): Faster voxel-based hulls+ /// - [`compute_primitive_intersections`](VHACD::compute_primitive_intersections): Get raw intersection points+ #[cfg(feature = "dim2")]+ pub fn compute_exact_convex_hulls(+ &self,+ points: &[Vector],+ indices: &[[u32; DIM]],+ ) -> Vec<Vec<Vector>> {+ self.voxel_parts+ .iter()+ .map(|part| part.compute_exact_convex_hull(points, indices))+ .collect()+ }++ /// Compute exact convex hulls using the original mesh geometry (3D version).+ ///+ /// This method generates convex hulls for each decomposed part by computing the convex+ /// hull of the intersection between the voxelized part and the **original triangle mesh+ /// primitives**. This produces more accurate hulls than the voxel-based method, preserving+ /// the original geometry's detail.+ ///+ /// # Requirements+ ///+ /// This method requires that `keep_voxel_to_primitives_map` was set to `true` when calling+ /// [`VHACD::decompose`]. If it was `false`, this method will **panic**.+ ///+ /// # Parameters+ ///+ /// * `points` - The same vertex buffer used when calling [`VHACD::decompose`]+ /// * `indices` - The same index buffer (triangle indices `[u32; 3]`) used when calling+ /// [`VHACD::decompose`]+ ///+ /// # Returns+ ///+ /// A vector of convex hulls (one per decomposed part), where each hull is represented as+ /// a tuple `(vertices, indices)`:+ /// - `vertices`: `Vec<Vector>` - The hull vertices+ /// - `indices`: `Vec<[u32; 3]>` - Triangle indices defining the hull surface+ ///+ /// # Performance+ ///+ /// This is more expensive than [`compute_convex_hulls`](VHACD::compute_convex_hulls) because+ /// it needs to compute intersections with the original primitives and then compute convex hulls.+ /// However, it produces more accurate results that better match the original mesh.+ ///+ /// # Examples+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::math::Vector;+ /// use parry3d::transformation::vhacd::{VHACD, VHACDParameters};+ ///+ /// # let vertices = vec![+ /// # Vector::new(0.0, 0.0, 0.0), Vector::new(1.0, 0.0, 0.0),+ /// # Vector::new(0.5, 1.0, 0.0), Vector::new(0.5, 0.5, 1.0),+ /// # ];+ /// # let indices = vec![[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]];+ /// #+ /// // IMPORTANT: Set keep_voxel_to_primitives_map to true+ /// let decomposition = VHACD::decompose(+ /// &VHACDParameters::default(),+ /// &vertices,+ /// &indices,+ /// true, // <-- Required for exact hulls+ /// );+ ///+ /// // Compute exact convex hulls using original geometry+ /// let exact_hulls = decomposition.compute_exact_convex_hulls(&vertices, &indices);+ ///+ /// for (i, (verts, tris)) in exact_hulls.iter().enumerate() {+ /// println!("Hull {}: {} vertices, {} triangles", i, verts.len(), tris.len());+ /// }+ /// # }+ /// ```+ ///+ /// # Panics+ ///+ /// Panics if `keep_voxel_to_primitives_map` was `false` during decomposition.+ ///+ /// # See Also+ ///+ /// - [`compute_convex_hulls`](VHACD::compute_convex_hulls): Faster voxel-based hulls+ /// - [`compute_primitive_intersections`](VHACD::compute_primitive_intersections): Get raw intersection points+ #[cfg(feature = "dim3")]+ pub fn compute_exact_convex_hulls(+ &self,+ points: &[Vector],+ indices: &[[u32; DIM]],+ ) -> Vec<(Vec<Vector>, Vec<[u32; DIM]>)> {+ self.voxel_parts+ .iter()+ .map(|part| part.compute_exact_convex_hull(points, indices))+ .collect()+ }++ /// Compute convex hulls from the voxelized parts (2D version).+ ///+ /// This method generates convex polygons for each decomposed part by computing the convex+ /// hull of the **voxel vertices**. This is faster than [`compute_exact_convex_hulls`](VHACD::compute_exact_convex_hulls)+ /// but the hulls are based on the voxelized representation rather than the original geometry.+ ///+ /// # Parameters+ ///+ /// * `downsampling` - Controls how many voxels to skip when generating the hull.+ /// Higher values = fewer points = simpler hulls = faster computation.+ /// - `1`: Use all voxel vertices (highest quality, slowest)+ /// - `4`: Use every 4th voxel (good balance, recommended)+ /// - `8+`: Use fewer voxels (fastest, simpler hulls)+ ///+ /// Values less than 1 are clamped to 1.+ ///+ /// # Returns+ ///+ /// A vector of convex polygons (one per decomposed part), where each polygon is+ /// represented as a `Vec<Vector>` containing the hull vertices in order.+ ///+ /// # Performance+ ///+ /// This method is faster than [`compute_exact_convex_hulls`](VHACD::compute_exact_convex_hulls)+ /// because it works directly with voxel data without needing to intersect with original+ /// mesh primitives. However, the resulting hulls are slightly less accurate.+ ///+ /// # When to Use+ ///+ /// Use this method when:+ /// - You don't need the highest accuracy+ /// - Performance is important+ /// - You didn't enable `keep_voxel_to_primitives_map` during decomposition+ /// - The voxel resolution is high enough for your needs+ ///+ /// Use [`compute_exact_convex_hulls`](VHACD::compute_exact_convex_hulls) when:+ /// - You need the most accurate representation of the original geometry+ /// - You have enabled `keep_voxel_to_primitives_map`+ ///+ /// # Examples+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// use parry2d::math::Vector;+ /// use parry2d::transformation::vhacd::{VHACD, VHACDParameters};+ ///+ /// // Define an L-shaped polyline+ /// let vertices = vec![+ /// Vector::new(0.0, 0.0), Vector::new(2.0, 0.0),+ /// Vector::new(2.0, 1.0), Vector::new(1.0, 1.0),+ /// Vector::new(1.0, 2.0), Vector::new(0.0, 2.0),+ /// ];+ /// let indices = vec![+ /// [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0],+ /// ];+ ///+ /// let decomposition = VHACD::decompose(+ /// &VHACDParameters::default(),+ /// &vertices,+ /// &indices,+ /// false, // voxel-to-primitive mapping not needed+ /// );+ ///+ /// // Compute voxel-based convex hulls with moderate downsampling+ /// let hulls = decomposition.compute_convex_hulls(4);+ ///+ /// for (i, hull) in hulls.iter().enumerate() {+ /// println!("Hull {}: {} vertices", i, hull.len());+ /// }+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`compute_exact_convex_hulls`](VHACD::compute_exact_convex_hulls): More accurate mesh-based hulls+ /// - [`voxel_parts`](VHACD::voxel_parts): Access the raw voxel data+ #[cfg(feature = "dim2")]+ pub fn compute_convex_hulls(&self, downsampling: u32) -> Vec<Vec<Vector>> {+ let downsampling = downsampling.max(1);+ self.voxel_parts+ .iter()+ .map(|part| part.compute_convex_hull(downsampling))+ .collect()+ }++ /// Compute convex hulls from the voxelized parts (3D version).+ ///+ /// This method generates convex meshes for each decomposed part by computing the convex+ /// hull of the **voxel vertices**. This is faster than [`compute_exact_convex_hulls`](VHACD::compute_exact_convex_hulls)+ /// but the hulls are based on the voxelized representation rather than the original geometry.+ ///+ /// # Parameters+ ///+ /// * `downsampling` - Controls how many voxels to skip when generating the hull.+ /// Higher values = fewer points = simpler hulls = faster computation.+ /// - `1`: Use all voxel vertices (highest quality, slowest)+ /// - `4`: Use every 4th voxel (good balance, recommended)+ /// - `8+`: Use fewer voxels (fastest, simpler hulls)+ ///+ /// Values less than 1 are clamped to 1.+ ///+ /// # Returns+ ///+ /// A vector of convex hulls (one per decomposed part), where each hull is represented as+ /// a tuple `(vertices, indices)`:+ /// - `vertices`: `Vec<Vector>` - The hull vertices+ /// - `indices`: `Vec<[u32; 3]>` - Triangle indices defining the hull surface+ ///+ /// # Performance+ ///+ /// This method is faster than [`compute_exact_convex_hulls`](VHACD::compute_exact_convex_hulls)+ /// because it works directly with voxel data without needing to intersect with original+ /// mesh primitives. The performance scales with the number of voxels and the downsampling factor.+ ///+ /// # When to Use+ ///+ /// Use this method when:+ /// - You don't need the highest accuracy+ /// - Performance is important+ /// - You didn't enable `keep_voxel_to_primitives_map` during decomposition+ /// - The voxel resolution is high enough for your needs+ /// - You're using this for real-time collision detection+ ///+ /// Use [`compute_exact_convex_hulls`](VHACD::compute_exact_convex_hulls) when:+ /// - You need the most accurate representation of the original geometry+ /// - You have enabled `keep_voxel_to_primitives_map`+ /// - Quality is more important than speed+ ///+ /// # Examples+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::math::Vector;+ /// use parry3d::transformation::vhacd::{VHACD, VHACDParameters};+ ///+ /// # let vertices = vec![+ /// # Vector::new(0.0, 0.0, 0.0), Vector::new(1.0, 0.0, 0.0),+ /// # Vector::new(0.5, 1.0, 0.0), Vector::new(0.5, 0.5, 1.0),+ /// # ];+ /// # let indices = vec![[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]];+ /// #+ /// let decomposition = VHACD::decompose(+ /// &VHACDParameters::default(),+ /// &vertices,+ /// &indices,+ /// false, // voxel-to-primitive mapping not needed+ /// );+ ///+ /// // Compute voxel-based convex hulls with moderate downsampling+ /// let hulls = decomposition.compute_convex_hulls(4);+ ///+ /// for (i, (verts, tris)) in hulls.iter().enumerate() {+ /// println!("Hull {}: {} vertices, {} triangles", i, verts.len(), tris.len());+ /// }+ /// # }+ /// ```+ ///+ /// ## Creating a Compound Shape for Collision Detection+ ///+ /// ```no_run+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::math::Vector;+ /// use parry3d::shape::{SharedShape, Compound};+ /// use parry3d::transformation::vhacd::{VHACD, VHACDParameters};+ /// use parry3d::math::Pose;+ ///+ /// # let vertices = vec![+ /// # Vector::new(0.0, 0.0, 0.0), Vector::new(1.0, 0.0, 0.0),+ /// # Vector::new(0.5, 1.0, 0.0), Vector::new(0.5, 0.5, 1.0),+ /// # ];+ /// # let indices = vec![[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]];+ /// #+ /// let decomposition = VHACD::decompose(+ /// &VHACDParameters::default(),+ /// &vertices,+ /// &indices,+ /// false,+ /// );+ ///+ /// let hulls = decomposition.compute_convex_hulls(4);+ /// # }+ /// ```+ ///+ /// # See Also+ ///+ /// - [`compute_exact_convex_hulls`](VHACD::compute_exact_convex_hulls): More accurate mesh-based hulls+ /// - [`voxel_parts`](VHACD::voxel_parts): Access the raw voxel data+ /// - [`SharedShape::convex_decomposition`](crate::shape::SharedShape::convex_decomposition): High-level API+ #[cfg(feature = "dim3")]+ pub fn compute_convex_hulls(&self, downsampling: u32) -> Vec<(Vec<Vector>, Vec<[u32; DIM]>)> {+ let downsampling = downsampling.max(1);+ self.voxel_parts+ .iter()+ .map(|part| part.compute_convex_hull(downsampling))+ .collect()+ }+}++fn compute_concavity(volume: Real, volume_ch: Real, volume0: Real) -> Real {+ (volume_ch - volume).abs() / volume0+}++fn clip_mesh(+ points: &[Vector],+ plane: &CutPlane,+ positive_part: &mut Vec<Vector>,+ negative_part: &mut Vec<Vector>,+) {+ for pt in points {+ let d = plane.abc.dot(*pt) + plane.d;++ if d > 0.0 {+ positive_part.push(*pt);+ } else if d < 0.0 {+ negative_part.push(*pt);+ } else {+ positive_part.push(*pt);+ negative_part.push(*pt);+ }+ }+}++#[cfg(feature = "dim2")]+fn convex_hull(vertices: &[Vector]) -> Vec<Vector> {+ if vertices.len() > 1 {+ crate::transformation::convex_hull(vertices)+ } else {+ Vec::new()+ }+}++#[cfg(feature = "dim3")]+fn convex_hull(vertices: &[Vector]) -> (Vec<Vector>, Vec<[u32; DIM]>) {+ if vertices.len() > 2 {+ crate::transformation::convex_hull(vertices)+ } else {+ (Vec::new(), Vec::new())+ }+}++#[cfg(feature = "dim2")]+fn compute_volume(polygon: &[Vector]) -> Real {+ if !polygon.is_empty() {+ crate::mass_properties::details::convex_polygon_area_and_center_of_mass(polygon).0+ } else {+ 0.0+ }+}++#[cfg(feature = "dim3")]+fn compute_volume(mesh: &(Vec<Vector>, Vec<[u32; DIM]>)) -> Real {+ if !mesh.0.is_empty() {+ crate::mass_properties::details::trimesh_signed_volume_and_center_of_mass(&mesh.0, &mesh.1)+ .0+ } else {+ 0.0+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/volume_mesh/cover_octree.rs b/renderer/third_party/parry3d/src/transformation/volume_mesh/cover_octree.rsnew file mode 100644index 0000000..20f6258--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/volume_mesh/cover_octree.rs@@ -0,0 +1,422 @@+//! The cover's subdivided background grid: an octree refined below the cell size where octants+//! cross the shape's boundary, turned into a conforming grid of cells (no hanging vertex) by the+//! balance rule and the transition cells.++use super::isosurface_stuffing::{par_map, BackgroundGrid, MeshOracle};+use super::VolumeMeshParameters;+use crate::bounding_volume::Aabb;+#[cfg(not(feature = "std"))]+use crate::math::ComplexField;+use crate::math::{Real, Vector};+use crate::utils::hashmap::HashMap;+use alloc::vec::Vec;++/// The eight corners of an octant, as offsets in units of its width.+const CORNERS: [[i32; 3]; 8] = [+ [0, 0, 0],+ [1, 0, 0],+ [0, 1, 0],+ [1, 1, 0],+ [0, 0, 1],+ [1, 0, 1],+ [0, 1, 1],+ [1, 1, 1],+];++/// The octants the boundary passes through, refined down to the finest level, and the coarser ones+/// filling the rest.+///+/// Octant coordinates are indices at their own level; vertex coordinates are integers in units of+/// half the finest octant's width, which makes every corner, center, face center and edge midpoint+/// of every level integral.+struct Octree {+ origin: Vector,+ /// Half the width of a finest octant, the unit of the vertex coordinates.+ half: Real,+ /// The level of the coarsest octants: they are `1 << levels` finest octants wide.+ levels: u32,+ /// The number of coarsest octants along each axis.+ dims: [i32; 3],+ /// The octants that have children.+ subdivided: HashMap<(u32, [i32; 3]), ()>,+}++impl Octree {+ /// The width of an octant, in vertex coordinates: a finest octant is two of them wide.+ fn width(&self, level: u32) -> i32 {+ 2 << level+ }++ /// The number of octants of a level along each axis.+ fn count(&self, level: u32) -> [i32; 3] {+ core::array::from_fn(|k| self.dims[k] << (self.levels - level))+ }++ fn in_range(&self, level: u32, c: [i32; 3]) -> bool {+ let count = self.count(level);+ (0..3).all(|k| c[k] >= 0 && c[k] < count[k])+ }++ fn is_subdivided(&self, level: u32, c: [i32; 3]) -> bool {+ self.subdivided.contains_key(&(level, c))+ }++ /// A corner of an octant, in vertex coordinates.+ fn corner(&self, level: u32, c: [i32; 3], offset: [i32; 3]) -> [i32; 3] {+ let width = self.width(level);+ core::array::from_fn(|k| (c[k] + offset[k]) * width)+ }++ /// The center of an octant, in vertex coordinates.+ fn center(&self, level: u32, c: [i32; 3]) -> [i32; 3] {+ let width = self.width(level);+ core::array::from_fn(|k| c[k] * width + width / 2)+ }++ fn point(&self, v: [i32; 3]) -> Vector {+ self.origin + Vector::new(v[0] as Real, v[1] as Real, v[2] as Real) * self.half+ }++ /// The leaf covering a given octant: itself when it is one, an ancestor when it sits inside a+ /// coarser leaf, `None` when it is subdivided (several leaves cover it) or out of range.+ fn covering_leaf(&self, level: u32, c: [i32; 3]) -> Option<(u32, [i32; 3])> {+ if !self.in_range(level, c) {+ return None;+ }++ let mut current = self.levels;+ loop {+ let shifted: [i32; 3] = core::array::from_fn(|k| c[k] >> (current - level));+ if !self.is_subdivided(current, shifted) {+ return Some((current, shifted));+ }+ if current == level {+ return None;+ }+ current -= 1;+ }+ }++ /// Gives an octant children, so that its own children become leaves.+ fn split(&mut self, level: u32, c: [i32; 3]) {+ debug_assert!(level > 0, "a finest octant has no children");+ let _ = self.subdivided.insert((level, c), ());+ }++ /// Every leaf of the octree.+ fn leaves(&self) -> Vec<(u32, [i32; 3])> {+ let mut leaves = Vec::new();+ let mut stack: Vec<(u32, [i32; 3])> = Vec::new();+ let roots = self.count(self.levels);++ for k in 0..roots[2] {+ for j in 0..roots[1] {+ for i in 0..roots[0] {+ stack.push((self.levels, [i, j, k]));+ }+ }+ }++ while let Some((level, c)) = stack.pop() {+ if level > 0 && self.is_subdivided(level, c) {+ for offset in CORNERS {+ stack.push((level - 1, core::array::from_fn(|k| c[k] * 2 + offset[k])));+ }+ } else {+ leaves.push((level, c));+ }+ }++ leaves+ }++ /// Whether an octant finer than `level` puts a vertex at the given coordinates.+ fn has_finer_vertex(&self, level: u32, v: [i32; 3]) -> bool {+ if level == 0 {+ return false;+ }++ let finer = level - 1;+ let width = self.width(finer);+ if (0..3).any(|k| v[k].rem_euclid(width) != 0) {+ return false;+ }++ let base: [i32; 3] = core::array::from_fn(|k| v[k] / width);+ CORNERS.iter().any(|offset| {+ let c: [i32; 3] = core::array::from_fn(|k| base[k] - offset[k]);+ matches!(self.covering_leaf(finer, c), Some((leaf, _)) if leaf <= finer)+ })+ }+}++/// The center of a face of an octant, in vertex coordinates.+fn face_center(octree: &Octree, level: u32, c: [i32; 3], axis: usize, positive: bool) -> [i32; 3] {+ let corners = face_corners(axis, positive).map(|offset| octree.corner(level, c, offset));+ core::array::from_fn(|k| (corners[0][k] + corners[2][k]) / 2)+}++/// The four corners of a face of an octant, walking around it, as offsets in units of its width.+fn face_corners(axis: usize, positive: bool) -> [[i32; 3]; 4] {+ let (u, v) = ((axis + 1) % 3, (axis + 2) % 3);+ let base = i32::from(positive);+ [[0, 0], [1, 0], [1, 1], [0, 1]].map(|[du, dv]| {+ let mut corner = [0; 3];+ corner[axis] = base;+ corner[u] = du;+ corner[v] = dv;+ corner+ })+}++/// The background grid of a cover ([`MeshEnclosure::Cover`](super::MeshEnclosure::Cover)): an+/// octant that may cross the shape's boundary is refined+/// [`VolumeMeshParameters::cover_subdivisions`] halvings below the cell size and one that cannot+/// is not; balancing and transition cells keep the grid conforming.+pub(super) fn cover_octree_grid(+ oracle: &MeshOracle,+ aabb: Aabb,+ params: &VolumeMeshParameters,+) -> Option<BackgroundGrid> {+ let cell_size = params.cell_size;+ let fine = cell_size / (1 << params.cover_subdivisions) as Real;+ let levels = params.cover_subdivisions;++ // The domain, in cell-sized octants, with margin so the boundary never reaches its+ // border.+ let coarse_width = cell_size;+ let margin = cell_size * 2.0;+ let origin = aabb.mins - Vector::splat(margin);+ let dims: [i32; 3] = core::array::from_fn(|k| {+ let extent = aabb.maxs[k] - aabb.mins[k] + margin * 2.0;+ ((extent / coarse_width).ceil() as i32).max(1)+ });++ let mut octree = Octree {+ origin,+ half: fine * 0.5,+ levels,+ dims,+ subdivided: HashMap::default(),+ };++ let roots = octree.count(levels);+ let mut frontier: Vec<[i32; 3]> = Vec::new();+ for k in 0..roots[2] {+ for j in 0..roots[1] {+ for i in 0..roots[0] {+ frontier.push([i, j, k]);+ }+ }+ }++ // Level-synchronous refinement: every octant of a level tests independently whether the+ // boundary reaches into it (an exact, early-exit BVH existence query), the splits are applied+ // in one pass, and the children become the next level's frontier.+ for level in (1..=levels).rev() {+ let decisions: Vec<bool> = par_map(&frontier, |c| {+ let octant = Aabb::new(+ octree.point(octree.corner(level, *c, [0, 0, 0])),+ octree.point(octree.corner(level, *c, [1, 1, 1])),+ );+ oracle.crosses_region(&octant)+ });++ let mut next = Vec::new();+ for (c, split) in frontier.iter().zip(&decisions) {+ if *split {+ octree.split(level, *c);+ for offset in CORNERS {+ next.push(core::array::from_fn(|k| c[k] * 2 + offset[k]));+ }+ }+ }+ frontier = next;+ if frontier.is_empty() {+ break;+ }+ }++ balance(&mut octree);+ Some(background_grid(&octree))+}++/// The Weak Balance Condition: two octants sharing so much as an edge may not differ by more than+/// one level, or there is no bridging them.+fn balance(octree: &mut Octree) {+ loop {+ let leaves = octree.leaves();++ // Each round decides every leaf against the same snapshot of the octree, in+ // parallel; balancing is monotone (splitting only ever demands more splits), so+ // the rounds converge on the same closure the one-by-one sweep would.+ let decisions: Vec<bool> = par_map(&leaves, |&(level, c)| {+ if level == 0 {+ return false;+ }++ // Every finest octant one step outside this leaf must be covered by a leaf no more+ // than one level coarser than it. Only the shell around the leaf is walked: the+ // octants inside it are its own.+ let span = 1 << level;+ let mut split = false;++ 'shell: for axis in 0..3 {+ for side in [-1, span] {+ for a in -1..=span {+ for b in -1..=span {+ let mut offset = [0; 3];+ offset[axis] = side;+ offset[(axis + 1) % 3] = a;+ offset[(axis + 2) % 3] = b;+ let neighbor: [i32; 3] =+ core::array::from_fn(|k| c[k] * span + offset[k]);++ let Some((neighbor_level, _)) = octree.covering_leaf(0, neighbor)+ else {+ continue;+ };+ // A neighbor two or more levels finer: this leaf is the one that has+ // to give, or nothing can bridge them.+ if neighbor_level + 1 < level {+ split = true;+ break 'shell;+ }+ }+ }+ }+ }++ split+ });++ let mut changed = false;+ for (&(level, c), split) in leaves.iter().zip(&decisions) {+ if *split {+ octree.split(level, c);+ changed = true;+ }+ }++ if !changed {+ break;+ }+ }+}++/// The background grid of a balanced octree: figure 10 of the paper.+///+/// A cell spanning two octants would be created from both of them; the same-size case, the only+/// symmetric one, is built from the positive side alone.+fn background_grid(octree: &Octree) -> BackgroundGrid {+ // Every leaf emits its cells independently, as vertex coordinates: the octree is only+ // read, so the leaves are one parallel pass, and the coordinates are deduplicated into+ // ids afterward.+ let leaves = octree.leaves();+ let per_leaf: Vec<Vec<[[i32; 3]; 4]>> =+ par_map(&leaves, |&(level, c)| leaf_cells(octree, level, c));+ let coord_cells: Vec<[[i32; 3]; 4]> = per_leaf.into_iter().flatten().collect();++ let mut coords: Vec<[i32; 3]> = coord_cells.iter().flatten().copied().collect();+ #[cfg(feature = "parallel")]+ {+ use rayon::prelude::*;+ coords.par_sort_unstable();+ }+ #[cfg(not(feature = "parallel"))]+ coords.sort_unstable();+ coords.dedup();++ let mut ids: HashMap<[i32; 3], u32> = HashMap::default();+ for (id, v) in coords.iter().enumerate() {+ let _ = ids.insert(*v, id as u32);+ }++ let points = par_map(&coords, |v| octree.point(*v));+ let cells = par_map(&coord_cells, |quad| quad.map(|v| ids[&v]));++ BackgroundGrid { points, cells }+}++/// The cells of one leaf, as vertex coordinates: figure 10 of Labelle and Shewchuk.+///+/// A cell spanning two octants would be created from both of them; the same-size case, the+/// only symmetric one, is built from the positive side alone.+fn leaf_cells(octree: &Octree, level: u32, c: [i32; 3]) -> Vec<[[i32; 3]; 4]> {+ let mut cells = Vec::new();+ let center = octree.center(level, c);++ for axis in 0..3 {+ for positive in [false, true] {+ let face: [[i32; 3]; 4] =+ face_corners(axis, positive).map(|offset| octree.corner(level, c, offset));++ let mut neighbor = c;+ neighbor[axis] += if positive { 1 } else { -1 };++ if octree.in_range(level, neighbor) && octree.is_subdivided(level, neighbor) {+ // Finer octants across the face put a vertex at its center: quadrisected cells.+ let middle: [i32; 3] = core::array::from_fn(|k| (face[0][k] + face[2][k]) / 2);++ for e in 0..4 {+ let (a, b) = (face[e], face[(e + 1) % 4]);+ let midpoint: [i32; 3] = core::array::from_fn(|k| (a[k] + b[k]) / 2);++ if octree.has_finer_vertex(level, midpoint) {+ cells.push([middle, center, a, midpoint]);+ cells.push([middle, center, midpoint, b]);+ } else {+ cells.push([middle, center, a, b]);+ }+ }+ continue;+ }++ match octree.covering_leaf(level, neighbor) {+ Some((neighbor_level, neighbor_c)) if neighbor_level == level => {+ // The same size: the lattice cells, built once per shared face.+ if !positive {+ continue;+ }+ let opposite = octree.center(neighbor_level, neighbor_c);++ for e in 0..4 {+ let (a, b) = (face[e], face[(e + 1) % 4]);+ let midpoint: [i32; 3] = core::array::from_fn(|k| (a[k] + b[k]) / 2);++ if octree.has_finer_vertex(level, midpoint) {+ // A finer octant split this edge: two bisected cells, which the+ // boundary never crosses.+ cells.push([center, opposite, a, midpoint]);+ cells.push([center, opposite, midpoint, b]);+ } else {+ cells.push([center, opposite, a, b]);+ }+ }+ }+ // A coarser neighbor, or the domain's border: two half-pyramids over the face,+ // whose diagonal runs through the coarse face's center so that its two triangles+ // are among the eight the coarse side fans out from that center.+ other => {+ let diagonal = other+ .and_then(|(neighbor_level, neighbor_c)| {+ let middle =+ face_center(octree, neighbor_level, neighbor_c, axis, !positive);+ face.iter().position(|v| *v == middle)+ })+ .unwrap_or(0);+ let (a, b, cc, d) = (+ face[diagonal],+ face[(diagonal + 1) % 4],+ face[(diagonal + 2) % 4],+ face[(diagonal + 3) % 4],+ );+ cells.push([center, a, b, cc]);+ cells.push([center, a, cc, d]);+ }+ }+ }+ }++ cells+}diff --git a/renderer/third_party/parry3d/src/transformation/volume_mesh/cover_smoothing.rs b/renderer/third_party/parry3d/src/transformation/volume_mesh/cover_smoothing.rsnew file mode 100644index 0000000..6a6fb07--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/volume_mesh/cover_smoothing.rs@@ -0,0 +1,354 @@+//! Shrink-wrap of a [`super::MeshEnclosure::Cover`] mesh: flattens its staircase while keeping its+//! containment guarantee, a boundary vertex moving only if its cells keep a volume floor and its+//! boundary faces still do not cross the shape. Vertices relax color by color in a fixed order.++use super::isosurface_stuffing::{par_map, MeshOracle};+use super::{VolumeMesh, VolumeMeshParameters};+use crate::bounding_volume::{Aabb, BoundingVolume};+use crate::math::{Real, Vector};+use alloc::vec::Vec;++/// How much of its lattice volume a cell must keep for a move to commit.+const VOLUME_FLOOR: Real = 0.2;++/// How far a boundary vertex may travel from where the lattice put it, in local cell+/// sizes. The wrap's targets all lie within a cell, so this hardly ever binds; what it+/// buys is a bound that makes each vertex's neighborhood of the shape collectable once.+const TRAVEL_BUDGET: Real = 1.0;++/// The half-extent of the region a vertex's shape primitives are collected in, in local+/// cell sizes: the incident faces' own extent, plus every incident vertex's travel budget,+/// with margin.+const REGION: Real = 2.5;++/// The committed step, as a fraction of the guard, under which a vertex goes to sleep.+const SLEEP: Real = 0.05;++/// The four faces of a tetrahedron, as index triples into the cell.+const FACES: [[usize; 3]; 4] = [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]];++fn cell_volume(positions: &[Vector], cell: [u32; 4]) -> Real {+ let [a, b, c, d] = cell.map(|i| positions[i as usize]);+ (b - a).cross(c - a).dot(d - a) / 6.0+}++/// The cell's volume, with vertex `v` read at `at` instead of its stored position.+fn cell_volume_at(positions: &[Vector], cell: [u32; 4], v: u32, at: Vector) -> Real {+ let p = cell.map(|i| if i == v { at } else { positions[i as usize] });+ (p[1] - p[0]).cross(p[2] - p[0]).dot(p[3] - p[0]) / 6.0+}++/// The face's points, with vertex `v` read at `at` instead of its stored position.+fn face_at(positions: &[Vector], face: [u32; 3], v: u32, at: Vector) -> [Vector; 3] {+ face.map(|i| if i == v { at } else { positions[i as usize] })+}++pub(super) fn smooth_cover(+ mesh: &mut VolumeMesh,+ oracle: &MeshOracle,+ params: &VolumeMeshParameters,+) {+ if params.cover_smoothing == 0 || params.cover_guard <= 0.0 || mesh.cells.is_empty() {+ return;+ }++ /*+ * The cover's boundary: the faces one cell shares with no other (found by sorting the+ * face keys, which is parallel-friendly and gives a deterministic order), their+ * vertices, and the adjacency the relaxation reads.+ */+ let mut keys: Vec<[u32; 3]> = Vec::with_capacity(mesh.cells.len() * 4);+ for cell in &mesh.cells {+ for face in FACES {+ let mut key = face.map(|k| cell[k]);+ key.sort_unstable();+ keys.push(key);+ }+ }+ #[cfg(feature = "parallel")]+ {+ use rayon::prelude::*;+ keys.par_sort_unstable();+ }+ #[cfg(not(feature = "parallel"))]+ keys.sort_unstable();++ let mut boundary_faces: Vec<[u32; 3]> = Vec::new();+ let mut at = 0;+ while at < keys.len() {+ let mut next = at + 1;+ while next < keys.len() && keys[next] == keys[at] {+ next += 1;+ }+ if next - at == 1 {+ boundary_faces.push(keys[at]);+ }+ at = next;+ }++ let n = mesh.vertices.len();+ let mut is_boundary = alloc::vec![false; n];+ let mut vertex_faces: Vec<Vec<u32>> = alloc::vec![Vec::new(); n];+ let mut neighbors: Vec<Vec<u32>> = alloc::vec![Vec::new(); n];++ for (id, face) in boundary_faces.iter().enumerate() {+ for k in 0..3 {+ let v = face[k] as usize;+ is_boundary[v] = true;+ vertex_faces[v].push(id as u32);+ for other in [face[(k + 1) % 3], face[(k + 2) % 3]] {+ if !neighbors[v].contains(&other) {+ neighbors[v].push(other);+ }+ }+ }+ }++ let mut vertex_cells: Vec<Vec<u32>> = alloc::vec![Vec::new(); n];+ for (id, cell) in mesh.cells.iter().enumerate() {+ for v in cell {+ vertex_cells[*v as usize].push(id as u32);+ }+ }++ /*+ * What the pristine lattice grants each cell and vertex: the volume floor, and the+ * guard and step cap scaled by the local cell size.+ */+ let floors: Vec<Real> = mesh+ .cells+ .iter()+ .map(|cell| cell_volume(&mesh.vertices, *cell) * VOLUME_FLOOR)+ .collect();+ let scales: Vec<Real> = (0..n)+ .map(|v| {+ if !is_boundary[v] {+ return 0.0;+ }+ vertex_cells[v]+ .iter()+ .flat_map(|c| {+ let pts = mesh.cells[*c as usize].map(|i| mesh.vertices[i as usize]);+ (0..4).flat_map(move |i| (i + 1..4).map(move |j| (pts[i] - pts[j]).length()))+ })+ .fold(0.0, Real::max)+ })+ .collect();+ let guards: Vec<Real> = scales.iter().map(|s| params.cover_guard * s).collect();++ let boundary_vertices: Vec<u32> = (0..n as u32).filter(|v| is_boundary[*v as usize]).collect();++ /*+ * Each vertex's and face's neighborhood of the shape, collected once: the shape is static and+ * vertex travel is bounded, so the per-move barrier and projection scan these short lists+ * instead of the whole shape.+ */+ let origins: Vec<Vector> = mesh.vertices.clone();+ let neighborhoods: Vec<Vec<u32>> = par_map(&boundary_vertices, |&v| {+ let vid = v as usize;+ let region = Aabb::from_half_extents(origins[vid], Vector::splat(scales[vid] * REGION));+ let mut primitives = Vec::new();+ oracle.collect(®ion, &mut primitives);+ primitives+ });+ let neighborhood_of = {+ let mut ids = alloc::vec![u32::MAX; n];+ for (k, v) in boundary_vertices.iter().enumerate() {+ ids[*v as usize] = k as u32;+ }+ ids+ };+ let face_lists: Vec<Vec<u32>> = par_map(&boundary_faces, |face| {+ let sweep = face+ .iter()+ .map(|v| scales[*v as usize])+ .fold(0.0, Real::max)+ * (TRAVEL_BUDGET * 1.1);+ let region = Aabb::from_points(face.iter().map(|v| origins[*v as usize])).loosened(sweep);+ let mut primitives = Vec::new();+ oracle.collect(®ion, &mut primitives);+ primitives+ });++ /*+ * Greedy coloring of boundary vertices, no two of a color sharing a cell: a vertex's target+ * and validity read only its incident cells and faces, so each color is one parallel batch.+ */+ let mut colors = alloc::vec![u32::MAX; n];+ let mut palette: Vec<Vec<u32>> = Vec::new();+ for &v in &boundary_vertices {+ let mut used = alloc::vec![false; palette.len()];+ for &c in &vertex_cells[v as usize] {+ for o in mesh.cells[c as usize] {+ let color = colors[o as usize];+ if color != u32::MAX {+ used[color as usize] = true;+ }+ }+ }+ let color = used.iter().position(|u| !*u).unwrap_or(palette.len());+ if color == palette.len() {+ palette.push(Vec::new());+ }+ colors[v as usize] = color as u32;+ palette[color].push(v);+ }++ /*+ * The wrap: color by color, each vertex validates its move against the batch's starting state+ * and proposals apply in order; the step is capped at the guard and tested at its midpoint, so+ * no sweep exceeds half a guard between exact tests; idle vertices wake on a neighbor's move.+ */+ let mut active = is_boundary.clone();++ for _ in 0..params.cover_smoothing {+ let mut moved_any = false;++ for group in &palette {+ let members: Vec<u32> = group+ .iter()+ .copied()+ .filter(|v| active[*v as usize])+ .collect();+ if members.is_empty() {+ continue;+ }++ let positions = &mesh.vertices;+ let proposals: Vec<(Vector, Real)> = par_map(&members, |&v| {+ let vid = v as usize;+ let pos = positions[vid];+ let guard = guards[vid];+ let primitives = &neighborhoods[neighborhood_of[vid] as usize];+ if neighbors[vid].is_empty() || primitives.is_empty() {+ return (pos, 0.0);+ }++ let average = neighbors[vid]+ .iter()+ .map(|o| positions[*o as usize])+ .sum::<Vector>()+ / neighbors[vid].len() as Real;+ let projection = oracle.project_among(pos, primitives).unwrap_or(pos);+ let Some(outward) = (pos - projection).try_normalize() else {+ return (pos, 0.0);+ };+ let held_off = projection + outward * guard;+ let target = (average + held_off) * 0.5;++ // The mid-step barrier test keeps the effective sweep at half of this, so+ // a full-guard cap converges twice as fast at the same tunneling+ // granularity.+ let mut step = target - pos;+ if step.length() > guard {+ step = step.normalize() * guard;+ }+ // The travel budget: what makes the collected neighborhoods complete.+ let budget = scales[vid] * TRAVEL_BUDGET;+ let strayed = pos + step - origins[vid];+ if strayed.length() > budget {+ step = origins[vid] + strayed.normalize() * budget - pos;+ }+ // A step already below the sleep threshold has nothing to buy: skip the+ // barrier work it would cost.+ if step.length() < guard * SLEEP {+ return (pos, 0.0);+ }++ let valid = |to: Vector| -> bool {+ for &c in &vertex_cells[vid] {+ if cell_volume_at(positions, mesh.cells[c as usize], v, to)+ < floors[c as usize]+ {+ return false;+ }+ }+ let middle = (pos + to) * 0.5;+ for &f in &vertex_faces[vid] {+ let face = boundary_faces[f as usize];+ let barrier = &face_lists[f as usize];+ if oracle.crosses_among(&face_at(positions, face, v, to), barrier)+ || oracle.crosses_among(&face_at(positions, face, v, middle), barrier)+ {+ return false;+ }+ }+ true+ };++ for factor in [1.0, 0.5, 0.25] {+ let candidate = pos + step * factor;+ if valid(candidate) {+ return (candidate, step.length() * factor);+ }+ }+ (pos, 0.0)+ });++ for (v, (to, committed)) in members.iter().zip(&proposals) {+ let vid = *v as usize;+ mesh.vertices[vid] = *to;+ if *committed < guards[vid] * SLEEP {+ active[vid] = false;+ } else {+ moved_any = true;+ for o in &neighbors[vid] {+ active[*o as usize] = true;+ }+ }+ }+ }++ if !moved_any {+ break;+ }+ }++ /*+ * A light interior relaxation: the ring of interior vertices next to the wrapped boundary+ * absorbed the squeeze, so they are eased toward their neighbors' average; the volume floor+ * still guards the cage's region against these moves.+ */+ let ring: Vec<u32> = (0..n as u32)+ .filter(|v| {+ !is_boundary[*v as usize]+ && vertex_cells[*v as usize].iter().any(|c| {+ mesh.cells[*c as usize]+ .iter()+ .any(|o| is_boundary[*o as usize])+ })+ })+ .collect();++ for _ in 0..2 {+ for &v in &ring {+ let vid = v as usize;+ let mut sum = Vector::ZERO;+ let mut count = 0;+ for &c in &vertex_cells[vid] {+ for o in mesh.cells[c as usize] {+ if o != v {+ sum += mesh.vertices[o as usize];+ count += 1;+ }+ }+ }+ if count == 0 {+ continue;+ }++ let pos = mesh.vertices[vid];+ let step = sum / count as Real - pos;+ for factor in [0.5, 0.25] {+ let candidate = pos + step * factor;+ mesh.vertices[vid] = candidate;+ if vertex_cells[vid].iter().all(|c| {+ cell_volume(&mesh.vertices, mesh.cells[*c as usize]) >= floors[*c as usize]+ }) {+ break;+ }+ mesh.vertices[vid] = pos;+ }+ }+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/volume_mesh/delaunay_refinement.rs b/renderer/third_party/parry3d/src/transformation/volume_mesh/delaunay_refinement.rsnew file mode 100644index 0000000..a1bf6d8--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/volume_mesh/delaunay_refinement.rs@@ -0,0 +1,131 @@+//! Triangulation of the interior of a closed polyline, by Delaunay refinement (Ruppert's and+//! Chew's algorithms, as implemented by `spade`).++use super::{VolumeMesh, VolumeMeshParameters};+use crate::math::{Real, Vector};+use crate::utils::hashmap::{Entry, HashMap};+use crate::utils::sanitize_spade_point;+use alloc::vec::Vec;+use spade::{+ AngleLimit, ConstrainedDelaunayTriangulation, Point2, RefinementParameters, Triangulation as _,+};++pub fn triangulate(+ vertices: &[Vector],+ indices: &[[u32; 2]],+ params: &VolumeMeshParameters,+) -> Option<VolumeMesh> {+ let cell_size = params.cell_size;++ if vertices.is_empty() || indices.is_empty() || cell_size <= 0.0 || cell_size.is_nan() {+ return None;+ }++ /*+ * The boundary, as constraint edges: only the vertices it references take part in the+ * triangulation.+ */+ let mut cdt: ConstrainedDelaunayTriangulation<Point2<Real>> =+ ConstrainedDelaunayTriangulation::new();+ let mut handles = HashMap::default();++ for edge in indices {+ let mut endpoints = [None; 2];++ for (k, vid) in edge.iter().enumerate() {+ let pt = *vertices.get(*vid as usize)?;+ let handle = match handles.entry(*vid) {+ Entry::Occupied(entry) => *entry.get(),+ Entry::Vacant(entry) => {+ let pt = sanitize_spade_point(Point2::new(pt.x, pt.y));+ *entry.insert(cdt.insert(pt).ok()?)+ }+ };+ endpoints[k] = Some(handle);+ }++ if let [Some(from), Some(to)] = endpoints {+ if from != to {+ // Intersecting constraint edges are left out instead of panicking; the boundary+ // shouldn't self-intersect in the first place.+ let _ = cdt.try_add_constraint(from, to);+ }+ }+ }++ /*+ * Refinement: split the triangles that are too large or too sharp, and the boundary edges that+ * stand in the way, until every triangle inside the boundary is fit for simulation.+ */+ #[cfg_attr(feature = "f64", expect(clippy::unnecessary_cast))]+ let angle_limit = AngleLimit::from_rad(params.min_angle as f64);+ // The area of the equilateral triangle of side `cell_size`.+ let max_area = cell_size * cell_size * Real::sqrt(0.75) / 2.0;+ // The refinement gives up after a fixed number of added points, which defaults to ten times+ // the boundary's: far too few for a small `cell_size`, and a mesh that stops mid-refinement is+ // worse than a coarse one. Budget for a few times the elements the area target asks for.+ let enclosed_area = indices+ .iter()+ .map(|e| vertices[e[0] as usize].perp_dot(vertices[e[1] as usize]) / 2.0)+ .sum::<Real>()+ .abs();+ let budget = (enclosed_area / max_area * 4.0) as usize + 1000;+ let refinement = cdt.refine(+ RefinementParameters::new()+ .with_angle_limit(angle_limit)+ .with_max_allowed_area(max_area)+ .with_max_additional_vertices(budget)+ .exclude_outer_faces(true),+ );++ if !refinement.refinement_complete {+ log::warn!(+ "volume_mesh: the refinement ran out of vertices after {budget}; some elements are \+ badly shaped. Try a larger cell size or a smaller minimum angle."+ );+ }++ let outer: HashMap<_, ()> = refinement+ .excluded_faces+ .into_iter()+ .map(|face| (face.index(), ()))+ .collect();+ let mut vertices = alloc::vec![Vector::ZERO; cdt.num_vertices()];++ for vertex in cdt.vertices() {+ let pt = vertex.position();+ vertices[vertex.fix().index()] = Vector::new(pt.x, pt.y);+ }++ let mut cells = Vec::new();++ for face in cdt.inner_faces() {+ if outer.contains_key(&face.fix().index()) {+ continue;+ }++ let cell = face.vertices().map(|v| v.fix().index() as u32);+ let [a, b, c] = cell.map(|v| vertices[v as usize]);++ // Positively oriented, and no degenerate cell.+ let area = (b - a).perp_dot(c - a) / 2.0;+ if area.abs() < max_area * 1.0e-6 {+ continue;+ }++ cells.push(if area > 0.0 {+ cell+ } else {+ [cell[0], cell[2], cell[1]]+ });+ }++ if cells.is_empty() {+ return None;+ }++ let mut result = VolumeMesh { vertices, cells };+ result.compact();++ Some(result)+}diff --git a/renderer/third_party/parry3d/src/transformation/volume_mesh/isosurface_stuffing.rs b/renderer/third_party/parry3d/src/transformation/volume_mesh/isosurface_stuffing.rsnew file mode 100644index 0000000..90f5b58--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/volume_mesh/isosurface_stuffing.rs@@ -0,0 +1,531 @@+//! Covering a shape with the cells of a body-centered cubic lattice (the lattice of Labelle and+//! Shewchuk's isosurface stuffing, SIGGRAPH 2007, kept whole instead of cut). Every cell the shape+//! reaches is kept by exact intersection tests, so the mesh always contains what it covers.++use super::{MeshEnclosure, VolumeMesh, VolumeMeshParameters};+use crate::bounding_volume::{Aabb, BoundingVolume};+#[cfg(not(feature = "std"))]+use crate::math::ComplexField;+use crate::math::{Pose, Real, Vector};+use crate::query::PointQueryWithLocation;+use crate::shape::{SupportMap, TriMesh, TriMeshFlags};+use crate::utils::hashmap::HashMap;+use alloc::vec::Vec;++/// An order-preserving map over a slice, in parallel when the `parallel` feature is on.+///+/// Everything the cover pipeline hands this is a pure per-item computation, and rayon's+/// collect keeps item order, so the parallel and sequential paths produce identical+/// results, bit for bit.+#[cfg(feature = "parallel")]+pub(super) fn par_map<T: Sync, R: Send, F: Fn(&T) -> R + Sync + Send>(items: &[T], f: F) -> Vec<R> {+ use rayon::prelude::*;+ items.par_iter().map(f).collect()+}++/// The sequential twin of the parallel [`par_map`].+#[cfg(not(feature = "parallel"))]+pub(super) fn par_map<T, R, F: Fn(&T) -> R>(items: &[T], f: F) -> Vec<R> {+ items.iter().map(f).collect()+}++/// A convex point set as a support map, which is all GJK asks of a shape: the tetrahedra+/// and convex hulls the enclosure tests intersect never need more structure than this.+pub(super) struct PointsSupportMap<'a>(pub &'a [Vector]);++impl SupportMap for PointsSupportMap<'_> {+ fn local_support_point(&self, dir: Vector) -> Vector {+ let mut best = self.0[0];+ for pt in &self.0[1..] {+ if pt.dot(dir) > best.dot(dir) {+ best = *pt;+ }+ }+ best+ }+}++/// Whether the hull of a point set (a tetrahedron, a cage triangle) and a convex+/// support-mapped shape intersect (GJK).+pub(super) fn convex_points_intersect(points: &[Vector], other: &impl SupportMap) -> bool {+ crate::query::details::intersection_test_support_map_support_map(+ &Pose::IDENTITY,+ &PointsSupportMap(points),+ other,+ )+}++/// The oracle of [`tetrahedralize`]: the boundary mesh's own pseudo-normal signed distance+/// and exact intersection tests, which is everything the lattice reads of the shape.+pub(super) struct MeshOracle<'a> {+ mesh: &'a TriMesh,+}++impl<'a> MeshOracle<'a> {+ pub fn new(mesh: &'a TriMesh) -> Self {+ Self { mesh }+ }+}++impl MeshOracle<'_> {+ /// The signed distance to the boundary: positive inside.+ pub fn signed_distance(&self, pt: Vector) -> Real {+ signed_distance(self.mesh, pt)+ }++ /// Whether the shape's surface reaches into the box: exact (the BVH prunes to candidate+ /// triangles, GJK decides each, the first hit exits), which is what the cover's octree needs+ /// to decide a subdivision.+ pub fn crosses_region(&self, region: &Aabb) -> bool {+ let corners = [+ region.mins,+ Vector::new(region.maxs.x, region.mins.y, region.mins.z),+ Vector::new(region.mins.x, region.maxs.y, region.mins.z),+ Vector::new(region.maxs.x, region.maxs.y, region.mins.z),+ Vector::new(region.mins.x, region.mins.y, region.maxs.z),+ Vector::new(region.maxs.x, region.mins.y, region.maxs.z),+ Vector::new(region.mins.x, region.maxs.y, region.maxs.z),+ region.maxs,+ ];+ let crossed = self+ .mesh+ .bvh()+ .intersect_aabb(region)+ .any(|tri| convex_points_intersect(&corners, &self.mesh.triangle(tri)));+ crossed+ }++ /// Whether the shape's surface passes through the tetrahedron ([`MeshEnclosure::Crust`]):+ /// a buried tetrahedron is not reached and no orientation is read, so the crust stays+ /// hollow and an open mesh can be crusted.+ pub fn surface_intersects(&self, tet: &[Vector; 4]) -> bool {+ let aabb = Aabb::from_points(tet.iter().copied());+ // Only the triangles the tetrahedron's Aabb can see are worth testing.+ let crossed = self+ .mesh+ .bvh()+ .intersect_aabb(&aabb)+ .any(|tri| convex_points_intersect(tet, &self.mesh.triangle(tri)));+ crossed+ }++ /// The triangles reaching into a region, collected once per boundary vertex or face for the+ /// smoothing's `_among` queries, so the per-move tests scan a few local triangles instead of+ /// re-walking the BVH.+ pub fn collect(&self, region: &Aabb, out: &mut Vec<u32>) {+ out.extend(self.mesh.bvh().intersect_aabb(region));+ }++ /// Whether the shape forbids a cage triangle passing there, tested against the listed+ /// triangles only: containment breaks exactly when the cage's boundary crosses the+ /// shape, so this is the smoothing's barrier.+ pub fn crosses_among(&self, triangle: &[Vector; 3], primitives: &[u32]) -> bool {+ // The Aabb reject is what keeps the listed neighborhood cheap: GJK only runs on+ // the one or two triangles overlapping the cage face's box.+ let aabb = Aabb::from_points(triangle.iter().copied());+ primitives.iter().any(|tri| {+ let candidate = self.mesh.triangle(*tri);+ let lows = candidate.a.min(candidate.b).min(candidate.c);+ let highs = candidate.a.max(candidate.b).max(candidate.c);+ lows.cmple(aabb.maxs).all()+ && highs.cmpge(aabb.mins).all()+ && convex_points_intersect(triangle, &candidate)+ })+ }++ /// The point of the shape's boundary closest to `pt` among the listed triangles, or+ /// `None` if the list is empty.+ pub fn project_among(&self, pt: Vector, primitives: &[u32]) -> Option<Vector> {+ use crate::query::PointQuery;++ // A triangle whose box is already farther than the best projection cannot beat it.+ let mut best = None;+ let mut best_dist = Real::MAX;+ for tri in primitives {+ let candidate = self.mesh.triangle(*tri);+ let lows = candidate.a.min(candidate.b).min(candidate.c);+ let highs = candidate.a.max(candidate.b).max(candidate.c);+ if (pt.clamp(lows, highs) - pt).length() >= best_dist {+ continue;+ }+ let projection = candidate.project_local_point(pt, true).point;+ let dist = (projection - pt).length();+ if dist < best_dist {+ best = Some(projection);+ best_dist = dist;+ }+ }+ best+ }+}++/// The body-centered cubic lattice covering an Aabb: the cube corners first, then the cube centers.+///+/// Coordinates are doubled so that both sublattices are integral: the lattice point with+/// coordinates `c` sits at `origin + c * cell_size / 2`, corners having only even coordinates and+/// centers only odd ones.+struct Lattice {+ origin: Vector,+ half_cell: Real,+ dims: [i32; 3],+ /// Number of even (resp. odd) coordinates along each axis.+ num_even: [i32; 3],+ num_odd: [i32; 3],+ /// Number of cube corners, i.e. the index of the first cube center.+ corners_len: usize,+}++impl Lattice {+ fn covering(aabb: Aabb, cell_size: Real) -> Self {+ let half_cell = cell_size * 0.5;+ // One cell of margin all around, so that every edge crossing the boundary has both of its+ // endpoints sampled.+ let origin = aabb.mins - Vector::splat(cell_size);+ let dims = core::array::from_fn(|i| {+ let extent = aabb.maxs[i] - aabb.mins[i] + cell_size * 2.0;+ ((extent / half_cell).ceil() as i32).max(2)+ });+ let num_even = core::array::from_fn(|i: usize| dims[i] / 2 + 1);+ let num_odd = core::array::from_fn(|i: usize| (dims[i] + 1) / 2);+ let corners_len = (num_even[0] * num_even[1] * num_even[2]) as usize;++ Self {+ origin,+ half_cell,+ dims,+ num_even,+ num_odd,+ corners_len,+ }+ }++ fn len(&self) -> usize {+ self.corners_len + (self.num_odd[0] * self.num_odd[1] * self.num_odd[2]) as usize+ }++ /// The index of the lattice point with the given doubled coordinates, if it is one and it is+ /// in range.+ fn index(&self, c: [i32; 3]) -> Option<u32> {+ if (0..3).any(|i| c[i] < 0 || c[i] > self.dims[i]) {+ return None;+ }++ let parity = c[0].rem_euclid(2);+ if c[1].rem_euclid(2) != parity || c[2].rem_euclid(2) != parity {+ return None;+ }++ let (base, counts) = if parity == 0 {+ (0, self.num_even)+ } else {+ (self.corners_len as i32, self.num_odd)+ };+ let [i, j, k] = [c[0] / 2, c[1] / 2, c[2] / 2];+ Some((base + i + (j + k * counts[1]) * counts[0]) as u32)+ }++ fn point(&self, c: [i32; 3]) -> Vector {+ self.origin + Vector::new(c[0] as Real, c[1] as Real, c[2] as Real) * self.half_cell+ }++ /// The doubled coordinates of every lattice point, in index order.+ fn coords(&self) -> Vec<[i32; 3]> {+ let mut coords = Vec::with_capacity(self.len());+ for (parity, counts) in [(0, self.num_even), (1, self.num_odd)] {+ for k in 0..counts[2] {+ for j in 0..counts[1] {+ for i in 0..counts[0] {+ coords.push([i * 2 + parity, j * 2 + parity, k * 2 + parity]);+ }+ }+ }+ }+ coords+ }+}++/// The lattice tetrahedra, each of them stored so that its two long edges are `[0, 1]` and+/// `[2, 3]`.+///+/// The lattice decomposes into octahedra: two neighboring cube centers plus the four corners of the+/// cube face between them. Splitting each octahedron along its two centers gives four tetrahedra,+/// one per edge of that face.+fn lattice_tetrahedra(lattice: &Lattice, coords: &[[i32; 3]]) -> Vec<[u32; 4]> {+ let mut tets = Vec::new();++ for (center, &c) in coords.iter().enumerate().skip(lattice.corners_len) {+ let center = center as u32;++ for axis in 0..3 {+ let mut step = [0; 3];+ step[axis] = 2;+ let Some(opposite) = lattice.index(core::array::from_fn(|i| c[i] + step[i])) else {+ continue;+ };++ // The corners of the cube face between the two centers, in cyclic order.+ let (u, v) = ((axis + 1) % 3, (axis + 2) % 3);+ let mut corners = [0; 4];+ let mut complete = true;++ for (k, [su, sv]) in [[1, 1], [-1, 1], [-1, -1], [1, -1]].into_iter().enumerate() {+ let mut corner = c;+ corner[axis] += 1;+ corner[u] += su;+ corner[v] += sv;++ match lattice.index(corner) {+ Some(corner) => corners[k] = corner,+ None => {+ complete = false;+ break;+ }+ }+ }++ if !complete {+ continue;+ }++ for k in 0..4 {+ tets.push([center, opposite, corners[k], corners[(k + 1) % 4]]);+ }+ }+ }++ tets+}++/// Whether every edge of the mesh is shared by exactly two triangles.+fn is_closed(indices: &[[u32; 3]]) -> bool {+ let mut edges: HashMap<[u32; 2], u32> = HashMap::default();++ for tri in indices {+ for k in 0..3 {+ *edges.entry(edge_key(tri[k], tri[(k + 1) % 3])).or_insert(0) += 1;+ }+ }++ edges.values().all(|count| *count == 2)+}++/// The signed distance to the boundary mesh: positive inside.+fn signed_distance(mesh: &TriMesh, pt: Vector) -> Real {+ // The projection has to keep its location for the inside test to use the pseudo-normals.+ let (proj, _) = mesh.project_local_point_and_get_location(pt, false);+ let dist = (pt - proj.point).length();+ if proj.is_inside {+ dist+ } else {+ -dist+ }+}++fn edge_key(a: u32, b: u32) -> [u32; 2] {+ if a < b {+ [a, b]+ } else {+ [b, a]+ }+}++/// The tetrahedron flipped positive, or nothing if it is degenerate.+fn orient_tet(pts: &[Vector], mut tet: [u32; 4], min_volume: Real) -> Option<[u32; 4]> {+ let [a, b, c, d] = tet.map(|i| pts[i as usize]);+ let volume = (b - a).cross(c - a).dot(d - a) / 6.0;++ if volume.abs() < min_volume {+ return None;+ }++ if volume < 0.0 {+ tet.swap(0, 1);+ }++ Some(tet)+}++/// A grid of cells filling the domain: the uniform lattice, or the cover's subdivided+/// octree grid.+pub(super) struct BackgroundGrid {+ pub points: Vec<Vector>,+ pub cells: Vec<[u32; 4]>,+}++/// The domain the grid has to cover: the shape's Aabb, grown by the whole cells the cover+/// keeps around the shape.+pub(super) fn domain(aabb: Aabb, cell_size: Real) -> Aabb {+ aabb.loosened(cell_size)+}++/// The body-centered cubic lattice covering an Aabb, as a background grid.+pub(super) fn uniform_grid(aabb: Aabb, cell_size: Real) -> BackgroundGrid {+ let lattice = Lattice::covering(aabb, cell_size);+ let coords = lattice.coords();+ let points = coords.iter().map(|&c| lattice.point(c)).collect();+ let cells = lattice_tetrahedra(&lattice, &coords);++ BackgroundGrid { points, cells }+}++/// Which non-crossing cells are inside the shape, by connectivity: cells untouched by the surface+/// that share a vertex lie on the same side of it, so their vertex-connected components are inside+/// or outside as a whole and one signed-distance probe per component classifies every cell in it.+fn flood_fill_inside(+ oracle: &MeshOracle,+ points: &[Vector],+ grid_cells: &[[u32; 4]],+ crossing: &[bool],+) -> Vec<bool> {+ // Union-find over the non-crossing cells, joined through shared vertices.+ let mut parent: Vec<u32> = (0..grid_cells.len() as u32).collect();+ fn root(parent: &mut [u32], mut i: u32) -> u32 {+ while parent[i as usize] != i {+ parent[i as usize] = parent[parent[i as usize] as usize];+ i = parent[i as usize];+ }+ i+ }++ let mut last_at_vertex = alloc::vec![u32::MAX; points.len()];+ for (id, cell) in grid_cells.iter().enumerate() {+ if crossing[id] {+ continue;+ }+ for v in cell {+ let previous = last_at_vertex[*v as usize];+ last_at_vertex[*v as usize] = id as u32;+ if previous != u32::MAX {+ let (a, b) = (root(&mut parent, previous), root(&mut parent, id as u32));+ parent[a as usize] = b;+ }+ }+ }++ // One probe per component, at the centroid of its representative cell.+ let mut inside_root: HashMap<u32, bool> = HashMap::default();+ let mut inside = alloc::vec![false; grid_cells.len()];+ for id in 0..grid_cells.len() {+ if crossing[id] {+ continue;+ }+ let component = root(&mut parent, id as u32);+ let is_inside = *inside_root.entry(component).or_insert_with(|| {+ let centroid = grid_cells[component as usize]+ .iter()+ .map(|v| points[*v as usize])+ .sum::<Vector>()+ / 4.0;+ oracle.signed_distance(centroid) > 0.0+ });+ inside[id] = is_inside;+ }++ inside+}++/// Keeps every whole cell of the background grid the shape reaches, cutting and warping+/// nothing: the mesh contains the shape by construction ([`MeshEnclosure::Cover`]).+///+/// A cell is kept when a vertex of it is inside the (dilated) shape, or when the exact+/// intersection test says the shape passes through it; the latter is what catches a feature+/// that slips between the sampled vertices, which the sampled field alone would lose.+fn cover_grid(+ grid: BackgroundGrid,+ oracle: &MeshOracle,+ params: &VolumeMeshParameters,+ min_volume: Real,+) -> Option<VolumeMesh> {+ let BackgroundGrid {+ points,+ cells: grid_cells,+ } = grid;++ // The cells the surface exactly passes through: the BVH prunes to the band along the+ // boundary, so the convex tests are only ever paid there.+ let crossing: Vec<bool> = par_map(&grid_cells, |tet| {+ let pts = tet.map(|v| points[v as usize]);+ oracle.surface_intersects(&pts)+ });++ // What else is kept: nothing for the crust (hollow by design); for the cover, the+ // cells inside the shape, classified by connectivity with one signed-distance probe+ // per component.+ let keep: Vec<bool> = if params.enclosure == MeshEnclosure::Crust {+ crossing+ } else {+ let inside = flood_fill_inside(oracle, &points, &grid_cells, &crossing);+ crossing+ .iter()+ .zip(&inside)+ .map(|(crossing, inside)| *crossing || *inside)+ .collect()+ };++ let ids: Vec<u32> = (0..grid_cells.len() as u32).collect();+ let kept = par_map(&ids, |id| {+ if keep[*id as usize] {+ orient_tet(&points, grid_cells[*id as usize], min_volume)+ } else {+ None+ }+ });+ let cells: Vec<[u32; 4]> = kept.into_iter().flatten().collect();++ if cells.is_empty() {+ return None;+ }++ let mut result = VolumeMesh {+ vertices: points,+ cells,+ };+ result.compact();++ Some(result)+}++pub fn tetrahedralize(+ vertices: &[Vector],+ indices: &[[u32; 3]],+ params: &VolumeMeshParameters,+) -> Option<VolumeMesh> {+ let cell_size = params.cell_size;++ if vertices.is_empty() || indices.is_empty() || cell_size <= 0.0 || cell_size.is_nan() {+ return None;+ }++ // The cut function is the signed distance to the boundary, so the boundary must be closed and+ // consistently oriented (duplicated vertices are welded first); the crust only keeps the cells+ // the surface passes through and never reads the sign, so it accepts an open mesh.+ let crust = params.enclosure == MeshEnclosure::Crust;+ let flags = if crust {+ TriMeshFlags::MERGE_DUPLICATE_VERTICES+ } else {+ TriMeshFlags::ORIENTED | TriMeshFlags::MERGE_DUPLICATE_VERTICES+ };+ let mesh = TriMesh::with_flags(vertices.to_vec(), indices.to_vec(), flags)+ .ok()+ .filter(|mesh| crust || (mesh.pseudo_normals().is_some() && is_closed(mesh.indices())))?;++ let oracle = MeshOracle::new(&mesh);+ let grid = if params.cover_subdivisions > 0 {+ super::cover_octree::cover_octree_grid(+ &oracle,+ domain(mesh.local_aabb(), cell_size),+ params,+ )?+ } else {+ uniform_grid(domain(mesh.local_aabb(), cell_size), cell_size)+ };++ let mut result = cover_grid(+ grid,+ &oracle,+ params,+ cell_size * cell_size * cell_size * 1.0e-6,+ )?;+ super::cover_smoothing::smooth_cover(&mut result, &oracle, params);+ Some(result)+}diff --git a/renderer/third_party/parry3d/src/transformation/volume_mesh/mod.rs b/renderer/third_party/parry3d/src/transformation/volume_mesh/mod.rsnew file mode 100644index 0000000..61ad7cc--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/volume_mesh/mod.rs@@ -0,0 +1,175 @@+//! Filling a closed boundary with a simulation-grade simplex mesh.++use crate::math::{Real, Vector, DIM};+use alloc::vec::Vec;++#[cfg(feature = "dim3")]+mod cover_octree;+#[cfg(feature = "dim3")]+mod cover_smoothing;+#[cfg(feature = "dim2")]+mod delaunay_refinement;+#[cfg(feature = "dim3")]+mod isosurface_stuffing;++/// A simplicial mesh filling the interior of a closed boundary: triangles in 2D, tetrahedra in 3D.+#[derive(Clone, Debug, Default)]+#[cfg_attr(+ feature = "serde-serialize",+ derive(serde::Serialize, serde::Deserialize)+)]+pub struct VolumeMesh {+ /// The mesh vertices.+ pub vertices: Vec<Vector>,+ /// The mesh cells, positively oriented (positive signed area/volume).+ pub cells: Vec<[u32; DIM + 1]>,+}++/// Which cover the mesh is (3D only): of the shape's volume, or of its surface alone.+///+/// Either way the mesh is made of whole lattice cells the shape reaches, so it *contains*+/// what it covers, which is what an embedding wants: every point of the shape (a skin+/// vertex, say) interpolates inside a cell instead of extrapolating outside all of them.+#[cfg(feature = "dim3")]+#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]+pub enum MeshEnclosure {+ /// Every lattice cell the shape reaches is kept whole: a solid fill containing the shape by+ /// construction, blocky at the cell size (see [`VolumeMeshParameters::cover_smoothing`] and+ /// [`VolumeMeshParameters::cover_subdivisions`]). Needs a closed, consistently oriented mesh.+ #[default]+ Cover,+ /// The cover of the shape's surface alone: only the cells the surface crosses are kept,+ /// the interior stays empty, and the mesh need not be closed or oriented. The result is a+ /// hollow shell that deforms like a shell, not like a solid.+ Crust,+}++/// Parameters of [`volume_mesh`].+#[derive(Copy, Clone, Debug, PartialEq)]+pub struct VolumeMeshParameters {+ /// Target size of the generated elements.+ pub cell_size: Real,+ /// Smallest angle, in radians, the refinement aims for (2D only).+ ///+ /// Above 30 degrees the refinement is not guaranteed to terminate, so it may stop early and+ /// leave some elements badly shaped.+ #[cfg(feature = "dim2")]+ pub min_angle: Real,+ /// Whether the whole shape is covered or its surface alone (3D only); see+ /// [`MeshEnclosure`].+ #[cfg(feature = "dim3")]+ pub enclosure: MeshEnclosure,+ /// How many shrink-wrap iterations smooth the staircase of a [`MeshEnclosure::Cover`] mesh,+ /// zero leaving it raw (3D only, cover only). Each iteration pulls the boundary toward+ /// the shape, held off by [`Self::cover_guard`], and commits a move only if containment holds.+ #[cfg(feature = "dim3")]+ pub cover_smoothing: u32,+ /// How close to the shape the smoothed cover may pull its boundary, as a fraction of+ /// the local cell size (3D only, read by the cover's smoothing only).+ #[cfg(feature = "dim3")]+ pub cover_guard: Real,+ /// How many halvings below [`Self::cell_size`] a [`MeshEnclosure::Cover`] cell crossing the+ /// shape's boundary may be refined, zero keeping the boundary at the cell size (3D only, cover+ /// only). The refinement is on the octree (no hanging vertex) and runs before the smoothing.+ #[cfg(feature = "dim3")]+ pub cover_subdivisions: u32,+}++impl VolumeMeshParameters {+ /// Parameters generating elements of size `cell_size`: in 3D a raw cover (no+ /// smoothing, no subdivision), in 2D a refinement aiming for 30 degree angles.+ pub fn new(cell_size: Real) -> Self {+ Self {+ cell_size,+ #[cfg(feature = "dim2")]+ #[cfg_attr(feature = "f64", expect(clippy::unnecessary_cast))]+ min_angle: core::f64::consts::PI as Real / 6.0,+ #[cfg(feature = "dim3")]+ enclosure: MeshEnclosure::Cover,+ #[cfg(feature = "dim3")]+ cover_smoothing: 0,+ #[cfg(feature = "dim3")]+ cover_guard: 0.15,+ #[cfg(feature = "dim3")]+ cover_subdivisions: 0,+ }+ }+}++/// Fills a boundary `(vertices, indices)` (2D polyline, 3D triangle mesh) with a simplex mesh+/// for finite-element simulation: 2D refines a constrained Delaunay triangulation of the boundary,+/// 3D builds a lattice cover containing it. Returns `None` if the boundary encloses nothing.+pub fn volume_mesh(+ vertices: &[Vector],+ indices: &[[u32; DIM]],+ params: &VolumeMeshParameters,+) -> Option<VolumeMesh> {+ #[cfg(feature = "dim2")]+ {+ delaunay_refinement::triangulate(vertices, indices, params)+ }+ #[cfg(feature = "dim3")]+ {+ isosurface_stuffing::tetrahedralize(vertices, indices, params)+ }+}++impl VolumeMesh {+ /// The connected component of each cell: two cells sharing a vertex are in the same one.+ ///+ /// Components are numbered from zero, so the number of them is the largest index plus one.+ /// A mesh in more than one piece means the input's own surface is in several pieces: the+ /// cover keeps every cell the surface reaches, however thin the feature.+ pub fn connected_components(&self) -> Vec<u32> {+ let mut parent: Vec<u32> = (0..self.vertices.len() as u32).collect();++ fn root(parent: &mut [u32], mut i: u32) -> u32 {+ while parent[i as usize] != i {+ parent[i as usize] = parent[parent[i as usize] as usize];+ i = parent[i as usize];+ }+ i+ }++ for cell in &self.cells {+ for vid in &cell[1..] {+ let (a, b) = (root(&mut parent, cell[0]), root(&mut parent, *vid));+ parent[a as usize] = b;+ }+ }++ let mut ids = alloc::vec![u32::MAX; self.vertices.len()];+ let mut count = 0;++ self.cells+ .iter()+ .map(|cell| {+ let id = &mut ids[root(&mut parent, cell[0]) as usize];+ if *id == u32::MAX {+ *id = count;+ count += 1;+ }+ *id+ })+ .collect()+ }++ /// Removes the vertices no cell references, and reindexes the cells accordingly.+ pub fn compact(&mut self) {+ let mut remap = alloc::vec![u32::MAX; self.vertices.len()];+ let mut vertices = Vec::with_capacity(self.vertices.len());++ for cell in &mut self.cells {+ for vid in cell {+ let remapped = &mut remap[*vid as usize];+ if *remapped == u32::MAX {+ *remapped = vertices.len() as u32;+ vertices.push(self.vertices[*vid as usize]);+ }+ *vid = *remapped;+ }+ }++ self.vertices = vertices;+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/voxelization/mod.rs b/renderer/third_party/parry3d/src/transformation/voxelization/mod.rsnew file mode 100644index 0000000..460e62f--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/voxelization/mod.rs@@ -0,0 +1,255 @@+//! Voxelization of 2D and 3D shapes.+//!+//! # What is Voxelization?+//!+//! Voxelization is the process of converting a continuous geometric shape (like a triangle mesh in 3D+//! or a polyline in 2D) into a discrete grid of cubic cells called **voxels**. Think of voxels as+//! 3D pixels - just like pixels make up 2D images, voxels make up 3D volumes. In 2D, voxels are+//! actually square cells (sometimes called "pixels" in other contexts).+//!+//! This is similar to how a photograph discretizes a continuous scene into pixels, except voxelization+//! works in 3D space (or 2D for 2D shapes).+//!+//! # When Should You Use Voxelization?+//!+//! Voxelization is useful when you need to:+//!+//! - **Approximate complex shapes** with a simpler grid-based representation+//! - **Compute volume** of complex meshes (by counting filled voxels)+//! - **Perform spatial queries** efficiently using a regular grid structure+//! - **Generate collision proxies** for physics simulations (using the V-HACD algorithm)+//! - **Simplify mesh operations** like boolean operations or distance field computation+//! - **Analyze shape properties** like connectivity, cavities, or internal structure+//!+//! # Key Concepts+//!+//! ## Voxel Grid+//!+//! A voxel grid divides space into a regular array of cubic (or square in 2D) cells. Each cell is+//! identified by integer coordinates `(i, j)` in 2D or `(i, j, k)` in 3D. The physical size of each+//! voxel is controlled by the `scale` parameter.+//!+//! ## Resolution vs Voxel Size+//!+//! You can control the granularity of voxelization in two ways:+//!+//! - **By resolution**: Specify how many subdivisions to make along the longest axis. The voxel size+//! is automatically computed to maintain cubic voxels.+//! - **By voxel size**: Directly specify the physical size of each voxel. The resolution is+//! automatically computed based on the shape's bounding box.+//!+//! Higher resolution (or smaller voxel size) gives more accurate approximation but uses more memory.+//!+//! ## Fill Modes+//!+//! The [`FillMode`](crate::transformation::voxelization::FillMode) enum controls which voxels are considered "filled":+//!+//! - **`SurfaceOnly`**: Only voxels that intersect the surface boundary are marked as filled.+//! This gives you a hollow shell representation.+//!+//! - **`FloodFill`**: Fills voxels on the surface AND all voxels inside the volume. This uses a+//! flood-fill algorithm starting from outside the shape. Options include:+//! - `detect_cavities`: Properly handles internal holes/cavities+//! - `detect_self_intersections` (2D only): Attempts to handle self-intersecting boundaries+//!+//! # Main Types+//!+//! - [`VoxelSet`](crate::transformation::voxelization::VoxelSet): A sparse set containing only filled voxels (memory-efficient output format)+//! - [`VoxelizedVolume`](crate::transformation::voxelization::VoxelizedVolume): A dense 3D grid of all voxels (intermediate format used during voxelization)+//! - [`Voxel`](crate::transformation::voxelization::Voxel): A single voxel with its grid coordinates and metadata+//! - [`FillMode`](crate::transformation::voxelization::FillMode): Configuration for how to determine filled vs empty voxels+//! - [`VoxelValue`](crate::transformation::voxelization::VoxelValue): The state of a voxel (inside, outside, or on surface)+//!+//! # Examples+//!+//! ## Basic 3D Voxelization (Surface Only)+//!+//! ```+//! # #[cfg(all(feature = "dim3", feature = "f32"))]+//! # {+//! use parry3d::transformation::voxelization::{FillMode, VoxelSet};+//! use parry3d::shape::Cuboid;+//! use parry3d::math::Vector;+//!+//! // Create a simple cuboid and convert it to a triangle mesh+//! let cuboid = Cuboid::new(Vector::new(1.0, 0.5, 0.3));+//! let (vertices, indices) = cuboid.to_trimesh();+//!+//! // Voxelize with resolution of 10 voxels along the longest axis+//! let voxels = VoxelSet::voxelize(+//! &vertices,+//! &indices,+//! 10, // resolution+//! FillMode::SurfaceOnly, // only surface voxels+//! false, // don't track voxel-to-triangle mapping+//! );+//!+//! println!("Created {} surface voxels", voxels.len());+//! println!("Each voxel has volume: {}", voxels.voxel_volume());+//!+//! // Access individual voxels+//! for voxel in voxels.voxels() {+//! println!("Voxel at grid position: {:?}", voxel);+//! println!(" World position: {:?}", voxels.get_voxel_point(voxel));+//! println!(" On surface: {}", voxel.is_on_surface);+//! }+//! # }+//! ```+//!+//! ## 3D Voxelization with Interior Fill+//!+//! ```+//! # #[cfg(all(feature = "dim3", feature = "f32"))]+//! # {+//! use parry3d::transformation::voxelization::{FillMode, VoxelSet};+//! use parry3d::shape::Ball;+//! use parry3d::math::Vector;+//!+//! // Create a sphere mesh+//! let ball = Ball::new(1.0);+//! let (vertices, indices) = ball.to_trimesh(20, 20); // subdivisions for sphere+//!+//! // Voxelize with flood-fill to get solid interior+//! let voxels = VoxelSet::voxelize(+//! &vertices,+//! &indices,+//! 15, // resolution+//! FillMode::FloodFill {+//! detect_cavities: false, // simple solid shape, no cavities+//! },+//! false,+//! );+//!+//! // Compute the approximate volume+//! let volume = voxels.compute_volume();+//! let expected_volume = 4.0 / 3.0 * std::f32::consts::PI * 1.0_f32.powi(3);+//! println!("Voxel volume: {}, Expected: {}", volume, expected_volume);+//!+//! // Count surface vs interior voxels+//! let surface_count = voxels.voxels().iter().filter(|v| v.is_on_surface).count();+//! let interior_count = voxels.voxels().iter().filter(|v| !v.is_on_surface).count();+//! println!("Surface voxels: {}, Interior voxels: {}", surface_count, interior_count);+//! # }+//! ```+//!+//! ## 2D Voxelization of a Polygon+//!+//! ```+//! # #[cfg(all(feature = "dim2", feature = "f32"))]+//! # {+//! use parry2d::transformation::voxelization::{FillMode, VoxelSet};+//! use parry2d::math::Vector;+//!+//! // Define a simple square as a polyline (boundary)+//! let vertices = vec![+//! Vector::ZERO,+//! Vector::new(2.0, 0.0),+//! Vector::new(2.0, 2.0),+//! Vector::new(0.0, 2.0),+//! ];+//!+//! // Create index buffer for the polyline segments (closed loop)+//! let indices = vec![+//! [0, 1], // bottom edge+//! [1, 2], // right edge+//! [2, 3], // top edge+//! [3, 0], // left edge+//! ];+//!+//! // Voxelize with specific voxel size+//! let voxels = VoxelSet::with_voxel_size(+//! &vertices,+//! &indices,+//! 0.2, // voxel size+//! FillMode::FloodFill {+//! detect_cavities: false,+//! detect_self_intersections: false,+//! },+//! false,+//! );+//!+//! println!("2D voxel area: {}", voxels.compute_volume());+//! # }+//! ```+//!+//! ## Computing Convex Hull from Voxels+//!+//! ```+//! # #[cfg(all(feature = "dim3", feature = "f32"))]+//! # {+//! use parry3d::transformation::voxelization::{FillMode, VoxelSet};+//! use parry3d::shape::Cuboid;+//! use parry3d::math::Vector;+//!+//! let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+//! let (vertices, indices) = cuboid.to_trimesh();+//!+//! let voxels = VoxelSet::voxelize(+//! &vertices,+//! &indices,+//! 8,+//! FillMode::SurfaceOnly,+//! false,+//! );+//!+//! // Compute convex hull from the voxel centers+//! // sampling=1 means use every voxel, higher values skip voxels for performance+//! let (hull_vertices, hull_indices) = voxels.compute_convex_hull(1);+//!+//! println!("Convex hull has {} vertices and {} triangles",+//! hull_vertices.len(), hull_indices.len());+//! # }+//! ```+//!+//! ## Tracking Which Triangles Intersect Each Voxel+//!+//! ```+//! # #[cfg(all(feature = "dim3", feature = "f32"))]+//! # {+//! use parry3d::transformation::voxelization::{FillMode, VoxelSet};+//! use parry3d::shape::Cuboid;+//! use parry3d::math::Vector;+//!+//! let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+//! let (vertices, indices) = cuboid.to_trimesh();+//!+//! // Enable voxel-to-primitives mapping+//! let voxels = VoxelSet::voxelize(+//! &vertices,+//! &indices,+//! 10,+//! FillMode::SurfaceOnly,+//! true, // keep_voxel_to_primitives_map = true+//! );+//!+//! // Now we can compute exact intersections between voxels and triangles+//! let intersection_points = voxels.compute_primitive_intersections(&vertices, &indices);+//! println!("Generated {} intersection points", intersection_points.len());+//!+//! // Or compute a more accurate convex hull using the triangle intersections+//! let (hull_verts, hull_indices) = voxels.compute_exact_convex_hull(&vertices, &indices);+//! println!("Exact convex hull: {} vertices", hull_verts.len());+//! # }+//! ```+//!+//! # Performance Considerations+//!+//! - **Resolution**: Doubling the resolution increases memory usage by 4× in 2D or 8× in 3D+//! - **VoxelSet vs VoxelizedVolume**: `VoxelSet` is sparse (only stores filled voxels), while+//! `VoxelizedVolume` is dense (stores all grid cells). For sparse shapes, `VoxelSet` is much+//! more memory-efficient.+//! - **Voxel-to-primitives map**: Setting `keep_voxel_to_primitives_map = true` adds memory overhead+//! but enables more precise operations like `compute_exact_convex_hull()`+//! - **Flood-fill**: Using `FloodFill` mode is more expensive than `SurfaceOnly` but gives you+//! solid volumes instead of hollow shells+//!+//! # Use in Convex Decomposition+//!+//! The voxelization system is used internally by Parry's V-HACD implementation for approximate+//! convex decomposition. See the [`vhacd`](crate::transformation::vhacd) module for details.++pub use self::voxel_set::{Voxel, VoxelSet};+pub use self::voxelized_volume::{FillMode, VoxelValue, VoxelizedVolume};++mod voxel_set;+mod voxelized_volume;diff --git a/renderer/third_party/parry3d/src/transformation/voxelization/voxel_set.rs b/renderer/third_party/parry3d/src/transformation/voxelization/voxel_set.rsnew file mode 100644index 0000000..97ba057--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/voxelization/voxel_set.rs@@ -0,0 +1,1131 @@+// Rust port, with modifications, of https://github.com/kmammou/v-hacd/blob/master/src/VHACD_Lib/src/vhacdVolume.cpp+// By Khaled Mamou+//+// # License of the original C++ code:+// > Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)+// > All rights reserved.+// >+// >+// > Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:+// >+// > 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.+// >+// > 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.+// >+// > 3. The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission.+// >+// > THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++use super::{FillMode, VoxelizedVolume};+use crate::bounding_volume::Aabb;+use crate::math::{ivect_to_vect, MatExt, VectorExt};+use crate::math::{IVector, Matrix, Real, Vector, DIM};+use crate::transformation::vhacd::CutPlane;+use alloc::sync::Arc;+use alloc::{vec, vec::Vec};++#[cfg(feature = "dim2")]+type ConvexHull = Vec<Vector>;+#[cfg(feature = "dim3")]+type ConvexHull = (Vec<Vector>, Vec<[u32; DIM]>);++/// A single voxel in a voxel grid.+///+/// A voxel represents a cubic (or square in 2D) cell in a discrete grid. Each voxel is identified+/// by its integer grid coordinates and contains metadata about its position relative to the+/// voxelized shape.+///+/// # Fields+///+/// - `coords`: The grid position `(i, j)` in 2D or `(i, j, k)` in 3D. These are **integer**+/// coordinates in the voxel grid, not world-space coordinates.+///+/// - `is_on_surface`: Whether this voxel intersects the surface boundary of the shape. If `false`,+/// the voxel is completely inside the shape (only possible when using [`FillMode::FloodFill`]).+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::voxelization::{FillMode, VoxelSet};+/// use parry3d::shape::Ball;+/// ///+/// let ball = Ball::new(1.0);+/// let (vertices, indices) = ball.to_trimesh(10, 10);+///+/// let voxels = VoxelSet::voxelize(+/// &vertices,+/// &indices,+/// 8,+/// FillMode::FloodFill { detect_cavities: false },+/// false,+/// );+///+/// // Examine individual voxels+/// for voxel in voxels.voxels() {+/// // Grid coordinates (integer position in the voxel grid)+/// println!("Grid position: {:?}", voxel);+///+/// // World-space position (actual 3D coordinates)+/// let world_pos = voxels.get_voxel_point(voxel);+/// println!("World position: {:?}", world_pos);+///+/// // Surface vs interior+/// if voxel.is_on_surface {+/// println!("This voxel is on the surface boundary");+/// } else {+/// println!("This voxel is inside the shape");+/// }+/// }+/// # }+/// ```+#[derive(Copy, Clone, Debug)]+pub struct Voxel {+ /// The integer coordinates of the voxel as part of the voxel grid.+ pub coords: IVector,+ /// Is this voxel on the surface of the volume (i.e. not inside of it)?+ pub is_on_surface: bool,+ /// Range of indices (to be looked up into the `VoxelSet` primitive map)+ /// of the primitives intersected by this voxel.+ pub(crate) intersections_range: (usize, usize),+}++impl Default for Voxel {+ fn default() -> Self {+ Self {+ coords: IVector::ZERO,+ is_on_surface: false,+ intersections_range: (0, 0),+ }+ }+}++/// A sparse set of filled voxels resulting from voxelization.+///+/// `VoxelSet` is a memory-efficient storage format that only contains voxels marked as "filled"+/// during the voxelization process. This is much more efficient than storing a dense 3D array+/// for shapes that are mostly empty or have a hollow interior.+///+/// # Structure+///+/// Each `VoxelSet` contains:+/// - A list of filled voxels with their grid coordinates+/// - The origin point and scale factor for converting grid coordinates to world space+/// - Optional metadata tracking which primitives (triangles/segments) intersect each voxel+///+/// # Grid Coordinates vs World Coordinates+///+/// Voxels are stored with integer grid coordinates `(i, j, k)`. To convert to world-space+/// coordinates, use:+///+/// ```text+/// world_position = origin + (i, j, k) * scale+/// ```+///+/// The [`get_voxel_point()`](VoxelSet::get_voxel_point) method does this conversion for you.+///+/// # Memory Layout+///+/// Unlike [`VoxelizedVolume`] which stores a dense 3D array, `VoxelSet` uses sparse storage:+/// - Only filled voxels are stored (typically much fewer than total grid cells)+/// - Memory usage is `O(filled_voxels)` instead of `O(resolution^3)`+/// - Ideal for shapes with low surface-to-volume ratio+///+/// # Example: Basic Usage+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::voxelization::{FillMode, VoxelSet};+/// use parry3d::shape::Cuboid;+/// use parry3d::math::Vector;+///+/// // Create and voxelize a shape+/// let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+/// let (vertices, indices) = cuboid.to_trimesh();+///+/// let voxels = VoxelSet::voxelize(+/// &vertices,+/// &indices,+/// 10, // resolution+/// FillMode::SurfaceOnly, // hollow surface only+/// false, // no primitive mapping+/// );+///+/// // Query the voxel set+/// println!("Number of voxels: {}", voxels.len());+/// println!("Voxel size: {}", voxels.scale);+/// println!("Total volume: {}", voxels.compute_volume());+///+/// // Access voxels+/// for voxel in voxels.voxels() {+/// let world_pos = voxels.get_voxel_point(voxel);+/// println!("Voxel at {:?}", world_pos);+/// }+/// # }+/// ```+///+/// # Example: Volume Computation+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::voxelization::{FillMode, VoxelSet};+/// use parry3d::shape::Ball;+/// ///+/// let ball = Ball::new(1.0);+/// let (vertices, indices) = ball.to_trimesh(20, 20);+///+/// // Voxelize with interior filling+/// let voxels = VoxelSet::voxelize(+/// &vertices,+/// &indices,+/// 20,+/// FillMode::FloodFill { detect_cavities: false },+/// false,+/// );+///+/// // Compute approximate volume+/// let voxel_volume = voxels.compute_volume();+/// let expected_volume = 4.0 / 3.0 * std::f32::consts::PI;+/// println!("Voxel volume: {:.3}, Expected: {:.3}", voxel_volume, expected_volume);+/// # }+/// ```+pub struct VoxelSet {+ /// The 3D origin of this voxel-set.+ pub origin: Vector,+ /// The scale factor between the voxel integer coordinates and their+ /// actual float world-space coordinates.+ pub scale: Real,+ pub(crate) min_bb_voxels: IVector,+ pub(crate) max_bb_voxels: IVector,+ pub(crate) voxels: Vec<Voxel>,+ pub(crate) intersections: Arc<Vec<u32>>,+ pub(crate) primitive_classes: Arc<Vec<u32>>,+}++impl Default for VoxelSet {+ fn default() -> Self {+ Self::new()+ }+}++impl VoxelSet {+ /// Creates a new empty set of voxels.+ pub fn new() -> Self {+ Self {+ origin: Vector::ZERO,+ min_bb_voxels: IVector::ZERO,+ max_bb_voxels: IVector::ONE,+ scale: 1.0,+ voxels: Vec::new(),+ intersections: Arc::new(Vec::new()),+ primitive_classes: Arc::new(Vec::new()),+ }+ }++ /// The volume of a single voxel of this voxel set.+ #[cfg(feature = "dim2")]+ pub fn voxel_volume(&self) -> Real {+ self.scale * self.scale+ }++ /// The volume of a single voxel of this voxel set.+ #[cfg(feature = "dim3")]+ pub fn voxel_volume(&self) -> Real {+ self.scale * self.scale * self.scale+ }++ /// Voxelizes a shape by specifying the physical size of each voxel.+ ///+ /// This creates a voxelized representation of a shape defined by its boundary:+ /// - In 3D: A triangle mesh (vertices and triangle indices)+ /// - In 2D: A polyline (vertices and segment indices)+ ///+ /// The resolution is automatically determined based on the shape's bounding box+ /// and the requested voxel size.+ ///+ /// # Parameters+ ///+ /// * `points` - Vertex buffer defining the boundary of the shape. These are the+ /// vertices of the triangle mesh (3D) or polyline (2D).+ ///+ /// * `indices` - Index buffer defining the boundary primitives:+ /// - 3D: Each element is `[v0, v1, v2]` defining a triangle+ /// - 2D: Each element is `[v0, v1]` defining a line segment+ ///+ /// * `voxel_size` - The physical size (edge length) of each cubic voxel. Smaller+ /// values give higher resolution but use more memory.+ ///+ /// * `fill_mode` - Controls which voxels are marked as filled:+ /// - [`FillMode::SurfaceOnly`]: Only voxels intersecting the boundary+ /// - [`FillMode::FloodFill`]: Surface voxels plus interior voxels+ ///+ /// * `keep_voxel_to_primitives_map` - If `true`, stores which primitives (triangles+ /// or segments) intersect each voxel. Required for [`compute_exact_convex_hull()`]+ /// and [`compute_primitive_intersections()`], but uses additional memory.+ ///+ /// # Returns+ ///+ /// A sparse `VoxelSet` containing only the filled voxels.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::voxelization::{FillMode, VoxelSet};+ /// use parry3d::shape::Ball;+ ///+ /// let ball = Ball::new(2.0); // radius = 2.0+ /// let (vertices, indices) = ball.to_trimesh(20, 20);+ ///+ /// // Create voxels with 0.1 unit size+ /// let voxels = VoxelSet::with_voxel_size(+ /// &vertices,+ /// &indices,+ /// 0.1, // each voxel is 0.1 x 0.1 x 0.1+ /// FillMode::SurfaceOnly,+ /// false,+ /// );+ ///+ /// println!("Created {} voxels", voxels.len());+ /// println!("Each voxel has volume {}", voxels.voxel_volume());+ /// # }+ /// ```+ ///+ /// [`compute_exact_convex_hull()`]: VoxelSet::compute_exact_convex_hull+ /// [`compute_primitive_intersections()`]: VoxelSet::compute_primitive_intersections+ pub fn with_voxel_size(+ points: &[Vector],+ indices: &[[u32; DIM]],+ voxel_size: Real,+ fill_mode: FillMode,+ keep_voxel_to_primitives_map: bool,+ ) -> Self {+ VoxelizedVolume::with_voxel_size(+ points,+ indices,+ voxel_size,+ fill_mode,+ keep_voxel_to_primitives_map,+ )+ .into()+ }++ /// Voxelizes a shape by specifying the grid resolution along the longest axis.+ ///+ /// This creates a voxelized representation of a shape defined by its boundary:+ /// - In 3D: A triangle mesh (vertices and triangle indices)+ /// - In 2D: A polyline (vertices and segment indices)+ ///+ /// The voxel size is automatically computed to fit the specified number of subdivisions+ /// along the shape's longest axis, while maintaining cubic (or square in 2D) voxels.+ /// Other axes will have proportionally determined resolutions.+ ///+ /// # Parameters+ ///+ /// * `points` - Vertex buffer defining the boundary of the shape. These are the+ /// vertices of the triangle mesh (3D) or polyline (2D).+ ///+ /// * `indices` - Index buffer defining the boundary primitives:+ /// - 3D: Each element is `[v0, v1, v2]` defining a triangle+ /// - 2D: Each element is `[v0, v1]` defining a line segment+ ///+ /// * `resolution` - Number of voxel subdivisions along the longest axis of the shape's+ /// bounding box. Higher values give more detail but use more memory.+ /// For example, `resolution = 10` creates approximately 10 voxels along the longest dimension.+ ///+ /// * `fill_mode` - Controls which voxels are marked as filled:+ /// - [`FillMode::SurfaceOnly`]: Only voxels intersecting the boundary+ /// - [`FillMode::FloodFill`]: Surface voxels plus interior voxels+ ///+ /// * `keep_voxel_to_primitives_map` - If `true`, stores which primitives (triangles+ /// or segments) intersect each voxel. Required for [`compute_exact_convex_hull()`]+ /// and [`compute_primitive_intersections()`], but uses additional memory.+ ///+ /// # Returns+ ///+ /// A sparse `VoxelSet` containing only the filled voxels.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::voxelization::{FillMode, VoxelSet};+ /// use parry3d::shape::Cuboid;+ /// use parry3d::math::Vector;+ ///+ /// // Create a cuboid: 2 units wide (x), 1 unit tall (y), 0.5 units deep (z)+ /// let cuboid = Cuboid::new(Vector::new(1.0, 0.5, 0.25));+ /// let (vertices, indices) = cuboid.to_trimesh();+ ///+ /// // Voxelize with 20 subdivisions along the longest axis (x = 2.0)+ /// // Other axes will be proportionally subdivided to maintain cubic voxels+ /// let voxels = VoxelSet::voxelize(+ /// &vertices,+ /// &indices,+ /// 20, // 20 voxels along x-axis+ /// FillMode::FloodFill {+ /// detect_cavities: false,+ /// },+ /// false,+ /// );+ ///+ /// println!("Created {} voxels", voxels.len());+ /// println!("Voxel scale: {}", voxels.scale); // automatically computed+ /// println!("Total volume: {}", voxels.compute_volume());+ /// # }+ /// ```+ ///+ /// # Choosing Resolution+ ///+ /// - **Low (5-10)**: Fast, coarse approximation, good for rough collision proxies+ /// - **Medium (10-30)**: Balanced detail and performance, suitable for most use cases+ /// - **High (50+)**: Fine detail, high memory usage, used for precise volume computation+ ///+ /// [`compute_exact_convex_hull()`]: VoxelSet::compute_exact_convex_hull+ /// [`compute_primitive_intersections()`]: VoxelSet::compute_primitive_intersections+ pub fn voxelize(+ points: &[Vector],+ indices: &[[u32; DIM]],+ resolution: u32,+ fill_mode: FillMode,+ keep_voxel_to_primitives_map: bool,+ ) -> Self {+ VoxelizedVolume::voxelize(+ points,+ indices,+ resolution,+ fill_mode,+ keep_voxel_to_primitives_map,+ )+ .into()+ }++ /// The minimal coordinates of the integer bounding-box of the voxels in this set.+ pub fn min_bb_voxels(&self) -> IVector {+ self.min_bb_voxels+ }++ /// The maximal coordinates of the integer bounding-box of the voxels in this set.+ pub fn max_bb_voxels(&self) -> IVector {+ self.max_bb_voxels+ }++ /// Computes the total volume occupied by all voxels in this set.+ ///+ /// This calculates the approximate volume by multiplying the number of filled voxels+ /// by the volume of each individual voxel. The result is an approximation of the+ /// volume of the original shape.+ ///+ /// # Accuracy+ ///+ /// The accuracy depends on the voxelization resolution:+ /// - Higher resolution (smaller voxels) → more accurate volume+ /// - Lower resolution (larger voxels) → faster but less accurate+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::voxelization::{FillMode, VoxelSet};+ /// use parry3d::shape::Ball;+ ///+ /// let ball = Ball::new(1.0);+ /// let (vertices, indices) = ball.to_trimesh(20, 20);+ ///+ /// let voxels = VoxelSet::voxelize(+ /// &vertices,+ /// &indices,+ /// 30, // Higher resolution for better accuracy+ /// FillMode::FloodFill { detect_cavities: false },+ /// false,+ /// );+ ///+ /// let voxel_volume = voxels.compute_volume();+ /// let expected_volume = 4.0 / 3.0 * std::f32::consts::PI * 1.0_f32.powi(3);+ ///+ /// println!("Voxel volume: {:.3}", voxel_volume);+ /// println!("Expected volume: {:.3}", expected_volume);+ /// println!("Error: {:.1}%", ((voxel_volume - expected_volume).abs() / expected_volume * 100.0));+ /// # }+ /// ```+ pub fn compute_volume(&self) -> Real {+ self.voxel_volume() * self.voxels.len() as Real+ }++ /// Converts voxel grid coordinates to world-space coordinates.+ ///+ /// Given a voxel, this computes the world-space position of the voxel's center.+ /// The conversion formula is:+ ///+ /// ```text+ /// world_position = origin + (voxel + 0.5) * scale+ /// ```+ ///+ /// Note that we add 0.5 to get the center of the voxel rather than its corner.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::voxelization::{FillMode, VoxelSet};+ /// use parry3d::shape::Cuboid;+ /// use parry3d::math::Vector;+ ///+ /// let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+ /// let (vertices, indices) = cuboid.to_trimesh();+ ///+ /// let voxels = VoxelSet::voxelize(+ /// &vertices,+ /// &indices,+ /// 10,+ /// FillMode::SurfaceOnly,+ /// false,+ /// );+ ///+ /// // Convert grid coordinates to world coordinates+ /// for voxel in voxels.voxels() {+ /// let grid_coords = voxel;+ /// let world_coords = voxels.get_voxel_point(voxel);+ ///+ /// println!("Grid: {:?} -> World: {:?}", grid_coords, world_coords);+ /// }+ /// # }+ /// ```+ pub fn get_voxel_point(&self, voxel: &Voxel) -> Vector {+ #[cfg(feature = "dim2")]+ let coords = Vector::new(voxel.coords.x as Real, voxel.coords.y as Real);+ #[cfg(feature = "dim3")]+ let coords = Vector::new(+ voxel.coords.x as Real,+ voxel.coords.y as Real,+ voxel.coords.z as Real,+ );+ self.get_point(coords)+ }++ pub(crate) fn get_point(&self, voxel: Vector) -> Vector {+ self.origin + voxel * self.scale+ }++ /// Does this voxel not contain any element?+ pub fn is_empty(&self) -> bool {+ self.len() == 0+ }++ /// The number of voxels in this set.+ pub fn len(&self) -> usize {+ self.voxels.len()+ }++ /// The set of voxels.+ pub fn voxels(&self) -> &[Voxel] {+ &self.voxels+ }++ /// Update the bounding box of this voxel set.+ pub fn compute_bb(&mut self) {+ let num_voxels = self.voxels.len();++ if num_voxels == 0 {+ return;+ }++ self.min_bb_voxels = self.voxels[0].coords;+ self.max_bb_voxels = self.voxels[0].coords;++ for p in 0..num_voxels {+ self.min_bb_voxels = self.min_bb_voxels.min(self.voxels[p].coords);+ self.max_bb_voxels = self.max_bb_voxels.max(self.voxels[p].coords);+ }+ }++ /// Computes a precise convex hull by clipping primitives against voxel boundaries.+ ///+ /// This method produces a more accurate convex hull than [`compute_convex_hull()`] by:+ /// 1. Finding which primitives (triangles/segments) intersect each voxel+ /// 2. Clipping those primitives to the voxel boundaries+ /// 3. Computing the convex hull from the clipped geometry+ ///+ /// This approach gives much tighter convex hulls, especially at lower resolutions, because+ /// it uses the actual intersection geometry rather than just voxel centers.+ ///+ /// # Requirements+ ///+ /// This method requires that the voxel set was created with `keep_voxel_to_primitives_map = true`.+ /// Otherwise, this method will panic.+ ///+ /// # Parameters+ ///+ /// * `points` - The same vertex buffer used during voxelization+ /// * `indices` - The same index buffer used during voxelization+ ///+ /// # Returns+ ///+ /// In 2D: A vector of points forming the convex hull polygon+ /// In 3D: A tuple of `(vertices, triangle_indices)` forming the convex hull mesh+ ///+ /// # Panics+ ///+ /// Panics if this `VoxelSet` was created with `keep_voxel_to_primitives_map = false`.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::voxelization::{FillMode, VoxelSet};+ /// use parry3d::shape::Cuboid;+ /// use parry3d::math::Vector;+ ///+ /// let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+ /// let (vertices, indices) = cuboid.to_trimesh();+ ///+ /// // IMPORTANT: Set keep_voxel_to_primitives_map = true+ /// let voxels = VoxelSet::voxelize(+ /// &vertices,+ /// &indices,+ /// 10,+ /// FillMode::SurfaceOnly,+ /// true, // Enable primitive mapping+ /// );+ ///+ /// // Compute exact convex hull using triangle clipping+ /// let (hull_vertices, hull_indices) = voxels.compute_exact_convex_hull(&vertices, &indices);+ ///+ /// println!("Exact convex hull: {} vertices, {} triangles",+ /// hull_vertices.len(), hull_indices.len());+ /// # }+ /// ```+ ///+ /// # Comparison with `compute_convex_hull()`+ ///+ /// - `compute_exact_convex_hull()`: More accurate, requires primitive mapping, slower+ /// - `compute_convex_hull()`: Approximate, uses voxel centers, faster+ ///+ /// [`compute_convex_hull()`]: VoxelSet::compute_convex_hull+ #[cfg(feature = "dim2")]+ pub fn compute_exact_convex_hull(+ &self,+ points: &[Vector],+ indices: &[[u32; DIM]],+ ) -> Vec<Vector> {+ self.do_compute_exact_convex_hull(points, indices)+ }++ /// Computes a precise convex hull by clipping primitives against voxel boundaries.+ ///+ /// This method produces a more accurate convex hull than [`compute_convex_hull()`] by:+ /// 1. Finding which primitives (triangles/segments) intersect each voxel+ /// 2. Clipping those primitives to the voxel boundaries+ /// 3. Computing the convex hull from the clipped geometry+ ///+ /// This approach gives much tighter convex hulls, especially at lower resolutions, because+ /// it uses the actual intersection geometry rather than just voxel centers.+ ///+ /// # Requirements+ ///+ /// This method requires that the voxel set was created with `keep_voxel_to_primitives_map = true`.+ /// Otherwise, this method will panic.+ ///+ /// # Parameters+ ///+ /// * `points` - The same vertex buffer used during voxelization+ /// * `indices` - The same index buffer used during voxelization+ ///+ /// # Returns+ ///+ /// In 2D: A vector of points forming the convex hull polygon+ /// In 3D: A tuple of `(vertices, triangle_indices)` forming the convex hull mesh+ ///+ /// # Panics+ ///+ /// Panics if this `VoxelSet` was created with `keep_voxel_to_primitives_map = false`.+ ///+ /// # Example+ ///+ /// ```+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// use parry3d::transformation::voxelization::{FillMode, VoxelSet};+ /// use parry3d::shape::Cuboid;+ /// use parry3d::math::Vector;+ ///+ /// let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+ /// let (vertices, indices) = cuboid.to_trimesh();+ ///+ /// // IMPORTANT: Set keep_voxel_to_primitives_map = true+ /// let voxels = VoxelSet::voxelize(+ /// &vertices,+ /// &indices,+ /// 10,+ /// FillMode::SurfaceOnly,+ /// true, // Enable primitive mapping+ /// );+ ///+ /// // Compute exact convex hull using triangle clipping+ /// let (hull_vertices, hull_indices) = voxels.compute_exact_convex_hull(&vertices, &indices);+ ///+ /// println!("Exact convex hull: {} vertices, {} triangles",+ /// hull_vertices.len(), hull_indices.len());+ /// # }+ /// ```+ ///+ /// # Comparison with `compute_convex_hull()`+ ///+ /// - `compute_exact_convex_hull()`: More accurate, requires primitive mapping, slower+ /// - `compute_convex_hull()`: Approximate, uses voxel centers, faster+ ///+ /// [`compute_convex_hull()`]: VoxelSet::compute_convex_hull+ #[cfg(feature = "dim3")]+ pub fn compute_exact_convex_hull(+ &self,+ points: &[Vector],+ indices: &[[u32; DIM]],+ ) -> (Vec<Vector>, Vec<[u32; DIM]>) {+ self.do_compute_exact_convex_hull(points, indices)+ }++ fn do_compute_exact_convex_hull(+ &self,+ points: &[Vector],+ indices: &[[u32; DIM]],+ ) -> ConvexHull {+ assert!(!self.intersections.is_empty(),+ "Cannot compute exact convex hull without voxel-to-primitives-map. Consider passing voxel_to_primitives_map = true to the voxelizer.");+ let mut surface_points = Vec::new();+ #[cfg(feature = "dim3")]+ let (mut polygon, mut workspace) = (Vec::new(), Vec::new());+ let mut pushed_points = vec![false; points.len()];++ // Grab all the points.+ for voxel in self.voxels.iter().filter(|v| v.is_on_surface) {+ let intersections =+ &self.intersections[voxel.intersections_range.0..voxel.intersections_range.1];+ for prim_id in intersections {+ let ia = indices[*prim_id as usize][0] as usize;+ let ib = indices[*prim_id as usize][1] as usize;+ #[cfg(feature = "dim3")]+ let ic = indices[*prim_id as usize][2] as usize;++ // If the primitives have been classified by VHACD, we know that:+ // - A class equal to Some(u32::MAX) means that the primitives intersects multiple+ // convex parts, so we need to split it.+ // - A class equal to None means that we did not compute any classes (so we+ // must assume that each triangle have to be split since it may intersect+ // multiple parts.+ // - A class different from `None` and `Some(u32::MAX)` means that the triangle is+ // included in only one convex part. So instead of cutting it, just push the whole+ // triangle once.+ let prim_class = self.primitive_classes.get(*prim_id as usize).copied();+ if prim_class == Some(u32::MAX) || prim_class.is_none() {+ let aabb_center = self.origin + ivect_to_vect(voxel.coords) * self.scale;+ let aabb =+ Aabb::from_half_extents(aabb_center, Vector::splat(self.scale / 2.0));++ #[cfg(feature = "dim2")]+ if let Some(seg) = aabb.clip_segment(points[ia], points[ib]) {+ surface_points.push(seg.a);+ surface_points.push(seg.b);+ }++ #[cfg(feature = "dim3")]+ {+ polygon.clear();+ polygon.extend_from_slice(&[points[ia], points[ib], points[ic]]);+ aabb.clip_polygon_with_workspace(&mut polygon, &mut workspace);+ surface_points.append(&mut polygon);+ }+ } else {+ // We know this triangle is only contained by+ // one voxel set, i.e., `self`. So we don't+ // need to cut it.+ //+ // Because one triangle may intersect multiple voxels contained by+ // the same convex part, we only push vertices we have not pushed+ // so far in order to avoid some useless duplicate points (duplicate+ // points are OK as far as convex hull computation is concerned, but+ // they imply some redundant computations).+ let mut push_pt = |i: usize| {+ if !pushed_points[i] {+ surface_points.push(points[i]);+ pushed_points[i] = true;+ }+ };++ push_pt(ia);+ push_pt(ib);+ #[cfg(feature = "dim3")]+ push_pt(ic);+ }+ }++ if intersections.is_empty() {+ self.map_voxel_points(voxel, |p| surface_points.push(p));+ }+ }++ // Compute the convex-hull.+ convex_hull(&surface_points)+ }++ /// Computes the intersections between all the voxels of this voxel set,+ /// and all the primitives (triangle or segments) it intersected (as per+ /// the voxel-to-primitives-map computed during voxelization).+ ///+ /// Panics if the voxelization was performed without setting the parameter+ /// `voxel_to_primitives_map = true`.+ pub fn compute_primitive_intersections(+ &self,+ points: &[Vector],+ indices: &[[u32; DIM]],+ ) -> Vec<Vector> {+ assert!(!self.intersections.is_empty(),+ "Cannot compute primitive intersections voxel-to-primitives-map. Consider passing voxel_to_primitives_map = true to the voxelizer.");+ let mut surface_points = Vec::new();+ #[cfg(feature = "dim3")]+ let (mut polygon, mut workspace) = (Vec::new(), Vec::new());++ // Grab all the points.+ for voxel in self.voxels.iter().filter(|v| v.is_on_surface) {+ let intersections =+ &self.intersections[voxel.intersections_range.0..voxel.intersections_range.1];+ for prim_id in intersections {+ let aabb_center = self.origin + ivect_to_vect(voxel.coords) * self.scale;+ let aabb = Aabb::from_half_extents(aabb_center, Vector::splat(self.scale / 2.0));++ let pa = points[indices[*prim_id as usize][0] as usize];+ let pb = points[indices[*prim_id as usize][1] as usize];+ #[cfg(feature = "dim3")]+ let pc = points[indices[*prim_id as usize][2] as usize];++ #[cfg(feature = "dim2")]+ if let Some(seg) = aabb.clip_segment(pa, pb) {+ surface_points.push(seg.a);+ surface_points.push(seg.b);+ }++ #[cfg(feature = "dim3")]+ {+ workspace.clear();+ polygon.clear();+ polygon.extend_from_slice(&[pa, pb, pc]);+ aabb.clip_polygon_with_workspace(&mut polygon, &mut workspace);++ if polygon.len() > 2 {+ for i in 1..polygon.len() - 1 {+ surface_points.push(polygon[0]);+ surface_points.push(polygon[i]);+ surface_points.push(polygon[i + 1]);+ }+ }+ }+ }+ }++ surface_points+ }++ /// Compute the convex-hull of the voxels in this set.+ ///+ /// # Parameters+ /// * `sampling` - The convex-hull computation will ignore `sampling` voxels at+ /// regular intervals. Useful to save some computation times if an exact result isn't need.+ /// Use `0` to make sure no voxel is being ignored.+ #[cfg(feature = "dim2")]+ pub fn compute_convex_hull(&self, sampling: u32) -> Vec<Vector> {+ let mut points = Vec::new();++ // Grab all the points.+ for voxel in self+ .voxels+ .iter()+ .filter(|v| v.is_on_surface)+ .step_by(sampling as usize)+ {+ self.map_voxel_points(voxel, |p| points.push(p));+ }++ // Compute the convex-hull.+ convex_hull(&points)+ }++ /// Compute the convex-hull of the voxels in this set.+ ///+ /// # Parameters+ /// * `sampling` - The convex-hull computation will ignore `sampling` voxels at+ /// regular intervals. Useful to save some computation times if an exact result isn't need.+ /// Use `0` to make sure no voxel is being ignored.+ #[cfg(feature = "dim3")]+ pub fn compute_convex_hull(&self, sampling: u32) -> (Vec<Vector>, Vec<[u32; DIM]>) {+ let mut points = Vec::new();++ // Grab all the points.+ for voxel in self+ .voxels+ .iter()+ .filter(|v| v.is_on_surface)+ .step_by(sampling as usize)+ {+ self.map_voxel_points(voxel, |p| points.push(p));+ }++ // Compute the convex-hull.+ convex_hull(&points)+ }++ /// Gets the vertices of the given voxel.+ fn map_voxel_points(&self, voxel: &Voxel, mut f: impl FnMut(Vector)) {+ let ijk = ivect_to_vect(voxel.coords);++ #[cfg(feature = "dim2")]+ let shifts = [+ Vector::new(-0.5, -0.5),+ Vector::new(0.5, -0.5),+ Vector::new(0.5, 0.5),+ Vector::new(-0.5, 0.5),+ ];++ #[cfg(feature = "dim3")]+ let shifts = [+ Vector::new(-0.5, -0.5, -0.5),+ Vector::new(0.5, -0.5, -0.5),+ Vector::new(0.5, 0.5, -0.5),+ Vector::new(-0.5, 0.5, -0.5),+ Vector::new(-0.5, -0.5, 0.5),+ Vector::new(0.5, -0.5, 0.5),+ Vector::new(0.5, 0.5, 0.5),+ Vector::new(-0.5, 0.5, 0.5),+ ];++ for shift in &shifts {+ f(self.origin + (ijk + *shift) * self.scale)+ }+ }++ pub(crate) fn intersect(+ &self,+ plane: &CutPlane,+ positive_pts: &mut Vec<Vector>,+ negative_pts: &mut Vec<Vector>,+ sampling: u32,+ ) {+ let num_voxels = self.voxels.len();++ if num_voxels == 0 {+ return;+ }++ let d0 = self.scale;+ let mut sp = 0;+ let mut sn = 0;++ for v in 0..num_voxels {+ let voxel = self.voxels[v];+ let pt = self.get_voxel_point(&voxel);+ let d = plane.abc.dot(pt) + plane.d;++ // if (d >= 0.0 && d <= d0) positive_pts.push(pt);+ // else if (d < 0.0 && -d <= d0) negative_pts.push(pt);++ if d >= 0.0 {+ if d <= d0 {+ self.map_voxel_points(&voxel, |p| positive_pts.push(p));+ } else {+ sp += 1;++ if sp == sampling {+ self.map_voxel_points(&voxel, |p| positive_pts.push(p));+ sp = 0;+ }+ }+ } else if -d <= d0 {+ self.map_voxel_points(&voxel, |p| negative_pts.push(p));+ } else {+ sn += 1;+ if sn == sampling {+ self.map_voxel_points(&voxel, |p| negative_pts.push(p));+ sn = 0;+ }+ }+ }+ }++ // Returns (negative_volume, positive_volume)+ pub(crate) fn compute_clipped_volumes(&self, plane: &CutPlane) -> (Real, Real) {+ if self.voxels.is_empty() {+ return (0.0, 0.0);+ }++ let mut num_positive_voxels = 0;++ for voxel in &self.voxels {+ let pt = self.get_voxel_point(voxel);+ let d = plane.abc.dot(pt) + plane.d;+ num_positive_voxels += (d >= 0.0) as usize;+ }++ let num_negative_voxels = self.voxels.len() - num_positive_voxels;+ let positive_volume = self.voxel_volume() * (num_positive_voxels as Real);+ let negative_volume = self.voxel_volume() * (num_negative_voxels as Real);++ (negative_volume, positive_volume)+ }++ // Set `on_surf` such that it contains only the voxel on surface contained by `self`.+ pub(crate) fn select_on_surface(&self, on_surf: &mut VoxelSet) {+ on_surf.origin = self.origin;+ on_surf.voxels.clear();+ on_surf.scale = self.scale;++ for voxel in &self.voxels {+ if voxel.is_on_surface {+ on_surf.voxels.push(*voxel);+ }+ }+ }++ /// Splits this voxel set into two parts, depending on where the voxel center lies wrt. the given plane.+ pub(crate) fn clip(+ &self,+ plane: &CutPlane,+ positive_part: &mut VoxelSet,+ negative_part: &mut VoxelSet,+ ) {+ let num_voxels = self.voxels.len();++ if num_voxels == 0 {+ return;+ }++ negative_part.origin = self.origin;+ negative_part.voxels.clear();+ negative_part.voxels.reserve(num_voxels);+ negative_part.scale = self.scale;++ positive_part.origin = self.origin;+ positive_part.voxels.clear();+ positive_part.voxels.reserve(num_voxels);+ positive_part.scale = self.scale;++ let d0 = self.scale;++ for v in 0..num_voxels {+ let mut voxel = self.voxels[v];+ let pt = self.get_voxel_point(&voxel);+ let d = plane.abc.dot(pt) + plane.d;++ if d >= 0.0 {+ if voxel.is_on_surface || d <= d0 {+ voxel.is_on_surface = true;+ positive_part.voxels.push(voxel);+ } else {+ positive_part.voxels.push(voxel);+ }+ } else if voxel.is_on_surface || -d <= d0 {+ voxel.is_on_surface = true;+ negative_part.voxels.push(voxel);+ } else {+ negative_part.voxels.push(voxel);+ }+ }+ }++ /// Convert `self` into a mesh, including only the voxels on the surface or only the voxel+ /// inside of the volume.+ #[cfg(feature = "dim3")]+ pub fn to_trimesh(+ &self,+ base_index: u32,+ is_on_surface: bool,+ ) -> (Vec<Vector>, Vec<[u32; DIM]>) {+ let mut vertices = Vec::new();+ let mut indices = Vec::new();++ for voxel in &self.voxels {+ if voxel.is_on_surface == is_on_surface {+ self.map_voxel_points(voxel, |p| vertices.push(p));++ indices.push([base_index, base_index + 2, base_index + 1]);+ indices.push([base_index, base_index + 3, base_index + 2]);+ indices.push([base_index + 4, base_index + 5, base_index + 6]);+ indices.push([base_index + 4, base_index + 6, base_index + 7]);+ indices.push([base_index + 7, base_index + 6, base_index + 2]);+ indices.push([base_index + 7, base_index + 2, base_index + 3]);+ indices.push([base_index + 4, base_index + 1, base_index + 5]);+ indices.push([base_index + 4, base_index, base_index + 1]);+ indices.push([base_index + 6, base_index + 5, base_index + 1]);+ indices.push([base_index + 6, base_index + 1, base_index + 2]);+ indices.push([base_index + 7, base_index, base_index + 4]);+ indices.push([base_index + 7, base_index + 3, base_index]);+ }+ }++ (vertices, indices)+ }++ pub(crate) fn compute_principal_axes(&self) -> Vector {+ let num_voxels = self.voxels.len();+ if num_voxels == 0 {+ return Vector::ZERO;+ }++ // TODO: find a way to reuse crate::utils::cov?+ // The difficulty being that we need to iterate through the set of+ // points twice. So passing an iterator to crate::utils::cov+ // isn't really possible.+ let mut center = Vector::ZERO;+ let denom = 1.0 / (num_voxels as Real);++ for voxel in &self.voxels {+ center += ivect_to_vect(voxel.coords) * denom;+ }++ let mut cov_mat = Matrix::ZERO;+ for voxel in &self.voxels {+ let xyz = ivect_to_vect(voxel.coords) - center;+ cov_mat += xyz.kronecker(xyz * denom);+ }+ cov_mat.symmetric_eigenvalues()+ }++ pub(crate) fn compute_axes_aligned_clipping_planes(+ &self,+ downsampling: u32,+ planes: &mut Vec<CutPlane>,+ ) {+ let min_v = self.min_bb_voxels();+ let max_v = self.max_bb_voxels();++ for dim in 0..DIM {+ let i0 = min_v[dim];+ let i1 = max_v[dim];++ for i in (i0..=i1).step_by(downsampling as usize) {+ let plane = CutPlane {+ abc: Vector::ith(dim, 1.0),+ axis: dim as u8,+ d: -(self.origin[dim] + (i as Real + 0.5) * self.scale),+ index: i as u32,+ };++ planes.push(plane);+ }+ }+ }+}++#[cfg(feature = "dim2")]+fn convex_hull(vertices: &[Vector]) -> Vec<Vector> {+ if vertices.len() > 1 {+ crate::transformation::convex_hull(vertices)+ } else {+ Vec::new()+ }+}++#[cfg(feature = "dim3")]+fn convex_hull(vertices: &[Vector]) -> (Vec<Vector>, Vec<[u32; DIM]>) {+ if vertices.len() > 2 {+ crate::transformation::try_convex_hull(vertices).unwrap_or_default()+ } else {+ (Vec::new(), Vec::new())+ }+}diff --git a/renderer/third_party/parry3d/src/transformation/voxelization/voxelized_volume.rs b/renderer/third_party/parry3d/src/transformation/voxelization/voxelized_volume.rsnew file mode 100644index 0000000..c3e64e2--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/voxelization/voxelized_volume.rs@@ -0,0 +1,1251 @@+// Rust port, with modifications, of https://github.com/kmammou/v-hacd/blob/master/src/VHACD_Lib/src/vhacdVolume.cpp+// By Khaled Mamou+//+// # License of the original C++ code:+// > Copyright (c) 2011 Khaled Mamou (kmamou at gmail dot com)+// > All rights reserved.+// >+// >+// > Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:+// >+// > 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.+// >+// > 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.+// >+// > 3. The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission.+// >+// > THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++use crate::bounding_volume::Aabb;+#[cfg(not(feature = "std"))]+use crate::math::ComplexField;+use crate::math::{IVector, Int, Real, Vector, DIM};+use crate::query;+use crate::transformation::voxelization::{Voxel, VoxelSet};+use alloc::sync::Arc;+use alloc::vec::Vec;++/// Controls how voxelization determines which voxels are filled vs empty.+///+/// The fill mode is a critical parameter that determines the structure of the resulting voxel set.+/// Choose the appropriate mode based on whether you need just the surface boundary or a solid volume.+///+/// # Variants+///+/// ## `SurfaceOnly`+///+/// Only voxels that intersect the input surface boundary (triangle mesh in 3D, polyline in 2D)+/// are marked as filled. This creates a hollow shell representation.+///+/// **Use this when:**+/// - You only need the surface boundary+/// - Memory is limited (fewer voxels to store)+/// - You're approximating a thin shell or surface+///+/// **Example:**+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::voxelization::{FillMode, VoxelSet};+/// use parry3d::shape::Ball;+/// ///+/// let ball = Ball::new(1.0);+/// let (vertices, indices) = ball.to_trimesh(20, 20);+///+/// let surface_voxels = VoxelSet::voxelize(+/// &vertices,+/// &indices,+/// 10,+/// FillMode::SurfaceOnly, // Only the shell+/// false,+/// );+///+/// // All voxels are on the surface+/// assert!(surface_voxels.voxels().iter().all(|v| v.is_on_surface));+/// # }+/// ```+///+/// ## `FloodFill`+///+/// Marks surface voxels AND all interior voxels as filled, creating a solid volume. Uses a+/// flood-fill algorithm starting from outside the shape to determine inside vs outside.+///+/// **Fields:**+/// - `detect_cavities`: If `true`, properly detects and preserves internal cavities/holes.+/// If `false`, all enclosed spaces are filled (faster but may fill unintended regions).+///+/// - `detect_self_intersections` (2D only): If `true`, attempts to handle self-intersecting+/// polylines correctly. More expensive but more robust.+///+/// **Use this when:**+/// - You need volume information (mass properties, volume computation)+/// - You want a solid representation for collision detection+/// - You need to distinguish between interior and surface voxels+///+/// **Example:**+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::voxelization::{FillMode, VoxelSet};+/// use parry3d::shape::Ball;+/// ///+/// let ball = Ball::new(1.0);+/// let (vertices, indices) = ball.to_trimesh(20, 20);+///+/// let solid_voxels = VoxelSet::voxelize(+/// &vertices,+/// &indices,+/// 15,+/// FillMode::FloodFill {+/// detect_cavities: false, // No cavities in a sphere+/// },+/// false,+/// );+///+/// // Mix of surface and interior voxels+/// let surface_count = solid_voxels.voxels().iter().filter(|v| v.is_on_surface).count();+/// let interior_count = solid_voxels.voxels().iter().filter(|v| !v.is_on_surface).count();+/// assert!(surface_count > 0 && interior_count > 0);+/// # }+/// ```+///+/// # Performance Notes+///+/// - `SurfaceOnly` is faster and uses less memory than `FloodFill`+/// - `detect_cavities = true` adds computational overhead but gives more accurate results+/// - For simple convex shapes, `detect_cavities = false` is usually sufficient+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub enum FillMode {+ /// Only consider full the voxels intersecting the surface of the+ /// shape being voxelized.+ SurfaceOnly,+ /// Use a flood-fill technique to consider fill the voxels intersecting+ /// the surface of the shape being voxelized, as well as all the voxels+ /// bounded of them.+ FloodFill {+ /// Detects holes inside of a solid contour.+ detect_cavities: bool,+ /// Attempts to properly handle self-intersections.+ #[cfg(feature = "dim2")]+ detect_self_intersections: bool,+ },+ // RaycastFill+}++impl Default for FillMode {+ fn default() -> Self {+ Self::FloodFill {+ detect_cavities: false,+ #[cfg(feature = "dim2")]+ detect_self_intersections: false,+ }+ }+}++impl FillMode {+ #[cfg(feature = "dim2")]+ pub(crate) fn detect_cavities(self) -> bool {+ match self {+ FillMode::FloodFill {+ detect_cavities, ..+ } => detect_cavities,+ _ => false,+ }+ }++ #[cfg(feature = "dim2")]+ pub(crate) fn detect_self_intersections(self) -> bool {+ match self {+ FillMode::FloodFill {+ detect_self_intersections,+ ..+ } => detect_self_intersections,+ _ => false,+ }+ }++ #[cfg(feature = "dim3")]+ pub(crate) fn detect_self_intersections(self) -> bool {+ false+ }+}++/// The state of a voxel during and after voxelization.+///+/// This enum represents the classification of each voxel in the grid. After voxelization completes,+/// only three values are meaningful for end-user code: `PrimitiveOutsideSurface`,+/// `PrimitiveInsideSurface`, and `PrimitiveOnSurface`. The other variants are intermediate+/// states used during the flood-fill algorithm.+///+/// # Usage+///+/// Most users will work with [`VoxelSet`] which filters out outside voxels and only stores+/// filled ones. However, if you're working directly with [`VoxelizedVolume`], you'll encounter+/// all these values.+///+/// # Final States (After Voxelization)+///+/// - **`PrimitiveOutsideSurface`**: Voxel is completely outside the shape+/// - **`PrimitiveInsideSurface`**: Voxel is fully inside the shape (only with [`FillMode::FloodFill`])+/// - **`PrimitiveOnSurface`**: Voxel intersects the boundary surface+///+/// # Intermediate States (During Voxelization)+///+/// The following are temporary states used during the flood-fill algorithm and should be+/// ignored by user code:+/// - `PrimitiveUndefined`+/// - `PrimitiveOutsideSurfaceToWalk`+/// - `PrimitiveInsideSurfaceToWalk`+/// - `PrimitiveOnSurfaceNoWalk`+/// - `PrimitiveOnSurfaceToWalk1`+/// - `PrimitiveOnSurfaceToWalk2`+///+/// # Example+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::voxelization::{FillMode, VoxelValue, VoxelizedVolume};+/// use parry3d::shape::Cuboid;+/// use parry3d::math::Vector;+///+/// let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+/// let (vertices, indices) = cuboid.to_trimesh();+///+/// // Create a dense voxelized volume+/// let volume = VoxelizedVolume::voxelize(+/// &vertices,+/// &indices,+/// 8,+/// FillMode::FloodFill { detect_cavities: false },+/// false,+/// );+///+/// // Query individual voxel values+/// let resolution = volume.resolution();+/// for i in 0..resolution[0] {+/// for j in 0..resolution[1] {+/// for k in 0..resolution[2] {+/// match volume.voxel(i, j, k) {+/// VoxelValue::PrimitiveOnSurface => {+/// // This voxel is on the boundary+/// }+/// VoxelValue::PrimitiveInsideSurface => {+/// // This voxel is inside the shape+/// }+/// VoxelValue::PrimitiveOutsideSurface => {+/// // This voxel is outside the shape+/// }+/// _ => {+/// // Should not happen after voxelization completes+/// }+/// }+/// }+/// }+/// }+/// # }+/// ```+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub enum VoxelValue {+ /// Intermediate value, should be ignored by end-user code.+ PrimitiveUndefined,+ /// Intermediate value, should be ignored by end-user code.+ PrimitiveOutsideSurfaceToWalk,+ /// Intermediate value, should be ignored by end-user code.+ PrimitiveInsideSurfaceToWalk,+ /// Intermediate value, should be ignored by end-user code.+ PrimitiveOnSurfaceNoWalk,+ /// Intermediate value, should be ignored by end-user code.+ PrimitiveOnSurfaceToWalk1,+ /// Intermediate value, should be ignored by end-user code.+ PrimitiveOnSurfaceToWalk2,+ /// A voxel that is outside of the voxelized shape.+ PrimitiveOutsideSurface,+ /// A voxel that is on the interior of the voxelized shape.+ PrimitiveInsideSurface,+ /// Voxel that intersects the surface of the voxelized shape.+ PrimitiveOnSurface,+}++#[derive(Copy, Clone, Debug, PartialEq, Eq)]+struct VoxelData {+ #[cfg(feature = "dim2")]+ multiplicity: u32,+ num_primitive_intersections: u32,+}++/// A dense voxel grid storing the state of every voxel in a cubic volume.+///+/// `VoxelizedVolume` is the intermediate representation used during the voxelization process.+/// Unlike [`VoxelSet`] which only stores filled voxels, `VoxelizedVolume` stores a complete+/// dense 3D array where every grid cell has an associated [`VoxelValue`].+///+/// # When to Use+///+/// Most users should use [`VoxelSet`] instead, which is converted from `VoxelizedVolume`+/// automatically and is much more memory-efficient. You might want to use `VoxelizedVolume`+/// directly if you need to:+///+/// - Query the state of ALL voxels, including empty ones+/// - Implement custom voxel processing algorithms+/// - Generate visualizations showing both filled and empty voxels+///+/// # Memory Usage+///+/// `VoxelizedVolume` stores **all** voxels in a dense 3D array:+/// - Memory usage: `O(resolution^3)` in 3D or `O(resolution^2)` in 2D+/// - A 100×100×100 grid requires 1 million voxel entries+///+/// For this reason, [`VoxelSet`] is usually preferred for storage.+///+/// # Conversion+///+/// `VoxelizedVolume` automatically converts to `VoxelSet`:+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::voxelization::{FillMode, VoxelSet, VoxelizedVolume};+/// use parry3d::shape::Ball;+/// ///+/// let ball = Ball::new(1.0);+/// let (vertices, indices) = ball.to_trimesh(10, 10);+///+/// // Create dense volume+/// let volume = VoxelizedVolume::voxelize(+/// &vertices,+/// &indices,+/// 10,+/// FillMode::SurfaceOnly,+/// false,+/// );+///+/// // Convert to sparse set (automatic via Into trait)+/// let voxel_set: VoxelSet = volume.into();+/// # }+/// ```+///+/// # Example: Querying All Voxels+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::transformation::voxelization::{FillMode, VoxelValue, VoxelizedVolume};+/// use parry3d::shape::Cuboid;+/// use parry3d::math::Vector;+///+/// let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0));+/// let (vertices, indices) = cuboid.to_trimesh();+///+/// let volume = VoxelizedVolume::voxelize(+/// &vertices,+/// &indices,+/// 8,+/// FillMode::FloodFill { detect_cavities: false },+/// false,+/// );+///+/// // Count voxels by state+/// let resolution = volume.resolution();+/// let mut inside = 0;+/// let mut surface = 0;+/// let mut outside = 0;+///+/// for i in 0..resolution[0] {+/// for j in 0..resolution[1] {+/// for k in 0..resolution[2] {+/// match volume.voxel(i, j, k) {+/// VoxelValue::PrimitiveInsideSurface => inside += 1,+/// VoxelValue::PrimitiveOnSurface => surface += 1,+/// VoxelValue::PrimitiveOutsideSurface => outside += 1,+/// _ => {}+/// }+/// }+/// }+/// }+///+/// println!("Inside: {}, Surface: {}, Outside: {}", inside, surface, outside);+/// # }+/// ```+pub struct VoxelizedVolume {+ origin: Vector,+ scale: Real,+ resolution: [u32; DIM],+ values: Vec<VoxelValue>,+ data: Vec<VoxelData>,+ primitive_intersections: Vec<(u32, u32)>,+}++impl VoxelizedVolume {+ /// Voxelizes the given shape described by its boundary:+ /// a triangle mesh (in 3D) or polyline (in 2D).+ ///+ /// # Parameters+ /// * `points` - The vertex buffer of the boundary of the shape to voxelize.+ /// * `indices` - The index buffer of the boundary of the shape to voxelize.+ /// * `resolution` - Controls the number of subdivision done along each axis. This number+ /// is the number of subdivisions along the axis where the input shape has the largest extent.+ /// The other dimensions will have a different automatically-determined resolution (in order to+ /// keep the voxels cubic).+ /// * `fill_mode` - Controls what is being voxelized.+ /// * `keep_voxel_to_primitives_map` - If set to `true` a map between the voxels+ /// and the primitives (3D triangles or 2D segments) it intersects will be computed.+ pub fn with_voxel_size(+ points: &[Vector],+ indices: &[[u32; DIM]],+ voxel_size: Real,+ fill_mode: FillMode,+ keep_voxel_to_primitives_map: bool,+ ) -> Self {+ let mut result = VoxelizedVolume {+ resolution: [0; DIM],+ origin: Vector::ZERO,+ scale: voxel_size,+ values: Vec::new(),+ data: Vec::new(),+ primitive_intersections: Vec::new(),+ };++ if points.is_empty() {+ return result;+ }++ let aabb = crate::bounding_volume::details::local_point_cloud_aabb_ref(points);+ result.origin = aabb.mins;+ let extents = aabb.extents() / voxel_size;+ #[cfg(feature = "dim2")]+ {+ result.resolution = [+ (extents.x.ceil() as u32).max(2) + 1,+ (extents.y.ceil() as u32).max(2) + 1,+ ];+ }+ #[cfg(feature = "dim3")]+ {+ result.resolution = [+ (extents.x.ceil() as u32).max(2) + 1,+ (extents.y.ceil() as u32).max(2) + 1,+ (extents.z.ceil() as u32).max(2) + 1,+ ];+ }++ result.do_voxelize(points, indices, fill_mode, keep_voxel_to_primitives_map);+ result+ }++ /// Voxelizes the given shape described by its boundary:+ /// a triangle mesh (in 3D) or polyline (in 2D).+ ///+ /// # Parameters+ /// * `points` - The vertex buffer of the boundary of the shape to voxelize.+ /// * `indices` - The index buffer of the boundary of the shape to voxelize.+ /// * `resolution` - Controls the number of subdivision done along each axis. This number+ /// is the number of subdivisions along the axis where the input shape has the largest extent.+ /// The other dimensions will have a different automatically-determined resolution (in order to+ /// keep the voxels cubic).+ /// * `fill_mode` - Controls what is being voxelized.+ /// * `keep_voxel_to_primitives_map` - If set to `true` a map between the voxels+ /// and the primitives (3D triangles or 2D segments) it intersects will be computed.+ pub fn voxelize(+ points: &[Vector],+ indices: &[[u32; DIM]],+ resolution: u32,+ fill_mode: FillMode,+ keep_voxel_to_primitives_map: bool,+ ) -> Self {+ let mut result = VoxelizedVolume {+ resolution: [0; DIM],+ origin: Vector::ZERO,+ scale: 1.0,+ values: Vec::new(),+ data: Vec::new(),+ primitive_intersections: Vec::new(),+ };++ if points.is_empty() {+ return result;+ }++ let aabb = crate::bounding_volume::details::local_point_cloud_aabb_ref(points);+ result.origin = aabb.mins;++ let d = aabb.maxs - aabb.mins;+ let r;++ #[cfg(feature = "dim2")]+ if d[0] > d[1] {+ r = d[0];+ result.resolution[0] = resolution;+ result.resolution[1] = 2 + (resolution as Real * d[1] / d[0]) as u32;+ } else {+ r = d[1];+ result.resolution[1] = resolution;+ result.resolution[0] = 2 + (resolution as Real * d[0] / d[1]) as u32;+ }++ #[cfg(feature = "dim3")]+ if d[0] >= d[1] && d[0] >= d[2] {+ r = d[0];+ result.resolution[0] = resolution;+ result.resolution[1] = 2 + (resolution as Real * d[1] / d[0]) as u32;+ result.resolution[2] = 2 + (resolution as Real * d[2] / d[0]) as u32;+ } else if d[1] >= d[0] && d[1] >= d[2] {+ r = d[1];+ result.resolution[1] = resolution;+ result.resolution[0] = 2 + (resolution as Real * d[0] / d[1]) as u32;+ result.resolution[2] = 2 + (resolution as Real * d[2] / d[1]) as u32;+ } else {+ r = d[2];+ result.resolution[2] = resolution;+ result.resolution[0] = 2 + (resolution as Real * d[0] / d[2]) as u32;+ result.resolution[1] = 2 + (resolution as Real * d[1] / d[2]) as u32;+ }++ result.scale = r / (resolution as Real - 1.0);+ result.do_voxelize(points, indices, fill_mode, keep_voxel_to_primitives_map);+ result+ }++ fn do_voxelize(+ &mut self,+ points: &[Vector],+ indices: &[[u32; DIM]],+ fill_mode: FillMode,+ keep_voxel_to_primitives_map: bool,+ ) {+ let inv_scale = 1.0 / self.scale;+ self.allocate();++ let mut tri_pts = [Vector::ZERO; DIM];+ let box_half_size = Vector::splat(0.5);+ let mut ijk0 = IVector::ZERO;+ let mut ijk1 = IVector::ZERO;++ let detect_self_intersections = fill_mode.detect_self_intersections();+ #[cfg(feature = "dim2")]+ let lock_high_multiplicities =+ fill_mode.detect_cavities() && fill_mode.detect_self_intersections();++ for (tri_id, tri) in indices.iter().enumerate() {+ // Find the range of voxels potentially intersecting the triangle.+ for c in 0..DIM {+ let pt = points[tri[c] as usize];+ tri_pts[c] = (pt - self.origin) * inv_scale;++ let i = (tri_pts[c].x + 0.5) as Int;+ let j = (tri_pts[c].y + 0.5) as Int;+ #[cfg(feature = "dim3")]+ let k = (tri_pts[c].z + 0.5) as Int;++ assert!((i as u32) < self.resolution[0] && (j as u32) < self.resolution[1]);+ #[cfg(feature = "dim3")]+ assert!((k as u32) < self.resolution[2]);++ #[cfg(feature = "dim2")]+ let ijk = IVector::new(i, j);+ #[cfg(feature = "dim3")]+ let ijk = IVector::new(i, j, k);++ if c == 0 {+ ijk0 = ijk;+ ijk1 = ijk;+ } else {+ ijk0 = ijk0.min(ijk);+ ijk1 = ijk1.max(ijk);+ }+ }++ ijk0 = (ijk0 - IVector::ONE).max(IVector::ZERO);+ #[cfg(feature = "dim2")]+ let resolution_vec = IVector::new(self.resolution[0] as Int, self.resolution[1] as Int);+ #[cfg(feature = "dim3")]+ let resolution_vec = IVector::new(+ self.resolution[0] as Int,+ self.resolution[1] as Int,+ self.resolution[2] as Int,+ );+ ijk1 = (ijk1 + IVector::ONE).min(resolution_vec);++ #[cfg(feature = "dim2")]+ let range_k = 0..1;+ #[cfg(feature = "dim3")]+ let range_k = ijk0.z..ijk1.z;++ // Determine exactly what voxel intersect the triangle.+ for i in ijk0.x..ijk1.x {+ for j in ijk0.y..ijk1.y {+ for k in range_k.clone() {+ #[cfg(feature = "dim2")]+ let pt = Vector::new(i as Real, j as Real);+ #[cfg(feature = "dim3")]+ let pt = Vector::new(i as Real, j as Real, k as Real);++ let id = self.voxel_index(i as u32, j as u32, k as u32);+ let value = &mut self.values[id as usize];+ let data = &mut self.data[id as usize];++ if detect_self_intersections+ || keep_voxel_to_primitives_map+ || *value == VoxelValue::PrimitiveUndefined+ {+ let aabb = Aabb::from_half_extents(pt, box_half_size);++ #[cfg(feature = "dim2")]+ if !detect_self_intersections {+ let segment = crate::shape::Segment::from(tri_pts);+ let intersect =+ query::details::intersection_test_aabb_segment(&aabb, &segment);++ if intersect {+ if keep_voxel_to_primitives_map {+ data.num_primitive_intersections += 1;+ self.primitive_intersections.push((id, tri_id as u32));+ }++ *value = VoxelValue::PrimitiveOnSurface;+ }+ } else if let Some(params) =+ aabb.clip_line_parameters(tri_pts[0], tri_pts[1] - tri_pts[0])+ {+ let eps = 0.0; // -1.0e-6;++ assert!(params.0 <= params.1);+ if params.0 > 1.0 + eps || params.1 < 0.0 - eps {+ continue;+ }++ if keep_voxel_to_primitives_map {+ data.num_primitive_intersections += 1;+ self.primitive_intersections.push((id, tri_id as u32));+ }++ if data.multiplicity > 4 && lock_high_multiplicities {+ *value = VoxelValue::PrimitiveOnSurfaceNoWalk;+ } else {+ *value = VoxelValue::PrimitiveOnSurface;+ }+ };++ #[cfg(feature = "dim3")]+ {+ let triangle = crate::shape::Triangle::from(tri_pts);+ let intersect = query::details::intersection_test_aabb_triangle(+ &aabb, &triangle,+ );++ if intersect {+ *value = VoxelValue::PrimitiveOnSurface;++ if keep_voxel_to_primitives_map {+ data.num_primitive_intersections += 1;+ self.primitive_intersections.push((id, tri_id as u32));+ }+ }+ };+ }+ }+ }+ }+ }++ match fill_mode {+ FillMode::SurfaceOnly => {+ for value in &mut self.values {+ if *value != VoxelValue::PrimitiveOnSurface {+ *value = VoxelValue::PrimitiveOutsideSurface+ }+ }+ }+ FillMode::FloodFill {+ detect_cavities, ..+ } => {+ #[cfg(feature = "dim2")]+ {+ self.mark_outside_surface(0, 0, self.resolution[0], 1);+ self.mark_outside_surface(+ 0,+ self.resolution[1] - 1,+ self.resolution[0],+ self.resolution[1],+ );+ self.mark_outside_surface(0, 0, 1, self.resolution[1]);+ self.mark_outside_surface(+ self.resolution[0] - 1,+ 0,+ self.resolution[0],+ self.resolution[1],+ );+ }++ #[cfg(feature = "dim3")]+ {+ self.mark_outside_surface(0, 0, 0, self.resolution[0], self.resolution[1], 1);+ self.mark_outside_surface(+ 0,+ 0,+ self.resolution[2] - 1,+ self.resolution[0],+ self.resolution[1],+ self.resolution[2],+ );+ self.mark_outside_surface(0, 0, 0, self.resolution[0], 1, self.resolution[2]);+ self.mark_outside_surface(+ 0,+ self.resolution[1] - 1,+ 0,+ self.resolution[0],+ self.resolution[1],+ self.resolution[2],+ );+ self.mark_outside_surface(0, 0, 0, 1, self.resolution[1], self.resolution[2]);+ self.mark_outside_surface(+ self.resolution[0] - 1,+ 0,+ 0,+ self.resolution[0],+ self.resolution[1],+ self.resolution[2],+ );+ }++ if detect_cavities {+ let _ = self.propagate_values(+ VoxelValue::PrimitiveOutsideSurfaceToWalk,+ VoxelValue::PrimitiveOutsideSurface,+ None,+ VoxelValue::PrimitiveOnSurfaceToWalk1,+ );++ loop {+ if !self.propagate_values(+ VoxelValue::PrimitiveInsideSurfaceToWalk,+ VoxelValue::PrimitiveInsideSurface,+ Some(VoxelValue::PrimitiveOnSurfaceToWalk1),+ VoxelValue::PrimitiveOnSurfaceToWalk2,+ ) {+ break;+ }++ if !self.propagate_values(+ VoxelValue::PrimitiveOutsideSurfaceToWalk,+ VoxelValue::PrimitiveOutsideSurface,+ Some(VoxelValue::PrimitiveOnSurfaceToWalk2),+ VoxelValue::PrimitiveOnSurfaceToWalk1,+ ) {+ break;+ }+ }++ for voxel in &mut self.values {+ if *voxel == VoxelValue::PrimitiveOnSurfaceToWalk1+ || *voxel == VoxelValue::PrimitiveOnSurfaceToWalk2+ || *voxel == VoxelValue::PrimitiveOnSurfaceNoWalk+ {+ *voxel = VoxelValue::PrimitiveOnSurface;+ }+ }+ } else {+ let _ = self.propagate_values(+ VoxelValue::PrimitiveOutsideSurfaceToWalk,+ VoxelValue::PrimitiveOutsideSurface,+ None,+ VoxelValue::PrimitiveOnSurface,+ );++ self.replace_value(+ VoxelValue::PrimitiveUndefined,+ VoxelValue::PrimitiveInsideSurface,+ );+ }+ }+ }+ }++ /// The number of voxel subdivisions along each coordinate axis.+ pub fn resolution(&self) -> [u32; DIM] {+ self.resolution+ }++ /// The scale factor that needs to be applied to the voxels of `self`+ /// in order to give them the size matching the original model's size.+ pub fn scale(&self) -> Real {+ self.scale+ }++ fn allocate(&mut self) {+ #[cfg(feature = "dim2")]+ let len = self.resolution[0] * self.resolution[1];+ #[cfg(feature = "dim3")]+ let len = self.resolution[0] * self.resolution[1] * self.resolution[2];+ self.values+ .resize(len as usize, VoxelValue::PrimitiveUndefined);+ self.data.resize(+ len as usize,+ VoxelData {+ #[cfg(feature = "dim2")]+ multiplicity: 0,+ num_primitive_intersections: 0,+ },+ );+ }++ fn voxel_index(&self, i: u32, j: u32, _k: u32) -> u32 {+ #[cfg(feature = "dim2")]+ return i + j * self.resolution[0];+ #[cfg(feature = "dim3")]+ return i + j * self.resolution[0] + _k * self.resolution[0] * self.resolution[1];+ }++ fn voxel_mut(&mut self, i: u32, j: u32, k: u32) -> &mut VoxelValue {+ let idx = self.voxel_index(i, j, k);+ &mut self.values[idx as usize]+ }++ /// The value of the given voxel.+ ///+ /// In 2D, the `k` argument is ignored.+ pub fn voxel(&self, i: u32, j: u32, k: u32) -> VoxelValue {+ let idx = self.voxel_index(i, j, k);+ self.values[idx as usize]+ }++ /// Mark all the PrimitiveUndefined voxels within the given bounds as PrimitiveOutsideSurfaceToWalk.+ #[cfg(feature = "dim2")]+ fn mark_outside_surface(&mut self, i0: u32, j0: u32, i1: u32, j1: u32) {+ for i in i0..i1 {+ for j in j0..j1 {+ let v = self.voxel_mut(i, j, 0);++ if *v == VoxelValue::PrimitiveUndefined {+ *v = VoxelValue::PrimitiveOutsideSurfaceToWalk;+ }+ }+ }+ }++ /// Mark all the PrimitiveUndefined voxels within the given bounds as PrimitiveOutsideSurfaceToWalk.+ #[cfg(feature = "dim3")]+ fn mark_outside_surface(&mut self, i0: u32, j0: u32, k0: u32, i1: u32, j1: u32, k1: u32) {+ for i in i0..i1 {+ for j in j0..j1 {+ for k in k0..k1 {+ let v = self.voxel_mut(i, j, k);++ if *v == VoxelValue::PrimitiveUndefined {+ *v = VoxelValue::PrimitiveOutsideSurfaceToWalk;+ }+ }+ }+ }+ }++ fn walk_forward(+ primitive_undefined_value_to_set: VoxelValue,+ on_surface_value_to_set: VoxelValue,+ start: isize,+ end: isize,+ mut ptr: isize,+ out: &mut [VoxelValue],+ stride: isize,+ max_distance: isize,+ ) {+ let mut i = start;+ let mut count = 0;++ while count < max_distance && i < end {+ if out[ptr as usize] == VoxelValue::PrimitiveUndefined {+ out[ptr as usize] = primitive_undefined_value_to_set;+ } else if out[ptr as usize] == VoxelValue::PrimitiveOnSurface {+ out[ptr as usize] = on_surface_value_to_set;+ break;+ } else {+ break;+ }++ i += 1;+ ptr += stride;+ count += 1;+ }+ }++ fn walk_backward(+ primitive_undefined_value_to_set: VoxelValue,+ on_surface_value_to_set: VoxelValue,+ start: isize,+ end: isize,+ mut ptr: isize,+ out: &mut [VoxelValue],+ stride: isize,+ max_distance: isize,+ ) {+ let mut i = start;+ let mut count = 0;++ while count < max_distance && i >= end {+ if out[ptr as usize] == VoxelValue::PrimitiveUndefined {+ out[ptr as usize] = primitive_undefined_value_to_set;+ } else if out[ptr as usize] == VoxelValue::PrimitiveOnSurface {+ out[ptr as usize] = on_surface_value_to_set;+ break;+ } else {+ break;+ }++ i -= 1;+ ptr -= stride;+ count += 1;+ }+ }++ fn propagate_values(+ &mut self,+ inside_surface_value_to_walk: VoxelValue,+ inside_surface_value_to_set: VoxelValue,+ on_surface_value_to_walk: Option<VoxelValue>,+ on_surface_value_to_set: VoxelValue,+ ) -> bool {+ let mut voxels_walked;+ let mut walked_at_least_once = false;+ let i0 = self.resolution[0];+ let j0 = self.resolution[1];+ #[cfg(feature = "dim2")]+ let k0 = 1;+ #[cfg(feature = "dim3")]+ let k0 = self.resolution[2];++ // Avoid striding too far in each direction to stay in L1 cache as much as possible.+ // The cache size required for the walk is roughly (4 * walk_distance * 64) since+ // the k direction doesn't count as it's walking byte per byte directly in a cache lines.+ // ~16k is required for a walk distance of 64 in each directions.+ let walk_distance = 64;++ // using the stride directly instead of calling get_voxel for each iterations saves+ // a lot of multiplications and pipeline stalls due to values dependencies on imul.+ let istride = self.voxel_index(1, 0, 0) as isize - self.voxel_index(0, 0, 0) as isize;+ let jstride = self.voxel_index(0, 1, 0) as isize - self.voxel_index(0, 0, 0) as isize;+ #[cfg(feature = "dim3")]+ let kstride = self.voxel_index(0, 0, 1) as isize - self.voxel_index(0, 0, 0) as isize;++ // It might seem counter intuitive to go over the whole voxel range multiple times+ // but since we do the run in memory order, it leaves us with far fewer cache misses+ // than a BFS algorithm and it has the additional benefit of not requiring us to+ // store and manipulate a fifo for recursion that might become huge when the number+ // of voxels is large.+ // This will outperform the BFS algorithm by several orders of magnitude in practice.+ loop {+ voxels_walked = 0;++ for i in 0..i0 {+ for j in 0..j0 {+ for k in 0..k0 {+ let idx = self.voxel_index(i, j, k) as isize;+ let voxel = self.voxel_mut(i, j, k);++ if *voxel == inside_surface_value_to_walk {+ voxels_walked += 1;+ walked_at_least_once = true;+ *voxel = inside_surface_value_to_set;+ } else if Some(*voxel) != on_surface_value_to_walk {+ continue;+ }++ // walk in each direction to mark other voxel that should be walked.+ // this will generate a 3d pattern that will help the overall+ // algorithm converge faster while remaining cache friendly.+ #[cfg(feature = "dim3")]+ Self::walk_forward(+ inside_surface_value_to_walk,+ on_surface_value_to_set,+ k as isize + 1,+ k0 as isize,+ idx + kstride,+ &mut self.values,+ kstride,+ walk_distance,+ );+ #[cfg(feature = "dim3")]+ Self::walk_backward(+ inside_surface_value_to_walk,+ on_surface_value_to_set,+ k as isize - 1,+ 0,+ idx - kstride,+ &mut self.values,+ kstride,+ walk_distance,+ );++ Self::walk_forward(+ inside_surface_value_to_walk,+ on_surface_value_to_set,+ j as isize + 1,+ j0 as isize,+ idx + jstride,+ &mut self.values,+ jstride,+ walk_distance,+ );+ Self::walk_backward(+ inside_surface_value_to_walk,+ on_surface_value_to_set,+ j as isize - 1,+ 0,+ idx - jstride,+ &mut self.values,+ jstride,+ walk_distance,+ );++ Self::walk_forward(+ inside_surface_value_to_walk,+ on_surface_value_to_set,+ (i + 1) as isize,+ i0 as isize,+ idx + istride,+ &mut self.values,+ istride,+ walk_distance,+ );+ Self::walk_backward(+ inside_surface_value_to_walk,+ on_surface_value_to_set,+ i as isize - 1,+ 0,+ idx - istride,+ &mut self.values,+ istride,+ walk_distance,+ );+ }+ }+ }++ if voxels_walked == 0 {+ break;+ }+ }++ walked_at_least_once+ }++ fn replace_value(&mut self, current_value: VoxelValue, new_value: VoxelValue) {+ for voxel in &mut self.values {+ if *voxel == current_value {+ *voxel = new_value;+ }+ }+ }++ /// Naive conversion of all the voxels with the given `value` to a triangle-mesh.+ ///+ /// This conversion is extremely naive: it will simply collect all the 12 triangles forming+ /// the faces of each voxel. No actual boundary extraction is done.+ #[cfg(feature = "dim3")]+ pub fn to_trimesh(&self, value: VoxelValue) -> (Vec<Vector>, Vec<[u32; DIM]>) {+ let mut vertices = Vec::new();+ let mut indices = Vec::new();++ for i in 0..self.resolution[0] {+ for j in 0..self.resolution[1] {+ for k in 0..self.resolution[2] {+ let voxel = self.voxel(i, j, k);++ if voxel == value {+ let ijk = Vector::new(i as Real, j as Real, k as Real);++ let shifts = [+ Vector::new(-0.5, -0.5, -0.5),+ Vector::new(0.5, -0.5, -0.5),+ Vector::new(0.5, 0.5, -0.5),+ Vector::new(-0.5, 0.5, -0.5),+ Vector::new(-0.5, -0.5, 0.5),+ Vector::new(0.5, -0.5, 0.5),+ Vector::new(0.5, 0.5, 0.5),+ Vector::new(-0.5, 0.5, 0.5),+ ];++ for shift in &shifts {+ vertices.push(self.origin + (ijk + shift) * self.scale);+ }++ let s = vertices.len() as u32;+ indices.push([s, s + 2, s + 1]);+ indices.push([s, s + 3, s + 2]);+ indices.push([s + 4, s + 5, s + 6]);+ indices.push([s + 4, s + 6, s + 7]);+ indices.push([s + 7, s + 6, s + 2]);+ indices.push([s + 7, s + 2, s + 3]);+ indices.push([s + 4, s + 1, s + 5]);+ indices.push([s + 4, s, s + 1]);+ indices.push([s + 6, s + 5, s + 1]);+ indices.push([s + 6, s + 1, s + 2]);+ indices.push([s + 7, s, s + 4]);+ indices.push([s + 7, s + 3, s]);+ }+ }+ }+ }++ (vertices, indices)+ }+}++impl From<VoxelizedVolume> for VoxelSet {+ fn from(mut shape: VoxelizedVolume) -> Self {+ let mut curr_intersection_index = 0;+ let mut vset = VoxelSet::new();+ let mut vset_intersections = Vec::new();+ vset.origin = shape.origin;+ vset.scale = shape.scale;++ #[cfg(feature = "dim2")]+ let k1 = 1;+ #[cfg(feature = "dim3")]+ let k1 = shape.resolution[2];++ for i in 0..shape.resolution[0] {+ for j in 0..shape.resolution[1] {+ for k in 0..k1 {+ let id = shape.voxel_index(i, j, k) as usize;+ let value = shape.values[id];+ #[cfg(feature = "dim2")]+ let coords = IVector::new(i as Int, j as Int);+ #[cfg(feature = "dim3")]+ let coords = IVector::new(i as Int, j as Int, k as Int);++ if value == VoxelValue::PrimitiveInsideSurface {+ let voxel = Voxel {+ coords,+ is_on_surface: false,+ intersections_range: (curr_intersection_index, curr_intersection_index),+ };+ vset.voxels.push(voxel);+ } else if value == VoxelValue::PrimitiveOnSurface {+ let mut voxel = Voxel {+ coords,+ is_on_surface: true,+ intersections_range: (curr_intersection_index, curr_intersection_index),+ };++ if !shape.primitive_intersections.is_empty() {+ let num_intersections =+ shape.data[id].num_primitive_intersections as usize;+ // We store the index where we should write the intersection on the+ // vset into num_primitive_intersections. That way we can reuse it+ // afterwards when copying the set of intersection into a single+ // flat Vec.+ shape.data[id].num_primitive_intersections =+ curr_intersection_index as u32;+ curr_intersection_index += num_intersections;+ voxel.intersections_range.1 = curr_intersection_index;+ }++ vset.voxels.push(voxel);+ }+ }+ }+ }++ if !shape.primitive_intersections.is_empty() {+ vset_intersections.resize(shape.primitive_intersections.len(), 0);+ for (voxel_id, prim_id) in shape.primitive_intersections {+ let num_inter = &mut shape.data[voxel_id as usize].num_primitive_intersections;+ vset_intersections[*num_inter as usize] = prim_id;+ *num_inter += 1;+ }+ }++ vset.intersections = Arc::new(vset_intersections);++ vset+ }+}++/*+fn traceRay(+ mesh: &RaycastMesh,+ start: Real,+ dir: Vector,+ inside_count: &mut u32,+ outside_count: &mut u32,+) {+ let out_t;+ let u;+ let v;+ let w;+ let face_sign;+ let face_index;+ let hit = raycast_mesh.raycast(start, dir, out_t, u, v, w, face_sign, face_index);++ if hit {+ if face_sign >= 0 {+ *inside_count += 1;+ } else {+ *outside_count += 1;+ }+ }+}+++fn raycast_fill(volume: &Volume, raycast_mesh: &RaycastMesh) {+if !raycast_mesh {+ return;+}++let scale = volume.scale;+let bmin = volume.min_bb;++let i0 = volume.resolution[0];+let j0 = volume.resolution[1];+let k0 = volume.resolution[2];++for i in 0..i0 {+ for j in 0..j0 {+ for k in 0..k0 {+ let voxel = volume.get_voxel(i, j, k);++ if voxel != VoxelValue::PrimitiveOnSurface {+ let start = Vector::new(+ i as Real * scale + bmin[0],+ j as Real * scale + bmin[1],+ k as Real * scale + bmin[2],+ );++ let mut inside_count = 0;+ let mut outside_count = 0;++ let directions = [+ Vector::X,+ -Vector::X,+ Vector::Y,+ -Vector::Y,+ Vector::Z,+ -Vector::Z,+ ];++ for r in 0..6 {+ traceRay(+ raycast_mesh,+ start,+ &directions[r * 3],+ &mut inside_count,+ &mut outside_count,+ );++ // Early out if we hit the outside of the mesh+ if outside_count != 0 {+ break;+ }++ // Early out if we accumulated 3 inside hits+ if inside_count >= 3 {+ break;+ }+ }++ if outside_count == 0 && inside_count >= 3 {+ volume.set_voxel(i, j, k, VoxelValue::PrimitiveInsideSurface);+ } else {+ volume.set_voxel(i, j, k, VoxelValue::PrimitiveOutsideSurface);+ }+ }+ }+ }+}+}+ */diff --git a/renderer/third_party/parry3d/src/transformation/wavefront.rs b/renderer/third_party/parry3d/src/transformation/wavefront.rsnew file mode 100644index 0000000..0f63731--- /dev/null+++ b/renderer/third_party/parry3d/src/transformation/wavefront.rs@@ -0,0 +1,43 @@+use crate::shape::TriMesh;+use alloc::{string::ToString, vec};+use obj::{Group, IndexTuple, ObjData, ObjError, Object, SimplePolygon};+use std::path::PathBuf;++impl TriMesh {+ /// Outputs a Wavefront (`.obj`) file at the given path.+ ///+ /// This function is enabled by the `wavefront` feature flag.+ pub fn to_obj_file(&self, path: &PathBuf) -> Result<(), ObjError> {+ let mut file = std::fs::File::create(path).unwrap();++ ObjData {+ #[expect(clippy::unnecessary_cast)]+ position: self+ .vertices()+ .iter()+ .map(|v| [v.x as f32, v.y as f32, v.z as f32])+ .collect(),+ objects: vec![Object {+ groups: vec![Group {+ polys: self+ .indices()+ .iter()+ .map(|tri| {+ SimplePolygon(vec![+ IndexTuple(tri[0] as usize, None, None),+ IndexTuple(tri[1] as usize, None, None),+ IndexTuple(tri[2] as usize, None, None),+ ])+ })+ .collect(),+ name: "".to_string(),+ index: 0,+ material: None,+ }],+ name: "".to_string(),+ }],+ ..Default::default()+ }+ .write_to_buf(&mut file)+ }+}diff --git a/renderer/third_party/parry3d/src/utils/array2.rs b/renderer/third_party/parry3d/src/utils/array2.rsnew file mode 100644index 0000000..70a220a--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/array2.rs@@ -0,0 +1,127 @@+use alloc::{vec, vec::Vec};+use core::ops::{Index, IndexMut};+use num::{Bounded, Zero};++#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]+#[derive(Debug, Clone)]+/// A column-major 2D array.+pub struct Array2<T> {+ nrows: usize,+ ncols: usize,+ data: Vec<T>,+}++impl<T> Array2<T> {+ /// Creates a new 2D array from the given dimensions and data.+ #[inline]+ pub fn new(nrows: usize, ncols: usize, data: Vec<T>) -> Self {+ assert_eq!(data.len(), ncols * nrows);+ Array2 { ncols, nrows, data }+ }++ /// Creates a new 2D array filled with copies of `elt`.+ #[inline]+ pub fn repeat(nrows: usize, ncols: usize, elt: T) -> Self+ where+ T: Copy,+ {+ Array2 {+ nrows,+ ncols,+ data: vec![elt; ncols * nrows],+ }+ }++ /// Creates a new 2D array filled with zeros.+ #[inline]+ pub fn zeros(nrows: usize, ncols: usize) -> Self+ where+ T: Copy + Zero,+ {+ Self::repeat(nrows, ncols, T::zero())+ }++ /// Computes the flat index for the given row and column.+ #[inline]+ pub fn flat_index(&self, i: usize, j: usize) -> usize {+ i + j * self.nrows+ }++ /// Returns a reference to the underlying data.+ #[inline]+ pub fn data(&self) -> &[T] {+ &self.data+ }++ /// Returns a mutable reference to the underlying data.+ #[inline]+ pub fn data_mut(&mut self) -> &mut [T] {+ &mut self.data+ }++ /// Returns the number of rows.+ #[inline]+ pub fn nrows(&self) -> usize {+ self.nrows+ }++ /// Returns the number of columns.+ #[inline]+ pub fn ncols(&self) -> usize {+ self.ncols+ }++ /// Returns the minimum element of the array.+ #[inline]+ pub fn min(&self) -> T+ where+ T: Copy + Bounded + PartialOrd,+ {+ self.data+ .iter()+ .fold(Bounded::max_value(), |a, b| if a < *b { a } else { *b })+ }++ /// Returns the maximum element of the array.+ #[inline]+ pub fn max(&self) -> T+ where+ T: Copy + Bounded + PartialOrd,+ {+ self.data+ .iter()+ .fold(Bounded::min_value(), |a, b| if a > *b { a } else { *b })+ }++ /// Creates a new 2D array from a function.+ #[inline]+ pub fn from_fn(nrows: usize, ncols: usize, f: impl Fn(usize, usize) -> T) -> Self {+ let mut data = Vec::with_capacity(ncols * nrows);++ for j in 0..ncols {+ for i in 0..nrows {+ data.push(f(i, j));+ }+ }+ data.shrink_to_fit();+ Self { nrows, ncols, data }+ }+}++impl<T> Index<(usize, usize)> for Array2<T> {+ type Output = T;++ #[inline]+ fn index(&self, index: (usize, usize)) -> &Self::Output {+ let fid = self.flat_index(index.0, index.1);+ &self.data[fid]+ }+}++impl<T> IndexMut<(usize, usize)> for Array2<T> {+ #[inline]+ fn index_mut(&mut self, index: (usize, usize)) -> &mut Self::Output {+ let fid = self.flat_index(index.0, index.1);+ &mut self.data[fid]+ }+}diff --git a/renderer/third_party/parry3d/src/utils/as_bytes.rs b/renderer/third_party/parry3d/src/utils/as_bytes.rsnew file mode 100644index 0000000..d47e405--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/as_bytes.rs@@ -0,0 +1,28 @@+use core::mem;+use core::slice;++use crate::math::{Real, Vector2, Vector3};++/// Trait that transforms thing to a slice of u8.+pub trait AsBytes {+ /// Converts `self` to a slice of bytes.+ fn as_bytes(&self) -> &[u8];+}++macro_rules! as_bytes_impl(+ ($T: ty, $dimension: expr) => (+ impl AsBytes for $T {+ #[inline(always)]+ fn as_bytes(&self) -> &[u8] {+ unsafe {+ slice::from_raw_parts(self as *const $T as *const u8, mem::size_of::<Real>() * $dimension)+ }+ }+ }+ )+);++as_bytes_impl!(Vector2, 2);+as_bytes_impl!(Vector3, 3);++// TODO: implement for all `T: Copy` instead?diff --git a/renderer/third_party/parry3d/src/utils/ccw_face_normal.rs b/renderer/third_party/parry3d/src/utils/ccw_face_normal.rsnew file mode 100644index 0000000..07fe8f3--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/ccw_face_normal.rs@@ -0,0 +1,26 @@+use crate::math::Vector;++/// Computes the direction pointing toward the right-hand-side of an oriented segment.+///+/// Returns `None` if the segment is degenerate.+#[inline]+#[cfg(feature = "dim2")]+pub fn ccw_face_normal(pts: [Vector; 2]) -> Option<Vector> {+ let ab = pts[1] - pts[0];+ let res = Vector::new(ab.y, -ab.x);++ res.try_normalize()+}++/// Computes the normal of a counter-clock-wise triangle.+///+/// Returns `None` if the triangle is degenerate.+#[inline]+#[cfg(feature = "dim3")]+pub fn ccw_face_normal(pts: [Vector; 3]) -> Option<Vector> {+ let ab = pts[1] - pts[0];+ let ac = pts[2] - pts[0];+ let res = ab.cross(ac);++ res.try_normalize()+}diff --git a/renderer/third_party/parry3d/src/utils/center.rs b/renderer/third_party/parry3d/src/utils/center.rsnew file mode 100644index 0000000..44e92bd--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/center.rs@@ -0,0 +1,97 @@+use crate::math::{Real, Vector};++/// Computes the geometric center (centroid) of a set of points.+///+/// The center is calculated by averaging all the point coordinates. This is also known as+/// the centroid or barycenter of the point cloud. All points are weighted equally.+///+/// # Arguments+///+/// * `pts` - A slice of points. Must contain at least one point.+///+/// # Returns+///+/// The geometric center as a `Vector`.+///+/// # Panics+///+/// Panics if the input slice is empty.+///+/// # Examples+///+/// ## 2D Example+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::utils::center;+/// use parry2d::math::Vector;+///+/// let points = vec![+/// Vector::new(0.0, 0.0),+/// Vector::new(2.0, 0.0),+/// Vector::new(2.0, 2.0),+/// Vector::new(0.0, 2.0),+/// ];+///+/// let c = center(&points);+///+/// // The center of a square is at its middle+/// assert!((c.x - 1.0).abs() < 1e-6);+/// assert!((c.y - 1.0).abs() < 1e-6);+/// # }+/// ```+///+/// ## 3D Example+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::utils::center;+/// use parry3d::math::Vector;+///+/// let points = vec![+/// Vector::new(0.0, 0.0, 0.0),+/// Vector::new(4.0, 0.0, 0.0),+/// Vector::new(0.0, 4.0, 0.0),+/// ];+///+/// let c = center(&points);+///+/// // The center of these three points+/// assert!((c.x - 4.0 / 3.0).abs() < 1e-6);+/// assert!((c.y - 4.0 / 3.0).abs() < 1e-6);+/// assert!(c.z.abs() < 1e-6);+/// # }+/// ```+///+/// ## Single Vector+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::utils::center;+/// use parry2d::math::Vector;+///+/// let points = vec![Vector::new(5.0, 10.0)];+/// let c = center(&points);+///+/// // The center of a single point is the point itself+/// assert_eq!(c, points[0]);+/// # }+/// ```+#[inline]+pub fn center(pts: &[Vector]) -> Vector {+ assert!(+ !pts.is_empty(),+ "Cannot compute the center of less than 1 point."+ );++ let denom: Real = 1.0 / (pts.len() as Real);++ let mut piter = pts.iter();+ let mut res = *piter.next().unwrap() * denom;++ for pt in piter {+ res += pt * denom;+ }++ res+}diff --git a/renderer/third_party/parry3d/src/utils/cleanup.rs b/renderer/third_party/parry3d/src/utils/cleanup.rsnew file mode 100644index 0000000..7b38b0f--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/cleanup.rs@@ -0,0 +1,34 @@+use crate::math::Vector;+use alloc::vec::Vec;+use core::iter;++/// Given an index buffer, remove from `points` every point that is not indexed.+pub fn remove_unused_points(points: &mut Vec<Vector>, idx: &mut [[u32; 3]]) {+ let mut used: Vec<bool> = iter::repeat_n(false, points.len()).collect();+ let mut remap: Vec<usize> = (0..points.len()).collect();+ let used = &mut used[..];+ let remap = &mut remap[..];++ for i in idx.iter() {+ used[i[0] as usize] = true;+ used[i[1] as usize] = true;+ used[i[2] as usize] = true;+ }++ let mut i = 0;+ while i != points.len() {+ if !used[i] {+ let _ = points.swap_remove(i);+ remap[points.len()] = i;+ used[i] = used[points.len()];+ } else {+ i += 1;+ }+ }++ for id in idx.iter_mut() {+ id[0] = remap[id[0] as usize] as u32;+ id[1] = remap[id[1] as usize] as u32;+ id[2] = remap[id[2] as usize] as u32;+ }+}diff --git a/renderer/third_party/parry3d/src/utils/consts.rs b/renderer/third_party/parry3d/src/utils/consts.rsnew file mode 100644index 0000000..2d0797c--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/consts.rs@@ -0,0 +1,13 @@+#![allow(clippy::excessive_precision)] // Clippy will complain in f32 mode, but we also need these consts for f64.++use crate::math::Real;++// pub(crate) const SIN_10_DEGREES: Real = 0.17364817766;+// pub(crate) const COS_10_DEGREES: Real = 0.98480775301;+// pub(crate) const COS_45_DEGREES: Real = 0.70710678118;+// pub(crate) const SIN_45_DEGREES: Real = COS_45_DEGREES;+pub(crate) const COS_1_DEGREES: Real = 0.99984769515;+// pub(crate) const COS_5_DEGREES: Real = 0.99619469809;+pub(crate) const COS_FRAC_PI_8: Real = 0.92387953251;+#[cfg(feature = "dim2")]+pub(crate) const SIN_FRAC_PI_8: Real = 0.38268343236;diff --git a/renderer/third_party/parry3d/src/utils/cov.rs b/renderer/third_party/parry3d/src/utils/cov.rsnew file mode 100644index 0000000..b0c8966--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/cov.rs@@ -0,0 +1,22 @@+use crate::math::{Matrix, Real, Vector, VectorExt};++/// Computes the covariance matrix of a set of points.+pub fn cov(pts: &[Vector]) -> Matrix {+ center_cov(pts).1+}++/// Computes the center and the covariance matrix of a set of points.+pub fn center_cov(pts: &[Vector]) -> (Vector, Matrix) {+ let center = crate::utils::center(pts);+ let mut cov = Matrix::ZERO;+ let normalizer: Real = 1.0 / (pts.len() as Real);++ for p in pts.iter() {+ let cp = *p - center;+ let cp_scaled = cp * normalizer;+ // Compute outer product: cp * cp_scaled^T+ cov += cp.kronecker(cp_scaled);+ }++ (center, cov)+}diff --git a/renderer/third_party/parry3d/src/utils/eigen2.rs b/renderer/third_party/parry3d/src/utils/eigen2.rsnew file mode 100644index 0000000..3f26e31--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/eigen2.rs@@ -0,0 +1,7 @@+//! Re-export of SymmetricEigen2 from glamx.++#[cfg(feature = "f32")]+pub use glamx::SymmetricEigen2;++#[cfg(feature = "f64")]+pub use glamx::DSymmetricEigen2 as SymmetricEigen2;diff --git a/renderer/third_party/parry3d/src/utils/eigen3.rs b/renderer/third_party/parry3d/src/utils/eigen3.rsnew file mode 100644index 0000000..70202b0--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/eigen3.rs@@ -0,0 +1,7 @@+//! Re-export of SymmetricEigen3 from glamx.++#[cfg(feature = "f32")]+pub use glamx::SymmetricEigen3;++#[cfg(feature = "f64")]+pub use glamx::DSymmetricEigen3 as SymmetricEigen3;diff --git a/renderer/third_party/parry3d/src/utils/fx_hasher.rs b/renderer/third_party/parry3d/src/utils/fx_hasher.rsnew file mode 100644index 0000000..17c3777--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/fx_hasher.rs@@ -0,0 +1,80 @@+//! FxHasher taken from rustc_hash, except that it does not depend on the pointer size.++const K: u32 = 0x9e3779b9;++/// This is the same as FxHasher, but with the guarantee that the internal hash is+/// an u32 instead of something that depends on the platform.+pub struct FxHasher32 {+ hash: u32,+}++impl Default for FxHasher32 {+ #[inline]+ fn default() -> FxHasher32 {+ FxHasher32 { hash: 0 }+ }+}++impl FxHasher32 {+ #[inline]+ fn add_to_hash(&mut self, i: u32) {+ use core::ops::BitXor;+ self.hash = self.hash.rotate_left(5).bitxor(i).wrapping_mul(K);+ }+}++impl core::hash::Hasher for FxHasher32 {+ #[inline]+ fn write(&mut self, mut bytes: &[u8]) {+ let read_u32 = |bytes: &[u8]| u32::from_ne_bytes(bytes[..4].try_into().unwrap());+ let mut hash = FxHasher32 { hash: self.hash };+ assert!(size_of::<u32>() <= 8);+ while bytes.len() >= size_of::<u32>() {+ hash.add_to_hash(read_u32(bytes));+ bytes = &bytes[size_of::<u32>()..];+ }+ if (size_of::<u32>() > 4) && (bytes.len() >= 4) {+ hash.add_to_hash(u32::from_ne_bytes(bytes[..4].try_into().unwrap()));+ bytes = &bytes[4..];+ }+ if (size_of::<u32>() > 2) && bytes.len() >= 2 {+ hash.add_to_hash(u16::from_ne_bytes(bytes[..2].try_into().unwrap()) as u32);+ bytes = &bytes[2..];+ }+ if (size_of::<u32>() > 1) && !bytes.is_empty() {+ hash.add_to_hash(bytes[0] as u32);+ }+ self.hash = hash.hash;+ }++ #[inline]+ fn write_u8(&mut self, i: u8) {+ self.add_to_hash(i as u32);+ }++ #[inline]+ fn write_u16(&mut self, i: u16) {+ self.add_to_hash(i as u32);+ }++ #[inline]+ fn write_u32(&mut self, i: u32) {+ self.add_to_hash(i);+ }++ #[inline]+ fn write_u64(&mut self, i: u64) {+ self.add_to_hash(i as u32);+ self.add_to_hash((i >> 32) as u32);+ }++ #[inline]+ fn write_usize(&mut self, i: usize) {+ self.add_to_hash(i as u32);+ }++ #[inline]+ fn finish(&self) -> u64 {+ self.hash as u64+ }+}diff --git a/renderer/third_party/parry3d/src/utils/hashable_partial_eq.rs b/renderer/third_party/parry3d/src/utils/hashable_partial_eq.rsnew file mode 100644index 0000000..3f20975--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/hashable_partial_eq.rs@@ -0,0 +1,31 @@+use crate::utils::AsBytes;+use core::hash::{Hash, Hasher};++/// A structure that implements `Eq` and is hashable even if the wrapped data implements only+/// `PartialEq`.+#[derive(PartialEq, Clone, Debug)]+pub struct HashablePartialEq<T> {+ value: T,+}++impl<T> HashablePartialEq<T> {+ /// Creates a new `HashablePartialEq`. Please make sure that you really+ /// want to transform the wrapped object's partial equality to an equivalence relation.+ pub fn new(value: T) -> HashablePartialEq<T> {+ HashablePartialEq { value }+ }++ /// Gets the wrapped value.+ pub fn unwrap(self) -> T {+ self.value+ }+}++impl<T: PartialEq> Eq for HashablePartialEq<T> {}++impl<T: AsBytes> Hash for HashablePartialEq<T> {+ #[inline]+ fn hash<H: Hasher>(&self, state: &mut H) {+ state.write(self.value.as_bytes())+ }+}diff --git a/renderer/third_party/parry3d/src/utils/hashmap.rs b/renderer/third_party/parry3d/src/utils/hashmap.rsnew file mode 100644index 0000000..959f358--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/hashmap.rs@@ -0,0 +1,63 @@+//! A hash-map that behaves deterministically when the+//! `enhanced-determinism` feature is enabled.++#[cfg(all(not(feature = "enhanced-determinism"), feature = "serde-serialize"))]+use hashbrown::hash_map::HashMap as StdHashMap;+#[cfg(all(feature = "enhanced-determinism", feature = "serde-serialize"))]+use indexmap::IndexMap as StdHashMap;++/// Serializes only the capacity of a hash-map instead of its actual content.+#[cfg(feature = "serde-serialize")]+pub fn serialize_hashmap_capacity<S: serde::Serializer, K, V, H: core::hash::BuildHasher>(+ map: &StdHashMap<K, V, H>,+ s: S,+) -> Result<S::Ok, S::Error> {+ s.serialize_u64(map.capacity() as u64)+}++/// Creates a new hash-map with its capacity deserialized from `d`.+#[cfg(feature = "serde-serialize")]+pub fn deserialize_hashmap_capacity<+ 'de,+ D: serde::Deserializer<'de>,+ K,+ V,+ H: core::hash::BuildHasher + Default,+>(+ d: D,+) -> Result<StdHashMap<K, V, H>, D::Error> {+ struct CapacityVisitor;+ impl serde::de::Visitor<'_> for CapacityVisitor {+ type Value = u64;++ fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {+ write!(formatter, "an integer between 0 and 2^64")+ }++ fn visit_u64<E: serde::de::Error>(self, val: u64) -> Result<Self::Value, E> {+ Ok(val)+ }+ }++ let capacity = d.deserialize_u64(CapacityVisitor)? as usize;+ Ok(StdHashMap::with_capacity_and_hasher(+ capacity,+ Default::default(),+ ))+}++/*+ * FxHasher taken from rustc_hash, except that it does not depend on the pointer size.+ */+/// Deterministic hashmap using [`indexmap::IndexMap`]+#[cfg(feature = "enhanced-determinism")]+pub type FxHashMap32<K, V> =+ indexmap::IndexMap<K, V, core::hash::BuildHasherDefault<super::fx_hasher::FxHasher32>>;+#[cfg(feature = "enhanced-determinism")]+pub use {self::FxHashMap32 as HashMap, indexmap::map::Entry};++#[cfg(not(feature = "enhanced-determinism"))]+pub use hashbrown::hash_map::Entry;+/// Hashmap using [`hashbrown::HashMap`]+#[cfg(not(feature = "enhanced-determinism"))]+pub type HashMap<K, V> = hashbrown::hash_map::HashMap<K, V, foldhash::fast::FixedState>;diff --git a/renderer/third_party/parry3d/src/utils/hashset.rs b/renderer/third_party/parry3d/src/utils/hashset.rsnew file mode 100644index 0000000..d6acb5a--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/hashset.rs@@ -0,0 +1,60 @@+//! A hash-map that behaves deterministically when the+//! `enhanced-determinism` feature is enabled.++#[cfg(all(feature = "enhanced-determinism", feature = "serde-serialize"))]+use indexmap::IndexSet as StdHashSet;+#[cfg(all(not(feature = "enhanced-determinism"), feature = "serde-serialize"))]+use std::collections::HashSet as StdHashSet;++/// Serializes only the capacity of a hash-set instead of its actual content.+#[cfg(feature = "serde-serialize")]+pub fn serialize_hashset_capacity<S: serde::Serializer, K, H: core::hash::BuildHasher>(+ set: &StdHashSet<K, H>,+ s: S,+) -> Result<S::Ok, S::Error> {+ s.serialize_u64(set.capacity() as u64)+}++/// Creates a new hash-set with its capacity deserialized from `d`.+#[cfg(feature = "serde-serialize")]+pub fn deserialize_hashset_capacity<+ 'de,+ D: serde::Deserializer<'de>,+ K,+ V,+ H: core::hash::BuildHasher + Default,+>(+ d: D,+) -> Result<StdHashSet<K, H>, D::Error> {+ struct CapacityVisitor;+ impl serde::de::Visitor<'_> for CapacityVisitor {+ type Value = u64;++ fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {+ write!(formatter, "an integer between 0 and 2^64")+ }++ fn visit_u64<E: serde::de::Error>(self, val: u64) -> Result<Self::Value, E> {+ Ok(val)+ }+ }++ let capacity = d.deserialize_u64(CapacityVisitor)? as usize;+ Ok(StdHashSet::with_capacity_and_hasher(+ capacity,+ Default::default(),+ ))+}++/// Deterministic hashset using [`indexmap::IndexSet`]+#[cfg(feature = "enhanced-determinism")]+pub type FxHashSet32<K> =+ indexmap::IndexSet<K, core::hash::BuildHasherDefault<super::fx_hasher::FxHasher32>>;+#[cfg(feature = "enhanced-determinism")]+pub use self::FxHashSet32 as HashSet;++#[cfg(not(feature = "enhanced-determinism"))]+pub use hashbrown::hash_set::Entry;+/// Hashset using [`hashbrown::HashSet`]+#[cfg(not(feature = "enhanced-determinism"))]+pub type HashSet<K> = hashbrown::hash_set::HashSet<K, foldhash::fast::FixedState>;diff --git a/renderer/third_party/parry3d/src/utils/interval.rs b/renderer/third_party/parry3d/src/utils/interval.rsnew file mode 100644index 0000000..63abebe--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/interval.rs@@ -0,0 +1,560 @@+// "Complete Interval Arithmetic and its Implementation on the Computer"+// Ulrich W. Kulisch+use alloc::{vec, vec::Vec};+use core::ops::{Add, AddAssign, Div, Mul, MulAssign, Neg, Sub, SubAssign};+use num::{One, Zero};+use num_traits::AsPrimitive;+use simba::scalar::RealField;++/// A derivable valued function which can be bounded on intervals.+pub trait IntervalFunction<T> {+ /// Evaluate the function at `t`.+ fn eval(&self, t: T) -> T;+ /// Bounds all the values of this function on the interval `t`.+ fn eval_interval(&self, t: Interval<T>) -> Interval<T>;+ /// Bounds all the values of the gradient of this function on the interval `t`.+ fn eval_interval_gradient(&self, t: Interval<T>) -> Interval<T>;+}++/// Execute the Interval Newton Method to isolate all the roots of the given nonlinear function.+///+/// The results are stored in `results`. The `candidate` buffer is just a workspace buffer used+/// to avoid allocations.+pub fn find_root_intervals_to<T: Copy + PartialOrd + RealField>(+ function: &impl IntervalFunction<T>,+ init: Interval<T>,+ min_interval_width: T,+ min_image_width: T,+ max_recursions: usize,+ results: &mut Vec<Interval<T>>,+ candidates: &mut Vec<(Interval<T>, usize)>,+) where+ f64: AsPrimitive<T>,+{+ candidates.clear();++ let push_candidate = |candidate,+ recursion,+ results: &mut Vec<Interval<T>>,+ candidates: &mut Vec<(Interval<T>, usize)>| {+ let candidate_image = function.eval_interval(candidate);+ let is_small_range =+ candidate.width() < min_interval_width || candidate_image.width() < min_image_width;++ if candidate_image.contains(T::zero()) {+ if recursion == max_recursions || is_small_range {+ results.push(candidate);+ } else {+ candidates.push((candidate, recursion + 1));+ }+ } else if is_small_range+ && function.eval(candidate.midpoint()).abs() < T::default_epsilon().sqrt()+ {+ // If we have a small range, and we are close to zero,+ // consider that we reached zero.+ results.push(candidate);+ }+ };++ push_candidate(init, 0, results, candidates);++ while let Some((candidate, recursion)) = candidates.pop() {+ // println!(+ // "Candidate: {:?}, recursion: {}, image: {:?}",+ // candidate,+ // recursion,+ // function.eval_interval(candidate)+ // );++ // NOTE: we don't check the max_recursions at the beginning of the+ // loop here because that would make us loose the candidate+ // we just popped.+ let mid = candidate.midpoint();+ let f_mid = function.eval(mid);+ let gradient = function.eval_interval_gradient(candidate);+ let (shift1, shift2) = Interval(f_mid, f_mid) / gradient;++ let new_candidates = [+ (Interval(mid, mid) - shift1).intersect(candidate),+ shift2.and_then(|shift2| (Interval(mid, mid) - shift2).intersect(candidate)),+ ];++ let prev_width = candidate.width();++ for new_candidate in new_candidates.iter().flatten() {+ if new_candidate.width() > prev_width * 0.75.as_() {+ // If the new candidate range is still quite big compared to+ // new candidate, split it to accelerate the search.+ let [a, b] = new_candidate.split();+ push_candidate(a, recursion, results, candidates);+ push_candidate(b, recursion, results, candidates);+ } else {+ push_candidate(*new_candidate, recursion, results, candidates);+ }+ }+ }+}++/// Execute the Interval Newton Method to isolate all the roots of the given nonlinear function.+pub fn find_root_intervals<T: Copy + PartialOrd + RealField>(+ function: &impl IntervalFunction<T>,+ init: Interval<T>,+ min_interval_width: T,+ min_image_width: T,+ max_recursions: usize,+) -> Vec<Interval<T>>+where+ f64: AsPrimitive<T>,+{+ let mut results = vec![];+ let mut candidates = vec![];+ find_root_intervals_to(+ function,+ init,+ min_interval_width,+ min_image_width,+ max_recursions,+ &mut results,+ &mut candidates,+ );+ results+}++/// An interval implementing interval arithmetic.+#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]+pub struct Interval<T>(pub T, pub T);++impl<T> Interval<T> {+ /// Create the interval `[min(a, b), max(a, b)]`.+ #[must_use]+ pub fn sort(a: T, b: T) -> Self+ where+ T: PartialOrd,+ {+ if a < b {+ Self(a, b)+ } else {+ Self(b, a)+ }+ }++ /// Create the interval `[e, e]` (single value).+ #[must_use]+ pub fn splat(e: T) -> Self+ where+ T: Clone,+ {+ Self(e.clone(), e)+ }++ /// Does this interval contain the given value?+ #[must_use]+ pub fn contains(&self, t: T) -> bool+ where+ T: PartialOrd<T>,+ {+ self.0 <= t && self.1 >= t+ }++ /// The width of this interval.+ #[must_use]+ pub fn width(self) -> T::Output+ where+ T: Sub<T>,+ {+ self.1 - self.0+ }++ /// The average of the two interval endpoints.+ #[must_use]+ pub fn midpoint(self) -> T+ where+ T: Copy + Add<T, Output = T> + Div<T, Output = T> + One,+ {+ let two = T::one() + T::one();+ (self.0 + self.1) / two+ }++ /// Splits this interval at its midpoint.+ #[must_use]+ pub fn split(self) -> [Self; 2]+ where+ T: Copy + Add<T, Output = T> + Div<T, Output = T> + One,+ {+ let mid = self.midpoint();+ [Interval(self.0, mid), Interval(mid, self.1)]+ }++ /// Computes a new interval that contains both `self` and `t`.+ #[must_use]+ pub fn enclose(self, t: T) -> Self+ where+ T: PartialOrd,+ {+ if t < self.0 {+ Interval(t, self.1)+ } else if t > self.1 {+ Interval(self.0, t)+ } else {+ self+ }+ }++ /// Computes the intersection between two intervals.+ ///+ /// Returns `None` if the intervals are disjoint.+ #[must_use]+ pub fn intersect(self, rhs: Self) -> Option<Self>+ where+ T: PartialOrd + RealField,+ {+ let result = Interval(self.0.max(rhs.0), self.1.min(rhs.1));++ if result.0 > result.1 {+ // The range is invalid if there is no intersection.+ None+ } else {+ Some(result)+ }+ }++ /// Bounds the image of the`sin` and `cos` functions on this interval.+ #[must_use]+ pub fn sin_cos(self) -> (Self, Self)+ where+ T: Copy + RealField,+ f64: AsPrimitive<T>,+ {+ (self.sin(), self.cos())+ }++ /// Bounds the image of the sinus function on this interval.+ #[must_use]+ pub fn sin(self) -> Self+ where+ T: Copy + RealField,+ f64: AsPrimitive<T>,+ {+ let two_pi = T::two_pi();+ let one = T::one();+ let pi = T::pi();+ let frac_pi_2 = T::frac_pi_2();++ if self.width() >= two_pi {+ Interval(one * (-1.0).as_(), one)+ } else {+ let sin0 = self.0.sin();+ let sin1 = self.1.sin();+ let mut result = Interval::sort(sin0, sin1);++ let orig = (self.0 / two_pi).floor() * two_pi;+ let crit = [orig + frac_pi_2, orig + pi + frac_pi_2];+ let crit_vals = [one, one * (-1.0).as_()];++ for i in 0..2 {+ if self.contains(crit[i]) || self.contains(crit[i] + two_pi) {+ result = result.enclose(crit_vals[i])+ }+ }++ result+ }+ }++ /// Bounds the image of the cosinus function on this interval.+ #[must_use]+ pub fn cos(self) -> Self+ where+ T: Copy + RealField,+ f64: AsPrimitive<T>,+ {+ let two_pi = T::two_pi();+ let one = T::one();+ let pi = T::pi();++ if self.width() >= two_pi {+ Interval(one * (-1.0).as_(), one)+ } else {+ let cos0 = self.0.cos();+ let cos1 = self.1.cos();+ let mut result = Interval::sort(cos0, cos1);++ let orig = (self.0 / two_pi).floor() * two_pi;+ let crit = [orig, orig + pi];+ let crit_vals = [one, one * (-1.0).as_()];++ for i in 0..2 {+ if self.contains(crit[i]) || self.contains(crit[i] + two_pi) {+ result = result.enclose(crit_vals[i])+ }+ }++ result+ }+ }+}++impl<T: Add<T> + Copy> Add<T> for Interval<T> {+ type Output = Interval<<T as Add<T>>::Output>;++ fn add(self, rhs: T) -> Self::Output {+ Interval(self.0 + rhs, self.1 + rhs)+ }+}++impl<T: Add<T>> Add<Interval<T>> for Interval<T> {+ type Output = Interval<<T as Add<T>>::Output>;++ fn add(self, rhs: Self) -> Self::Output {+ Interval(self.0 + rhs.0, self.1 + rhs.1)+ }+}++impl<T: Sub<T> + Copy> Sub<T> for Interval<T> {+ type Output = Interval<<T as Sub<T>>::Output>;++ fn sub(self, rhs: T) -> Self::Output {+ Interval(self.0 - rhs, self.1 - rhs)+ }+}++impl<T: Sub<T> + Copy> Sub<Interval<T>> for Interval<T> {+ type Output = Interval<<T as Sub<T>>::Output>;++ fn sub(self, rhs: Self) -> Self::Output {+ Interval(self.0 - rhs.1, self.1 - rhs.0)+ }+}++impl<T: Neg> Neg for Interval<T> {+ type Output = Interval<T::Output>;++ fn neg(self) -> Self::Output {+ Interval(-self.1, -self.0)+ }+}++impl<T: Mul<T>> Mul<T> for Interval<T>+where+ T: Copy + PartialOrd + Zero,+{+ type Output = Interval<<T as Mul<T>>::Output>;++ fn mul(self, rhs: T) -> Self::Output {+ if rhs < T::zero() {+ Interval(self.1 * rhs, self.0 * rhs)+ } else {+ Interval(self.0 * rhs, self.1 * rhs)+ }+ }+}++impl<T: Mul<T>> Mul<Interval<T>> for Interval<T>+where+ T: Copy + PartialOrd + Zero + RealField,+ <T as Mul<T>>::Output: PartialOrd + RealField,+{+ type Output = Interval<<T as Mul<T>>::Output>;++ fn mul(self, rhs: Self) -> Self::Output {+ let Interval(a1, a2) = self;+ let Interval(b1, b2) = rhs;++ if a2 <= T::zero() {+ if b2 <= T::zero() {+ Interval(a2 * b2, a1 * b1)+ } else if b1 < T::zero() {+ Interval(a1 * b2, a1 * b1)+ } else {+ Interval(a1 * b2, a2 * b1)+ }+ } else if a1 < T::zero() {+ if b2 <= T::zero() {+ Interval(a2 * b1, a1 * b1)+ } else if b1 < T::zero() {+ Interval((a1 * b2).min(b2 * b1), (a1 * b1).max(a2 * b2))+ } else {+ Interval(a1 * b2, a2 * b2)+ }+ } else if b2 <= T::zero() {+ Interval(a2 * b1, a1 * b2)+ } else if b1 < T::zero() {+ Interval(a2 * b1, a2 * b2)+ } else {+ Interval(a1 * b1, a2 * b2)+ }+ }+}++impl<T: Div<T>> Div<Interval<T>> for Interval<T>+where+ T: Copy + One + Zero + PartialOrd + 'static,+ <T as Div<T>>::Output: PartialOrd + RealField,+ f64: AsPrimitive<T>,+{+ type Output = (+ Interval<<T as Div<T>>::Output>,+ Option<Interval<<T as Div<T>>::Output>>,+ );++ fn div(self, rhs: Self) -> Self::Output {+ let infinity = T::one() / T::zero();+ let neg_one: T = (-1.0).as_();+ let neg_infinity = neg_one / T::zero();++ let Interval(a1, a2) = self;+ let Interval(b1, b2) = rhs;++ if b1 <= T::zero() && b2 >= T::zero() {+ // rhs contains T::zero() so we my have to return+ // two intervals.+ if a2 < T::zero() {+ if b2 == T::zero() {+ (Interval(a2 / b1, infinity), None)+ } else if b1 != T::zero() {+ (+ Interval(neg_infinity, a2 / b2),+ Some(Interval(a2 / b1, infinity)),+ )+ } else {+ (Interval(neg_infinity, a2 / b2), None)+ }+ } else if a1 <= T::zero() {+ (Interval(neg_infinity, infinity), None)+ } else if b2 == T::zero() {+ (Interval(neg_infinity, a1 / b1), None)+ } else if b1 != T::zero() {+ (+ Interval(neg_infinity, a1 / b1),+ Some(Interval(a1 / b2, infinity)),+ )+ } else {+ (Interval(a1 / b2, infinity), None)+ }+ } else if a2 <= T::zero() {+ if b2 < T::zero() {+ (Interval(a2 / b1, a1 / b2), None)+ } else {+ (Interval(a1 / b1, a2 / b2), None)+ }+ } else if a1 < T::zero() {+ if b2 < T::zero() {+ (Interval(a2 / b2, a1 / b2), None)+ } else {+ (Interval(a1 / b1, a2 / b1), None)+ }+ } else if b2 < T::zero() {+ (Interval(a2 / b2, a1 / b1), None)+ } else {+ (Interval(a1 / b2, a2 / b1), None)+ }+ }+}++impl<T: Copy + Add<T, Output = T>> AddAssign<Interval<T>> for Interval<T> {+ fn add_assign(&mut self, rhs: Interval<T>) {+ *self = *self + rhs;+ }+}++impl<T: Copy + Sub<T, Output = T>> SubAssign<Interval<T>> for Interval<T> {+ fn sub_assign(&mut self, rhs: Interval<T>) {+ *self = *self - rhs;+ }+}++impl<T: Mul<T, Output = T>> MulAssign<Interval<T>> for Interval<T>+where+ T: Copy + PartialOrd + Zero + RealField,+ <T as Mul<T>>::Output: PartialOrd + RealField,+{+ fn mul_assign(&mut self, rhs: Interval<T>) {+ *self = *self * rhs;+ }+}++impl<T: Zero + Add<T>> Zero for Interval<T> {+ fn zero() -> Self {+ Self(T::zero(), T::zero())+ }++ fn is_zero(&self) -> bool {+ self.0.is_zero() && self.1.is_zero()+ }+}++impl<T: One + Mul<T>> One for Interval<T>+where+ Interval<T>: Mul<Interval<T>, Output = Interval<T>>,+{+ fn one() -> Self {+ Self(T::one(), T::one())+ }+}++#[cfg(test)]+mod test {+ use super::{Interval, IntervalFunction};++ #[test]+ fn roots_sin() {+ struct Sin;++ impl IntervalFunction<f32> for Sin {+ fn eval(&self, t: f32) -> f32 {+ t.sin()+ }++ fn eval_interval(&self, t: Interval<f32>) -> Interval<f32> {+ t.sin()+ }++ fn eval_interval_gradient(&self, t: Interval<f32>) -> Interval<f32> {+ t.cos()+ }+ }++ let function = Sin;+ let two_pi = core::f32::consts::TAU;+ let roots =+ super::find_root_intervals(&function, Interval(0.0, two_pi), 1.0e-5, 1.0e-5, 100);+ assert_eq!(roots.len(), 3);+ }++ #[test]+ fn interval_sin_cos() {+ let a = core::f32::consts::PI / 6.0;+ let b = core::f32::consts::FRAC_PI_2 + core::f32::consts::PI / 6.0;+ let c = core::f32::consts::PI + core::f32::consts::PI / 6.0;+ let d = core::f32::consts::PI + core::f32::consts::FRAC_PI_2 + core::f32::consts::PI / 6.0;+ let two_pi = core::f32::consts::TAU;+ let shifts = [0.0, two_pi * 100.0, -two_pi * 100.0];++ for shift in shifts.iter() {+ // Test sinus.+ assert_eq!(+ Interval(a + *shift, b + *shift).sin(),+ Interval((a + *shift).sin(), 1.0)+ );+ assert_eq!(+ Interval(a + *shift, c + *shift).sin(),+ Interval((c + *shift).sin(), 1.0)+ );+ assert_eq!(Interval(a + *shift, d + *shift).sin(), Interval(-1.0, 1.0));++ // Test cosinus.+ assert_eq!(+ Interval(a + *shift, b + *shift).cos(),+ Interval((b + *shift).cos(), (a + *shift).cos())+ );+ assert_eq!(+ Interval(a + *shift, c + *shift).cos(),+ Interval(-1.0, (a + *shift).cos())+ );+ assert_eq!(+ Interval(a + *shift, d + *shift).cos(),+ Interval(-1.0, (a + *shift).cos())+ );+ }+ }+}diff --git a/renderer/third_party/parry3d/src/utils/inv.rs b/renderer/third_party/parry3d/src/utils/inv.rsnew file mode 100644index 0000000..97888ca--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/inv.rs@@ -0,0 +1,9 @@+use crate::math::Real;++pub fn inv(val: Real) -> Real {+ if val == 0.0 {+ 0.0+ } else {+ 1.0 / val+ }+}diff --git a/renderer/third_party/parry3d/src/utils/isometry_ops.rs b/renderer/third_party/parry3d/src/utils/isometry_ops.rsnew file mode 100644index 0000000..1a4acb7--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/isometry_ops.rs@@ -0,0 +1,114 @@+use crate::math::{Pose, Vector};++/// Extra operations with isometries.+pub trait PoseOps {+ /// Transform a vector by the absolute value of the homogeneous matrix+ /// equivalent to `self`.+ // TODO: move this to the rotation+ fn absolute_transform_vector(&self, v: Vector) -> Vector;+}++impl PoseOps for Pose {+ #[inline]+ fn absolute_transform_vector(&self, v: Vector) -> Vector {+ #[cfg(feature = "dim3")]+ {+ let rot_matrix = crate::math::Matrix::from_quat(self.rotation);+ rot_matrix.abs() * v+ }+ #[cfg(feature = "dim2")]+ {+ let rot_matrix = self.rotation.to_mat();+ rot_matrix.abs() * v+ }+ }+}++/// Various operations usable with `Option<Pose>` and `Option<&Pose>`+/// where `None` is assumed to be equivalent to the identity.+pub trait PoseOpt {+ /// Computes `self.inverse() * rhs`.+ fn inv_mul(self, rhs: &Pose) -> Pose;+ /// Computes `rhs * self`.+ fn prepend_to(self, rhs: &Pose) -> Pose;+ /// Computes `self * p`.+ fn transform_point(self, p: Vector) -> Vector;+ /// Computes `self.inverse() * p`.+ fn inverse_transform_point(self, p: Vector) -> Vector;+}++impl PoseOpt for Option<&Pose> {+ #[inline]+ fn inv_mul(self, rhs: &Pose) -> Pose {+ if let Some(iso) = self {+ iso.inv_mul(rhs)+ } else {+ *rhs+ }+ }++ #[inline]+ fn prepend_to(self, rhs: &Pose) -> Pose {+ if let Some(iso) = self {+ *rhs * *iso+ } else {+ *rhs+ }+ }++ #[inline]+ fn transform_point(self, p: Vector) -> Vector {+ if let Some(iso) = self {+ iso * p+ } else {+ p+ }+ }++ #[inline]+ fn inverse_transform_point(self, p: Vector) -> Vector {+ if let Some(iso) = self {+ iso.inverse_transform_point(p)+ } else {+ p+ }+ }+}++impl PoseOpt for Option<Pose> {+ #[inline]+ fn inv_mul(self, rhs: &Pose) -> Pose {+ if let Some(iso) = self {+ iso.inv_mul(rhs)+ } else {+ *rhs+ }+ }++ #[inline]+ fn prepend_to(self, rhs: &Pose) -> Pose {+ if let Some(iso) = self {+ *rhs * iso+ } else {+ *rhs+ }+ }++ #[inline]+ fn transform_point(self, p: Vector) -> Vector {+ if let Some(iso) = self {+ iso * p+ } else {+ p+ }+ }++ #[inline]+ fn inverse_transform_point(self, p: Vector) -> Vector {+ if let Some(iso) = self {+ iso.inverse_transform_point(p)+ } else {+ p+ }+ }+}diff --git a/renderer/third_party/parry3d/src/utils/median.rs b/renderer/third_party/parry3d/src/utils/median.rsnew file mode 100644index 0000000..4ffbb11--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/median.rs@@ -0,0 +1,99 @@+use crate::math::Real;++/// Computes the median of a set of values.+///+/// The median is the middle value when the data is sorted. For an even number of values,+/// it returns the average of the two middle values. This function modifies the input slice+/// by sorting it in-place.+///+/// # Arguments+///+/// * `vals` - A mutable slice of values. Must contain at least one value. The slice will be+/// sorted in-place as a side effect.+///+/// # Returns+///+/// The median value as a `Real`.+///+/// # Panics+///+/// Panics if the input slice is empty.+///+/// # Examples+///+/// ## Odd Number of Values+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::math::Real;+/// use parry2d::utils::median;+///+/// let mut values = vec![5.0, 1.0, 3.0, 9.0, 2.0];+/// let med = median(&mut values);+///+/// // With 5 values, the median is the 3rd value when sorted: [1, 2, 3, 5, 9]+/// assert_eq!(med, 3.0);+/// # }+/// ```+///+/// ## Even Number of Values+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::math::Real;+/// use parry2d::utils::median;+///+/// let mut values = vec![1.0, 2.0, 3.0, 4.0];+/// let med = median(&mut values);+///+/// // With 4 values, median is average of middle two: (2 + 3) / 2 = 2.5+/// assert_eq!(med, 2.5);+/// # }+/// ```+///+/// ## Single Value+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::math::Real;+/// use parry2d::utils::median;+///+/// let mut values = vec![42.0];+/// let med = median(&mut values);+///+/// // The median of a single value is the value itself+/// assert_eq!(med, 42.0);+/// # }+/// ```+///+/// ## Values Are Sorted In-Place+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::utils::median;+///+/// let mut values = vec![5.0, 1.0, 3.0];+/// let med = median(&mut values);+///+/// // After calling median, the values are sorted+/// assert_eq!(values, vec![1.0, 3.0, 5.0]);+/// assert_eq!(med, 3.0);+/// # }+/// ```+#[inline]+pub fn median(vals: &mut [Real]) -> Real {+ assert!(+ !vals.is_empty(),+ "Cannot compute the median of zero values."+ );++ vals.sort_by(|a, b| a.partial_cmp(b).unwrap());++ let n = vals.len();++ if n.is_multiple_of(2) {+ (vals[n / 2 - 1] + vals[n / 2]) / 2.0+ } else {+ vals[n / 2]+ }+}diff --git a/renderer/third_party/parry3d/src/utils/mod.rs b/renderer/third_party/parry3d/src/utils/mod.rsnew file mode 100644index 0000000..809c597--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/mod.rs@@ -0,0 +1,89 @@+//! Various unsorted geometrical and logical operators.++pub use self::ccw_face_normal::ccw_face_normal;+pub use self::center::center;++#[cfg(feature = "alloc")]+pub use self::array2::Array2;+#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+pub use self::cleanup::remove_unused_points;+pub use self::eigen2::SymmetricEigen2;+pub use self::eigen3::SymmetricEigen3;+pub(crate) use self::inv::inv;+pub use self::isometry_ops::{PoseOps, PoseOpt};+#[cfg(feature = "alloc")]+pub use self::median::median;+pub use self::point_cloud_support_point::{+ point_cloud_support_point, point_cloud_support_point_id,+};+pub use self::point_in_poly2d::{point_in_convex_poly2d, point_in_poly2d};+pub use self::sdp_matrix::{SdpMatrix2, SdpMatrix3};++#[cfg(feature = "alloc")]+pub use self::vec_map::VecMap;++pub use self::as_bytes::AsBytes;+#[cfg(any(feature = "alloc", feature = "std"))]+pub(crate) use self::consts::*;+pub use self::cov::{center_cov, cov};+pub use self::hashable_partial_eq::HashablePartialEq;+#[cfg(feature = "alloc")]+pub use self::interval::{find_root_intervals, find_root_intervals_to, Interval, IntervalFunction};+pub use self::obb::obb;+pub use self::relative_eq::relative_eq_vector;+pub use self::segments_intersection::{segments_intersection2d, SegmentsIntersection};+#[cfg(feature = "dim3")]+pub use self::sort::sort2;+pub use self::sort::sort3;+pub use self::sorted_pair::SortedPair;+#[cfg(feature = "spade")]+pub(crate) use self::spade::sanitize_spade_point;+pub(crate) use self::wops::{WBasis, WCross, WSign};++#[allow(unused_imports)]+pub(crate) use self::wops::simd_swap;++#[cfg(feature = "alloc")]+mod array2;+mod as_bytes;+mod ccw_face_normal;+mod center;+#[cfg(feature = "dim3")]+#[cfg(feature = "alloc")]+mod cleanup;+#[cfg(any(feature = "alloc", feature = "std"))]+mod consts;+mod cov;+#[cfg(feature = "enhanced-determinism")]+mod fx_hasher;+mod hashable_partial_eq;+#[cfg(feature = "alloc")]+pub mod hashmap;+#[cfg(feature = "alloc")]+pub mod hashset;+#[cfg(feature = "alloc")]+mod interval;+mod inv;+mod isometry_ops;+#[cfg(feature = "alloc")]+mod median;+pub mod morton;+mod obb;+mod point_cloud_support_point;+mod point_in_poly2d;+#[cfg(feature = "dim2")]+pub mod point_in_triangle;+mod sdp_matrix;+mod segments_intersection;+mod sort;+mod sorted_pair;+#[cfg(feature = "spade")]+mod spade;+mod wops;++mod eigen2;+mod eigen3;+mod relative_eq;+#[cfg(feature = "alloc")]+mod vec_map;diff --git a/renderer/third_party/parry3d/src/utils/morton.rs b/renderer/third_party/parry3d/src/utils/morton.rsnew file mode 100644index 0000000..f157b3e--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/morton.rs@@ -0,0 +1,45 @@+//! Morton encoding of 3D vectors.++// From https://github.com/DGriffin91/obvhs/tree/main/src/ploc/morton.rs+// MIT/Apache 2 license.++//---------------------------------------------------+// --- 21 bit resolution per channel morton curve ---+//---------------------------------------------------++use crate::math::Vector;++#[inline]+fn split_by_3_u64(a: u32) -> u64 {+ let mut x = a as u64 & 0x1fffff; // we only look at the first 21 bits+ x = (x | x << 32) & 0x1f00000000ffff;+ x = (x | x << 16) & 0x1f0000ff0000ff;+ x = (x | x << 8) & 0x100f00f00f00f00f;+ x = (x | x << 4) & 0x10c30c30c30c30c3;+ x = (x | x << 2) & 0x1249249249249249;+ x+}++#[inline]+/// Encode x,y,z position into a u64 morton value.+/// Input should be 0..=2u32.pow(21) (or 1u32 << 21)+fn morton_encode_u64(x: u32, y: u32, z: u32) -> u64 {+ split_by_3_u64(x) | split_by_3_u64(y) << 1 | split_by_3_u64(z) << 2+}++#[inline]+/// Encode a 3D position into a u64 morton value.+/// Input should be 0.0..=1.0+#[cfg_attr(feature = "f64", expect(clippy::unnecessary_cast))]+pub fn morton_encode_u64_unorm(p: Vector) -> u64 {+ let scale = (1u64 << 21) as f64;+ let x = (p.x as f64 * scale) as u32;+ let y = (p.y as f64 * scale) as u32;+ #[cfg(feature = "dim2")]+ return morton_encode_u64(x, y, 0);+ #[cfg(feature = "dim3")]+ {+ let z = (p.z as f64 * scale) as u32;+ morton_encode_u64(x, y, z)+ }+}diff --git a/renderer/third_party/parry3d/src/utils/obb.rs b/renderer/third_party/parry3d/src/utils/obb.rsnew file mode 100644index 0000000..4862e5b--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/obb.rs@@ -0,0 +1,43 @@+use crate::math::{MatExt, Pose, Real, Rotation, Vector, VectorExt, DIM};+use crate::shape::Cuboid;++/// Computes an oriented bounding box for the given set of points.+///+/// The returned OBB is not guaranteed to be the smallest enclosing OBB.+/// Though it should be a pretty good on for most purposes.+pub fn obb(pts: &[Vector]) -> (Pose, Cuboid) {+ let cov = crate::utils::cov(pts);+ let mut eigv = cov.symmetric_eigen().eigenvectors;++ if eigv.determinant() < 0.0 {+ eigv = -eigv;+ }++ let mut mins = Vector::splat(Real::MAX);+ let mut maxs = Vector::splat(-Real::MAX);++ for pt in pts {+ for i in 0..DIM {+ let dot = eigv.col(i).dot(*pt);+ mins.vset(i, mins.vget(i).min(dot));+ maxs.vset(i, maxs.vget(i).max(dot));+ }+ }++ #[cfg(feature = "dim2")]+ let rot = {+ // Extract rotation from 2x2 matrix+ // Matrix rows are [cos θ, -sin θ; sin θ, cos θ]+ Rotation::from_matrix_unchecked(eigv)+ };+ #[cfg(feature = "dim3")]+ let rot = Rotation::from_mat3(&eigv);++ // Create the isometry with rotation and the rotated center translation+ let center = (maxs + mins) / 2.0;+ let rotated_center = rot * center;+ (+ Pose::from_parts(rotated_center, rot),+ Cuboid::new((maxs - mins) / 2.0),+ )+}diff --git a/renderer/third_party/parry3d/src/utils/point_cloud_support_point.rs b/renderer/third_party/parry3d/src/utils/point_cloud_support_point.rsnew file mode 100644index 0000000..1e5142b--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/point_cloud_support_point.rs@@ -0,0 +1,25 @@+use crate::math::Vector;++/// Computes the index of the support point of a cloud of points.+#[inline]+pub fn point_cloud_support_point_id(dir: Vector, points: &[Vector]) -> usize {+ let mut best_pt = 0;+ let mut best_dot = points[0].dot(dir);++ for (i, p) in points.iter().enumerate().skip(1) {+ let dot = p.dot(dir);++ if dot > best_dot {+ best_dot = dot;+ best_pt = i;+ }+ }++ best_pt+}++/// Computes the support point of a cloud of points.+#[inline]+pub fn point_cloud_support_point(dir: Vector, points: &[Vector]) -> Vector {+ points[point_cloud_support_point_id(dir, points)]+}diff --git a/renderer/third_party/parry3d/src/utils/point_in_poly2d.rs b/renderer/third_party/parry3d/src/utils/point_in_poly2d.rsnew file mode 100644index 0000000..a452c61--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/point_in_poly2d.rs@@ -0,0 +1,337 @@+use crate::math::Vector2;+use num::Zero;++/// Tests if the given point is inside a convex polygon with arbitrary orientation.+///+/// This function uses a faster algorithm than [`point_in_poly2d`] but only works for+/// convex polygons. It checks if the point is on the same side of all edges of the polygon.+///+/// The polygon is assumed to be closed, i.e., first and last point of the polygon are implicitly+/// assumed to be connected by an edge.+///+/// # Arguments+///+/// * `pt` - The point to test+/// * `poly` - A slice of points defining the convex polygon vertices in any order (clockwise or counter-clockwise)+///+/// # Returns+///+/// `true` if the point is inside or on the boundary of the polygon, `false` otherwise.+///+/// # Examples+///+/// ## Vector Inside a Square+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::utils::point_in_convex_poly2d;+/// use parry2d::math::Vector;+///+/// let square = vec![+/// Vector::ZERO,+/// Vector::new(2.0, 0.0),+/// Vector::new(2.0, 2.0),+/// Vector::new(0.0, 2.0),+/// ];+///+/// let inside = Vector::new(1.0, 1.0);+/// let outside = Vector::new(3.0, 1.0);+///+/// assert!(point_in_convex_poly2d(inside, &square));+/// assert!(!point_in_convex_poly2d(outside, &square));+/// # }+/// ```+///+/// ## Vector on the Boundary+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::utils::point_in_convex_poly2d;+/// use parry2d::math::Vector;+///+/// let triangle = vec![+/// Vector::ZERO,+/// Vector::new(2.0, 0.0),+/// Vector::new(1.0, 2.0),+/// ];+///+/// let on_edge = Vector::new(1.0, 0.0);+/// assert!(point_in_convex_poly2d(on_edge, &triangle));+/// # }+/// ```+///+/// ## Empty Polygon+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::utils::point_in_convex_poly2d;+/// use parry2d::math::Vector;+///+/// let empty: Vec<Vector> = vec![];+/// let point = Vector::new(1.0, 1.0);+///+/// // An empty polygon contains no points+/// assert!(!point_in_convex_poly2d(point, &empty));+/// # }+/// ```+pub fn point_in_convex_poly2d(pt: Vector2, poly: &[Vector2]) -> bool {+ if poly.is_empty() {+ false+ } else {+ let mut sign = 0.0;++ for i1 in 0..poly.len() {+ let i2 = (i1 + 1) % poly.len();+ let seg_dir = poly[i2] - poly[i1];+ let dpt = pt - poly[i1];+ let perp = dpt.perp_dot(seg_dir);++ if sign.is_zero() {+ sign = perp;+ } else if sign * perp < 0.0 {+ return false;+ }+ }++ true+ }+}++/// Tests if the given point is inside an arbitrary closed polygon with arbitrary orientation,+/// using a winding number algorithm.+///+/// This function works with both convex and concave polygons, and even self-intersecting+/// polygons. It uses a winding number algorithm to determine if a point is inside.+///+/// The polygon is assumed to be closed, i.e., first and last point of the polygon are implicitly+/// assumed to be connected by an edge.+///+/// This handles concave polygons. For a faster function dedicated to convex polygons, see [`point_in_convex_poly2d`].+///+/// # Arguments+///+/// * `pt` - The point to test+/// * `poly` - A slice of points defining the polygon vertices in order (clockwise or counter-clockwise)+///+/// # Returns+///+/// `true` if the point is inside the polygon, `false` otherwise.+///+/// # Examples+///+/// ## Convex Polygon (Square)+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::utils::point_in_poly2d;+/// use parry2d::math::Vector;+///+/// let square = vec![+/// Vector::ZERO,+/// Vector::new(2.0, 0.0),+/// Vector::new(2.0, 2.0),+/// Vector::new(0.0, 2.0),+/// ];+///+/// let inside = Vector::new(1.0, 1.0);+/// let outside = Vector::new(3.0, 1.0);+///+/// assert!(point_in_poly2d(inside, &square));+/// assert!(!point_in_poly2d(outside, &square));+/// # }+/// ```+///+/// ## Concave Polygon (L-Shape)+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::utils::point_in_poly2d;+/// use parry2d::math::Vector;+///+/// // L-shaped polygon (concave)+/// let l_shape = vec![+/// Vector::ZERO,+/// Vector::new(2.0, 0.0),+/// Vector::new(2.0, 1.0),+/// Vector::new(1.0, 1.0),+/// Vector::new(1.0, 2.0),+/// Vector::new(0.0, 2.0),+/// ];+///+/// let inside_corner = Vector::new(0.5, 0.5);+/// let outside_corner = Vector::new(1.5, 1.5);+///+/// assert!(point_in_poly2d(inside_corner, &l_shape));+/// assert!(!point_in_poly2d(outside_corner, &l_shape));+/// # }+/// ```+///+/// ## Complex Polygon with Holes+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::utils::point_in_poly2d;+/// use parry2d::math::Vector;+///+/// // A star shape (self-intersecting creates a complex winding pattern)+/// let star = vec![+/// Vector::new(0.0, 1.0),+/// Vector::new(0.5, 0.5),+/// Vector::new(1.0, 1.0),+/// Vector::new(0.7, 0.3),+/// Vector::new(1.0, -0.5),+/// Vector::ZERO,+/// Vector::new(-1.0, -0.5),+/// Vector::new(-0.7, 0.3),+/// Vector::new(-1.0, 1.0),+/// Vector::new(-0.5, 0.5),+/// ];+///+/// let center = Vector::new(0.0, 0.5);+/// assert!(point_in_poly2d(center, &star));+/// # }+/// ```+///+/// ## Empty Polygon+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// use parry2d::utils::point_in_poly2d;+/// use parry2d::math::Vector;+///+/// let empty: Vec<Vector> = vec![];+/// let point = Vector::new(1.0, 1.0);+///+/// // An empty polygon contains no points+/// assert!(!point_in_poly2d(point, &empty));+/// # }+/// ```+pub fn point_in_poly2d(pt: Vector2, poly: &[Vector2]) -> bool {+ if poly.is_empty() {+ return false;+ }++ let mut winding = 0i32;++ for (i, a) in poly.iter().enumerate() {+ let b = poly[(i + 1) % poly.len()];+ let seg_dir = b - a;+ let dpt = pt - a;+ let perp = dpt.perp_dot(seg_dir);+ winding += match (dpt.y >= 0.0, b.y > pt.y) {+ (true, true) if perp < 0.0 => 1,+ (false, false) if perp > 0.0 => 1,+ _ => 0,+ };+ }++ winding % 2 == 1+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn point_in_poly2d_self_intersecting() {+ let poly = [+ [-1.0, -1.0],+ [0.0, -1.0],+ [0.0, 1.0],+ [-2.0, 1.0],+ [-2.0, -2.0],+ [1.0, -2.0],+ [1.0, 2.0],+ [-1.0, 2.0],+ ]+ .map(|[x, y]| Vector2::new(x, y));+ assert!(!point_in_poly2d(Vector2::new(-0.5, -0.5), &poly));+ assert!(point_in_poly2d(Vector2::new(0.5, -0.5), &poly));+ }++ #[test]+ fn point_in_poly2d_concave() {+ let poly = [+ [615.4741821289063, 279.4120788574219],+ [617.95947265625, 281.8973693847656],+ [624.1727294921875, 288.73193359375],+ [626.6580200195313, 292.4598693847656],+ [634.7352294921875, 302.40106201171875],+ [637.8418579101563, 306.7503356933594],+ [642.8124389648438, 312.96356201171875],+ [652.7536010742188, 330.98193359375],+ [654.6176147460938, 334.7098693847656],+ [661.4521484375, 349.0003356933594],+ [666.4227294921875, 360.18414306640625],+ [670.1506958007813, 367.6400451660156],+ [675.1212768554688, 381.30914306640625],+ [678.2279052734375, 391.2503356933594],+ [681.33447265625, 402.43414306640625],+ [683.81982421875, 414.23931884765625],+ [685.0624389648438, 422.3165283203125],+ [685.6837768554688, 431.0150146484375],+ [686.3051147460938, 442.8201904296875],+ [685.6837768554688, 454.0040283203125],+ [683.81982421875, 460.83856201171875],+ [679.4705200195313, 470.77972412109375],+ [674.4999389648438, 480.720947265625],+ [670.1506958007813, 486.93414306640625],+ [662.073486328125, 497.49664306640625],+ [659.5881958007813, 499.36065673828125],+ [653.3749389648438, 503.70989990234375],+ [647.7830200195313, 506.1951904296875],+ [642.8124389648438, 507.43780517578125],+ [631.6286010742188, 508.05914306640625],+ [621.0661010742188, 508.05914306640625],+ [605.5330200195313, 508.05914306640625],+ [596.2131958007813, 508.05914306640625],+ [586.893310546875, 508.05914306640625],+ [578.8161010742188, 508.05914306640625],+ [571.3602294921875, 506.1951904296875],+ [559.5551147460938, 499.36065673828125],+ [557.0697631835938, 497.49664306640625],+ [542.1580200195313, 484.4488525390625],+ [534.7021484375, 476.37164306640625],+ [532.8381958007813, 473.8863525390625],+ [527.2462768554688, 466.43048095703125],+ [522.2756958007813, 450.89739990234375],+ [521.6543579101563, 444.06280517578125],+ [521.0330200195313, 431.6363525390625],+ [521.6543579101563, 422.93780517578125],+ [523.518310546875, 409.26873779296875],+ [527.2462768554688, 397.46356201171875],+ [532.8381958007813, 385.6584167480469],+ [540.9154052734375, 373.23193359375],+ [547.1286010742188, 365.77606201171875],+ [559.5551147460938, 354.59222412109375],+ [573.2241821289063, 342.165771484375],+ [575.70947265625, 339.68048095703125],+ [584.4080200195313, 331.603271484375],+ [597.455810546875, 317.3128356933594],+ [601.8051147460938, 311.7209167480469],+ [607.39697265625, 303.6437072753906],+ [611.7462768554688, 296.1878356933594],+ [614.2315673828125, 288.1106262207031],+ [615.4741821289063, 280.65472412109375],+ [615.4741821289063, 279.4120788574219],+ ]+ .map(|[x, y]| Vector2::new(x, y));+ let pt = Vector2::new(596.0181884765625, 427.9162902832031);+ assert!(point_in_poly2d(pt, &poly));+ }++ #[test]+ #[cfg(all(feature = "dim2", feature = "alloc"))]+ fn point_in_poly2d_concave_exact_vertex_bug() {+ let poly = crate::shape::Ball::new(1.0).to_polyline(10);+ assert!(point_in_poly2d(Vector2::ZERO, &poly));+ assert!(point_in_poly2d(Vector2::new(-0.25, 0.0), &poly));+ assert!(point_in_poly2d(Vector2::new(0.25, 0.0), &poly));+ assert!(point_in_poly2d(Vector2::new(0.0, -0.25), &poly));+ assert!(point_in_poly2d(Vector2::new(0.0, 0.25), &poly));+ assert!(!point_in_poly2d(Vector2::new(-2.0, 0.0), &poly));+ assert!(!point_in_poly2d(Vector2::new(2.0, 0.0), &poly));+ assert!(!point_in_poly2d(Vector2::new(0.0, -2.0), &poly));+ assert!(!point_in_poly2d(Vector2::new(0.0, 2.0), &poly));+ }+}diff --git a/renderer/third_party/parry3d/src/utils/point_in_triangle.rs b/renderer/third_party/parry3d/src/utils/point_in_triangle.rsnew file mode 100644index 0000000..cc87364--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/point_in_triangle.rs@@ -0,0 +1,61 @@+//! Function to check if a point is inside a triangle and related functions.++use crate::math::{Real, Vector};++#[derive(Eq, PartialEq, Debug, Copy, Clone)]+/// The orientation or winding direction of a corner or polygon.+pub enum Orientation {+ /// Counter-clockwise+ Ccw,+ /// Clockwise+ Cw,+ /// Neither (a straight line)+ None,+}++/// Returns the direction of a line through `p1`, `p2` and `p3`.+///+/// Counter-clockwise example:+/// o p1+/// . o p3+/// . .+/// . .+/// o p2+///+/// Clockwise example:+/// o p2+/// . .+/// . .+/// . o p3+/// o p1+pub fn corner_direction(p1: Vector, p2: Vector, p3: Vector) -> Orientation {+ let v1 = p1 - p2;+ let v2 = p3 - p2;+ let cross: Real = v1.perp_dot(v2);++ match cross+ .partial_cmp(&0.0)+ .expect("Found NaN while computing corner direction.")+ {+ core::cmp::Ordering::Less => Orientation::Ccw,+ core::cmp::Ordering::Equal => Orientation::None,+ core::cmp::Ordering::Greater => Orientation::Cw,+ }+}++/// Returns `true` if point `p` is in triangle with corners `v1`, `v2` and `v3`.+/// Returns `None` if the triangle is invalid i.e. all points are the same or on a straight line.+pub fn is_point_in_triangle(p: Vector, v1: Vector, v2: Vector, v3: Vector) -> Option<bool> {+ let d1 = corner_direction(p, v1, v2);+ let d2 = corner_direction(p, v2, v3);+ let d3 = corner_direction(p, v3, v1);++ let has_cw = d1 == Orientation::Cw || d2 == Orientation::Cw || d3 == Orientation::Cw;+ let has_ccw = d1 == Orientation::Ccw || d2 == Orientation::Ccw || d3 == Orientation::Ccw;++ if d1 == Orientation::None && d2 == Orientation::None && d3 == Orientation::None {+ None+ } else {+ Some(!(has_cw && has_ccw))+ }+}diff --git a/renderer/third_party/parry3d/src/utils/relative_eq.rs b/renderer/third_party/parry3d/src/utils/relative_eq.rsnew file mode 100644index 0000000..eafc493--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/relative_eq.rs@@ -0,0 +1,14 @@+//! This module only exists for working around the fact that glam+//! doesn’t allow its `approx` feature to be enabled when targeting spirv.++use crate::math::Vector;+use approx::relative_eq;++/// Checks approximate equality between two vectors, component-wise.+#[inline]+pub fn relative_eq_vector(a: Vector, b: Vector) -> bool {+ #[cfg(feature = "dim2")]+ return relative_eq!(a.x, b.x) && relative_eq!(a.y, b.y);+ #[cfg(feature = "dim3")]+ return relative_eq!(a.x, b.x) && relative_eq!(a.y, b.y) && relative_eq!(a.z, b.z);+}diff --git a/renderer/third_party/parry3d/src/utils/sdp_matrix.rs b/renderer/third_party/parry3d/src/utils/sdp_matrix.rsnew file mode 100644index 0000000..31e8b1a--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/sdp_matrix.rs@@ -0,0 +1,385 @@+use crate::math::{Matrix2, Matrix3, Real, Vector2, Vector3};+use core::ops::{Add, Div, Mul, Neg, Sub};+use num_traits::{One, Zero};++/// A 2x2 symmetric-definite-positive matrix.+#[derive(Copy, Clone, Debug, PartialEq, Default)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+pub struct SdpMatrix2<N> {+ /// The component at the first row and first column of this matrix.+ pub m11: N,+ /// The component at the first row and second column of this matrix.+ pub m12: N,+ /// The component at the second row and second column of this matrix.+ pub m22: N,+}++impl<+ N: Copy+ + Zero+ + One+ + Add<Output = N>+ + Sub<Output = N>+ + Mul<Output = N>+ + Div<Output = N>+ + Neg<Output = N>,+ > SdpMatrix2<N>+{+ /// A new SDP 2x2 matrix with the given components.+ ///+ /// Because the matrix is symmetric, only the lower off-diagonal component is required.+ pub fn new(m11: N, m12: N, m22: N) -> Self {+ Self { m11, m12, m22 }+ }++ /// Create a new SDP matrix filled with zeros.+ pub fn zero() -> Self {+ Self {+ m11: N::zero(),+ m12: N::zero(),+ m22: N::zero(),+ }+ }++ /// Create a new SDP matrix with its diagonal filled with `val`, and its off-diagonal elements set to zero.+ pub fn diagonal(val: N) -> Self {+ Self {+ m11: val,+ m12: N::zero(),+ m22: val,+ }+ }++ /// Adds `val` to the diagonal components of `self`.+ pub fn add_diagonal(&mut self, elt: N) -> Self {+ Self {+ m11: self.m11 + elt,+ m12: self.m12,+ m22: self.m22 + elt,+ }+ }++ /// Compute the inverse of this SDP matrix without performing any inversibility check.+ pub fn inverse_unchecked(&self) -> Self {+ self.inverse_and_get_determinant_unchecked().0+ }++ /// Compute the inverse of this SDP matrix without performing any inversibility check.+ pub fn inverse_and_get_determinant_unchecked(&self) -> (Self, N) {+ let determinant = self.m11 * self.m22 - self.m12 * self.m12;+ let m11 = self.m22 / determinant;+ let m12 = -self.m12 / determinant;+ let m22 = self.m11 / determinant;++ (Self { m11, m12, m22 }, determinant)+ }+}++impl SdpMatrix2<Real> {+ /// Build an `SdpMatrix2` structure from a plain matrix, assuming it is SDP.+ pub fn from_sdp_matrix(mat: Matrix2) -> Self {+ let cols = mat.to_cols_array_2d();+ Self {+ m11: cols[0][0],+ m12: cols[1][0],+ m22: cols[1][1],+ }+ }++ /// Convert this SDP matrix to a regular matrix representation.+ pub fn into_matrix(self) -> Matrix2 {+ Matrix2::from_cols(+ Vector2::new(self.m11, self.m12),+ Vector2::new(self.m12, self.m22),+ )+ }++ /// Multiply this matrix by a vector.+ pub fn mul_vec(&self, rhs: Vector2) -> Vector2 {+ Vector2::new(+ self.m11 * rhs.x + self.m12 * rhs.y,+ self.m12 * rhs.x + self.m22 * rhs.y,+ )+ }+}++impl<N: Add<Output = N>> Add<SdpMatrix2<N>> for SdpMatrix2<N> {+ type Output = Self;++ fn add(self, rhs: SdpMatrix2<N>) -> Self {+ Self {+ m11: self.m11 + rhs.m11,+ m12: self.m12 + rhs.m12,+ m22: self.m22 + rhs.m22,+ }+ }+}++impl Mul<Vector2> for SdpMatrix2<Real> {+ type Output = Vector2;++ fn mul(self, rhs: Vector2) -> Self::Output {+ self.mul_vec(rhs)+ }+}++impl Mul<Real> for SdpMatrix2<Real> {+ type Output = SdpMatrix2<Real>;++ fn mul(self, rhs: Real) -> Self::Output {+ SdpMatrix2 {+ m11: self.m11 * rhs,+ m12: self.m12 * rhs,+ m22: self.m22 * rhs,+ }+ }+}++/// A 3x3 symmetric-definite-positive matrix.+#[derive(Copy, Clone, Debug, PartialEq, Default)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+pub struct SdpMatrix3<N> {+ /// The component at the first row and first column of this matrix.+ pub m11: N,+ /// The component at the first row and second column of this matrix.+ pub m12: N,+ /// The component at the first row and third column of this matrix.+ pub m13: N,+ /// The component at the second row and second column of this matrix.+ pub m22: N,+ /// The component at the second row and third column of this matrix.+ pub m23: N,+ /// The component at the third row and third column of this matrix.+ pub m33: N,+}++impl<+ N: Copy+ + Zero+ + One+ + Add<Output = N>+ + Sub<Output = N>+ + Mul<Output = N>+ + Div<Output = N>+ + Neg<Output = N>+ + PartialEq,+ > SdpMatrix3<N>+{+ /// A new SDP 3x3 matrix with the given components.+ ///+ /// Because the matrix is symmetric, only the lower off-diagonal components is required.+ pub fn new(m11: N, m12: N, m13: N, m22: N, m23: N, m33: N) -> Self {+ Self {+ m11,+ m12,+ m13,+ m22,+ m23,+ m33,+ }+ }++ /// Create a new SDP matrix filled with zeros.+ pub fn zero() -> Self {+ Self {+ m11: N::zero(),+ m12: N::zero(),+ m13: N::zero(),+ m22: N::zero(),+ m23: N::zero(),+ m33: N::zero(),+ }+ }++ /// Create a new SDP matrix with its diagonal filled with `val`, and its off-diagonal elements set to zero.+ pub fn diagonal(val: N) -> Self {+ Self {+ m11: val,+ m12: N::zero(),+ m13: N::zero(),+ m22: val,+ m23: N::zero(),+ m33: val,+ }+ }++ /// Are all components of this matrix equal to zero?+ pub fn is_zero(&self) -> bool {+ self.m11 == N::zero()+ && self.m12 == N::zero()+ && self.m13 == N::zero()+ && self.m22 == N::zero()+ && self.m23 == N::zero()+ && self.m33 == N::zero()+ }++ /// Compute the inverse of this SDP matrix without performing any inversibility check.+ pub fn inverse_unchecked(&self) -> Self {+ let minor_m12_m23 = self.m22 * self.m33 - self.m23 * self.m23;+ let minor_m11_m23 = self.m12 * self.m33 - self.m13 * self.m23;+ let minor_m11_m22 = self.m12 * self.m23 - self.m13 * self.m22;++ let determinant =+ self.m11 * minor_m12_m23 - self.m12 * minor_m11_m23 + self.m13 * minor_m11_m22;+ let inv_det = N::one() / determinant;++ SdpMatrix3 {+ m11: minor_m12_m23 * inv_det,+ m12: -minor_m11_m23 * inv_det,+ m13: minor_m11_m22 * inv_det,+ m22: (self.m11 * self.m33 - self.m13 * self.m13) * inv_det,+ m23: (self.m13 * self.m12 - self.m23 * self.m11) * inv_det,+ m33: (self.m11 * self.m22 - self.m12 * self.m12) * inv_det,+ }+ }++ /// Adds `elt` to the diagonal components of `self`.+ pub fn add_diagonal(&self, elt: N) -> Self {+ Self {+ m11: self.m11 + elt,+ m12: self.m12,+ m13: self.m13,+ m22: self.m22 + elt,+ m23: self.m23,+ m33: self.m33 + elt,+ }+ }+}++impl SdpMatrix3<Real> {+ /// Build an `SdpMatrix3` structure from a plain matrix, assuming it is SDP.+ pub fn from_sdp_matrix(mat: Matrix3) -> Self {+ let cols = mat.to_cols_array_2d();+ Self {+ m11: cols[0][0],+ m12: cols[1][0],+ m13: cols[2][0],+ m22: cols[1][1],+ m23: cols[2][1],+ m33: cols[2][2],+ }+ }++ /// Multiply this matrix by a vector.+ pub fn mul_vec(&self, rhs: Vector3) -> Vector3 {+ let x = self.m11 * rhs.x + self.m12 * rhs.y + self.m13 * rhs.z;+ let y = self.m12 * rhs.x + self.m22 * rhs.y + self.m23 * rhs.z;+ let z = self.m13 * rhs.x + self.m23 * rhs.y + self.m33 * rhs.z;+ Vector3::new(x, y, z)+ }++ /// Multiply this matrix by a 3x3 matrix.+ pub fn mul_mat(&self, rhs: Matrix3) -> Matrix3 {+ let cols = rhs.to_cols_array_2d();+ let col0 = self.mul_vec(Vector3::new(cols[0][0], cols[0][1], cols[0][2]));+ let col1 = self.mul_vec(Vector3::new(cols[1][0], cols[1][1], cols[1][2]));+ let col2 = self.mul_vec(Vector3::new(cols[2][0], cols[2][1], cols[2][2]));+ Matrix3::from_cols(col0, col1, col2)+ }++ /// Compute the quadratic form `m.transpose() * self * m`.+ pub fn quadform(&self, m: &Matrix3) -> Self {+ let sm = self.mul_mat(*m);+ let result = m.transpose() * sm;+ Self::from_sdp_matrix(result)+ }++ /// Compute the quadratic form `m.transpose() * self * m` for a 3x2 matrix.+ pub fn quadform3x2(+ &self,+ m11: Real,+ m12: Real,+ m21: Real,+ m22: Real,+ m31: Real,+ m32: Real,+ ) -> SdpMatrix2<Real> {+ let x0 = self.m11 * m11 + self.m12 * m21 + self.m13 * m31;+ let y0 = self.m12 * m11 + self.m22 * m21 + self.m23 * m31;+ let z0 = self.m13 * m11 + self.m23 * m21 + self.m33 * m31;++ let x1 = self.m11 * m12 + self.m12 * m22 + self.m13 * m32;+ let y1 = self.m12 * m12 + self.m22 * m22 + self.m23 * m32;+ let z1 = self.m13 * m12 + self.m23 * m22 + self.m33 * m32;++ let r11 = m11 * x0 + m21 * y0 + m31 * z0;+ let r12 = m11 * x1 + m21 * y1 + m31 * z1;+ let r22 = m12 * x1 + m22 * y1 + m32 * z1;++ SdpMatrix2 {+ m11: r11,+ m12: r12,+ m22: r22,+ }+ }+}++impl<N: Add<Output = N>> Add<SdpMatrix3<N>> for SdpMatrix3<N> {+ type Output = SdpMatrix3<N>;++ fn add(self, rhs: SdpMatrix3<N>) -> Self::Output {+ SdpMatrix3 {+ m11: self.m11 + rhs.m11,+ m12: self.m12 + rhs.m12,+ m13: self.m13 + rhs.m13,+ m22: self.m22 + rhs.m22,+ m23: self.m23 + rhs.m23,+ m33: self.m33 + rhs.m33,+ }+ }+}++impl Mul<Real> for SdpMatrix3<Real> {+ type Output = SdpMatrix3<Real>;++ fn mul(self, rhs: Real) -> Self::Output {+ SdpMatrix3 {+ m11: self.m11 * rhs,+ m12: self.m12 * rhs,+ m13: self.m13 * rhs,+ m22: self.m22 * rhs,+ m23: self.m23 * rhs,+ m33: self.m33 * rhs,+ }+ }+}++impl Mul<Vector3> for SdpMatrix3<Real> {+ type Output = Vector3;++ fn mul(self, rhs: Vector3) -> Self::Output {+ self.mul_vec(rhs)+ }+}++impl Mul<Matrix3> for SdpMatrix3<Real> {+ type Output = Matrix3;++ fn mul(self, rhs: Matrix3) -> Self::Output {+ self.mul_mat(rhs)+ }+}++impl<T> From<[SdpMatrix3<Real>; 4]> for SdpMatrix3<T>+where+ T: From<[Real; 4]>,+{+ fn from(data: [SdpMatrix3<Real>; 4]) -> Self {+ SdpMatrix3 {+ m11: T::from([data[0].m11, data[1].m11, data[2].m11, data[3].m11]),+ m12: T::from([data[0].m12, data[1].m12, data[2].m12, data[3].m12]),+ m13: T::from([data[0].m13, data[1].m13, data[2].m13, data[3].m13]),+ m22: T::from([data[0].m22, data[1].m22, data[2].m22, data[3].m22]),+ m23: T::from([data[0].m23, data[1].m23, data[2].m23, data[3].m23]),+ m33: T::from([data[0].m33, data[1].m33, data[2].m33, data[3].m33]),+ }+ }+}diff --git a/renderer/third_party/parry3d/src/utils/segments_intersection.rs b/renderer/third_party/parry3d/src/utils/segments_intersection.rsnew file mode 100644index 0000000..e7bf526--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/segments_intersection.rs@@ -0,0 +1,179 @@+use crate::math::Vector2;++use crate::math::Real;+use crate::shape::{SegmentPointLocation, Triangle, TriangleOrientation};++/// Intersection between two segments.+pub enum SegmentsIntersection {+ /// Single point of intersection.+ Point {+ /// Location of the intersection point on the first segment.+ loc1: SegmentPointLocation,+ /// Location of the intersection point on the second segment.+ loc2: SegmentPointLocation,+ },+ /// Intersection along a segment (when both segments are collinear).+ Segment {+ /// Location of the first intersection point on the first segment.+ first_loc1: SegmentPointLocation,+ /// Location of the first intersection point on the second segment.+ first_loc2: SegmentPointLocation,+ /// Location of the second intersection point on the first segment.+ second_loc1: SegmentPointLocation,+ /// Location of the second intersection point on the second segment.+ second_loc2: SegmentPointLocation,+ },+}++/// Computes the intersection between two segments.+pub fn segments_intersection2d(+ a: Vector2,+ b: Vector2,+ c: Vector2,+ d: Vector2,+ epsilon: Real,+) -> Option<SegmentsIntersection> {+ let denom = a.x * (d.y - c.y) + b.x * (c.y - d.y) + d.x * (b.y - a.y) + c.x * (a.y - b.y);++ // If denom is zero, then segments are parallel: handle separately.+ if denom.abs() < epsilon || ulps_eq!(denom, 0.0) {+ return parallel_intersection(a, b, c, d, epsilon);+ }++ let num = a.x * (d.y - c.y) + c.x * (a.y - d.y) + d.x * (c.y - a.y);+ let s = num / denom;++ let num = -(a.x * (c.y - b.y) + b.x * (a.y - c.y) + c.x * (b.y - a.y));+ let t = num / denom;++ if 0.0 > s || s > 1.0 || 0.0 > t || t > 1.0 {+ None+ } else {+ let loc1 = if s == 0.0 {+ SegmentPointLocation::OnVertex(0)+ } else if s == 1.0 {+ SegmentPointLocation::OnVertex(1)+ } else {+ SegmentPointLocation::OnEdge([1.0 - s, s])+ };++ let loc2 = if t == 0.0 {+ SegmentPointLocation::OnVertex(0)+ } else if t == 1.0 {+ SegmentPointLocation::OnVertex(1)+ } else {+ SegmentPointLocation::OnEdge([1.0 - t, t])+ };++ Some(SegmentsIntersection::Point { loc1, loc2 })+ }+}++fn parallel_intersection(+ a: Vector2,+ b: Vector2,+ c: Vector2,+ d: Vector2,+ epsilon: Real,+) -> Option<SegmentsIntersection> {+ if Triangle::orientation2d(a, b, c, epsilon) != TriangleOrientation::Degenerate {+ return None;+ }++ let ab_c = between(a, b, c);+ let ab_d = between(a, b, d);+ if let (Some(loc1), Some(loc2)) = (ab_c, ab_d) {+ return Some(SegmentsIntersection::Segment {+ first_loc1: loc1,+ first_loc2: SegmentPointLocation::OnVertex(0),+ second_loc1: loc2,+ second_loc2: SegmentPointLocation::OnVertex(1),+ });+ }++ let cd_a = between(c, d, a);+ let cd_b = between(c, d, b);+ if let (Some(loc1), Some(loc2)) = (cd_a, cd_b) {+ return Some(SegmentsIntersection::Segment {+ first_loc1: SegmentPointLocation::OnVertex(0),+ first_loc2: loc1,+ second_loc1: SegmentPointLocation::OnVertex(1),+ second_loc2: loc2,+ });+ }++ if let (Some(loc1), Some(loc2)) = (ab_c, cd_b) {+ return Some(SegmentsIntersection::Segment {+ first_loc1: loc1,+ first_loc2: SegmentPointLocation::OnVertex(0),+ second_loc1: SegmentPointLocation::OnVertex(1),+ second_loc2: loc2,+ });+ }++ if let (Some(loc1), Some(loc2)) = (ab_c, cd_a) {+ return Some(SegmentsIntersection::Segment {+ first_loc1: loc1,+ first_loc2: SegmentPointLocation::OnVertex(0),+ second_loc1: SegmentPointLocation::OnVertex(0),+ second_loc2: loc2,+ });+ }++ if let (Some(loc1), Some(loc2)) = (ab_d, cd_b) {+ return Some(SegmentsIntersection::Segment {+ first_loc1: loc1,+ first_loc2: SegmentPointLocation::OnVertex(1),+ second_loc1: SegmentPointLocation::OnVertex(1),+ second_loc2: loc2,+ });+ }++ if let (Some(loc1), Some(loc2)) = (ab_d, cd_a) {+ return Some(SegmentsIntersection::Segment {+ first_loc1: loc1,+ first_loc2: SegmentPointLocation::OnVertex(1),+ second_loc1: SegmentPointLocation::OnVertex(0),+ second_loc2: loc2,+ });+ }++ None+}++// Checks that `c` is in-between `a` and `b`.+// Assumes the three points are collinear.+fn between(a: Vector2, b: Vector2, c: Vector2) -> Option<SegmentPointLocation> {+ // Classifies the barycentric coordinate of `c` along `ab`, snapping the+ // exact endpoints to `OnVertex` instead of `OnEdge`.+ fn classify(bcoord_b: Real) -> SegmentPointLocation {+ if bcoord_b == 0.0 {+ SegmentPointLocation::OnVertex(0)+ } else if bcoord_b == 1.0 {+ SegmentPointLocation::OnVertex(1)+ } else {+ SegmentPointLocation::OnEdge([1.0 - bcoord_b, bcoord_b])+ }+ }++ // If ab not vertical, check betweenness on x; else on y.+ if a.x != b.x {+ if a.x <= c.x && c.x <= b.x {+ return Some(classify((c.x - a.x) / (b.x - a.x)));+ } else if a.x >= c.x && c.x >= b.x {+ let bcoord = (c.x - b.x) / (a.x - b.x);+ return Some(classify(1.0 - bcoord));+ }+ } else if a.y != b.y {+ if a.y <= c.y && c.y <= b.y {+ return Some(classify((c.y - a.y) / (b.y - a.y)));+ } else if a.y >= c.y && c.y >= b.y {+ let bcoord = (c.y - b.y) / (a.y - b.y);+ return Some(classify(1.0 - bcoord));+ }+ } else if a.x == c.x && a.y == c.y {+ return Some(SegmentPointLocation::OnVertex(0));+ }++ None+}diff --git a/renderer/third_party/parry3d/src/utils/sort.rs b/renderer/third_party/parry3d/src/utils/sort.rsnew file mode 100644index 0000000..a4c7df3--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/sort.rs@@ -0,0 +1,186 @@+#[cfg(feature = "dim3")]+#[inline]+/// Sorts a set of two values in increasing order.+///+/// This is a simple utility function that takes two values and returns them+/// as a tuple in sorted order (smallest first). This function is only available+/// in 3D mode (`dim3` feature).+///+/// # Arguments+///+/// * `a` - The first value+/// * `b` - The second value+///+/// # Returns+///+/// A tuple `(min, max)` where `min` is the smaller value and `max` is the larger value.+///+/// # Examples+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::utils::sort2;+///+/// let (min, max) = sort2(5.0, 2.0);+/// assert_eq!(min, 2.0);+/// assert_eq!(max, 5.0);+///+/// // Already sorted values remain in the same order+/// let (min, max) = sort2(1.0, 3.0);+/// assert_eq!(min, 1.0);+/// assert_eq!(max, 3.0);+/// # }+/// ```+pub fn sort2<T: PartialOrd + Copy>(a: T, b: T) -> (T, T) {+ if a > b {+ (b, a)+ } else {+ (a, b)+ }+}++/// Sorts a set of three values in increasing order.+///+/// This function efficiently sorts three values using a minimal number of comparisons+/// (between 2 and 3 comparisons). The values are passed by reference and references+/// are returned, making this efficient for larger types.+///+/// # Arguments+///+/// * `a` - Reference to the first value+/// * `b` - Reference to the second value+/// * `c` - Reference to the third value+///+/// # Returns+///+/// A tuple of three references `(&min, &mid, &max)` in sorted order.+///+/// # Examples+///+/// ## Basic Sorting+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::utils::sort3;+///+/// let x = 5.0;+/// let y = 2.0;+/// let z = 8.0;+///+/// let (min, mid, max) = sort3(&x, &y, &z);+///+/// assert_eq!(*min, 2.0);+/// assert_eq!(*mid, 5.0);+/// assert_eq!(*max, 8.0);+/// # }+/// ```+///+/// ## All Permutations Work+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::utils::sort3;+///+/// let a = 1.0;+/// let b = 2.0;+/// let c = 3.0;+///+/// // All orderings produce the same sorted result+/// let (min1, mid1, max1) = sort3(&a, &b, &c);+/// let (min2, mid2, max2) = sort3(&c, &a, &b);+/// let (min3, mid3, max3) = sort3(&b, &c, &a);+///+/// assert_eq!(*min1, *min2);+/// assert_eq!(*min1, *min3);+/// assert_eq!(*max1, *max2);+/// assert_eq!(*max1, *max3);+/// # }+/// ```+///+/// ## Finding Median of Three+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::utils::sort3;+///+/// let values = [10.0, 5.0, 7.0];+/// let (_, median, _) = sort3(&values[0], &values[1], &values[2]);+///+/// // The middle value is the median+/// assert_eq!(*median, 7.0);+/// # }+/// ```+///+/// ## Works with Integers+///+/// ```+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// use parry3d::utils::sort3;+///+/// let x = 42;+/// let y = 17;+/// let z = 99;+///+/// let (min, mid, max) = sort3(&x, &y, &z);+///+/// assert_eq!(*min, 17);+/// assert_eq!(*mid, 42);+/// assert_eq!(*max, 99);+/// # }+/// ```+#[inline]+pub fn sort3<'a, T: PartialOrd + Copy>(a: &'a T, b: &'a T, c: &'a T) -> (&'a T, &'a T, &'a T) {+ let a_b = *a > *b;+ let a_c = *a > *c;+ let b_c = *b > *c;++ let sa;+ let sb;+ let sc;++ // Sort the three values.+ if a_b {+ // a > b+ if a_c {+ // a > c+ sc = a;++ if b_c {+ // b > c+ sa = c;+ sb = b;+ } else {+ // b <= c+ sa = b;+ sb = c;+ }+ } else {+ // a <= c+ sa = b;+ sb = a;+ sc = c;+ }+ } else {+ // a < b+ if !a_c {+ // a <= c+ sa = a;++ if b_c {+ // b > c+ sb = c;+ sc = b;+ } else {+ sb = b;+ sc = c;+ }+ } else {+ // a > c+ sa = c;+ sb = a;+ sc = b;+ }+ }++ (sa, sb, sc)+}diff --git a/renderer/third_party/parry3d/src/utils/sorted_pair.rs b/renderer/third_party/parry3d/src/utils/sorted_pair.rsnew file mode 100644index 0000000..dda6379--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/sorted_pair.rs@@ -0,0 +1,177 @@+use core::cmp::PartialOrd;+use core::mem;+use core::ops::Deref;++/// A pair of elements sorted in increasing order.+///+/// This structure guarantees that the first element is always less than or equal to+/// the second element. It is useful for representing edges, connections, or any+/// unordered pair where you want canonical ordering (e.g., ensuring that edge (A, B)+/// and edge (B, A) are treated as the same edge).+///+/// The sorted pair implements `Deref` to `(T, T)` for convenient access to the elements.+///+/// # Examples+///+/// ## Creating a Sorted Pair+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::utils::SortedPair;+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::utils::SortedPair;+///+/// // Create a pair - the elements will be sorted automatically+/// let pair1 = SortedPair::new(5, 2);+/// let pair2 = SortedPair::new(2, 5);+///+/// // Both pairs are equal because they contain the same sorted elements+/// assert_eq!(pair1, pair2);+///+/// // Access elements via dereferencing+/// assert_eq!(pair1.0, 2);+/// assert_eq!(pair1.1, 5);+/// # }+/// # }+/// ```+///+/// ## Using as HashMap Keys+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::utils::SortedPair;+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::utils::SortedPair;+/// use std::collections::HashMap;+///+/// let mut edge_weights = HashMap::new();+///+/// // These represent the same edge, so they'll map to the same entry+/// edge_weights.insert(SortedPair::new(1, 3), 10.0);+/// edge_weights.insert(SortedPair::new(3, 1), 20.0); // Overwrites previous+///+/// assert_eq!(edge_weights.len(), 1);+/// assert_eq!(edge_weights.get(&SortedPair::new(1, 3)), Some(&20.0));+/// # }+/// # }+/// ```+///+/// ## Representing Graph Edges+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::utils::SortedPair;+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::utils::SortedPair;+///+/// // Represent undirected edges in a graph+/// let edges = vec![+/// SortedPair::new(0, 1), // Edge between vertices 0 and 1+/// SortedPair::new(1, 2), // Edge between vertices 1 and 2+/// SortedPair::new(2, 0), // Edge between vertices 2 and 0+/// ];+///+/// // Check if a specific edge exists (order doesn't matter)+/// let query_edge = SortedPair::new(2, 1);+/// assert!(edges.contains(&query_edge));+/// # }+/// # }+/// ```+///+/// ## Ordering+///+/// ```+/// # #[cfg(all(feature = "dim2", feature = "f32"))] {+/// # use parry2d::utils::SortedPair;+/// # #[cfg(all(feature = "dim3", feature = "f32"))] {+/// # use parry3d::utils::SortedPair;+///+/// let pair1 = SortedPair::new(1, 5);+/// let pair2 = SortedPair::new(2, 3);+/// let pair3 = SortedPair::new(1, 6);+///+/// // Pairs are compared lexicographically (first element, then second)+/// assert!(pair1 < pair2); // (1, 5) < (2, 3)+/// assert!(pair1 < pair3); // (1, 5) < (1, 6)+/// # }+/// # }+/// ```+#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+pub struct SortedPair<T: PartialOrd>([T; 2]);++impl<T: PartialOrd> SortedPair<T> {+ /// Sorts two elements in increasing order into a new pair.+ ///+ /// # Arguments+ ///+ /// * `element1` - The first element+ /// * `element2` - The second element+ ///+ /// # Returns+ ///+ /// A `SortedPair` where the smaller element comes first.+ ///+ /// # Examples+ ///+ /// ```+ /// # #[cfg(all(feature = "dim2", feature = "f32"))] {+ /// # use parry2d::utils::SortedPair;+ /// # #[cfg(all(feature = "dim3", feature = "f32"))] {+ /// # use parry3d::utils::SortedPair;+ ///+ /// let pair = SortedPair::new(10, 5);+ ///+ /// // Elements are automatically sorted+ /// assert_eq!(pair.0, 5);+ /// assert_eq!(pair.1, 10);+ /// # }+ /// # }+ /// ```+ pub fn new(element1: T, element2: T) -> Self {+ if element1 > element2 {+ SortedPair([element2, element1])+ } else {+ SortedPair([element1, element2])+ }+ }+}++impl<T: PartialOrd> Deref for SortedPair<T> {+ type Target = (T, T);++ fn deref(&self) -> &(T, T) {+ unsafe { mem::transmute(self) }+ }+}++// TODO: can we avoid these manual impls of Hash/PartialEq/Eq for the archived types?+#[cfg(feature = "rkyv")]+impl<T: rkyv::Archive + PartialOrd> core::hash::Hash for ArchivedSortedPair<T>+where+ [<T as rkyv::Archive>::Archived; 2]: core::hash::Hash,+{+ fn hash<H: core::hash::Hasher>(&self, state: &mut H) {+ self.0.hash(state)+ }+}++#[cfg(feature = "rkyv")]+impl<T: rkyv::Archive + PartialOrd> PartialEq for ArchivedSortedPair<T>+where+ [<T as rkyv::Archive>::Archived; 2]: PartialEq,+{+ fn eq(&self, other: &Self) -> bool {+ self.0 == other.0+ }+}++#[cfg(feature = "rkyv")]+impl<T: rkyv::Archive + PartialOrd> Eq for ArchivedSortedPair<T> where+ [<T as rkyv::Archive>::Archived; 2]: Eq+{+}diff --git a/renderer/third_party/parry3d/src/utils/spade.rs b/renderer/third_party/parry3d/src/utils/spade.rsnew file mode 100644index 0000000..e687422--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/spade.rs@@ -0,0 +1,27 @@+use crate::math::Real;++/// Ensures the given coordinate doesn’t go out of the bounds of spade’s acceptable values.+///+/// Returns 0.0 if the coordinate is smaller than `spade::MIN_ALLOWED_VALUE`.+/// Returns `spade::MAX_ALLOWED_VALUE` the coordinate is larger than `spade::MAX_ALLOWED_VALUE`.+pub fn sanitize_spade_coord(coord: Real) -> Real {+ let abs = coord.abs();++ #[allow(clippy::unnecessary_cast)]+ if abs as f64 <= spade::MIN_ALLOWED_VALUE {+ return 0.0;+ }++ #[cfg(feature = "f64")]+ if abs > spade::MAX_ALLOWED_VALUE {+ // This cannot happen in f32 since the max is 3.40282347E+38.+ return spade::MAX_ALLOWED_VALUE * coord.signum();+ }++ coord+}++/// Ensures the coordinates of the given point don't go out of the bounds of spade's acceptable values.+pub fn sanitize_spade_point(point: spade::Point2<Real>) -> spade::Point2<Real> {+ spade::Point2::new(sanitize_spade_coord(point.x), sanitize_spade_coord(point.y))+}diff --git a/renderer/third_party/parry3d/src/utils/vec_map.rs b/renderer/third_party/parry3d/src/utils/vec_map.rsnew file mode 100644index 0000000..daa3246--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/vec_map.rs@@ -0,0 +1,1691 @@+// Copyright 2012-2024 The Rust Project Developers. See the COPYRIGHT+// file at the top-level directory of this distribution and at+// http://rust-lang.org/COPYRIGHT.+//+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your+// option. This file may not be copied, modified, or distributed+// except according to those terms.++/*+ * NOTE: this is copied from https://github.com/contain-rs/vec-map/blob/master/src/lib.rs+ * (currently under passive maintenance) with the following modifications:+ * - Removal of the allocator type parameter.+ * - Implement rkyv serialization/deserialization.+ * - no-std support.+ */++#![forbid(unsafe_code)]+#![deny(missing_docs)]+#![warn(rust_2018_idioms)]+#![allow(clippy::type_complexity)]++//! # Description+//!+//! A simple map based on a vector for small integer keys. Space requirements+//! are **O(highest integer key)**.++use self::Entry::*;++use alloc::vec::{self, Vec};+use core::cmp::{max, Ordering};+use core::fmt;+use core::hash::{Hash, Hasher};+use core::iter::{Enumerate, FilterMap, FromIterator};+use core::mem::swap;+use core::ops::{Index, IndexMut};+use core::slice;++/// A map optimized for small integer keys.+///+/// # Examples+///+/// ```ignore+/// use parry::utils::VecMap;+///+/// let mut months = VecMap::new();+/// months.insert(1, "Jan");+/// months.insert(2, "Feb");+/// months.insert(3, "Mar");+///+/// if !months.contains_key(12) {+/// println!("The end is near!");+/// }+///+/// assert_eq!(months.get(1), Some(&"Jan"));+///+/// if let Some(value) = months.get_mut(3) {+/// *value = "Venus";+/// }+///+/// assert_eq!(months.get(3), Some(&"Venus"));+///+/// // Print out all months+/// for (key, value) in &months {+/// println!("month {} is {}", key, value);+/// }+///+/// months.clear();+/// assert!(months.is_empty());+/// ```+#[cfg_attr(+ feature = "serde-serialize",+ derive(serde::Serialize, serde::Deserialize),+ serde(bound(+ deserialize = "V: serde::Deserialize<'de>",+ serialize = "V: serde::Serialize"+ ))+)]+#[cfg_attr(+ feature = "rkyv",+ derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)+)]+pub struct VecMap<V> {+ n: usize,+ v: Vec<Option<V>>,+}++/// A view into a single entry in a map, which may either be vacant or occupied.+pub enum Entry<'a, V> {+ /// A vacant `Entry`+ Vacant(VacantEntry<'a, V>),++ /// An occupied `Entry`+ Occupied(OccupiedEntry<'a, V>),+}++/// A vacant `Entry`.+pub struct VacantEntry<'a, V> {+ map: &'a mut VecMap<V>,+ index: usize,+}++/// An occupied `Entry`.+pub struct OccupiedEntry<'a, V> {+ map: &'a mut VecMap<V>,+ index: usize,+}++impl<V> Default for VecMap<V> {+ #[inline]+ fn default() -> Self {+ Self::new()+ }+}++impl<V: Hash> Hash for VecMap<V> {+ fn hash<H: Hasher>(&self, state: &mut H) {+ // In order to not traverse the `VecMap` twice, count the elements+ // during iteration.+ let mut count: usize = 0;+ for elt in self {+ elt.hash(state);+ count += 1;+ }+ count.hash(state);+ }+}++impl<V> VecMap<V> {+ /// Creates an empty `VecMap`.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ /// let mut map: VecMap<&str> = VecMap::new();+ /// ```+ pub fn new() -> Self {+ VecMap {+ n: 0,+ v: Vec::new(),+ }+ }++ /// Creates an empty `VecMap` with space for at least `capacity`+ /// elements before resizing.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ /// let mut map: VecMap<&str> = VecMap::with_capacity(10);+ /// ```+ pub fn with_capacity(capacity: usize) -> Self {+ VecMap {+ n: 0,+ v: Vec::with_capacity(capacity),+ }+ }+}++impl<V> VecMap<V> {+ /// Returns the number of elements the `VecMap` can hold without+ /// reallocating.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ /// let map: VecMap<String> = VecMap::with_capacity(10);+ /// assert!(map.capacity() >= 10);+ /// ```+ #[inline]+ pub fn capacity(&self) -> usize {+ self.v.capacity()+ }++ /// Reserves capacity for the given `VecMap` to contain `len` distinct keys.+ /// In the case of `VecMap` this means reallocations will not occur as long+ /// as all inserted keys are less than `len`.+ ///+ /// The collection may reserve more space to avoid frequent reallocations.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ /// let mut map: VecMap<&str> = VecMap::new();+ /// map.reserve_len(10);+ /// assert!(map.capacity() >= 10);+ /// ```+ pub fn reserve_len(&mut self, len: usize) {+ let cur_len = self.v.len();+ if len >= cur_len {+ self.v.reserve(len - cur_len);+ }+ }++ /// Reserves the minimum capacity for the given `VecMap` to contain `len` distinct keys.+ /// In the case of `VecMap` this means reallocations will not occur as long as all inserted+ /// keys are less than `len`.+ ///+ /// Note that the allocator may give the collection more space than it requests.+ /// Therefore capacity cannot be relied upon to be precisely minimal. Prefer+ /// `reserve_len` if future insertions are expected.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ /// let mut map: VecMap<&str> = VecMap::new();+ /// map.reserve_len_exact(10);+ /// assert!(map.capacity() >= 10);+ /// ```+ pub fn reserve_len_exact(&mut self, len: usize) {+ let cur_len = self.v.len();+ if len >= cur_len {+ self.v.reserve_exact(len - cur_len);+ }+ }++ /// Trims the `VecMap` of any excess capacity.+ ///+ /// The collection may reserve more space to avoid frequent reallocations.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ /// let mut map: VecMap<&str> = VecMap::with_capacity(10);+ /// map.shrink_to_fit();+ /// assert_eq!(map.capacity(), 0);+ /// ```+ pub fn shrink_to_fit(&mut self) {+ // strip off trailing `None`s+ if let Some(idx) = self.v.iter().rposition(Option::is_some) {+ self.v.truncate(idx + 1);+ } else {+ self.v.clear();+ }++ self.v.shrink_to_fit()+ }++ /// Returns an iterator visiting all keys in ascending order of the keys.+ /// The iterator's element type is `usize`.+ pub fn keys(&self) -> Keys<'_, V> {+ Keys { iter: self.iter() }+ }++ /// Returns an iterator visiting all values in ascending order of the keys.+ /// The iterator's element type is `&'r V`.+ pub fn values(&self) -> Values<'_, V> {+ Values { iter: self.iter() }+ }++ /// Returns an iterator visiting all values in ascending order of the keys.+ /// The iterator's element type is `&'r mut V`.+ pub fn values_mut(&mut self) -> ValuesMut<'_, V> {+ ValuesMut {+ iter_mut: self.iter_mut(),+ }+ }++ /// Returns an iterator visiting all key-value pairs in ascending order of the keys.+ /// The iterator's element type is `(usize, &'r V)`.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut map = VecMap::new();+ /// map.insert(1, "a");+ /// map.insert(3, "c");+ /// map.insert(2, "b");+ ///+ /// // Print `1: a` then `2: b` then `3: c`+ /// for (key, value) in map.iter() {+ /// println!("{}: {}", key, value);+ /// }+ /// ```+ pub fn iter(&self) -> Iter<'_, V> {+ Iter {+ front: 0,+ back: self.v.len(),+ n: self.n,+ yielded: 0,+ iter: self.v.iter(),+ }+ }++ /// Returns an iterator visiting all key-value pairs in ascending order of the keys,+ /// with mutable references to the values.+ /// The iterator's element type is `(usize, &'r mut V)`.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut map = VecMap::new();+ /// map.insert(1, "a");+ /// map.insert(2, "b");+ /// map.insert(3, "c");+ ///+ /// for (key, value) in map.iter_mut() {+ /// *value = "x";+ /// }+ ///+ /// for (key, value) in &map {+ /// assert_eq!(value, &"x");+ /// }+ /// ```+ pub fn iter_mut(&mut self) -> IterMut<'_, V> {+ IterMut {+ front: 0,+ back: self.v.len(),+ n: self.n,+ yielded: 0,+ iter: self.v.iter_mut(),+ }+ }++ /// Moves all elements from `other` into the map while overwriting existing keys.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut a = VecMap::new();+ /// a.insert(1, "a");+ /// a.insert(2, "b");+ ///+ /// let mut b = VecMap::new();+ /// b.insert(3, "c");+ /// b.insert(4, "d");+ ///+ /// a.append(&mut b);+ ///+ /// assert_eq!(a.len(), 4);+ /// assert_eq!(b.len(), 0);+ /// assert_eq!(a[1], "a");+ /// assert_eq!(a[2], "b");+ /// assert_eq!(a[3], "c");+ /// assert_eq!(a[4], "d");+ /// ```+ pub fn append(&mut self, other: &mut Self) {+ self.extend(other.drain());+ }++ /// Splits the collection into two at the given key.+ ///+ /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,+ /// and the returned `Self` contains elements `[at, max_key)`.+ ///+ /// Note that the capacity of `self` does not change.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut a = VecMap::new();+ /// a.insert(1, "a");+ /// a.insert(2, "b");+ /// a.insert(3, "c");+ /// a.insert(4, "d");+ ///+ /// let b = a.split_off(3);+ ///+ /// assert_eq!(a[1], "a");+ /// assert_eq!(a[2], "b");+ ///+ /// assert_eq!(b[3], "c");+ /// assert_eq!(b[4], "d");+ /// ```+ pub fn split_off(&mut self, at: usize) -> Self {+ let mut other = VecMap::new();++ if at == 0 {+ // Move all elements to other+ // The swap will also fix .n+ swap(self, &mut other);+ return other;+ } else if at >= self.v.len() {+ // No elements to copy+ return other;+ }++ // Look up the index of the first non-None item+ let first_index = self.v.iter().position(|el| el.is_some());+ let start_index = match first_index {+ Some(index) => max(at, index),+ None => {+ // self has no elements+ return other;+ }+ };++ // Fill the new VecMap with `None`s until `start_index`+ other.v.extend((0..start_index).map(|_| None));++ // Move elements beginning with `start_index` from `self` into `other`+ let mut taken = 0;+ other.v.extend(self.v[start_index..].iter_mut().map(|el| {+ let el = el.take();+ if el.is_some() {+ taken += 1;+ }+ el+ }));+ other.n = taken;+ self.n -= taken;++ other+ }++ /// Returns an iterator visiting all key-value pairs in ascending order of+ /// the keys, emptying (but not consuming) the original `VecMap`.+ /// The iterator's element type is `(usize, &'r V)`. Keeps the allocated memory for reuse.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut map = VecMap::new();+ /// map.insert(1, "a");+ /// map.insert(3, "c");+ /// map.insert(2, "b");+ ///+ /// let vec: Vec<(usize, &str)> = map.drain().collect();+ ///+ /// assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]);+ /// ```+ pub fn drain(&mut self) -> Drain<'_, V> {+ fn filter<A>((i, v): (usize, Option<A>)) -> Option<(usize, A)> {+ v.map(|v| (i, v))+ }+ let filter: fn((usize, Option<V>)) -> Option<(usize, V)> = filter; // coerce to fn ptr++ self.n = 0;+ Drain {+ iter: self.v.drain(..).enumerate().filter_map(filter),+ }+ }++ /// Returns the number of elements in the map.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut a = VecMap::new();+ /// assert_eq!(a.len(), 0);+ /// a.insert(1, "a");+ /// assert_eq!(a.len(), 1);+ /// ```+ pub fn len(&self) -> usize {+ self.n+ }++ /// Returns true if the map contains no elements.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut a = VecMap::new();+ /// assert!(a.is_empty());+ /// a.insert(1, "a");+ /// assert!(!a.is_empty());+ /// ```+ pub fn is_empty(&self) -> bool {+ self.n == 0+ }++ /// Clears the map, removing all key-value pairs.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut a = VecMap::new();+ /// a.insert(1, "a");+ /// a.clear();+ /// assert!(a.is_empty());+ /// ```+ pub fn clear(&mut self) {+ self.n = 0;+ self.v.clear()+ }++ /// Returns a reference to the value corresponding to the key.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut map = VecMap::new();+ /// map.insert(1, "a");+ /// assert_eq!(map.get(1), Some(&"a"));+ /// assert_eq!(map.get(2), None);+ /// ```+ pub fn get(&self, key: usize) -> Option<&V> {+ if key < self.v.len() {+ self.v[key].as_ref()+ } else {+ None+ }+ }++ /// Returns true if the map contains a value for the specified key.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut map = VecMap::new();+ /// map.insert(1, "a");+ /// assert_eq!(map.contains_key(1), true);+ /// assert_eq!(map.contains_key(2), false);+ /// ```+ #[inline]+ pub fn contains_key(&self, key: usize) -> bool {+ self.get(key).is_some()+ }++ /// Returns a mutable reference to the value corresponding to the key.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut map = VecMap::new();+ /// map.insert(1, "a");+ /// if let Some(x) = map.get_mut(1) {+ /// *x = "b";+ /// }+ /// assert_eq!(map[1], "b");+ /// ```+ pub fn get_mut(&mut self, key: usize) -> Option<&mut V> {+ if key < self.v.len() {+ self.v[key].as_mut()+ } else {+ None+ }+ }++ /// Inserts a key-value pair into the map. If the key already had a value+ /// present in the map, that value is returned. Otherwise, `None` is returned.+ ///+ /// *WARNING*: You should only use trusted values as keys in VecMap. Otherwise, a+ /// denial-of-service vulnerability may occur that deplets memory with a large key value.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut map = VecMap::new();+ /// assert_eq!(map.insert(37, "a"), None);+ /// assert_eq!(map.is_empty(), false);+ ///+ /// map.insert(37, "b");+ /// assert_eq!(map.insert(37, "c"), Some("b"));+ /// assert_eq!(map[37], "c");+ /// ```+ pub fn insert(&mut self, key: usize, value: V) -> Option<V> {+ let len = self.v.len();+ if len <= key {+ self.v.extend((0..key - len + 1).map(|_| None));+ }+ let was = self.v[key].replace(value);+ if was.is_none() {+ self.n += 1;+ }+ was+ }++ /// Removes a key from the map, returning the value at the key if the key+ /// was previously in the map.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut map = VecMap::new();+ /// map.insert(1, "a");+ /// assert_eq!(map.remove(1), Some("a"));+ /// assert_eq!(map.remove(1), None);+ /// ```+ pub fn remove(&mut self, key: usize) -> Option<V> {+ if key >= self.v.len() {+ return None;+ }+ let result = &mut self.v[key];+ let was = result.take();+ if was.is_some() {+ self.n -= 1;+ }+ was+ }++ /// Gets the given key's corresponding entry in the map for in-place manipulation.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut count: VecMap<u32> = VecMap::new();+ ///+ /// // count the number of occurrences of numbers in the vec+ /// for x in vec![1, 2, 1, 2, 3, 4, 1, 2, 4] {+ /// *count.entry(x).or_insert(0) += 1;+ /// }+ ///+ /// assert_eq!(count[1], 3);+ /// ```+ pub fn entry(&mut self, key: usize) -> Entry<'_, V> {+ // FIXME(Gankro): this is basically the dumbest implementation of+ // entry possible, because weird non-lexical borrows issues make it+ // completely insane to do any other way. That said, Entry is a border-line+ // useless construct on VecMap, so it's hardly a big loss.+ if self.contains_key(key) {+ Occupied(OccupiedEntry {+ map: self,+ index: key,+ })+ } else {+ Vacant(VacantEntry {+ map: self,+ index: key,+ })+ }+ }++ /// Retains only the elements specified by the predicate.+ ///+ /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut map: VecMap<usize> = (0..8).map(|x|(x, x*10)).collect();+ /// map.retain(|k, _| k % 2 == 0);+ /// assert_eq!(map.len(), 4);+ /// ```+ pub fn retain<F>(&mut self, mut f: F)+ where+ F: FnMut(usize, &mut V) -> bool,+ {+ for (i, e) in self.v.iter_mut().enumerate() {+ let remove = match *e {+ Some(ref mut value) => !f(i, value),+ None => false,+ };+ if remove {+ *e = None;+ self.n -= 1;+ }+ }+ }+}++impl<'a, V> Entry<'a, V> {+ /// Ensures a value is in the entry by inserting the default if empty, and+ /// returns a mutable reference to the value in the entry.+ pub fn or_insert(self, default: V) -> &'a mut V {+ match self {+ Occupied(entry) => entry.into_mut(),+ Vacant(entry) => entry.insert(default),+ }+ }++ /// Ensures a value is in the entry by inserting the result of the default+ /// function if empty, and returns a mutable reference to the value in the+ /// entry.+ pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {+ match self {+ Occupied(entry) => entry.into_mut(),+ Vacant(entry) => entry.insert(default()),+ }+ }+}++impl<'a, V> VacantEntry<'a, V> {+ /// Sets the value of the entry with the `VacantEntry`'s key,+ /// and returns a mutable reference to it.+ pub fn insert(self, value: V) -> &'a mut V {+ let index = self.index;+ let _ = self.map.insert(index, value);+ &mut self.map[index]+ }+}++impl<'a, V> OccupiedEntry<'a, V> {+ /// Gets a reference to the value in the entry.+ pub fn get(&self) -> &V {+ let index = self.index;+ &self.map[index]+ }++ /// Gets a mutable reference to the value in the entry.+ pub fn get_mut(&mut self) -> &mut V {+ let index = self.index;+ &mut self.map[index]+ }++ /// Converts the entry into a mutable reference to its value.+ pub fn into_mut(self) -> &'a mut V {+ let index = self.index;+ &mut self.map[index]+ }++ /// Sets the value of the entry with the `OccupiedEntry`'s key,+ /// and returns the entry's old value.+ pub fn insert(&mut self, value: V) -> V {+ let index = self.index;+ self.map.insert(index, value).unwrap()+ }++ /// Takes the value of the entry out of the map, and returns it.+ pub fn remove(self) -> V {+ let index = self.index;+ self.map.remove(index).unwrap()+ }+}++impl<V: Clone> Clone for VecMap<V> {+ #[inline]+ fn clone(&self) -> Self {+ VecMap {+ n: self.n,+ v: self.v.clone(),+ }+ }++ #[inline]+ fn clone_from(&mut self, source: &Self) {+ self.v.clone_from(&source.v);+ self.n = source.n;+ }+}++impl<V, W> PartialEq<VecMap<W>> for VecMap<V>+where+ V: PartialEq<W>,+{+ fn eq(&self, other: &VecMap<W>) -> bool {+ self.n == other.n+ && self+ .iter()+ .zip(other.iter())+ .all(|((i, x), (j, y))| i == j && x == y)+ }+}++impl<V: Eq> Eq for VecMap<V> {}++impl<V> PartialOrd<VecMap<V>> for VecMap<V>+where+ V: PartialOrd,+{+ #[inline]+ fn partial_cmp(&self, other: &VecMap<V>) -> Option<Ordering> {+ self.iter().partial_cmp(other.iter())+ }+}++impl<V: Ord> Ord for VecMap<V> {+ #[inline]+ fn cmp(&self, other: &Self) -> Ordering {+ self.iter().cmp(other.iter())+ }+}++impl<V: fmt::Debug> fmt::Debug for VecMap<V> {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_map().entries(self).finish()+ }+}++impl<V> FromIterator<(usize, V)> for VecMap<V> {+ fn from_iter<I: IntoIterator<Item = (usize, V)>>(iter: I) -> Self {+ let mut map = Self::new();+ map.extend(iter);+ map+ }+}++impl<T> IntoIterator for VecMap<T> {+ type Item = (usize, T);+ type IntoIter = IntoIter<T>;++ /// Returns an iterator visiting all key-value pairs in ascending order of+ /// the keys, consuming the original `VecMap`.+ /// The iterator's element type is `(usize, &'r V)`.+ ///+ /// # Examples+ ///+ /// ```ignore+ /// use parry::utils::VecMap;+ ///+ /// let mut map = VecMap::new();+ /// map.insert(1, "a");+ /// map.insert(3, "c");+ /// map.insert(2, "b");+ ///+ /// let vec: Vec<(usize, &str)> = map.into_iter().collect();+ ///+ /// assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]);+ /// ```+ fn into_iter(self) -> IntoIter<T> {+ IntoIter {+ n: self.n,+ yielded: 0,+ iter: self.v.into_iter().enumerate(),+ }+ }+}++impl<'a, T> IntoIterator for &'a VecMap<T> {+ type Item = (usize, &'a T);+ type IntoIter = Iter<'a, T>;++ fn into_iter(self) -> Iter<'a, T> {+ self.iter()+ }+}++impl<'a, T> IntoIterator for &'a mut VecMap<T> {+ type Item = (usize, &'a mut T);+ type IntoIter = IterMut<'a, T>;++ fn into_iter(self) -> IterMut<'a, T> {+ self.iter_mut()+ }+}++impl<V> Extend<(usize, V)> for VecMap<V> {+ fn extend<I: IntoIterator<Item = (usize, V)>>(&mut self, iter: I) {+ for (k, v) in iter {+ let _ = self.insert(k, v);+ }+ }+}++impl<'a, V: Copy> Extend<(usize, &'a V)> for VecMap<V> {+ fn extend<I: IntoIterator<Item = (usize, &'a V)>>(&mut self, iter: I) {+ self.extend(iter.into_iter().map(|(key, &value)| (key, value)));+ }+}++impl<V> Index<usize> for VecMap<V> {+ type Output = V;++ #[inline]+ fn index(&self, i: usize) -> &V {+ self.get(i).expect("key not present")+ }+}++impl<V> Index<&usize> for VecMap<V> {+ type Output = V;++ #[inline]+ fn index(&self, i: &usize) -> &V {+ self.get(*i).expect("key not present")+ }+}++impl<V> IndexMut<usize> for VecMap<V> {+ #[inline]+ fn index_mut(&mut self, i: usize) -> &mut V {+ self.get_mut(i).expect("key not present")+ }+}++impl<V> IndexMut<&usize> for VecMap<V> {+ #[inline]+ fn index_mut(&mut self, i: &usize) -> &mut V {+ self.get_mut(*i).expect("key not present")+ }+}++macro_rules! iterator {+ (impl $name:ident -> $elem:ty, $($getter:ident),+) => {+ impl<'a, V> Iterator for $name<'a, V> {+ type Item = $elem;++ #[inline]+ fn next(&mut self) -> Option<$elem> {+ while self.front < self.back {+ if let Some(elem) = self.iter.next() {+ if let Some(x) = elem$(. $getter ())+ {+ let index = self.front;+ self.front += 1;+ self.yielded += 1;+ return Some((index, x));+ }+ }+ self.front += 1;+ }+ None+ }++ #[inline]+ fn size_hint(&self) -> (usize, Option<usize>) {+ (self.n - self.yielded, Some(self.n - self.yielded))+ }+ }+ }+}++macro_rules! double_ended_iterator {+ (impl $name:ident -> $elem:ty, $($getter:ident),+) => {+ impl<'a, V> DoubleEndedIterator for $name<'a, V> {+ #[inline]+ fn next_back(&mut self) -> Option<$elem> {+ while self.front < self.back {+ if let Some(elem) = self.iter.next_back() {+ if let Some(x) = elem$(. $getter ())+ {+ self.back -= 1;+ return Some((self.back, x));+ }+ }+ self.back -= 1;+ }+ None+ }+ }+ }+}++/// An iterator over the key-value pairs of a map.+#[derive(Clone)]+pub struct Iter<'a, V> {+ front: usize,+ back: usize,+ n: usize,+ yielded: usize,+ iter: slice::Iter<'a, Option<V>>,+}++iterator! { impl Iter -> (usize, &'a V), as_ref }+impl<'a, V> ExactSizeIterator for Iter<'a, V> {}+double_ended_iterator! { impl Iter -> (usize, &'a V), as_ref }++/// An iterator over the key-value pairs of a map, with the+/// values being mutable.+pub struct IterMut<'a, V> {+ front: usize,+ back: usize,+ n: usize,+ yielded: usize,+ iter: slice::IterMut<'a, Option<V>>,+}++iterator! { impl IterMut -> (usize, &'a mut V), as_mut }+impl<'a, V> ExactSizeIterator for IterMut<'a, V> {}+double_ended_iterator! { impl IterMut -> (usize, &'a mut V), as_mut }++/// An iterator over the keys of a map.+#[derive(Clone)]+pub struct Keys<'a, V> {+ iter: Iter<'a, V>,+}++/// An iterator over the values of a map.+#[derive(Clone)]+pub struct Values<'a, V> {+ iter: Iter<'a, V>,+}++/// An iterator over the values of a map.+pub struct ValuesMut<'a, V> {+ iter_mut: IterMut<'a, V>,+}++/// A consuming iterator over the key-value pairs of a map.+pub struct IntoIter<V> {+ n: usize,+ yielded: usize,+ iter: Enumerate<vec::IntoIter<Option<V>>>,+}++/// A draining iterator over the key-value pairs of a map.+pub struct Drain<'a, V> {+ iter: FilterMap<+ Enumerate<vec::Drain<'a, Option<V>>>,+ fn((usize, Option<V>)) -> Option<(usize, V)>,+ >,+}++impl<'a, V> Iterator for Drain<'a, V> {+ type Item = (usize, V);++ fn next(&mut self) -> Option<(usize, V)> {+ self.iter.next()+ }+ fn size_hint(&self) -> (usize, Option<usize>) {+ self.iter.size_hint()+ }+}++impl<'a, V> ExactSizeIterator for Drain<'a, V> {}++impl<'a, V> DoubleEndedIterator for Drain<'a, V> {+ fn next_back(&mut self) -> Option<(usize, V)> {+ self.iter.next_back()+ }+}++impl<'a, V> Iterator for Keys<'a, V> {+ type Item = usize;++ fn next(&mut self) -> Option<usize> {+ self.iter.next().map(|e| e.0)+ }+ fn size_hint(&self) -> (usize, Option<usize>) {+ self.iter.size_hint()+ }+}++impl<'a, V> ExactSizeIterator for Keys<'a, V> {}++impl<'a, V> DoubleEndedIterator for Keys<'a, V> {+ fn next_back(&mut self) -> Option<usize> {+ self.iter.next_back().map(|e| e.0)+ }+}++impl<'a, V> Iterator for Values<'a, V> {+ type Item = &'a V;++ fn next(&mut self) -> Option<&'a V> {+ self.iter.next().map(|e| e.1)+ }+ fn size_hint(&self) -> (usize, Option<usize>) {+ self.iter.size_hint()+ }+}++impl<'a, V> ExactSizeIterator for Values<'a, V> {}++impl<'a, V> DoubleEndedIterator for Values<'a, V> {+ fn next_back(&mut self) -> Option<&'a V> {+ self.iter.next_back().map(|e| e.1)+ }+}++impl<'a, V> Iterator for ValuesMut<'a, V> {+ type Item = &'a mut V;++ fn next(&mut self) -> Option<&'a mut V> {+ self.iter_mut.next().map(|e| e.1)+ }+ fn size_hint(&self) -> (usize, Option<usize>) {+ self.iter_mut.size_hint()+ }+}++impl<'a, V> ExactSizeIterator for ValuesMut<'a, V> {}++impl<'a, V> DoubleEndedIterator for ValuesMut<'a, V> {+ fn next_back(&mut self) -> Option<&'a mut V> {+ self.iter_mut.next_back().map(|e| e.1)+ }+}++impl<V> Iterator for IntoIter<V> {+ type Item = (usize, V);++ fn next(&mut self) -> Option<(usize, V)> {+ loop {+ match self.iter.next() {+ None => return None,+ Some((i, Some(value))) => {+ self.yielded += 1;+ return Some((i, value));+ }+ _ => {}+ }+ }+ }++ fn size_hint(&self) -> (usize, Option<usize>) {+ (self.n - self.yielded, Some(self.n - self.yielded))+ }+}++impl<V> ExactSizeIterator for IntoIter<V> {}++impl<V> DoubleEndedIterator for IntoIter<V> {+ fn next_back(&mut self) -> Option<(usize, V)> {+ loop {+ match self.iter.next_back() {+ None => return None,+ Some((i, Some(value))) => return Some((i, value)),+ _ => {}+ }+ }+ }+}++#[allow(dead_code)]+fn assert_properties() {+ fn vec_map_covariant<'a, T>(map: VecMap<&'static T>) -> VecMap<&'a T> {+ map+ }++ fn into_iter_covariant<'a, T>(iter: IntoIter<&'static T>) -> IntoIter<&'a T> {+ iter+ }++ fn iter_covariant<'i, 'a, T>(iter: Iter<'i, &'static T>) -> Iter<'i, &'a T> {+ iter+ }++ fn keys_covariant<'i, 'a, T>(iter: Keys<'i, &'static T>) -> Keys<'i, &'a T> {+ iter+ }++ fn values_covariant<'i, 'a, T>(iter: Values<'i, &'static T>) -> Values<'i, &'a T> {+ iter+ }+}++#[cfg(test)]+mod test {+ use super::Entry::{Occupied, Vacant};+ use super::VecMap;+ use std::boxed::Box;+ use std::collections::hash_map::DefaultHasher;+ use std::hash::{Hash, Hasher};+ use std::vec::Vec;++ #[test]+ fn test_get_mut() {+ let mut m = VecMap::new();+ assert!(m.insert(1, 12).is_none());+ assert!(m.insert(2, 8).is_none());+ assert!(m.insert(5, 14).is_none());+ let new = 100;+ match m.get_mut(5) {+ None => panic!(),+ Some(x) => *x = new,+ }+ assert_eq!(m.get(5), Some(&new));+ }++ #[test]+ fn test_len() {+ let mut map = VecMap::new();+ assert_eq!(map.len(), 0);+ assert!(map.is_empty());+ assert!(map.insert(5, 20).is_none());+ assert_eq!(map.len(), 1);+ assert!(!map.is_empty());+ assert!(map.insert(11, 12).is_none());+ assert_eq!(map.len(), 2);+ assert!(!map.is_empty());+ assert!(map.insert(14, 22).is_none());+ assert_eq!(map.len(), 3);+ assert!(!map.is_empty());+ }++ #[test]+ fn test_clear() {+ let mut map = VecMap::new();+ assert!(map.insert(5, 20).is_none());+ assert!(map.insert(11, 12).is_none());+ assert!(map.insert(14, 22).is_none());+ map.clear();+ assert!(map.is_empty());+ assert!(map.get(5).is_none());+ assert!(map.get(11).is_none());+ assert!(map.get(14).is_none());+ }++ #[test]+ fn test_insert() {+ let mut m = VecMap::new();+ assert_eq!(m.insert(1, 2), None);+ assert_eq!(m.insert(1, 3), Some(2));+ assert_eq!(m.insert(1, 4), Some(3));+ }++ #[test]+ fn test_remove() {+ let mut m = VecMap::new();+ let _ = m.insert(1, 2);+ assert_eq!(m.remove(1), Some(2));+ assert_eq!(m.remove(1), None);+ }++ #[test]+ fn test_keys() {+ let mut map = VecMap::new();+ let _ = map.insert(1, 'a');+ let _ = map.insert(2, 'b');+ let _ = map.insert(3, 'c');+ let keys: Vec<_> = map.keys().collect();+ assert_eq!(keys.len(), 3);+ assert!(keys.contains(&1));+ assert!(keys.contains(&2));+ assert!(keys.contains(&3));+ }++ #[test]+ fn test_values() {+ let mut map = VecMap::new();+ let _ = map.insert(1, 'a');+ let _ = map.insert(2, 'b');+ let _ = map.insert(3, 'c');+ let values: Vec<_> = map.values().cloned().collect();+ assert_eq!(values.len(), 3);+ assert!(values.contains(&'a'));+ assert!(values.contains(&'b'));+ assert!(values.contains(&'c'));+ }++ #[test]+ fn test_iterator() {+ let mut m = VecMap::new();++ assert!(m.insert(0, 1).is_none());+ assert!(m.insert(1, 2).is_none());+ assert!(m.insert(3, 5).is_none());+ assert!(m.insert(6, 10).is_none());+ assert!(m.insert(10, 11).is_none());++ let mut it = m.iter();+ assert_eq!(it.size_hint(), (5, Some(5)));+ assert_eq!(it.next().unwrap(), (0, &1));+ assert_eq!(it.size_hint(), (4, Some(4)));+ assert_eq!(it.next().unwrap(), (1, &2));+ assert_eq!(it.size_hint(), (3, Some(3)));+ assert_eq!(it.next().unwrap(), (3, &5));+ assert_eq!(it.size_hint(), (2, Some(2)));+ assert_eq!(it.next().unwrap(), (6, &10));+ assert_eq!(it.size_hint(), (1, Some(1)));+ assert_eq!(it.next().unwrap(), (10, &11));+ assert_eq!(it.size_hint(), (0, Some(0)));+ assert!(it.next().is_none());+ }++ #[test]+ fn test_iterator_size_hints() {+ let mut m = VecMap::new();++ assert!(m.insert(0, 1).is_none());+ assert!(m.insert(1, 2).is_none());+ assert!(m.insert(3, 5).is_none());+ assert!(m.insert(6, 10).is_none());+ assert!(m.insert(10, 11).is_none());++ assert_eq!(m.iter().size_hint(), (5, Some(5)));+ assert_eq!(m.iter().rev().size_hint(), (5, Some(5)));+ assert_eq!(m.iter_mut().size_hint(), (5, Some(5)));+ assert_eq!(m.iter_mut().rev().size_hint(), (5, Some(5)));+ }++ #[test]+ fn test_mut_iterator() {+ let mut m = VecMap::new();++ assert!(m.insert(0, 1).is_none());+ assert!(m.insert(1, 2).is_none());+ assert!(m.insert(3, 5).is_none());+ assert!(m.insert(6, 10).is_none());+ assert!(m.insert(10, 11).is_none());++ for (k, v) in &mut m {+ *v += k as isize;+ }++ let mut it = m.iter();+ assert_eq!(it.next().unwrap(), (0, &1));+ assert_eq!(it.next().unwrap(), (1, &3));+ assert_eq!(it.next().unwrap(), (3, &8));+ assert_eq!(it.next().unwrap(), (6, &16));+ assert_eq!(it.next().unwrap(), (10, &21));+ assert!(it.next().is_none());+ }++ #[test]+ fn test_rev_iterator() {+ let mut m = VecMap::new();++ assert!(m.insert(0, 1).is_none());+ assert!(m.insert(1, 2).is_none());+ assert!(m.insert(3, 5).is_none());+ assert!(m.insert(6, 10).is_none());+ assert!(m.insert(10, 11).is_none());++ let mut it = m.iter().rev();+ assert_eq!(it.next().unwrap(), (10, &11));+ assert_eq!(it.next().unwrap(), (6, &10));+ assert_eq!(it.next().unwrap(), (3, &5));+ assert_eq!(it.next().unwrap(), (1, &2));+ assert_eq!(it.next().unwrap(), (0, &1));+ assert!(it.next().is_none());+ }++ #[test]+ fn test_mut_rev_iterator() {+ let mut m = VecMap::new();++ assert!(m.insert(0, 1).is_none());+ assert!(m.insert(1, 2).is_none());+ assert!(m.insert(3, 5).is_none());+ assert!(m.insert(6, 10).is_none());+ assert!(m.insert(10, 11).is_none());++ for (k, v) in m.iter_mut().rev() {+ *v += k as isize;+ }++ let mut it = m.iter();+ assert_eq!(it.next().unwrap(), (0, &1));+ assert_eq!(it.next().unwrap(), (1, &3));+ assert_eq!(it.next().unwrap(), (3, &8));+ assert_eq!(it.next().unwrap(), (6, &16));+ assert_eq!(it.next().unwrap(), (10, &21));+ assert!(it.next().is_none());+ }++ #[test]+ fn test_move_iter() {+ let mut m: VecMap<Box<_>> = VecMap::new();+ let _ = m.insert(1, Box::new(2));+ let mut called = false;+ for (k, v) in m {+ assert!(!called);+ called = true;+ assert_eq!(k, 1);+ assert_eq!(v, Box::new(2));+ }+ assert!(called);+ }++ #[test]+ fn test_drain_iterator() {+ let mut map = VecMap::new();+ let _ = map.insert(1, "a");+ let _ = map.insert(3, "c");+ let _ = map.insert(2, "b");++ let vec: Vec<_> = map.drain().collect();++ assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]);+ assert_eq!(map.len(), 0);+ }++ #[test]+ fn test_append() {+ let mut a = VecMap::new();+ let _ = a.insert(1, "a");+ let _ = a.insert(2, "b");+ let _ = a.insert(3, "c");++ let mut b = VecMap::new();+ let _ = b.insert(3, "d"); // Overwrite element from a+ let _ = b.insert(4, "e");+ let _ = b.insert(5, "f");++ a.append(&mut b);++ assert_eq!(a.len(), 5);+ assert_eq!(b.len(), 0);+ // Capacity shouldn't change for possible reuse+ assert!(b.capacity() >= 4);++ assert_eq!(a[1], "a");+ assert_eq!(a[2], "b");+ assert_eq!(a[3], "d");+ assert_eq!(a[4], "e");+ assert_eq!(a[5], "f");+ }++ #[test]+ fn test_split_off() {+ // Split within the key range+ let mut a = VecMap::new();+ let _ = a.insert(1, "a");+ let _ = a.insert(2, "b");+ let _ = a.insert(3, "c");+ let _ = a.insert(4, "d");++ let b = a.split_off(3);++ assert_eq!(a.len(), 2);+ assert_eq!(b.len(), 2);++ assert_eq!(a[1], "a");+ assert_eq!(a[2], "b");++ assert_eq!(b[3], "c");+ assert_eq!(b[4], "d");++ // Split at 0+ a.clear();+ let _ = a.insert(1, "a");+ let _ = a.insert(2, "b");+ let _ = a.insert(3, "c");+ let _ = a.insert(4, "d");++ let b = a.split_off(0);++ assert_eq!(a.len(), 0);+ assert_eq!(b.len(), 4);+ assert_eq!(b[1], "a");+ assert_eq!(b[2], "b");+ assert_eq!(b[3], "c");+ assert_eq!(b[4], "d");++ // Split behind max_key+ a.clear();+ let _ = a.insert(1, "a");+ let _ = a.insert(2, "b");+ let _ = a.insert(3, "c");+ let _ = a.insert(4, "d");++ let b = a.split_off(5);++ assert_eq!(a.len(), 4);+ assert_eq!(b.len(), 0);+ assert_eq!(a[1], "a");+ assert_eq!(a[2], "b");+ assert_eq!(a[3], "c");+ assert_eq!(a[4], "d");+ }++ #[test]+ fn test_show() {+ let mut map = VecMap::new();+ let empty = VecMap::<i32>::new();++ let _ = map.insert(1, 2);+ let _ = map.insert(3, 4);++ let map_str = format!("{:?}", map);+ assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");+ assert_eq!(format!("{:?}", empty), "{}");+ }++ #[test]+ fn test_clone() {+ let mut a = VecMap::new();++ let _ = a.insert(1, 'x');+ let _ = a.insert(4, 'y');+ let _ = a.insert(6, 'z');++ assert_eq!(+ a.clone().iter().collect::<Vec<_>>(),+ [(1, &'x'), (4, &'y'), (6, &'z')]+ );+ }++ #[test]+ fn test_eq() {+ let mut a = VecMap::new();+ let mut b = VecMap::new();++ assert!(a == b);+ assert!(a.insert(0, 5).is_none());+ assert!(a != b);+ assert!(b.insert(0, 4).is_none());+ assert!(a != b);+ assert!(a.insert(5, 19).is_none());+ assert!(a != b);+ assert!(b.insert(0, 5).is_some());+ assert!(a != b);+ assert!(b.insert(5, 19).is_none());+ assert!(a == b);++ a = VecMap::new();+ b = VecMap::with_capacity(1);+ assert!(a == b);+ }++ #[test]+ fn test_lt() {+ let mut a = VecMap::new();+ let mut b = VecMap::new();++ assert!(a >= b && b >= a);+ assert!(b.insert(2, 5).is_none());+ assert!(a < b);+ assert!(a.insert(2, 7).is_none());+ assert!(a >= b && b < a);+ assert!(b.insert(1, 0).is_none());+ assert!(b < a);+ assert!(a.insert(0, 6).is_none());+ assert!(a < b);+ assert!(a.insert(6, 2).is_none());+ assert!(a < b && b >= a);+ }++ #[test]+ fn test_ord() {+ let mut a = VecMap::new();+ let mut b = VecMap::new();++ assert!(a == b);+ assert!(a.insert(1, 1).is_none());+ assert!(a > b && a >= b);+ assert!(b < a && b <= a);+ assert!(b.insert(2, 2).is_none());+ assert!(b > a && b >= a);+ assert!(a < b && a <= b);+ }++ #[test]+ fn test_hash() {+ fn hash<T: Hash>(t: &T) -> u64 {+ let mut s = DefaultHasher::new();+ t.hash(&mut s);+ s.finish()+ }++ let mut x = VecMap::new();+ let mut y = VecMap::new();++ assert!(hash(&x) == hash(&y));+ let _ = x.insert(1, 'a');+ let _ = x.insert(2, 'b');+ let _ = x.insert(3, 'c');++ let _ = y.insert(3, 'c');+ let _ = y.insert(2, 'b');+ let _ = y.insert(1, 'a');++ assert!(hash(&x) == hash(&y));++ let _ = x.insert(1000, 'd');+ let _ = x.remove(1000);++ assert!(hash(&x) == hash(&y));+ }++ #[test]+ fn test_from_iter() {+ let xs = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];++ let map: VecMap<_> = xs.iter().cloned().collect();++ for &(k, v) in &xs {+ assert_eq!(map.get(k), Some(&v));+ }+ }++ #[test]+ fn test_index() {+ let mut map = VecMap::new();++ let _ = map.insert(1, 2);+ let _ = map.insert(2, 1);+ let _ = map.insert(3, 4);++ assert_eq!(map[3], 4);+ }++ #[test]+ #[should_panic]+ fn test_index_nonexistent() {+ let mut map = VecMap::new();++ let _ = map.insert(1, 2);+ let _ = map.insert(2, 1);+ let _ = map.insert(3, 4);++ let _ = map[4];+ }++ #[test]+ fn test_entry() {+ let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];++ let mut map: VecMap<_> = xs.iter().cloned().collect();++ // Existing key (insert)+ match map.entry(1) {+ Vacant(_) => unreachable!(),+ Occupied(mut view) => {+ assert_eq!(view.get(), &10);+ assert_eq!(view.insert(100), 10);+ }+ }++ assert_eq!(map.get(1).unwrap(), &100);+ assert_eq!(map.len(), 6);++ // Existing key (update)+ match map.entry(2) {+ Vacant(_) => unreachable!(),+ Occupied(mut view) => {+ let v = view.get_mut();+ *v *= 10;+ }+ }++ assert_eq!(map.get(2).unwrap(), &200);+ assert_eq!(map.len(), 6);++ // Existing key (take)+ match map.entry(3) {+ Vacant(_) => unreachable!(),+ Occupied(view) => {+ assert_eq!(view.remove(), 30);+ }+ }++ assert_eq!(map.get(3), None);+ assert_eq!(map.len(), 5);++ // Inexistent key (insert)+ match map.entry(10) {+ Occupied(_) => unreachable!(),+ Vacant(view) => {+ assert_eq!(*view.insert(1000), 1000);+ }+ }++ assert_eq!(map.get(10).unwrap(), &1000);+ assert_eq!(map.len(), 6);+ }++ #[test]+ fn test_extend_ref() {+ let mut a = VecMap::new();+ let _ = a.insert(1, "one");+ let mut b = VecMap::new();+ let _ = b.insert(2, "two");+ let _ = b.insert(3, "three");++ a.extend(&b);++ assert_eq!(a.len(), 3);+ assert_eq!(a[&1], "one");+ assert_eq!(a[&2], "two");+ assert_eq!(a[&3], "three");+ }++ #[test]+ #[cfg(feature = "serde")]+ fn test_serde() {+ use serde::{Deserialize, Serialize};+ fn impls_serde_traits<'de, S: Serialize + Deserialize<'de>>() {}++ impls_serde_traits::<VecMap<u32>>();+ }++ #[test]+ fn test_retain() {+ let mut map = VecMap::new();+ let _ = map.insert(1, "one");+ let _ = map.insert(2, "two");+ let _ = map.insert(3, "three");+ map.retain(|k, v| match k {+ 1 => false,+ 2 => {+ *v = "two changed";+ true+ }+ 3 => false,+ _ => panic!(),+ });++ assert_eq!(map.len(), 1);+ assert_eq!(map.get(1), None);+ assert_eq!(map[2], "two changed");+ assert_eq!(map.get(3), None);+ }+}diff --git a/renderer/third_party/parry3d/src/utils/wops.rs b/renderer/third_party/parry3d/src/utils/wops.rsnew file mode 100644index 0000000..535c521--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/wops.rs@@ -0,0 +1,143 @@+//! Miscellaneous utilities.++use crate::math::{Real, Vector2, Vector3};++use {+ crate::math::{SimdBool, SimdReal},+ simba::simd::SimdValue,+};++#[allow(dead_code)]+/// Conditionally swaps each lanes of `a` with those of `b`.+///+/// For each `i in [0..SIMD_WIDTH[`, if `do_swap.extract(i)` is `true` then+/// `a.extract(i)` is swapped with `b.extract(i)`.+pub fn simd_swap(do_swap: SimdBool, a: &mut SimdReal, b: &mut SimdReal) {+ let _a = *a;+ *a = b.select(do_swap, *a);+ *b = _a.select(do_swap, *b);+}++/// Trait to copy the sign of each component of one scalar/vector/matrix to another.+pub trait WSign<Rhs>: Sized {+ // See SIMD implementations of copy_sign there: https://stackoverflow.com/a/57872652+ /// Copy the sign of each component of `self` to the corresponding component of `to`.+ fn copy_sign_to(self, to: Rhs) -> Rhs;+}++impl WSign<Real> for Real {+ #[inline]+ fn copy_sign_to(self, to: Self) -> Self {+ #[cfg(not(target_arch = "nvptx64"))]+ return to.copysign(self);+ #[cfg(target_arch = "nvptx64")]+ {+ // TODO: this is a manual implementation of copysign.+ // Apparently, the cuda_std copysign doesn’t compile with+ // rust-cuda.+ // return cuda_std::float::GpuFloat::copysign(to, self);+ let minus_zero: Real = -0.0;+ let signbit = minus_zero.to_bits();+ Real::from_bits((signbit & self.to_bits()) | ((!signbit) & to.to_bits()))+ }+ }+}++impl WSign<Vector2> for Real {+ fn copy_sign_to(self, to: Vector2) -> Vector2 {+ Vector2::new(self.copy_sign_to(to.x), self.copy_sign_to(to.y))+ }+}++impl WSign<Vector3> for Real {+ fn copy_sign_to(self, to: Vector3) -> Vector3 {+ Vector3::new(+ self.copy_sign_to(to.x),+ self.copy_sign_to(to.y),+ self.copy_sign_to(to.z),+ )+ }+}++impl WSign<Vector2> for Vector2 {+ fn copy_sign_to(self, to: Vector2) -> Vector2 {+ Vector2::new(self.x.copy_sign_to(to.x), self.y.copy_sign_to(to.y))+ }+}++impl WSign<Vector3> for Vector3 {+ fn copy_sign_to(self, to: Vector3) -> Vector3 {+ Vector3::new(+ self.x.copy_sign_to(to.x),+ self.y.copy_sign_to(to.y),+ self.z.copy_sign_to(to.z),+ )+ }+}++impl WSign<SimdReal> for SimdReal {+ fn copy_sign_to(self, to: SimdReal) -> SimdReal {+ use simba::simd::SimdRealField;+ to.simd_copysign(self)+ }+}++/// Trait to compute the orthonormal basis of a vector.+pub trait WBasis: Sized {+ /// The type of the array of orthonormal vectors.+ type Basis;+ /// Computes the vectors which, when combined with `self`, form an orthonormal basis.+ fn orthonormal_basis(self) -> Self::Basis;+}++impl WBasis for Vector2 {+ type Basis = [Vector2; 1];+ fn orthonormal_basis(self) -> [Vector2; 1] {+ [Vector2::new(-self.y, self.x)]+ }+}++impl WBasis for Vector3 {+ type Basis = [Vector3; 2];+ // Robust and branchless implementation from Pixar:+ // https://graphics.pixar.com/library/OrthonormalB/paper.pdf+ fn orthonormal_basis(self) -> [Vector3; 2] {+ let sign = self.z.copy_sign_to(1.0);+ let a = -1.0 / (sign + self.z);+ let b = self.x * self.y * a;++ [+ Vector3::new(1.0 + sign * self.x * self.x * a, sign * b, -sign * self.x),+ Vector3::new(b, sign + self.y * self.y * a, -self.y),+ ]+ }+}++pub(crate) trait WCross<Rhs>: Sized {+ type Result;+ fn gcross(&self, rhs: Rhs) -> Self::Result;+}++impl WCross<Vector3> for Vector3 {+ type Result = Self;++ fn gcross(&self, rhs: Vector3) -> Self::Result {+ self.cross(rhs)+ }+}++impl WCross<Vector2> for Vector2 {+ type Result = Real;++ fn gcross(&self, rhs: Vector2) -> Self::Result {+ self.x * rhs.y - self.y * rhs.x+ }+}++impl WCross<Vector2> for Real {+ type Result = Vector2;++ fn gcross(&self, rhs: Vector2) -> Self::Result {+ Vector2::new(-rhs.y * *self, rhs.x * *self)+ }+}diff --git a/renderer/third_party/parry3d/src/utils/z_order.rs b/renderer/third_party/parry3d/src/utils/z_order.rsnew file mode 100644index 0000000..f9a98d3--- /dev/null+++ b/renderer/third_party/parry3d/src/utils/z_order.rs@@ -0,0 +1,70 @@+use core::cmp::Ordering;+use num_traits::float::FloatCore;++#[allow(dead_code)] // We don't use this currently, but might in the future.+pub fn z_cmp_ints(lhs: &[usize], rhs: &[usize]) -> Ordering {+ assert_eq!(+ lhs.len(),+ rhs.len(),+ "Cannot compare array with different lengths."+ );++ let mut msd = 0;++ for dim in 1..rhs.len() {+ if less_msb(lhs[msd] ^ rhs[msd], lhs[dim] ^ rhs[dim]) {+ msd = dim;+ }+ }++ lhs[msd].cmp(&rhs[msd])+}++fn less_msb(x: usize, y: usize) -> bool {+ x < y && x < (x ^ y)+}++// Fast construction of k-Nearest Neighbor Graphs for Point Clouds+// Michael Connor, Piyush Kumar+// Algorithm 1+//+// http://compgeom.com/~piyush/papers/tvcg_stann.pdf+pub fn z_cmp_floats(p1: &[Real], p2: &[Real]) -> Option<Ordering> {+ assert_eq!(+ p1.len(),+ p2.len(),+ "Cannot compare array with different lengths."+ );+ let mut x = 0;+ let mut dim = 0;++ for j in 0..p1.len() {+ let y = xor_msb_float(p1[j], p2[j]);+ if x < y {+ x = y;+ dim = j;+ }+ }++ p1[dim].partial_cmp(&p2[dim])+}++fn xor_msb_float(fa: Real, fb: Real) -> i16 {+ let (mantissa1, exponent1, _sign1) = fa.integer_decode();+ let (mantissa2, exponent2, _sign2) = fb.integer_decode();+ let x = exponent1; // To keep the same notation as the paper.+ let y = exponent2; // To keep the same notation as the paper.++ if x == y {+ let z = msdb(mantissa1, mantissa2);+ x - z+ } else if y < x {+ x+ } else {+ y+ }+}++fn msdb(x: u64, y: u64) -> i16 {+ 64i16 - (x ^ y).leading_zeros() as i16+}diff --git a/renderer/web/Cargo.lock b/renderer/web/Cargo.lockindex eebe149..14a631b 100644--- a/renderer/web/Cargo.lock+++ b/renderer/web/Cargo.lock@@ -1663,8 +1663,6 @@ dependencies = [[[package]]name = "parry3d"version = "0.31.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7b626edc0b497dba4bdf6e1e0797895294ed9f61dac2bd28cb5d34d37ad2ca7e"dependencies = ["approx","arrayvec",diff --git a/renderer/web/Cargo.toml b/renderer/web/Cargo.tomlindex e7a403c..8af4ada 100644--- a/renderer/web/Cargo.toml+++ b/renderer/web/Cargo.toml@@ -31,3 +31,4 @@ lto = "thin"# depend on the platform's math functions (../third_party/glamx/PATCH.md).[patch.crates-io]glamx = { path = "../third_party/glamx" }+parry3d = { path = "../third_party/parry3d" }