alice-physics 2.2.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
//! Deformable Body Simulation (FEM-XPBD)
//!
//! Tetrahedral mesh deformable bodies using XPBD volume + shape constraints.
//! Supports SDF collision for deformable-rigid interaction.
//!
//! # Algorithm
//!
//! - Volume constraints preserve tetrahedral volume
//! - Shape matching constraints resist deformation
//! - Edge constraints prevent over-stretching
//! - SDF collision for surface contacts
//!
//! Author: Moroya Sakamoto

use crate::math::{Fix128, Vec3Fix};
#[cfg(feature = "std")]
use crate::sdf_collider::SdfCollider;

#[cfg(not(feature = "std"))]
use alloc::vec;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

// ============================================================================
// Deformable Configuration
// ============================================================================

/// Deformable body configuration
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DeformableConfig {
    /// Solver iterations
    pub iterations: usize,
    /// Number of substeps
    pub substeps: usize,
    /// Gravity
    pub gravity: Vec3Fix,
    /// Velocity retention per frame (`step()` call), applied once per frame since 1.2.0
    pub damping: Fix128,
    /// Volume preservation compliance (0 = rigid volume)
    pub volume_compliance: Fix128,
    /// Edge stretch compliance
    pub edge_compliance: Fix128,
    /// Shape matching stiffness (0..1, 1 = rigid)
    pub shape_stiffness: Fix128,
    /// SDF collision friction
    pub sdf_friction: Fix128,
}

impl Default for DeformableConfig {
    fn default() -> Self {
        Self {
            iterations: 8,
            substeps: 4,
            gravity: Vec3Fix::new(Fix128::ZERO, Fix128::from_int(-10), Fix128::ZERO),
            damping: Fix128::from_ratio(99, 100),
            volume_compliance: Fix128::from_ratio(1, 1000),
            edge_compliance: Fix128::ZERO,
            shape_stiffness: Fix128::from_ratio(5, 10),
            sdf_friction: Fix128::from_ratio(3, 10),
        }
    }
}

// ============================================================================
// Constraints
// ============================================================================

/// Tetrahedral volume constraint
#[derive(Clone, Copy, Debug, PartialEq)]
struct TetConstraint {
    /// Four vertex indices
    indices: [usize; 4],
    /// Rest volume (signed, preserves orientation)
    rest_volume: Fix128,
}

/// Edge length constraint
#[derive(Clone, Copy, Debug, PartialEq)]
struct EdgeConstraint {
    i0: usize,
    i1: usize,
    rest_length: Fix128,
}

// ============================================================================
// Deformable Body
// ============================================================================

/// Deformable body simulation
pub struct DeformableBody {
    /// Particle positions
    pub positions: Vec<Vec3Fix>,
    /// Previous positions
    prev_positions: Vec<Vec3Fix>,
    /// Velocities
    pub velocities: Vec<Vec3Fix>,
    /// Inverse mass per particle
    pub inv_masses: Vec<Fix128>,
    /// Tetrahedra (4 vertex indices each)
    pub tetrahedra: Vec<[usize; 4]>,
    /// Surface triangles (for rendering/collision)
    pub surface_triangles: Vec<[usize; 3]>,
    /// Tetrahedral volume constraints
    tet_constraints: Vec<TetConstraint>,
    /// Edge constraints
    edge_constraints: Vec<EdgeConstraint>,
    /// Rest positions relative to center
    rest_relative: Vec<Vec3Fix>,
    /// Configuration
    pub config: DeformableConfig,
}

impl DeformableBody {
    /// Create from particle positions and tetrahedra
    #[must_use]
    pub fn new(
        positions: Vec<Vec3Fix>,
        tetrahedra: &[[usize; 4]],
        surface_triangles: Vec<[usize; 3]>,
        mass_per_particle: Fix128,
    ) -> Self {
        let n = positions.len();
        let inv_mass = if mass_per_particle.is_zero() {
            Fix128::ZERO
        } else {
            Fix128::ONE / mass_per_particle
        };

        // Compute rest shape
        let rest_center = compute_center_of_mass(&positions);
        let rest_relative: Vec<Vec3Fix> = positions.iter().map(|p| *p - rest_center).collect();

        let mut body = Self {
            prev_positions: positions.clone(),
            velocities: vec![Vec3Fix::ZERO; n],
            inv_masses: vec![inv_mass; n],
            tetrahedra: tetrahedra.to_vec(),
            surface_triangles,
            tet_constraints: Vec::new(),
            edge_constraints: Vec::new(),
            rest_relative,
            positions,
            config: DeformableConfig::default(),
        };

        body.build_constraints();
        body
    }

