alice-physics 3.1.0

Deterministic physics engine: 128-bit fixed-point rigid bodies with bit-exact, replayable results, typed observation and rollback for search and planning, plus FEM, CFD and 3D-print analysis modules
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! `BuoyancyZone` — 3-D fluid volume that applies buoyancy + drag to
//! immersed rigid bodies.
//!
//! Complements the existing [`crate::force::ForceField::Buoyancy`]
//! variant (infinite half-space with a horizontal water surface) by
//! modelling a **bounded** fluid volume with an explicit shape. Two
//! shapes are supported today:
//!
//! - [`ZoneShape::Aabb`] — axis-aligned box, e.g. a pool or tank.
//! - [`ZoneShape::Sphere`] — spherical pocket, e.g. a droplet or
//!   underwater cave.
//!
//! For each dynamic body inside the zone the resulting force is
//!
//! ```text
//! F = ρ_water · V_displaced · |g|  · ŷ_up
//!   − c_lin  · v
//!   − c_quad · v · |v|
//! ```
//!
// LIMITATION(COV-COUPLE-066): where `V_displaced` is estimated from a spherical body proxy of radius `body_radius`; the exact submerged volume of an arbitrary mesh is out of scope for this module and remains future work.
//! where `V_displaced` is estimated from a spherical body proxy of
//! radius `body_radius`; the exact submerged volume of an arbitrary
//! mesh is out of scope for this module and remains future work.

use crate::math::{Fix128, Vec3Fix};
use crate::solver::RigidBody;

/// Shape of the buoyancy zone volume.
#[derive(Debug, Clone, Copy)]
pub enum ZoneShape {
    /// Axis-aligned box defined by `min` and `max` corners.
    Aabb {
        /// Lower corner (inclusive).
        min: Vec3Fix,
        /// Upper corner (inclusive).
        max: Vec3Fix,
    },
    /// Sphere with a centre and radius.
    Sphere {
        /// Centre position.
        centre: Vec3Fix,
        /// Radius.
        radius: Fix128,
    },
}

impl ZoneShape {
    /// True when `point` lies strictly inside the shape.
    #[must_use]
    pub fn contains(&self, point: Vec3Fix) -> bool {
        match self {
            Self::Aabb { min, max } => {
                point.x >= min.x
                    && point.x <= max.x
                    && point.y >= min.y
                    && point.y <= max.y
                    && point.z >= min.z
                    && point.z <= max.z
            }
            Self::Sphere { centre, radius } => {
                let delta = point - *centre;
                delta.length_squared() <= (*radius) * (*radius)
            }
        }
    }

    /// Signed depth of `point` below the zone's upper surface (negative when
    /// the point is above it), or `None` when the point is outside the zone's
    /// horizontal footprint / below its floor — i.e. cannot be touching the
    /// fluid at all. Used by [`BuoyancyZone::submerged_fraction`].
    #[must_use]
    pub fn signed_depth_below_surface(&self, point: Vec3Fix) -> Option<Fix128> {
        match self {
            Self::Aabb { min, max } => {
                if point.x < min.x || point.x > max.x || point.z < min.z || point.z > max.z {
                    return None;
                }
                if point.y < min.y {
                    return None;
                }
                Some(max.y - point.y)
            }
            Self::Sphere { centre, radius } => {
                let dx = point.x - centre.x;
                let dz = point.z - centre.z;
                if dx * dx + dz * dz >= *radius * *radius {
                    return None;
                }
                if point.y < centre.y - *radius {
                    return None;
                }
                Some(centre.y + *radius - point.y)
            }
        }
    }

    /// Unsigned depth below the upper surface, `ZERO` when the point is not
    /// inside the fluid (outside the footprint, above the surface or below
    /// the floor).
    #[must_use]
    pub fn depth_below_surface(&self, point: Vec3Fix) -> Fix128 {
        match self {
            Self::Aabb { min, max } => {
                if point.x < min.x
                    || point.x > max.x
                    || point.z < min.z
                    || point.z > max.z
                    || point.y > max.y
                {
                    return Fix128::ZERO;
                }
                if point.y < min.y {
                    // below the pool floor: not in the water (pre-1.2.0 clamped
                    // to the floor and reported full depth)
                    return Fix128::ZERO;
                }
                max.y - point.y
            }
            Self::Sphere { centre, radius } => {
                let delta = point - *centre;
                let dist_squared = delta.length_squared();
                let r_squared = (*radius) * (*radius);
                if dist_squared >= r_squared {
                    return Fix128::ZERO;
                }
                let surface_y = centre.y + *radius;
                if point.y > surface_y {
                    Fix128::ZERO
                } else {
                    surface_y - point.y
                }
            }
        }
    }
}

