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
29fn open_planar_loops() -> bool {
33 debug_flag!("BREP_OPEN_PLANAR_LOOPS")
34}
35
36pub(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
58pub 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
85const SEAM_COINCIDENCE_REL: f64 = 1e-12;
95
96pub 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 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
188pub const GAUSS_COUNT: usize = GAUSS_X.len();
190
191pub(super) fn tensor_blocks_on() -> bool {
197 switch!("BREP_MASS_TENSOR_BLOCK", true)
198}
199
200pub 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 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 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
249pub fn area_adaptive_on() -> bool {
261 switch!("BREP_MASS_AREA_ADAPTIVE", true)
262}
263
264const AREA_ADAPTIVE_DEPTH: usize = 6;
266
267const AREA_ADAPTIVE_TOLERANCE: f64 = 1e-11;
270
271fn 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
316pub(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 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
439pub 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
465pub 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#[derive(Clone, Copy)]
510pub struct BiBand {
511 pub(super) p_is_u: bool,
513 pub q_lo: f64,
515 pub q_hi: f64,
516 pub(super) complement: bool,
520 pub rim_wobble: f64,
527}
528
529pub const BAND_RIM_LEVEL_TOLERANCE_REL: f64 = 1e-9;
543
544pub 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 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 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; }
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 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
683pub 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
724pub(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}