alice-physics 1.3.0

Deterministic 128-bit Fixed-Point Physics Engine
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
//! Simulation Modifier Core System
//!
//! Trait and wrapper for physics-driven SDF modifiers.
//! `ModifiedSdf` chains multiple modifiers that read simulation
//! fields (temperature, pressure, stress) and alter the SDF
//! distance at evaluation time.
//!
//! # Pattern
//!
//! Each modifier:
//! 1. Owns its simulation field data (`ScalarField3D`)
//! 2. Has `update(dt)` to advance simulation state
//! 3. `modify_distance(x, y, z, dist)` alters SDF distance
//!
//! # Example
//!
//! ```
//! use alice_physics::sdf_collider::ClosureSdf;
//! use alice_physics::sim_modifier::ModifiedSdf;
//! use alice_physics::thermal::{ThermalModifier, ThermalConfig};
//! use alice_physics::pressure::{PressureModifier, PressureConfig};
//! use alice_physics::sdf_collider::SdfField;
//!
//! let sphere_sdf = ClosureSdf::new(
//!     |x, y, z| (x*x + y*y + z*z).sqrt() - 1.0,
//!     |x, y, z| { let l = (x*x + y*y + z*z).sqrt().max(1e-6); (x/l, y/l, z/l) },
//! );
//! let bounds = (-2.0, -2.0, -2.0);
//! let bounds_max = (2.0, 2.0, 2.0);
//! let thermal = ThermalModifier::new(ThermalConfig::default(), 4, bounds, bounds_max);
//! let pressure = PressureModifier::new(PressureConfig::default(), 4, bounds, bounds_max);
//!
//! let modified = ModifiedSdf::new(Box::new(sphere_sdf))
//!     .with_modifier(Box::new(thermal))
//!     .with_modifier(Box::new(pressure));
//!
//! let dist = modified.distance(0.0, 0.0, 0.0);
//! ```
//!
//! Author: Moroya Sakamoto

use crate::sdf_collider::SdfField;

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

// ============================================================================
// PhysicsModifier Trait
// ============================================================================

/// Trait for simulation-driven SDF modifiers
pub trait PhysicsModifier: Send + Sync {
    /// Modify the SDF distance at a world-space point.
    ///
    /// Returns the modified distance. Positive offset = surface recedes
    /// (material removed). Negative offset = surface expands.
    fn modify_distance(&self, x: f32, y: f32, z: f32, original_dist: f32) -> f32;

    /// Advance the simulation state by dt seconds.
    fn update(&mut self, dt: f32);

    /// Name of this modifier (for debugging)
    fn name(&self) -> &str;

    /// Whether this modifier has any active effect
    fn is_active(&self) -> bool {
        true
    }
}

// ============================================================================
// ModifiedSdf
// ============================================================================

/// SDF wrapper that applies a chain of physics modifiers.
///
/// Implements `SdfField`, so it can be used anywhere an SDF is expected.
pub struct ModifiedSdf {
    /// Original SDF field
    original: Box<dyn SdfField>,
    /// Chain of modifiers (applied in order)
    modifiers: Vec<Box<dyn PhysicsModifier>>,
    /// Epsilon for normal computation
    normal_eps: f32,
}

impl ModifiedSdf {
    /// Create a new modified SDF wrapping the original field
    #[must_use]
    pub fn new(original: Box<dyn SdfField>) -> Self {
        Self {
            original,
            modifiers: Vec::new(),
            normal_eps: 0.001,
        }
    }

    /// Add a modifier to the chain
    #[must_use]
    pub fn with_modifier(mut self, modifier: Box<dyn PhysicsModifier>) -> Self {
        self.modifiers.push(modifier);
        self
    }

    /// Add a modifier (mutable)
    pub fn add_modifier(&mut self, modifier: Box<dyn PhysicsModifier>) {
        self.modifiers.push(modifier);
    }

    /// Remove all modifiers
    pub fn clear_modifiers(&mut self) {
        self.modifiers.clear();
    }