    /// Create a simple cube deformable (for testing)
    #[must_use]
    pub fn new_cube(center: Vec3Fix, half_extent: Fix128, mass: Fix128) -> Self {
        let h = half_extent;
        let positions = vec![
            center + Vec3Fix::new(-h, -h, -h),
            center + Vec3Fix::new(h, -h, -h),
            center + Vec3Fix::new(h, h, -h),
            center + Vec3Fix::new(-h, h, -h),
            center + Vec3Fix::new(-h, -h, h),
            center + Vec3Fix::new(h, -h, h),
            center + Vec3Fix::new(h, h, h),
            center + Vec3Fix::new(-h, h, h),
        ];

        // 5 tetrahedra to fill a cube
        let tetrahedra = vec![
            [0, 1, 3, 4],
            [1, 2, 3, 6],
            [1, 4, 5, 6],
            [3, 4, 6, 7],
            [1, 3, 4, 6],
        ];

        let surface_triangles = vec![
            [0, 1, 2],
            [0, 2, 3], // front
            [4, 6, 5],
            [4, 7, 6], // back
            [0, 4, 5],
            [0, 5, 1], // bottom
            [2, 6, 7],
            [2, 7, 3], // top
            [0, 3, 7],
            [0, 7, 4], // left
            [1, 5, 6],
            [1, 6, 2], // right
        ];

        let mass_per_particle = mass / Fix128::from_int(8);
        Self::new(positions, &tetrahedra, surface_triangles, mass_per_particle)
    }

    /// Build constraints from geometry
    fn build_constraints(&mut self) {
        // Tetrahedral volume constraints (skip degenerate tetrahedra)
        let min_volume = Fix128::from_ratio(1, 1000000); // 1e-6
        for tet in &self.tetrahedra {
            let rest_vol = compute_tet_volume(
                self.positions[tet[0]],
                self.positions[tet[1]],
                self.positions[tet[2]],
                self.positions[tet[3]],
            );
            if rest_vol.abs() < min_volume {
                continue; // Skip degenerate (near-zero volume) tetrahedra
            }
            self.tet_constraints.push(TetConstraint {
                indices: *tet,
                rest_volume: rest_vol,
            });
        }

        // Edge constraints: unique edges from tetrahedra
        let mut edge_set: Vec<(usize, usize)> = Vec::new();
        for tet in &self.tetrahedra {
            let edges = [
                (tet[0], tet[1]),
                (tet[0], tet[2]),
                (tet[0], tet[3]),
                (tet[1], tet[2]),
                (tet[1], tet[3]),
                (tet[2], tet[3]),
            ];
            for (a, b) in edges {
                let (lo, hi) = if a < b { (a, b) } else { (b, a) };
                if !edge_set.contains(&(lo, hi)) {
                    edge_set.push((lo, hi));
                    let rest = (self.positions[a] - self.positions[b]).length();
                    self.edge_constraints.push(EdgeConstraint {
                        i0: a,
                        i1: b,
                        rest_length: rest,
                    });
                }
            }
        }
    }

    /// Number of particles
    #[inline]
    #[must_use]
    pub fn particle_count(&self) -> usize {
        self.positions.len()
    }

    /// Step simulation
    pub fn step(&mut self, dt: Fix128) {
        let substep_dt = dt / Fix128::from_int(self.config.substeps as i64);
        for _ in 0..self.config.substeps {
            self.substep(substep_dt);
        }
        self.apply_frame_damping();
    }

    /// Step with SDF collision
    #[cfg(feature = "std")]
    pub fn step_with_sdf(&mut self, dt: Fix128, sdf_colliders: &[SdfCollider]) {
        let substep_dt = dt / Fix128::from_int(self.config.substeps as i64);
        for _ in 0..self.config.substeps {
            self.substep(substep_dt);
            self.resolve_sdf_collisions(sdf_colliders);
        }
        self.apply_frame_damping();
    }

