1use crate::curve::interior_knot_count;
2pub use super::*;
3
4pub fn trim_sample_count(curve: &NurbsCurve) -> usize {
25 2usize.max((interior_knot_count(&curve.knots, curve.degree) + 1) * (curve.degree + 1) * 4)
26}
27
28pub fn trim_station(start: f64, end: f64, index: usize, count: usize) -> f64 {
36 start + (end - start) * index as f64 / count as f64
37}
38
39pub const SEAM_BAND_MERGED_SWITCH: &str = "BREP_SEAM_BAND_MERGED";
44
45pub const HORIZON_CONTAINMENT_SWITCH: &str = "BREP_HORIZON_CONTAINMENT";
48
49pub const HORIZON_SINGLE_LOOP_SWITCH: &str = "BREP_HORIZON_SINGLE_LOOP";
53
54pub const HORIZON_CROSS_FRAME_SWITCH: &str = "BREP_HORIZON_CROSS_FRAME";
59
60pub const COVERING_RIM_STRIP_SWITCH: &str = "BREP_COVERING_RIM_STRIP";
63
64pub const NO_SPHERE_CHART_TRIM_SWITCH: &str = "BREP_NO_SPHERE_CHART_TRIM";
69
70pub fn horizon_cross_frame() -> bool {
83 switch!(HORIZON_CROSS_FRAME_SWITCH, true)
84}
85
86fn sphere_chart_trim_enabled() -> bool {
90 env_read!("BREP_NO_SPHERE_CHARTS").is_none()
91 && std::env::var(NO_SPHERE_CHART_TRIM_SWITCH).is_err()
92}
93
94fn point_segment_distance(point: Vec2, start: Vec2, end: Vec2) -> f64 {
95 point.distance_to_segment(start, end, 1e-30)
96}
97
98pub use crate::polygon::PolygonClass;
99
100pub fn point_in_polygon(point: Vec2, polygon: &[Vec2], tolerance: f64) -> PolygonClass {
101 crate::polygon::classify(point, polygon, tolerance, 1e-30)
102}
103
104fn polygon_parity_inside(point: Vec2, polygon: &[Vec2]) -> bool {
107 crate::polygon::parity_inside([point.x, point.y], polygon.len(), |i| [polygon[i].x, polygon[i].y])
108}
109
110
111#[derive(Clone, Copy)]
116struct SegmentPrep {
117 coedge_index: usize,
118 parameter_start: f64,
119 parameter_end: f64,
120}
121
122pub fn lane_switches() -> f64 {
126 let mut bits = 0u32;
127 if !switch!(SEAM_BAND_MERGED_SWITCH, true) {
128 bits |= 1;
129 }
130 if !switch!(HORIZON_CONTAINMENT_SWITCH, true) {
131 bits |= 2;
132 }
133 if !switch!(HORIZON_SINGLE_LOOP_SWITCH, true) {
134 bits |= 4;
135 }
136 if !switch!(COVERING_RIM_STRIP_SWITCH, true) {
137 bits |= 8;
138 }
139 bits as f64
140}
141
142enum SeamBandPrep {
144 NotApplicable,
146 AlwaysInside,
148 Merged { polygon: Vec<Vec2>, u_span: f64, v_span: f64 },
150 Analyzed { polygon: Vec<Vec2> },
152 Rings { p_is_u: bool, q_lo: f64, q_hi: f64, complement: bool },
154 Declined,
156}
157
158struct SphereCapPrep {
160 rim: Vec<Vec2>,
161 pole_v: f64,
162 period: f64,
163}
164
165struct HorizonPrep {
167 loops: Vec<Vec<Vec2>>,
168 u_period: f64,
169 index: std::cell::OnceCell<Option<ChordIndex>>,
171}
172
173struct RimStripPrep {
175 lower: Vec<Vec2>,
176 upper: Vec<Vec2>,
177 period: f64,
178}
179
180pub struct GenericPrep {
183 pub loops: Vec<LoopSamples>,
184 segments: Vec<Vec<SegmentPrep>>,
185 chord_count: usize,
187 index: std::cell::OnceCell<Option<ChordIndex>>,
190}
191
192const CHORD_INDEX_MIN_CHORDS: usize = 64;
196
197const CHORD_INDEX_LEAF: usize = 6;
199
200const CHORD_INDEX_MAX_COORDINATE: f64 = 1e100;
205
206#[derive(Clone, Copy)]
212struct ChordNode {
213 low: Vec2,
214 high: Vec2,
215 loop_index: u32,
216 first: u32,
217 last: u32,
218 children: Option<(u32, u32)>,
219}
220
221struct ChordIndex {
254 nodes: Vec<ChordNode>,
255 roots: Vec<u32>,
257 slack: f64,
259}
260
261trait ChordLoops {
264 fn loop_count(&self) -> usize;
265 fn polygon(&self, index: usize) -> &[Vec2];
266}
267
268impl ChordLoops for [LoopSamples] {
269 fn loop_count(&self) -> usize {
270 self.len()
271 }
272
273 fn polygon(&self, index: usize) -> &[Vec2] {
274 &self[index].polygon
275 }
276}
277
278impl ChordLoops for [Vec<Vec2>] {
279 fn loop_count(&self) -> usize {
280 self.len()
281 }
282
283 fn polygon(&self, index: usize) -> &[Vec2] {
284 &self[index]
285 }
286}
287
288impl ChordIndex {
289 fn build<L: ChordLoops + ?Sized>(loops: &L) -> Option<ChordIndex> {
293 let mut nodes: Vec<ChordNode> = Vec::new();
294 let mut roots = Vec::new();
295 let mut largest: f64 = 0.0;
296 for loop_index in 0..loops.loop_count() {
297 let polygon = loops.polygon(loop_index);
298 let len = polygon.len();
299 if len == 0 {
300 continue;
301 }
302 u32::try_from(len).ok()?;
303 for sample in polygon {
304 if !(sample.x.abs() <= CHORD_INDEX_MAX_COORDINATE && sample.y.abs() <= CHORD_INDEX_MAX_COORDINATE) {
305 return None;
306 }
307 largest = largest.max(sample.x.abs()).max(sample.y.abs());
308 }
309 let loop_index = u32::try_from(loop_index).ok()?;
310 let mut level: Vec<u32> = Vec::with_capacity(len / CHORD_INDEX_LEAF + 1);
311 for first in (0..len).step_by(CHORD_INDEX_LEAF) {
312 let last = (first + CHORD_INDEX_LEAF).min(len);
313 let (mut low, mut high) = (polygon[first], polygon[first]);
314 for index in first..last {
315 let end = polygon[(index + 1) % len];
316 low = Vec2 { x: low.x.min(end.x), y: low.y.min(end.y) };
317 high = Vec2 { x: high.x.max(end.x), y: high.y.max(end.y) };
318 let start = polygon[index];
319 low = Vec2 { x: low.x.min(start.x), y: low.y.min(start.y) };
320 high = Vec2 { x: high.x.max(start.x), y: high.y.max(start.y) };
321 }
322 level.push(u32::try_from(nodes.len()).ok()?);
323 nodes.push(ChordNode {
324 low,
325 high,
326 loop_index,
327 first: first as u32,
328 last: last as u32,
329 children: None,
330 });
331 }
332 while level.len() > 1 {
333 let mut next = Vec::with_capacity(level.len() / 2 + 1);
334 for pair in level.chunks(2) {
335 let &[left, right] = pair else {
336 next.push(pair[0]);
337 continue;
338 };
339 let (a, b) = (nodes[left as usize], nodes[right as usize]);
340 next.push(u32::try_from(nodes.len()).ok()?);
341 nodes.push(ChordNode {
342 low: Vec2 { x: a.low.x.min(b.low.x), y: a.low.y.min(b.low.y) },
343 high: Vec2 { x: a.high.x.max(b.high.x), y: a.high.y.max(b.high.y) },
344 loop_index,
345 first: a.first,
346 last: b.last,
347 children: Some((left, right)),
348 });
349 }
350 level = next;
351 }
352 roots.push(level[0]);
353 }
354 if roots.is_empty() {
355 return None;
356 }
357 Some(ChordIndex {
358 nodes,
359 roots,
360 slack: 1e-12 * (1.0 + largest),
361 })
362 }
363
364 fn slack_at(&self, point: Vec2) -> f64 {
367 self.slack + 1e-12 * point.x.abs().max(point.y.abs())
368 }
369
370 fn box_distance(node: &ChordNode, point: Vec2) -> f64 {
371 let dx = (node.low.x - point.x).max(point.x - node.high.x).max(0.0);
372 let dy = (node.low.y - point.y).max(point.y - node.high.y).max(0.0);
373 (dx * dx + dy * dy).sqrt()
374 }
375
376 fn nearest<L: ChordLoops + ?Sized>(&self, loops: &L, point: Vec2) -> Option<(usize, usize, f64)> {
380 let slack = self.slack_at(point);
381 let mut best: Option<(f64, u32, u32)> = None;
382 let mut stack: Vec<(u32, f64)> = Vec::with_capacity(64);
383 for &root in &self.roots {
384 stack.push((root, Self::box_distance(&self.nodes[root as usize], point)));
385 }
386 while let Some((node_index, bound)) = stack.pop() {
387 if best.is_some_and(|(distance, _, _)| bound > distance + slack + 1e-12 * distance) {
388 continue;
389 }
390 let node = self.nodes[node_index as usize];
391 match node.children {
392 None => {
393 let polygon = loops.polygon(node.loop_index as usize);
394 for index in node.first..node.last {
395 let start = polygon[index as usize];
396 let end = polygon[(index as usize + 1) % polygon.len()];
397 let distance = point_segment_distance(point, start, end);
398 let better = best.is_none_or(|(least, loop_index, chord_index)| {
399 distance < least
400 || (distance == least && (node.loop_index, index) < (loop_index, chord_index))
401 });
402 if better {
403 best = Some((distance, node.loop_index, index));
404 }
405 }
406 }
407 Some((left, right)) => {
408 let left_bound = Self::box_distance(&self.nodes[left as usize], point);
409 let right_bound = Self::box_distance(&self.nodes[right as usize], point);
410 if left_bound <= right_bound {
412 stack.push((right, right_bound));
413 stack.push((left, left_bound));
414 } else {
415 stack.push((left, left_bound));
416 stack.push((right, right_bound));
417 }
418 }
419 }
420 }
421 best.map(|(distance, loop_index, chord_index)| {
422 (loop_index as usize, chord_index as usize, distance)
423 })
424 }
425
426 fn any_within<L: ChordLoops + ?Sized>(&self, loops: &L, point: Vec2, tolerance: f64) -> bool {
429 let reach = tolerance + self.slack_at(point) + 1e-12 * tolerance.abs();
430 let mut stack: Vec<u32> = self.roots.clone();
431 while let Some(node_index) = stack.pop() {
432 let node = self.nodes[node_index as usize];
433 if Self::box_distance(&node, point) > reach {
434 continue;
435 }
436 match node.children {
437 None => {
438 let polygon = loops.polygon(node.loop_index as usize);
439 for index in node.first as usize..node.last as usize {
440 let (start, end) = (polygon[index], polygon[(index + 1) % polygon.len()]);
441 if point_segment_distance(point, start, end) <= tolerance {
442 return true;
443 }
444 }
445 }
446 Some((left, right)) => {
447 stack.push(right);
448 stack.push(left);
449 }
450 }
451 }
452 false
453 }
454
455 fn flip_crossings<L: ChordLoops + ?Sized>(&self, loops: &L, point: Vec2, odd: &mut [bool]) {
458 let slack = self.slack_at(point);
459 let mut stack: Vec<u32> = self.roots.clone();
460 while let Some(node_index) = stack.pop() {
461 let node = self.nodes[node_index as usize];
462 if !(node.low.y <= point.y && node.high.y > point.y) || node.high.x + slack < point.x {
463 continue;
464 }
465 match node.children {
466 None => {
467 let polygon = loops.polygon(node.loop_index as usize);
468 for index in node.first as usize..node.last as usize {
469 let a = polygon[index];
470 let b = polygon[(index + 1) % polygon.len()];
471 if crate::polygon::crosses_ray([point.x, point.y], [a.x, a.y], [b.x, b.y]) {
472 let parity = &mut odd[node.loop_index as usize];
473 *parity = !*parity;
474 }
475 }
476 }
477 Some((left, right)) => {
478 stack.push(right);
479 stack.push(left);
480 }
481 }
482 }
483 }
484}
485
486#[derive(Clone, Copy, PartialEq, Eq)]
489enum ChordScan {
490 Auto,
492 Indexed,
494 Linear,
496}
497
498impl ChordScan {
499 fn indexes(self, chords: usize) -> bool {
501 match self {
502 ChordScan::Linear => false,
503 ChordScan::Indexed => true,
504 ChordScan::Auto => chords >= CHORD_INDEX_MIN_CHORDS,
505 }
506 }
507}
508
509fn in_index_range(point: Vec2) -> bool {
512 point.x.abs() <= CHORD_INDEX_MAX_COORDINATE && point.y.abs() <= CHORD_INDEX_MAX_COORDINATE
513}
514
515fn linear_scan(
518 generic: &GenericPrep,
519 point: Vec2,
520 tolerance: f64,
521) -> (usize, bool, Option<(usize, usize, f64)>) {
522 let mut crossings = 0;
523 let mut boundary = false;
524 let mut nearest: Option<(usize, usize, f64)> = None;
527 let fused = fused_scan_enabled();
528 for (loop_index, (samples, chords)) in generic.loops.iter().zip(&generic.segments).enumerate() {
529 let polygon = &samples.polygon;
530 if fused {
531 let mut on_boundary = false;
534 for index in 0..polygon.len() {
535 let distance = point_segment_distance(point, polygon[index], polygon[(index + 1) % polygon.len()]);
536 if distance <= tolerance {
537 on_boundary = true;
538 }
539 if index < chords.len()
540 && nearest
541 .as_ref()
542 .is_none_or(|(_, _, nearest_distance)| distance < *nearest_distance)
543 {
544 nearest = Some((loop_index, index, distance));
545 }
546 }
547 if on_boundary {
548 boundary = true;
549 } else if polygon_parity_inside(point, polygon) {
550 crossings += 1;
551 }
552 continue;
553 }
554 match point_in_polygon(point, polygon, tolerance) {
555 PolygonClass::Boundary => boundary = true,
556 PolygonClass::Inside => crossings += 1,
557 PolygonClass::Outside => {}
558 }
559 for index in 0..chords.len() {
560 let start = polygon[index];
561 let end = polygon[(index + 1) % polygon.len()];
562 let distance = point_segment_distance(point, start, end);
563 if nearest
564 .as_ref()
565 .is_none_or(|(_, _, nearest_distance)| distance < *nearest_distance)
566 {
567 nearest = Some((loop_index, index, distance));
568 }
569 }
570 }
571 (crossings, boundary, nearest)
572}
573
574fn fused_scan_enabled() -> bool {
581 switch!("BREP_CONTAINMENT_FUSED_SCAN", true)
582}
583
584
585fn generic_scan(
589 generic: &GenericPrep,
590 point: Vec2,
591 tolerance: f64,
592 scan: ChordScan,
593) -> (usize, bool, Option<(usize, usize, f64)>) {
594 if scan.indexes(generic.chord_count) && in_index_range(point) {
595 if let Some(index) = generic.index.get_or_init(|| {
596 let started = containment_profile_started();
597 let built = ChordIndex::build(generic.loops.as_slice());
598 let ms = containment_elapsed_ms(started);
599 containment_profile(|p| {
600 p.index_builds += 1;
601 p.index_ms += ms;
602 });
603 built
604 }) {
605 let loops = generic.loops.as_slice();
606 let nearest = index.nearest(loops, point);
607 let boundary = nearest.is_some_and(|(_, _, distance)| distance <= tolerance);
608 let crossings = if boundary {
609 0
610 } else {
611 let mut odd = vec![false; loops.len()];
612 index.flip_crossings(loops, point, &mut odd);
613 odd.into_iter().filter(|&parity| parity).count()
614 };
615 return (crossings, boundary, nearest);
616 }
617 }
618 linear_scan(generic, point, tolerance)
619}
620
621pub struct PreparedFace {
628 seam_band: std::cell::OnceCell<Result<SeamBandPrep, String>>,
629 sphere_cap: std::cell::OnceCell<Result<Option<SphereCapPrep>, String>>,
630 horizon: std::cell::OnceCell<Result<Option<HorizonPrep>, String>>,
631 rim_strip: std::cell::OnceCell<Result<Option<RimStripPrep>, String>>,
632 generic: std::cell::OnceCell<Result<GenericPrep, String>>,
633 sphere_region: std::cell::OnceCell<Result<crate::sphere_chart::SphericalRegion, String>>,
635 sphere_region_reduced: std::cell::OnceCell<Result<Option<(crate::sphere_chart::SphericalRegion, f64)>, String>>,
639 loop_samples: std::cell::RefCell<Vec<Option<Result<std::rc::Rc<Vec<Vec2>>, String>>>>,
644}
645
646impl PreparedFace {
647 fn new() -> Self {
648 Self {
649 seam_band: std::cell::OnceCell::new(),
650 sphere_cap: std::cell::OnceCell::new(),
651 horizon: std::cell::OnceCell::new(),
652 rim_strip: std::cell::OnceCell::new(),
653 generic: std::cell::OnceCell::new(),
654 sphere_region: std::cell::OnceCell::new(),
655 sphere_region_reduced: std::cell::OnceCell::new(),
656 loop_samples: std::cell::RefCell::new(Vec::new()),
657 }
658 }
659}
660
661fn loop_samples(prepared: &PreparedFace, face: &FaceRecord, loop_index: usize) -> Result<std::rc::Rc<Vec<Vec2>>, String> {
671 if let Some(Some(sampled)) = prepared.loop_samples.borrow().get(loop_index) {
672 return sampled.clone();
673 }
674 let sampled = (|| {
675 let mut points: Vec<Vec2> = Vec::new();
676 for coedge in &face.loops[loop_index].coedges {
677 let curve = &coedge.pcurve;
678 let [start, end] = curve.domain()?;
679 let sample_count = trim_sample_count(curve);
680 for index in 0..sample_count {
681 let parameter = trim_station(start, end, index, sample_count);
682 let evaluated = curve.evaluate(parameter)?;
683 points.push(Vec2 {
684 x: evaluated.x,
685 y: evaluated.y,
686 });
687 }
688 }
689 Ok(std::rc::Rc::new(points))
690 })();
691 let mut cells = prepared.loop_samples.borrow_mut();
692 if cells.len() < face.loops.len() {
693 cells.resize(face.loops.len(), None);
694 }
695 cells[loop_index] = Some(sampled.clone());
696 sampled
697}
698
699#[derive(Default, Clone, Copy)]
709struct ContainmentProfile {
710 enabled: bool,
711 cache_misses: u64,
712 seam_band_preps: u64,
713 seam_band_ms: f64,
714 sphere_cap_preps: u64,
715 sphere_cap_ms: f64,
716 horizon_preps: u64,
717 horizon_ms: f64,
718 rim_strip_preps: u64,
719 rim_strip_ms: f64,
720 generic_preps: u64,
721 generic_ms: f64,
722 generic_chords: u64,
723 index_builds: u64,
724 index_ms: f64,
725 region_builds: u64,
726 region_evaluate_ms: f64,
727 region_canonical_ms: f64,
728 region_segments_ms: f64,
729}
730
731thread_local! {
732 static CONTAINMENT_PROFILE: std::cell::Cell<ContainmentProfile> =
733 const { std::cell::Cell::new(ContainmentProfile {
734 enabled: false, cache_misses: 0, seam_band_preps: 0, seam_band_ms: 0.0,
735 sphere_cap_preps: 0, sphere_cap_ms: 0.0, horizon_preps: 0, horizon_ms: 0.0,
736 rim_strip_preps: 0, rim_strip_ms: 0.0, generic_preps: 0, generic_ms: 0.0,
737 generic_chords: 0, index_builds: 0, index_ms: 0.0, region_builds: 0,
738 region_evaluate_ms: 0.0, region_canonical_ms: 0.0, region_segments_ms: 0.0,
739 }) };
740}
741
742impl crate::profile::Counters for ContainmentProfile {
743 fn armed(&self) -> bool {
744 self.enabled
745 }
746}
747
748fn containment_profile(update: impl FnOnce(&mut ContainmentProfile)) {
749 crate::profile::update(&CONTAINMENT_PROFILE, update)
750}
751
752fn containment_profile_started() -> Option<web_time::Instant> {
753 crate::profile::started(&CONTAINMENT_PROFILE)
754}
755
756use crate::profile::elapsed_ms as containment_elapsed_ms;
757
758pub fn containment_profile_begin() {
760 let enabled = crate::profile::profile_enabled();
761 CONTAINMENT_PROFILE.with(|cell| {
762 cell.set(ContainmentProfile {
763 enabled,
764 ..ContainmentProfile::default()
765 })
766 });
767}
768
769pub fn containment_profile_report(label: &str) {
772 let p = CONTAINMENT_PROFILE.with(|cell| cell.get());
773 if !p.enabled {
774 return;
775 }
776 profile_line!(
777 "containment.profile {label} cache_misses={} seam_band: preps={} ms={:.2} sphere_cap: preps={} ms={:.2} horizon: preps={} ms={:.2} rim_strip: preps={} ms={:.2} generic: preps={} ms={:.2} chords={} index: builds={} ms={:.2} region: builds={} evaluate_ms={:.2} canonical_ms={:.2} segments_ms={:.2}",
778 p.cache_misses, p.seam_band_preps, p.seam_band_ms, p.sphere_cap_preps, p.sphere_cap_ms,
779 p.horizon_preps, p.horizon_ms, p.rim_strip_preps, p.rim_strip_ms, p.generic_preps,
780 p.generic_ms, p.generic_chords, p.index_builds, p.index_ms, p.region_builds,
781 p.region_evaluate_ms, p.region_canonical_ms, p.region_segments_ms,
782 );
783 CONTAINMENT_PROFILE.with(|cell| cell.set(ContainmentProfile::default()));
784}
785
786fn timed_lane<'a, T>(
789 cell: &'a std::cell::OnceCell<Result<T, String>>,
790 build: impl FnOnce() -> Result<T, String>,
791 record: fn(&mut ContainmentProfile, f64),
792) -> Result<&'a T, String> {
793 lane(cell, || {
794 let started = containment_profile_started();
795 let built = build();
796 let ms = containment_elapsed_ms(started);
797 containment_profile(|p| record(p, ms));
798 built
799 })
800}
801
802fn lane<'a, T>(
803 cell: &'a std::cell::OnceCell<Result<T, String>>,
804 build: impl FnOnce() -> Result<T, String>,
805) -> Result<&'a T, String> {
806 match cell.get_or_init(build) {
807 Ok(value) => Ok(value),
808 Err(error) => Err(error.clone()),
809 }
810}
811
812pub struct PreparedFaceCache {
830 entries: Vec<(u64, Vec<f64>, std::rc::Rc<PreparedFace>)>,
831}
832
833const PREPARED_FACE_CACHE_ENTRIES: usize = 64;
834
835thread_local! {
836 static PREPARED_FACES: std::cell::RefCell<PreparedFaceCache> = const {
837 std::cell::RefCell::new(PreparedFaceCache {
838 entries: Vec::new(),
839 })
840 };
841}
842
843fn coedge_slots(face: &FaceRecord) -> Vec<usize> {
857 let ids: Vec<u64> = face.loops.iter().flat_map(|record| record.coedges.iter().map(|coedge| coedge.edge_id)).collect();
858 ids.iter().enumerate().map(|(at, id)| ids[..at].iter().position(|earlier| earlier == id).unwrap_or(at)).collect()
859}
860
861fn walk_face_signature<F: FnMut(f64) -> bool>(face: &FaceRecord, switches: f64, visit: &mut F) -> bool {
862 let slots = coedge_slots(face);
863 let mut flat = 0usize;
864 let surface = &face.surface;
865 let point = |visit: &mut F, p: &crate::Vec4| visit(p.x) && visit(p.y) && visit(p.z) && visit(p.w);
866 if !(visit(switches)
867 && visit(if face.same_sense { 1.0 } else { 0.0 })
868 && visit(surface.degree_u as f64)
869 && visit(surface.degree_v as f64)
870 && visit(surface.knots_u.len() as f64))
871 {
872 return false;
873 }
874 if !(surface.knots_u.iter().all(|&knot| visit(knot)) && visit(surface.knots_v.len() as f64)) {
875 return false;
876 }
877 if !(surface.knots_v.iter().all(|&knot| visit(knot)) && visit(surface.control_points.len() as f64)) {
878 return false;
879 }
880 for row in &surface.control_points {
881 if !(visit(row.len() as f64) && row.iter().all(|p| point(visit, p))) {
882 return false;
883 }
884 }
885 if !visit(face.loops.len() as f64) {
886 return false;
887 }
888 for loop_record in &face.loops {
889 if !visit(loop_record.coedges.len() as f64) {
890 return false;
891 }
892 for coedge in &loop_record.coedges {
893 let curve = &coedge.pcurve;
894 let slot = slots[flat];
895 flat += 1;
896 if !(visit(slot as f64)
897 && visit(if coedge.forward { 1.0 } else { 0.0 })
898 && visit(curve.degree as f64)
899 && visit(curve.knots.len() as f64))
900 {
901 return false;
902 }
903 if !(curve.knots.iter().all(|&knot| visit(knot)) && visit(curve.control_points.len() as f64)) {
904 return false;
905 }
906 if !curve.control_points.iter().all(|p| point(visit, p)) {
907 return false;
908 }
909 }
910 }
911 true
912}
913
914fn face_key_hash(face: &FaceRecord, switches: f64) -> u64 {
919 use std::hash::Hasher;
920 let slots = coedge_slots(face);
921 let mut flat = 0usize;
922 let mut hasher = rustc_hash::FxHasher::default();
923 let mut write = |value: f64| hasher.write_u64(value.to_bits());
924 let surface = &face.surface;
925 write(switches);
926 write(if face.same_sense { 1.0 } else { 0.0 });
927 write(surface.degree_u as f64);
928 write(surface.degree_v as f64);
929 write(surface.knots_u.len() as f64);
930 write(surface.knots_v.len() as f64);
931 write(surface.control_points.len() as f64);
932 let corners = [surface.control_points.first().and_then(|row| row.first()), surface.control_points.last().and_then(|row| row.last())];
933 for p in corners.into_iter().flatten() {
934 [p.x, p.y, p.z, p.w].into_iter().for_each(&mut write);
935 }
936 write(face.loops.len() as f64);
937 for loop_record in &face.loops {
938 write(loop_record.coedges.len() as f64);
939 for coedge in &loop_record.coedges {
940 let curve = &coedge.pcurve;
941 write(slots[flat] as f64);
942 flat += 1;
943 write(if coedge.forward { 1.0 } else { 0.0 });
944 write(curve.degree as f64);
945 write(curve.knots.len() as f64);
946 write(curve.control_points.len() as f64);
947 for knot in [curve.knots.first(), curve.knots.last()].into_iter().flatten() {
948 write(*knot);
949 }
950 for p in [curve.control_points.first(), curve.control_points.last()].into_iter().flatten() {
951 [p.x, p.y, p.z, p.w].into_iter().for_each(&mut write);
952 }
953 }
954 }
955 hasher.finish()
956}
957
958fn cached_entry(
960 entries: &[(u64, Vec<f64>, std::rc::Rc<PreparedFace>)],
961 face: &FaceRecord,
962 switches: f64,
963 hash: u64,
964) -> Option<usize> {
965 entries.iter().position(|(entry_hash, signature, _)| {
966 if *entry_hash != hash {
967 return false;
968 }
969 let mut at = 0;
970 let walked = walk_face_signature(face, switches, &mut |value: f64| {
971 let same = signature
972 .get(at)
973 .is_some_and(|stored| stored.to_bits() == value.to_bits() && !value.is_nan());
974 at += 1;
975 same
976 });
977 walked && at == signature.len()
978 })
979}
980
981pub fn forget_prepared_faces() {
984 PREPARED_FACES.with(|cache| cache.borrow_mut().entries.clear());
985}
986
987
988fn cached_prepared_face(face: &FaceRecord) -> Option<std::rc::Rc<PreparedFace>> {
992 PREPARED_FACES.with(|cache| {
993 let PreparedFaceCache { entries } = &*cache.borrow();
994 let switches = lane_switches();
995 let hash = face_key_hash(face, switches);
996 cached_entry(entries, face, switches, hash).map(|index| entries[index].2.clone())
997 })
998}
999
1000pub fn prepared_face(face: &FaceRecord) -> std::rc::Rc<PreparedFace> {
1001 PREPARED_FACES.with(|cache| {
1002 let PreparedFaceCache { entries } = &mut *cache.borrow_mut();
1003 let switches = lane_switches();
1004 let hash = face_key_hash(face, switches);
1005 if let Some(index) = cached_entry(entries, face, switches, hash) {
1006 if index != 0 {
1007 let entry = entries.remove(index);
1008 entries.insert(0, entry);
1009 }
1010 return entries[0].2.clone();
1011 }
1012 let mut signature = Vec::new();
1013 walk_face_signature(face, switches, &mut |value: f64| {
1014 signature.push(value);
1015 true
1016 });
1017 let prepared = std::rc::Rc::new(PreparedFace::new());
1018 entries.insert(0, (hash, signature, prepared.clone()));
1019 entries.truncate(PREPARED_FACE_CACHE_ENTRIES);
1020 containment_profile(|p| p.cache_misses += 1);
1021 prepared
1022 })
1023}
1024
1025fn prepare_seam_band(face: &FaceRecord) -> Result<SeamBandPrep, String> {
1034 if face.surface.closed_directions()? != (true, true) {
1035 return Ok(SeamBandPrep::NotApplicable);
1036 }
1037 let [u0, u1] = face.surface.domain_u()?;
1038 let [v0, v1] = face.surface.domain_v()?;
1039 if crate::topology::doubly_periodic_has_only_collapsed_loops(face)? {
1040 return Ok(SeamBandPrep::AlwaysInside);
1041 }
1042 let u_span = (u1 - u0).abs().max(1e-30);
1043 let v_span = (v1 - v0).abs().max(1e-30);
1044 let mut loops_uv: Vec<Vec<[f64; 2]>> = Vec::with_capacity(face.loops.len());
1045 let mut retained: Vec<usize> = Vec::with_capacity(face.loops.len());
1049 for (loop_index, loop_record) in face.loops.iter().enumerate() {
1050 let mut points: Vec<[f64; 2]> = Vec::new();
1051 for coedge in &loop_record.coedges {
1052 let [d0, d1] = coedge.pcurve.domain()?;
1053 let samples = 24;
1054 for k in 0..=samples {
1055 let t = trim_station(d0, d1, k, samples);
1056 let p = coedge.pcurve.evaluate(t)?;
1057 points.push([p.x, p.y]);
1058 }
1059 }
1060 let (mut umin, mut umax, mut vmin, mut vmax) = (
1061 f64::INFINITY,
1062 f64::NEG_INFINITY,
1063 f64::INFINITY,
1064 f64::NEG_INFINITY,
1065 );
1066 for p in &points {
1067 umin = umin.min(p[0]);
1068 umax = umax.max(p[0]);
1069 vmin = vmin.min(p[1]);
1070 vmax = vmax.max(p[1]);
1071 }
1072 if (umax - umin) <= 1e-3 * u_span && (vmax - vmin) <= 1e-3 * v_span {
1092 continue;
1093 }
1094 retained.push(loop_index);
1095 loops_uv.push(points);
1096 }
1097 if loops_uv.len() == 1 && switch!(SEAM_BAND_MERGED_SWITCH, true) {
1108 let coedges = &face.loops[retained[0]].coedges;
1109 let offsets = crate::topology::loop_seam_offsets(coedges, true, true, u_span, v_span)?;
1110 if offsets.iter().any(|o| o[0] != 0.0 || o[1] != 0.0) {
1111 let mut polygon: Vec<Vec2> = Vec::new();
1112 for (coedge_index, coedge) in coedges.iter().enumerate() {
1113 let [d0, d1] = coedge.pcurve.domain()?;
1114 let samples = 24;
1115 for k in 0..samples {
1116 let t = trim_station(d0, d1, k, samples);
1117 let p = coedge.pcurve.evaluate(t)?;
1118 polygon.push(Vec2 {
1119 x: p.x + offsets[coedge_index][0],
1120 y: p.y + offsets[coedge_index][1],
1121 });
1122 }
1123 }
1124 return Ok(SeamBandPrep::Merged { polygon, u_span, v_span });
1125 }
1126 }
1127 if loops_uv.len() != 2 {
1128 return Ok(SeamBandPrep::Declined);
1129 }
1130 if let Some(band) = crate::topology::analyze_doubly_periodic_seam_band(
1131 &loops_uv,
1132 [u0, u1, v0, v1],
1133 face.same_sense,
1134 ) {
1135 let polygon: Vec<Vec2> =
1136 crate::topology::seam_band_uv_polygon(&loops_uv, [u0, u1, v0, v1], &band)
1137 .into_iter()
1138 .map(|p| Vec2 { x: p[0], y: p[1] })
1139 .collect();
1140 return Ok(SeamBandPrep::Analyzed { polygon });
1141 }
1142 for p_is_u in [true, false] {
1149 let (period, q_extent) = if p_is_u {
1150 (u1 - u0, v_span)
1151 } else {
1152 (v1 - v0, u_span)
1153 };
1154 if !(period > 0.0) {
1155 continue;
1156 }
1157 let coord = |p: &[f64; 2]| if p_is_u { (p[0], p[1]) } else { (p[1], p[0]) };
1158 let mut rings = Vec::with_capacity(2);
1159 for points in &loops_uv {
1160 let (mut pmin, mut pmax, mut qmin, mut qmax) = (
1161 f64::INFINITY,
1162 f64::NEG_INFINITY,
1163 f64::INFINITY,
1164 f64::NEG_INFINITY,
1165 );
1166 for p in points {
1167 let (periodic, cross) = coord(p);
1168 pmin = pmin.min(periodic);
1169 pmax = pmax.max(periodic);
1170 qmin = qmin.min(cross);
1171 qmax = qmax.max(cross);
1172 }
1173 if (pmax - pmin) < 0.6 * period || (qmax - qmin) > 0.05 * q_extent {
1174 rings.clear();
1175 break;
1176 }
1177 let mut net = 0.0;
1178 for pair in points.windows(2) {
1179 let mut delta = coord(&pair[1]).0 - coord(&pair[0]).0;
1180 if delta > 0.5 * period {
1181 delta -= period;
1182 } else if delta < -0.5 * period {
1183 delta += period;
1184 }
1185 net += delta;
1186 }
1187 let direction = if net > 0.25 * period {
1188 1
1189 } else if net < -0.25 * period {
1190 -1
1191 } else {
1192 0
1193 };
1194 rings.push((0.5 * (qmin + qmax), direction));
1195 }
1196 if rings.len() != 2 {
1197 continue;
1198 }
1199 rings.sort_by(|a, b| a.0.total_cmp(&b.0));
1200 let [(q_lo, lower_direction), (q_hi, upper_direction)] = rings.as_slice() else {
1201 unreachable!()
1202 };
1203 let inconclusive =
1204 *lower_direction == 0 || *upper_direction == 0 || lower_direction == upper_direction;
1205 let between_is_ccw_uv = if p_is_u {
1206 *lower_direction > 0
1207 } else {
1208 *lower_direction < 0
1209 };
1210 let complement = !inconclusive && between_is_ccw_uv != face.same_sense;
1211 return Ok(SeamBandPrep::Rings {
1212 p_is_u,
1213 q_lo: *q_lo,
1214 q_hi: *q_hi,
1215 complement,
1216 });
1217 }
1218 Ok(SeamBandPrep::Declined)
1219}
1220
1221fn seam_band_point_in_face(
1222 prepared: &SeamBandPrep,
1223 point: Vec2,
1224 tolerance: f64,
1225) -> Option<PolygonClass> {
1226 match prepared {
1227 SeamBandPrep::NotApplicable | SeamBandPrep::Declined => None,
1228 SeamBandPrep::AlwaysInside => Some(PolygonClass::Inside),
1229 SeamBandPrep::Merged { polygon, u_span, v_span } => {
1230 let mut best = PolygonClass::Outside;
1231 'images: for du in [-1.0, 0.0, 1.0] {
1232 for dv in [-1.0, 0.0, 1.0] {
1233 let image = Vec2 {
1234 x: point.x + du * u_span,
1235 y: point.y + dv * v_span,
1236 };
1237 match point_in_polygon(image, polygon, tolerance) {
1238 PolygonClass::Boundary => {
1239 best = PolygonClass::Boundary;
1240 break 'images;
1241 }
1242 PolygonClass::Inside => best = PolygonClass::Inside,
1243 PolygonClass::Outside => {}
1244 }
1245 }
1246 }
1247 Some(best)
1248 }
1249 SeamBandPrep::Analyzed { polygon } => Some(point_in_polygon(point, polygon, tolerance)),
1250 SeamBandPrep::Rings { p_is_u, q_lo, q_hi, complement } => {
1251 let q = if *p_is_u { point.y } else { point.x };
1252 if (q - q_lo).abs() <= tolerance || (q - q_hi).abs() <= tolerance {
1253 return Some(PolygonClass::Boundary);
1254 }
1255 let between = q > *q_lo && q < *q_hi;
1256 Some(if between != *complement {
1257 PolygonClass::Inside
1258 } else {
1259 PolygonClass::Outside
1260 })
1261 }
1262 }
1263}
1264
1265fn prepare_wrapped_horizon(face: &FaceRecord, prepared: &PreparedFace) -> Result<Option<HorizonPrep>, String> {
1281 if face.surface.closed_directions()? != (true, false) || face.loops.is_empty() {
1282 return Ok(None);
1283 }
1284 if !switch!(HORIZON_CONTAINMENT_SWITCH, true) {
1285 return Ok(None);
1286 }
1287 if face.loops.len() <= 2 && !switch!(HORIZON_SINGLE_LOOP_SWITCH, true) {
1298 return Ok(None);
1299 }
1300 let [u0, u1] = face.surface.domain_u()?;
1301 let u_period = u1 - u0;
1302 if u_period <= 0.0 {
1303 return Ok(None);
1304 }
1305 let debug = std::env::var("BREP_DEBUG_HORIZON").is_ok();
1306 let mut loops: Vec<Vec<Vec2>> = Vec::new();
1307 let mut straddling = false;
1308 for loop_index in 0..face.loops.len() {
1309 let points = loop_samples(prepared, face, loop_index)?;
1310 if points.len() < 3 {
1311 continue;
1312 }
1313 let mut unwrapped = Vec::with_capacity(points.len());
1317 let mut jumps = 0usize;
1318 let mut cursor = points[0];
1319 unwrapped.push(cursor);
1320 for pair in points.windows(2) {
1321 let mut du = pair[1].x - pair[0].x;
1322 let folded = du - u_period * (du / u_period).round();
1323 if (du - folded).abs() > 0.25 * u_period {
1324 jumps += 1;
1325 }
1326 du = folded;
1327 cursor = Vec2 {
1328 x: cursor.x + du,
1329 y: pair[1].y,
1330 };
1331 unwrapped.push(cursor);
1332 }
1333 let closure = (unwrapped[0].x - unwrapped[unwrapped.len() - 1].x).abs();
1334 if closure > 0.25 * u_period {
1335 if debug {
1336 eprintln!(
1337 "horizon: face {} loop winds the period (closure {closure:.3}) — bail",
1338 face.id
1339 );
1340 }
1341 return Ok(None); }
1343 if jumps > 0 {
1344 straddling = true;
1345 }
1346 loops.push(unwrapped);
1347 }
1348 if !straddling || loops.is_empty() {
1349 return Ok(None);
1350 }
1351 Ok(Some(HorizonPrep {
1352 loops,
1353 u_period,
1354 index: std::cell::OnceCell::new(),
1355 }))
1356}
1357
1358fn wrapped_horizon_point_in_face(
1359 face: &FaceRecord,
1360 prepared: &HorizonPrep,
1361 point: Vec2,
1362 tolerance: f64,
1363 scan: ChordScan,
1364) -> Option<PolygonClass> {
1365 let HorizonPrep { loops, u_period, index } = prepared;
1366 let u_period = *u_period;
1367 let debug = std::env::var("BREP_DEBUG_HORIZON").is_ok();
1368 if !horizon_cross_frame() {
1383 let mut best: Option<PolygonClass> = None;
1384 for shift in [-u_period, 0.0, u_period] {
1385 let image = Vec2 {
1386 x: point.x + shift,
1387 y: point.y,
1388 };
1389 let mut crossings = 0usize;
1390 for polygon in loops {
1391 match point_in_polygon(image, polygon, tolerance) {
1392 PolygonClass::Boundary => return Some(PolygonClass::Boundary),
1393 PolygonClass::Inside => crossings += 1,
1394 PolygonClass::Outside => {}
1395 }
1396 }
1397 if crossings % 2 == 1 {
1398 best = Some(PolygonClass::Inside);
1399 } else if best.is_none() {
1400 best = Some(PolygonClass::Outside);
1401 }
1402 }
1403 if debug {
1404 eprintln!(
1405 "horizon: face {} loops={} straddling (legacy per-image) -> {:?}",
1406 face.id,
1407 loops.len(),
1408 best
1409 );
1410 }
1411 return best;
1412 }
1413 let images = [-u_period, 0.0, u_period].map(|shift| Vec2 {
1414 x: point.x + shift,
1415 y: point.y,
1416 });
1417 let chords: usize = loops.iter().map(Vec::len).sum();
1418 let indexed = (scan.indexes(chords) && images.iter().all(|image| in_index_range(*image)))
1419 .then(|| index.get_or_init(|| ChordIndex::build(loops.as_slice())).as_ref())
1420 .flatten();
1421 let mut crossings = 0usize;
1422 if let Some(index) = indexed {
1423 let loops = loops.as_slice();
1427 if images.iter().any(|image| index.any_within(loops, *image, tolerance)) {
1428 return Some(PolygonClass::Boundary);
1429 }
1430 let mut odd = vec![false; loops.len()];
1431 for image in images {
1432 index.flip_crossings(loops, image, &mut odd);
1433 }
1434 crossings = odd.into_iter().filter(|&parity| parity).count();
1435 } else {
1436 for polygon in loops {
1437 let mut image_hits = 0usize;
1438 for image in images {
1439 match point_in_polygon(image, polygon, tolerance) {
1440 PolygonClass::Boundary => return Some(PolygonClass::Boundary),
1441 PolygonClass::Inside => image_hits += 1,
1442 PolygonClass::Outside => {}
1443 }
1444 }
1445 crossings += image_hits % 2;
1446 }
1447 }
1448 let class = if crossings % 2 == 1 {
1449 PolygonClass::Inside
1450 } else {
1451 PolygonClass::Outside
1452 };
1453 if debug {
1454 eprintln!(
1455 "horizon: face {} loops={} straddling -> {:?}",
1456 face.id,
1457 loops.len(),
1458 class
1459 );
1460 }
1461 Some(class)
1462}
1463
1464fn prepare_winding_sphere_cap(face: &FaceRecord, prepared: &PreparedFace) -> Result<Option<SphereCapPrep>, String> {
1469 if !matches!(
1470 face.surface.analytic(),
1471 Some(crate::AnalyticSurface::Sphere { .. })
1472 ) || face.surface.closed_directions()? != (true, false)
1473 || face.loops.len() != 2
1474 {
1475 return Ok(None);
1476 }
1477 let [u0, u1] = face.surface.domain_u()?;
1478 let [v0, v1] = face.surface.domain_v()?;
1479 let period = u1 - u0;
1480 let v_span = v1 - v0;
1481 if !(period > 0.0 && v_span > 0.0) {
1482 return Ok(None);
1483 }
1484 struct WindingLoop {
1485 points: Vec<Vec2>,
1486 winding: f64,
1487 vmin: f64,
1488 vmax: f64,
1489 }
1490 let mut loops = Vec::with_capacity(2);
1491 for loop_index in 0..face.loops.len() {
1492 let points = loop_samples(prepared, face, loop_index)?;
1493 if points.len() < 2 {
1494 return Ok(None);
1495 }
1496 let first = points[0];
1497 let mut cursor = first;
1498 let mut unwrapped = vec![cursor];
1499 for next in points.iter().skip(1) {
1500 let du = next.x - cursor.x;
1501 let folded = du - period * (du / period).round();
1502 cursor = Vec2 {
1503 x: cursor.x + folded,
1504 y: next.y,
1505 };
1506 unwrapped.push(cursor);
1507 }
1508 let last_raw = *points.last().unwrap();
1509 let closing_du = first.x - last_raw.x;
1510 let closing_folded = closing_du - period * (closing_du / period).round();
1511 let winding = cursor.x + closing_folded - first.x;
1512 let (mut vmin, mut vmax) = (f64::INFINITY, f64::NEG_INFINITY);
1513 for p in &unwrapped {
1514 vmin = vmin.min(p.y);
1515 vmax = vmax.max(p.y);
1516 }
1517 loops.push(WindingLoop {
1518 points: unwrapped,
1519 winding,
1520 vmin,
1521 vmax,
1522 });
1523 }
1524 if loops
1525 .iter()
1526 .any(|loop_data| (loop_data.winding.abs() - period).abs() > 0.05 * period)
1527 || loops[0].winding * loops[1].winding >= 0.0
1528 {
1529 return Ok(None);
1530 }
1531 let flat = |loop_data: &WindingLoop| loop_data.vmax - loop_data.vmin <= 1e-6 * v_span;
1532 let (pole, rim) = match (flat(&loops[0]), flat(&loops[1])) {
1533 (true, false) => (&loops[0], &loops[1]),
1534 (false, true) => (&loops[1], &loops[0]),
1535 _ => return Ok(None),
1536 };
1537 let pole_v = 0.5 * (pole.vmin + pole.vmax);
1538 if (pole_v - v0).abs() > 1e-6 * v_span && (pole_v - v1).abs() > 1e-6 * v_span {
1539 return Ok(None);
1540 }
1541 Ok(Some(SphereCapPrep {
1542 rim: rim.points.clone(),
1543 pole_v,
1544 period,
1545 }))
1546}
1547
1548fn winding_sphere_cap_point_in_face(
1549 prepared: &SphereCapPrep,
1550 point: Vec2,
1551 tolerance: f64,
1552) -> Option<PolygonClass> {
1553 let SphereCapPrep { rim, pole_v, period } = prepared;
1554 let (pole_v, period) = (*pole_v, *period);
1555 let window_start = rim[0].x.min(rim[rim.len() - 1].x);
1556 let query_u = window_start + (point.x - window_start).rem_euclid(period);
1557 let mut crossings = Vec::new();
1558 for pair in rim.windows(2) {
1559 let (a, b) = (pair[0], pair[1]);
1560 if (a.x > query_u) != (b.x > query_u) {
1561 crossings.push(a.y + (query_u - a.x) / (b.x - a.x) * (b.y - a.y));
1562 }
1563 for image in [-period, 0.0, period] {
1564 if point_segment_distance(
1565 Vec2 {
1566 x: point.x + image,
1567 y: point.y,
1568 },
1569 a,
1570 b,
1571 ) <= tolerance
1572 {
1573 return Some(PolygonClass::Boundary);
1574 }
1575 }
1576 }
1577 let rim_v = crossings
1578 .into_iter()
1579 .min_by(|a, b| (a - point.y).abs().total_cmp(&(b - point.y).abs()))?;
1580 let inside = if pole_v < rim_v {
1581 point.y <= rim_v + tolerance
1582 } else {
1583 point.y >= rim_v - tolerance
1584 };
1585 Some(if inside {
1586 PolygonClass::Inside
1587 } else {
1588 PolygonClass::Outside
1589 })
1590}
1591
1592fn prepare_covering_rim_strip(face: &FaceRecord) -> Result<Option<RimStripPrep>, String> {
1624 if face.surface.closed_directions()? != (true, false) || face.loops.len() != 2 {
1625 return Ok(None);
1626 }
1627 if !switch!(COVERING_RIM_STRIP_SWITCH, true) {
1628 return Ok(None);
1629 }
1630 let [u0, u1] = face.surface.domain_u()?;
1631 let [v0, v1] = face.surface.domain_v()?;
1632 let period = u1 - u0;
1633 if !(period > 0.0) {
1634 return Ok(None);
1635 }
1636 let v_span = (v1 - v0).abs().max(1e-30);
1637 struct Rim {
1638 points: Vec<Vec2>,
1639 vmin: f64,
1640 vmax: f64,
1641 ascending: bool,
1642 }
1643 let mut rims: Vec<Rim> = Vec::with_capacity(2);
1644 let mut out_of_domain = false;
1645 for loop_record in &face.loops {
1646 let mut points: Vec<Vec2> = Vec::new();
1647 for coedge in &loop_record.coedges {
1648 let curve = &coedge.pcurve;
1649 let [start, end] = curve.domain()?;
1650 let sample_count = trim_sample_count(curve);
1651 for index in 0..=sample_count {
1652 let parameter = trim_station(start, end, index, sample_count);
1653 let evaluated = curve.evaluate(parameter)?;
1654 points.push(Vec2 {
1655 x: evaluated.x,
1656 y: evaluated.y,
1657 });
1658 }
1659 }
1660 if points.len() < 3 {
1661 return Ok(None);
1662 }
1663 for p in &points {
1666 if p.x < u0 - 1e-3 * period || p.x > u1 + 1e-3 * period {
1667 out_of_domain = true;
1668 }
1669 }
1670 let mut unwrapped: Vec<Vec2> = Vec::with_capacity(points.len());
1674 let mut cursor = points[0];
1675 unwrapped.push(cursor);
1676 for pair in points.windows(2) {
1677 let du = pair[1].x - pair[0].x;
1678 let folded = du - period * (du / period).round();
1679 cursor = Vec2 {
1680 x: cursor.x + folded,
1681 y: pair[1].y,
1682 };
1683 unwrapped.push(cursor);
1684 }
1685 let net = unwrapped[unwrapped.len() - 1].x - unwrapped[0].x;
1686 if (net.abs() - period).abs() > 2e-2 * period {
1687 return Ok(None); }
1689 if (unwrapped[unwrapped.len() - 1].y - unwrapped[0].y).abs() > 1e-3 * v_span {
1690 return Ok(None); }
1692 let (mut vmin, mut vmax) = (f64::INFINITY, f64::NEG_INFINITY);
1693 for p in &unwrapped {
1694 vmin = vmin.min(p.y);
1695 vmax = vmax.max(p.y);
1696 }
1697 rims.push(Rim {
1698 points: unwrapped,
1699 vmin,
1700 vmax,
1701 ascending: net > 0.0,
1702 });
1703 }
1704 if !out_of_domain {
1705 return Ok(None);
1706 }
1707 if rims[0].ascending == rims[1].ascending {
1708 return Ok(None); }
1710 let (lower, upper) = if rims[0].vmax <= rims[1].vmin {
1711 (&rims[0], &rims[1])
1712 } else if rims[1].vmax <= rims[0].vmin {
1713 (&rims[1], &rims[0])
1714 } else {
1715 return Ok(None); };
1717 if upper.vmin - lower.vmax <= 1e-6 * v_span {
1718 return Ok(None);
1719 }
1720 if (lower.ascending) != face.same_sense {
1725 return Ok(None);
1726 }
1727 Ok(Some(RimStripPrep {
1728 lower: lower.points.clone(),
1729 upper: upper.points.clone(),
1730 period,
1731 }))
1732}
1733
1734fn covering_rim_strip_point_in_face(
1735 prepared: &RimStripPrep,
1736 point: Vec2,
1737 tolerance: f64,
1738) -> Option<PolygonClass> {
1739 let RimStripPrep { lower, upper, period } = prepared;
1740 let period = *period;
1741 for rim in [lower, upper] {
1743 for shift in [-period, 0.0, period] {
1744 let image = Vec2 {
1745 x: point.x + shift,
1746 y: point.y,
1747 };
1748 for pair in rim.windows(2) {
1749 if point_segment_distance(image, pair[0], pair[1]) <= tolerance {
1750 return Some(PolygonClass::Boundary);
1751 }
1752 }
1753 }
1754 }
1755 let mut crossings = 0usize;
1758 for rim in [lower, upper] {
1759 let window_base = rim[0].x.min(rim[rim.len() - 1].x);
1760 let x = window_base + (point.x - window_base).rem_euclid(period);
1761 for pair in rim.windows(2) {
1762 let (a, b) = (pair[0], pair[1]);
1763 if (a.x > x) != (b.x > x) {
1764 let v_cross = a.y + (x - a.x) / (b.x - a.x) * (b.y - a.y);
1765 if v_cross > point.y {
1766 crossings += 1;
1767 }
1768 }
1769 }
1770 }
1771 Some(if crossings % 2 == 1 {
1772 PolygonClass::Inside
1773 } else {
1774 PolygonClass::Outside
1775 })
1776}
1777
1778pub fn prepare_generic(face: &FaceRecord, prepared: &PreparedFace) -> Result<GenericPrep, String> {
1782 let slots = coedge_slots(face);
1783 let mut flat = 0usize;
1784 let mut loops: Vec<LoopSamples> = Vec::with_capacity(face.loops.len());
1785 let mut segments: Vec<Vec<SegmentPrep>> = Vec::with_capacity(face.loops.len());
1786 let mut chord_count = 0;
1787 for (loop_index, loop_record) in face.loops.iter().enumerate() {
1788 let polygon = loop_samples(prepared, face, loop_index)?;
1789 let mut chords = Vec::with_capacity(polygon.len());
1790 let mut coedges = Vec::with_capacity(loop_record.coedges.len());
1791 let mut first = 0;
1792 for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
1793 let curve = &coedge.pcurve;
1794 let [start, end] = curve.domain()?;
1795 let sample_count = trim_sample_count(curve);
1796 for index in 0..sample_count {
1797 let parameter = trim_station(start, end, index, sample_count);
1798 let parameter_end = if index + 1 < sample_count {
1799 trim_station(start, end, index + 1, sample_count)
1800 } else {
1801 end
1802 };
1803 chords.push(SegmentPrep {
1804 coedge_index,
1805 parameter_start: parameter,
1806 parameter_end,
1807 });
1808 }
1809 coedges.push((slots[flat] as u64, first, sample_count));
1810 flat += 1;
1811 first += sample_count;
1812 }
1813 debug_assert_eq!(first, polygon.len());
1814 chord_count += chords.len();
1815 loops.push(LoopSamples { polygon, coedges });
1816 segments.push(chords);
1817 }
1818 containment_profile(|p| p.generic_chords += chord_count as u64);
1819 Ok(GenericPrep {
1820 loops,
1821 segments,
1822 chord_count,
1823 index: std::cell::OnceCell::new(),
1824 })
1825}
1826
1827pub struct LoopSamples {
1832 polygon: std::rc::Rc<Vec<Vec2>>,
1833 coedges: Vec<(u64, usize, usize)>,
1834}
1835
1836fn sphere_chart_point_in_face(
1861 face: &FaceRecord,
1862 point: Vec2,
1863 prepared: &PreparedFace,
1864 sampled: &[LoopSamples],
1865) -> Result<Option<PolygonClass>, String> {
1866 let Some(atlas) = sphere_chart_atlas(face) else {
1867 return Ok(None);
1868 };
1869 if sphere_region_reduced_enabled() {
1870 let reduced = lane(&prepared.sphere_region_reduced, || build_sphere_region_reduced(face, &atlas, sampled))?;
1871 if let Some((region, margin)) = reduced {
1872 if !region.is_whole_sphere() && region.is_decidable() {
1873 let probe = face.surface.evaluate(point.x, point.y)?;
1874 if region.clear_of_boundary(atlas.centre, probe, *margin) {
1875 return Ok(Some(if region.contains(atlas.centre, probe) {
1876 PolygonClass::Inside
1877 } else {
1878 PolygonClass::Outside
1879 }));
1880 }
1881 }
1882 }
1883 }
1884 let region = lane(&prepared.sphere_region, || build_sphere_region(face, &atlas, sampled))?;
1885 if region.is_whole_sphere() {
1886 return Ok(Some(PolygonClass::Inside));
1887 }
1888 if !region.is_decidable() {
1889 return Ok(None);
1892 }
1893 let probe = face.surface.evaluate(point.x, point.y)?;
1894 Ok(Some(if region.contains(atlas.centre, probe) {
1895 PolygonClass::Inside
1896 } else {
1897 PolygonClass::Outside
1898 }))
1899}
1900
1901fn sphere_region_reduced_enabled() -> bool {
1904 crate::switch!("BREP_SPHERE_REGION_REDUCED", true)
1905}
1906
1907const REDUCED_REGION_SAMPLES: usize = 4096;
1909
1910pub fn build_sphere_region_reduced(
1928 face: &FaceRecord,
1929 atlas: &crate::sphere_chart::SphereAtlas,
1930 sampled: &[LoopSamples],
1931) -> Result<Option<(crate::sphere_chart::SphericalRegion, f64)>, String> {
1932 let total: usize = sampled.iter().map(|samples| samples.polygon.len()).sum();
1933 if total < REDUCED_REGION_SAMPLES {
1934 return Ok(None);
1935 }
1936 let mut uses: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();
1937 for slot in coedge_slots(face) {
1938 *uses.entry(slot as u64).or_insert(0) += 1;
1939 }
1940 let outward_face_normal = face.same_sense == atlas.parameterization_is_outward(&face.surface)?;
1941 let memo = sphere_reduction_memo_enabled();
1942 let carrier = memo.then(|| {
1943 let mut lane = crate::mass_properties::TwoLane::new();
1944 crate::mass_properties::hash_surface(&mut lane, &face.surface);
1945 lane.finish()
1946 });
1947 let mut points: Vec<Vec3> = Vec::new();
1948 let mut spans: Vec<(usize, usize)> = Vec::new();
1949 let mut deviation = 0.0f64;
1950 for samples in sampled {
1951 let count = samples.polygon.len();
1952 if count < 2 {
1953 continue;
1954 }
1955 for &(edge_id, first, span) in &samples.coedges {
1956 if span == 0 || uses.get(&edge_id).copied().unwrap_or(0) >= 2 {
1957 continue;
1958 }
1959 let key = carrier.map(|carrier| {
1960 let mut lane = crate::mass_properties::TwoLane::new();
1961 lane.u64(carrier[0]);
1962 lane.u64(carrier[1]);
1963 lane.usize(span);
1964 for offset in 0..=span {
1965 let uv = samples.polygon[(first + offset) % count];
1966 lane.f64(uv.x);
1967 lane.f64(uv.y);
1968 }
1969 lane.finish()
1970 });
1971 if let Some(served) = key.and_then(|key| SPHERE_REDUCTIONS.with(|memo| memo.borrow().get(&key).cloned())) {
1972 let Some((kept, kept_deviation)) = served else {
1973 return Ok(None);
1974 };
1975 deviation = deviation.max(kept_deviation);
1976 let start = points.len();
1977 points.extend(kept.iter().copied());
1978 spans.push((start, points.len()));
1979 continue;
1980 }
1981 let reduced = reduce_sphere_coedge(face, atlas, &samples.polygon, first, span)?;
1982 if let Some(key) = key {
1983 SPHERE_REDUCTIONS.with(|memo| {
1984 let mut memo = memo.borrow_mut();
1985 if memo.len() >= SPHERE_REDUCTION_ENTRIES {
1986 memo.clear();
1987 }
1988 memo.insert(key, reduced.clone());
1989 });
1990 }
1991 let Some((kept, kept_deviation)) = reduced else {
1992 return Ok(None);
1993 };
1994 deviation = deviation.max(kept_deviation);
1995 let start = points.len();
1996 points.extend(kept.iter().copied());
1997 spans.push((start, points.len()));
1998 }
1999 }
2000 if 2 * points.len() > total {
2001 return Ok(None);
2002 }
2003 crate::sphere_chart::canonicalize_points(&mut points, 1e-9);
2004 let mut boundary: Vec<(Vec3, Vec3)> = Vec::new();
2005 for (first, last) in spans {
2006 for index in first..last.saturating_sub(1) {
2007 boundary.push((points[index], points[index + 1]));
2008 }
2009 }
2010 let region = crate::sphere_chart::SphericalRegion::from_segments(atlas.centre, &boundary, outward_face_normal);
2011 let rounding = 4e-9 / atlas.radius.max(f64::MIN_POSITIVE);
2012 Ok(Some((region, 2.0 * deviation + rounding)))
2013}
2014
2015fn reduce_sphere_coedge(
2021 face: &FaceRecord,
2022 atlas: &crate::sphere_chart::SphereAtlas,
2023 polygon: &[Vec2],
2024 first: usize,
2025 span: usize,
2026) -> Result<Option<(std::rc::Rc<Vec<Vec3>>, f64)>, String> {
2027 use crate::sphere_chart::{arc_distance, arc_normal};
2028 let count = polygon.len();
2029 let mut along: Vec<Vec3> = Vec::with_capacity(span + 1);
2030 for offset in 0..=span {
2031 let uv = polygon[(first + offset) % count];
2032 along.push(face.surface.evaluate(uv.x, uv.y)?);
2033 }
2034 let Ok(units) = along.iter().map(|p| p.sub(atlas.centre).normalized()).collect::<Result<Vec<_>, _>>() else {
2035 return Ok(None);
2036 };
2037 let last = along.len() - 1;
2038 let mut chords: Vec<f64> = units.windows(2).map(|pair| pair[0].sub(pair[1]).length()).collect();
2039 chords.sort_by(f64::total_cmp);
2040 let target = 0.1 * chords[chords.len() / 2];
2041 let mut kept: Vec<usize> = (0..=last).collect();
2042 let mut kept_deviation = 0.0f64;
2043 for stride in [32usize, 16, 8, 4, 2] {
2044 if last < 2 * stride {
2045 continue;
2046 }
2047 let indices: Vec<usize> = (0..=last).filter(|&i| i.min(last - i) % stride == 0).collect();
2048 let mut worst = 0.0f64;
2049 for pair in indices.windows(2) {
2050 let (a, b) = (units[pair[0]], units[pair[1]]);
2051 let normal = arc_normal(a, b);
2052 for j in pair[0] + 1..pair[1] {
2053 worst = worst.max(arc_distance(a, b, normal, units[j]));
2054 }
2055 }
2056 if worst <= target {
2057 kept = indices;
2058 kept_deviation = worst;
2059 break;
2060 }
2061 }
2062 Ok(Some((std::rc::Rc::new(kept.iter().map(|&i| along[i]).collect()), kept_deviation)))
2063}
2064
2065fn sphere_reduction_memo_enabled() -> bool {
2072 let enabled = crate::switch!("BREP_SPHERE_REDUCTION_MEMO", true);
2073 enabled
2074}
2075
2076
2077const SPHERE_REDUCTION_ENTRIES: usize = 4096;
2079
2080thread_local! {
2081 pub static SPHERE_REDUCTIONS: std::cell::RefCell<std::collections::HashMap<[u64; 2], Option<(std::rc::Rc<Vec<Vec3>>, f64)>>> =
2085 std::cell::RefCell::new(std::collections::HashMap::new());
2086}
2087
2088fn build_sphere_region(
2106 face: &FaceRecord,
2107 atlas: &crate::sphere_chart::SphereAtlas,
2108 sampled: &[LoopSamples],
2109) -> Result<crate::sphere_chart::SphericalRegion, String> {
2110 let mut uses: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();
2114 for slot in coedge_slots(face) {
2115 *uses.entry(slot as u64).or_insert(0) += 1;
2116 }
2117 let outward_face_normal =
2142 face.same_sense == atlas.parameterization_is_outward(&face.surface)?;
2143 let evaluate_started = containment_profile_started();
2144 let mut points: Vec<Vec3> = Vec::new();
2145 let mut spans: Vec<(usize, usize)> = Vec::new();
2146 for samples in sampled {
2147 let count = samples.polygon.len();
2148 if count < 2 {
2149 continue;
2150 }
2151 for &(edge_id, first, span) in &samples.coedges {
2152 if span == 0 || uses.get(&edge_id).copied().unwrap_or(0) >= 2 {
2153 continue;
2154 }
2155 let start = points.len();
2159 for offset in 0..=span {
2160 let uv = samples.polygon[(first + offset) % count];
2161 points.push(face.surface.evaluate(uv.x, uv.y)?);
2162 }
2163 spans.push((start, points.len()));
2164 }
2165 }
2166 let evaluate_ms = containment_elapsed_ms(evaluate_started);
2171 let canonical_started = containment_profile_started();
2172 crate::sphere_chart::canonicalize_points(&mut points, 1e-9);
2173 let canonical_ms = containment_elapsed_ms(canonical_started);
2174 let segments_started = containment_profile_started();
2175 let mut boundary: Vec<(Vec3, Vec3)> = Vec::new();
2176 for (first, last) in spans {
2177 for index in first..last.saturating_sub(1) {
2178 boundary.push((points[index], points[index + 1]));
2179 }
2180 }
2181 let region = crate::sphere_chart::SphericalRegion::from_segments(
2182 atlas.centre,
2183 &boundary,
2184 outward_face_normal,
2185 );
2186 let segments_ms = containment_elapsed_ms(segments_started);
2187 containment_profile(|p| {
2188 p.region_builds += 1;
2189 p.region_evaluate_ms += evaluate_ms;
2190 p.region_canonical_ms += canonical_ms;
2191 p.region_segments_ms += segments_ms;
2192 });
2193 Ok(region)
2194}
2195
2196
2197pub fn sphere_chart_atlas(face: &FaceRecord) -> Option<crate::sphere_chart::SphereAtlas> {
2200 if !sphere_chart_trim_enabled() {
2201 return None;
2202 }
2203 crate::sphere_chart::SphereAtlas::of_surface(&face.surface)
2204}
2205
2206fn containment_trace_enabled() -> bool {
2210 debug_flag!("BREP_DEBUG_CONTAINMENT")
2211}
2212
2213fn trace_lane(face: &FaceRecord, point: Vec2, lane: &str, class: PolygonClass) {
2218 if containment_trace_enabled() {
2219 eprintln!(
2220 "containment face={} uv=({:.8},{:.8}) lane={lane} -> {class:?}",
2221 face.id, point.x, point.y
2222 );
2223 }
2224}
2225
2226
2227enum Lane<'a> {
2229 SeamBand(&'a SeamBandPrep),
2230 SphereCap(&'a SphereCapPrep),
2231 Horizon(&'a HorizonPrep),
2232 RimStrip(&'a RimStripPrep),
2233 Generic,
2234}
2235
2236fn lane_from<'a>(
2244 face: &FaceRecord,
2245 prepared: &'a PreparedFace,
2246 from: usize,
2247) -> Result<(usize, Lane<'a>), String> {
2248 if from == 0 {
2249 let band = timed_lane(&prepared.seam_band, || prepare_seam_band(face), |p, ms| {
2250 p.seam_band_preps += 1;
2251 p.seam_band_ms += ms;
2252 })?;
2253 if !matches!(band, SeamBandPrep::NotApplicable | SeamBandPrep::Declined) {
2254 return Ok((0, Lane::SeamBand(band)));
2255 }
2256 }
2257 if from <= 1 {
2258 if let Some(cap) = timed_lane(&prepared.sphere_cap, || prepare_winding_sphere_cap(face, prepared), |p, ms| {
2259 p.sphere_cap_preps += 1;
2260 p.sphere_cap_ms += ms;
2261 })? {
2262 return Ok((1, Lane::SphereCap(cap)));
2263 }
2264 }
2265 if from <= 2 {
2266 if let Some(horizon) = timed_lane(&prepared.horizon, || prepare_wrapped_horizon(face, prepared), |p, ms| {
2267 p.horizon_preps += 1;
2268 p.horizon_ms += ms;
2269 })? {
2270 return Ok((2, Lane::Horizon(horizon)));
2271 }
2272 }
2273 if from <= 3 {
2274 if let Some(strip) = timed_lane(&prepared.rim_strip, || prepare_covering_rim_strip(face), |p, ms| {
2275 p.rim_strip_preps += 1;
2276 p.rim_strip_ms += ms;
2277 })? {
2278 return Ok((3, Lane::RimStrip(strip)));
2279 }
2280 }
2281 Ok((4, Lane::Generic))
2282}
2283
2284pub fn containment_lane(face: &FaceRecord) -> Result<ContainmentLane, String> {
2326 let prepared = cached_prepared_face(face).unwrap_or_else(|| std::rc::Rc::new(PreparedFace::new()));
2327 Ok(match lane_from(face, &prepared, 0)?.1 {
2328 Lane::SeamBand(_) => ContainmentLane::SeamBand,
2329 Lane::SphereCap(_) => ContainmentLane::SphereCap,
2330 Lane::Horizon(horizon) => ContainmentLane::WrappedHorizon {
2331 loops: horizon.loops.clone(),
2332 u_period: horizon.u_period,
2333 cross_frame: horizon_cross_frame(),
2334 },
2335 Lane::RimStrip(_) => ContainmentLane::CoveringRimStrip,
2336 Lane::Generic => ContainmentLane::Generic {
2337 sphere_chart: sphere_chart_atlas(face).is_some(),
2338 },
2339 })
2340}
2341
2342#[derive(Clone, Debug)]
2344pub enum ContainmentLane {
2345 SeamBand,
2347 SphereCap,
2351 WrappedHorizon {
2358 loops: Vec<Vec<Vec2>>,
2361 u_period: f64,
2362 cross_frame: bool,
2363 },
2364 CoveringRimStrip,
2366 Generic {
2372 sphere_chart: bool,
2375 },
2376}
2377
2378pub fn parameter_point_in_face(
2379 face: &FaceRecord,
2380 point: Vec2,
2381 tolerance: f64,
2382) -> Result<PolygonClass, String> {
2383 point_in_face_scanned(face, point, tolerance, ChordScan::Auto)
2384}
2385
2386#[doc(hidden)]
2391pub fn parameter_point_in_face_scan(
2392 face: &FaceRecord,
2393 point: Vec2,
2394 tolerance: f64,
2395 indexed: bool,
2396) -> Result<PolygonClass, String> {
2397 let scan = if indexed {
2398 ChordScan::Indexed
2399 } else {
2400 ChordScan::Linear
2401 };
2402 point_in_face_scanned(face, point, tolerance, scan)
2403}
2404
2405fn point_in_face_scanned(
2406 face: &FaceRecord,
2407 point: Vec2,
2408 tolerance: f64,
2409 scan: ChordScan,
2410) -> Result<PolygonClass, String> {
2411 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
2412 let prepared = prepared_face(face);
2413 let mut from = 0;
2414 loop {
2415 let (position, lane) = lane_from(face, &prepared, from)?;
2416 let answer = match lane {
2417 Lane::SeamBand(band) => {
2418 seam_band_point_in_face(band, point, tolerance).map(|class| ("seam_band", class))
2419 }
2420 Lane::SphereCap(cap) => winding_sphere_cap_point_in_face(cap, point, tolerance)
2421 .map(|class| ("winding_sphere_cap", class)),
2422 Lane::Horizon(horizon) => wrapped_horizon_point_in_face(face, horizon, point, tolerance, scan)
2423 .map(|class| ("wrapped_horizon", class)),
2424 Lane::RimStrip(strip) => covering_rim_strip_point_in_face(strip, point, tolerance)
2425 .map(|class| ("covering_rim_strip", class)),
2426 Lane::Generic => break,
2427 };
2428 if let Some((name, class)) = answer {
2429 trace_lane(face, point, name, class);
2430 return Ok(class);
2431 }
2432 from = position + 1;
2433 }
2434 let generic = timed_lane(&prepared.generic, || prepare_generic(face, &prepared), |p, ms| {
2435 p.generic_preps += 1;
2436 p.generic_ms += ms;
2437 })?;
2438 let (crossings, boundary, nearest) = generic_scan(generic, point, tolerance, scan);
2439 if boundary {
2440 trace_lane(face, point, "polygon_boundary", PolygonClass::Boundary);
2441 return Ok(PolygonClass::Boundary);
2442 }
2443 let parity = if crossings % 2 == 1 {
2444 PolygonClass::Inside
2445 } else {
2446 PolygonClass::Outside
2447 };
2448 let chord = nearest.map(|(loop_index, index, distance)| {
2449 let polygon = &generic.loops[loop_index].polygon;
2450 let prep = generic.segments[loop_index][index];
2451 (
2452 polygon[index],
2453 polygon[(index + 1) % polygon.len()],
2454 &face.loops[loop_index].coedges[prep.coedge_index].pcurve,
2455 prep,
2456 distance,
2457 )
2458 });
2459 if containment_trace_enabled() {
2460 let (distance, length) = match chord.as_ref() {
2461 Some((start, end, _, _, distance)) => (*distance, end.sub(*start).length()),
2462 None => (f64::NAN, f64::NAN),
2463 };
2464 eprintln!(
2465 "containment face={} uv=({:.8},{:.8}) crossings={crossings} parity={parity:?} \
2466 nearest distance={distance:.3e} segment length={length:.3e}",
2467 face.id, point.x, point.y
2468 );
2469 }
2470 let parity_decides = match chord.as_ref() {
2479 None => true,
2480 Some((start, end, _, _, distance)) => {
2481 let length = end.sub(*start).length();
2482 *distance > length || length <= 0.0
2483 }
2484 };
2485 if parity_decides {
2486 if let Some(class) = sphere_chart_point_in_face(face, point, &prepared, &generic.loops)? {
2487 trace_lane(face, point, "sphere_chart", class);
2488 return Ok(class);
2489 }
2490 }
2491 let Some((segment_start, segment_end, curve, prep, distance)) = chord else {
2492 trace_lane(face, point, "parity (no segment)", parity);
2493 return Ok(parity);
2494 };
2495 let segment_length = segment_end.sub(segment_start).length();
2496 if distance > segment_length || segment_length <= 0.0 {
2497 trace_lane(face, point, "parity (far from every segment)", parity);
2498 return Ok(parity);
2499 }
2500 let chord_parameter = prep.parameter_start
2501 + (prep.parameter_end - prep.parameter_start)
2502 * (point.sub(segment_start).dot(segment_end.sub(segment_start))
2503 / (segment_length * segment_length))
2504 .clamp(0.0, 1.0);
2505 let [domain_start, domain_end] = curve.domain()?;
2506 let small = crate::curve::small_curve_derivatives_enabled();
2507 let read = |parameter: f64, count: usize| -> Result<[Vec3; 3], String> {
2508 if small {
2509 return curve.derivatives_small(parameter, count);
2510 }
2511 let heap = curve.derivatives(parameter, count)?;
2512 let mut grid = [Vec3::default(); 3];
2513 grid[..heap.len()].copy_from_slice(&heap);
2514 Ok(grid)
2515 };
2516 use crate::projection::{curve_foot_newton, CurveFootPolicy, FootDomain, FootMode};
2517 let (parameter, _) = curve_foot_newton(curve, Vec3::new(point.x, point.y, 0.0),
2518 chord_parameter, [domain_start, domain_end], CurveFootPolicy {
2519 domain: FootDomain::Clamp,
2520 iterations: 12,
2521 slope_guard: 1e-30,
2522 step_limit: f64::INFINITY,
2523 parameter_tolerance: 1e-14 * (domain_end - domain_start + 1.0),
2524 mode: FootMode::Planar,
2525 })?;
2526 let margin = 1e-9 * (domain_end - domain_start);
2527 if parameter > domain_start + margin && parameter < domain_end - margin {
2528 let derivatives = read(parameter, 1)?;
2529 let on_curve = Vec2 {
2530 x: derivatives[0].x,
2531 y: derivatives[0].y,
2532 };
2533 let tangent = Vec2 {
2534 x: derivatives[1].x,
2535 y: derivatives[1].y,
2536 };
2537 let offset = point.sub(on_curve);
2538 if offset.length() <= tolerance {
2539 trace_lane(face, point, "nearest curve (on it)", PolygonClass::Boundary);
2540 return Ok(PolygonClass::Boundary);
2541 }
2542 let cross = tangent.x * offset.y - tangent.y * offset.x;
2543 if cross.abs() > 1e-30 {
2544 let class = if (cross > 0.0) == face.same_sense {
2545 PolygonClass::Inside
2546 } else {
2547 PolygonClass::Outside
2548 };
2549 trace_lane(face, point, "nearest curve (side)", class);
2550 return Ok(class);
2551 }
2552 }
2553 trace_lane(face, point, "parity (nearest curve declined)", parity);
2554 Ok(parity)
2555}
2556
2557