    /// Number of active modifiers
    #[must_use]
    pub fn modifier_count(&self) -> usize {
        self.modifiers.len()
    }

    /// Update all modifier simulations
    pub fn update(&mut self, dt: f32) {
        for m in &mut self.modifiers {
            m.update(dt);
        }
    }

    /// Get mutable access to a modifier by index
    #[allow(clippy::option_if_let_else)]
    pub fn modifier_mut(&mut self, index: usize) -> Option<&mut dyn PhysicsModifier> {
        match self.modifiers.get_mut(index) {
            Some(m) => Some(m.as_mut()),
            None => None,
        }
    }

    /// Evaluate the modified distance at a point
    #[inline]
    fn eval_distance(&self, x: f32, y: f32, z: f32) -> f32 {
        let mut d = self.original.distance(x, y, z);
        for m in &self.modifiers {
            if m.is_active() {
                d = m.modify_distance(x, y, z, d);
            }
        }
        d
    }
}

impl SdfField for ModifiedSdf {
    #[inline]
    fn distance(&self, x: f32, y: f32, z: f32) -> f32 {
        self.eval_distance(x, y, z)
    }

    #[inline]
    fn normal(&self, x: f32, y: f32, z: f32) -> (f32, f32, f32) {
        let e = self.normal_eps;
        let dx = self.eval_distance(x + e, y, z) - self.eval_distance(x - e, y, z);
        let dy = self.eval_distance(x, y + e, z) - self.eval_distance(x, y - e, z);
        let dz = self.eval_distance(x, y, z + e) - self.eval_distance(x, y, z - e);

        let len = dz.mul_add(dz, dx.mul_add(dx, dy * dy)).sqrt();
        if len < 1e-10 {
            (0.0, 1.0, 0.0)
        } else {
            (dx / len, dy / len, dz / len)
        }
    }

    fn distance_and_normal(&self, x: f32, y: f32, z: f32) -> (f32, (f32, f32, f32)) {
        let d = self.eval_distance(x, y, z);
        let n = self.normal(x, y, z);
        (d, n)
    }
}

// ============================================================================
// SingleModifiedSdf (lightweight single-modifier wrapper)
// ============================================================================

/// Lightweight SDF wrapper for a single modifier (avoids Vec overhead)
pub struct SingleModifiedSdf<M: PhysicsModifier> {
    /// Original SDF
    pub original: Box<dyn SdfField>,
    /// The modifier
    pub modifier: M,
    /// Epsilon for normals
    normal_eps: f32,
}

impl<M: PhysicsModifier> SingleModifiedSdf<M> {
    /// Create wrapper with a single modifier
    pub fn new(original: Box<dyn SdfField>, modifier: M) -> Self {
        Self {
            original,
            modifier,
            normal_eps: 0.001,
        }
    }

    /// Update the modifier simulation
    pub fn update(&mut self, dt: f32) {
        self.modifier.update(dt);
    }

    #[inline]
    fn eval_distance(&self, x: f32, y: f32, z: f32) -> f32 {
        let d = self.original.distance(x, y, z);
        self.modifier.modify_distance(x, y, z, d)
    }
}

impl<M: PhysicsModifier> SdfField for SingleModifiedSdf<M> {
    #[inline]
    fn distance(&self, x: f32, y: f32, z: f32) -> f32 {
        self.eval_distance(x, y, z)
    }

    #[inline]
    fn normal(&self, x: f32, y: f32, z: f32) -> (f32, f32, f32) {
        let e = self.normal_eps;
        let dx = self.eval_distance(x + e, y, z) - self.eval_distance(x - e, y, z);
        let dy = self.eval_distance(x, y + e, z) - self.eval_distance(x, y - e, z);
        let dz = self.eval_distance(x, y, z + e) - self.eval_distance(x, y, z - e);

        let len = dz.mul_add(dz, dx.mul_add(dx, dy * dy)).sqrt();
        if len < 1e-10 {
            (0.0, 1.0, 0.0)
        } else {
            (dx / len, dy / len, dz / len)
        }
    }

