1use crate::curve::interior_knots;
2pub use crate::{NurbsCurve, NurbsSurface, Vec3, Vec4};
3use serde::Serialize;
4
5const EPSILON: f64 = crate::tolerance::FP_FLOOR;
6const LINEAR_TOLERANCE: f64 = crate::tolerance::DEFAULT_MODEL;
7const MAX_NEWTON_ITERATIONS: usize = 50;
8
9#[derive(Clone, Copy, Debug, Serialize)]
10pub struct CurveProjection {
11 pub u: f64,
12 pub point: Vec3,
13 pub distance: f64,
14}
15
16#[derive(Clone, Copy, Debug, Serialize)]
17pub struct SurfaceProjection {
18 pub u: f64,
19 pub v: f64,
20 pub point: Vec3,
21 pub distance: f64,
22}
23
24pub fn fit_parameter(value: f64, minimum: f64, maximum: f64, closed: bool) -> f64 {
25 if closed {
26 let period = maximum - minimum;
27 (value - minimum).rem_euclid(period) + minimum
28 } else {
29 value.clamp(minimum, maximum)
30 }
31}
32
33fn witness_rescue_enabled() -> bool {
39 switch!("BREP_PROJECTION_WITNESS", true)
40}
41
42fn point_segment_distance_squared(point: Vec3, a: Vec3, b: Vec3) -> f64 {
48 point.distance_to_segment_squared(a, b)
49}
50
51#[allow(clippy::too_many_arguments)]
59fn curve_newton(
60 curve: &NurbsCurve,
61 point: Vec3,
62 seed: f64,
63 start: f64,
64 end: f64,
65 closed: bool,
66 best_u: &mut f64,
67 best_distance_squared: &mut f64,
68) -> Result<f64, String> {
69 let (last, nearest, squared) = curve_foot_newton_state(curve, point, seed, [start, end],
70 CurveFootPolicy {
71 domain: if closed { FootDomain::Wrap } else { FootDomain::Clamp },
72 iterations: MAX_NEWTON_ITERATIONS,
73 slope_guard: EPSILON,
74 step_limit: (end - start) / 4.0,
75 parameter_tolerance: 1e-15 * (end - start),
76 mode: FootMode::Witness,
77 })?;
78 if squared < *best_distance_squared {
79 *best_distance_squared = squared;
80 *best_u = nearest;
81 }
82 Ok(last)
83}
84
85fn bracketed_nearest(curve: &NurbsCurve, point: Vec3, low: f64, high: f64) -> Result<f64, String> {
93 const CONTRACTION: f64 = 0.618_033_988_749_894_9;
96 const CONTRACTIONS: usize = 64;
97 let width = high - low;
98 if !(width > 0.0) {
99 return Ok(low);
100 }
101 let (mut low, mut high) = (low, high);
102 let mut c = high - CONTRACTION * (high - low);
103 let mut d = low + CONTRACTION * (high - low);
104 let mut value_c = curve.evaluate(c)?.sub(point).length_squared();
105 let mut value_d = curve.evaluate(d)?.sub(point).length_squared();
106 for _ in 0..CONTRACTIONS {
107 if high - low <= 1e-15 * width {
108 break;
109 }
110 if value_c < value_d {
111 high = d;
112 d = c;
113 value_d = value_c;
114 c = high - CONTRACTION * (high - low);
115 value_c = curve.evaluate(c)?.sub(point).length_squared();
116 } else {
117 low = c;
118 c = d;
119 value_c = value_d;
120 d = low + CONTRACTION * (high - low);
121 value_d = curve.evaluate(d)?.sub(point).length_squared();
122 }
123 }
124 Ok((low + high) * 0.5)
125}
126
127pub fn project_point_to_curve(curve: &NurbsCurve, point: Vec3) -> Result<CurveProjection, String> {
128 if projection_memo_enabled() {
129 if let Some(key) = straight_projection_key(curve, point) {
130 if let Some(hit) = PROJECTION_MEMO.with(|memo| memo.borrow().get(&key).copied()) {
131 return Ok(hit);
132 }
133 let projection = project_point_to_curve_uncached(curve, point)?;
134 PROJECTION_MEMO.with(|memo| {
135 let mut memo = memo.borrow_mut();
136 if memo.len() >= PROJECTION_MEMO_ENTRIES {
137 memo.clear();
138 }
139 memo.insert(key, projection);
140 });
141 return Ok(projection);
142 }
143 }
144 project_point_to_curve_uncached(curve, point)
145}
146
147const PROJECTION_MEMO_ENTRIES: usize = 4096;
156
157thread_local! {
158 static PROJECTION_MEMO: std::cell::RefCell<rustc_hash::FxHashMap<[u64; 16], CurveProjection>> = Default::default();
159}
160
161pub fn straight_projection_key(curve: &NurbsCurve, point: Vec3) -> Option<[u64; 16]> {
162 if curve.degree != 1 || curve.control_points.len() != 2 || curve.knots.len() != 4 {
163 return None;
164 }
165 let [a, b] = [curve.control_points[0], curve.control_points[1]];
166 let k = &curve.knots;
167 Some([
168 1, k[0].to_bits(), k[1].to_bits(), k[2].to_bits(), k[3].to_bits(),
169 a.x.to_bits(), a.y.to_bits(), a.z.to_bits(), a.w.to_bits(),
170 b.x.to_bits(), b.y.to_bits(), b.z.to_bits(), b.w.to_bits(),
171 point.x.to_bits(), point.y.to_bits(), point.z.to_bits(),
172 ])
173}
174
175fn projection_memo_enabled() -> bool {
176 switch!("BREP_PROJECTION_MEMO", true)
177}
178
179
180type CurveSeeds = std::rc::Rc<[(f64, Vec3)]>;
183const CURVE_SEED_BUDGET: usize = 262_144;
184thread_local! {
185 static CURVE_SEEDS: std::cell::RefCell<(rustc_hash::FxHashMap<[u64; 2], CurveSeeds>, usize)> = Default::default();
186}
187
188pub fn clear_curve_seed_cache() {
195 CURVE_SEEDS.with(|memo| *memo.borrow_mut() = Default::default());
196}
197
198fn visit_curve_seeds(curve: &NurbsCurve, start: f64, end: f64, mut visit: impl FnMut(f64, Vec3)) -> Result<(), String> {
199 let mut breaks = vec![start];
200 breaks.extend(interior_knots(&curve.knots, curve.degree));
201 breaks.push(end);
202 let samples_per_span = 4usize.max(curve.degree + 2);
203 for pair in breaks.windows(2) {
204 for index in 0..=samples_per_span {
205 let parameter = pair[0] + (pair[1] - pair[0]) * index as f64 / samples_per_span as f64;
206 visit(parameter, curve.evaluate(parameter)?);
207 }
208 }
209 Ok(())
210}
211
212fn cached_curve_seeds(curve: &NurbsCurve, start: f64, end: f64) -> Result<Option<CurveSeeds>, String> {
217 if !switch!("BREP_CURVE_PROJECTION_SEEDS", true) { return Ok(None); }
218 let bound = curve.knots.len().saturating_add(1).saturating_mul(4usize.max(curve.degree + 2).saturating_add(1));
220 if bound > CURVE_SEED_BUDGET { return Ok(None); }
221 let mut key = crate::identity_hash::TwoLane::new();
222 crate::identity_hash::hash_curve(&mut key, curve);
223 key.f64(start); key.f64(end);
224 let key = key.finish();
225 if let Some(seeds) = CURVE_SEEDS.with(|memo| memo.borrow().0.get(&key).cloned()) {
226 return Ok(Some(seeds));
227 }
228 let mut seeds = Vec::new();
229 visit_curve_seeds(curve, start, end, |u, point| seeds.push((u, point)))?;
230 let seeds: CurveSeeds = seeds.into();
231 CURVE_SEEDS.with(|memo| {
232 let mut memo = memo.borrow_mut();
233 if memo.0.len() >= PROJECTION_MEMO_ENTRIES || memo.1 + seeds.len() > CURVE_SEED_BUDGET {
234 memo.0.clear(); memo.1 = 0;
235 }
236 memo.1 += seeds.len();
237 memo.0.insert(key, seeds.clone());
238 });
239 Ok(Some(seeds))
240}
241
242fn project_point_to_curve_uncached(curve: &NurbsCurve, point: Vec3) -> Result<CurveProjection, String> {
243 let [start, end] = curve.domain()?;
244 let mut best_u = start;
245 let mut best_distance_squared = f64::INFINITY;
246 let mut start_point = None;
251 let mut end_point = None;
252 let mut previous: Option<(f64, Vec3)> = None;
255 let mut witness_distance_squared = f64::INFINITY;
256 let mut witness_low = start;
257 let mut witness_high = start;
258 let mut visit = |parameter, sample: Vec3| {
259 if start_point.is_none() {
260 start_point = Some(sample);
261 }
262 end_point = Some(sample);
263 let distance_squared = sample.sub(point).length_squared();
264 if distance_squared < best_distance_squared {
265 best_distance_squared = distance_squared;
266 best_u = parameter;
267 }
268 if let Some((previous_parameter, previous_sample)) = previous {
269 let segment = point_segment_distance_squared(point, previous_sample, sample);
270 if segment < witness_distance_squared {
271 witness_distance_squared = segment;
272 witness_low = previous_parameter;
273 witness_high = parameter;
274 }
275 }
276 previous = Some((parameter, sample));
277 };
278 if let Some(seeds) = cached_curve_seeds(curve, start, end)? {
279 for &(parameter, sample) in seeds.iter() { visit(parameter, sample); }
280 } else {
281 visit_curve_seeds(curve, start, end, visit)?;
282 }
283 const CLOSED_SEAM_TOLERANCE: f64 = 1e-6;
296 let closed = match (start_point, end_point) {
297 (Some(first), Some(last)) => first.sub(last).length() <= CLOSED_SEAM_TOLERANCE,
298 _ => false,
299 };
300
301 let parameter = curve_newton(
302 curve,
303 point,
304 best_u,
305 start,
306 end,
307 closed,
308 &mut best_u,
309 &mut best_distance_squared,
310 )?;
311 for candidate in [start, end, parameter] {
312 let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
313 if distance_squared < best_distance_squared {
314 best_distance_squared = distance_squared;
315 best_u = candidate;
316 }
317 }
318 const WITNESS_FACTOR: f64 = 2.0;
350 if witness_distance_squared * (WITNESS_FACTOR * WITNESS_FACTOR) < best_distance_squared
351 && witness_rescue_enabled()
352 {
353 let bracketed = bracketed_nearest(curve, point, witness_low, witness_high)?;
354 let polished = curve_newton(
355 curve,
356 point,
357 bracketed,
358 start,
359 end,
360 closed,
361 &mut best_u,
362 &mut best_distance_squared,
363 )?;
364 for candidate in [bracketed, polished] {
365 let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
366 if distance_squared < best_distance_squared {
367 best_distance_squared = distance_squared;
368 best_u = candidate;
369 }
370 }
371 }
372 let projected = curve.evaluate(best_u)?;
373 Ok(CurveProjection {
374 u: best_u,
375 point: projected,
376 distance: projected.sub(point).length(),
377 })
378}
379
380fn project_linear_revolution(
381 surface: &NurbsSurface,
382 point: Vec3,
383) -> Result<Option<SurfaceProjection>, String> {
384 let rows = &surface.control_points;
385 if surface.degree_u != 2
386 || surface.degree_v != 1
387 || rows.len() < 5
388 || rows[0].len() != 2
389 || !surface.closed_directions()?.0
390 {
391 return Ok(None);
392 }
393 let base = rows[0][0].point()?.add(rows[4][0].point()?).scale(0.5);
394 let top = rows[0][1].point()?.add(rows[4][1].point()?).scale(0.5);
395 let axis_vector = top.sub(base);
396 let height = axis_vector.length();
397 if height <= EPSILON {
398 return Ok(None);
399 }
400 let axis = axis_vector.normalized()?;
401 let [v0, v1] = surface.domain_v()?;
402 let axial = point.sub(base).dot(axis).clamp(0.0, height);
403 let v = v0 + (v1 - v0) * axial / height;
404 let circle = surface.iso_curve_v(v)?;
405 let projection = project_point_to_curve(&circle, point)?;
406 let [u0, u1] = surface.domain_u()?;
407 let u = projection.u.clamp(u0, u1);
408 let projected = surface.evaluate(u, v)?;
409 Ok(Some(SurfaceProjection {
410 u,
411 v,
412 point: projected,
413 distance: projected.sub(point).length(),
414 }))
415}
416
417#[derive(Clone, Copy)]
418struct NewtonResult {
419 u: f64,
420 v: f64,
421 distance_squared: f64,
422 converged: bool,
423}
424
425fn surface_newton(
426 surface: &NurbsSurface,
427 point: Vec3,
428 seed_u: f64,
429 seed_v: f64,
430 domains: [f64; 4],
431 closed_u: bool,
432 closed_v: bool,
433) -> Result<NewtonResult, String> {
434 surface_newton_impl(surface, point, seed_u, seed_v, domains, closed_u, closed_v,
435 switch!("BREP_PROJECTION_LAZY_DERIVATIVES", false), LINEAR_TOLERANCE)
436}
437
438fn surface_newton_impl(
443 surface: &NurbsSurface,
444 point: Vec3,
445 seed_u: f64,
446 seed_v: f64,
447 domains: [f64; 4],
448 closed_u: bool,
449 closed_v: bool,
450 lazy: bool,
451 linear_tolerance: f64,
452) -> Result<NewtonResult, String> {
453 let [u0, u1, v0, v1] = domains;
454 let mut u = seed_u;
455 let mut v = seed_v;
456 let mut converged = false;
457 let mut best = NewtonResult {
458 u,
459 v,
460 distance_squared: surface.evaluate(u, v)?.sub(point).length_squared(),
461 converged,
462 };
463 let cycle_exit = switch!("BREP_PROJECTION_NEWTON_CYCLE_EXIT", true);
475 let mut trail = [(0u64, 0u64); MAX_NEWTON_ITERATIONS];
476 for iteration in 0..MAX_NEWTON_ITERATIONS {
477 if cycle_exit {
478 let state = (u.to_bits(), v.to_bits());
479 if let Some(first) = trail[..iteration].iter().position(|earlier| *earlier == state) {
480 let period = iteration - first;
481 let (last_u, last_v) = trail[first + (MAX_NEWTON_ITERATIONS - first) % period];
482 u = f64::from_bits(last_u);
483 v = f64::from_bits(last_v);
484 crate::work_counts::add(|c| c.newton_iterations += (MAX_NEWTON_ITERATIONS - iteration) as u64);
485 break;
486 }
487 trail[iteration] = state;
488 }
489 crate::work_counts::add(|c| c.newton_iterations += 1);
490 let derivatives = surface.derivatives_small(u, v, if lazy { 0 } else { 2 })?;
491 let residual = derivatives[0][0].sub(point);
492 let distance_squared = residual.length_squared();
493 if distance_squared < best.distance_squared {
494 best.u = u;
495 best.v = v;
496 best.distance_squared = distance_squared;
497 }
498 let residual_length = distance_squared.sqrt();
499 if residual_length <= linear_tolerance {
500 crate::work_counts::add(|c| { c.newton_unused += 1; c.newton_unused_first += u64::from(iteration == 0); });
501 converged = true;
502 break;
503 }
504 let derivatives = if lazy { surface.derivatives_small(u, v, 2)? } else { derivatives };
505 let f = derivatives[1][0].dot(residual);
506 let g = derivatives[0][1].dot(residual);
507 let tangent_u_length = derivatives[1][0].length();
508 let tangent_v_length = derivatives[0][1].length();
509 let cosine_u = if tangent_u_length * residual_length <= EPSILON {
510 0.0
511 } else {
512 f.abs() / (tangent_u_length * residual_length)
513 };
514 let cosine_v = if tangent_v_length * residual_length <= EPSILON {
515 0.0
516 } else {
517 g.abs() / (tangent_v_length * residual_length)
518 };
519 if cosine_u <= 1e-10 && cosine_v <= 1e-10 {
520 converged = true;
521 break;
522 }
523 let j00 = derivatives[2][0].dot(residual) + derivatives[1][0].length_squared();
524 let j01 = derivatives[1][1].dot(residual) + derivatives[1][0].dot(derivatives[0][1]);
525 let j11 = derivatives[0][2].dot(residual) + derivatives[0][1].length_squared();
526 let determinant = j00 * j11 - j01 * j01;
527 if determinant.abs() <= EPSILON {
528 break;
529 }
530 let mut du = (-f * j11 + g * j01) / determinant;
531 let mut dv = (-g * j00 + f * j01) / determinant;
532 du = du.clamp(-(u1 - u0) / 4.0, (u1 - u0) / 4.0);
533 dv = dv.clamp(-(v1 - v0) / 4.0, (v1 - v0) / 4.0);
534 let next_u = fit_parameter(u + du, u0, u1, closed_u);
535 let next_v = fit_parameter(v + dv, v0, v1, closed_v);
536 let stalled =
537 (next_u - u).abs() <= 1e-15 * (u1 - u0) && (next_v - v).abs() <= 1e-15 * (v1 - v0);
538 u = next_u;
539 v = next_v;
540 if stalled {
541 break;
542 }
543 }
544 let final_distance_squared = surface.evaluate(u, v)?.sub(point).length_squared();
545 if final_distance_squared < best.distance_squared {
546 best.u = u;
547 best.v = v;
548 best.distance_squared = final_distance_squared;
549 }
550 best.converged = converged;
551 Ok(best)
552}
553
554pub fn refine_trim_foot(
558 surface: &NurbsSurface, point: Vec3, foot: SurfaceProjection,
559) -> Result<SurfaceProjection, String> {
560 let [u0, u1] = surface.domain_u()?;
561 let [v0, v1] = surface.domain_v()?;
562 let (cu, cv) = surface.closed_directions()?;
563 let result = surface_newton_impl(surface, point, foot.u, foot.v,
564 [u0, u1, v0, v1], cu, cv, false, 1e-11)?;
565 let projected = surface.evaluate(result.u, result.v)?;
566 Ok(SurfaceProjection { u: result.u, v: result.v, point: projected,
567 distance: projected.sub(point).length() })
568}
569
570#[track_caller]
576pub fn project_point_to_surface(
577 surface: &NurbsSurface,
578 point: Vec3,
579) -> Result<SurfaceProjection, String> {
580 crate::work_counts::add(|c| c.projection_global += 1);
581 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_PROJECT, surface);
582 if let Some(analytic) = surface.analytic() {
586 if let Some(projection) = analytic.project(surface, point) {
587 return Ok(projection);
588 }
589 }
590 if let Some(ellipsoid) = surface.affine_sphere() {
591 if let Some(projection) = ellipsoid.project(surface, point) {
592 return Ok(projection);
593 }
594 }
595 project_point_to_surface_general(surface, point)
596}
597
598pub fn project_point_to_surface_seeded(
608 surface: &NurbsSurface,
609 point: Vec3,
610 seed_u: f64,
611 seed_v: f64,
612) -> Result<SurfaceProjection, String> {
613 crate::work_counts::add(|c| c.projection_seeded += 1);
614 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
615 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_SEEDED, surface);
616 if let Some(ellipsoid) = surface.affine_sphere() {
620 if let Some(projection) = ellipsoid.project(surface, point) {
621 return Ok(projection);
622 }
623 }
624 let [u0, u1] = surface.domain_u()?;
625 let [v0, v1] = surface.domain_v()?;
626 let (closed_u, closed_v) = surface.closed_directions()?;
627 let result = surface_newton(
628 surface,
629 point,
630 seed_u,
631 seed_v,
632 [u0, u1, v0, v1],
633 closed_u,
634 closed_v,
635 )?;
636 let projected = surface.evaluate(result.u, result.v)?;
637 Ok(SurfaceProjection {
638 u: result.u,
639 v: result.v,
640 point: projected,
641 distance: projected.sub(point).length(),
642 })
643}
644
645#[track_caller]
679pub fn project_point_to_surface_from_seed(
680 surface: &NurbsSurface,
681 point: Vec3,
682 seed: [f64; 2],
683) -> Result<SurfaceProjection, String> {
684 crate::work_counts::add(|c| c.projection_from_seed += 1);
685 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
686 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_SEED, surface);
687 if let Some(analytic) = surface.analytic() {
688 if let Some(projection) = analytic.project(surface, point) {
689 return Ok(projection);
690 }
691 }
692 if let Some(ellipsoid) = surface.affine_sphere() {
693 if let Some(projection) = ellipsoid.project(surface, point) {
694 return Ok(projection);
695 }
696 }
697 let caller = std::panic::Location::caller();
698 if !seeded_answer_admitted(caller) {
699 return project_point_to_surface_general(surface, point);
700 }
701 let seeded = project_point_to_surface_seeded(surface, point, seed[0], seed[1])?;
702 if seed_audit_enabled() {
703 let nearest = project_point_to_surface_general(surface, point)?;
704 if seeded.point.sub(nearest.point).length() > LINEAR_TOLERANCE {
705 seed_audit_record(caller, surface, seed, &seeded, &nearest);
706 }
707 }
708 Ok(seeded)
709}
710
711fn seeded_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
714 static SITES: std::sync::OnceLock<Option<Option<Vec<String>>>> = std::sync::OnceLock::new();
715 let sites = SITES.get_or_init(|| {
716 if std::env::var("BREP_PROJECTION_FROM_SEED").as_deref() == Ok("0") {
717 return None;
718 }
719 Some(std::env::var("BREP_PROJECTION_FROM_SEED_SITES").ok().map(|value| {
720 value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect()
721 }))
722 });
723 match sites {
724 None => false,
725 Some(None) => true,
726 Some(Some(only)) => {
727 let location = format!("{}:{}", caller.file(), caller.line());
728 only.iter().any(|site| location.contains(site.as_str()))
729 }
730 }
731}
732
733fn seed_audit_enabled() -> bool {
734 debug_flag!("BREP_PROJECTION_AUDIT")
735}
736
737fn seed_audit_record(
741 caller: &std::panic::Location<'_>,
742 surface: &NurbsSurface,
743 seed: [f64; 2],
744 seeded: &SurfaceProjection,
745 nearest: &SurfaceProjection,
746) {
747 use std::io::Write;
748 static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
749 std::sync::OnceLock::new();
750 let sink = SINK.get_or_init(|| {
751 let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
752 let path = std::path::Path::new(&directory)
753 .join(format!("projection-seed-audit-{}.tsv", std::process::id()));
754 std::fs::OpenOptions::new()
755 .create(true)
756 .append(true)
757 .open(path)
758 .ok()
759 .map(std::sync::Mutex::new)
760 });
761 if let Some(file) = sink {
762 if let Ok(mut file) = file.lock() {
763 let _ = writeln!(
764 file,
765 "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.6e}\t{}x{} cp {}x{}",
766 caller.file(),
767 caller.line(),
768 seeded.distance,
769 nearest.distance,
770 seed[0],
771 seed[1],
772 seeded.u,
773 seeded.v,
774 nearest.u,
775 nearest.v,
776 seeded.point.sub(nearest.point).length(),
777 surface.degree_u,
778 surface.degree_v,
779 surface.control_points.len(),
780 surface.control_points.first().map(Vec::len).unwrap_or(0),
781 );
782 }
783 }
784}
785
786fn projection_seed_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
791 if let Some(grid) = surface.projection_grid.get() {
792 return Ok(grid);
793 }
794 let [u0, u1] = surface.domain_u()?;
795 let [v0, v1] = surface.domain_v()?;
796 let (closed_u, closed_v) = surface.closed_directions()?;
797 let mut breaks_u = vec![u0];
798 breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
799 breaks_u.push(u1);
800 let mut breaks_v = vec![v0];
801 breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
802 breaks_v.push(v1);
803 let samples_u = if closed_u {
804 8usize.max(surface.degree_u * 4)
805 } else {
806 3usize.max(surface.degree_u + 1)
807 };
808 let samples_v = if closed_v {
809 8usize.max(surface.degree_v * 4)
810 } else {
811 3usize.max(surface.degree_v + 1)
812 };
813 let mut grid = Vec::new();
814 for u_pair in breaks_u.windows(2) {
815 for v_pair in breaks_v.windows(2) {
816 for i in 0..=samples_u {
817 for j in 0..=samples_v {
818 let u = u_pair[0] + (u_pair[1] - u_pair[0]) * i as f64 / samples_u as f64;
819 let v = v_pair[0] + (v_pair[1] - v_pair[0]) * j as f64 / samples_v as f64;
820 grid.push((u, v, surface.evaluate(u, v)?));
821 }
822 }
823 }
824 }
825 Ok(surface.projection_grid.get_or_init(|| SampleGrid::new(grid)))
826}
827
828fn projection_dense_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
835 if let Some(grid) = surface.projection_dense_grid.get() {
836 return Ok(grid);
837 }
838 let [u0, u1] = surface.domain_u()?;
839 let [v0, v1] = surface.domain_v()?;
840 let mut breaks_u = vec![u0];
841 breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
842 breaks_u.push(u1);
843 let mut breaks_v = vec![v0];
844 breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
845 breaks_v.push(v1);
846 let count_u = 32usize.max((breaks_u.len() - 1) * 8);
847 let count_v = 16usize.max((breaks_v.len() - 1) * 8);
848 let mut grid = Vec::with_capacity((count_u + 1) * (count_v + 1));
849 for i in 0..=count_u {
850 for j in 0..=count_v {
851 let u = u0 + (u1 - u0) * i as f64 / count_u as f64;
852 let v = v0 + (v1 - v0) * j as f64 / count_v as f64;
853 grid.push((u, v, surface.evaluate(u, v)?));
854 }
855 }
856 Ok(surface.projection_dense_grid.get_or_init(|| SampleGrid::with_tree(grid)))
857}
858
859const SAMPLE_BLOCK: usize = 32;
861
862const GROUP_BLOCKS: usize = 32;
865
866#[derive(Clone, Debug)]
871pub struct SampleGrid {
872 samples: Vec<(f64, f64, Vec3)>,
873 blocks: Vec<SampleBlock>,
874 groups: Vec<SampleBlock>,
879 tree: Vec<Vec<SampleBlock>>,
885}
886
887const TREE_FANOUT: usize = 4;
889
890fn union_boxes(boxes: &[SampleBlock]) -> Vec<SampleBlock> {
892 boxes
893 .chunks(TREE_FANOUT)
894 .map(|chunk| {
895 let mut union = chunk[0];
896 for block in chunk {
897 union.low = Vec3::new(union.low.x.min(block.low.x), union.low.y.min(block.low.y), union.low.z.min(block.low.z));
898 union.high = Vec3::new(union.high.x.max(block.high.x), union.high.y.max(block.high.y), union.high.z.max(block.high.z));
899 union.prunable &= block.prunable;
900 }
901 union
902 })
903 .collect()
904}
905
906#[derive(Clone, Copy, Debug)]
909struct SampleBlock {
910 low: Vec3,
911 high: Vec3,
912 prunable: bool,
913}
914
915impl SampleGrid {
916 fn new(samples: Vec<(f64, f64, Vec3)>) -> Self {
917 let blocks = samples
918 .chunks(SAMPLE_BLOCK)
919 .map(|chunk| {
920 let mut low = chunk[0].2;
921 let mut high = low;
922 let mut prunable = true;
923 for &(_, _, p) in chunk {
924 prunable &= p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
925 low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
926 high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
927 }
928 SampleBlock { low, high, prunable }
929 })
930 .collect::<Vec<_>>();
931 let groups = blocks
932 .chunks(GROUP_BLOCKS)
933 .map(|chunk| {
934 let mut group = chunk[0];
935 for block in chunk {
936 group.low = Vec3::new(group.low.x.min(block.low.x), group.low.y.min(block.low.y), group.low.z.min(block.low.z));
937 group.high = Vec3::new(group.high.x.max(block.high.x), group.high.y.max(block.high.y), group.high.z.max(block.high.z));
938 group.prunable &= block.prunable;
939 }
940 group
941 })
942 .collect();
943 Self { samples, blocks, groups, tree: Vec::new() }
944 }
945
946 fn with_tree(samples: Vec<(f64, f64, Vec3)>) -> Self {
953 let mut grid = Self::new(samples);
954 if grid.blocks.len() > GROUP_BLOCKS {
955 grid.tree.push(union_boxes(&grid.blocks));
956 while grid.tree.last().is_some_and(|level| level.len() > 1) {
957 let next = union_boxes(grid.tree.last().unwrap());
958 grid.tree.push(next);
959 }
960 }
961 grid
962 }
963}
964
965impl SampleBlock {
966 fn lower_bound(&self, point: Vec3) -> f64 {
974 let gap = |p: f64, low: f64, high: f64| {
975 if p < low {
976 low - p
977 } else if p > high {
978 p - high
979 } else {
980 0.0
981 }
982 };
983 let x = gap(point.x, self.low.x, self.high.x);
984 let y = gap(point.y, self.low.y, self.high.y);
985 let z = gap(point.z, self.low.z, self.high.z);
986 x * x + y * y + z * z
987 }
988}
989
990fn pruned_scan() -> bool {
993 switch!("BREP_PROJECTION_PRUNED_SCAN", true)
994}
995
996fn nearest_sample(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1006 if !grid.tree.is_empty() && scan_tree() && pruned_scan() && bound_first_scan() {
1007 nearest_sample_tree(grid, point, best);
1008 return;
1009 }
1010 nearest_sample_with(grid, point, best, pruned_scan(), bound_first_scan());
1011}
1012
1013fn scan_tree() -> bool {
1025 switch!("BREP_PROJECTION_SCAN_TREE", true)
1026}
1027
1028fn scan_hint() -> bool {
1038 switch!("BREP_PROJECTION_SCAN_HINT", true)
1039}
1040
1041const HINT_SLOTS: usize = 8;
1042
1043thread_local! {
1044 static SCAN_HINTS: std::cell::Cell<[(usize, usize); HINT_SLOTS]> =
1046 const { std::cell::Cell::new([(0, usize::MAX); HINT_SLOTS]) };
1047}
1048
1049fn hint_slot(grid: &SampleGrid) -> (usize, usize) {
1050 let address = grid.samples.as_ptr() as usize;
1051 (address, (address >> 4) % HINT_SLOTS)
1052}
1053
1054fn hinted_bound(grid: &SampleGrid, point: Vec3, mut bound: f64) -> f64 {
1061 if !scan_hint() {
1062 return bound;
1063 }
1064 let (address, slot) = hint_slot(grid);
1065 let (held, run) = SCAN_HINTS.with(|hints| hints.get()[slot]);
1066 if held != address || run >= grid.blocks.len() || !grid.blocks[run].prunable {
1067 return bound;
1068 }
1069 let start = run * SAMPLE_BLOCK;
1070 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1071 for &(_, _, sample) in &grid.samples[start..end] {
1072 let distance_squared = sample.sub(point).length_squared();
1073 if distance_squared < bound {
1074 bound = distance_squared;
1075 }
1076 }
1077 bound
1078}
1079
1080fn remember_hint(grid: &SampleGrid, run: Option<usize>) {
1082 if let Some(run) = run.filter(|_| scan_hint()) {
1083 let (address, slot) = hint_slot(grid);
1084 SCAN_HINTS.with(|hints| {
1085 let mut all = hints.get();
1086 all[slot] = (address, run);
1087 hints.set(all);
1088 });
1089 }
1090}
1091
1092fn nearest_sample_tree(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1103 let top = grid.tree.len() - 1;
1104 let mut bound = best.distance_squared;
1105 let mut node = 0usize;
1107 let mut reached = true;
1108 for level in (0..=top).rev() {
1109 let children = |count: usize| node * TREE_FANOUT..((node + 1) * TREE_FANOUT).min(count);
1110 let below = if level == 0 { &grid.blocks } else { &grid.tree[level - 1] };
1111 match lowest_floor(below, children(below.len()), point) {
1112 Some(child) => node = child,
1113 None => {
1114 reached = false;
1115 break;
1116 }
1117 }
1118 }
1119 if reached {
1120 let start = node * SAMPLE_BLOCK;
1121 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1122 for &(_, _, sample) in &grid.samples[start..end] {
1123 let distance_squared = sample.sub(point).length_squared();
1124 if distance_squared < bound {
1125 bound = distance_squared;
1126 }
1127 }
1128 }
1129 let bound = hinted_bound(grid, point, bound);
1130 let skip = |box_: &SampleBlock, held: f64| {
1131 if !box_.prunable {
1132 return false;
1133 }
1134 let floor = box_.lower_bound(point);
1135 floor >= held || floor > bound
1136 };
1137 let mut answer_run = None;
1138 let mut stack: Vec<(usize, usize)> = Vec::with_capacity(TREE_FANOUT * (top + 2));
1140 stack.push((top + 1, 0));
1141 while let Some((level, index)) = stack.pop() {
1142 if level == 0 {
1143 if skip(&grid.blocks[index], best.distance_squared) {
1144 continue;
1145 }
1146 let start = index * SAMPLE_BLOCK;
1147 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1148 let held = best.distance_squared;
1149 scan_run(&grid.samples[start..end], point, best);
1150 if best.distance_squared < held {
1151 answer_run = Some(index);
1152 }
1153 continue;
1154 }
1155 if skip(&grid.tree[level - 1][index], best.distance_squared) {
1156 continue;
1157 }
1158 let count = if level == 1 { grid.blocks.len() } else { grid.tree[level - 2].len() };
1159 let children = index * TREE_FANOUT..((index + 1) * TREE_FANOUT).min(count);
1160 for child in children.rev() {
1162 stack.push((level - 1, child));
1163 }
1164 }
1165 remember_hint(grid, answer_run);
1166}
1167
1168fn bound_first_scan() -> bool {
1184 switch!("BREP_PROJECTION_BOUND_FIRST", true)
1185}
1186
1187fn nearest_sample_with(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult, pruned: bool, bound_first: bool) {
1197 if !(pruned && bound_first) {
1198 for (block, chunk) in grid.blocks.iter().zip(grid.samples.chunks(SAMPLE_BLOCK)) {
1199 if pruned && block.prunable && block.lower_bound(point) >= best.distance_squared {
1200 continue;
1201 }
1202 scan_run(chunk, point, best);
1203 }
1204 return;
1205 }
1206 let mut bound = best.distance_squared;
1209 let lowest_group = lowest_floor(&grid.groups, 0..grid.groups.len(), point);
1210 if let Some(group) = lowest_group {
1211 let runs = group * GROUP_BLOCKS..((group + 1) * GROUP_BLOCKS).min(grid.blocks.len());
1212 if let Some(run) = lowest_floor(&grid.blocks, runs, point) {
1213 let start = run * SAMPLE_BLOCK;
1214 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1215 for &(_, _, sample) in &grid.samples[start..end] {
1216 let distance_squared = sample.sub(point).length_squared();
1217 if distance_squared < bound {
1218 bound = distance_squared;
1219 }
1220 }
1221 }
1222 }
1223 let bound = hinted_bound(grid, point, bound);
1224 let skip = |box_: &SampleBlock, held: f64| {
1225 if !box_.prunable {
1226 return false;
1227 }
1228 let floor = box_.lower_bound(point);
1229 floor >= held || floor > bound
1230 };
1231 let mut answer_run = None;
1232 for (group_index, group) in grid.groups.iter().enumerate() {
1233 if skip(group, best.distance_squared) {
1234 continue;
1235 }
1236 let first = group_index * GROUP_BLOCKS;
1237 let last = (first + GROUP_BLOCKS).min(grid.blocks.len());
1238 for run in first..last {
1239 if skip(&grid.blocks[run], best.distance_squared) {
1240 continue;
1241 }
1242 let start = run * SAMPLE_BLOCK;
1243 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1244 let held = best.distance_squared;
1245 scan_run(&grid.samples[start..end], point, best);
1246 if best.distance_squared < held {
1247 answer_run = Some(run);
1248 }
1249 }
1250 }
1251 remember_hint(grid, answer_run);
1252}
1253
1254fn scan_run(run: &[(f64, f64, Vec3)], point: Vec3, best: &mut NewtonResult) {
1257 for &(u, v, sample) in run {
1258 let distance_squared = sample.sub(point).length_squared();
1259 if distance_squared < best.distance_squared {
1260 best.u = u;
1261 best.v = v;
1262 best.distance_squared = distance_squared;
1263 }
1264 }
1265}
1266
1267fn lowest_floor(boxes: &[SampleBlock], range: std::ops::Range<usize>, point: Vec3) -> Option<usize> {
1270 let mut lowest: Option<(usize, f64)> = None;
1271 for index in range {
1272 let box_ = &boxes[index];
1273 if !box_.prunable {
1274 continue;
1275 }
1276 let floor = box_.lower_bound(point);
1277 if lowest.is_none_or(|(_, held)| floor < held) {
1278 lowest = Some((index, floor));
1279 }
1280 }
1281 lowest.map(|(index, _)| index)
1282}
1283
1284const RING_EXPONENTS: usize = 22;
1288const RING_INDICES: usize = 33; #[inline]
1291fn ring_slot(side: usize, exponent_index: usize, index: usize) -> usize {
1292 (side * RING_EXPONENTS + exponent_index) * RING_INDICES + index
1293}
1294
1295fn projection_ring_grid(surface: &NurbsSurface) -> Result<&[Vec3], String> {
1302 if let Some(grid) = surface.projection_ring_grid.get() {
1303 return Ok(grid);
1304 }
1305 let [u0, u1] = surface.domain_u()?;
1306 let [v0, v1] = surface.domain_v()?;
1307 let mut grid = vec![Vec3::default(); 4 * RING_EXPONENTS * RING_INDICES];
1308 for exponent in 1..=RING_EXPONENTS as i32 {
1309 let offset = 1.0 / 2f64.powi(exponent);
1310 let e = exponent as usize - 1;
1311 let v_lo = v0 + (v1 - v0) * offset;
1312 let v_hi = v1 - (v1 - v0) * offset;
1313 let u_lo = u0 + (u1 - u0) * offset;
1314 let u_hi = u1 - (u1 - u0) * offset;
1315 for index in 0..=32 {
1316 let u = u0 + (u1 - u0) * index as f64 / 32.0;
1317 grid[ring_slot(0, e, index as usize)] = surface.evaluate(u, v_lo)?;
1318 grid[ring_slot(1, e, index as usize)] = surface.evaluate(u, v_hi)?;
1319 }
1320 for index in 0..=32 {
1321 let v = v0 + (v1 - v0) * index as f64 / 32.0;
1322 grid[ring_slot(2, e, index as usize)] = surface.evaluate(u_lo, v)?;
1323 grid[ring_slot(3, e, index as usize)] = surface.evaluate(u_hi, v)?;
1324 }
1325 }
1326 Ok(surface.projection_ring_grid.get_or_init(|| grid))
1327}
1328
1329fn nearest_seed_answer(
1339 surface: &NurbsSurface,
1340 point: Vec3,
1341 [u0, u1, v0, v1]: [f64; 4],
1342 closed_u: bool,
1343 closed_v: bool,
1344) -> Result<NewtonResult, String> {
1345 let mut best = NewtonResult {
1346 u: u0,
1347 v: v0,
1348 distance_squared: f64::INFINITY,
1349 converged: false,
1350 };
1351 nearest_sample(projection_seed_grid(surface)?, point, &mut best);
1352 if let Some(revolution) = project_linear_revolution(surface, point)? {
1353 if revolution.distance * revolution.distance < best.distance_squared {
1354 best.u = revolution.u;
1355 best.v = revolution.v;
1356 best.distance_squared = revolution.distance * revolution.distance;
1357 }
1358 }
1359 let first_newton = surface_newton(
1360 surface,
1361 point,
1362 best.u,
1363 best.v,
1364 [u0, u1, v0, v1],
1365 closed_u,
1366 closed_v,
1367 )?;
1368 if first_newton.distance_squared < best.distance_squared {
1369 best = first_newton;
1370 }
1371 let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1372 let degenerate = su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length());
1373 if degenerate || !first_newton.converged {
1374 let mut grid = best;
1375 nearest_sample(projection_dense_grid(surface)?, point, &mut grid);
1376 if grid.distance_squared < best.distance_squared {
1377 best = grid;
1378 }
1379 let polished = surface_newton(
1380 surface,
1381 point,
1382 grid.u,
1383 grid.v,
1384 [u0, u1, v0, v1],
1385 closed_u,
1386 closed_v,
1387 )?;
1388 if polished.distance_squared < best.distance_squared {
1389 best = polished;
1390 }
1391
1392 let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1393 if su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length()) {
1394 let ring_grid = projection_ring_grid(surface)?;
1395 let mut ring = best;
1396 let scan = |side: usize,
1400 exponent_index: usize,
1401 along_u: bool,
1402 fixed: f64,
1403 candidate: &mut NewtonResult| {
1404 for index in 0..=32 {
1405 let moving = if along_u {
1406 u0 + (u1 - u0) * index as f64 / 32.0
1407 } else {
1408 v0 + (v1 - v0) * index as f64 / 32.0
1409 };
1410 let (u, v) = if along_u {
1411 (moving, fixed)
1412 } else {
1413 (fixed, moving)
1414 };
1415 let distance_squared = ring_grid
1416 [ring_slot(side, exponent_index, index as usize)]
1417 .sub(point)
1418 .length_squared();
1419 if distance_squared < candidate.distance_squared {
1420 candidate.u = u;
1421 candidate.v = v;
1422 candidate.distance_squared = distance_squared;
1423 }
1424 }
1425 };
1426 for exponent in 1..=22 {
1427 let offset = 1.0 / 2f64.powi(exponent);
1428 let e = exponent as usize - 1;
1429 if (best.v - v0).abs() <= (v1 - v0) * 0.02 {
1430 scan(0, e, true, v0 + (v1 - v0) * offset, &mut ring);
1431 }
1432 if (best.v - v1).abs() <= (v1 - v0) * 0.02 {
1433 scan(1, e, true, v1 - (v1 - v0) * offset, &mut ring);
1434 }
1435 if (best.u - u0).abs() <= (u1 - u0) * 0.02 {
1436 scan(2, e, false, u0 + (u1 - u0) * offset, &mut ring);
1437 }
1438 if (best.u - u1).abs() <= (u1 - u0) * 0.02 {
1439 scan(3, e, false, u1 - (u1 - u0) * offset, &mut ring);
1440 }
1441 }
1442 if ring.distance_squared < best.distance_squared {
1443 best = ring;
1444 }
1445 let polished = surface_newton(
1446 surface,
1447 point,
1448 ring.u,
1449 ring.v,
1450 [u0, u1, v0, v1],
1451 closed_u,
1452 closed_v,
1453 )?;
1454 if polished.distance_squared < best.distance_squared {
1455 best = polished;
1456 }
1457 }
1458 }
1459 Ok(best)
1460}
1461
1462fn global_stage_enabled() -> bool {
1467 switch!("BREP_PROJECTION_GLOBAL", true)
1468}
1469
1470pub fn global_site_filter_active() -> bool {
1479 static ACTIVE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1484 *ACTIVE.get_or_init(|| {
1485 std::env::var_os("BREP_PROJECTION_GLOBAL_SITES").is_some() || std::env::var_os("BREP_PROJECTION_GLOBAL_EXCEPT").is_some()
1486 })
1487}
1488
1489fn global_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
1490 fn list(name: &str) -> Option<Vec<String>> {
1491 std::env::var(name)
1492 .ok()
1493 .map(|value| value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect())
1494 }
1495 static SITES: std::sync::OnceLock<(Option<Vec<String>>, Option<Vec<String>>)> =
1496 std::sync::OnceLock::new();
1497 let (only, except) = SITES.get_or_init(|| {
1498 (list("BREP_PROJECTION_GLOBAL_SITES"), list("BREP_PROJECTION_GLOBAL_EXCEPT"))
1499 });
1500 if only.is_none() && except.is_none() {
1501 return true;
1502 }
1503 let location = format!("{}:{}", caller.file(), caller.line());
1504 let named = |sites: &Vec<String>| sites.iter().any(|site| location.contains(site.as_str()));
1505 only.as_ref().is_none_or(named) && !except.as_ref().is_some_and(named)
1506}
1507
1508fn audit_record(caller: &std::panic::Location<'_>, surface: &NurbsSurface, local: &NewtonResult, global: &NewtonResult) {
1514 use std::io::Write;
1515 static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
1516 std::sync::OnceLock::new();
1517 let sink = SINK.get_or_init(|| {
1518 let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
1519 let path = std::path::Path::new(&directory)
1520 .join(format!("projection-audit-{}.tsv", std::process::id()));
1521 std::fs::OpenOptions::new()
1522 .create(true)
1523 .append(true)
1524 .open(path)
1525 .ok()
1526 .map(std::sync::Mutex::new)
1527 });
1528 if let Some(file) = sink {
1529 if let Ok(mut file) = file.lock() {
1530 let _ = writeln!(
1531 file,
1532 "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{}x{} cp {}x{}",
1533 caller.file(),
1534 caller.line(),
1535 local.distance_squared.sqrt(),
1536 global.distance_squared.sqrt(),
1537 local.u,
1538 local.v,
1539 global.u,
1540 global.v,
1541 surface.degree_u,
1542 surface.degree_v,
1543 surface.control_points.len(),
1544 surface.control_points.first().map(Vec::len).unwrap_or(0),
1545 );
1546 }
1547 }
1548}
1549
1550#[track_caller]
1626pub fn project_point_to_surface_general(
1627 surface: &NurbsSurface,
1628 point: Vec3,
1629) -> Result<SurfaceProjection, String> {
1630 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_GENERAL, surface);
1631 let [u0, u1] = surface.domain_u()?;
1632 let [v0, v1] = surface.domain_v()?;
1633 let (closed_u, closed_v) = surface.closed_directions()?;
1634 let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1635 let mut best = local;
1636 if global_stage_enabled() {
1637 global_minimum(
1638 surface,
1639 point,
1640 [u0, u1, v0, v1],
1641 (closed_u, closed_v),
1642 &mut best,
1643 &mut GlobalStats::default(),
1644 )?;
1645 if best.u != local.u || best.v != local.v {
1646 let caller = std::panic::Location::caller();
1647 if global_answer_admitted(caller) {
1648 audit_record(caller, surface, &local, &best);
1649 } else {
1650 best = local;
1651 }
1652 }
1653 }
1654 let projected = surface.evaluate(best.u, best.v)?;
1655 Ok(SurfaceProjection {
1656 u: best.u,
1657 v: best.v,
1658 point: projected,
1659 distance: projected.sub(point).length(),
1660 })
1661}
1662
1663pub fn project_point_to_surface_from_nearest_seed(
1673 surface: &NurbsSurface,
1674 point: Vec3,
1675) -> Result<SurfaceProjection, String> {
1676 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_NEAREST_SEED, surface);
1677 if let Some(analytic) = surface.analytic() {
1678 if let Some(projection) = analytic.project(surface, point) {
1679 return Ok(projection);
1680 }
1681 }
1682 if let Some(ellipsoid) = surface.affine_sphere() {
1683 if let Some(projection) = ellipsoid.project(surface, point) {
1684 return Ok(projection);
1685 }
1686 }
1687 let [u0, u1] = surface.domain_u()?;
1688 let [v0, v1] = surface.domain_v()?;
1689 let (closed_u, closed_v) = surface.closed_directions()?;
1690 let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1691 let projected = surface.evaluate(local.u, local.v)?;
1692 Ok(SurfaceProjection {
1693 u: local.u,
1694 v: local.v,
1695 point: projected,
1696 distance: projected.sub(point).length(),
1697 })
1698}
1699
1700#[doc(hidden)]
1703pub fn project_point_to_surface_general_lanes(
1704 surface: &NurbsSurface,
1705 point: Vec3,
1706 run_global: bool,
1707) -> Result<(SurfaceProjection, GlobalStats), String> {
1708 let [u0, u1] = surface.domain_u()?;
1709 let [v0, v1] = surface.domain_v()?;
1710 let (closed_u, closed_v) = surface.closed_directions()?;
1711 let mut best = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1712 let mut stats = GlobalStats::default();
1713 if run_global {
1714 global_minimum(surface, point, [u0, u1, v0, v1], (closed_u, closed_v), &mut best, &mut stats)?;
1715 }
1716 let projected = surface.evaluate(best.u, best.v)?;
1717 Ok((
1718 SurfaceProjection {
1719 u: best.u,
1720 v: best.v,
1721 point: projected,
1722 distance: projected.sub(point).length(),
1723 },
1724 stats,
1725 ))
1726}
1727
1728#[doc(hidden)]
1731#[derive(Clone, Debug, Default)]
1732pub struct BasinCensus {
1733 pub cells: usize,
1736 pub descents: usize,
1738 pub unconverged: usize,
1740 pub cells_with_two_basins: usize,
1744 pub foot_cells_with_two_basins: usize,
1747 pub least: f64,
1749 pub least_uv: (f64, f64),
1750 pub foot_cell_descents: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)>,
1754}
1755
1756#[doc(hidden)]
1761pub fn project_point_to_surface_basin_census(
1762 surface: &NurbsSurface,
1763 point: Vec3,
1764 answer_distance: f64,
1765 bar: f64,
1766) -> Result<BasinCensus, String> {
1767 let mut census = BasinCensus {
1768 least: f64::INFINITY,
1769 ..BasinCensus::default()
1770 };
1771 let Some(cells) = projection_cells(surface)? else {
1772 return Ok(census);
1773 };
1774 let columns = cells.vs.len() - 1;
1775 let mut spreads: Vec<(usize, f64)> = Vec::new();
1776 let mut runs: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)> = Vec::new();
1777 for (cell, cell_box) in cells.boxes.iter().enumerate() {
1778 if cell_box.lower_bound(point) >= answer_distance {
1779 continue;
1780 }
1781 census.cells += 1;
1782 let (row, column) = (cell / columns, cell % columns);
1783 let rectangle = [cells.us[row], cells.us[row + 1], cells.vs[column], cells.vs[column + 1]];
1784 let middle = ((rectangle[0] + rectangle[1]) * 0.5, (rectangle[2] + rectangle[3]) * 0.5);
1785 let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
1786 for seed in [
1787 (rectangle[0], rectangle[2]),
1788 (rectangle[1], rectangle[2]),
1789 (rectangle[0], rectangle[3]),
1790 (rectangle[1], rectangle[3]),
1791 middle,
1792 ] {
1793 census.descents += 1;
1794 let (found, _) = confined_descent(surface, point, seed, rectangle, (false, false))?;
1795 let distance = found.distance_squared.sqrt();
1796 runs.push((cell, rectangle, seed, (found.u, found.v), distance, found.converged));
1797 if distance < census.least {
1798 census.least = distance;
1799 census.least_uv = (found.u, found.v);
1800 }
1801 if !found.converged {
1802 census.unconverged += 1;
1803 continue;
1804 }
1805 low = low.min(distance.max(LINEAR_TOLERANCE));
1806 high = high.max(distance.max(LINEAR_TOLERANCE));
1807 }
1808 if high - low > bar {
1809 spreads.push((cell, high - low));
1810 }
1811 }
1812 census.cells_with_two_basins = spreads.len();
1813 let (u, v) = census.least_uv;
1814 let foot_cells: Vec<usize> = spreads
1815 .iter()
1816 .map(|&(cell, _)| cell)
1817 .filter(|&cell| {
1818 let (row, column) = (cell / columns, cell % columns);
1819 cells.us[row] <= u && u <= cells.us[row + 1] && cells.vs[column] <= v && v <= cells.vs[column + 1]
1820 })
1821 .collect();
1822 census.foot_cells_with_two_basins = foot_cells.len();
1823 census.foot_cell_descents = runs.into_iter().filter(|run| foot_cells.contains(&run.0)).collect();
1824 Ok(census)
1825}
1826
1827#[doc(hidden)]
1829#[derive(Clone, Copy, Debug, Default)]
1830pub struct GlobalStats {
1831 pub settled_by_floor: bool,
1833 pub candidates: usize,
1835 pub refinements: usize,
1837 pub continuations: usize,
1839 pub replaced: bool,
1841 pub hull_lower_bound: f64,
1844}
1845
1846#[derive(Clone, Debug)]
1849struct CellBox {
1850 axes: [Vec3; 3],
1851 low: [f64; 3],
1852 high: [f64; 3],
1853}
1854
1855impl CellBox {
1856 fn lower_bound(&self, point: Vec3) -> f64 {
1859 let mut squared = 0.0;
1860 for axis in 0..3 {
1861 let coordinate = point.dot(self.axes[axis]);
1862 let excess = (self.low[axis] - coordinate).max(coordinate - self.high[axis]).max(0.0);
1863 squared += excess * excess;
1864 }
1865 squared.sqrt()
1866 }
1867}
1868
1869#[derive(Clone, Copy, Debug)]
1872struct CellTreeNode {
1873 centre: Vec3,
1874 radius: f64,
1875 children: Option<(u32, u32)>,
1876 cell: u32,
1877}
1878
1879#[derive(Clone, Debug)]
1882pub struct ProjectionCells {
1883 us: Vec<f64>,
1884 vs: Vec<f64>,
1885 nodes: Vec<Vec3>,
1887 boxes: Vec<CellBox>,
1889 tree: Vec<CellTreeNode>,
1891 node_boxes: Vec<CellBox>,
1895 node_margin: f64,
1897 scale: f64,
1899 resolution: f64,
1900}
1901
1902fn lattice_parameters(knots: &[f64], degree: usize, closed: bool) -> Vec<f64> {
1906 let [start, end] = crate::curve::knot_domain(knots, degree);
1907 let samples = if closed {
1908 8usize.max(degree * 4)
1909 } else {
1910 3usize.max(degree + 1)
1911 };
1912 let mut breaks = vec![start];
1913 breaks.extend(interior_knots(knots, degree));
1914 breaks.push(end);
1915 let mut parameters = Vec::with_capacity((breaks.len() - 1) * samples + 1);
1916 for pair in breaks.windows(2) {
1917 for index in 0..samples {
1918 parameters.push(pair[0] + (pair[1] - pair[0]) * index as f64 / samples as f64);
1919 }
1920 }
1921 parameters.push(end);
1922 parameters
1923}
1924
1925fn refine_to_lattice(net: &mut Vec<Vec<Vec4>>, knots: &mut Vec<f64>, degree: usize, parameters: &[f64]) {
1934 let p = degree;
1935 let n = net.len() - 1;
1936 let mut inserted = Vec::new();
1937 for ¶meter in parameters {
1938 let multiplicity = knots.iter().filter(|&&knot| knot == parameter).count();
1939 for _ in multiplicity..p {
1940 inserted.push(parameter);
1941 }
1942 }
1943 if inserted.is_empty() || p == 0 {
1944 return;
1945 }
1946 inserted.sort_by(f64::total_cmp);
1947 let find_span = |parameter: f64| -> usize {
1948 if parameter >= knots[n + 1] {
1949 return n;
1950 }
1951 (knots.partition_point(|&knot| knot <= parameter) - 1).clamp(p, n)
1952 };
1953 let r = inserted.len() - 1;
1954 let m = n + p + 1;
1955 let a = find_span(inserted[0]);
1956 let b = find_span(inserted[r]) + 1;
1957 let columns = net[0].len();
1958 let blank = vec![
1959 Vec4 {
1960 x: 0.0,
1961 y: 0.0,
1962 z: 0.0,
1963 w: 0.0,
1964 };
1965 columns
1966 ];
1967 let mut refined = vec![blank; n + r + 2];
1968 let mut refined_knots = vec![0.0; m + r + 2];
1969 for j in 0..=a - p {
1970 refined[j] = net[j].clone();
1971 }
1972 for j in b - 1..=n {
1973 refined[j + r + 1] = net[j].clone();
1974 }
1975 refined_knots[..=a].copy_from_slice(&knots[..=a]);
1976 for j in b + p..=m {
1977 refined_knots[j + r + 1] = knots[j];
1978 }
1979 let mut i = b + p - 1;
1980 let mut k = b + p + r;
1981 for j in (0..=r).rev() {
1982 while inserted[j] <= knots[i] && i > a {
1983 refined[k - p - 1] = net[i - p - 1].clone();
1984 refined_knots[k] = knots[i];
1985 k -= 1;
1986 i -= 1;
1987 }
1988 refined[k - p - 1] = refined[k - p].clone();
1989 for l in 1..=p {
1990 let index = k - p + l;
1991 let numerator = refined_knots[k + l] - inserted[j];
1992 if numerator == 0.0 {
1993 refined[index - 1] = refined[index].clone();
1994 } else {
1995 let alpha = numerator / (refined_knots[k + l] - knots[i - p + l]);
1996 let (head, tail) = refined.split_at_mut(index);
1997 for (before, &here) in head[index - 1].iter_mut().zip(&tail[0]) {
1998 *before = before.scale(alpha).add(here.scale(1.0 - alpha));
1999 }
2000 }
2001 }
2002 refined_knots[k] = inserted[j];
2003 k = k.saturating_sub(1);
2004 }
2005 *net = refined;
2006 *knots = refined_knots;
2007}
2008
2009fn supporting_range(knots: &[f64], degree: usize, count: usize, low: f64, high: f64) -> (usize, usize) {
2012 let first_span = knots.partition_point(|&knot| knot <= low).saturating_sub(1);
2013 let last_span = knots.partition_point(|&knot| knot < high).saturating_sub(1);
2014 (
2015 first_span.saturating_sub(degree).min(count - 1),
2016 last_span.max(first_span).min(count - 1),
2017 )
2018}
2019
2020fn unit_or(vector: Vec3, fallback: Vec3) -> Vec3 {
2021 let length = vector.length();
2022 if length > 0.0 && length.is_finite() {
2023 vector.scale(1.0 / length)
2024 } else {
2025 fallback
2026 }
2027}
2028
2029fn enclosing_sphere(a: (Vec3, f64), b: (Vec3, f64)) -> (Vec3, f64) {
2030 let offset = b.0.sub(a.0);
2031 let separation = offset.length();
2032 if separation + b.1 <= a.1 {
2033 return a;
2034 }
2035 if separation + a.1 <= b.1 {
2036 return b;
2037 }
2038 let radius = (separation + a.1 + b.1) * 0.5;
2039 let centre = a.0.add(offset.scale((radius - a.1) / separation));
2040 (centre, radius)
2041}
2042
2043struct NodeBoxInputs<'a> {
2047 boxes: &'a [CellBox],
2048 nodes: &'a [Vec3],
2049 lattice_columns: usize,
2050 margin: f64,
2051}
2052
2053fn enclosing_node_box(corners: [Vec3; 4], children: [&CellBox; 2], margin: f64) -> CellBox {
2058 let unbounded = || CellBox {
2059 axes: [Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 0.0, 1.0)],
2060 low: [f64::NEG_INFINITY; 3],
2061 high: [f64::INFINITY; 3],
2062 };
2063 let [c00, c10, c01, c11] = corners;
2064 let along_u = c10.sub(c00).add(c11.sub(c01));
2065 let along_v = c01.sub(c00).add(c11.sub(c10));
2066 let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2067 let Ok(fallback) = e1.perpendicular() else {
2068 return unbounded();
2069 };
2070 let normal = unit_or(e1.cross(along_v), fallback);
2071 let e2 = unit_or(normal.cross(e1), fallback);
2072 let e3 = e1.cross(e2);
2073 let axes = [e1, e2, e3];
2074 let mut low = [f64::INFINITY; 3];
2075 let mut high = [f64::NEG_INFINITY; 3];
2076 for child in children {
2077 for corner in 0..8 {
2078 let mut point = Vec3::default();
2079 for axis in 0..3 {
2080 let value = if corner >> axis & 1 == 0 { child.low[axis] } else { child.high[axis] };
2081 point = point.add(child.axes[axis].scale(value));
2082 }
2083 for axis in 0..3 {
2084 let coordinate = point.dot(axes[axis]);
2085 low[axis] = low[axis].min(coordinate);
2086 high[axis] = high[axis].max(coordinate);
2087 }
2088 }
2089 }
2090 for axis in 0..3 {
2091 low[axis] -= margin;
2092 high[axis] += margin;
2093 }
2094 if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2095 return unbounded();
2096 }
2097 CellBox { axes, low, high }
2098}
2099
2100fn build_cell_tree(
2101 tree: &mut Vec<CellTreeNode>,
2102 node_boxes: &mut Vec<CellBox>,
2103 inputs: &NodeBoxInputs<'_>,
2104 spheres: &[(Vec3, f64)],
2105 columns: usize,
2106 [row_low, row_high, column_low, column_high]: [usize; 4],
2107) -> u32 {
2108 if row_high - row_low == 1 && column_high - column_low == 1 {
2109 let cell = row_low * columns + column_low;
2110 node_boxes.push(inputs.boxes[cell].clone());
2111 tree.push(CellTreeNode {
2112 centre: spheres[cell].0,
2113 radius: spheres[cell].1,
2114 children: None,
2115 cell: cell as u32,
2116 });
2117 return (tree.len() - 1) as u32;
2118 }
2119 let (first, second) = if row_high - row_low >= column_high - column_low {
2120 let middle = (row_low + row_high) / 2;
2121 (
2122 [row_low, middle, column_low, column_high],
2123 [middle, row_high, column_low, column_high],
2124 )
2125 } else {
2126 let middle = (column_low + column_high) / 2;
2127 (
2128 [row_low, row_high, column_low, middle],
2129 [row_low, row_high, middle, column_high],
2130 )
2131 };
2132 let first = build_cell_tree(tree, node_boxes, inputs, spheres, columns, first);
2133 let second = build_cell_tree(tree, node_boxes, inputs, spheres, columns, second);
2134 let a = tree[first as usize];
2135 let b = tree[second as usize];
2136 let lattice = |row: usize, column: usize| inputs.nodes[row * inputs.lattice_columns + column];
2137 node_boxes.push(enclosing_node_box(
2138 [
2139 lattice(row_low, column_low),
2140 lattice(row_high, column_low),
2141 lattice(row_low, column_high),
2142 lattice(row_high, column_high),
2143 ],
2144 [&node_boxes[first as usize], &node_boxes[second as usize]],
2145 inputs.margin,
2146 ));
2147 let (centre, radius) = enclosing_sphere((a.centre, a.radius), (b.centre, b.radius));
2151 tree.push(CellTreeNode {
2152 centre,
2153 radius: radius * (1.0 + 4.0 * f64::EPSILON),
2154 children: Some((first, second)),
2155 cell: u32::MAX,
2156 });
2157 (tree.len() - 1) as u32
2158}
2159
2160fn projection_cells(surface: &NurbsSurface) -> Result<Option<&ProjectionCells>, String> {
2161 if let Some(cells) = surface.projection_cells.get() {
2162 return Ok(cells.as_ref());
2163 }
2164 let cells = build_projection_cells(surface)?;
2165 Ok(surface.projection_cells.get_or_init(|| cells).as_ref())
2166}
2167
2168fn build_projection_cells(surface: &NurbsSurface) -> Result<Option<ProjectionCells>, String> {
2169 let (closed_u, closed_v) = surface.closed_directions()?;
2170 let us = lattice_parameters(&surface.knots_u, surface.degree_u, closed_u);
2171 let vs = lattice_parameters(&surface.knots_v, surface.degree_v, closed_v);
2172 if us.len() < 2 || vs.len() < 2 {
2173 return Ok(None);
2174 }
2175 let mut scale = 0.0f64;
2176 for control in surface.control_points.iter().flatten() {
2177 let point = control.point()?;
2178 scale = scale.max(point.x.abs()).max(point.y.abs()).max(point.z.abs());
2179 }
2180 let resolution =
2181 ((surface.degree_u + 1) * (surface.degree_v + 1)) as f64 * f64::EPSILON * scale;
2182
2183 let mut net = surface.control_points.clone();
2185 let mut knots_u = surface.knots_u.clone();
2186 refine_to_lattice(&mut net, &mut knots_u, surface.degree_u, &us);
2187 let columns = net.first().map(Vec::len).unwrap_or(0);
2188 let mut transposed: Vec<Vec<Vec4>> =
2189 (0..columns).map(|column| net.iter().map(|row| row[column]).collect()).collect();
2190 let mut knots_v = surface.knots_v.clone();
2191 refine_to_lattice(&mut transposed, &mut knots_v, surface.degree_v, &vs);
2192 let rows = transposed.first().map(Vec::len).unwrap_or(0);
2193 let columns = transposed.len();
2194 if rows == 0 || columns == 0 {
2195 return Ok(None);
2196 }
2197 let mut points = vec![Vec3::default(); rows * columns];
2198 for (column, fibre) in transposed.iter().enumerate() {
2199 for (row, control) in fibre.iter().enumerate() {
2200 points[row * columns + column] = control.point()?;
2201 }
2202 }
2203
2204 let mut nodes = Vec::with_capacity(us.len() * vs.len());
2205 for &u in &us {
2206 for &v in &vs {
2207 nodes.push(surface.evaluate(u, v)?);
2208 }
2209 }
2210
2211 let cell_rows = us.len() - 1;
2212 let cell_columns = vs.len() - 1;
2213 let mut boxes = Vec::with_capacity(cell_rows * cell_columns);
2214 let mut spheres = Vec::with_capacity(cell_rows * cell_columns);
2215 for i in 0..cell_rows {
2216 let (row_low, row_high) =
2217 supporting_range(&knots_u, surface.degree_u, rows, us[i], us[i + 1]);
2218 for j in 0..cell_columns {
2219 let (column_low, column_high) =
2220 supporting_range(&knots_v, surface.degree_v, columns, vs[j], vs[j + 1]);
2221 let at = |row: usize, column: usize| points[row * columns + column];
2222 let c00 = at(row_low, column_low);
2223 let c10 = at(row_high, column_low);
2224 let c01 = at(row_low, column_high);
2225 let c11 = at(row_high, column_high);
2226 let along_u = c10.sub(c00).add(c11.sub(c01));
2227 let along_v = c01.sub(c00).add(c11.sub(c10));
2228 let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2229 let normal = unit_or(e1.cross(along_v), e1.perpendicular()?);
2230 let e2 = unit_or(normal.cross(e1), e1.perpendicular()?);
2231 let e3 = e1.cross(e2);
2232 let axes = [e1, e2, e3];
2233 let mut low = [f64::INFINITY; 3];
2234 let mut high = [f64::NEG_INFINITY; 3];
2235 for row in row_low..=row_high {
2236 for column in column_low..=column_high {
2237 let point = at(row, column);
2238 for axis in 0..3 {
2239 let coordinate = point.dot(axes[axis]);
2240 low[axis] = low[axis].min(coordinate);
2241 high[axis] = high[axis].max(coordinate);
2242 }
2243 }
2244 }
2245 for axis in 0..3 {
2246 low[axis] -= resolution;
2247 high[axis] += resolution;
2248 }
2249 let mut centre = Vec3::default();
2250 let mut half_diagonal_squared = 0.0;
2251 for axis in 0..3 {
2252 centre = centre.add(axes[axis].scale((low[axis] + high[axis]) * 0.5));
2253 let half = (high[axis] - low[axis]) * 0.5;
2254 half_diagonal_squared += half * half;
2255 }
2256 if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2257 return Ok(None);
2258 }
2259 spheres.push((centre, half_diagonal_squared.sqrt() + resolution));
2260 boxes.push(CellBox { axes, low, high });
2261 }
2262 }
2263 let mut tree = Vec::with_capacity(2 * boxes.len());
2264 let mut node_boxes = Vec::with_capacity(2 * boxes.len());
2265 let node_margin = NODE_BOX_MARGIN * scale;
2270 let inputs = NodeBoxInputs { boxes: &boxes, nodes: &nodes, lattice_columns: vs.len(), margin: node_margin };
2271 build_cell_tree(&mut tree, &mut node_boxes, &inputs, &spheres, cell_columns, [0, cell_rows, 0, cell_columns]);
2272 if !(node_margin > 0.0 && node_margin.is_finite()) {
2273 node_boxes = Vec::new();
2274 }
2275 Ok(Some(ProjectionCells {
2276 us,
2277 vs,
2278 nodes,
2279 boxes,
2280 tree,
2281 node_boxes,
2282 node_margin,
2283 scale,
2284 resolution,
2285 }))
2286}
2287
2288fn optimality(
2293 derivatives: &[[Vec3; 3]; 3],
2294 point: Vec3,
2295 (u, v): (f64, f64),
2296 [ua, ub, va, vb]: [f64; 4],
2297 periodic: (bool, bool),
2298) -> Optimality {
2299 let residual = derivatives[0][0].sub(point);
2300 let residual_length = residual.length();
2301 let su = derivatives[1][0];
2302 let sv = derivatives[0][1];
2303 let f = su.dot(residual);
2304 let g = sv.dot(residual);
2305 let metric_u = su.length_squared();
2306 let metric_v = sv.length_squared();
2307 let stationary_u = metric_u.sqrt() * residual_length <= EPSILON
2308 || f.abs() <= 1e-10 * metric_u.sqrt() * residual_length;
2309 let stationary_v = metric_v.sqrt() * residual_length <= EPSILON
2310 || g.abs() <= 1e-10 * metric_v.sqrt() * residual_length;
2311 let pinned_u = !periodic.0 && ((u <= ua && f > 0.0) || (u >= ub && f < 0.0));
2312 let pinned_v = !periodic.1 && ((v <= va && g > 0.0) || (v >= vb && g < 0.0));
2313 let j00 = derivatives[2][0].dot(residual) + metric_u;
2314 let j01 = derivatives[1][1].dot(residual) + su.dot(sv);
2315 let j11 = derivatives[0][2].dot(residual) + metric_v;
2316 let determinant = j00 * j11 - j01 * j01;
2317 let convex = match (!pinned_u, !pinned_v) {
2318 (true, true) => j00 > 0.0 && determinant > 0.0,
2319 (true, false) => j00 > 0.0,
2320 (false, true) => j11 > 0.0,
2321 (false, false) => true,
2322 };
2323 Optimality {
2324 residual_length,
2325 gradient: (f, g),
2326 metric: (metric_u, metric_v),
2327 hessian: (j00, j01, j11),
2328 determinant,
2329 pinned: (pinned_u, pinned_v),
2330 convex,
2331 minimum: residual_length <= LINEAR_TOLERANCE
2332 || ((stationary_u || pinned_u) && (stationary_v || pinned_v) && convex),
2333 }
2334}
2335
2336struct Optimality {
2337 residual_length: f64,
2338 gradient: (f64, f64),
2339 metric: (f64, f64),
2340 hessian: (f64, f64, f64),
2341 determinant: f64,
2342 pinned: (bool, bool),
2343 convex: bool,
2344 minimum: bool,
2345}
2346
2347fn is_verified_minimum(
2348 surface: &NurbsSurface,
2349 point: Vec3,
2350 at: (f64, f64),
2351 rectangle: [f64; 4],
2352 periodic: (bool, bool),
2353) -> Result<bool, String> {
2354 let derivatives = surface.derivatives_small(at.0, at.1, 2)?;
2355 Ok(optimality(&derivatives, point, at, rectangle, periodic).minimum)
2356}
2357
2358fn confined_descent(
2374 surface: &NurbsSurface,
2375 point: Vec3,
2376 seed: (f64, f64),
2377 rectangle: [f64; 4],
2378 periodic: (bool, bool),
2379) -> Result<(NewtonResult, bool), String> {
2380 let [ua, ub, va, vb] = rectangle;
2381 let mut u = fit_parameter(seed.0, ua, ub, periodic.0);
2382 let mut v = fit_parameter(seed.1, va, vb, periodic.1);
2383 let mut converged = false;
2384 let mut current = surface.evaluate(u, v)?.sub(point).length_squared();
2385 for _ in 0..MAX_NEWTON_ITERATIONS {
2386 let derivatives = surface.derivatives_small(u, v, 2)?;
2387 let state = optimality(&derivatives, point, (u, v), rectangle, periodic);
2388 current = state.residual_length * state.residual_length;
2389 if state.minimum {
2390 converged = true;
2391 break;
2392 }
2393 let (f, g) = state.gradient;
2394 let (metric_u, metric_v) = state.metric;
2395 let (j00, j01, j11) = state.hessian;
2396 let determinant = state.determinant;
2397 let (free_u, free_v) = (!state.pinned.0, !state.pinned.1);
2398 let (mut du, mut dv) = match (free_u, free_v) {
2399 (true, true) if state.convex => (
2400 (-f * j11 + g * j01) / determinant,
2401 (-g * j00 + f * j01) / determinant,
2402 ),
2403 (true, false) if state.convex => (-f / j00, 0.0),
2404 (false, true) if state.convex => (0.0, -g / j11),
2405 _ => (
2406 if free_u && metric_u > 0.0 { -f / metric_u } else { 0.0 },
2407 if free_v && metric_v > 0.0 { -g / metric_v } else { 0.0 },
2408 ),
2409 };
2410 if !(du.is_finite() && dv.is_finite()) || (du == 0.0 && dv == 0.0) {
2411 break;
2412 }
2413 let mut moved = false;
2414 let taken = |next: f64, here: f64, low: f64, high: f64, wraps: bool| {
2416 let raw = next - here;
2417 if wraps {
2418 raw - (high - low) * (raw / (high - low)).round()
2419 } else {
2420 raw
2421 }
2422 };
2423 for _ in 0..40 {
2424 let next_u = fit_parameter(u + du, ua, ub, periodic.0);
2425 let next_v = fit_parameter(v + dv, va, vb, periodic.1);
2426 if next_u == u && next_v == v {
2427 break;
2428 }
2429 let trial = surface.evaluate(next_u, next_v)?.sub(point).length_squared();
2430 if trial <= current {
2431 moved = taken(next_u, u, ua, ub, periodic.0).abs() > 1e-15 * (ub - ua)
2432 || taken(next_v, v, va, vb, periodic.1).abs() > 1e-15 * (vb - va);
2433 u = next_u;
2434 v = next_v;
2435 current = trial;
2436 break;
2437 }
2438 du *= 0.5;
2439 dv *= 0.5;
2440 }
2441 if !moved {
2442 break;
2443 }
2444 }
2445 let result = NewtonResult {
2446 u,
2447 v,
2448 distance_squared: current,
2449 converged,
2450 };
2451 let on_edge =
2452 (!periodic.0 && (u <= ua || u >= ub)) || (!periodic.1 && (v <= va || v >= vb));
2453 Ok((result, on_edge))
2454}
2455
2456const NODE_BOX_MARGIN: f64 = 1e-9;
2459
2460fn node_boxes_enabled() -> bool {
2464 switch!("BREP_PROJECTION_NODE_BOXES", true)
2465}
2466
2467fn hull_candidates(cells: &ProjectionCells, point: Vec3, bound: f64, node_boxes: bool) -> (Vec<(f64, usize)>, f64) {
2488 let read_error = 32.0 * f64::EPSILON * (point.x.abs() + point.y.abs() + point.z.abs() + 4.0 * cells.scale);
2489 let boxes = node_boxes && !cells.node_boxes.is_empty() && 4.0 * read_error <= cells.node_margin;
2490 let mut candidates: Vec<(f64, usize)> = Vec::new();
2491 let mut excluded = f64::INFINITY;
2492 let mut stack: Vec<u32> = Vec::with_capacity(64);
2493 stack.push((cells.tree.len() - 1) as u32);
2494 while let Some(index) = stack.pop() {
2495 let node = cells.tree[index as usize];
2496 let sphere_bound = (point.sub(node.centre).length() - node.radius).max(0.0);
2497 if sphere_bound >= bound {
2498 excluded = excluded.min(sphere_bound);
2499 continue;
2500 }
2501 match node.children {
2502 Some((first, second)) => {
2503 if boxes {
2504 let box_bound = cells.node_boxes[index as usize].lower_bound(point);
2505 if box_bound >= bound && box_bound > 2.0 * read_error {
2506 excluded = excluded.min(box_bound);
2507 continue;
2508 }
2509 }
2510 stack.push(first);
2511 stack.push(second);
2512 }
2513 None => {
2514 let cell = node.cell as usize;
2515 let box_bound = cells.boxes[cell].lower_bound(point);
2516 if box_bound < bound {
2517 candidates.push((box_bound, cell));
2518 } else {
2519 excluded = excluded.min(box_bound);
2520 }
2521 }
2522 }
2523 }
2524 (candidates, excluded)
2525}
2526
2527#[allow(clippy::too_many_arguments)]
2530fn global_minimum(
2531 surface: &NurbsSurface,
2532 point: Vec3,
2533 domains: [f64; 4],
2534 periodic: (bool, bool),
2535 best: &mut NewtonResult,
2536 stats: &mut GlobalStats,
2537) -> Result<(), String> {
2538 if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
2539 stats.settled_by_floor = true;
2540 return Ok(());
2541 }
2542 let Some(cells) = projection_cells(surface)? else {
2543 return Ok(());
2544 };
2545 let resolution = cells.resolution;
2546 let columns = cells.vs.len() - 1;
2547 let columns_u = cells.us.len() - 1;
2548 let mut bound = best.distance_squared.sqrt() - resolution;
2549
2550 let (mut candidates, excluded) = hull_candidates(cells, point, bound, node_boxes_enabled());
2553 stats.candidates = candidates.len();
2554 candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
2555 stats.hull_lower_bound = candidates
2556 .first()
2557 .map_or(excluded, |&(least, _)| least.min(excluded));
2558
2559 let cell_of = |u: f64, v: f64| {
2565 let row = (cells.us.partition_point(|&value| value <= u).max(1) - 1).min(columns_u - 1);
2566 let column = (cells.vs.partition_point(|&value| value <= v).max(1) - 1).min(columns - 1);
2567 row * columns + column
2568 };
2569 let mut settled: Vec<usize> = Vec::new();
2570 if is_verified_minimum(surface, point, (best.u, best.v), domains, periodic)? {
2571 settled.push(cell_of(best.u, best.v));
2572 }
2573 for (cell_bound, cell) in candidates {
2574 if cell_bound >= bound {
2575 break;
2576 }
2577 let row = cell / columns;
2578 let column = cell % columns;
2579 let rectangle = [
2580 cells.us[row],
2581 cells.us[row + 1],
2582 cells.vs[column],
2583 cells.vs[column + 1],
2584 ];
2585 if settled.contains(&cell) {
2586 continue;
2587 }
2588 let mut seed = (rectangle[0], rectangle[2]);
2589 let mut seed_distance = f64::INFINITY;
2590 for (node_row, node_column) in
2591 [(row, column), (row + 1, column), (row, column + 1), (row + 1, column + 1)]
2592 {
2593 let distance = cells.nodes[node_row * cells.vs.len() + node_column]
2594 .sub(point)
2595 .length_squared();
2596 if distance < seed_distance {
2597 seed_distance = distance;
2598 seed = (cells.us[node_row], cells.vs[node_column]);
2599 }
2600 }
2601 stats.refinements += 1;
2602 let (confined, on_edge) = confined_descent(surface, point, seed, rectangle, (false, false))?;
2603 let mut found = confined;
2604 if on_edge && confined.distance_squared.sqrt() < bound {
2605 stats.continuations += 1;
2608 let (continued, _) =
2609 confined_descent(surface, point, (confined.u, confined.v), domains, periodic)?;
2610 if continued.distance_squared < found.distance_squared {
2611 found = continued;
2612 }
2613 if continued.converged {
2614 settled.push(cell_of(continued.u, continued.v));
2615 }
2616 }
2617 if found.distance_squared.sqrt() < bound {
2618 *best = found;
2619 bound = best.distance_squared.sqrt() - resolution;
2620 stats.replaced = true;
2621 if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
2622 return Ok(());
2623 }
2624 }
2625 }
2626 Ok(())
2627}
2628
2629
2630
2631#[derive(Clone, Copy)]
2633pub enum FootDomain {
2634 Clamp,
2635 Wrap,
2636 Extended,
2637}
2638
2639#[derive(Clone, Copy)]
2640pub struct CurveFootPolicy {
2641 pub domain: FootDomain,
2642 pub iterations: usize,
2643 pub slope_guard: f64,
2644 pub step_limit: f64,
2645 pub parameter_tolerance: f64,
2646 pub mode: FootMode,
2647}
2648
2649#[derive(Clone, Copy)]
2651pub enum FootMode {
2652 Monotone,
2653 Witness,
2654 Stationary { positive_slope: bool, relative_step: bool },
2655 Backtracked,
2656 Planar,
2657}
2658
2659fn curve_foot_newton_state(
2662 curve: &NurbsCurve,
2663 point: Vec3,
2664 seed: f64,
2665 bracket: [f64; 2],
2666 policy: CurveFootPolicy,
2667) -> Result<(f64, f64, f64), String> {
2668 let fit = |u| match policy.domain {
2669 FootDomain::Clamp => fit_parameter(u, bracket[0], bracket[1], false),
2670 FootDomain::Wrap => fit_parameter(u, bracket[0], bracket[1], true),
2671 FootDomain::Extended => u,
2672 };
2673 let extended = matches!(policy.domain, FootDomain::Extended) || matches!(policy.mode, FootMode::Backtracked);
2674 let planar = matches!(policy.mode, FootMode::Planar);
2675 let project = |p: Vec3| if planar { Vec3::new(p.x, p.y, 0.0) } else { p };
2676 let point = project(point);
2677 let distance = |u| -> Result<f64, String> {
2678 let p = if extended { curve.derivatives_extended(u, 0)?[0] } else { curve.evaluate(u)? };
2679 Ok(project(p).sub(point).length())
2680 };
2681 let monotone = matches!(policy.mode, FootMode::Monotone | FootMode::Backtracked);
2682 let witness = matches!(policy.mode, FootMode::Witness);
2683 let mut u = if witness { seed } else { fit(seed) };
2684 let mut nearest_u = seed;
2685 let mut nearest_squared = f64::INFINITY;
2686 let mut best = if monotone { distance(u)? } else { f64::INFINITY };
2687 for _ in 0..policy.iterations {
2688 let derivatives = if extended {
2689 let values = curve.derivatives_extended(u, 2)?;
2690 [values[0], values[1], values[2]]
2691 } else if matches!(policy.mode, FootMode::Stationary { .. })
2692 || (planar && !crate::curve::small_curve_derivatives_enabled()) {
2693 let values = curve.derivatives(u, 2)?;
2694 [values[0], values[1], values[2]]
2695 } else {
2696 curve.derivatives_small(u, 2)?
2697 }.map(project);
2698 let offset = derivatives[0].sub(point);
2699 let numerator = offset.dot(derivatives[1]);
2700 let denominator = derivatives[1].dot(derivatives[1]) + offset.dot(derivatives[2]);
2701 if witness {
2702 let squared = offset.length_squared();
2703 if squared < nearest_squared {
2704 nearest_u = u;
2705 nearest_squared = squared;
2706 }
2707 let residual_length = squared.sqrt();
2708 if residual_length <= LINEAR_TOLERANCE
2709 || numerator.abs() <= EPSILON + 1e-10 * derivatives[1].length() * residual_length {
2710 break;
2711 }
2712 }
2713 let singular = if planar { denominator.abs() < policy.slope_guard }
2714 else { denominator.abs() <= policy.slope_guard };
2715 if singular || (matches!(policy.mode, FootMode::Stationary { positive_slope: true, .. }) && !(denominator > 0.0)) { break; }
2716 let mut step = if matches!(policy.mode, FootMode::Backtracked) && !(denominator > 0.0) {
2717 policy.step_limit.copysign(numerator)
2718 } else {
2719 (numerator / denominator).clamp(-policy.step_limit, policy.step_limit)
2720 };
2721 let mut next = fit(u - step);
2722 let mut next_distance = if monotone { distance(next)? } else { f64::INFINITY };
2723 if matches!(policy.mode, FootMode::Backtracked) {
2724 for _ in 0..30 {
2725 if next_distance < best { break; }
2726 step *= 0.5;
2727 next = fit(u - step);
2728 next_distance = distance(next)?;
2729 }
2730 if !(next_distance < best) { break; }
2731 } else if monotone && next_distance >= best { break; }
2732 let moved = if planar || matches!(policy.domain, FootDomain::Extended) { step }
2733 else if matches!(policy.domain, FootDomain::Wrap) {
2734 let period = bracket[1] - bracket[0];
2735 let raw = next - u;
2736 raw - period * (raw / period).round()
2737 } else { next - u };
2738 let tolerance = if matches!(policy.mode, FootMode::Stationary { relative_step: true, .. }) {
2739 policy.parameter_tolerance * (1.0 + u.abs())
2740 } else { policy.parameter_tolerance };
2741 let small = if planar || matches!(policy.mode, FootMode::Backtracked) { moved.abs() < tolerance }
2742 else { moved.abs() <= tolerance };
2743 if small && matches!(policy.mode, FootMode::Monotone) { break; }
2744 u = next;
2745 best = next_distance;
2746 if small { break; }
2747 }
2748 if witness { return Ok((u, nearest_u, nearest_squared)); }
2749 if !monotone { best = distance(u)?; }
2750 Ok((u, u, best * best))
2751}
2752
2753pub fn curve_foot_newton(
2754 curve: &NurbsCurve, point: Vec3, seed: f64, bracket: [f64; 2], policy: CurveFootPolicy,
2755) -> Result<(f64, f64), String> {
2756 let (_, nearest, squared) = curve_foot_newton_state(curve, point, seed, bracket, policy)?;
2757 Ok((nearest, squared))
2758}
2759
2760
2761