alice-physics 3.0.1

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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! Thin-Wall Detection for 3D Print Safety
//!
//! Phase A2 of the ALICE-Physics completeness project. Detects regions where
//! the local wall thickness falls below a manufacturability threshold (e.g.
//! `nozzle_diameter × 2 = 0.8mm` for a 0.4mm nozzle). Uses SDF-based sphere
//! marching along the inward surface normal to measure "opposite surface
//! distance" — the classic wall-thickness definition in 3D printing.
//!
//! # Algorithm
//!
//! For each surface sample point:
//!
//! 1. Read outward normal from the SDF gradient.
//! 2. Step slightly inward (past the surface) to enter the negative-SDF region.
//! 3. Sphere-march along the inward normal, taking steps of `|SDF|` (the exact
//!    distance to the nearest surface, Lipschitz-safe by definition of SDF).
//! 4. Stop when the SDF becomes non-negative — the ray has exited through the
//!    opposite surface. Total distance travelled = local wall thickness.
//!
//! # Determinism note
//!
//! [`SdfField`] returns `f32` (SDF evaluation is inherently floating-point);
//! measured thicknesses are therefore not bit-exact across platforms. The
//! iteration structure (max_iterations, epsilon cutoffs) IS deterministic —
//! results agree to `~epsilon` across x86 / ARM / WASM.

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

#[cfg(feature = "std")]
use crate::sdf_collider::SdfField;

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

// ============================================================================
// Configuration
// ============================================================================

/// Configuration for thin-wall detection.
#[derive(Clone, Copy, Debug)]
pub struct ThinWallConfig {
    /// Report walls thinner than this as `regions` (mm).
    ///
    /// FDM rule of thumb: `nozzle_diameter × 2` for reliable extrusion.
    /// For a 0.4mm nozzle → 0.8mm minimum wall.
    pub min_thickness_mm: Fix128,
    /// Stop ray marching after this cumulative distance (mm). Prevents infinite
    /// loops for open geometry (unbounded march) or precision starvation.
    pub max_march_distance_mm: Fix128,
    /// Safety cap on the sphere-marching iteration count.
    pub max_iterations: u32,
    /// Small offset (mm) applied along the inward normal at start of march to
    /// escape numerical noise at the surface (SDF ≈ 0).
    pub start_offset_mm: f32,
    /// Minimum step size (mm) — protects against slow convergence for near-
    /// parallel ray/surface configurations.
    pub min_step_mm: f32,
}

impl Default for ThinWallConfig {
    fn default() -> Self {
        Self {
            // 0.8mm = nozzle 0.4 × 2 (FDM industry default)
            min_thickness_mm: Fix128::from_ratio(8, 10),
            // 50mm covers typical print bed features; adjust for larger parts.
            max_march_distance_mm: Fix128::from_int(50),
            max_iterations: 128,
            start_offset_mm: 0.01,
            min_step_mm: 0.001,
        }
    }
}

impl ThinWallConfig {
    /// Construct config for a given nozzle diameter (mm).
    ///
    /// Sets `min_thickness_mm = nozzle_mm × 2` per FDM manufacturability
    /// guidance from Bambu Lab / Prusa knowledge bases.
    ///
    /// # Panics
    ///
    /// If `nozzle_mm <= 0`. A non-positive nozzle diameter has no physical
    /// meaning, and `min_thickness_mm = nozzle_mm × 2` of zero silently
    /// disabled thin-wall detection entirely (`has_thin_walls()` would
    /// never return `true`, regardless of actual geometry) — fixed
    /// 2026-10-03, `for_nozzle` silent footgun. Failing fast here is a
    /// behaviour change for any caller that was (accidentally or not)
    /// passing zero; no in-repo caller does (`grep -rn
    /// 'for_nozzle(.*ZERO\|for_nozzle(0'` at the time of this fix, excluding
    /// the oracle this change updates).
    #[must_use]
    pub fn for_nozzle(nozzle_mm: Fix128) -> Self {
        assert!(
            nozzle_mm > Fix128::ZERO,
            "for_nozzle: nozzle_mm must be positive, got {}",
            nozzle_mm.to_f64()
        );
        Self {
            min_thickness_mm: nozzle_mm.double(),
            ..Self::default()
        }
    }
}

// ============================================================================
// Reports
// ============================================================================

