1pub(super) use crate::curve::interior_knots;
2use super::*;
3
4pub(crate) 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
29fn open_planar_loops() -> bool {
33 static OPEN: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
34 *OPEN.get_or_init(|| std::env::var_os("BREP_OPEN_PLANAR_LOOPS").is_some())
35}
36
37pub(super) fn loop_closing_chords(face: &FaceRecord) -> Result<Vec<(Vec3, Vec3)>, String> {
41 let mut chords = Vec::new();
42 if open_planar_loops() {
43 return Ok(chords);
44 }
45 for loop_record in &face.loops {
46 let count = loop_record.coedges.len();
47 for index in 0..count {
48 let [_, end] = loop_record.coedges[index].pcurve.domain()?;
49 let [start, _] = loop_record.coedges[(index + 1) % count].pcurve.domain()?;
50 chords.push((
51 loop_record.coedges[index].pcurve.evaluate(end)?,
52 loop_record.coedges[(index + 1) % count].pcurve.evaluate(start)?,
53 ));
54 }
55 }
56 Ok(chords)
57}
58
59pub(crate) fn closed_parameter_space_area(face: &FaceRecord) -> Result<f64, String> {
79 let mut area = parameter_space_area(face)?;
80 for (end, start) in loop_closing_chords(face)? {
81 area += 0.5 * (end.x * start.y - start.x * end.y);
82 }
83 Ok(area)
84}
85
86const SEAM_COINCIDENCE_REL: f64 = 1e-12;
96
97pub(crate) fn closed_parameter_space_area_on_carrier(face: &FaceRecord) -> Result<f64, String> {
113 let mut area = parameter_space_area(face)?;
114 let mut coincidence: Option<f64> = None;
115 for loop_record in &face.loops {
116 let count = loop_record.coedges.len();
117 for index in 0..count {
118 let [_, end] = loop_record.coedges[index].pcurve.domain()?;
119 let [start, _] = loop_record.coedges[(index + 1) % count].pcurve.domain()?;
120 let here = loop_record.coedges[index].pcurve.evaluate(end)?;
121 let next = loop_record.coedges[(index + 1) % count].pcurve.evaluate(start)?;
122 if here.x == next.x && here.y == next.y {
123 continue;
124 }
125 let bar = *coincidence.get_or_insert_with(|| {
126 SEAM_COINCIDENCE_REL
127 * crate::tolerance::model_scale(
128 face.surface
129 .control_points
130 .iter()
131 .flatten()
132 .filter_map(|control| control.point().ok()),
133 )
134 });
135 let (image_here, image_next) = (
136 face.surface.evaluate_extended(here.x, here.y)?,
137 face.surface.evaluate_extended(next.x, next.y)?,
138 );
139 if image_here.sub(image_next).length() <= bar {
140 continue;
141 }
142 area += 0.5 * (here.x * next.y - next.x * here.y);
143 }
144 }
145 Ok(area)
146}
147
148pub(super) fn is_affine(surface: &NurbsSurface) -> Result<bool, String> {
149 surface.is_affine()
151}
152
153pub(crate) fn surface_breaks(surface: &NurbsSurface) -> Result<(Vec<f64>, Vec<f64>), String> {
154 let ku = crate::KnotVector::new(surface.knots_u.clone(), surface.degree_u)?;
155 let kv = crate::KnotVector::new(surface.knots_v.clone(), surface.degree_v)?;
156 let [u0, u1] = ku.domain();
157 let [v0, v1] = kv.domain();
158 let mut u = vec![u0];
159 u.extend(interior_knots(&surface.knots_u, surface.degree_u));
160 u.push(u1);
161 let mut v = vec![v0];
162 v.extend(interior_knots(&surface.knots_v, surface.degree_v));
163 v.push(v1);
164 Ok((u, v))
165}
166
167pub(super) fn integrand_value(kind: Integrand, point: Vec3, weighted_normal: Vec3) -> f64 {
168 let (x, y, z) = (point.x, point.y, point.z);
169 match kind {
170 Integrand::Area => weighted_normal.length(),
171 Integrand::Volume => point.dot(weighted_normal),
172 Integrand::VolumeAbout(reference) => point.sub(reference).dot(weighted_normal),
173 Integrand::MomentX => 0.5 * x * x * weighted_normal.x,
174 Integrand::MomentY => 0.5 * y * y * weighted_normal.y,
175 Integrand::MomentZ => 0.5 * z * z * weighted_normal.z,
176 Integrand::SecondXX => x * x * x / 3.0 * weighted_normal.x,
177 Integrand::SecondYY => y * y * y / 3.0 * weighted_normal.y,
178 Integrand::SecondZZ => z * z * z / 3.0 * weighted_normal.z,
179 Integrand::ProductXY => 0.5 * x * x * y * weighted_normal.x,
180 Integrand::ProductXZ => 0.5 * x * x * z * weighted_normal.x,
181 Integrand::ProductYZ => 0.5 * y * y * z * weighted_normal.y,
182 }
183}
184
185
186pub(super) const GAUSS_COUNT: usize = GAUSS_X.len();
188
189pub(super) fn tensor_blocks_on() -> bool {
195 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
196 *ON.get_or_init(|| std::env::var("BREP_MASS_TENSOR_BLOCK").as_deref() != Ok("0"))
197}
198
199pub(super) fn integrate_cell_scaled(
213 face: &FaceRecord,
214 cell: [f64; 4],
215 scale: f64,
216 kinds: &[Integrand],
217 totals: &mut [f64],
218 rules: &mut rule::SurfaceRules,
219) -> Result<usize, String> {
220 let (u_panels, v_panels) = rules.panels(&face.surface, cell)?;
224 let mut stations = 0;
225 for u_panel in &u_panels {
226 for v_panel in &v_panels {
227 integrate_block(face, *u_panel, *v_panel, scale, kinds, totals)?;
228 stations += u_panel.order * v_panel.order;
229 }
230 }
231 Ok(stations)
232}
233
234fn integrate_block(
236 face: &FaceRecord,
237 u_panel: rule::Panel,
238 v_panel: rule::Panel,
239 scale: f64,
240 kinds: &[Integrand],
241 totals: &mut [f64],
242) -> Result<(), String> {
243 let half_u = (u_panel.hi - u_panel.lo) * 0.5;
244 let middle_u = (u_panel.hi + u_panel.lo) * 0.5;
245 let half_v = (v_panel.hi - v_panel.lo) * 0.5;
246 let middle_v = (v_panel.hi + v_panel.lo) * 0.5;
247 let (u_x, u_w) = u_panel.nodes();
248 let (v_x, v_w) = v_panel.nodes();
249 let sign = if face.same_sense { 1.0 } else { -1.0 };
250 let base_rule = u_x.len() == GAUSS_COUNT && v_x.len() == GAUSS_COUNT;
256 if base_rule && tensor_blocks_on() && face.surface.deriv1_tensor_supported() {
257 let mut u_stations = [0.0f64; GAUSS_COUNT];
258 let mut v_stations = [0.0f64; GAUSS_COUNT];
259 for index in 0..GAUSS_COUNT {
260 u_stations[index] = middle_u + half_u * GAUSS_X[index];
261 v_stations[index] = middle_v + half_v * GAUSS_X[index];
262 }
263 return face
264 .surface
265 .deriv1_tensor_each(&u_stations, &v_stations, |i, j, point, su, sv| {
266 let weighted_normal = su.cross(sv).scale(sign);
267 for (slot, kind) in kinds.iter().enumerate() {
268 totals[slot] += scale
269 * GAUSS_W[i]
270 * GAUSS_W[j]
271 * half_u
272 * half_v
273 * integrand_value(*kind, point, weighted_normal);
274 }
275 Ok(())
276 });
277 }
278 if base_rule && !face.surface.deriv1_tensor_supported() {
279 for i in 0..GAUSS_COUNT {
280 for j in 0..GAUSS_COUNT {
281 let (point, su, sv) = face
282 .surface
283 .deriv1(middle_u + half_u * GAUSS_X[i], middle_v + half_v * GAUSS_X[j])?;
284 let weighted_normal = su.cross(sv).scale(sign);
285 for (slot, kind) in kinds.iter().enumerate() {
286 totals[slot] += scale
287 * GAUSS_W[i]
288 * GAUSS_W[j]
289 * half_u
290 * half_v
291 * integrand_value(*kind, point, weighted_normal);
292 }
293 }
294 }
295 return Ok(());
296 }
297 if tensor_blocks_on() && face.surface.deriv1_tensor_supported() {
298 let mut u_stations = [0.0f64; rule::MAX_ORDER];
299 let mut v_stations = [0.0f64; rule::MAX_ORDER];
300 for index in 0..u_x.len() {
301 u_stations[index] = middle_u + half_u * u_x[index];
302 }
303 for index in 0..v_x.len() {
304 v_stations[index] = middle_v + half_v * v_x[index];
305 }
306 return face.surface.deriv1_tensor_each(
307 &u_stations[..u_x.len()],
308 &v_stations[..v_x.len()],
309 |i, j, point, su, sv| {
310 let weighted_normal = su.cross(sv).scale(sign);
311 for (slot, kind) in kinds.iter().enumerate() {
312 totals[slot] += scale
313 * u_w[i]
314 * v_w[j]
315 * half_u
316 * half_v
317 * integrand_value(*kind, point, weighted_normal);
318 }
319 Ok(())
320 },
321 );
322 }
323 for i in 0..u_x.len() {
324 for j in 0..v_x.len() {
325 let (point, su, sv) = face
326 .surface
327 .deriv1(middle_u + half_u * u_x[i], middle_v + half_v * v_x[j])?;
328 let weighted_normal = su.cross(sv).scale(sign);
329 for (slot, kind) in kinds.iter().enumerate() {
330 totals[slot] += scale
331 * u_w[i]
332 * v_w[j]
333 * half_u
334 * half_v
335 * integrand_value(*kind, point, weighted_normal);
336 }
337 }
338 }
339 Ok(())
340}
341
342pub(super) fn integrate_untrimmed_multi(
347 face: &FaceRecord,
348 kinds: &[Integrand],
349) -> Result<Vec<f64>, String> {
350 let (u_breaks, v_breaks) = surface_breaks(&face.surface)?;
351 let mut totals = vec![0.0f64; kinds.len()];
352 let mut rules = rule::SurfaceRules::new(&face.surface)?;
353 for upair in u_breaks.windows(2) {
354 for vpair in v_breaks.windows(2) {
355 integrate_cell_scaled(
356 face,
357 [upair[0], upair[1], vpair[0], vpair[1]],
358 1.0,
359 kinds,
360 &mut totals,
361 &mut rules,
362 )?;
363 }
364 }
365 Ok(totals)
366}
367
368pub(super) fn integrate_untrimmed(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
369 Ok(integrate_untrimmed_multi(face, &[kind])?[0])
370}
371
372#[derive(Clone, Copy)]
379pub(super) struct BiBand {
380 pub(super) p_is_u: bool,
382 pub(super) q_lo: f64,
384 pub(super) q_hi: f64,
385 pub(super) complement: bool,
389 pub(super) rim_wobble: f64,
396}
397
398pub(super) const BAND_RIM_LEVEL_TOLERANCE_REL: f64 = 1e-9;
413
414pub(super) fn biperiodic_band_range(face: &FaceRecord) -> Result<Option<BiBand>, String> {
421 let surface = &face.surface;
422 let (closed_u, closed_v) = surface.closed_directions()?;
423 if !(closed_u && closed_v) {
424 return Ok(None);
425 }
426 let [u0, u1] = surface.domain_u()?;
427 let [v0, v1] = surface.domain_v()?;
428 let u_span = (u1 - u0).abs().max(1e-30);
429 let v_span = (v1 - v0).abs().max(1e-30);
430 let mut loop_points: Vec<Vec<[f64; 2]>> = Vec::with_capacity(2);
436 for loop_record in &face.loops {
437 let mut points = Vec::new();
438 for coedge in &loop_record.coedges {
439 let [d0, d1] = coedge.pcurve.domain()?;
440 let samples = 32;
443 for k in 0..=samples {
444 let t = d0 + (d1 - d0) * k as f64 / samples as f64;
445 let p = coedge.pcurve.evaluate(t)?;
446 points.push([p.x, p.y]);
447 }
448 }
449 if points.len() < 2 {
450 return Ok(None);
451 }
452 let (mut umin, mut umax, mut vmin, mut vmax) = (
453 f64::INFINITY,
454 f64::NEG_INFINITY,
455 f64::INFINITY,
456 f64::NEG_INFINITY,
457 );
458 for pt in &points {
459 umin = umin.min(pt[0]);
460 umax = umax.max(pt[0]);
461 vmin = vmin.min(pt[1]);
462 vmax = vmax.max(pt[1]);
463 }
464 if (umax - umin) <= 1e-3 * u_span && (vmax - vmin) <= 1e-3 * v_span {
465 continue; }
467 loop_points.push(points);
468 }
469 if loop_points.len() != 2 {
470 return Ok(None);
471 }
472 for p_is_u in [true, false] {
473 let (period, _p0, _p1) = if p_is_u {
474 (u1 - u0, u0, u1)
475 } else {
476 (v1 - v0, v0, v1)
477 };
478 let (q_dom_lo, q_dom_hi) = if p_is_u { (v0, v1) } else { (u0, u1) };
479 let q_extent = (q_dom_hi - q_dom_lo).abs().max(1e-30);
480 if !(period > 0.0) {
481 continue;
482 }
483 let coord = |pt: &[f64; 2]| -> (f64, f64) {
484 if p_is_u {
485 (pt[0], pt[1])
486 } else {
487 (pt[1], pt[0])
488 }
489 };
490 let mut rings: Vec<(f64, i32)> = Vec::with_capacity(2);
493 let mut clean = true;
494 let mut rim_wobble = 0.0f64;
495 for points in &loop_points {
496 let (mut pmin, mut pmax, mut qmin, mut qmax) = (
497 f64::INFINITY,
498 f64::NEG_INFINITY,
499 f64::INFINITY,
500 f64::NEG_INFINITY,
501 );
502 for pt in points {
503 let (p, q) = coord(pt);
504 pmin = pmin.min(p);
505 pmax = pmax.max(p);
506 qmin = qmin.min(q);
507 qmax = qmax.max(q);
508 }
509 if (pmax - pmin) < 0.6 * period || (qmax - qmin) > 0.05 * q_extent {
510 clean = false;
511 break;
512 }
513 rim_wobble = rim_wobble.max((qmax - qmin) / q_extent);
514 let mut net = 0.0;
515 for pair in points.windows(2) {
516 let mut delta = coord(&pair[1]).0 - coord(&pair[0]).0;
517 if delta > 0.5 * period {
518 delta -= period;
519 } else if delta < -0.5 * period {
520 delta += period;
521 }
522 net += delta;
523 }
524 let direction = if net > 0.25 * period {
525 1
526 } else if net < -0.25 * period {
527 -1
528 } else {
529 0
530 };
531 rings.push((0.5 * (qmin + qmax), direction));
532 }
533 if !clean || rings.len() != 2 {
534 continue;
535 }
536 rings.sort_by(|a, b| a.0.total_cmp(&b.0));
537 let (q_lo, lower_dir) = rings[0];
538 let (q_hi, upper_dir) = rings[1];
539 let inconclusive = lower_dir == 0 || upper_dir == 0 || lower_dir == upper_dir;
540 let between_rims_is_ccw_uv = if p_is_u { lower_dir > 0 } else { lower_dir < 0 };
541 let complement = !inconclusive && between_rims_is_ccw_uv != face.same_sense;
542 return Ok(Some(BiBand {
543 p_is_u,
544 q_lo,
545 q_hi,
546 complement,
547 rim_wobble,
548 }));
549 }
550 Ok(None)
551}
552
553pub(super) fn integrate_rectangle(
556 face: &FaceRecord,
557 u_lo: f64,
558 u_hi: f64,
559 v_lo: f64,
560 v_hi: f64,
561 kind: Integrand,
562) -> Result<f64, String> {
563 let (u_full, v_full) = surface_breaks(&face.surface)?;
564 let clamp = |breaks: &[f64], lo: f64, hi: f64| -> Vec<f64> {
565 let eps = 1e-9 * (hi - lo).abs().max(1e-30);
566 let mut out = vec![lo];
567 for &b in breaks {
568 if b > lo + eps && b < hi - eps {
569 out.push(b);
570 }
571 }
572 out.push(hi);
573 out
574 };
575 let u_breaks = clamp(&u_full, u_lo, u_hi);
576 let v_breaks = clamp(&v_full, v_lo, v_hi);
577 let mut totals = [0.0f64];
578 let mut rules = rule::SurfaceRules::new(&face.surface)?;
579 for upair in u_breaks.windows(2) {
580 for vpair in v_breaks.windows(2) {
581 integrate_cell_scaled(
582 face,
583 [upair[0], upair[1], vpair[0], vpair[1]],
584 1.0,
585 &[kind],
586 &mut totals,
587 &mut rules,
588 )?;
589 }
590 }
591 Ok(totals[0])
592}
593
594pub(super) fn biperiodic_band_integral(
611 face: &FaceRecord,
612 kinds: &[Integrand],
613) -> Result<Option<Vec<f64>>, String> {
614 let Some(band) = biperiodic_band_range(face)? else {
615 return Ok(None);
616 };
617 let [u0, u1] = face.surface.domain_u()?;
618 let [v0, v1] = face.surface.domain_v()?;
619 let (u_lo, u_hi, v_lo, v_hi) = if band.p_is_u {
620 (u0, u1, band.q_lo, band.q_hi)
621 } else {
622 (band.q_lo, band.q_hi, v0, v1)
623 };
624 let strips: Vec<f64> = if band.rim_wobble <= BAND_RIM_LEVEL_TOLERANCE_REL {
625 kinds
626 .iter()
627 .map(|&kind| integrate_rectangle(face, u_lo, u_hi, v_lo, v_hi, kind))
628 .collect::<Result<_, _>>()?
629 } else {
630 super::winding::winding_loops_integral(face, kinds, band.p_is_u, 1)?
631 };
632 let mut out = Vec::with_capacity(kinds.len());
633 for (&kind, strip) in kinds.iter().zip(strips) {
634 let value = if band.complement {
635 integrate_untrimmed(face, kind)? - strip
636 } else {
637 strip
638 };
639 out.push(value);
640 }
641 Ok(Some(out))
642}