    /// `config.damping` once per frame (velocity retention per `step()` call).
    ///
    /// 1.2.0: applied per substep before, which made the terminal velocity
    /// depend on `substeps` (`g·h·d/(1−d)`, `h = dt/substeps`) — the same
    /// defect as the rigid-body solver's frame damping fix.
    fn apply_frame_damping(&mut self) {
        let d = self.config.damping;
        for v in &mut self.velocities {
            *v = *v * d;
        }
    }

    /// Single substep
    fn substep(&mut self, dt: Fix128) {
        let n = self.particle_count();

        // 1. Predict
        for i in 0..n {
            if self.inv_masses[i].is_zero() {
                continue;
            }
            self.prev_positions[i] = self.positions[i];
            self.velocities[i] = self.velocities[i] + self.config.gravity * dt;
            self.positions[i] = self.positions[i] + self.velocities[i] * dt;
        }

        // 2. Solve constraints
        for _ in 0..self.config.iterations {
            self.solve_edge_constraints(dt);
            self.solve_volume_constraints(dt);
            self.apply_shape_matching();
        }

        // 3. Update velocities
        let inv_dt = Fix128::ONE / dt;
        for i in 0..n {
            if self.inv_masses[i].is_zero() {
                continue;
            }
            self.velocities[i] = (self.positions[i] - self.prev_positions[i]) * inv_dt;
        }
    }

    /// Solve edge constraints
    fn solve_edge_constraints(&mut self, dt: Fix128) {
        let compliance = self.config.edge_compliance / (dt * dt);

        for c_idx in 0..self.edge_constraints.len() {
            let c = self.edge_constraints[c_idx];
            let p0 = self.positions[c.i0];
            let p1 = self.positions[c.i1];
            let w0 = self.inv_masses[c.i0];
            let w1 = self.inv_masses[c.i1];

            let w_sum = w0 + w1 + compliance;
            if w_sum.is_zero() {
                continue;
            }

            let delta = p1 - p0;
            let dist = delta.length();
            if dist.is_zero() {
                continue;
            }

            let error = dist - c.rest_length;
            let lambda = error / w_sum;
            let correction = delta / dist * lambda;

            if !w0.is_zero() {
                self.positions[c.i0] = self.positions[c.i0] + correction * w0;
            }
            if !w1.is_zero() {
                self.positions[c.i1] = self.positions[c.i1] - correction * w1;
            }
        }
    }

    /// Solve tetrahedral volume constraints
    fn solve_volume_constraints(&mut self, dt: Fix128) {
        let compliance = self.config.volume_compliance / (dt * dt);

        for c_idx in 0..self.tet_constraints.len() {
            let c = self.tet_constraints[c_idx];
            let [i0, i1, i2, i3] = c.indices;

            let p0 = self.positions[i0];
            let p1 = self.positions[i1];
            let p2 = self.positions[i2];
            let p3 = self.positions[i3];

            let current_vol = compute_tet_volume(p0, p1, p2, p3);
            let error = current_vol - c.rest_volume;

            if error.abs() < Fix128::from_ratio(1, 10000) {
                continue;
            }

            // Gradients of volume w.r.t. each vertex
            let g0 = (p1 - p3).cross(p2 - p3);
            let g1 = (p2 - p3).cross(p0 - p3);
            let g2 = (p0 - p3).cross(p1 - p3);
            let g3 = -(g0 + g1 + g2);

            let w0 = self.inv_masses[i0];
            let w1 = self.inv_masses[i1];
            let w2 = self.inv_masses[i2];
            let w3 = self.inv_masses[i3];

            let denom = w0 * g0.length_squared()
                + w1 * g1.length_squared()
                + w2 * g2.length_squared()
                + w3 * g3.length_squared()
                + compliance;

            if denom.is_zero() {
                continue;
            }

            let lambda = error / denom;
            let six = Fix128::from_int(6);

            if !w0.is_zero() {
                self.positions[i0] = self.positions[i0] - g0 * (lambda * w0 / six);
            }
            if !w1.is_zero() {
                self.positions[i1] = self.positions[i1] - g1 * (lambda * w1 / six);
            }
            if !w2.is_zero() {
                self.positions[i2] = self.positions[i2] - g2 * (lambda * w2 / six);
            }
            if !w3.is_zero() {
                self.positions[i3] = self.positions[i3] - g3 * (lambda * w3 / six);
            }
        }
    }