/// A single sample point flagged as too thin.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ThinRegion {
    /// World-space surface point where thickness was measured.
    pub position: Vec3Fix,
    /// Outward surface normal at the sample point (from SDF gradient).
    pub outward_normal: (f32, f32, f32),
    /// Measured wall thickness at this point (mm).
    pub thickness_mm: Fix128,
}

/// Result of a thin-wall analysis pass.
#[derive(Clone, Debug, Default)]
pub struct ThinWallReport {
    /// Sample points whose thickness fell below `config.min_thickness_mm`.
    pub regions: Vec<ThinRegion>,
    /// Total number of surface samples processed.
    pub sampled_count: usize,
    /// Samples for which the opposite surface was not found within
    /// `max_march_distance_mm` (open geometry or too-large parts).
    pub unbounded_count: usize,
    /// Minimum thickness observed across all successful samples (mm).
    pub min_thickness_seen: Fix128,
    /// Maximum thickness observed across all successful samples (mm).
    pub max_thickness_seen: Fix128,
}

impl ThinWallReport {
    /// Whether any thin regions were detected (i.e. print is unsafe as-is).
    #[inline]
    #[must_use]
    pub fn has_thin_walls(&self) -> bool {
        !self.regions.is_empty()
    }

    /// Fraction of sampled points that failed thickness check.
    /// Returns 0 if `sampled_count == 0`.
    #[must_use]
    pub fn thin_fraction(&self) -> Fix128 {
        if self.sampled_count == 0 {
            return Fix128::ZERO;
        }
        Fix128::from_ratio(self.regions.len() as i64, self.sampled_count as i64)
    }
}

// ============================================================================
// Core measurement
// ============================================================================

/// Measure the wall thickness at a single surface point via sphere marching.
///
/// Returns `None` if the ray does not hit an opposite surface within
/// `config.max_march_distance_mm` or if `config.max_iterations` was exhausted.
///
/// A `surface_point` off the zero set on the outside by more than
/// `config.start_offset_mm` (a mesh vertex slightly off the field) is first
/// sphere-traced inward onto the surface, and the thickness is measured from
/// there; the gap outside is not wall. A point within the offset of the zero
/// set is taken as on the surface, so a wall thinner than the offset still
/// reports the offset.
#[cfg(feature = "std")]
#[must_use]
pub fn measure_thickness_at(
    sdf: &dyn SdfField,
    surface_point: Vec3Fix,
    outward_normal: (f32, f32, f32),
    config: &ThinWallConfig,
) -> Option<Fix128> {
    // Inward normal = -outward
    let inward = (-outward_normal.0, -outward_normal.1, -outward_normal.2);

    // Verify normal is unit-ish; degenerate inputs cannot be marched.
    let n_len_sq = inward.0 * inward.0 + inward.1 * inward.1 + inward.2 * inward.2;
    if n_len_sq < 0.5 || n_len_sq > 1.5 {
        return None;
    }

    // Convert to f32 for hot loop (SdfField is f32-native).
    let mut px = surface_point.x.to_f32();
    let mut py = surface_point.y.to_f32();
    let mut pz = surface_point.z.to_f32();

    let max_dist_f32 = config.max_march_distance_mm.to_f32();

    // Off the surface on the outside: trace inward onto it first. The SDF is
    // the distance to the nearest surface, so a step of `d` cannot overshoot
    // it; the approach and the measurement share the iteration and distance
    // budgets.
    let mut iterations = 0;
    let mut approach = 0.0_f32;
    loop {
        let d = sdf.distance(px, py, pz);
        if d <= config.start_offset_mm {
            break;
        }
        iterations += 1;
        let step = crate::det_math::max(d, config.min_step_mm);
        approach += step;
        if iterations > config.max_iterations || approach > max_dist_f32 {
            return None;
        }
        let prev = (px, py, pz);
        px += inward.0 * step;
        py += inward.1 * step;
        pz += inward.2 * step;
        if (px, py, pz) == prev {
            return None;
        }
    }

    // Step just inside the surface to leave the SDF ≈ 0 noise band.
    let (prev_px, prev_py, prev_pz) = (px, py, pz);
    px += inward.0 * config.start_offset_mm;
    py += inward.1 * config.start_offset_mm;
    pz += inward.2 * config.start_offset_mm;
    let mut distance = config.start_offset_mm;

    // ⚠️ At extreme magnitudes (`surface_point` coordinates ≈ 1e9) the `f32`
    // ULP there (≈64) swallows a `start_offset_mm` of 0.01 entirely — `px`
    // above is then bit-identical to `prev_px`, so the *next* `sdf.distance`
    // call queries the surface itself again, not a point just inside it.
    // The old code did not notice and reported `Some(start_offset_mm)` on
    // the very first loop iteration — a thickness unrelated to any real
    // opposite-face distance (fixed 2026-10-03, `measure_thickness_at`
    // silent footgun). Detecting "did not actually move" and reporting
    // `None` (cannot reliably measure here) matches this function's
    // existing `None` contract ("ray did not hit an opposite surface") —
    // not a signature change, a correctness fix within it.
    if (px, py, pz) == (prev_px, prev_py, prev_pz) {
        return None;
    }

    for _ in iterations..config.max_iterations {
        let d = sdf.distance(px, py, pz);
        if d >= 0.0 {
            // Exited through the opposite surface.
            return Some(Fix128::from_f32(distance));
        }
        // Inside: |SDF| is exact distance to nearest surface, safe to advance.
        let mut step = -d;
        if step < config.min_step_mm {
            step = config.min_step_mm;
        }
        let (prev_px, prev_py, prev_pz) = (px, py, pz);
        px += inward.0 * step;
        py += inward.1 * step;
        pz += inward.2 * step;
        // Same ULP-stagnation guard as above, mid-march: the object itself
        // (not just the single start offset) can sit at a magnitude where
        // no achievable `step` moves the query point at all.
        if (px, py, pz) == (prev_px, prev_py, prev_pz) {
            return None;
        }
        distance += step;
        if approach + distance > max_dist_f32 {
            return None;
        }
    }
    None
}

