Skip to main content

brep_kernel/props/mass_properties/
polygons.rs

1use super::*;
2use crate::topology::CoedgeRecord;
3
4/// The pcurve arc behind one chord of a [`TrimPolygon`]: coedge
5/// `coedge_index` of loop `loop_index`, from parameter `t0` at the chord's
6/// start to `t1` at its end (`t1 < t0` when the loop was reversed), shifted by
7/// `offset` on the covering plane.
8#[derive(Clone, Copy, Debug)]
9pub(super) struct ChordArc {
10    pub loop_index: usize,
11    pub coedge_index: usize,
12    pub t0: f64,
13    pub t1: f64,
14    pub offset: [f64; 2],
15}
16
17/// One trim loop as the integrator consumes it: the chord polygon plus, per
18/// chord, the pcurve arc it stands in for. `arcs[k]` belongs to the chord from
19/// `points[k]` to `points[(k + 1) % n]`; `None` marks a segment with nothing
20/// to correct against — a straight pcurve span, a synthetic side (band
21/// rectangle, cap join, seam closure) or a jump between coedges that do not
22/// meet. The integrator adds, per arc, the signed region between the arc and
23/// its chord, so the chord count sets only the quadrature's work, never the
24/// answer (`integrate_trimmed_polys`).
25#[derive(Clone, Debug)]
26pub(super) struct TrimPolygon {
27    pub points: Vec<[f64; 2]>,
28    pub arcs: Vec<Option<ChordArc>>,
29    /// Where the last pushed coedge's pcurve ends (shifted): the point the next
30    /// vertex has to land on for the chord leaving the last sample to be that
31    /// pcurve's closing arc rather than a jump.
32    pending_end: Option<[f64; 2]>,
33    /// A vertex further than this from `pending_end` is a jump — a seam
34    /// teleport is a whole period, a stitched pcurve gap is far smaller.
35    jump_tolerance: f64,
36}
37
38/// Whether every control point of `curve` lies on the line through its two
39/// ends, to 1e-12 of the control polygon's extent. By the convex-hull
40/// property the whole curve then lies on that line, so the sliver between any
41/// chord of it and the arc behind the chord has no area: its correction is
42/// zero. `is_straight_polyline` is the exact degree-1 case the sampler keeps
43/// at its knots; this is the wider one the sign reading skips corrections
44/// on — a bore's rim on its wall, written by the imprint as a rational
45/// quadratic (the circle's own knots and weights) whose control points sit
46/// on one `v` line.
47pub(super) fn is_straight_in_uv(curve: &NurbsCurve) -> bool {
48    let mut points = Vec::with_capacity(curve.control_points.len());
49    for control in &curve.control_points {
50        let Ok(point) = control.point() else {
51            return false;
52        };
53        points.push([point.x, point.y]);
54    }
55    let (Some(first), Some(last)) = (points.first().copied(), points.last().copied()) else {
56        return false;
57    };
58    let extent = points
59        .iter()
60        .map(|point| (point[0] - first[0]).hypot(point[1] - first[1]))
61        .fold(0.0f64, f64::max);
62    if extent <= 0.0 {
63        return true;
64    }
65    let direction = [last[0] - first[0], last[1] - first[1]];
66    let length = direction[0].hypot(direction[1]);
67    if length <= 1e-12 * extent {
68        return false;
69    }
70    points.iter().all(|point| {
71        ((point[0] - first[0]) * direction[1] - (point[1] - first[1]) * direction[0]).abs()
72            <= 1e-12 * extent * length
73    })
74}
75
76fn is_straight_polyline(curve: &NurbsCurve) -> bool {
77    let rational = curve
78        .control_points
79        .iter()
80        .any(|point| (point.w - curve.control_points[0].w).abs() > 1e-12);
81    curve.degree == 1 && !rational
82}
83
84impl TrimPolygon {
85    pub(super) fn new(domain: [f64; 4]) -> Self {
86        let [u0, u1, v0, v1] = domain;
87        let jump_tolerance = 1e-3 * (u1 - u0).abs().min((v1 - v0).abs()).max(1e-300);
88        Self {
89            points: Vec::new(),
90            arcs: Vec::new(),
91            pending_end: None,
92            jump_tolerance,
93        }
94    }
95
96    pub(super) fn for_face(face: &FaceRecord) -> Result<Self, String> {
97        let [u0, u1] = face.surface.domain_u()?;
98        let [v0, v1] = face.surface.domain_v()?;
99        Ok(Self::new([u0, u1, v0, v1]))
100    }
101
102    fn settle_pending(&mut self, next: [f64; 2]) {
103        if let Some(end) = self.pending_end.take() {
104            if switch!("BREP_MASS_TRIM_JOINS", true) {
105                // The next coedge need not start at this coedge's end.
106                // Keep the complete arc, then a separate straight join;
107                // otherwise the polygon silently replaces its final chord.
108                if end != next && (self.points.last() != Some(&end)
109                    || self.arcs.last().is_some_and(Option::is_some))
110                {
111                    self.points.push(end);
112                    self.arcs.push(None);
113                }
114                return;
115            }
116            let gap = ((next[0] - end[0]).powi(2) + (next[1] - end[1]).powi(2)).sqrt();
117            if gap > self.jump_tolerance {
118                if let Some(last) = self.arcs.last_mut() {
119                    *last = None;
120                }
121            }
122        }
123    }
124
125    /// A vertex with no arc behind the chord that leaves it.
126    pub(super) fn push_point(&mut self, point: [f64; 2]) {
127        self.settle_pending(point);
128        self.points.push(point);
129        self.arcs.push(None);
130    }
131
132    /// Append one coedge's pcurve the way the integrator samples trims: a
133    /// straight polyline at its knots (exact, no arcs), anything curved at
134    /// 24..128 chords spread over its knot spans with the arc recorded behind
135    /// every chord. A chord never straddles a knot, so each arc is one
136    /// polynomial (or rational) piece and the sliver quadrature is exact on it.
137    pub(super) fn push_coedge(
138        &mut self,
139        loop_index: usize,
140        coedge_index: usize,
141        coedge: &CoedgeRecord,
142        offset: [f64; 2],
143    ) -> Result<(), String> {
144        let curve = &coedge.pcurve;
145        let interior = interior_knots(&curve.knots, curve.degree);
146        if is_straight_polyline(curve) {
147            let [start, end] = curve.domain()?;
148            for parameter in std::iter::once(start).chain(interior.iter().copied()) {
149                let point = curve.evaluate(parameter)?;
150                self.push_point([point.x + offset[0], point.y + offset[1]]);
151            }
152            if switch!("BREP_MASS_TRIM_JOINS", true) {
153                let point = curve.evaluate(end)?;
154                self.pending_end = Some([point.x + offset[0], point.y + offset[1]]);
155            }
156            return Ok(());
157        }
158        let sample_count = (24usize).max((interior.len() + 1) * 16).min(128);
159        self.push_coedge_spans(loop_index, coedge_index, coedge, offset, sample_count, false)
160    }
161
162    /// Append about `target` chords of one coedge's pcurve, spread evenly over
163    /// its knot spans (at least one per span, so no chord straddles a knot)
164    /// and tagged with the arc behind each; a straight polyline contributes
165    /// its knots exactly. The end point is pushed too when `include_end`.
166    pub(super) fn push_coedge_spans(
167        &mut self,
168        loop_index: usize,
169        coedge_index: usize,
170        coedge: &CoedgeRecord,
171        offset: [f64; 2],
172        target: usize,
173        include_end: bool,
174    ) -> Result<(), String> {
175        let curve = &coedge.pcurve;
176        let spans = curve_breaks(curve)?;
177        let [_, end] = curve.domain()?;
178        if is_straight_polyline(curve) {
179            let last = if include_end { spans.len() } else { spans.len() - 1 };
180            for &parameter in &spans[..last] {
181                let point = curve.evaluate(parameter)?;
182                self.push_point([point.x + offset[0], point.y + offset[1]]);
183            }
184            if !include_end && switch!("BREP_MASS_TRIM_JOINS", true) {
185                let point = curve.evaluate(end)?;
186                self.pending_end = Some([point.x + offset[0], point.y + offset[1]]);
187            }
188            return Ok(());
189        }
190        let span_count = spans.len().saturating_sub(1).max(1);
191        let per_span = target.div_ceil(span_count).max(1);
192        let mut previous: Option<(f64, [f64; 2])> = None;
193        let mut emit = |this: &mut Self, t: f64| -> Result<(), String> {
194            let point = curve.evaluate(t)?;
195            let point = [point.x + offset[0], point.y + offset[1]];
196            if let Some((t_prev, _)) = previous {
197                if let Some(last) = this.arcs.last_mut() {
198                    *last = Some(ChordArc { loop_index, coedge_index, t0: t_prev, t1: t, offset });
199                }
200            }
201            this.settle_pending(point);
202            this.points.push(point);
203            this.arcs.push(None);
204            previous = Some((t, point));
205            Ok(())
206        };
207        for pair in spans.windows(2) {
208            for index in 0..per_span {
209                emit(self, pair[0] + (pair[1] - pair[0]) * index as f64 / per_span as f64)?;
210            }
211        }
212        if include_end {
213            emit(self, end)?;
214        } else if let Some((t_prev, _)) = previous {
215            // The chord leaving the last sample reaches the pcurve's end, which
216            // the next vertex must supply.
217            if let Some(last) = self.arcs.last_mut() {
218                *last = Some(ChordArc { loop_index, coedge_index, t0: t_prev, t1: end, offset });
219            }
220            let point = curve.evaluate(end)?;
221            self.pending_end = Some([point.x + offset[0], point.y + offset[1]]);
222        }
223        Ok(())
224    }
225
226    /// Close the loop: the chord back to the first vertex is the last pcurve's
227    /// closing arc only if the first vertex is where that pcurve ends.
228    pub(super) fn finish(&mut self) {
229        if let Some(first) = self.points.first().copied() {
230            self.settle_pending(first);
231        }
232        self.pending_end = None;
233    }
234
235    pub(super) fn reverse(&mut self) {
236        self.finish();
237        let n = self.points.len();
238        if n == 0 {
239            return;
240        }
241        let old = std::mem::take(&mut self.arcs);
242        let swap = |arc: Option<ChordArc>| arc.map(|a| ChordArc { t0: a.t1, t1: a.t0, ..a });
243        let mut arcs = Vec::with_capacity(n);
244        for k in 0..n - 1 {
245            arcs.push(swap(old[n - 2 - k]));
246        }
247        arcs.push(swap(old[n - 1]));
248        self.arcs = arcs;
249        self.points.reverse();
250    }
251
252    pub(super) fn shift_u(&mut self, du: f64) {
253        for point in &mut self.points {
254            point[0] += du;
255        }
256        for arc in self.arcs.iter_mut().flatten() {
257            arc.offset[0] += du;
258        }
259        if let Some(end) = &mut self.pending_end {
260            end[0] += du;
261        }
262    }
263
264    /// Concatenate `other` after this loop's vertices; both joins are synthetic.
265    pub(super) fn append(&mut self, mut other: TrimPolygon) {
266        self.finish();
267        other.finish();
268        if let Some(last) = self.arcs.last_mut() {
269            *last = None;
270        }
271        if let Some(last) = other.arcs.last_mut() {
272            *last = None;
273        }
274        self.points.append(&mut other.points);
275        self.arcs.append(&mut other.arcs);
276    }
277}
278
279/// The chord polygons of `face`'s trim loops, as sampled for integration.
280pub fn trim_polygons(face: &FaceRecord) -> Result<Vec<Vec<[f64; 2]>>, String> {
281    Ok(trim_polygons_tagged(face)?
282        .into_iter()
283        .map(|polygon| polygon.points)
284        .collect())
285}
286
287pub(super) fn trim_polygons_tagged(face: &FaceRecord) -> Result<Vec<TrimPolygon>, String> {
288    let surface = &face.surface;
289    // This changes only the polygon work count. Every polynomial span keeps
290    // its exact arc correction, including its endpoint and real joins.
291    let span_chords = switch!("BREP_MASS_TRIM_SPAN_CHORDS", true)
292        && switch!("BREP_MASS_EXACT_DOMAIN_COVER", true)
293        && surface.closed_directions()? == (false, false)
294        && surface.degree_u <= 3 && surface.degree_v <= 3
295        && surface.control_points.len() == surface.degree_u + 1
296        && surface.control_points[0].len() == surface.degree_v + 1
297        && surface.control_points.iter().flatten().all(|p| p.w == surface.control_points[0][0].w)
298        && near_rectangle_for_span_chords(face)?;
299    let mut polygons = Vec::new();
300    for (loop_index, loop_record) in face.loops.iter().enumerate() {
301        let mut polygon = TrimPolygon::for_face(face)?;
302        for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
303            if span_chords {
304                polygon.push_coedge_spans(loop_index, coedge_index, coedge, [0.0, 0.0], 1, false)?;
305            } else {
306                polygon.push_coedge(loop_index, coedge_index, coedge, [0.0, 0.0])?;
307            }
308        }
309        polygon.finish();
310        polygons.push(polygon);
311    }
312    Ok(polygons)
313}
314
315/// Rebuild a sphere cap bounded by a varying full-period contact rim and the
316/// collapsed opposite-winding rim at one parameter pole.  In the flat UV
317/// plane both individual loops have zero enclosed area; joined across one cut
318/// of the periodic cover they form the actual cap polygon.
319pub(super) fn singly_periodic_sphere_cap_polygons(
320    face: &FaceRecord,
321    closed_u: bool,
322    closed_v: bool,
323    domain: [f64; 4],
324) -> Result<Option<Vec<TrimPolygon>>, String> {
325    if !matches!(
326        face.surface.analytic(),
327        Some(crate::AnalyticSurface::Sphere { .. })
328    ) || (closed_u, closed_v) != (true, false)
329        || face.loops.len() != 2
330    {
331        return Ok(None);
332    }
333    let [u0, u1, v0, v1] = domain;
334    let period = u1 - u0;
335    let v_span = v1 - v0;
336    struct Rim {
337        polygon: TrimPolygon,
338        winding: f64,
339        vmin: f64,
340        vmax: f64,
341    }
342    let mut rims = Vec::with_capacity(2);
343    for (loop_index, loop_record) in face.loops.iter().enumerate() {
344        let mut polygon = TrimPolygon::new(domain);
345        for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
346            polygon.push_coedge_spans(loop_index, coedge_index, coedge, [0.0, 0.0], 64, true)?;
347        }
348        polygon.finish();
349        let points = &polygon.points;
350        if points.len() < 2 {
351            return Ok(None);
352        }
353        let winding = points.last().unwrap()[0] - points[0][0];
354        let (mut vmin, mut vmax) = (f64::INFINITY, f64::NEG_INFINITY);
355        for point in points {
356            vmin = vmin.min(point[1]);
357            vmax = vmax.max(point[1]);
358        }
359        rims.push(Rim {
360            polygon,
361            winding,
362            vmin,
363            vmax,
364        });
365    }
366    if rims
367        .iter()
368        .any(|rim| (rim.winding.abs() - period).abs() > 0.05 * period)
369        || rims[0].winding * rims[1].winding >= 0.0
370    {
371        return Ok(None);
372    }
373    let flat = |rim: &Rim| rim.vmax - rim.vmin <= 1e-6 * v_span;
374    let pole = match (flat(&rims[0]), flat(&rims[1])) {
375        (true, false) => &rims[0],
376        (false, true) => &rims[1],
377        _ => return Ok(None),
378    };
379    let pole_v = 0.5 * (pole.vmin + pole.vmax);
380    if (pole_v - v0).abs() > 1e-6 * v_span && (pole_v - v1).abs() > 1e-6 * v_span {
381        return Ok(None);
382    }
383
384    let (lower, upper) = if rims[0].vmax <= rims[1].vmin {
385        (&rims[0], &rims[1])
386    } else if rims[1].vmax <= rims[0].vmin {
387        (&rims[1], &rims[0])
388    } else {
389        return Ok(None);
390    };
391    let mut lower_points = lower.polygon.clone();
392    if lower.winding < 0.0 {
393        lower_points.reverse();
394    }
395    let mut upper_points = upper.polygon.clone();
396    if upper.winding > 0.0 {
397        upper_points.reverse();
398    }
399    let shift = ((lower_points.points[0][0] - upper_points.points.last().unwrap()[0]) / period)
400        .round()
401        * period;
402    upper_points.shift_u(shift);
403    lower_points.append(upper_points);
404    Ok(Some(vec![lower_points]))
405}
406
407/// Trim polygons with implicit torus seams unwrapped onto the covering plane.
408/// Returns `(polygons, unwrapped)`; `unwrapped` is true iff any loop crossed an
409/// implicit seam (and therefore carries out-of-domain parameters). Only attempts
410/// the unwrap on a doubly-periodic surface — single-periodic seams the raw
411/// integrator already handles are left in-domain.
412pub(super) fn trim_polygons_unwrapped(
413    face: &FaceRecord,
414    closed_u: bool,
415    closed_v: bool,
416    u_period: f64,
417    v_period: f64,
418) -> Result<(Vec<TrimPolygon>, bool), String> {
419    let mut polygons = Vec::new();
420    let mut unwrapped = false;
421    for (loop_index, loop_record) in face.loops.iter().enumerate() {
422        let offsets = crate::topology::loop_seam_offsets(
423            &loop_record.coedges,
424            closed_u,
425            closed_v,
426            u_period,
427            v_period,
428        )?;
429        let mut polygon = TrimPolygon::for_face(face)?;
430        for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
431            let offset = offsets[coedge_index];
432            if offset[0] != 0.0 || offset[1] != 0.0 {
433                unwrapped = true;
434            }
435            polygon.push_coedge(loop_index, coedge_index, coedge, offset)?;
436        }
437        polygon.finish();
438        polygons.push(polygon);
439    }
440    Ok((polygons, unwrapped))
441}
442
443/// A singly-periodic (cylinder/cone) wall whose seam is IMPLICIT: the closed
444/// wall is bounded by two full-wrap rim loops (iso-parametric lines at constant
445/// cross-level) with NO seam edge connecting them — the two-rim-circles form
446/// OCC/STEP emit for a full lateral face. This is the single-periodic analogue
447/// of [`biperiodic_band_range`]: each rim is a degenerate iso line in parameter
448/// space, so the raw trim integrates the band between them to ~zero (only the
449/// in-band holes survive — a full cylinder wall collapses to a ~1000x-too-small
450/// sliver, ABC 00000056 solid 2). We restrict to the unambiguous case where the
451/// two rims sit at the cross-domain EXTREMES: the material region is then the
452/// WHOLE surface (full periodic span × full cross span) minus any hole/notch
453/// loops, with no between-rims-vs-complement choice to get wrong. Replacing the
454/// two rim lines with a single full-domain band rectangle lets the existing
455/// winding integrator fill the wall while the remaining loops subtract as holes.
456///
457/// Returns the rebuilt polygon set (band rectangle first, then the unwrapped
458/// non-rim loops), or None when `face` is not a clean two-extreme-rim band —
459/// every other periodic face keeps its existing integration path unchanged.
460pub(super) fn singly_periodic_wall_polygons(
461    face: &FaceRecord,
462    closed_u: bool,
463    closed_v: bool,
464    domain: [f64; 4],
465) -> Result<Option<Vec<TrimPolygon>>, String> {
466    // Exactly one periodic direction (the doubly-periodic case is handled by
467    // `biperiodic_band_integral` upstream).
468    if closed_u == closed_v {
469        return Ok(None);
470    }
471    let [u0, u1, v0, v1] = domain;
472    let p_is_u = closed_u;
473    let period = if p_is_u { u1 - u0 } else { v1 - v0 };
474    if !(period > 0.0) {
475        return Ok(None);
476    }
477    let (q_dom_lo, q_dom_hi) = if p_is_u { (v0, v1) } else { (u0, u1) };
478    let q_extent = (q_dom_hi - q_dom_lo).abs();
479    if !(q_extent > 0.0) {
480        return Ok(None);
481    }
482    // (periodic, cross) coordinate split.
483    let coord = |p: [f64; 2]| if p_is_u { (p[0], p[1]) } else { (p[1], p[0]) };
484
485    let mut rim_indices: Vec<usize> = Vec::new();
486    let mut rim_levels: Vec<f64> = Vec::new();
487    for (index, loop_record) in face.loops.iter().enumerate() {
488        // Sample the loop's pcurves in traversal order.
489        let mut points: Vec<[f64; 2]> = Vec::new();
490        for coedge in &loop_record.coedges {
491            let [d0, d1] = coedge.pcurve.domain()?;
492            let samples = 16;
493            for k in 0..=samples {
494                let t = d0 + (d1 - d0) * k as f64 / samples as f64;
495                let p = coedge.pcurve.evaluate(t)?;
496                points.push([p.x, p.y]);
497            }
498        }
499        if points.len() < 2 {
500            return Ok(None);
501        }
502        let (mut qmin, mut qmax) = (f64::INFINITY, f64::NEG_INFINITY);
503        let mut net = 0.0;
504        for pair in points.windows(2) {
505            let (p0, q0) = coord(pair[0]);
506            let (p1, _q1) = coord(pair[1]);
507            qmin = qmin.min(q0);
508            qmax = qmax.max(q0);
509            let mut delta = p1 - p0;
510            if delta > 0.5 * period {
511                delta -= period;
512            } else if delta < -0.5 * period {
513                delta += period;
514            }
515            net += delta;
516        }
517        if let Some(last) = points.last() {
518            let (_p, q) = coord(*last);
519            qmin = qmin.min(q);
520            qmax = qmax.max(q);
521        }
522        // A rim: nets a full period in the periodic direction and stays on a
523        // near-constant cross-level (a true iso line).
524        let is_rim = net.abs() > 0.75 * period && (qmax - qmin) <= 0.02 * q_extent;
525        if is_rim {
526            rim_indices.push(index);
527            rim_levels.push(0.5 * (qmin + qmax));
528        }
529    }
530    if rim_levels.len() != 2 {
531        return Ok(None);
532    }
533    let (q_lo, q_hi) = if rim_levels[0] <= rim_levels[1] {
534        (rim_levels[0], rim_levels[1])
535    } else {
536        (rim_levels[1], rim_levels[0])
537    };
538    // Require the rims at the cross-domain extremes: material is then the whole
539    // wall (no between-rims/complement ambiguity). A sub-band (rims interior to
540    // the cross domain) is declined here — the existing path keeps handling it.
541    let tol = 0.02 * q_extent;
542    if (q_lo - q_dom_lo).abs() > tol || (q_hi - q_dom_hi).abs() > tol {
543        return Ok(None);
544    }
545    if (q_hi - q_lo) <= 0.5 * q_extent {
546        return Ok(None);
547    }
548
549    // Band rectangle over the full periodic span × the rim cross-levels.
550    let (r_ulo, r_uhi, r_vlo, r_vhi) = if p_is_u {
551        (u0, u1, q_lo, q_hi)
552    } else {
553        (q_lo, q_hi, v0, v1)
554    };
555    let mut rectangle = TrimPolygon::new(domain);
556    for corner in [
557        [r_ulo, r_vlo],
558        [r_uhi, r_vlo],
559        [r_uhi, r_vhi],
560        [r_ulo, r_vhi],
561    ] {
562        rectangle.push_point(corner);
563    }
564    let mut polygons: Vec<TrimPolygon> = vec![rectangle];
565    // Keep the non-rim loops (holes / notches), unwrapping any implicit-seam hop
566    // so a seam-straddling hole subtracts as one region.
567    for (index, loop_record) in face.loops.iter().enumerate() {
568        if rim_indices.contains(&index) {
569            continue;
570        }
571        let offsets = crate::topology::loop_seam_offsets(
572            &loop_record.coedges,
573            closed_u,
574            closed_v,
575            u1 - u0,
576            v1 - v0,
577        )?;
578        let mut polygon = TrimPolygon::new(domain);
579        for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
580            polygon.push_coedge(index, coedge_index, coedge, offsets[coedge_index])?;
581        }
582        polygon.finish();
583        polygons.push(polygon);
584    }
585    Ok(Some(polygons))
586}
587
588/// A DOUBLY-periodic (torus) face whose trim is a full-wrap BAND bounded by a
589/// constant-cross-level seam RIM (at a cross-domain extreme) and a single-valued
590/// WAVY CUT. The raw winding integrator collapses it to a sliver (the rim is a
591/// zero-area iso line and the cut's own polygon encloses only the thin strip it
592/// bounds), so — mirroring [`singly_periodic_wall_polygons`] for the singly-
593/// periodic wall — rebuild the material region as ONE simple (u,v) polygon:
594/// the wavy cut as one boundary, the flat rim iso-line (at the OPPOSITE cross
595/// extreme, which is the same physical seam circle) as the other, closed by the
596/// two private wrap-seam edges. The winding integrator then fills the band.
597///
598/// Returns None for anything that is not this exact signature (see
599/// [`crate::topology::analyze_doubly_periodic_seam_band`]) — every other face
600/// keeps its existing integration path bit-for-bit.
601pub(super) fn doubly_periodic_seam_band_polygons(
602    face: &FaceRecord,
603    domain: [f64; 4],
604) -> Result<Option<Vec<TrimPolygon>>, String> {
605    let (closed_u, closed_v) = face.surface.closed_directions()?;
606    if !(closed_u && closed_v) {
607        return Ok(None);
608    }
609    // Sample each loop's pcurves in traversal order; every sample remembers
610    // the pcurve parameter it came from so the band polygon's chords keep
611    // their arcs through the rotation below.
612    type Tagged = ([f64; 2], Option<(usize, usize, f64)>);
613    let mut loops_uv: Vec<Vec<[f64; 2]>> = Vec::with_capacity(face.loops.len());
614    let mut loops_tagged: Vec<Vec<Tagged>> = Vec::with_capacity(face.loops.len());
615    for (loop_index, loop_record) in face.loops.iter().enumerate() {
616        let mut points: Vec<[f64; 2]> = Vec::new();
617        let mut tagged: Vec<Tagged> = Vec::new();
618        for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
619            let [d0, d1] = coedge.pcurve.domain()?;
620            let samples = 24;
621            let curved = !is_straight_polyline(&coedge.pcurve);
622            for k in 0..=samples {
623                let t = d0 + (d1 - d0) * k as f64 / samples as f64;
624                let p = coedge.pcurve.evaluate(t)?;
625                points.push([p.x, p.y]);
626                tagged.push(([p.x, p.y], curved.then_some((loop_index, coedge_index, t))));
627            }
628        }
629        loops_uv.push(points);
630        loops_tagged.push(tagged);
631    }
632    let Some(band) =
633        crate::topology::analyze_doubly_periodic_seam_band(&loops_uv, domain, face.same_sense)
634    else {
635        return Ok(None);
636    };
637    let vertices = crate::topology::seam_band_uv_polygon_with(
638        &loops_tagged,
639        |vertex: &Tagged| vertex.0,
640        |point| (point, None),
641        domain,
642        &band,
643    );
644    let mut polygon = TrimPolygon::new(domain);
645    let n = vertices.len();
646    for (k, (point, tag)) in vertices.iter().enumerate() {
647        polygon.push_point(*point);
648        // The chord to the next vertex is an arc only between two samples of
649        // one pcurve; the rotation keeps consecutive samples adjacent, and a
650        // synthetic vertex (seam extension, rim corner) carries no tag.
651        let next = &vertices[(k + 1) % n];
652        if let (Some((l0, c0, t0)), Some((l1, c1, t1))) = (tag, next.1) {
653            if *l0 == l1 && *c0 == c1 {
654                polygon.arcs[k] = Some(ChordArc {
655                    loop_index: *l0,
656                    coedge_index: *c0,
657                    t0: *t0,
658                    t1,
659                    offset: [0.0, 0.0],
660                });
661            }
662        }
663    }
664    Ok(Some(vec![polygon]))
665}
666
667/// A conservative proof that all trim arcs and their closing chords lie on
668/// the domain boundary. Positive rational weights keep each arc inside its
669/// control hull. Exact coordinate comparisons deliberately decline uncertain
670/// fits; those retain their authored boundary in the trimmed integrator.
671pub(super) fn trim_on_domain_boundary(face: &FaceRecord, domain: [f64; 4]) -> Result<bool, String> {
672    let [u0, u1, v0, v1] = domain;
673    let sides = |p: Vec3| -> u8 {
674        if !p.x.is_finite() || !p.y.is_finite()
675            || p.x < u0 || p.x > u1 || p.y < v0 || p.y > v1 {
676            return 0;
677        }
678        u8::from(p.x == u0) | (u8::from(p.x == u1) << 1)
679            | (u8::from(p.y == v0) << 2) | (u8::from(p.y == v1) << 3)
680    };
681    for rim in &face.loops {
682        if rim.coedges.is_empty() { return Ok(false); }
683        let mut ends = Vec::with_capacity(rim.coedges.len());
684        for coedge in &rim.coedges {
685            let curve = &coedge.pcurve;
686            let mut common = 15;
687            for control in &curve.control_points {
688                if !(control.w > 0.0) { return Ok(false); }
689                common &= sides(control.point()?);
690            }
691            if common == 0 || curve.control_points.is_empty() { return Ok(false); }
692            let [a, b] = curve.domain()?;
693            ends.push((sides(curve.evaluate(a)?), sides(curve.evaluate(b)?)));
694        }
695        for i in 0..ends.len() {
696            if ends[i].1 & ends[(i + 1) % ends.len()].0 == 0 { return Ok(false); }
697        }
698    }
699    Ok(true)
700}
701
702pub(super) fn is_untrimmed(face: &FaceRecord) -> Result<bool, String> {
703    if face.loops.len() != 1 {
704        return Ok(false);
705    }
706    let ku = crate::KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u)?;
707    let kv = crate::KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v)?;
708    let [u0, u1] = ku.domain();
709    let [v0, v1] = kv.domain();
710    let domain_area = (u1 - u0) * (v1 - v0);
711    if switch!("BREP_MASS_EXACT_DOMAIN_COVER", true)
712        && !trim_on_domain_boundary(face, [u0, u1, v0, v1])? {
713        return Ok(false);
714    }
715    // With the boundary proof enabled this checks the winding of a loop
716    // confined to the domain boundary. The legacy path instead treats area
717    // closeness alone as evidence that a fitted trim covers the whole domain.
718    Ok((closed_parameter_space_area_on_carrier(face)?.abs() - domain_area).abs() <= 1e-6 * domain_area)
719}
720
721/// The single loop of `face` as an iso-rectangle `[u_lo, u_hi, v_lo, v_hi]`
722/// inside the surface domain: exactly four straight pcurves, each parallel
723/// to a parameter axis, joined end to end, alternating direction, wound
724/// counter-clockwise in uv, every corner within 1e-6 of the domain's span of
725/// the domain. Such a trim is a sub-rectangle of the knot grid and is
726/// integrated by `integration::integrate_iso_rectangle_multi` (lane O,
727/// 2026-10-28). `None` for anything else — a curved or oblique pcurve, a
728/// hole, a clockwise loop (whose meaning the trimmed route decides) — which
729/// keeps the trimmed route. Under `BREP_PROFILE_MASS_FACES` a decline names
730/// its reason on stderr.
731pub(super) fn iso_rectangle_trim(face: &FaceRecord) -> Result<Option<[f64; 4]>, String> {
732    let found = iso_rectangle_trim_impl(face)?;
733    if let Err(reason) = &found {
734        if super::profile::face_lines_enabled() {
735            eprintln!("mass.iso_rect face={} declined: {reason}", face.id);
736        }
737    }
738    Ok(found.ok())
739}
740
741/// `BREP_MASS_ISO_RECT_TRIMMED` (default on since the brep-bench promotion;
742/// `=0` restores the old reading): the pole-side clip in
743/// [`iso_rectangle_trim_impl`], and the trimmed integrator reading an
744/// iso-rectangle face on the untrimmed sweep's rules
745/// (`trimmed::integrate_trimmed_multi_with`).
746pub(super) fn pole_side_clip_on() -> bool {
747    switch!("BREP_MASS_ISO_RECT_TRIMMED", true)
748}
749
750fn iso_rectangle_trim_impl(face: &FaceRecord) -> Result<Result<[f64; 4], &'static str>, String> {
751    iso_rectangle_trim_impl_with_exact(face, switch!("BREP_MASS_EXACT_DOMAIN_COVER", true), false)
752}
753
754/// A cost classifier only: the caller integrates the actual pcurves, never
755/// the approximate rectangle returned here.
756pub(super) fn near_rectangle_for_span_chords(face: &FaceRecord) -> Result<bool, String> {
757    Ok(iso_rectangle_trim_impl_with_exact(face, false, true)?.is_ok())
758}
759
760fn iso_rectangle_trim_impl_with_exact(face: &FaceRecord, exact: bool, either_orientation: bool) -> Result<Result<[f64; 4], &'static str>, String> {
761    if face.loops.len() != 1 {
762        return Ok(Err("not one loop"));
763    }
764    if face.loops[0].coedges.len() != 4 {
765        return Ok(Err("not four coedges"));
766    }
767    let ku = crate::KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u)?;
768    let kv = crate::KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v)?;
769    let [u0, u1] = ku.domain();
770    let [v0, v1] = kv.domain();
771    let (span_u, span_v) = (u1 - u0, v1 - v0);
772    if !(span_u > 0.0 && span_v > 0.0) {
773        return Ok(Err("empty domain"));
774    }
775    // Pcurve ends meet and controls sit on their line to round-off on an
776    // exact chart and to the fit's own residual on a fitted one: 1e-7 of the
777    // span admits both and is a decade under the sign reading's own margin.
778    // An approximate axis classification can replace a real curved or
779    // oblique trim by a rectangle. Exact coverage also requires this second
780    // shortcut to preserve the boundary; uncertain fits take the trimmed
781    // route, including its arc corrections and open-domain extension.
782    let (eps_u, eps_v) = if exact { (0.0, 0.0) } else { (1e-7 * span_u, 1e-7 * span_v) };
783    let mut segments: Vec<([f64; 2], [f64; 2])> = Vec::with_capacity(4);
784    for coedge in &face.loops[0].coedges {
785        // A straight axis-parallel pcurve of ANY degree: every control point
786        // shares the constant coordinate (a NURBS curve lies in its control
787        // hull, so the curve is the segment between its ends) and the control
788        // polygon is monotone in the other, so the curve traverses that
789        // segment once. The imprint emits a fitted straight pcurve on a
790        // fitted carrier; its degree says nothing about the trim.
791        let pcurve = &coedge.pcurve;
792        if pcurve.control_points.len() < 2 {
793            return Ok(Err("a pcurve with one control point"));
794        }
795        let mut controls = Vec::with_capacity(pcurve.control_points.len());
796        for control in &pcurve.control_points {
797            controls.push(control.point()?);
798        }
799        let (first, last) = (controls[0], controls[controls.len() - 1]);
800        let (du, dv) = ((last.x - first.x).abs(), (last.y - first.y).abs());
801        let along_u = dv <= eps_v && du > eps_u;
802        let along_v = du <= eps_u && dv > eps_v;
803        if !(along_u || along_v) {
804            return Ok(Err("a pcurve not parallel to a parameter axis"));
805        }
806        let (constant, varying, eps_constant): (fn(&Vec3) -> f64, fn(&Vec3) -> f64, f64) =
807            if along_u { (|p| p.y, |p| p.x, eps_v) } else { (|p| p.x, |p| p.y, eps_u) };
808        let level = constant(&first);
809        if controls.iter().any(|control| (constant(control) - level).abs() > eps_constant) {
810            return Ok(Err("a pcurve whose controls leave its line"));
811        }
812        let direction = (varying(&last) - varying(&first)).signum();
813        if controls.windows(2).any(|pair| (varying(&pair[1]) - varying(&pair[0])) * direction < 0.0) {
814            return Ok(Err("a pcurve whose controls turn back"));
815        }
816        // A pcurve is stored in the loop's traversal direction; `forward`
817        // relates the coedge to its 3-D edge, not to the pcurve.
818        segments.push(([first.x, first.y], [last.x, last.y]));
819    }
820    let along_u = |segment: &([f64; 2], [f64; 2])| (segment.1[1] - segment.0[1]).abs() <= eps_v;
821    // `BREP_MASS_ISO_RECT_TRIMMED` (default on): a pcurve along u at a level
822    // where the carrier collapses to one point (a sphere's pole) is a
823    // degenerate edge whose u range says nothing about the trim. Boolean
824    // assembly can store it over the whole period (u 1 -> 0) on a face that
825    // spans only part of it, so it does not meet its neighbours and the face
826    // left this route for the trimmed one, which read brep-bench
827    // tangent/half-balls-overlapping's kept quarter sphere (iso-rectangle
828    // [0.25, 0.75] x [0.5, 1]) 1.8e-5 large. Clipped to run from the previous
829    // pcurve's end to the next one's start, it is the rectangle's pole side.
830    if pole_side_clip_on() {
831        for index in 0..4 {
832            let segment = segments[index];
833            if !along_u(&segment) {
834                continue;
835            }
836            let level = segment.0[1];
837            let probe = |u: f64| face.surface.evaluate(u, level);
838            let (a, b, c) = (probe(u0)?, probe(0.5 * (u0 + u1))?, probe(u1)?);
839            let scale = a.length().max(1.0) * 1e-12;
840            if a.sub(b).length() > scale || a.sub(c).length() > scale {
841                continue;
842            }
843            let previous = segments[(index + 3) % 4].1;
844            let next = segments[(index + 1) % 4].0;
845            if (previous[1] - level).abs() <= eps_v && (next[1] - level).abs() <= eps_v {
846                segments[index] = ([previous[0], level], [next[0], level]);
847            }
848        }
849    }
850    for index in 0..4 {
851        let (_, to) = segments[index];
852        let (from, _) = segments[(index + 1) % 4];
853        if (to[0] - from[0]).abs() > eps_u || (to[1] - from[1]).abs() > eps_v {
854            if super::profile::face_lines_enabled() {
855                eprintln!(
856                    "mass.iso_rect face={} gap between pcurves {} and {}: ({:.3e}, {:.3e}) of spans ({:.3e}, {:.3e})",
857                    face.id, index, (index + 1) % 4, to[0] - from[0], to[1] - from[1], span_u, span_v
858                );
859            }
860            return Ok(Err("consecutive pcurves do not meet"));
861        }
862        if along_u(&segments[index]) == along_u(&segments[(index + 1) % 4]) {
863            return Ok(Err("consecutive pcurves run the same way"));
864        }
865    }
866    let corners: Vec<[f64; 2]> = segments.iter().map(|segment| segment.0).collect();
867    if !(if either_orientation { polygon_signed_area(&corners).abs() } else { polygon_signed_area(&corners) } > 0.0) {
868        return Ok(Err("not wound counter-clockwise"));
869    }
870    let (mut u_lo, mut u_hi, mut v_lo, mut v_hi) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
871    for corner in &corners {
872        u_lo = u_lo.min(corner[0]);
873        u_hi = u_hi.max(corner[0]);
874        v_lo = v_lo.min(corner[1]);
875        v_hi = v_hi.max(corner[1]);
876    }
877    // A corner outside the domain by more than round-off is not a sub-rectangle
878    // of the knot grid; one inside it by round-off is clamped onto it.
879    let (slack_u, slack_v) = if exact { (0.0, 0.0) } else { (1e-6 * span_u, 1e-6 * span_v) };
880    if u_lo < u0 - slack_u || u_hi > u1 + slack_u || v_lo < v0 - slack_v || v_hi > v1 + slack_v {
881        return Ok(Err("a corner outside the domain"));
882    }
883    let rectangle = [u_lo.max(u0), u_hi.min(u1), v_lo.max(v0), v_hi.min(v1)];
884    if rectangle[1] - rectangle[0] <= eps_u || rectangle[3] - rectangle[2] <= eps_v {
885        return Ok(Err("a collapsed rectangle"));
886    }
887    Ok(Ok(rectangle))
888}
889
890/// Symmetric degree-5 triangle cubature (barycentric points and weights,
891/// normalized to unit area) — Golovanov §8.10 Table 8.10.2.
892pub(super) const TRIANGLE_CUBATURE: [([f64; 3], f64); 7] = [
893    ([1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0], 0.225),
894    (
895        [0.101286507323456, 0.101286507323456, 0.797426985353087],
896        0.125939180544827,
897    ),
898    (
899        [0.101286507323456, 0.797426985353087, 0.101286507323456],
900        0.125939180544827,
901    ),
902    (
903        [0.797426985353087, 0.101286507323456, 0.101286507323456],
904        0.125939180544827,
905    ),
906    (
907        [0.470142064105115, 0.470142064105115, 0.059715871789770],
908        0.132394152788506,
909    ),
910    (
911        [0.470142064105115, 0.059715871789770, 0.470142064105115],
912        0.132394152788506,
913    ),
914    (
915        [0.059715871789770, 0.470142064105115, 0.470142064105115],
916        0.132394152788506,
917    ),
918];
919
920pub(super) fn polygon_signed_area(polygon: &[[f64; 2]]) -> f64 {
921    crate::polygon::signed_area_2d(polygon.len(), |i| polygon[i])
922}
923
924/// Sutherland–Hodgman clip of one loop against an axis-aligned cell.  A
925/// loop that fully encloses the cell clips to the whole cell; a disjoint
926/// loop clips to nothing — so clipping every loop handles containment,
927/// holes, and partial coverage uniformly, with the loop's winding as the
928/// contribution sign.
929///
930/// The four half-plane passes write into caller-owned buffers: the two working
931/// vectors are ping-ponged for the whole call instead of allocated per pass. The integrator clips every trim loop
932/// against every cell of a knot-conforming grid and then against every
933/// quadtree child of every boundary cell, so the five vectors a call used to
934/// allocate were the shape of its clipping cost.
935pub(super) fn clip_polygon_to_cell_into(
936    polygon: &[[f64; 2]],
937    cell: [f64; 4],
938    scratch: &mut Vec<[f64; 2]>,
939    out: &mut Vec<[f64; 2]>,
940) {
941    let [u_low, u_high, v_low, v_high] = cell;
942    out.clear();
943    out.extend_from_slice(polygon);
944    // (axis, bound, keep_below)
945    for (axis, bound, keep_below) in [
946        (0, u_low, false),
947        (0, u_high, true),
948        (1, v_low, false),
949        (1, v_high, true),
950    ] {
951        if out.len() < 3 {
952            out.clear();
953            return;
954        }
955        let inside = |point: &[f64; 2]| {
956            if keep_below {
957                point[axis] <= bound
958            } else {
959                point[axis] >= bound
960            }
961        };
962        scratch.clear();
963        scratch.reserve(out.len() + 4);
964        for index in 0..out.len() {
965            let a = out[index];
966            let b = out[(index + 1) % out.len()];
967            let a_in = inside(&a);
968            let b_in = inside(&b);
969            if a_in {
970                scratch.push(a);
971            }
972            if a_in != b_in {
973                let t = (bound - a[axis]) / (b[axis] - a[axis]);
974                let mut crossing = [0.0; 2];
975                crossing[axis] = bound;
976                crossing[1 - axis] = a[1 - axis] + t * (b[1 - axis] - a[1 - axis]);
977                scratch.push(crossing);
978            }
979        }
980        std::mem::swap(scratch, out);
981    }
982}
983
984/// The passes of [`clip_polygon_to_cell_into`] split in two, with the same
985/// arithmetic in the same order: [`clip_polygon_to_column_into`] runs the two
986/// u passes (they read only the cell's u bounds, so every cell of one grid
987/// column shares their result) and [`clip_column_to_cell_into`] runs the two v
988/// passes on that fragment. Chained, they leave in `out` exactly what the
989/// four-pass call leaves.
990pub(super) fn clip_polygon_to_column_into(
991    polygon: &[[f64; 2]],
992    u_low: f64,
993    u_high: f64,
994    scratch: &mut Vec<[f64; 2]>,
995    out: &mut Vec<[f64; 2]>,
996) {
997    out.clear();
998    out.extend_from_slice(polygon);
999    clip_passes(&[(0, u_low, false), (0, u_high, true)], scratch, out);
1000}
1001
1002/// The two v passes of [`clip_polygon_to_cell_into`] on a column fragment
1003/// from [`clip_polygon_to_column_into`].
1004pub(super) fn clip_column_to_cell_into(
1005    column: &[[f64; 2]],
1006    v_low: f64,
1007    v_high: f64,
1008    scratch: &mut Vec<[f64; 2]>,
1009    out: &mut Vec<[f64; 2]>,
1010) {
1011    out.clear();
1012    out.extend_from_slice(column);
1013    clip_passes(&[(1, v_low, false), (1, v_high, true)], scratch, out);
1014}
1015
1016/// The half-plane passes of [`clip_polygon_to_cell_into`], verbatim: before
1017/// each pass a fragment under three points clips to nothing.
1018fn clip_passes(passes: &[(usize, f64, bool)], scratch: &mut Vec<[f64; 2]>, out: &mut Vec<[f64; 2]>) {
1019    for &(axis, bound, keep_below) in passes {
1020        if out.len() < 3 {
1021            out.clear();
1022            return;
1023        }
1024        let inside = |point: &[f64; 2]| {
1025            if keep_below {
1026                point[axis] <= bound
1027            } else {
1028                point[axis] >= bound
1029            }
1030        };
1031        scratch.clear();
1032        scratch.reserve(out.len() + 4);
1033        for index in 0..out.len() {
1034            let a = out[index];
1035            let b = out[(index + 1) % out.len()];
1036            let a_in = inside(&a);
1037            let b_in = inside(&b);
1038            if a_in {
1039                scratch.push(a);
1040            }
1041            if a_in != b_in {
1042                let t = (bound - a[axis]) / (b[axis] - a[axis]);
1043                let mut crossing = [0.0; 2];
1044                crossing[axis] = bound;
1045                crossing[1 - axis] = a[1 - axis] + t * (b[1 - axis] - a[1 - axis]);
1046                scratch.push(crossing);
1047            }
1048        }
1049        std::mem::swap(scratch, out);
1050    }
1051}
1052
1053pub(super) fn cell_breaks(knots: &[f64], degree: usize, low: f64, high: f64) -> Vec<f64> {
1054    let mut breaks = vec![low, high];
1055    breaks.extend(interior_knots(knots, degree));
1056    breaks.sort_by(f64::total_cmp);
1057    breaks.dedup_by(|a, b| (*a - *b).abs() <= (high - low) * 1e-12);
1058    // Subdivide spans so the base grid has at least MINIMUM_CELLS cells
1059    // across the domain; boundary cells then refine adaptively.
1060    const MINIMUM_CELLS: usize = 8;
1061    let target = (high - low) / MINIMUM_CELLS as f64;
1062    let mut refined = Vec::with_capacity(breaks.len() * 2);
1063    for pair in breaks.windows(2) {
1064        refined.push(pair[0]);
1065        let span = pair[1] - pair[0];
1066        let pieces = (span / target).ceil().max(1.0) as usize;
1067        for piece in 1..pieces {
1068            refined.push(pair[0] + span * piece as f64 / pieces as f64);
1069        }
1070    }
1071    refined.push(high);
1072    refined
1073}
1074
1075/// Tile one period's `cell_breaks` across `[lo, hi]` for a periodic direction
1076/// whose unwrapped trim ran past the domain end. Shifted copies of the base
1077/// breaks keep the knot-conforming grid on every covered period; a direction
1078/// that stayed in-domain yields exactly the base breaks.
1079pub(super) fn tiled_breaks(base: &[f64], lo: f64, hi: f64, period: f64) -> Vec<f64> {
1080    if period <= 0.0 || base.len() < 2 {
1081        return base.to_vec();
1082    }
1083    let origin = base[0];
1084    let first = ((lo - origin) / period).floor() as i64;
1085    let last = ((hi - origin) / period).ceil() as i64;
1086    let mut breaks = Vec::new();
1087    for tile in first..=last {
1088        let shift = tile as f64 * period;
1089        for &value in base {
1090            let shifted = value + shift;
1091            if breaks.last().map_or(true, |&previous: &f64| {
1092                (shifted - previous).abs() > 1e-12 * period
1093            }) {
1094                breaks.push(shifted);
1095            }
1096        }
1097    }
1098    breaks
1099}