BREP_render 0.2.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
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
use super::*;
use crate::camera::Aabb;

// ===========================================================================
// Interference check (assemblies build-spec §9) — pairwise NON-DESTRUCTIVE
// kernel INTERSECT booleans over the component instances, reporting every
// overlapping pair + its intersection volume. Zero interference is a PASS.
//
// Runs MAIN-SIDE like every other assembly op (the thread-local rule): the
// component solids' kernel handles come from [`EngineState::
// resident_solid_handles`] — a warm-cache replay of the rolled-to history on
// THIS thread — and `brep_kernel::boolean_handle` / `mass_properties_handle_
// native` read the SAME thread-local registry. The operand handles belong to
// the incremental cache + scene; ONLY the boolean RESULT handle is freed.
//
// Scale sanity: N components = N·(N−1)/2 pairs, but a full boolean only runs
// for pairs whose (inflated, mesh-derived) bboxes overlap — [`plan_pairs`]
// prefilters, so disjoint pairs are PROVEN clear for the cost of a box test.
// Bbox-overlapping pairs beyond [`MAX_BOOLEAN_PAIRS`] are SKIPPED with an
// explicit per-pair note (never silently). Hidden components participate —
// interference is a physical question — with the pair flagged so the window
// can note it.
// ===========================================================================

/// Budget of component pairs allowed to run REAL booleans per check run. Full
/// booleans cost ~10–100 ms each; the bbox prefilter keeps normal assemblies
/// far below this. Pairs beyond the budget are reported as skipped.
const MAX_BOOLEAN_PAIRS: usize = 64;

/// Interference counts only above this intersection volume (mm³): exact face
/// contact (mated components) integrates to ~0 and must read as clear.
const VOLUME_EPSILON: f64 = 1e-6;

/// One INTERFERING component pair: the two owning ACOMP feature ids, their
/// summed intersection volume (mm³, over all member-solid cross pairs), and
/// whether either participant is currently hidden (it still participates —
/// the window notes it).
#[derive(Debug, Clone, PartialEq)]
pub struct InterferencePair {
    pub a: String,
    pub b: String,
    pub volume: f64,
    pub a_hidden: bool,
    pub b_hidden: bool,
}

/// The result of one interference run — everything the results window shows.
/// `pairs` empty + `skipped`/`unverified` empty = the green all-clear.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct InterferenceReport {
    /// Number of component instances that participated.
    pub component_count: usize,
    /// Every pair considered: N·(N−1)/2.
    pub pair_total: usize,
    /// Pairs that ran the boolean lane (bbox-overlapping, within budget).
    /// The rest were PROVEN clear by the bbox prefilter (or noted below).
    pub booleans_run: usize,
    /// The interfering pairs, largest intersection volume first.
    pub pairs: Vec<InterferencePair>,
    /// Anything NOT fully checked, one human-readable line each: pairs beyond
    /// the boolean budget, components with no resident geometry. NEVER silent.
    pub skipped: Vec<String>,
    /// Pairs whose boolean REFUSED (the kernel is conservative on grazing /
    /// tangent contact): not a pass, not an interference — shown under their
    /// own heading so a mated assembly never reads as a wall of errors.
    pub unverified: Vec<String>,
}

// --- the test seam: count trips through the boolean lane --------------------