// ============================================================================
// Batch analysis
// ============================================================================

/// Analyse thickness for an explicit set of surface sample points.
///
/// Callers typically obtain surface points from a marching-cubes mesh, from
/// on-surface SDF root finding, or from a Poisson-disk surface sampling pass.
/// For a bounding-box grid sweep use [`analyze_thickness_grid`].
#[cfg(feature = "std")]
#[must_use]
pub fn analyze_thickness(
    sdf: &dyn SdfField,
    surface_points: &[Vec3Fix],
    config: &ThinWallConfig,
) -> ThinWallReport {
    let mut report = ThinWallReport {
        sampled_count: surface_points.len(),
        min_thickness_seen: Fix128::from_int(i64::MAX >> 1),
        ..Default::default()
    };

    for &p in surface_points {
        let normal = sdf.normal(p.x.to_f32(), p.y.to_f32(), p.z.to_f32());
        match measure_thickness_at(sdf, p, normal, config) {
            Some(thickness) => {
                if thickness < report.min_thickness_seen {
                    report.min_thickness_seen = thickness;
                }
                if thickness > report.max_thickness_seen {
                    report.max_thickness_seen = thickness;
                }
                if thickness < config.min_thickness_mm {
                    report.regions.push(ThinRegion {
                        position: p,
                        outward_normal: normal,
                        thickness_mm: thickness,
                    });
                }
            }
            None => report.unbounded_count += 1,
        }
    }

    // If nothing successful was sampled, reset min to zero for a clean report.
    if report.sampled_count == report.unbounded_count {
        report.min_thickness_seen = Fix128::ZERO;
    }

    report
}

/// Sample the SDF on a regular grid inside `[aabb_min, aabb_max]`, extract
/// approximate surface points where the SDF sign changes between adjacent
/// grid cells, then analyse thickness at each.
///
/// This is a convenience wrapper for callers without a mesh; for meshed
/// geometry use [`analyze_thickness`] directly on the vertex positions.
///
/// `grid_step_mm` controls sampling density — smaller is more thorough but
/// scales O(n³). A reasonable default is `min_thickness_mm × 0.5`.
#[cfg(feature = "std")]
#[must_use]
pub fn analyze_thickness_grid(
    sdf: &dyn SdfField,
    aabb_min: Vec3Fix,
    aabb_max: Vec3Fix,
    grid_step_mm: Fix128,
    config: &ThinWallConfig,
) -> ThinWallReport {
    let surface_points = sample_surface_points(sdf, aabb_min, aabb_max, grid_step_mm);
    analyze_thickness(sdf, &surface_points, config)
}

