Skip to main content

brep_topology/props/mass_properties/
integration.rs

1pub(super) use crate::curve::interior_knots;
2use super::*;
3
4pub fn curve_breaks(curve: &NurbsCurve) -> Result<Vec<f64>, String> {
5    let [start, end] = curve.domain()?;
6    let mut result = vec![start];
7    result.extend(interior_knots(&curve.knots, curve.degree));
8    result.push(end);
9    Ok(result)
10}
11
12pub fn parameter_space_area(face: &FaceRecord) -> Result<f64, String> {
13    let mut area = 0.0;
14    for loop_record in &face.loops {
15        for coedge in &loop_record.coedges {
16            for pair in curve_breaks(&coedge.pcurve)?.windows(2) {
17                for panel in rule::curve_panels(&coedge.pcurve, pair[0], pair[1])? {
18                    for (parameter, weight) in panel.stations() {
19                        let (point, tangent) = coedge.pcurve.deriv1(parameter)?;
20                        area += weight * 0.5 * (point.x * tangent.y - point.y * tangent.x);
21                    }
22                }
23            }
24        }
25    }
26    Ok(area)
27}
28
29/// The escape hatch for [`closed_parameter_space_area`]: `BREP_OPEN_PLANAR_LOOPS=1`
30/// reads every planar face's trim loops open again, as they were read before
31/// the closing chords, so the two readings are two cells of one binary.
32fn open_planar_loops() -> bool {
33    debug_flag!("BREP_OPEN_PLANAR_LOOPS")
34}
35
36/// Every straight uv chord that closes a trim loop of `face`: from where one
37/// coedge's pcurve ends to where the next one's begins, the last back to the
38/// first. A loop whose pcurves meet contributes chords of zero length.
39pub(super) fn loop_closing_chords(face: &FaceRecord) -> Result<Vec<(Vec3, Vec3)>, String> {
40    let mut chords = Vec::new();
41    if open_planar_loops() {
42        return Ok(chords);
43    }
44    for loop_record in &face.loops {
45        let count = loop_record.coedges.len();
46        for index in 0..count {
47            let [_, end] = loop_record.coedges[index].pcurve.domain()?;
48            let [start, _] = loop_record.coedges[(index + 1) % count].pcurve.domain()?;
49            chords.push((
50                loop_record.coedges[index].pcurve.evaluate(end)?,
51                loop_record.coedges[(index + 1) % count].pcurve.evaluate(start)?,
52            ));
53        }
54    }
55    Ok(chords)
56}
57
58/// [`parameter_space_area`] with every trim loop CLOSED by its chords
59/// ([`loop_closing_chords`]). The mass lane of a planar face reads its area
60/// here.
61///
62/// `½∮(u dv − v du)` is independent of where the uv origin sits only over a
63/// closed path. Summed over pcurves whose ends miss one another by `δ`, it
64/// reads `½(e × δ)` too much or too little at each joint `e`, so the same
65/// region read about a translated parameterization gives a different area.
66/// The offset shell's planar faces carry such joints — the pcurve ends of the
67/// box-bore-sphere shells' opening cork miss their vertices by up to 5.6e-5
68/// while the 3D vertices are exact — and on `offsetShellProblem` that alone
69/// put the cork's area 6.680e-4 short and the solid's volume 4.453e-3 short of
70/// a kernel-free integral. Closed, the same face reads within 1e-8 of it.
71///
72/// The chord closes what the face record names. The curved lane's trim
73/// polygons close the same way, implicitly, which is why a curved face with
74/// the same gaps already read true. [`parameter_space_area`] itself stays
75/// OPEN: its other callers read its SIGN as a loop's winding, and on a
76/// periodic carrier a loop that wraps once is not closed in uv by design.
77pub fn closed_parameter_space_area(face: &FaceRecord) -> Result<f64, String> {
78    let mut area = parameter_space_area(face)?;
79    for (end, start) in loop_closing_chords(face)? {
80        area += 0.5 * (crate::polygon::area_term([end.x, end.y], [start.x, start.y]));
81    }
82    Ok(area)
83}
84
85/// The fraction of a face's own extent within which two parameter points are the SAME
86/// point of the carrier. It separates a SEAM — where a loop steps from one edge of the
87/// domain to the other and both parameters name one 3D point, so their evaluations agree
88/// to floating-point rounding — from a trim that misses its own joint.
89///
90/// Set from the separation the population shows, not picked: across 92,000 readings of
91/// this kernel's corpus and both suites, a seam or pole joint's two images agree to
92/// ~1e-14 of the face's extent, while the smallest real miss measured is 1.06e-7 — five
93/// orders above this bar, and a hundred above double-precision evaluation noise.
94const SEAM_COINCIDENCE_REL: f64 = 1e-12;
95
96/// [`parameter_space_area`] with every joint that MISSES closed by a chord, and every
97/// joint that steps across a SEAM left open — the reading a caller on a carrier that may
98/// be periodic or have a pole needs.
99///
100/// The affine lane closes every joint ([`closed_parameter_space_area`]) because a plane has
101/// neither. A general carrier has both: a loop that wraps a closed direction steps a whole
102/// period at one joint by design, and a chord there cancels the sweep — measured on the lib
103/// suite, such a reading collapses to 5e-17 — while a pole's degenerate edge steps a whole
104/// domain edge that is one point. Both are recognised the same way, and by GEOMETRY rather
105/// than by a flag: the two parameters name one point or they do not. `closed_directions()`
106/// is analytic-keyed and answers `false` for a FITTED periodic patch, which is exactly the
107/// carrier a flag-keyed test would mistake.
108///
109/// Nothing is evaluated for a joint whose pcurves meet exactly, which is all but 216 of the
110/// 15,443 calls one corpus replay makes through here.
111pub fn closed_parameter_space_area_on_carrier(face: &FaceRecord) -> Result<f64, String> {
112    let mut area = parameter_space_area(face)?;
113    let mut coincidence: Option<f64> = None;
114    for loop_record in &face.loops {
115        let count = loop_record.coedges.len();
116        for index in 0..count {
117            let [_, end] = loop_record.coedges[index].pcurve.domain()?;
118            let [start, _] = loop_record.coedges[(index + 1) % count].pcurve.domain()?;
119            let here = loop_record.coedges[index].pcurve.evaluate(end)?;
120            let next = loop_record.coedges[(index + 1) % count].pcurve.evaluate(start)?;
121            if here.x == next.x && here.y == next.y {
122                continue;
123            }
124            let bar = *coincidence.get_or_insert_with(|| {
125                SEAM_COINCIDENCE_REL
126                    * crate::tolerance::model_scale(
127                        face.surface
128                            .control_points
129                            .iter()
130                            .flatten()
131                            .filter_map(|control| control.point().ok()),
132                    )
133            });
134            let (image_here, image_next) = (
135                face.surface.evaluate_extended(here.x, here.y)?,
136                face.surface.evaluate_extended(next.x, next.y)?,
137            );
138            if image_here.sub(image_next).length() <= bar {
139                continue;
140            }
141            area += 0.5 * (crate::polygon::area_term([here.x, here.y], [next.x, next.y]));
142        }
143    }
144    Ok(area)
145}
146
147pub fn is_affine(surface: &NurbsSurface) -> Result<bool, String> {
148    // Keep exact metric shortcuts consistent with geometry recognition.
149    surface.is_affine()
150}
151
152pub fn surface_breaks(surface: &NurbsSurface) -> Result<(Vec<f64>, Vec<f64>), String> {
153    let ku = crate::KnotVector::new(surface.knots_u.clone(), surface.degree_u)?;
154    let kv = crate::KnotVector::new(surface.knots_v.clone(), surface.degree_v)?;
155    let [u0, u1] = ku.domain();
156    let [v0, v1] = kv.domain();
157    let mut u = vec![u0];
158    u.extend(interior_knots(&surface.knots_u, surface.degree_u));
159    u.push(u1);
160    let mut v = vec![v0];
161    v.extend(interior_knots(&surface.knots_v, surface.degree_v));
162    v.push(v1);
163    Ok((u, v))
164}
165
166pub fn integrand_value(kind: Integrand, point: Vec3, weighted_normal: Vec3) -> f64 {
167    let (x, y, z) = (point.x, point.y, point.z);
168    match kind {
169        Integrand::Area => weighted_normal.length(),
170        Integrand::Volume => point.dot(weighted_normal),
171        Integrand::VolumeAbout(reference) => point.sub(reference).dot(weighted_normal),
172        Integrand::NormalX => weighted_normal.x,
173        Integrand::NormalY => weighted_normal.y,
174        Integrand::NormalZ => weighted_normal.z,
175        Integrand::MomentX => 0.5 * x * x * weighted_normal.x,
176        Integrand::MomentY => 0.5 * y * y * weighted_normal.y,
177        Integrand::MomentZ => 0.5 * z * z * weighted_normal.z,
178        Integrand::SecondXX => x * x * x / 3.0 * weighted_normal.x,
179        Integrand::SecondYY => y * y * y / 3.0 * weighted_normal.y,
180        Integrand::SecondZZ => z * z * z / 3.0 * weighted_normal.z,
181        Integrand::ProductXY => 0.5 * x * x * y * weighted_normal.x,
182        Integrand::ProductXZ => 0.5 * x * x * z * weighted_normal.x,
183        Integrand::ProductYZ => 0.5 * y * y * z * weighted_normal.y,
184    }
185}
186
187
188/// Stations per direction in a fixed tensor Gauss block.
189pub const GAUSS_COUNT: usize = GAUSS_X.len();
190
191/// The tensor-block station evaluator is on unless `BREP_MASS_TENSOR_BLOCK=0`
192/// turns it off. It is bit-identical to the per-station path by construction
193/// (`NurbsSurface::deriv1_tensor_each`), so the switch buys nothing but a
194/// paired A/B timing of the two in ONE binary under ONE load — which is the
195/// only honest way to quote a speed-up on a box that runs eight agents.
196pub(super) fn tensor_blocks_on() -> bool {
197    switch!("BREP_MASS_TENSOR_BLOCK", true)
198}
199
200/// Accumulate every `kind` over ONE parameter cell by tensor Gauss–Legendre,
201/// with every station's weight scaled — the trimmed path's full cells carry
202/// their winding and the sweep's orientation there. `scale` multiplies FIRST,
203/// as every call site has always written the product, so a cell read at the
204/// base rule is bit-identical to the one-block rule it replaces.
205///
206/// Identical arithmetic to the per-station loop it replaces (kept as the
207/// tests' reference sweep) — the same stations in the same i-outer/j-inner
208/// order, the same `weight_u * weight_v * half_u * half_v * value` product and
209/// the same running sum per slot — but each of the block's u and v
210/// spans/basis rows is evaluated ONCE rather than once per station it takes
211/// part in, which at the base rule is eight rows each instead of sixty-four
212/// evaluations.
213pub fn integrate_cell_scaled(
214    face: &FaceRecord,
215    cell: [f64; 4],
216    scale: f64,
217    kinds: &[Integrand],
218    totals: &mut [f64],
219    rules: &mut rule::SurfaceRules,
220) -> Result<usize, String> {
221    // A rational carrier's cell is read on the panels and at the orders its
222    // own weights ask for (`rule`); a polynomial one keeps ONE base-order
223    // block over the whole cell.
224    let (u_panels, v_panels) = rules.panels(&face.surface, cell)?;
225    let area_slot = if area_adaptive_on() {
226        kinds.iter().position(|kind| matches!(kind, Integrand::Area))
227    } else {
228        None
229    };
230    let before = area_slot.map(|slot| totals[slot]);
231    let mut stations = 0;
232    for u_panel in &u_panels {
233        for v_panel in &v_panels {
234            integrate_block(face, *u_panel, *v_panel, scale, kinds, totals, rules.station_identity)?;
235            stations += u_panel.order * v_panel.order;
236        }
237    }
238    if let (Some(slot), Some(before)) = (area_slot, before) {
239        // The area integrand |S_u × S_v| is a square root: no fixed-order
240        // rule reads it exactly, polynomial carrier or not, so the cell's
241        // AREA alone is re-read adaptively and every other integrand keeps
242        // the reading above bit for bit.
243        let coarse = (totals[slot] - before) / scale;
244        totals[slot] = before + scale * adaptive_cell_area(face, cell, coarse, rules, AREA_ADAPTIVE_DEPTH, &mut stations)?;
245    }
246    Ok(stations)
247}
248
249/// `BREP_MASS_AREA_ADAPTIVE` (default on) re-reads each cell's AREA by quadrant
250/// refinement until a cell and its four quadrants agree to
251/// [`AREA_ADAPTIVE_TOLERANCE`] of the cell's own area. Default ON since the
252/// 2026-11-05 promotion (owner: accuracy beats speed); `=0` restores one
253/// fixed-rule reading per cell for every integrand.
254///
255/// brep-bench 2026-11-05: one 8-point block per knot cell read the degree-15
256/// Bézier dome's patch (`geometry/high-degree-bezier-dome`) 2.3e-5 small and
257/// the twisted sweep's degree 1×3 blade faces (`loft/twisted-thin-blade`)
258/// 1.7e-5 large, while their volumes were exact to round-off; refined, they
259/// read 1.6e-9 and 1.4e-7 of the closed forms.
260pub fn area_adaptive_on() -> bool {
261    switch!("BREP_MASS_AREA_ADAPTIVE", true)
262}
263
264/// How many times a cell may be quartered while its area is re-read.
265const AREA_ADAPTIVE_DEPTH: usize = 6;
266
267/// Relative agreement between a cell's area and the sum of its quadrants'
268/// that ends the refinement: a few hundred ulps of the cell's own area.
269const AREA_ADAPTIVE_TOLERANCE: f64 = 1e-11;
270
271/// The area over `cell` (unscaled), given the reading `coarse` of the whole
272/// cell: the four quadrants are read on their own panels, and any quadrant
273/// whose own refinement still moves is quartered again, to `depth` levels.
274fn adaptive_cell_area(
275    face: &FaceRecord,
276    cell: [f64; 4],
277    coarse: f64,
278    rules: &mut rule::SurfaceRules,
279    depth: usize,
280    stations: &mut usize,
281) -> Result<f64, String> {
282    if depth == 0 {
283        return Ok(coarse);
284    }
285    let [u_lo, u_hi, v_lo, v_hi] = cell;
286    let (u_mid, v_mid) = (0.5 * (u_lo + u_hi), 0.5 * (v_lo + v_hi));
287    let quadrants = [
288        [u_lo, u_mid, v_lo, v_mid],
289        [u_mid, u_hi, v_lo, v_mid],
290        [u_lo, u_mid, v_mid, v_hi],
291        [u_mid, u_hi, v_mid, v_hi],
292    ];
293    let mut readings = [0.0f64; 4];
294    for (index, quadrant) in quadrants.iter().enumerate() {
295        let (u_panels, v_panels) = rules.panels(&face.surface, *quadrant)?;
296        let mut area = [0.0f64];
297        for u_panel in &u_panels {
298            for v_panel in &v_panels {
299                integrate_block(face, *u_panel, *v_panel, 1.0, &[Integrand::Area], &mut area, rules.station_identity)?;
300                *stations += u_panel.order * v_panel.order;
301            }
302        }
303        readings[index] = area[0];
304    }
305    let fine: f64 = readings.iter().sum();
306    if (fine - coarse).abs() <= AREA_ADAPTIVE_TOLERANCE * fine.abs() {
307        return Ok(fine);
308    }
309    let mut total = 0.0;
310    for (index, quadrant) in quadrants.iter().enumerate() {
311        total += adaptive_cell_area(face, *quadrant, readings[index], rules, depth - 1, stations)?;
312    }
313    Ok(total)
314}
315
316/// One tensor Gauss block: every station of `u_panel × v_panel`, every kind.
317/// The existing tensor rule without area refinement, for an interior cell
318/// of an extended trim. The covering-grid caller already used this rule;
319/// only repeated surface-basis evaluation is removed.
320pub(super) fn integrate_interior_cell_base(
321    face: &FaceRecord, cell: [f64; 4], scale: f64, kinds: &[Integrand],
322    totals: &mut [f64], rules: &mut rule::SurfaceRules,
323) -> Result<Option<usize>, String> {
324    let (us, vs) = rules.panels(&face.surface, cell)?;
325    if us.len() != 1 || vs.len() != 1 || us[0].order != GAUSS_COUNT || vs[0].order != GAUSS_COUNT {
326        return Ok(None);
327    }
328    integrate_block(face, us[0], vs[0], scale, kinds, totals, rules.station_identity)?;
329    Ok(Some(GAUSS_COUNT * GAUSS_COUNT))
330}
331
332fn integrate_block(
333    face: &FaceRecord,
334    u_panel: rule::Panel,
335    v_panel: rule::Panel,
336    scale: f64,
337    kinds: &[Integrand],
338    totals: &mut [f64],
339    station_identity: Option<[u64; 2]>,
340) -> Result<(), String> {
341    let half_u = (u_panel.hi - u_panel.lo) * 0.5;
342    let middle_u = (u_panel.hi + u_panel.lo) * 0.5;
343    let half_v = (v_panel.hi - v_panel.lo) * 0.5;
344    let middle_v = (v_panel.hi + v_panel.lo) * 0.5;
345    let (u_x, u_w) = u_panel.nodes();
346    let (v_x, v_w) = v_panel.nodes();
347    let sign = if face.same_sense { 1.0 } else { -1.0 };
348    // The base rule, written against the fixed-size tables: its trip count is
349    // a constant the compiler unrolls, and reading the nodes through a slice
350    // of run-time length instead cost 0.28 µs a station on a 900 000-station
351    // import (measured 2026-09-15). Every polynomial carrier is on this path,
352    // and it is the arithmetic the one-block rule always did.
353    let base_rule = u_x.len() == GAUSS_COUNT && v_x.len() == GAUSS_COUNT;
354    if base_rule && tensor_blocks_on() && face.surface.deriv1_tensor_supported() {
355        let mut u_stations = [0.0f64; GAUSS_COUNT];
356        let mut v_stations = [0.0f64; GAUSS_COUNT];
357        for index in 0..GAUSS_COUNT {
358            u_stations[index] = middle_u + half_u * GAUSS_X[index];
359            v_stations[index] = middle_v + half_v * GAUSS_X[index];
360        }
361        return super::cell_memo::each(&face.surface, station_identity, &u_stations, &v_stations, |i, j, point, su, sv| {
362                let weighted_normal = su.cross(sv).scale(sign);
363                for (slot, kind) in kinds.iter().enumerate() {
364                    totals[slot] += scale
365                        * GAUSS_W[i]
366                        * GAUSS_W[j]
367                        * half_u
368                        * half_v
369                        * integrand_value(*kind, point, weighted_normal);
370                }
371                Ok(())
372            });
373    }
374    if base_rule && !face.surface.deriv1_tensor_supported() {
375        for i in 0..GAUSS_COUNT {
376            for j in 0..GAUSS_COUNT {
377                let (point, su, sv) = face
378                    .surface
379                    .deriv1(middle_u + half_u * GAUSS_X[i], middle_v + half_v * GAUSS_X[j])?;
380                let weighted_normal = su.cross(sv).scale(sign);
381                for (slot, kind) in kinds.iter().enumerate() {
382                    totals[slot] += scale
383                        * GAUSS_W[i]
384                        * GAUSS_W[j]
385                        * half_u
386                        * half_v
387                        * integrand_value(*kind, point, weighted_normal);
388                }
389            }
390        }
391        return Ok(());
392    }
393    if tensor_blocks_on() && face.surface.deriv1_tensor_supported() {
394        let mut u_stations = [0.0f64; rule::MAX_ORDER];
395        let mut v_stations = [0.0f64; rule::MAX_ORDER];
396        for index in 0..u_x.len() {
397            u_stations[index] = middle_u + half_u * u_x[index];
398        }
399        for index in 0..v_x.len() {
400            v_stations[index] = middle_v + half_v * v_x[index];
401        }
402        return super::cell_memo::each(
403            &face.surface, station_identity,
404            &u_stations[..u_x.len()],
405            &v_stations[..v_x.len()],
406            |i, j, point, su, sv| {
407                let weighted_normal = su.cross(sv).scale(sign);
408                for (slot, kind) in kinds.iter().enumerate() {
409                    totals[slot] += scale
410                        * u_w[i]
411                        * v_w[j]
412                        * half_u
413                        * half_v
414                        * integrand_value(*kind, point, weighted_normal);
415                }
416                Ok(())
417            },
418        );
419    }
420    for i in 0..u_x.len() {
421        for j in 0..v_x.len() {
422            let (point, su, sv) = face
423                .surface
424                .deriv1(middle_u + half_u * u_x[i], middle_v + half_v * v_x[j])?;
425            let weighted_normal = su.cross(sv).scale(sign);
426            for (slot, kind) in kinds.iter().enumerate() {
427                totals[slot] += scale
428                    * u_w[i]
429                    * v_w[j]
430                    * half_u
431                    * half_v
432                    * integrand_value(*kind, point, weighted_normal);
433            }
434        }
435    }
436    Ok(())
437}
438
439/// Every `kind` over the whole (untrimmed) knot-span grid in ONE sweep.
440/// `solid_mass_properties` asks an untrimmed face for its area and its volume
441/// flux; two single-kind sweeps evaluated every station twice for a second
442/// integrand that costs a multiply.
443pub fn integrate_untrimmed_multi(
444    face: &FaceRecord,
445    kinds: &[Integrand],
446) -> Result<Vec<f64>, String> {
447    let (u_breaks, v_breaks) = surface_breaks(&face.surface)?;
448    let mut totals = vec![0.0f64; kinds.len()];
449    let mut rules = rule::SurfaceRules::new(&face.surface)?;
450    for upair in u_breaks.windows(2) {
451        for vpair in v_breaks.windows(2) {
452            integrate_cell_scaled(
453                face,
454                [upair[0], upair[1], vpair[0], vpair[1]],
455                1.0,
456                kinds,
457                &mut totals,
458                &mut rules,
459            )?;
460        }
461    }
462    Ok(totals)
463}
464
465/// Every `kind` over the knot-span grid CLIPPED to `rectangle`
466/// (`[u_lo, u_hi, v_lo, v_hi]`, inside the domain): the untrimmed sweep's
467/// own rules on each cell's intersection with the rectangle, so a face whose
468/// single loop is an iso-rectangle (`polygons::iso_rectangle_trim`) is read
469/// without the trimmed route's chord polygons, cell quadtree and triangle
470/// cubature. Lane O, 2026-10-28: the filleted box's outward offset carried
471/// its quarter-cylinder image as such a face (the carrier extended past the
472/// walls, the trim v in [0.069, 0.931]) and the trimmed route spent 6.5 ms
473/// on 496 full cells and 31 744 stations for a one-span surface; this sweep
474/// reads it in a few stations per span.
475pub fn integrate_iso_rectangle_multi(
476    face: &FaceRecord,
477    rectangle: [f64; 4],
478    kinds: &[Integrand],
479) -> Result<Vec<f64>, String> {
480    let (u_breaks, v_breaks) = surface_breaks(&face.surface)?;
481    let mut totals = vec![0.0f64; kinds.len()];
482    let mut rules = rule::SurfaceRules::new(&face.surface)?;
483    for upair in u_breaks.windows(2) {
484        let (u_lo, u_hi) = (upair[0].max(rectangle[0]), upair[1].min(rectangle[1]));
485        if u_hi <= u_lo {
486            continue;
487        }
488        for vpair in v_breaks.windows(2) {
489            let (v_lo, v_hi) = (vpair[0].max(rectangle[2]), vpair[1].min(rectangle[3]));
490            if v_hi <= v_lo {
491                continue;
492            }
493            integrate_cell_scaled(face, [u_lo, u_hi, v_lo, v_hi], 1.0, kinds, &mut totals, &mut rules)?;
494        }
495    }
496    Ok(totals)
497}
498
499pub fn integrate_untrimmed(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
500    Ok(integrate_untrimmed_multi(face, &[kind])?[0])
501}
502
503/// A bi-periodic band face (surface closed in both u and v, exactly two loops
504/// each a full-wrap constant-cross-level rim) whose trim is NOT expressed with a
505/// seam ruling — the fillet-torus bands OCC/STEP emit as two rim circles. Such a
506/// face integrates to ZERO on the trimmed path (both loops are degenerate iso
507/// lines in parameter space), so it is handled analytically over the seam-cut
508/// rectangle instead. See [`biperiodic_band_range`].
509#[derive(Clone, Copy)]
510pub struct BiBand {
511    /// Which parameter is the periodic (full-wrap) one.
512    pub(super) p_is_u: bool,
513    /// The two rim cross-levels, ascending (q_lo <= q_hi) in the cross param.
514    pub q_lo: f64,
515    pub q_hi: f64,
516    /// True when the material band is the CROSS-SEAM COMPLEMENT of [q_lo, q_hi]
517    /// rather than the between-rims strip (mirrors the tessellator's
518    /// `close_periodic_trim_dir` orientation test).
519    pub(super) complement: bool,
520    /// The larger of the two rims' cross-parameter extents, as a fraction of
521    /// the cross domain. Zero (to double noise) for the rim circles OCC/STEP
522    /// emit as exact iso lines; a few 1e-3 for a rim PROJECTED from a vendor
523    /// 3D curve that sits off the carrier, whose pcurve then wanders in the
524    /// cross parameter. Decides between the seam-cut rectangle and the
525    /// rim-following strip — see [`biperiodic_band_integral`].
526    pub rim_wobble: f64,
527}
528
529/// Above this fraction of the cross domain a rim is not an iso line, and the
530/// band between the rims is integrated along the rims' own pcurves instead
531/// of over the rectangle between their mean levels.
532///
533/// The bar is double noise, not a geometric tolerance: a rim that IS an iso
534/// line measures ~1e-15 here, and the two paths agree on it to quadrature
535/// precision, so nothing that reads exactly today moves. Set at 1e-9 rather
536/// than at the noise floor so a level rim of a large-domain surface is never
537/// pushed onto the pcurve walk by rounding alone. `importTestWorking`
538/// SOLID_03 face 90: a torus fillet strip whose upper rim was projected from
539/// an edge 2.2e-3 mm off the torus wanders over v ∈ [0.746903, 0.750195] —
540/// 3.3e-3 of the period — and the rectangle at the mean level 0.748549 read
541/// the strip 9.67e-3 mm² (0.09%) small and its origin flux 0.388 low.
542pub const BAND_RIM_LEVEL_TOLERANCE_REL: f64 = 1e-9;
543
544/// Detect the bi-periodic band configuration of `face` and choose which of the
545/// two regions its rims bound is material. The choice replicates the watertight
546/// tessellator (`watertight_tessellation::close_periodic_trim_dir`): the
547/// material is to the LEFT of the boundary traversal, so the between-rims strip
548/// is kept unless the cross direction wraps AND the rim senses conclusively name
549/// the complement. Returns None for anything that is not a clean two-rim band.
550pub fn biperiodic_band_range(face: &FaceRecord) -> Result<Option<BiBand>, String> {
551    let surface = &face.surface;
552    let (closed_u, closed_v) = surface.closed_directions()?;
553    if !(closed_u && closed_v) {
554        return Ok(None);
555    }
556    let [u0, u1] = surface.domain_u()?;
557    let [v0, v1] = surface.domain_v()?;
558    let u_span = (u1 - u0).abs().max(1e-30);
559    let v_span = (v1 - v0).abs().max(1e-30);
560    // Sample each loop's pcurves (in coedge/traversal order) into (u,v) points.
561    // A DEGENERATE loop — a pole/apex vertex whose whole trace collapses to one
562    // parameter point (a fat fillet torus touches its outer equator at a single
563    // seam point: ABC 00000039 faces 68/70) — is not a band boundary; drop it
564    // and keep the two real rims. Anything else leaves the band ambiguous.
565    let mut loop_points: Vec<Vec<[f64; 2]>> = Vec::with_capacity(2);
566    for loop_record in &face.loops {
567        let mut points = Vec::new();
568        for coedge in &loop_record.coedges {
569            let [d0, d1] = coedge.pcurve.domain()?;
570            // 32 per coedge: enough to see a projected rim wander, which a
571            // 12-sample read of a smooth pcurve could straddle.
572            let samples = 32;
573            for k in 0..=samples {
574                let t = d0 + (d1 - d0) * k as f64 / samples as f64;
575                let p = coedge.pcurve.evaluate(t)?;
576                points.push([p.x, p.y]);
577            }
578        }
579        if points.len() < 2 {
580            return Ok(None);
581        }
582        let (mut umin, mut umax, mut vmin, mut vmax) = (
583            f64::INFINITY,
584            f64::NEG_INFINITY,
585            f64::INFINITY,
586            f64::NEG_INFINITY,
587        );
588        for pt in &points {
589            umin = umin.min(pt[0]);
590            umax = umax.max(pt[0]);
591            vmin = vmin.min(pt[1]);
592            vmax = vmax.max(pt[1]);
593        }
594        if (umax - umin) <= 1e-3 * u_span && (vmax - vmin) <= 1e-3 * v_span {
595            continue; // degenerate pole/apex loop
596        }
597        loop_points.push(points);
598    }
599    if loop_points.len() != 2 {
600        return Ok(None);
601    }
602    for p_is_u in [true, false] {
603        let (period, _p0, _p1) = if p_is_u {
604            (u1 - u0, u0, u1)
605        } else {
606            (v1 - v0, v0, v1)
607        };
608        let (q_dom_lo, q_dom_hi) = if p_is_u { (v0, v1) } else { (u0, u1) };
609        let q_extent = (q_dom_hi - q_dom_lo).abs().max(1e-30);
610        if !(period > 0.0) {
611            continue;
612        }
613        let coord = |pt: &[f64; 2]| -> (f64, f64) {
614            if p_is_u {
615                (pt[0], pt[1])
616            } else {
617                (pt[1], pt[0])
618            }
619        };
620        // (level, winding-direction) for each rim; None if any loop is not a
621        // clean full-wrap constant-cross-level rim in this p direction.
622        let mut rings: Vec<(f64, i32)> = Vec::with_capacity(2);
623        let mut clean = true;
624        let mut rim_wobble = 0.0f64;
625        for points in &loop_points {
626            let (mut pmin, mut pmax, mut qmin, mut qmax) = (
627                f64::INFINITY,
628                f64::NEG_INFINITY,
629                f64::INFINITY,
630                f64::NEG_INFINITY,
631            );
632            for pt in points {
633                let (p, q) = coord(pt);
634                pmin = pmin.min(p);
635                pmax = pmax.max(p);
636                qmin = qmin.min(q);
637                qmax = qmax.max(q);
638            }
639            if (pmax - pmin) < 0.6 * period || (qmax - qmin) > 0.05 * q_extent {
640                clean = false;
641                break;
642            }
643            rim_wobble = rim_wobble.max((qmax - qmin) / q_extent);
644            let mut net = 0.0;
645            for pair in points.windows(2) {
646                let mut delta = coord(&pair[1]).0 - coord(&pair[0]).0;
647                if delta > 0.5 * period {
648                    delta -= period;
649                } else if delta < -0.5 * period {
650                    delta += period;
651                }
652                net += delta;
653            }
654            let direction = if net > 0.25 * period {
655                1
656            } else if net < -0.25 * period {
657                -1
658            } else {
659                0
660            };
661            rings.push((0.5 * (qmin + qmax), direction));
662        }
663        if !clean || rings.len() != 2 {
664            continue;
665        }
666        rings.sort_by(|a, b| a.0.total_cmp(&b.0));
667        let (q_lo, lower_dir) = rings[0];
668        let (q_hi, upper_dir) = rings[1];
669        let inconclusive = lower_dir == 0 || upper_dir == 0 || lower_dir == upper_dir;
670        let between_rims_is_ccw_uv = if p_is_u { lower_dir > 0 } else { lower_dir < 0 };
671        let complement = !inconclusive && between_rims_is_ccw_uv != face.same_sense;
672        return Ok(Some(BiBand {
673            p_is_u,
674            q_lo,
675            q_hi,
676            complement,
677            rim_wobble,
678        }));
679    }
680    Ok(None)
681}
682
683/// Gauss–Legendre integral of `kind` over the axis-aligned parameter rectangle
684/// \[u_lo,u_hi\]×\[v_lo,v_hi\], subdividing at knot spans clipped to the rectangle.
685pub fn integrate_rectangle(
686    face: &FaceRecord,
687    u_lo: f64,
688    u_hi: f64,
689    v_lo: f64,
690    v_hi: f64,
691    kind: Integrand,
692) -> Result<f64, String> {
693    let (u_full, v_full) = surface_breaks(&face.surface)?;
694    let clamp = |breaks: &[f64], lo: f64, hi: f64| -> Vec<f64> {
695        let eps = 1e-9 * (hi - lo).abs().max(1e-30);
696        let mut out = vec![lo];
697        for &b in breaks {
698            if b > lo + eps && b < hi - eps {
699                out.push(b);
700            }
701        }
702        out.push(hi);
703        out
704    };
705    let u_breaks = clamp(&u_full, u_lo, u_hi);
706    let v_breaks = clamp(&v_full, v_lo, v_hi);
707    let mut totals = [0.0f64];
708    let mut rules = rule::SurfaceRules::new(&face.surface)?;
709    for upair in u_breaks.windows(2) {
710        for vpair in v_breaks.windows(2) {
711            integrate_cell_scaled(
712                face,
713                [upair[0], upair[1], vpair[0], vpair[1]],
714                1.0,
715                &[kind],
716                &mut totals,
717                &mut rules,
718            )?;
719        }
720    }
721    Ok(totals[0])
722}
723
724/// Integrate each of `kinds` over a bi-periodic band face, or return None when
725/// `face` is not such a band. The between-rims strip integrates over the full
726/// periodic span × the cross-level strip; the complement is the full-domain
727/// integral MINUS that strip (the two tile the closed cross period, so no
728/// domain-extended evaluation is needed).
729///
730/// Two readings of the strip. Rims that ARE iso lines (every rim circle a
731/// kernel-built or exactly exported torus carries) integrate over the
732/// seam-cut rectangle between their levels. A rim that wanders in the cross
733/// parameter — a pcurve PROJECTED from a vendor edge that sits off the
734/// carrier — is not at any one level, and the rectangle at its mean level
735/// mis-reads the strip by the wander times the rim length; such a band is
736/// integrated along the rims' own pcurves by the winding boundary integral
737/// (`∮ −G du`, [`super::winding::winding_loops_integral`]), which reads the
738/// trim exactly as given. The material choice (`complement`) is the same in
739/// both readings; only the strip's quadrature differs.
740pub(super) fn biperiodic_band_integral(
741    face: &FaceRecord,
742    kinds: &[Integrand],
743) -> Result<Option<Vec<f64>>, String> {
744    let Some(band) = biperiodic_band_range(face)? else {
745        if switch!("BREP_MASS_TORUS_LIFT", true) {
746            return super::torus::lifted_band_integral(face, kinds);
747        }
748        return Ok(None);
749    };
750    let [u0, u1] = face.surface.domain_u()?;
751    let [v0, v1] = face.surface.domain_v()?;
752    let (u_lo, u_hi, v_lo, v_hi) = if band.p_is_u {
753        (u0, u1, band.q_lo, band.q_hi)
754    } else {
755        (band.q_lo, band.q_hi, v0, v1)
756    };
757    let strips: Vec<f64> = if band.rim_wobble <= BAND_RIM_LEVEL_TOLERANCE_REL {
758        kinds
759            .iter()
760            .map(|&kind| integrate_rectangle(face, u_lo, u_hi, v_lo, v_hi, kind))
761            .collect::<Result<_, _>>()?
762    } else {
763        super::winding::winding_loops_integral(face, kinds, band.p_is_u, 1)?
764    };
765    let mut out = Vec::with_capacity(kinds.len());
766    for (&kind, strip) in kinds.iter().zip(strips) {
767        let value = if band.complement {
768            integrate_untrimmed(face, kind)? - strip
769        } else {
770            strip
771        };
772        out.push(value);
773    }
774    Ok(Some(out))
775}