    /// Shape matching: move particles toward their rest pose
    fn apply_shape_matching(&mut self) {
        let alpha = self.config.shape_stiffness;
        if alpha.is_zero() {
            return;
        }

        // Current center of mass
        let current_center = compute_center_of_mass(&self.positions);

        // LIMITATION(COV-SOFT-017): Simplified shape matching: blend toward rest shape
        // Simplified shape matching: blend toward rest shape
        for i in 0..self.particle_count() {
            if self.inv_masses[i].is_zero() {
                continue;
            }

            let target = current_center + self.rest_relative[i];
            let delta = target - self.positions[i];
            self.positions[i] = self.positions[i] + delta * alpha;
        }
    }

    /// Resolve SDF collisions
    #[cfg(feature = "std")]
    fn resolve_sdf_collisions(&mut self, sdf_colliders: &[SdfCollider]) {
        for i in 0..self.particle_count() {
            if self.inv_masses[i].is_zero() {
                continue;
            }

            for sdf in sdf_colliders {
                let (lx, ly, lz) = sdf.world_to_local(self.positions[i]);
                let dist = sdf.field.distance(lx, ly, lz) * sdf.scale_f32;

                if dist < 0.0 {
                    let (nx, ny, nz) = sdf.field.normal(lx, ly, lz);
                    let normal = sdf.local_normal_to_world(nx, ny, nz);
                    let depth = Fix128::from_f32(-dist);
                    self.positions[i] = self.positions[i] + normal * depth;

                    let vel = self.velocities[i];
                    let vn = normal * vel.dot(normal);
                    let vt = vel - vn;
                    self.velocities[i] = vt * (Fix128::ONE - self.config.sdf_friction);
                }
            }
        }
    }

    /// Centroid of the particle positions. Every constructor gives all particles the same
    /// mass, for which this is the centre of mass; it is **not** mass weighted if
    /// `inv_masses` are edited to differ. Zero for a body without particles.
    #[must_use]
    pub fn center_of_mass(&self) -> Vec3Fix {
        compute_center_of_mass(&self.positions)
    }

    /// Resolve collisions between deformable body particles and rigid bodies
    ///
    // LIMITATION(COV-SOFT-059): Treats each rigid body as a sphere with given radius for simplicity.
    /// Treats each rigid body as a sphere with given radius for simplicity.
    /// Applies two-way coupling: deformable particles are pushed out,
    /// and rigid bodies receive reaction impulses.
    ///
    /// The correction and the (perfectly inelastic) normal impulse are shared by inverse
    /// mass, `w_p / (w_p + w_b)` to the particle and `w_b / (w_p + w_b)` to the body; a body
    /// with zero inverse mass (static, kinematic) takes none, so a particle pressed into it
    /// ends exactly on its surface with zero approach speed. A particle exactly at the
    /// centre of a body has no push direction and is left untouched; pinned particles
    /// (zero inverse mass) are skipped. `dt` only gates the call (zero is a no-op).
    pub fn resolve_rigid_body_collisions(
        &mut self,
        rigid_bodies: &mut [crate::solver::RigidBody],
        body_radii: &[Fix128],
        dt: Fix128,
    ) {
        if dt.is_zero() {
            return;
        }

        for i in 0..self.particle_count() {
            if self.inv_masses[i].is_zero() {
                continue;
            }

            for (rb_idx, rb) in rigid_bodies.iter_mut().enumerate() {
                if rb.is_static() && rb_idx >= body_radii.len() {
                    continue;
                }
                let radius = if rb_idx < body_radii.len() {
                    body_radii[rb_idx]
                } else {
                    Fix128::ONE
                };

                let delta = self.positions[i] - rb.position;
                let dist_sq = delta.length_squared();
                let r_sq = radius * radius;

                if dist_sq < r_sq && !dist_sq.is_zero() {
                    let dist = dist_sq.sqrt();
                    let normal = delta / dist;
                    let penetration = radius - dist;

                    // Inverse-mass weights: a body with zero inverse mass (static or
                    // kinematic) is infinitely heavy and takes no share, so the particle
                    // is moved by the whole penetration and loses the whole approach
                    // speed (no finite stand-in mass, which left `m_p / (m_p + 10^6)`
                    // of the penetration and of the speed behind).
                    let w_particle = self.inv_masses[i];
                    let w_body = rb.inv_mass;
                    let w_sum = w_particle + w_body;
                    if w_sum.is_zero() {
                        continue;
                    }

                    let particle_ratio = w_particle / w_sum;
                    let rb_ratio = w_body / w_sum;

                    // Position correction
                    self.positions[i] = self.positions[i] + normal * (penetration * particle_ratio);

                    if !rb.inv_mass.is_zero() {
                        rb.position = rb.position - normal * (penetration * rb_ratio);
                    }

                    // Velocity response (inelastic along the normal)
                    let rel_vel = self.velocities[i] - rb.velocity;
                    let vel_normal = rel_vel.dot(normal);

                    if vel_normal < Fix128::ZERO {
                        let impulse_mag = -vel_normal / w_sum;
                        let impulse = normal * impulse_mag;

                        self.velocities[i] = self.velocities[i] + impulse * w_particle;
                        if !rb.inv_mass.is_zero() {
                            rb.velocity = rb.velocity - impulse * rb.inv_mass;
                        }
                    }
                }
            }
        }
    }
}