/// Extract approximate surface points from a grid AABB by finding sign changes
/// between adjacent cells along each of the X, Y and Z axes (X lines first,
/// then Y, then Z), so a wall thin along any axis is crossed by the lines of
/// that axis. Linear interpolation refines the zero-crossing location. The
/// samples on each axis are `min + i * step` up to `max`, with `max` itself
/// as the last one when the extent is not a multiple of the step, so every
/// point lies inside `[aabb_min, aabb_max]` and the whole box is scanned.
/// Exposed for tests and advanced callers.
#[cfg(feature = "std")]
#[must_use]
pub fn sample_surface_points(
    sdf: &dyn SdfField,
    aabb_min: Vec3Fix,
    aabb_max: Vec3Fix,
    grid_step_mm: Fix128,
) -> Vec<Vec3Fix> {
    let step = grid_step_mm.to_f32();
    if step <= 0.0 {
        return Vec::new();
    }

    let xmin = aabb_min.x.to_f32();
    let ymin = aabb_min.y.to_f32();
    let zmin = aabb_min.z.to_f32();
    let xmax = aabb_max.x.to_f32();
    let ymax = aabb_max.y.to_f32();
    let zmax = aabb_max.z.to_f32();

    // ⚠️ `while coord <= max { coord += step }` (the previous shape here)
    // never terminates once `step` is smaller than the `f32` ULP at `coord`'s
    // magnitude (`coord += step` becomes a no-op) — hit empirically at
    // `coord ≈ 1e9`, `step = 1` (ULP ≈ 64 there), 2026-10-03. Fixed at
    // the root: the number of steps per axis is computed once as an integer
    // (`axis_steps`, `f64` headroom so the count itself doesn't fall prey to
    // the same `f32`-ULP rounding at extreme magnitudes) and the loops below
    // walk that integer down to `0` — termination no longer depends on
    // floating-point addition ever "landing" on `max`. Sample *positions*
    // can still lose resolution at extreme magnitudes (an `f32`-native
    // `SdfField` can't represent a 1mm step at 1e9mm regardless of how the
    // loop is driven) — that is a separate, inherent precision limit, not a
    // non-termination bug, and is out of scope here.
    fn axis_steps(min: f32, max: f32, step: f32) -> u32 {
        if max < min {
            return 0; // inverted AABB: empty on this axis, by design (existing contract)
        }
        let n = (f64::from(max) - f64::from(min)) / f64::from(step);
        // grid points `min + i * step` for `i < n`, then `max` itself as the
        // last point (`axis_coord` clamps), so the whole extent is scanned
        // and no point lies beyond `max`. The relative slack of 1e-6 (several
        // f32 rounding errors of `min`, `max` and `step`) keeps an extent that
        // is a multiple of the step from gaining a near-duplicate last point.
        u32::try_from((n * (1.0 - 1e-6)).ceil() as i64).unwrap_or(u32::MAX)
    }
    fn axis_coord(min: f32, max: f32, step: f32, i: u32) -> f32 {
        // `f64` intermediate: avoids compounding `f32` rounding across
        // iterations the way repeated `+= step` did; the last point is
        // clamped onto `max` (it would be up to one step beyond it)
        crate::det_math::min(
            (f64::from(min) + f64::from(i) * f64::from(step)) as f32,
            max,
        )
    }

    let lo = [xmin, ymin, zmin];
    let hi = [xmax, ymax, zmax];
    let steps = [
        axis_steps(xmin, xmax, step),
        axis_steps(ymin, ymax, step),
        axis_steps(zmin, zmax, step),
    ];
    let coord = |axis: usize, i: u32| axis_coord(lo[axis], hi[axis], step, i);
    let at = |p: [f32; 3]| sdf.distance(p[0], p[1], p[2]);

    let mut out = Vec::new();
    // lines along `axis`, the two other axes `u` (outer) and `v` (inner) in
    // ascending order: X lines over (y, z), Y lines over (x, z), Z lines over (x, y)
    for (axis, u, v) in [(0, 1, 2), (1, 0, 2), (2, 0, 1)] {
        for ui in 0..=steps[u] {
            for vi in 0..=steps[v] {
                let mut p = [0.0_f32; 3];
                p[u] = coord(u, ui);
                p[v] = coord(v, vi);
                p[axis] = coord(axis, 0);
                let mut prev_d = at(p);
                for ai in 1..=steps[axis] {
                    let mut q = p;
                    q[axis] = coord(axis, ai);
                    let d = at(q);
                    if (prev_d < 0.0 && d >= 0.0) || (prev_d >= 0.0 && d < 0.0) {
                        // Sign change: linear interp on the segment [p, q].
                        let denom = d - prev_d;
                        if denom.abs() > f32::EPSILON {
                            let t = -prev_d / denom; // in [0, 1]
                            let mut c = p;
                            c[axis] = p[axis] + t * (q[axis] - p[axis]);
                            out.push(Vec3Fix::new(
                                Fix128::from_f32(c[0]),
                                Fix128::from_f32(c[1]),
                                Fix128::from_f32(c[2]),
                            ));
                        }
                    }
                    prev_d = d;
                    p = q;
                }
            }
        }
    }

    out
}

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