#[cfg(test)]
thread_local! {
    static BOOLEAN_LANE_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// Tally one boolean-lane invocation (test-observable; free in release).
fn note_boolean_call() {
    #[cfg(test)]
    BOOLEAN_LANE_CALLS.with(|calls| calls.set(calls.get() + 1));
}

#[cfg(test)]
pub(crate) fn boolean_lane_calls() -> usize {
    BOOLEAN_LANE_CALLS.with(|calls| calls.get())
}

#[cfg(test)]
pub(crate) fn reset_boolean_lane_calls() {
    BOOLEAN_LANE_CALLS.with(|calls| calls.set(0));
}

// --- the boolean lane -------------------------------------------------------

/// Intersection volume (mm³) of two RESIDENT solids, non-destructively:
/// `boolean_handle_native` reads both operands by reference (pipeline-default
/// options), the result registers under a NEW handle whose exact volume is
/// integrated, and that intermediate is freed. A legitimately-disjoint
/// intersect yields an EMPTY solid → volume 0. The OPERAND handles are owned
/// by the incremental cache + scene — never free them here.
fn intersect_volume(a: u32, b: u32) -> Result<f64, String> {
    note_boolean_call();
    let result = brep_kernel::boolean_handle_native(
        a,
        b,
        brep_kernel::BooleanOperation::Intersect,
        &brep_kernel::BooleanOptions::default(),
    )?;
    let volume = brep_kernel::mass_properties_handle_native(result, 1.0).map(|p| p.volume);
    // Free ONLY the result — the intermediate this check minted.
    brep_kernel::free_solid(result);
    volume
}

// --- the pure pair planner (prefilter + budget) ------------------------------

/// One component as the planner sees it: id, the union bbox of its member
/// solids (EMPTY = no resident geometry), and the hidden flag.
pub(crate) struct PlanComponent {
    pub id: String,
    pub bbox: Aabb,
    pub hidden: bool,
}

/// What [`plan_pairs`] decides: which index pairs go to the boolean lane, and
/// the explicit notes for everything that will NOT be boolean-checked.
pub(crate) struct PairPlan {
    pub boolean_pairs: Vec<(usize, usize)>,
    pub skipped: Vec<String>,
    pub pair_total: usize,
}

/// Grow a mesh-derived bbox conservatively before the overlap test: the scene
/// bbox is over TESSELLATED positions, which under-approximate curved BREP by
/// up to the chord deviation — a false positive costs one boolean that comes
/// back empty; a false negative would silently miss real interference.
fn inflated(bbox: &Aabb) -> Aabb {
    if bbox.is_empty() {
        return *bbox;
    }
    let size = bbox.size();
    let diagonal = (size[0] * size[0] + size[1] * size[1] + size[2] * size[2]).sqrt();
    let margin = (diagonal * 0.01).max(1e-6);
    let mut out = *bbox;
    for axis in 0..3 {
        out.min[axis] -= margin;
        out.max[axis] += margin;
    }
    out
}

/// Axis-aligned overlap (empty boxes never overlap).
fn overlaps(a: &Aabb, b: &Aabb) -> bool {
    if a.is_empty() || b.is_empty() {
        return false;
    }
    (0..3).all(|axis| a.min[axis] <= b.max[axis] && b.min[axis] <= a.max[axis])
}

/// The PURE planning pass: which pairs must pay for a boolean. Bbox-disjoint
/// pairs are PROVEN clear (checked, not skipped); pairs past `cap` and
/// geometry-less components get explicit notes. Deterministic id order.
pub(crate) fn plan_pairs(components: &[PlanComponent], cap: usize) -> PairPlan {
    let mut plan = PairPlan {
        boolean_pairs: Vec::new(),
        skipped: Vec::new(),
        pair_total: components.len().saturating_sub(1) * components.len() / 2,
    };
    for component in components {
        if component.bbox.is_empty() {
            plan.skipped
                .push(format!("{} — no resident geometry, not checked", component.id));
        }
    }
    let boxes: Vec<Aabb> = components.iter().map(|c| inflated(&c.bbox)).collect();
    for i in 0..components.len() {
        for j in (i + 1)..components.len() {
            if !overlaps(&boxes[i], &boxes[j]) {
                continue; // proven clear by the prefilter — no boolean needed
            }
            if plan.boolean_pairs.len() >= cap {
                plan.skipped.push(format!(
                    "{} × {} — skipped (boolean budget of {cap} pairs reached)",
                    components[i].id, components[j].id
                ));
                continue;
            }
            plan.boolean_pairs.push((i, j));
        }
    }
    plan
}

// --- the engine surface ------------------------------------------------------

impl EngineState {
    /// Run the interference check over every component instance (hidden ones
    /// included — interference is a physical question). Non-destructive: the
    /// component solids are only READ; each pairwise INTERSECT result is
    /// measured and freed. Returns the full report for the results window.
    pub fn interference_check(&mut self) -> InterferenceReport {
        self.ensure_assembly_synced();

        // Gather the participants: members + union bbox + hidden, in the
        // deterministic history order component_ids() gives.
        let ids = self.component_ids();
        let mut members: Vec<Vec<String>> = Vec::with_capacity(ids.len());
        let mut plan_input: Vec<PlanComponent> = Vec::with_capacity(ids.len());
        for id in &ids {
            let info = self.component_info(id);
            let solids = info.map(|info| info.members).unwrap_or_default();
            let mut bbox = Aabb::empty();
            let mut hidden = false;
            for name in &solids {
                if let Some(solid) = self.scene.solid(name) {
                    bbox.union(&solid.bbox);
                    hidden |= !solid.visible;
                }
            }
            plan_input.push(PlanComponent {
                id: id.clone(),
                bbox,
                hidden,
            });
            members.push(solids);
        }

        let plan = plan_pairs(&plan_input, MAX_BOOLEAN_PAIRS);
        let mut report = InterferenceReport {
            component_count: ids.len(),
            pair_total: plan.pair_total,
            booleans_run: 0,
            pairs: Vec::new(),
            skipped: plan.skipped,
            unverified: Vec::new(),
        };
        if plan.boolean_pairs.is_empty() {
            return report;
        }

        // The warm MAIN-SIDE handle map (cache-hit replay on this thread) —
        // the same lane the Info windows' mass properties ride.
        let handles = self.resident_solid_handles();
        for (i, j) in plan.boolean_pairs {
            report.booleans_run += 1;
            let mut volume = 0.0;
            let mut refusal: Option<String> = None;
            for solid_a in &members[i] {
                for solid_b in &members[j] {
                    let (Some(&ha), Some(&hb)) = (handles.get(solid_a), handles.get(solid_b))
                    else {
                        continue; // not resident (rolled back mid-frame)
                    };
                    // Member-level prefilter: within an overlapping component
                    // pair, only member solids whose own boxes overlap pay.
                    let (Some(a), Some(b)) =
                        (self.scene.solid(solid_a), self.scene.solid(solid_b))
                    else {
                        continue;
                    };
                    if !overlaps(&inflated(&a.bbox), &inflated(&b.bbox)) {
                        continue;
                    }
                    match intersect_volume(ha, hb) {
                        Ok(v) => volume += v,
                        Err(error) => {
                            // A conservative kernel refusal (grazing/tangent
                            // contact): the pair is UNVERIFIED, never a
                            // silent pass and never fake interference.
                            refusal.get_or_insert(error);
                        }
                    }
                }
            }
            let (a, b) = (&plan_input[i], &plan_input[j]);
            if let Some(error) = refusal {
                report
                    .unverified
                    .push(format!("{} × {} — boolean refused: {error}", a.id, b.id));
            }
            if volume > VOLUME_EPSILON {
                report.pairs.push(InterferencePair {
                    a: a.id.clone(),
                    b: b.id.clone(),
                    volume,
                    a_hidden: a.hidden,
                    b_hidden: b.hidden,
                });
            }
        }
        // Largest interference first (stable → id order breaks ties).
        report
            .pairs
            .sort_by(|x, y| y.volume.total_cmp(&x.volume));
        report
    }
}

// ===========================================================================
// Tests — the lane's spec battery: overlap volume, all-clear + prefilter
// (boolean lane NOT invoked, via the call counter), three components → three
// pairs, hidden participant flagged, exact face contact pinned, and the pure
// planner's budget notes.
// ===========================================================================
#[cfg(test)]
mod tests {
    use super::super::components::component_fixtures::two_instance_assembly_json;
    use super::*;

    /// The shared two-cube fixture (10 mm cubes, ACOMP1 at origin) with
    /// ACOMP2's translate overridden.
    fn two_cube_engine(second_translate: [f64; 3]) -> EngineState {
        brep_kernel::clear_history_cache();
        reset_boolean_lane_calls();
        let mut doc: serde_json::Value =
            serde_json::from_str(&two_instance_assembly_json()).unwrap();
        doc["features"][1]["inputParams"]["transform"]["translate"] =
            serde_json::json!(second_translate);
        let mut engine = EngineState::new();
        engine.set_history_json(&doc.to_string()).expect("fixture loads");
        engine
    }

    /// TWO OVERLAPPING CUBES: 10 mm cubes offset 5 mm in X intersect in a
    /// 5×10×10 slab — the pair is reported with THAT volume (the kernel's
    /// exact integrator, so near-exact).
    #[test]
    fn overlapping_cubes_report_the_pair_with_the_known_volume() {
        let mut engine = two_cube_engine([5.0, 0.0, 0.0]);
        let report = engine.interference_check();
        assert_eq!(report.component_count, 2);
        assert_eq!(report.pair_total, 1);
        assert_eq!(report.booleans_run, 1);
        assert_eq!(report.pairs.len(), 1, "{report:?}");
        let pair = &report.pairs[0];
        assert_eq!((pair.a.as_str(), pair.b.as_str()), ("ACOMP1", "ACOMP2"));
        assert!(
            (pair.volume - 500.0).abs() < 1e-6,
            "5×10×10 overlap: {}",
            pair.volume
        );
        assert!(!pair.a_hidden && !pair.b_hidden);
        assert!(report.skipped.is_empty() && report.unverified.is_empty());
    }

    /// SEPARATED CUBES: all-clear (a PASS state) — and the bbox prefilter
    /// means the boolean lane is NEVER invoked (the call-counter seam).
    #[test]
    fn separated_cubes_are_all_clear_without_any_boolean() {
        let mut engine = two_cube_engine([20.0, 0.0, 0.0]);
        let report = engine.interference_check();
        assert_eq!(report.pair_total, 1);
        assert!(report.pairs.is_empty(), "{report:?}");
        assert_eq!(report.booleans_run, 0, "prefilter proves the pair clear");
        assert_eq!(boolean_lane_calls(), 0, "the boolean lane was not invoked");
        assert!(report.skipped.is_empty() && report.unverified.is_empty());
    }

    /// THREE COMPONENTS → THREE PAIRS, each with its own exact volume.
    #[test]
    fn three_components_check_three_pairs() {
        brep_kernel::clear_history_cache();
        reset_boolean_lane_calls();
        let mut doc: serde_json::Value =
            serde_json::from_str(&two_instance_assembly_json()).unwrap();
        doc["features"][1]["inputParams"]["transform"]["translate"] =
            serde_json::json!([5.0, 0.0, 0.0]);
        let mut third = doc["features"][1].clone();
        third["inputParams"]["id"] = serde_json::json!("ACOMP3");
        third["inputParams"]["transform"]["translate"] = serde_json::json!([2.0, 0.0, 0.0]);
        doc["features"].as_array_mut().unwrap().push(third);
        let mut engine = EngineState::new();
        engine.set_history_json(&doc.to_string()).expect("fixture loads");

        let report = engine.interference_check();
        assert_eq!(report.component_count, 3);
        assert_eq!(report.pair_total, 3, "N(N−1)/2");
        assert_eq!(report.booleans_run, 3);
        assert_eq!(report.pairs.len(), 3, "{report:?}");
        // Largest overlap first: 1×3 = 8·10·10, 2×3 = 7·10·10, 1×2 = 5·10·10.
        let key = |p: &InterferencePair| (p.a.clone(), p.b.clone(), p.volume);
        let got: Vec<_> = report.pairs.iter().map(key).collect();
        assert_eq!(got[0].0, "ACOMP1");
        assert_eq!(got[0].1, "ACOMP3");
        assert!((got[0].2 - 800.0).abs() < 1e-6, "{got:?}");
        assert_eq!(got[1].0, "ACOMP2");
        assert_eq!(got[1].1, "ACOMP3");
        assert!((got[1].2 - 700.0).abs() < 1e-6, "{got:?}");
        assert_eq!(got[2].0, "ACOMP1");
        assert_eq!(got[2].1, "ACOMP2");
        assert!((got[2].2 - 500.0).abs() < 1e-6, "{got:?}");
    }

    /// A HIDDEN participant still participates (physical question) and the
    /// pair is FLAGGED so the window can note it.
    #[test]
    fn hidden_participant_still_checked_and_flagged() {
        let mut engine = two_cube_engine([5.0, 0.0, 0.0]);
        assert!(engine.scene.set_visible("ACOMP2:Part", false));
        let report = engine.interference_check();
        assert_eq!(report.pairs.len(), 1, "hidden ACOMP2 still participates");
        let pair = &report.pairs[0];
        assert!((pair.volume - 500.0).abs() < 1e-6);
        assert!(!pair.a_hidden, "ACOMP1 is visible");
        assert!(pair.b_hidden, "ACOMP2 is hidden and flagged");
    }

    /// EXACT FACE CONTACT (the mated-assembly norm): PINNED — never false
    /// interference. The kernel refuses the graze conservatively ("operation
    /// produced no boundary faces"), which lands in the UNVERIFIED bucket:
    /// visible in the window, not a silent pass, not fake interference.
    #[test]
    fn exact_face_contact_is_never_false_interference() {
        let mut engine = two_cube_engine([10.0, 0.0, 0.0]);
        let report = engine.interference_check();
        assert_eq!(report.booleans_run, 1, "inflated boxes overlap at contact");
        assert!(
            report.pairs.is_empty(),
            "face contact must not read as interference: {report:?}"
        );
        assert!(report.skipped.is_empty());
        assert_eq!(report.unverified.len(), 1, "{report:?}");
        assert!(
            report.unverified[0].starts_with("ACOMP1 × ACOMP2 — boolean refused:"),
            "{:?}",
            report.unverified
        );
    }

    /// The PURE planner: bbox-disjoint pairs are proven clear (no boolean, no
    /// note); pairs past the budget get explicit per-pair notes; geometry-less
    /// components are noted.
    #[test]
    fn planner_prefilters_caps_and_notes() {
        let cube = |origin: [f64; 3]| Aabb {
            min: origin,
            max: [origin[0] + 1.0, origin[1] + 1.0, origin[2] + 1.0],
        };
        let component = |id: &str, bbox: Aabb| PlanComponent {
            id: id.to_string(),
            bbox,
            hidden: false,
        };

        // Disjoint pair: no boolean, no skipped note (proof, not omission).
        let plan = plan_pairs(
            &[
                component("ACOMP1", cube([0.0; 3])),
                component("ACOMP2", cube([10.0, 0.0, 0.0])),
            ],
            8,
        );
        assert_eq!(plan.pair_total, 1);
        assert!(plan.boolean_pairs.is_empty());
        assert!(plan.skipped.is_empty());

        // Four coincident cubes = 6 overlapping pairs, budget 2: the first two
        // run, the other four are each named in a skipped note.
        let coincident: Vec<PlanComponent> = (1..=4)
            .map(|n| component(&format!("ACOMP{n}"), cube([0.0; 3])))
            .collect();
        let plan = plan_pairs(&coincident, 2);
        assert_eq!(plan.pair_total, 6);
        assert_eq!(plan.boolean_pairs, vec![(0, 1), (0, 2)]);
        assert_eq!(plan.skipped.len(), 4);
        assert!(
            plan.skipped
                .iter()
                .all(|note| note.contains("boolean budget of 2")),
            "{:?}",
            plan.skipped
        );

        // A geometry-less component is noted and never paired.
        let plan = plan_pairs(
            &[
                component("ACOMP1", cube([0.0; 3])),
                component("ACOMP2", Aabb::empty()),
            ],
            8,
        );
        assert!(plan.boolean_pairs.is_empty());
        assert_eq!(plan.skipped.len(), 1);
        assert!(plan.skipped[0].contains("no resident geometry"));
    }
}