// ============================================================================
// Helpers
// ============================================================================

/// Compute center of mass
fn compute_center_of_mass(positions: &[Vec3Fix]) -> Vec3Fix {
    if positions.is_empty() {
        return Vec3Fix::ZERO;
    }
    let mut sum = Vec3Fix::ZERO;
    for p in positions {
        sum = sum + *p;
    }
    sum / Fix128::from_int(positions.len() as i64)
}

/// Compute signed volume of a tetrahedron
fn compute_tet_volume(p0: Vec3Fix, p1: Vec3Fix, p2: Vec3Fix, p3: Vec3Fix) -> Fix128 {
    let a = p1 - p0;
    let b = p2 - p0;
    let c = p3 - p0;
    a.dot(b.cross(c)) / Fix128::from_int(6)
}

impl core::fmt::Debug for DeformableBody {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("DeformableBody")
            .field(
                "positions",
                &format_args!("[{} items]", self.positions.len()),
            )
            .field(
                "prev_positions",
                &format_args!("[{} items]", self.prev_positions.len()),
            )
            .field(
                "velocities",
                &format_args!("[{} items]", self.velocities.len()),
            )
            .field(
                "inv_masses",
                &format_args!("[{} items]", self.inv_masses.len()),
            )
            .field(
                "tetrahedra",
                &format_args!("[{} items]", self.tetrahedra.len()),
            )
            .field(
                "surface_triangles",
                &format_args!("[{} items]", self.surface_triangles.len()),
            )
            .field(
                "tet_constraints",
                &format_args!("[{} items]", self.tet_constraints.len()),
            )
            .field(
                "edge_constraints",
                &format_args!("[{} items]", self.edge_constraints.len()),
            )
            .field(
                "rest_relative",
                &format_args!("[{} items]", self.rest_relative.len()),
            )
            .field("config", &self.config)
            .finish()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_deformable_cube() {
        let body = DeformableBody::new_cube(Vec3Fix::ZERO, Fix128::ONE, Fix128::from_int(10));

        assert_eq!(body.particle_count(), 8);
        assert_eq!(body.tetrahedra.len(), 5);
        assert!(!body.edge_constraints.is_empty());
        assert!(!body.tet_constraints.is_empty());
    }

    #[test]
    fn test_deformable_gravity() {
        let mut body = DeformableBody::new_cube(
            Vec3Fix::from_int(0, 5, 0),
            Fix128::ONE,
            Fix128::from_int(10),
        );

        let dt = Fix128::from_ratio(1, 60);
        for _ in 0..60 {
            body.step(dt);
        }

        let com = body.center_of_mass();
        assert!(
            com.y < Fix128::from_int(5),
            "Deformable should fall under gravity"
        );
    }

    #[test]
    fn test_tet_volume() {
        let vol = compute_tet_volume(
            Vec3Fix::ZERO,
            Vec3Fix::from_int(1, 0, 0),
            Vec3Fix::from_int(0, 1, 0),
            Vec3Fix::from_int(0, 0, 1),
        );
        // Volume of standard simplex = 1/6
        let expected = Fix128::from_ratio(1, 6);
        let error = (vol - expected).abs();
        assert!(
            error < Fix128::from_ratio(1, 100),
            "Tet volume should be 1/6"
        );
    }