#[cfg(all(test, feature = "std"))]
mod tests {
    use super::*;
    use crate::sdf_collider::ClosureSdf;

    /// Sphere centred at origin, radius R (in mm).
    fn sphere_sdf(radius: f32) -> ClosureSdf {
        ClosureSdf::new(
            move |x, y, z| (x * x + y * y + z * z).sqrt() - radius,
            |x, y, z| {
                let len = (x * x + y * y + z * z).sqrt().max(f32::EPSILON);
                (x / len, y / len, z / len)
            },
        )
    }

    /// Hollow sphere: shell between R_out and R_in (SDF = max(inner_neg, outer_pos)).
    /// Wall thickness anywhere on outer surface = R_out - R_in.
    fn hollow_sphere_sdf(r_out: f32, r_in: f32) -> ClosureSdf {
        ClosureSdf::new(
            move |x, y, z| {
                let r = (x * x + y * y + z * z).sqrt();
                let outer = r - r_out; // negative inside R_out
                let inner = r_in - r; // negative outside R_in (so positive inside cavity)
                outer.max(inner)
            },
            |x, y, z| {
                let len = (x * x + y * y + z * z).sqrt().max(f32::EPSILON);
                (x / len, y / len, z / len)
            },
        )
    }

    #[test]
    fn config_default_uses_industry_thresholds() {
        let cfg = ThinWallConfig::default();
        // 0.8mm = 0.4mm nozzle × 2
        assert_eq!(cfg.min_thickness_mm, Fix128::from_ratio(8, 10));
        assert!(cfg.max_iterations >= 32);
    }

    #[test]
    fn config_for_nozzle_scales() {
        let cfg = ThinWallConfig::for_nozzle(Fix128::from_ratio(6, 10));
        // 0.6mm nozzle → 1.2mm min wall. `.double()` and `from_ratio(12, 10)`
        // agree to within one ULP so compare with a small tolerance.
        let expected = Fix128::from_ratio(12, 10);
        let diff = if cfg.min_thickness_mm > expected {
            cfg.min_thickness_mm - expected
        } else {
            expected - cfg.min_thickness_mm
        };
        assert!(diff <= Fix128::from_ratio(1, 1_000_000));
    }

    #[test]
    fn thickness_solid_sphere_equals_diameter() {
        // Solid sphere R=10 → measuring inward from surface, opposite surface
        // is at ~20mm (diameter). Sphere marching should find it easily.
        let sdf = sphere_sdf(10.0);
        let cfg = ThinWallConfig::default();
        let p = Vec3Fix::new(
            Fix128::from_int(10), // on +X surface
            Fix128::ZERO,
            Fix128::ZERO,
        );
        let normal = (1.0, 0.0, 0.0);
        let t = measure_thickness_at(&sdf, p, normal, &cfg).expect("must hit opposite");
        // Expect ~20mm, allow generous tolerance from sphere-tracing convergence
        let diff = (t.to_f32() - 20.0).abs();
        assert!(diff < 0.5, "diameter ≈ 20mm, got {}", t.to_f32());
    }

    #[test]
    fn thickness_hollow_shell_matches_wall() {
        // Shell R_out=10, R_in=8 → wall = 2mm
        let sdf = hollow_sphere_sdf(10.0, 8.0);
        let cfg = ThinWallConfig::default();
        let p = Vec3Fix::new(Fix128::from_int(10), Fix128::ZERO, Fix128::ZERO);
        let normal = (1.0, 0.0, 0.0);
        let t = measure_thickness_at(&sdf, p, normal, &cfg).expect("must hit inner wall");
        let diff = (t.to_f32() - 2.0).abs();
        assert!(diff < 0.2, "wall ≈ 2mm, got {}", t.to_f32());
    }