/// Bounded fluid volume applying buoyancy + drag.
#[derive(Debug, Clone, Copy)]
pub struct BuoyancyZone {
    /// Geometry of the fluid pocket.
    pub shape: ZoneShape,
    /// Fluid density (kg/m³). Water at 20 °C is ≈ 998.
    pub density_kg_m3: Fix128,
    /// Gravity magnitude (m/s²). Positive; direction is fixed to
    /// `+y` for buoyancy (world coordinates assume `+y = up`).
    pub gravity: Fix128,
    /// Linear drag coefficient `c_lin`. Applied as `-c_lin · v`.
    pub drag_linear: Fix128,
    /// Quadratic drag coefficient `c_quad`. Applied as `-c_quad · v · |v|`.
    pub drag_quadratic: Fix128,
}

impl BuoyancyZone {
    /// Construct a zone with reasonable defaults for a water pool
    /// (ρ = 1000 kg/m³, |g| = 9.81 m/s², linear drag 0.5, quadratic drag 1.0).
    #[must_use]
    pub fn water_pool(shape: ZoneShape) -> Self {
        Self {
            shape,
            density_kg_m3: Fix128::from_int(1000),
            gravity: Fix128::from_ratio(981, 100),
            drag_linear: Fix128::from_ratio(1, 2),
            drag_quadratic: Fix128::ONE,
        }
    }

    /// Compute the buoyancy + drag force acting on `body`. `body_radius`
    /// approximates the immersed volume as a sphere; callers can pass
    /// the enclosing-sphere radius of a compound collider.
    #[must_use]
    pub fn force_on(&self, body: &RigidBody, body_radius: Fix128) -> Vec3Fix {
        let submerged_fraction = self.submerged_fraction(body.position, body_radius);
        if submerged_fraction.is_zero() {
            return Vec3Fix::ZERO;
        }

        // V_displaced = fraction · (4/3) π r³. Before this fix the constant was
        // `from_ratio(41888, 10000)` = 4.1888, 2.3e-6 above the true 4.18879020…
        // (the comment even quoted a different value, 4.18879); it now uses the
        // full-precision `Fix128::PI`.
        let four_pi_third = Fix128::PI * Fix128::from_int(4) / Fix128::from_int(3);
        let radius_cubed = body_radius * body_radius * body_radius;
        let full_volume = four_pi_third * radius_cubed;
        let displaced = full_volume * submerged_fraction;
        let buoy_magnitude = self.density_kg_m3 * displaced * self.gravity;
        let buoyancy = Vec3Fix::new(Fix128::ZERO, buoy_magnitude, Fix128::ZERO);

        // Linear drag: -c_lin · v.
        let linear_drag = if body.velocity.length_squared().is_zero() {
            Vec3Fix::ZERO
        } else {
            body.velocity * (-self.drag_linear)
        };

        // Quadratic drag: -c_quad · v · |v|.
        let speed_sq = body.velocity.length_squared();
        let quadratic_drag = if speed_sq.is_zero() {
            Vec3Fix::ZERO
        } else {
            let speed = speed_sq.sqrt();
            body.velocity * (-self.drag_quadratic * speed)
        };

        buoyancy + linear_drag + quadratic_drag
    }