    #[test]
    fn test_center_of_mass() {
        let positions = vec![
            Vec3Fix::from_int(0, 0, 0),
            Vec3Fix::from_int(2, 0, 0),
            Vec3Fix::from_int(0, 2, 0),
            Vec3Fix::from_int(0, 0, 2),
        ];

        let com = compute_center_of_mass(&positions);
        let (cx, cy, cz) = com.to_f32();
        assert!((cx - 0.5).abs() < 0.01);
        assert!((cy - 0.5).abs() < 0.01);
        assert!((cz - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_soft_rigid_coupling() {
        use crate::solver::RigidBody;

        let mut body = DeformableBody::new_cube(
            Vec3Fix::from_int(0, 0, 0),
            Fix128::ONE,
            Fix128::from_int(10),
        );

        let mut rigid_bodies = vec![RigidBody::new(
            Vec3Fix::from_int(0, 0, 0),
            Fix128::from_int(5),
        )];
        let radii = vec![Fix128::from_int(3)]; // Large sphere overlapping the cube

        let dt = Fix128::from_ratio(1, 60);
        body.resolve_rigid_body_collisions(&mut rigid_bodies, &radii, dt);

        // After collision resolution, some particles should have moved
        // and the rigid body should have received a reaction
        // This is a basic sanity test
        let com = body.center_of_mass();
        // The COM might have shifted due to collision response
        assert!(
            com.x.hi >= -10 && com.x.hi <= 10,
            "COM should be reasonable"
        );
    }

    /// 原点中心の単位球 SDF (f32 sqrt のみ、det_math gate 対象外)
    #[cfg(feature = "std")]
    fn unit_sphere_collider() -> crate::sdf_collider::SdfCollider {
        use crate::sdf_collider::{ClosureSdf, SdfCollider};
        let field = ClosureSdf::new(
            |x, y, z| (x * x + y * y + z * z).sqrt() - 1.0,
            |x, y, z| {
                let len = (x * x + y * y + z * z).sqrt();
                if len > 1e-6 {
                    (x / len, y / len, z / len)
                } else {
                    (0.0, 1.0, 0.0)
                }
            },
        );
        SdfCollider::new_static(
            Box::new(field),
            Vec3Fix::ZERO,
            crate::math::QuatFix::IDENTITY,
        )
    }

    /// 単位球からの符号付き距離 (f32 oracle)
    #[cfg(feature = "std")]
    fn sphere_dist(p: Vec3Fix) -> f32 {
        let (x, y, z) = p.to_f32();
        (x * x + y * y + z * z).sqrt() - 1.0
    }

    #[cfg(feature = "std")]
    #[test]
    fn step_with_sdf_keeps_cube_particles_outside_unit_sphere() {
        // 一辺 1 の cube (8 corner) を y = 2.5 から球の上に落とす
        let make = || {
            DeformableBody::new_cube(
                Vec3Fix::new(Fix128::ZERO, Fix128::from_ratio(5, 2), Fix128::ZERO),
                Fix128::from_ratio(1, 2),
                Fix128::from_int(8),
            )
        };
        let sphere = [unit_sphere_collider()];
        let mut body = make();
        let dt = Fix128::from_ratio(1, 60);
        let mut min_dist = f32::MAX;
        for frame in 0..60 {
            body.step_with_sdf(dt, &sphere);
            for (i, p) in body.positions.iter().enumerate() {
                let d = sphere_dist(*p);
                min_dist = min_dist.min(d);
                assert!(
                    d >= -1e-3,
                    "frame {frame} particle {i} inside sphere: dist {d}"
                );
            }
        }
        assert!(min_dist < 0.05, "never touched: min dist {min_dist}");
        // 重心は球の上 (y > 0) に留まる (貫通落下なら y < 0)
        let (_, cy, _) = body.center_of_mass().to_f32();
        assert!(cy > 0.5, "center of mass y {cy}");

        // SDF なしでは球を貫通する frame が存在する
        let mut free = make();
        let mut free_min = f32::MAX;
        for _ in 0..60 {
            free.step(dt);
            for p in &free.positions {
                free_min = free_min.min(sphere_dist(*p));
            }
        }
        assert!(
            free_min < -0.1,
            "without SDF the cube should pass through: {free_min}"
        );

        // collider が空なら step と bit 一致
        let mut a = make();
        let mut b = make();
        for _ in 0..10 {
            a.step_with_sdf(dt, &[]);
            b.step(dt);
        }
        assert_eq!(a.positions, b.positions);
        assert_eq!(a.velocities, b.velocities);
    }
}