    #[test]
    fn thickness_below_threshold_is_flagged() {
        // Shell wall = 0.5mm; default threshold 0.8mm → should flag
        let sdf = hollow_sphere_sdf(5.0, 4.5);
        let cfg = ThinWallConfig::default();
        let p = Vec3Fix::new(Fix128::from_int(5), Fix128::ZERO, Fix128::ZERO);
        let normal = (1.0, 0.0, 0.0);
        let t = measure_thickness_at(&sdf, p, normal, &cfg).unwrap();
        assert!(t < cfg.min_thickness_mm, "0.5mm < 0.8mm threshold");
    }

    #[test]
    fn measure_returns_none_on_degenerate_normal() {
        let sdf = sphere_sdf(10.0);
        let cfg = ThinWallConfig::default();
        let p = Vec3Fix::new(Fix128::from_int(10), Fix128::ZERO, Fix128::ZERO);
        // Zero-length normal
        let t = measure_thickness_at(&sdf, p, (0.0, 0.0, 0.0), &cfg);
        assert!(t.is_none());
    }

    #[test]
    fn measure_returns_none_when_open_geometry() {
        // Half-space plane at x=0, inside is x < 0 → marching from surface
        // point (0,0,0) inward (-X) never re-enters positive SDF.
        let sdf = ClosureSdf::new(|x, _y, _z| x, |_, _, _| (1.0, 0.0, 0.0));
        let cfg = ThinWallConfig {
            max_march_distance_mm: Fix128::from_int(5),
            ..ThinWallConfig::default()
        };
        let p = Vec3Fix::new(Fix128::ZERO, Fix128::ZERO, Fix128::ZERO);
        let normal = (1.0, 0.0, 0.0);
        let t = measure_thickness_at(&sdf, p, normal, &cfg);
        assert!(t.is_none(), "open half-space should be unbounded");
    }

    #[test]
    fn batch_analyze_partitions_regions() {
        // Solid sphere R=10 with 8 sample points on the ±X, ±Y, ±Z surface.
        // All thicknesses are ~20mm → nothing should be flagged as thin.
        let sdf = sphere_sdf(10.0);
        let cfg = ThinWallConfig::default();
        let pts: Vec<Vec3Fix> = [
            (10, 0, 0),
            (-10, 0, 0),
            (0, 10, 0),
            (0, -10, 0),
            (0, 0, 10),
            (0, 0, -10),
        ]
        .into_iter()
        .map(|(x, y, z)| {
            Vec3Fix::new(
                Fix128::from_int(x),
                Fix128::from_int(y),
                Fix128::from_int(z),
            )
        })
        .collect();
        let report = analyze_thickness(&sdf, &pts, &cfg);
        assert_eq!(report.sampled_count, 6);
        assert_eq!(report.regions.len(), 0);
        assert!(!report.has_thin_walls());
    }

    #[test]
    fn batch_analyze_flags_thin_shell() {
        // Thin shell wall = 0.3mm → all 6 sample points should be flagged.
        let sdf = hollow_sphere_sdf(5.0, 4.7);
        let cfg = ThinWallConfig::default();
        let pts: Vec<Vec3Fix> = [
            (5, 0, 0),
            (-5, 0, 0),
            (0, 5, 0),
            (0, -5, 0),
            (0, 0, 5),
            (0, 0, -5),
        ]
        .into_iter()
        .map(|(x, y, z)| {
            Vec3Fix::new(
                Fix128::from_int(x),
                Fix128::from_int(y),
                Fix128::from_int(z),
            )
        })
        .collect();
        let report = analyze_thickness(&sdf, &pts, &cfg);
        assert_eq!(report.sampled_count, 6);
        assert_eq!(report.regions.len(), 6, "all 6 shell samples should flag");
        assert!(report.has_thin_walls());
        assert_eq!(report.thin_fraction(), Fix128::ONE);
    }

    #[test]
    fn thin_fraction_is_zero_when_no_samples() {
        let report = ThinWallReport::default();
        assert_eq!(report.thin_fraction(), Fix128::ZERO);
    }

    #[test]
    fn thin_fraction_half() {
        let mut report = ThinWallReport {
            sampled_count: 4,
            ..Default::default()
        };
        report.regions.push(ThinRegion {
            position: Vec3Fix::default(),
            outward_normal: (1.0, 0.0, 0.0),
            thickness_mm: Fix128::from_ratio(3, 10),
        });
        report.regions.push(ThinRegion {
            position: Vec3Fix::default(),
            outward_normal: (0.0, 1.0, 0.0),
            thickness_mm: Fix128::from_ratio(4, 10),
        });
        // 2/4 = 0.5
        assert_eq!(report.thin_fraction(), Fix128::from_ratio(1, 2));
    }