    /// Submerged volume fraction (`0..=1`) of a sphere of `radius` centred
    /// at `position`: the exact spherical-cap ratio `h²(3r − h) / (4r³)` with
    /// `h = clamp(d + r, 0, 2r)`, where `d` is the signed depth of the centre
    /// below the zone's upper surface (negative above it).
    ///
    /// Continuous through the surface: a centre `r` above the surface gives
    /// 0, at the surface ½, `r` below 1. Before 1.2.0 the fraction was the
    /// linear estimate `(d + r) / 2r` (up to 9.4 % off the cap volume) and
    /// jumped from 0 to ½ as the centre crossed the surface, so a body lighter
    /// than half the fluid density could never settle
    /// (`tests/engineering_oracles_fluid.rs`). For AABB zones the centre must
    /// lie inside the horizontal footprint and above the floor; for sphere
    /// zones inside the ball's horizontal extent.
    #[must_use]
    pub fn submerged_fraction(&self, position: Vec3Fix, radius: Fix128) -> Fix128 {
        if radius <= Fix128::ZERO {
            return Fix128::ZERO;
        }
        let Some(depth) = self.shape.signed_depth_below_surface(position) else {
            return Fix128::ZERO;
        };
        let two_r = radius + radius;
        let mut h = depth + radius;
        if h <= Fix128::ZERO {
            return Fix128::ZERO;
        }
        if h >= two_r {
            return Fix128::ONE;
        }
        // cap volume / sphere volume = h²(3r − h) / (4 r³)
        h = h.min(two_r);
        let three_r_minus_h = Fix128::from_int(3) * radius - h;
        (h * h * three_r_minus_h) / (Fix128::from_int(4) * radius * radius * radius)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::solver::{BodyType, RigidBody};

    fn floating_body(y: i64) -> RigidBody {
        let mut body = RigidBody {
            position: Vec3Fix::new(Fix128::ZERO, Fix128::from_int(y), Fix128::ZERO),
            velocity: Vec3Fix::ZERO,
            inv_mass: Fix128::ONE,
            inv_inertia: Vec3Fix::ZERO,
            prev_position: Vec3Fix::ZERO,
            rotation: crate::math::QuatFix::IDENTITY,
            angular_velocity: Vec3Fix::ZERO,
            prev_rotation: crate::math::QuatFix::IDENTITY,
            restitution: Fix128::ZERO,
            friction: Fix128::ZERO,
            gravity_scale: Fix128::ONE,
            linear_damping: Fix128::ONE,
            angular_damping: Fix128::ONE,
            is_sensor: false,
            body_type: BodyType::Dynamic,
            kinematic_target: None,
        };
        body.prev_position = body.position;
        body
    }

    #[test]
    fn aabb_contains_interior_point() {
        let shape = ZoneShape::Aabb {
            min: Vec3Fix::new(
                Fix128::from_int(-1),
                Fix128::from_int(-1),
                Fix128::from_int(-1),
            ),
            max: Vec3Fix::new(
                Fix128::from_int(1),
                Fix128::from_int(1),
                Fix128::from_int(1),
            ),
        };
        assert!(shape.contains(Vec3Fix::ZERO));
        assert!(!shape.contains(Vec3Fix::new(
            Fix128::from_int(2),
            Fix128::ZERO,
            Fix128::ZERO,
        )));
    }

    #[test]
    fn sphere_contains_interior_point() {
        let shape = ZoneShape::Sphere {
            centre: Vec3Fix::ZERO,
            radius: Fix128::from_int(1),
        };
        assert!(shape.contains(Vec3Fix::new(
            Fix128::from_ratio(1, 2),
            Fix128::ZERO,
            Fix128::ZERO,
        )));
        assert!(!shape.contains(Vec3Fix::new(
            Fix128::from_int(2),
            Fix128::ZERO,
            Fix128::ZERO,
        )));
    }

    #[test]
    fn aabb_depth_zero_above_surface() {
        let shape = ZoneShape::Aabb {
            min: Vec3Fix::new(
                Fix128::from_int(-1),
                Fix128::from_int(-1),
                Fix128::from_int(-1),
            ),
            max: Vec3Fix::new(
                Fix128::from_int(1),
                Fix128::from_int(1),
                Fix128::from_int(1),
            ),
        };
        let above = Vec3Fix::new(Fix128::ZERO, Fix128::from_int(2), Fix128::ZERO);
        assert_eq!(shape.depth_below_surface(above), Fix128::ZERO);
    }

    #[test]
    fn aabb_depth_matches_expected_at_centre() {
        let shape = ZoneShape::Aabb {
            min: Vec3Fix::new(
                Fix128::from_int(-1),
                Fix128::from_int(-2),
                Fix128::from_int(-1),
            ),
            max: Vec3Fix::new(
                Fix128::from_int(1),
                Fix128::from_int(2),
                Fix128::from_int(1),
            ),
        };
        // Point at (0, 0, 0). Zone top at y = 2. Depth should be 2.
        let depth = shape.depth_below_surface(Vec3Fix::ZERO);
        assert_eq!(depth, Fix128::from_int(2));
    }

    #[test]
    fn buoyancy_produces_upward_force_when_submerged() {
        let shape = ZoneShape::Aabb {
            min: Vec3Fix::new(
                Fix128::from_int(-5),
                Fix128::from_int(-5),
                Fix128::from_int(-5),
            ),
            max: Vec3Fix::new(
                Fix128::from_int(5),
                Fix128::from_int(5),
                Fix128::from_int(5),
            ),
        };
        let zone = BuoyancyZone::water_pool(shape);
        let body = floating_body(-1);
        let force = zone.force_on(&body, Fix128::ONE);
        // Upward buoyancy => positive y component.
        assert!(force.y > Fix128::ZERO);
        // No horizontal force in resting state.
        assert_eq!(force.x, Fix128::ZERO);
        assert_eq!(force.z, Fix128::ZERO);
    }

    #[test]
    fn buoyancy_zero_when_body_above_surface() {
        let shape = ZoneShape::Aabb {
            min: Vec3Fix::new(
                Fix128::from_int(-5),
                Fix128::from_int(-5),
                Fix128::from_int(-5),
            ),
            max: Vec3Fix::new(
                Fix128::from_int(5),
                Fix128::from_int(5),
                Fix128::from_int(5),
            ),
        };
        let zone = BuoyancyZone::water_pool(shape);
        // Body at y = 10, zone max y = 5 → outside.
        let body = floating_body(10);
        let force = zone.force_on(&body, Fix128::ONE);
        assert_eq!(force, Vec3Fix::ZERO);
    }

    #[test]
    fn drag_opposes_velocity_when_submerged() {
        let shape = ZoneShape::Aabb {
            min: Vec3Fix::new(
                Fix128::from_int(-5),
                Fix128::from_int(-5),
                Fix128::from_int(-5),
            ),
            max: Vec3Fix::new(
                Fix128::from_int(5),
                Fix128::from_int(5),
                Fix128::from_int(5),
            ),
        };
        let zone = BuoyancyZone::water_pool(shape);
        let mut body = floating_body(0);
        body.velocity = Vec3Fix::new(Fix128::from_int(2), Fix128::ZERO, Fix128::ZERO);
        let force = zone.force_on(&body, Fix128::ONE);
        // Drag should be negative x (opposing velocity).
        assert!(force.x < Fix128::ZERO);
    }

    #[test]
    fn submerged_fraction_capped_at_one() {
        let shape = ZoneShape::Aabb {
            min: Vec3Fix::new(
                Fix128::from_int(-5),
                Fix128::from_int(-5),
                Fix128::from_int(-5),
            ),
            max: Vec3Fix::new(
                Fix128::from_int(5),
                Fix128::from_int(5),
                Fix128::from_int(5),
            ),
        };
        let zone = BuoyancyZone::water_pool(shape);
        let position = Vec3Fix::new(Fix128::ZERO, Fix128::from_int(-4), Fix128::ZERO);
        // Deep inside — fraction should be 1.
        let fraction = zone.submerged_fraction(position, Fix128::from_ratio(1, 2));
        assert_eq!(fraction, Fix128::ONE);
    }

    #[test]
    fn submerged_fraction_zero_above_surface() {
        let shape = ZoneShape::Aabb {
            min: Vec3Fix::new(
                Fix128::from_int(-5),
                Fix128::from_int(-5),
                Fix128::from_int(-5),
            ),
            max: Vec3Fix::new(
                Fix128::from_int(5),
                Fix128::from_int(5),
                Fix128::from_int(5),
            ),
        };
        let zone = BuoyancyZone::water_pool(shape);
        let position = Vec3Fix::new(Fix128::ZERO, Fix128::from_int(10), Fix128::ZERO);
        let fraction = zone.submerged_fraction(position, Fix128::ONE);
        assert_eq!(fraction, Fix128::ZERO);
    }

    #[test]
    fn zero_radius_has_zero_fraction() {
        let shape = ZoneShape::Aabb {
            min: Vec3Fix::new(
                Fix128::from_int(-1),
                Fix128::from_int(-1),
                Fix128::from_int(-1),
            ),
            max: Vec3Fix::new(
                Fix128::from_int(1),
                Fix128::from_int(1),
                Fix128::from_int(1),
            ),
        };
        let zone = BuoyancyZone::water_pool(shape);
        let fraction = zone.submerged_fraction(Vec3Fix::ZERO, Fix128::ZERO);
        assert_eq!(fraction, Fix128::ZERO);
    }
}