ferravex_physics/
radial.rs

1//! Allocation-free radial impulses selected by the existing direct-overlap query.
2//!
3//! Selection uses current collider surfaces, including compound child offsets,
4//! rather than body-origin distance. Each dynamic body receives at most one
5//! **linear COM impulse** (no torque). Direction is from the request center to
6//! the body's current COM; falloff uses the nearest accepted child surface.
7//! Fixed/kinematic bodies are excluded. Sleeping behavior is explicit.
8//!
9//! All ordinary failures are checked before changing velocities, wake flags,
10//! forces or the accepted-output buffer. Candidate scratch may change on error.
11//! A truncated query is rejected, never applied as a first-N blast. An additional
12//! numeric preflight rejects geometry the existing f32 query would silently omit.
13//! No clocks, detector, damage, feedback, replay state or persistent cache is added.
14//!
15//! A physics-lab pulse can replace a manual body loop at an actual fixed tick:
16//!
17//! ```
18//! # #[cfg(feature = "dim2")] {
19//! use ferravex_math::{Vec2, Vec3};
20//! use ferravex_physics::{d2::*, radial::*};
21//! let mut world = PhysicsWorld::default();
22//! let ball = world.add_ball([2., 0.], 0.5, true);
23//! let wall = world.add_ball([0., -2.], 0.5, false);
24//! let mut candidates = [None; 8]; // Reuse these caller buffers on later ticks.
25//! let mut accepted = [None; 4];
26//! let request = RadialImpulseRequest {
27//!     center: Vec3::ZERO, radius: 8.,
28//!     model: ImpulseModel::PerBody(11.), falloff: Falloff::LinearSurface,
29//!     zero_distance: ZeroDistance::Axis(Vec3::Y),
30//!     sleeping: SleepingPolicy::Wake, sensors: RadialSensors::Exclude,
31//!     layers: u32::MAX, ignored_body: None, max_bodies: 4, max_colliders: 8,
32//! };
33//! let report = apply_radial_impulse(&mut world, request, &mut candidates,
34//!     &mut accepted).unwrap();
35//! assert_eq!(report.applied, 1);
36//! let effect = accepted[0].unwrap();
37//! assert_eq!(effect.body, ball);
38//! assert!((world.bodies[ball].linvel() - Vec2::X * effect.impulse.x
39//!     / world.bodies[ball].mass()).length() < 1e-4);
40//! assert_eq!(world.bodies[wall].linvel(), Vec2::ZERO);
41//! world.step(1. / 120.); // Real physics progresses; the operation itself runs no tick.
42//! assert!(world.bodies[ball].translation().x > 2.);
43//! // Restart owns world/body restoration; this helper retains no pending blast.
44//! assert!(world.remove_body(ball));
45//! let replacement = world.add_ball([2., 0.], 0.5, true);
46//! let report = apply_radial_impulse(&mut world, request, &mut candidates,
47//!     &mut accepted).unwrap();
48//! assert_eq!(report.applied, 1);
49//! assert_eq!(accepted[0].unwrap().body, replacement);
50//! assert_ne!(replacement, ball);
51//! # }
52//! ```
53//!
54//! The same generic adapter accepts the spatial world without a new renderer:
55//!
56//! ```
57//! # #[cfg(feature = "dim3")] {
58//! use ferravex_math::Vec3;
59//! use ferravex_physics::{d3::*, radial::*};
60//! let mut world = PhysicsWorld::default();
61//! let body = world.add_ball([0., 0., 2.], 0.5, true);
62//! let request = RadialImpulseRequest {
63//!     center: Vec3::ZERO, radius: 4., model: ImpulseModel::Total(6.),
64//!     falloff: Falloff::Constant, zero_distance: ZeroDistance::Skip,
65//!     sleeping: SleepingPolicy::Skip, sensors: RadialSensors::Exclude,
66//!     layers: u32::MAX, ignored_body: None, max_bodies: 1, max_colliders: 1,
67//! };
68//! let mut candidates = [None; 1];
69//! let mut accepted = [None; 1];
70//! assert_eq!(apply_radial_impulse(&mut world, request, &mut candidates,
71//!     &mut accepted).unwrap().applied, 1);
72//! assert_eq!(accepted[0].unwrap().impulse, Vec3::Z * 6.);
73//! assert!((world.bodies[body].linvel() - Vec3::Z * 6.
74//!     / world.bodies[body].mass()).length() < 1e-4);
75//! world.step(1. / 120.);
76//! assert!(world.bodies[body].translation().z > 2.);
77//! # }
78//! ```
79
80use crate::{
81    ColliderHandle, RigidBodyHandle,
82    body::{Access, Kind},
83    world::World,
84};
85use ferravex_math::Vec3;
86
87/// Scalar impulse policy; magnitudes must be finite and nonnegative.
88#[derive(Clone, Copy, Debug, PartialEq)]
89pub enum ImpulseModel {
90    /// Each body receives `magnitude * falloff_weight` impulse units.
91    PerBody(f32),
92    /// Split this total scalar impulse budget in proportion to falloff weights.
93    /// This bounds the sum of magnitudes, not the vector sum or kinetic energy.
94    /// With no eligible nonzero weights, no impulse is spent. f32 rounding applies.
95    Total(f32),
96}
97
98/// Falloff uses signed distance to the nearest child accepted by the query.
99#[derive(Clone, Copy, Debug, PartialEq, Eq)]
100pub enum Falloff {
101    Constant,
102    /// Weight = clamp(1 - max(surface_distance, 0) / radius, 0, 1).
103    /// A zero-radius point probe gives weight one to every overlapping child.
104    LinearSurface,
105}
106
107/// Direction when the body's COM coincides exactly with the request center.
108#[derive(Clone, Copy, Debug, PartialEq)]
109pub enum ZeroDistance {
110    /// Exclude this body from the budget, bound and accepted output.
111    Skip,
112    /// Normalize this finite nonzero vector using f64 intermediates.
113    /// In a planar world the vector must have z == 0, even if no body is centered.
114    Axis(Vec3),
115}
116
117/// Only dynamic bodies can be affected; sleeping dynamics follow this policy.
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
119pub enum SleepingPolicy {
120    Skip,
121    /// Store the velocity change without changing sleep/quiet/wake flags.
122    Preserve,
123    /// Apply the impulse and request ordinary body/island waking.
124    Wake,
125}
126
127/// Identical sensor membership rules to the dimensional overlap queries.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub enum RadialSensors {
130    Exclude,
131    Include,
132    Only,
133}
134
135/// Explicit blast policy. See the module's runnable fixed-tick lab recipes.
136/// No default model, falloff or zero-distance axis is chosen for the caller.
137#[derive(Clone, Copy, Debug, PartialEq)]
138pub struct RadialImpulseRequest {
139    /// World units. Planar requests require z == 0.
140    pub center: Vec3,
141    /// Existing sphere-query radius range: finite 0..=1000.
142    pub radius: f32,
143    pub model: ImpulseModel,
144    pub falloff: Falloff,
145    pub zero_distance: ZeroDistance,
146    pub sleeping: SleepingPolicy,
147    pub sensors: RadialSensors,
148    /// Collider membership mask, independent of collision response bits.
149    pub layers: u32,
150    /// Exclude all children of this exact generational body handle.
151    pub ignored_body: Option<RigidBodyHandle>,
152    /// Maximum accepted unique bodies. Output must hold this requested capacity.
153    pub max_bodies: usize,
154    /// Maximum live colliders in the world, including filtered/fixed colliders.
155    /// Reject before query work when exceeded. See [`apply_radial_impulse`].
156    pub max_colliders: usize,
157}
158
159/// Exact accepted impulse; zero/underflow impulses and skipped bodies are absent.
160/// Output order is ascending generational body handle, independent of child order.
161#[derive(Clone, Copy, Debug, PartialEq)]
162pub struct RadialImpulse {
163    pub body: RigidBodyHandle,
164    /// Nearest accepted child, with ascending collider handle breaking ties.
165    pub collider: ColliderHandle,
166    /// Signed sphere-probe separation from the existing overlap query.
167    pub separation: f32,
168    pub impulse: Vec3,
169}
170
171/// Counts for one successful invocation; no counters persist between invocations.
172#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
173#[must_use]
174pub struct RadialImpulseReport {
175    /// Live colliders admitted by the work bound (including filtered colliders).
176    pub colliders: usize,
177    /// Complete accepted query children, including non-dynamic/skipped bodies.
178    pub candidates: usize,
179    pub applied: usize,
180}
181
182/// Atomic rejection: world state and accepted output remain unchanged.
183/// Candidate scratch is unspecified after any error.
184#[derive(Clone, Copy, Debug, PartialEq, Eq)]
185#[non_exhaustive]
186pub enum RadialImpulseError {
187    InvalidCenter,
188    InvalidRadius,
189    InvalidMagnitude,
190    InvalidZeroAxis,
191    /// Output length is smaller than the requested max-body capacity.
192    OutputCapacity {
193        required: usize,
194    },
195    /// World live-collider count exceeds the caller's work limit.
196    WorkLimit {
197        required: usize,
198    },
199    /// Complete query candidates did not fit. No first-N effects are applied.
200    CandidateCapacity {
201        required: usize,
202    },
203    BodyLimit {
204        required: usize,
205    },
206    /// A query distance/witness or COM cannot be represented reliably as finite.
207    IncompleteGeometry {
208        collider: ColliderHandle,
209    },
210    /// An admitted body has pending mass edits; refresh explicitly before retry.
211    /// This helper never refreshes mass as part of a supposedly atomic rejection.
212    PendingMass {
213        body: RigidBodyHandle,
214    },
215    /// Impulse, its f32 mass product or resulting velocity would be nonfinite.
216    NonFiniteEffect {
217        body: RigidBodyHandle,
218    },
219}
220impl std::fmt::Display for RadialImpulseError {
221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222        write!(f, "radial impulse: {self:?}")
223    }
224}
225impl std::error::Error for RadialImpulseError {}
226
227// Sealing prevents user callbacks/forged hits from claiming query completeness.
228mod sealed {
229    use super::*;
230    pub trait Candidate: Copy {
231        fn parts(self) -> (RigidBodyHandle, ColliderHandle, f32);
232    }
233    pub trait Body: Access {
234        fn apply(&mut self, impulse: Vec3, wake: bool);
235    }
236    pub trait Adapter {
237        type Body: Body;
238        type Candidate: Candidate;
239        fn raw(&self) -> &World<Self::Body>;
240        fn raw_mut(&mut self) -> &mut World<Self::Body>;
241        fn planar(&self) -> bool;
242        fn query(
243            &self,
244            request: RadialImpulseRequest,
245            scratch: &mut [Option<Self::Candidate>],
246        ) -> (usize, usize);
247    }
248}
249
250/// Sealed adapter for the existing d2/d3 `PhysicsWorld`s. See the module recipes.
251/// Generic consumers can accept `W: RadialWorld`; no caller-provided detector or
252/// callback runs between preflight and commit. The shared kernel uses `World<B>`.
253///
254/// ```
255/// use ferravex_physics::radial::*;
256/// fn tick_pulse<W: RadialWorld>(world: &mut W, request: RadialImpulseRequest,
257///     scratch: &mut [Option<W::Candidate>], accepted: &mut [Option<RadialImpulse>])
258///     -> Result<RadialImpulseReport, RadialImpulseError>
259/// {
260///     apply_radial_impulse(world, request, scratch, accepted)
261/// }
262/// ```
263pub trait RadialWorld: sealed::Adapter {}
264
265#[cfg(any(feature = "dim2", feature = "dim3"))]
266macro_rules! dimension_adapter {
267    ($module:ident, $planar:expr, $array:expr, $vector:expr) => {
268        impl sealed::Body for crate::$module::RigidBody {
269            fn apply(&mut self, impulse: Vec3, wake: bool) {
270                self.apply_impulse(($vector)(impulse), wake);
271            }
272        }
273        impl sealed::Candidate for crate::$module::OverlapHit {
274            fn parts(self) -> (RigidBodyHandle, ColliderHandle, f32) {
275                (
276                    self.body.expect("overlap queries return attached children"),
277                    self.collider,
278                    self.separation,
279                )
280            }
281        }
282        impl sealed::Adapter for crate::$module::PhysicsWorld {
283            type Body = crate::$module::RigidBody;
284            type Candidate = crate::$module::OverlapHit;
285            fn raw(&self) -> &World<Self::Body> {
286                &self.raw
287            }
288            fn raw_mut(&mut self) -> &mut World<Self::Body> {
289                &mut self.raw
290            }
291            fn planar(&self) -> bool {
292                $planar
293            }
294            fn query(
295                &self,
296                request: RadialImpulseRequest,
297                scratch: &mut [Option<Self::Candidate>],
298            ) -> (usize, usize) {
299                use crate::$module::{QueryOptions, SensorPolicy};
300                let options = QueryOptions {
301                    max_distance: 0.,
302                    layers: request.layers,
303                    ignored_body: request.ignored_body,
304                    sensors: match request.sensors {
305                        RadialSensors::Exclude => SensorPolicy::Exclude,
306                        RadialSensors::Include => SensorPolicy::Include,
307                        RadialSensors::Only => SensorPolicy::Only,
308                    },
309                };
310                let result = self
311                    .overlap_sphere_into(($array)(request.center), request.radius, options, scratch)
312                    .expect("radial request validated query inputs");
313                (result.written, result.total)
314            }
315        }
316        impl RadialWorld for crate::$module::PhysicsWorld {}
317    };
318}
319#[cfg(feature = "dim2")]
320dimension_adapter!(d2, true, |v: Vec3| [v.x, v.y], |v: Vec3| v.truncate());
321#[cfg(feature = "dim3")]
322dimension_adapter!(d3, false, |v: Vec3| v.to_array(), |v: Vec3| v);
323
324use sealed::{Body, Candidate};
325
326/// Check the complete blast, then apply existing body COM-impulse methods once
327/// per accepted body. See the module for runnable recipes in both dimensions.
328///
329/// `candidates` is dimensional `Option<OverlapHit>` scratch. Every query hit must
330/// fit, including fixed/kinematic/sensor children; the caller can size it to the
331/// world's collider count. `output.len() >= request.max_bodies` is required even
332/// for a miss. Every Err preserves all accepted output entries. Success writes
333/// exactly `report.applied` entries and clears the entire remaining output.
334///
335/// Work is bounded by the requested live-collider limit, the existing bounded
336/// arenas and caller slice lengths: one numeric guard pass, one existing overlap
337/// pass (sorted insertion at most O(C * min(C, scratch.len()))), in-place unstable
338/// O(H log H) canonical sorting, and bounded body/child passes. There is no heap
339/// allocation. This is a work-admission bound, not a time/throughput guarantee.
340///
341/// Falloff is derived from task220's signed separation, never a body-origin
342/// radius test. Nonzero impulses that round to zero are omitted. Total-budget
343/// distribution is not renormalized after f32 underflow. All f32 multiply/add
344/// intermediates used by the existing impulse method are checked, not just the
345/// wider mathematical result. Pending child mass edits reject without refreshing.
346/// Forces, torque, angular velocity and kinematic targets are never modified.
347/// No bitwise cross-platform determinism or concurrent-world safety is claimed.
348pub fn apply_radial_impulse<W: RadialWorld>(
349    world: &mut W,
350    request: RadialImpulseRequest,
351    candidates: &mut [Option<W::Candidate>],
352    output: &mut [Option<RadialImpulse>],
353) -> Result<RadialImpulseReport, RadialImpulseError> {
354    let axis = validate_request(request, world.planar(), output.len())?;
355    let colliders = world.raw().colliders.len();
356    if colliders > request.max_colliders {
357        return Err(RadialImpulseError::WorkLimit {
358            required: colliders,
359        });
360    }
361    world.raw().radial_check_geometry(request)?;
362    let (written, total) = world.query(request, candidates);
363    if written != total {
364        return Err(RadialImpulseError::CandidateCapacity { required: total });
365    }
366    let hits = &mut candidates[..written];
367    hits.sort_unstable_by(|a, b| {
368        let (ab, ac, ad) = a.unwrap().parts();
369        let (bb, bc, bd) = b.unwrap().parts();
370        ab.cmp(&bb)
371            .then_with(|| ad.total_cmp(&bd))
372            .then(ac.cmp(&bc))
373    });
374    // Select exactly one (nearest, then lowest collider) candidate per body.
375    let selected = || {
376        unique_hits(hits).filter_map(|hit| {
377            let (body, collider, separation) = hit.parts();
378            let core = world.raw().bodies[body].core();
379            if core.kind != Kind::Dynamic
380                || (core.sleeping && request.sleeping == SleepingPolicy::Skip)
381            {
382                return None;
383            }
384            let weight = weight(request, separation);
385            let direction = direction(core.world_com(), request.center).or(axis);
386            (weight > 0.).then_some((body, collider, separation, weight, direction?))
387        })
388    };
389    let weight_sum = selected().map(|v| v.3).sum::<f64>();
390    let mut applied = 0;
391    for (body, _, _, weight, direction) in selected() {
392        let impulse = impulse(request.model, weight, weight_sum, direction);
393        world.raw().radial_check_effect(body, impulse)?;
394        if impulse != Vec3::ZERO {
395            applied += 1;
396        }
397    }
398    if applied > request.max_bodies {
399        return Err(RadialImpulseError::BodyLimit { required: applied });
400    }
401    // No fallible callbacks or world edits intervene. Recomputing the checked
402    // scalar effects avoids using/changing caller output as temporary storage.
403    output.fill(None);
404    let mut count = 0;
405    for hit in unique_hits(hits) {
406        let (body, collider, separation) = hit.parts();
407        let core = world.raw().bodies[body].core();
408        if core.kind != Kind::Dynamic || (core.sleeping && request.sleeping == SleepingPolicy::Skip)
409        {
410            continue;
411        }
412        let Some(direction) = direction(core.world_com(), request.center).or(axis) else {
413            continue;
414        };
415        let impulse = impulse(
416            request.model,
417            weight(request, separation),
418            weight_sum,
419            direction,
420        );
421        if impulse == Vec3::ZERO {
422            continue;
423        }
424        world
425            .raw_mut()
426            .bodies
427            .get_mut(body)
428            .unwrap()
429            .apply(impulse, request.sleeping == SleepingPolicy::Wake);
430        output[count] = Some(RadialImpulse {
431            body,
432            collider,
433            separation,
434            impulse,
435        });
436        count += 1;
437    }
438    Ok(RadialImpulseReport {
439        colliders,
440        candidates: total,
441        applied: count,
442    })
443}
444
445fn unique_hits<H: Candidate>(hits: &[Option<H>]) -> impl Iterator<Item = H> + '_ {
446    let mut previous = None;
447    hits.iter().filter_map(move |hit| {
448        let hit = hit.unwrap();
449        let body = hit.parts().0;
450        if previous == Some(body) {
451            None
452        } else {
453            previous = Some(body);
454            Some(hit)
455        }
456    })
457}
458
459fn validate_request(
460    request: RadialImpulseRequest,
461    planar: bool,
462    capacity: usize,
463) -> Result<Option<Vec3>, RadialImpulseError> {
464    use RadialImpulseError as E;
465    if !request.center.is_finite() || (planar && request.center.z != 0.) {
466        return Err(E::InvalidCenter);
467    }
468    if !request.radius.is_finite() || !(0. ..=1000.).contains(&request.radius) {
469        return Err(E::InvalidRadius);
470    }
471    let (ImpulseModel::Total(magnitude) | ImpulseModel::PerBody(magnitude)) = request.model;
472    if !magnitude.is_finite() || magnitude < 0. {
473        return Err(E::InvalidMagnitude);
474    }
475    let axis = match request.zero_distance {
476        ZeroDistance::Skip => None,
477        ZeroDistance::Axis(v) => {
478            if !v.is_finite() || (planar && v.z != 0.) {
479                return Err(E::InvalidZeroAxis);
480            }
481            Some(direction(v, Vec3::ZERO).ok_or(E::InvalidZeroAxis)?)
482        }
483    };
484    if capacity < request.max_bodies {
485        return Err(E::OutputCapacity {
486            required: request.max_bodies,
487        });
488    }
489    Ok(axis)
490}
491
492// Wide subtraction/normalization admits tiny axes and opposite finite extremes.
493fn direction(point: Vec3, center: Vec3) -> Option<Vec3> {
494    let delta = [
495        f64::from(point.x) - f64::from(center.x),
496        f64::from(point.y) - f64::from(center.y),
497        f64::from(point.z) - f64::from(center.z),
498    ];
499    let length = delta.iter().map(|v| v * v).sum::<f64>().sqrt();
500    (length.is_finite() && length > 0.).then(|| {
501        Vec3::new(
502            (delta[0] / length) as f32,
503            (delta[1] / length) as f32,
504            (delta[2] / length) as f32,
505        )
506    })
507}
508fn weight(request: RadialImpulseRequest, separation: f32) -> f64 {
509    match request.falloff {
510        Falloff::Constant => 1.,
511        Falloff::LinearSurface if request.radius == 0. => 1.,
512        Falloff::LinearSurface => {
513            (-f64::from(separation) / f64::from(request.radius)).clamp(0., 1.)
514        }
515    }
516}
517fn impulse(model: ImpulseModel, weight: f64, sum: f64, direction: Vec3) -> Vec3 {
518    let magnitude = match model {
519        ImpulseModel::PerBody(m) => f64::from(m) * weight,
520        ImpulseModel::Total(m) if sum > 0. => f64::from(m) * (weight / sum),
521        ImpulseModel::Total(_) => 0.,
522    };
523    Vec3::new(
524        (f64::from(direction.x) * magnitude) as f32,
525        (f64::from(direction.y) * magnitude) as f32,
526        (f64::from(direction.z) * magnitude) as f32,
527    )
528}
529
530impl<B: Access> World<B> {
531    // Preserve task220 completeness despite its documented finite-result omission.
532    // This is a numeric guard using the same kernel, not a replacement selection.
533    fn radial_check_geometry(
534        &self,
535        request: RadialImpulseRequest,
536    ) -> Result<(), RadialImpulseError> {
537        for (id, collider) in self.colliders.iter() {
538            let sensor = match request.sensors {
539                RadialSensors::Exclude => !collider.sensor,
540                RadialSensors::Include => true,
541                RadialSensors::Only => collider.sensor,
542            };
543            if !sensor
544                || collider.membership & request.layers == 0
545                || collider.parent == request.ignored_body
546            {
547                continue;
548            }
549            let body = collider
550                .parent
551                .and_then(|h| self.bodies.get(h))
552                .ok_or(RadialImpulseError::IncompleteGeometry { collider: id })?;
553            let core = body.core();
554            let pose = collider.pose(core);
555            let (distance, normal) = crate::geometry::distance(
556                collider.shape,
557                pose.position,
558                pose.rotation,
559                request.center,
560                core.planar,
561            );
562            if !pose.position.is_finite()
563                || !pose.rotation.is_finite()
564                || !core.world_com().is_finite()
565                || !distance.is_finite()
566                || !(distance - request.radius).is_finite()
567                || !normal.is_finite()
568                || !(request.center - normal * distance).is_finite()
569                || !(request.center - normal * request.radius).is_finite()
570            {
571                return Err(RadialImpulseError::IncompleteGeometry { collider: id });
572            }
573        }
574        Ok(())
575    }
576
577    fn radial_check_effect(
578        &self,
579        body: RigidBodyHandle,
580        impulse: Vec3,
581    ) -> Result<(), RadialImpulseError> {
582        if impulse == Vec3::ZERO {
583            return Ok(());
584        }
585        let core = self.bodies[body].core();
586        if core
587            .colliders
588            .iter()
589            .any(|id| self.colliders[*id].mass_dirty)
590        {
591            return Err(RadialImpulseError::PendingMass { body });
592        }
593        let delta = impulse * core.inv_mass;
594        if !impulse.is_finite()
595            || !core.inv_mass.is_finite()
596            || core.inv_mass <= 0.
597            || !delta.is_finite()
598            || !(core.velocity + delta).is_finite()
599        {
600            return Err(RadialImpulseError::NonFiniteEffect { body });
601        }
602        Ok(())
603    }
604}