    #[test]
    fn sample_surface_points_hits_sphere() {
        let sdf = sphere_sdf(5.0);
        let pts = sample_surface_points(
            &sdf,
            Vec3Fix::new(
                Fix128::from_int(-7),
                Fix128::from_int(-7),
                Fix128::from_int(-7),
            ),
            Vec3Fix::new(
                Fix128::from_int(7),
                Fix128::from_int(7),
                Fix128::from_int(7),
            ),
            Fix128::from_int(1),
        );
        // Should find many surface crossings; each point should lie on |p|≈5
        assert!(!pts.is_empty());
        for p in &pts {
            let r = (crate::det_math::powi(p.x.to_f32(), 2)
                + crate::det_math::powi(p.y.to_f32(), 2)
                + crate::det_math::powi(p.z.to_f32(), 2))
            .sqrt();
            assert!(
                (r - 5.0).abs() < 1.5,
                "surface point radius {} deviates from 5",
                r
            );
        }
    }

    #[test]
    fn grid_analyze_solid_sphere_finds_no_thin_regions() {
        let sdf = sphere_sdf(10.0);
        let cfg = ThinWallConfig::default();
        let report = analyze_thickness_grid(
            &sdf,
            Vec3Fix::new(
                Fix128::from_int(-12),
                Fix128::from_int(-12),
                Fix128::from_int(-12),
            ),
            Vec3Fix::new(
                Fix128::from_int(12),
                Fix128::from_int(12),
                Fix128::from_int(12),
            ),
            Fix128::from_int(4),
            &cfg,
        );
        assert!(report.sampled_count > 0);
        // Solid sphere → walls always thick → no flagged regions
        assert_eq!(report.regions.len(), 0);
    }

    fn at(x: f32, y: f32, z: f32) -> Vec3Fix {
        Vec3Fix::from_f32(x, y, z)
    }

    #[test]
    fn for_nozzle_rejects_zero_and_negative() {
        assert!(std::panic::catch_unwind(|| ThinWallConfig::for_nozzle(Fix128::ZERO)).is_err());
        assert!(
            std::panic::catch_unwind(|| ThinWallConfig::for_nozzle(Fix128::from_ratio(-4, 10)))
                .is_err()
        );
    }

    #[test]
    fn off_surface_point_is_traced_onto_the_surface_first() {
        // 1 mm outside a 10 mm solid sphere: the gap is not wall, the chord is 10 mm
        let cfg = ThinWallConfig::default();
        let s = sphere_sdf(5.0);
        let t = measure_thickness_at(&s, at(6.0, 0.0, 0.0), (1.0, 0.0, 0.0), &cfg)
            .expect("1 mm off a 10 mm solid is measurable");
        assert!((t.to_f64() - 10.0).abs() < 2e-2, "{}", t.to_f64());
        // the approach shares the march budget: 5 + 10 > 12 is not measured
        let tight = ThinWallConfig {
            max_march_distance_mm: Fix128::from_int(12),
            ..ThinWallConfig::default()
        };
        assert_eq!(
            measure_thickness_at(&s, at(10.0, 0.0, 0.0), (1.0, 0.0, 0.0), &tight),
            None
        );
        // ... and the iteration budget: 3 approach steps cannot reach a surface 20 mm away
        let few = ThinWallConfig {
            max_iterations: 3,
            max_march_distance_mm: Fix128::from_int(100),
            ..ThinWallConfig::default()
        };
        let slow = ClosureSdf::new(|x, _y, _z| (x - 5.0).min(1.0), |_, _, _| (1.0, 0.0, 0.0));
        assert_eq!(
            measure_thickness_at(&slow, at(25.0, 0.0, 0.0), (1.0, 0.0, 0.0), &few),
            None
        );
    }