    fn distance_and_normal(&self, x: f32, y: f32, z: f32) -> (f32, (f32, f32, f32)) {
        let d = self.eval_distance(x, y, z);
        let n = self.normal(x, y, z);
        (d, n)
    }
}

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

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

    /// Simple modifier that uniformly expands the SDF
    struct ExpandModifier {
        amount: f32,
    }

    impl PhysicsModifier for ExpandModifier {
        fn modify_distance(&self, _x: f32, _y: f32, _z: f32, d: f32) -> f32 {
            d - self.amount
        }
        fn update(&mut self, _dt: f32) {}
        fn name(&self) -> &'static str {
            "expand"
        }
    }

    #[test]
    fn test_modified_sdf_no_modifiers() {
        let sphere = ClosureSdf::new(
            |x, y, z| z.mul_add(z, x.mul_add(x, y * y)).sqrt() - 1.0,
            |x, y, z| {
                let len = z.mul_add(z, x.mul_add(x, y * y)).sqrt();
                if len < 1e-10 {
                    (0.0, 1.0, 0.0)
                } else {
                    (x / len, y / len, z / len)
                }
            },
        );

        let modified = ModifiedSdf::new(Box::new(sphere));
        let d = modified.distance(2.0, 0.0, 0.0);
        assert!(
            (d - 1.0).abs() < 0.01,
            "No modifiers should pass through, got {d}"
        );
    }

    #[test]
    fn test_modified_sdf_expand() {
        let sphere = ClosureSdf::new(
            |x, y, z| z.mul_add(z, x.mul_add(x, y * y)).sqrt() - 1.0,
            |x, y, z| {
                let len = z.mul_add(z, x.mul_add(x, y * y)).sqrt();
                if len < 1e-10 {
                    (0.0, 1.0, 0.0)
                } else {
                    (x / len, y / len, z / len)
                }
            },
        );

        let modified = ModifiedSdf::new(Box::new(sphere))
            .with_modifier(Box::new(ExpandModifier { amount: 0.5 }));

        // Original: distance at (2,0,0) = 1.0
        // After expand by 0.5: distance = 0.5
        let d = modified.distance(2.0, 0.0, 0.0);
        assert!(
            (d - 0.5).abs() < 0.01,
            "Expand should reduce distance, got {d}"
        );
    }

    #[test]
    fn test_modifier_chain() {
        let sphere = ClosureSdf::new(
            |x, y, z| z.mul_add(z, x.mul_add(x, y * y)).sqrt() - 1.0,
            |x, y, z| {
                let len = z.mul_add(z, x.mul_add(x, y * y)).sqrt();
                if len < 1e-10 {
                    (0.0, 1.0, 0.0)
                } else {
                    (x / len, y / len, z / len)
                }
            },
        );

        let modified = ModifiedSdf::new(Box::new(sphere))
            .with_modifier(Box::new(ExpandModifier { amount: 0.3 }))
            .with_modifier(Box::new(ExpandModifier { amount: 0.2 }));

        // Total expand = 0.5
        let d = modified.distance(2.0, 0.0, 0.0);
        assert!(
            (d - 0.5).abs() < 0.01,
            "Chain should sum expansions, got {d}"
        );
    }

    #[test]
    fn test_single_modified_sdf() {
        let sphere = ClosureSdf::new(
            |x, y, z| z.mul_add(z, x.mul_add(x, y * y)).sqrt() - 1.0,
            |x, y, z| {
                let len = z.mul_add(z, x.mul_add(x, y * y)).sqrt();
                if len < 1e-10 {
                    (0.0, 1.0, 0.0)
                } else {
                    (x / len, y / len, z / len)
                }
            },
        );

        let modified = SingleModifiedSdf::new(Box::new(sphere), ExpandModifier { amount: 0.5 });

        let d = modified.distance(2.0, 0.0, 0.0);
        assert!((d - 0.5).abs() < 0.01, "Single modifier expand, got {d}");
    }

    /// 地面 (distance = y): 数値誤差なしで offset を観測できる
    fn ground() -> ClosureSdf {
        ClosureSdf::new(|_x, y, _z| y, |_x, _y, _z| (0.0, 1.0, 0.0))
    }

    /// update(dt) で amount が dt ずつ増える (状態を持つ) modifier
    struct GrowModifier {
        amount: f32,
    }

    impl PhysicsModifier for GrowModifier {
        fn modify_distance(&self, _x: f32, _y: f32, _z: f32, d: f32) -> f32 {
            d - self.amount
        }
        fn update(&mut self, dt: f32) {
            self.amount += dt;
        }
        fn name(&self) -> &'static str {
            "grow"
        }
    }

    #[test]
    fn clear_modifiers_restores_original_field_and_allows_re_adding() {
        let mut modified = ModifiedSdf::new(Box::new(ground()))
            .with_modifier(Box::new(ExpandModifier { amount: 0.25 }))
            .with_modifier(Box::new(ExpandModifier { amount: 0.5 }));
        assert_eq!(modified.modifier_count(), 2);
        // y = 2 → 2 - 0.25 - 0.5 = 1.25
        assert!((modified.distance(0.0, 2.0, 0.0) - 1.25).abs() < 1e-6);

        modified.clear_modifiers();
        assert_eq!(modified.modifier_count(), 0);
        assert!(modified.modifier_mut(0).is_none());
        // 元の field そのまま
        assert!((modified.distance(0.0, 2.0, 0.0) - 2.0).abs() < 1e-6);
        let (nx, ny, nz) = modified.normal(0.0, 2.0, 0.0);
        assert!(nx.abs() < 1e-6 && (ny - 1.0).abs() < 1e-6 && nz.abs() < 1e-6);
        // 空でもう一度 clear しても問題なし、再追加で再び効く
        modified.clear_modifiers();
        modified.add_modifier(Box::new(ExpandModifier { amount: 1.0 }));
        assert_eq!(modified.modifier_count(), 1);
        assert!((modified.distance(0.0, 2.0, 0.0) - 1.0).abs() < 1e-6);
    }

    #[test]
    fn modifier_mut_gives_in_place_access_by_index() {
        let mut modified = ModifiedSdf::new(Box::new(ground()))
            .with_modifier(Box::new(GrowModifier { amount: 0.25 }))
            .with_modifier(Box::new(ExpandModifier { amount: 0.5 }));
        // y = 2 → 2 - 0.25 - 0.5 = 1.25
        assert!((modified.distance(0.0, 2.0, 0.0) - 1.25).abs() < 1e-6);

        // index 順に対応する modifier が返る
        assert_eq!(modified.modifier_mut(0).map(|m| m.name()), Some("grow"));
        assert_eq!(modified.modifier_mut(1).map(|m| m.name()), Some("expand"));
        assert!(modified.modifier_mut(2).is_none());

        // 返された &mut を通した update は field に反映される: grow 0.25 → 0.75
        match modified.modifier_mut(0) {
            Some(m) => m.update(0.5),
            None => panic!("modifier 0 must exist"),
        }
        assert!((modified.distance(0.0, 2.0, 0.0) - 0.75).abs() < 1e-6);
        // expand (index 1) は状態を持たないので update しても不変
        match modified.modifier_mut(1) {
            Some(m) => m.update(0.5),
            None => panic!("modifier 1 must exist"),
        }
        assert!((modified.distance(0.0, 2.0, 0.0) - 0.75).abs() < 1e-6);
        // ModifiedSdf::update(dt) は全 modifier を進める = modifier_mut(0).update と同じ効果
        modified.update(0.25);
        assert!((modified.distance(0.0, 2.0, 0.0) - 0.5).abs() < 1e-6);
        assert_eq!(modified.modifier_count(), 2);
    }
}