    #[test]
    fn iteration_budget_and_min_step_floor() {
        // slab |z| - 2 from its top face: a few iterations are not enough
        let slab = ClosureSdf::new(
            |_x, _y, z| z.abs() - 2.0,
            |_x, _y, z| (0.0, 0.0, if z >= 0.0 { 1.0 } else { -1.0 }),
        );
        let mut cfg = ThinWallConfig {
            max_iterations: 3,
            ..ThinWallConfig::default()
        };
        assert!(measure_thickness_at(&slab, at(0.0, 0.0, 2.0), (0.0, 0.0, 1.0), &cfg).is_none());
        cfg.max_iterations = 64;
        let t = measure_thickness_at(&slab, at(0.0, 0.0, 2.0), (0.0, 0.0, 1.0), &cfg).unwrap();
        assert!((t.to_f64() - 4.0).abs() < 5e-3, "{}", t.to_f64());

        // |d| = 1e-4 until z = -0.5: the 1e-3 floor lands within one step of 0.5
        let shallow = ClosureSdf::new(
            |_x, _y, z| if z > -0.5 { -1e-4 } else { 1e-4 },
            |_x, _y, _z| (0.0, 0.0, 1.0),
        );
        let mut cfg = ThinWallConfig {
            max_iterations: 1000,
            ..ThinWallConfig::default()
        };
        let t = measure_thickness_at(&shallow, at(0.0, 0.0, 0.0), (0.0, 0.0, 1.0), &cfg)
            .unwrap()
            .to_f64();
        assert!((0.5..=0.5 + 1.1e-3).contains(&t), "{t}");
        // without the floor 1000 iterations of 1e-4 are not enough
        cfg.min_step_mm = 1e-4;
        assert!(measure_thickness_at(&shallow, at(0.0, 0.0, 0.0), (0.0, 0.0, 1.0), &cfg).is_none());
    }

    #[test]
    fn a_step_below_the_f32_spacing_is_not_measured() {
        // at 1e9 the f32 spacing is 64, so the 0.01 start offset does not move
        let plane = ClosureSdf::new(|x, _y, _z| x - 1.0e9, |_, _, _| (1.0, 0.0, 0.0));
        let cfg = ThinWallConfig::default();
        assert_eq!(
            measure_thickness_at(&plane, at(1.0e9, 0.0, 0.0), (1.0, 0.0, 0.0), &cfg),
            None
        );
        // at 1e5 the spacing is 2^-7: the 0.01 offset moves one spacing, the
        // 1e-3 steps after it do not
        let flat = ClosureSdf::new(
            |x, _y, _z| if x >= 1.0e5 { 0.0 } else { -1.0e-3 },
            |_, _, _| (1.0, 0.0, 0.0),
        );
        assert_eq!(
            measure_thickness_at(&flat, at(1.0e5, 0.0, 0.0), (1.0, 0.0, 0.0), &cfg),
            None
        );
    }

    #[test]
    fn unbounded_samples_count_and_zero_extrema_when_none_succeed() {
        // degenerate (zero) normals for x > 5 cannot be marched
        let s = ClosureSdf::new(
            |_x, _y, z| z.abs() - 0.3,
            |x, _y, _z| {
                if x > 5.0 {
                    (0.0, 0.0, 0.0)
                } else {
                    (0.0, 0.0, 1.0)
                }
            },
        );
        let cfg = ThinWallConfig::default();
        let r = analyze_thickness(&s, &[at(-1.0, 0.0, 0.3), at(6.0, 0.0, 0.3)], &cfg);
        assert_eq!(r.sampled_count, 2);
        assert_eq!(r.unbounded_count, 1);
        assert_eq!(r.regions.len(), 1);
        assert_eq!(r.thin_fraction(), Fix128::from_ratio(1, 2));
        let none = analyze_thickness(&s, &[at(6.0, 0.0, 0.3), at(7.0, 0.0, 0.3)], &cfg);
        assert_eq!(none.unbounded_count, 2);
        assert_eq!(none.min_thickness_seen, Fix128::ZERO);
        assert_eq!(none.max_thickness_seen, Fix128::ZERO);
        assert!(!none.has_thin_walls());
    }

    #[test]
    fn non_positive_step_and_inverted_box_sample_nothing() {
        let s = sphere_sdf(1.0);
        let lo = at(-2.0, -2.0, -2.0);
        let hi = at(2.0, 2.0, 2.0);
        assert!(sample_surface_points(&s, lo, hi, Fix128::ZERO).is_empty());
        assert!(sample_surface_points(&s, lo, hi, Fix128::from_int(-1)).is_empty());
        assert!(sample_surface_points(&s, hi, lo, Fix128::from_ratio(1, 2)).is_empty());
        assert!(!sample_surface_points(&s, lo, hi, Fix128::from_ratio(1, 2)).is_empty());
    }
}