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<Vec<(f64, Vec3)>>;
181const CURVE_SEED_BUDGET: usize = 262_144;
182thread_local! {
183 static CURVE_SEEDS: std::cell::RefCell<(rustc_hash::FxHashMap<[u64; 2], CurveSeeds>, usize)> = Default::default();
184}
185
186pub fn clear_curve_seed_cache() {
188 CURVE_SEEDS.with(|memo| *memo.borrow_mut() = Default::default());
189}
190
191fn visit_curve_seeds(curve: &NurbsCurve, start: f64, end: f64, mut visit: impl FnMut(f64, Vec3)) -> Result<(), String> {
192 let mut breaks = vec![start];
193 breaks.extend(interior_knots(&curve.knots, curve.degree));
194 breaks.push(end);
195 let samples_per_span = 4usize.max(curve.degree + 2);
196 for pair in breaks.windows(2) {
197 for index in 0..=samples_per_span {
198 let parameter = pair[0] + (pair[1] - pair[0]) * index as f64 / samples_per_span as f64;
199 visit(parameter, curve.evaluate(parameter)?);
200 }
201 }
202 Ok(())
203}
204
205fn cached_curve_seeds(curve: &NurbsCurve, start: f64, end: f64) -> Result<Option<CurveSeeds>, String> {
210 if !switch!("BREP_CURVE_PROJECTION_SEEDS", false) { return Ok(None); }
211 let bound = curve.knots.len().saturating_add(1).saturating_mul(4usize.max(curve.degree + 2).saturating_add(1));
213 if bound > CURVE_SEED_BUDGET { return Ok(None); }
214 let mut key = crate::identity_hash::TwoLane::new();
215 crate::identity_hash::hash_curve(&mut key, curve);
216 key.f64(start); key.f64(end);
217 let key = key.finish();
218 if let Some(seeds) = CURVE_SEEDS.with(|memo| memo.borrow().0.get(&key).cloned()) {
219 return Ok(Some(seeds));
220 }
221 let mut seeds = Vec::new();
222 visit_curve_seeds(curve, start, end, |u, point| seeds.push((u, point)))?;
223 let seeds = std::rc::Rc::new(seeds);
224 CURVE_SEEDS.with(|memo| {
225 let mut memo = memo.borrow_mut();
226 if memo.0.len() >= PROJECTION_MEMO_ENTRIES || memo.1 + seeds.len() > CURVE_SEED_BUDGET {
227 memo.0.clear(); memo.1 = 0;
228 }
229 memo.1 += seeds.len();
230 memo.0.insert(key, seeds.clone());
231 });
232 Ok(Some(seeds))
233}
234
235fn project_point_to_curve_uncached(curve: &NurbsCurve, point: Vec3) -> Result<CurveProjection, String> {
236 let [start, end] = curve.domain()?;
237 let mut best_u = start;
238 let mut best_distance_squared = f64::INFINITY;
239 let mut start_point = None;
244 let mut end_point = None;
245 let mut previous: Option<(f64, Vec3)> = None;
248 let mut witness_distance_squared = f64::INFINITY;
249 let mut witness_low = start;
250 let mut witness_high = start;
251 let mut visit = |parameter, sample: Vec3| {
252 if start_point.is_none() {
253 start_point = Some(sample);
254 }
255 end_point = Some(sample);
256 let distance_squared = sample.sub(point).length_squared();
257 if distance_squared < best_distance_squared {
258 best_distance_squared = distance_squared;
259 best_u = parameter;
260 }
261 if let Some((previous_parameter, previous_sample)) = previous {
262 let segment = point_segment_distance_squared(point, previous_sample, sample);
263 if segment < witness_distance_squared {
264 witness_distance_squared = segment;
265 witness_low = previous_parameter;
266 witness_high = parameter;
267 }
268 }
269 previous = Some((parameter, sample));
270 };
271 if let Some(seeds) = cached_curve_seeds(curve, start, end)? {
272 for &(parameter, sample) in seeds.iter() { visit(parameter, sample); }
273 } else {
274 visit_curve_seeds(curve, start, end, visit)?;
275 }
276 const CLOSED_SEAM_TOLERANCE: f64 = 1e-6;
289 let closed = match (start_point, end_point) {
290 (Some(first), Some(last)) => first.sub(last).length() <= CLOSED_SEAM_TOLERANCE,
291 _ => false,
292 };
293
294 let parameter = curve_newton(
295 curve,
296 point,
297 best_u,
298 start,
299 end,
300 closed,
301 &mut best_u,
302 &mut best_distance_squared,
303 )?;
304 for candidate in [start, end, parameter] {
305 let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
306 if distance_squared < best_distance_squared {
307 best_distance_squared = distance_squared;
308 best_u = candidate;
309 }
310 }
311 const WITNESS_FACTOR: f64 = 2.0;
343 if witness_distance_squared * (WITNESS_FACTOR * WITNESS_FACTOR) < best_distance_squared
344 && witness_rescue_enabled()
345 {
346 let bracketed = bracketed_nearest(curve, point, witness_low, witness_high)?;
347 let polished = curve_newton(
348 curve,
349 point,
350 bracketed,
351 start,
352 end,
353 closed,
354 &mut best_u,
355 &mut best_distance_squared,
356 )?;
357 for candidate in [bracketed, polished] {
358 let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
359 if distance_squared < best_distance_squared {
360 best_distance_squared = distance_squared;
361 best_u = candidate;
362 }
363 }
364 }
365 let projected = curve.evaluate(best_u)?;
366 Ok(CurveProjection {
367 u: best_u,
368 point: projected,
369 distance: projected.sub(point).length(),
370 })
371}
372
373fn project_linear_revolution(
374 surface: &NurbsSurface,
375 point: Vec3,
376) -> Result<Option<SurfaceProjection>, String> {
377 let rows = &surface.control_points;
378 if surface.degree_u != 2
379 || surface.degree_v != 1
380 || rows.len() < 5
381 || rows[0].len() != 2
382 || !surface.closed_directions()?.0
383 {
384 return Ok(None);
385 }
386 let base = rows[0][0].point()?.add(rows[4][0].point()?).scale(0.5);
387 let top = rows[0][1].point()?.add(rows[4][1].point()?).scale(0.5);
388 let axis_vector = top.sub(base);
389 let height = axis_vector.length();
390 if height <= EPSILON {
391 return Ok(None);
392 }
393 let axis = axis_vector.normalized()?;
394 let [v0, v1] = surface.domain_v()?;
395 let axial = point.sub(base).dot(axis).clamp(0.0, height);
396 let v = v0 + (v1 - v0) * axial / height;
397 let circle = surface.iso_curve_v(v)?;
398 let projection = project_point_to_curve(&circle, point)?;
399 let [u0, u1] = surface.domain_u()?;
400 let u = projection.u.clamp(u0, u1);
401 let projected = surface.evaluate(u, v)?;
402 Ok(Some(SurfaceProjection {
403 u,
404 v,
405 point: projected,
406 distance: projected.sub(point).length(),
407 }))
408}
409
410#[derive(Clone, Copy)]
411struct NewtonResult {
412 u: f64,
413 v: f64,
414 distance_squared: f64,
415 converged: bool,
416}
417
418fn surface_newton(
419 surface: &NurbsSurface,
420 point: Vec3,
421 seed_u: f64,
422 seed_v: f64,
423 domains: [f64; 4],
424 closed_u: bool,
425 closed_v: bool,
426) -> Result<NewtonResult, String> {
427 surface_newton_impl(surface, point, seed_u, seed_v, domains, closed_u, closed_v,
428 switch!("BREP_PROJECTION_LAZY_DERIVATIVES", false), LINEAR_TOLERANCE)
429}
430
431fn surface_newton_impl(
436 surface: &NurbsSurface,
437 point: Vec3,
438 seed_u: f64,
439 seed_v: f64,
440 domains: [f64; 4],
441 closed_u: bool,
442 closed_v: bool,
443 lazy: bool,
444 linear_tolerance: f64,
445) -> Result<NewtonResult, String> {
446 let [u0, u1, v0, v1] = domains;
447 let mut u = seed_u;
448 let mut v = seed_v;
449 let mut converged = false;
450 let mut best = NewtonResult {
451 u,
452 v,
453 distance_squared: surface.evaluate(u, v)?.sub(point).length_squared(),
454 converged,
455 };
456 let cycle_exit = switch!("BREP_PROJECTION_NEWTON_CYCLE_EXIT", true);
468 let mut trail = [(0u64, 0u64); MAX_NEWTON_ITERATIONS];
469 for iteration in 0..MAX_NEWTON_ITERATIONS {
470 if cycle_exit {
471 let state = (u.to_bits(), v.to_bits());
472 if let Some(first) = trail[..iteration].iter().position(|earlier| *earlier == state) {
473 let period = iteration - first;
474 let (last_u, last_v) = trail[first + (MAX_NEWTON_ITERATIONS - first) % period];
475 u = f64::from_bits(last_u);
476 v = f64::from_bits(last_v);
477 crate::work_counts::add(|c| c.newton_iterations += (MAX_NEWTON_ITERATIONS - iteration) as u64);
478 break;
479 }
480 trail[iteration] = state;
481 }
482 crate::work_counts::add(|c| c.newton_iterations += 1);
483 let derivatives = surface.derivatives_small(u, v, if lazy { 0 } else { 2 })?;
484 let residual = derivatives[0][0].sub(point);
485 let distance_squared = residual.length_squared();
486 if distance_squared < best.distance_squared {
487 best.u = u;
488 best.v = v;
489 best.distance_squared = distance_squared;
490 }
491 let residual_length = distance_squared.sqrt();
492 if residual_length <= linear_tolerance {
493 crate::work_counts::add(|c| { c.newton_unused += 1; c.newton_unused_first += u64::from(iteration == 0); });
494 converged = true;
495 break;
496 }
497 let derivatives = if lazy { surface.derivatives_small(u, v, 2)? } else { derivatives };
498 let f = derivatives[1][0].dot(residual);
499 let g = derivatives[0][1].dot(residual);
500 let tangent_u_length = derivatives[1][0].length();
501 let tangent_v_length = derivatives[0][1].length();
502 let cosine_u = if tangent_u_length * residual_length <= EPSILON {
503 0.0
504 } else {
505 f.abs() / (tangent_u_length * residual_length)
506 };
507 let cosine_v = if tangent_v_length * residual_length <= EPSILON {
508 0.0
509 } else {
510 g.abs() / (tangent_v_length * residual_length)
511 };
512 if cosine_u <= 1e-10 && cosine_v <= 1e-10 {
513 converged = true;
514 break;
515 }
516 let j00 = derivatives[2][0].dot(residual) + derivatives[1][0].length_squared();
517 let j01 = derivatives[1][1].dot(residual) + derivatives[1][0].dot(derivatives[0][1]);
518 let j11 = derivatives[0][2].dot(residual) + derivatives[0][1].length_squared();
519 let determinant = j00 * j11 - j01 * j01;
520 if determinant.abs() <= EPSILON {
521 break;
522 }
523 let mut du = (-f * j11 + g * j01) / determinant;
524 let mut dv = (-g * j00 + f * j01) / determinant;
525 du = du.clamp(-(u1 - u0) / 4.0, (u1 - u0) / 4.0);
526 dv = dv.clamp(-(v1 - v0) / 4.0, (v1 - v0) / 4.0);
527 let next_u = fit_parameter(u + du, u0, u1, closed_u);
528 let next_v = fit_parameter(v + dv, v0, v1, closed_v);
529 let stalled =
530 (next_u - u).abs() <= 1e-15 * (u1 - u0) && (next_v - v).abs() <= 1e-15 * (v1 - v0);
531 u = next_u;
532 v = next_v;
533 if stalled {
534 break;
535 }
536 }
537 let final_distance_squared = surface.evaluate(u, v)?.sub(point).length_squared();
538 if final_distance_squared < best.distance_squared {
539 best.u = u;
540 best.v = v;
541 best.distance_squared = final_distance_squared;
542 }
543 best.converged = converged;
544 Ok(best)
545}
546
547pub fn refine_trim_foot(
551 surface: &NurbsSurface, point: Vec3, foot: SurfaceProjection,
552) -> Result<SurfaceProjection, String> {
553 let [u0, u1] = surface.domain_u()?;
554 let [v0, v1] = surface.domain_v()?;
555 let (cu, cv) = surface.closed_directions()?;
556 let result = surface_newton_impl(surface, point, foot.u, foot.v,
557 [u0, u1, v0, v1], cu, cv, false, 1e-11)?;
558 let projected = surface.evaluate(result.u, result.v)?;
559 Ok(SurfaceProjection { u: result.u, v: result.v, point: projected,
560 distance: projected.sub(point).length() })
561}
562
563#[track_caller]
569pub fn project_point_to_surface(
570 surface: &NurbsSurface,
571 point: Vec3,
572) -> Result<SurfaceProjection, String> {
573 crate::work_counts::add(|c| c.projection_global += 1);
574 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_PROJECT, surface);
575 if let Some(analytic) = surface.analytic() {
579 if let Some(projection) = analytic.project(surface, point) {
580 return Ok(projection);
581 }
582 }
583 if let Some(ellipsoid) = surface.affine_sphere() {
584 if let Some(projection) = ellipsoid.project(surface, point) {
585 return Ok(projection);
586 }
587 }
588 project_point_to_surface_general(surface, point)
589}
590
591pub fn project_point_to_surface_seeded(
601 surface: &NurbsSurface,
602 point: Vec3,
603 seed_u: f64,
604 seed_v: f64,
605) -> Result<SurfaceProjection, String> {
606 crate::work_counts::add(|c| c.projection_seeded += 1);
607 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
608 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_SEEDED, surface);
609 if let Some(ellipsoid) = surface.affine_sphere() {
613 if let Some(projection) = ellipsoid.project(surface, point) {
614 return Ok(projection);
615 }
616 }
617 let [u0, u1] = surface.domain_u()?;
618 let [v0, v1] = surface.domain_v()?;
619 let (closed_u, closed_v) = surface.closed_directions()?;
620 let result = surface_newton(
621 surface,
622 point,
623 seed_u,
624 seed_v,
625 [u0, u1, v0, v1],
626 closed_u,
627 closed_v,
628 )?;
629 let projected = surface.evaluate(result.u, result.v)?;
630 Ok(SurfaceProjection {
631 u: result.u,
632 v: result.v,
633 point: projected,
634 distance: projected.sub(point).length(),
635 })
636}
637
638#[track_caller]
672pub fn project_point_to_surface_from_seed(
673 surface: &NurbsSurface,
674 point: Vec3,
675 seed: [f64; 2],
676) -> Result<SurfaceProjection, String> {
677 crate::work_counts::add(|c| c.projection_from_seed += 1);
678 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
679 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_SEED, surface);
680 if let Some(analytic) = surface.analytic() {
681 if let Some(projection) = analytic.project(surface, point) {
682 return Ok(projection);
683 }
684 }
685 if let Some(ellipsoid) = surface.affine_sphere() {
686 if let Some(projection) = ellipsoid.project(surface, point) {
687 return Ok(projection);
688 }
689 }
690 let caller = std::panic::Location::caller();
691 if !seeded_answer_admitted(caller) {
692 return project_point_to_surface_general(surface, point);
693 }
694 let seeded = project_point_to_surface_seeded(surface, point, seed[0], seed[1])?;
695 if seed_audit_enabled() {
696 let nearest = project_point_to_surface_general(surface, point)?;
697 if seeded.point.sub(nearest.point).length() > LINEAR_TOLERANCE {
698 seed_audit_record(caller, surface, seed, &seeded, &nearest);
699 }
700 }
701 Ok(seeded)
702}
703
704fn seeded_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
707 static SITES: std::sync::OnceLock<Option<Option<Vec<String>>>> = std::sync::OnceLock::new();
708 let sites = SITES.get_or_init(|| {
709 if std::env::var("BREP_PROJECTION_FROM_SEED").as_deref() == Ok("0") {
710 return None;
711 }
712 Some(std::env::var("BREP_PROJECTION_FROM_SEED_SITES").ok().map(|value| {
713 value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect()
714 }))
715 });
716 match sites {
717 None => false,
718 Some(None) => true,
719 Some(Some(only)) => {
720 let location = format!("{}:{}", caller.file(), caller.line());
721 only.iter().any(|site| location.contains(site.as_str()))
722 }
723 }
724}
725
726fn seed_audit_enabled() -> bool {
727 debug_flag!("BREP_PROJECTION_AUDIT")
728}
729
730fn seed_audit_record(
734 caller: &std::panic::Location<'_>,
735 surface: &NurbsSurface,
736 seed: [f64; 2],
737 seeded: &SurfaceProjection,
738 nearest: &SurfaceProjection,
739) {
740 use std::io::Write;
741 static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
742 std::sync::OnceLock::new();
743 let sink = SINK.get_or_init(|| {
744 let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
745 let path = std::path::Path::new(&directory)
746 .join(format!("projection-seed-audit-{}.tsv", std::process::id()));
747 std::fs::OpenOptions::new()
748 .create(true)
749 .append(true)
750 .open(path)
751 .ok()
752 .map(std::sync::Mutex::new)
753 });
754 if let Some(file) = sink {
755 if let Ok(mut file) = file.lock() {
756 let _ = writeln!(
757 file,
758 "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.6e}\t{}x{} cp {}x{}",
759 caller.file(),
760 caller.line(),
761 seeded.distance,
762 nearest.distance,
763 seed[0],
764 seed[1],
765 seeded.u,
766 seeded.v,
767 nearest.u,
768 nearest.v,
769 seeded.point.sub(nearest.point).length(),
770 surface.degree_u,
771 surface.degree_v,
772 surface.control_points.len(),
773 surface.control_points.first().map(Vec::len).unwrap_or(0),
774 );
775 }
776 }
777}
778
779fn projection_seed_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
784 if let Some(grid) = surface.projection_grid.get() {
785 return Ok(grid);
786 }
787 let [u0, u1] = surface.domain_u()?;
788 let [v0, v1] = surface.domain_v()?;
789 let (closed_u, closed_v) = surface.closed_directions()?;
790 let mut breaks_u = vec![u0];
791 breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
792 breaks_u.push(u1);
793 let mut breaks_v = vec![v0];
794 breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
795 breaks_v.push(v1);
796 let samples_u = if closed_u {
797 8usize.max(surface.degree_u * 4)
798 } else {
799 3usize.max(surface.degree_u + 1)
800 };
801 let samples_v = if closed_v {
802 8usize.max(surface.degree_v * 4)
803 } else {
804 3usize.max(surface.degree_v + 1)
805 };
806 let mut grid = Vec::new();
807 for u_pair in breaks_u.windows(2) {
808 for v_pair in breaks_v.windows(2) {
809 for i in 0..=samples_u {
810 for j in 0..=samples_v {
811 let u = u_pair[0] + (u_pair[1] - u_pair[0]) * i as f64 / samples_u as f64;
812 let v = v_pair[0] + (v_pair[1] - v_pair[0]) * j as f64 / samples_v as f64;
813 grid.push((u, v, surface.evaluate(u, v)?));
814 }
815 }
816 }
817 }
818 Ok(surface.projection_grid.get_or_init(|| SampleGrid::new(grid)))
819}
820
821fn projection_dense_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
828 if let Some(grid) = surface.projection_dense_grid.get() {
829 return Ok(grid);
830 }
831 let [u0, u1] = surface.domain_u()?;
832 let [v0, v1] = surface.domain_v()?;
833 let mut breaks_u = vec![u0];
834 breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
835 breaks_u.push(u1);
836 let mut breaks_v = vec![v0];
837 breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
838 breaks_v.push(v1);
839 let count_u = 32usize.max((breaks_u.len() - 1) * 8);
840 let count_v = 16usize.max((breaks_v.len() - 1) * 8);
841 let mut grid = Vec::with_capacity((count_u + 1) * (count_v + 1));
842 for i in 0..=count_u {
843 for j in 0..=count_v {
844 let u = u0 + (u1 - u0) * i as f64 / count_u as f64;
845 let v = v0 + (v1 - v0) * j as f64 / count_v as f64;
846 grid.push((u, v, surface.evaluate(u, v)?));
847 }
848 }
849 Ok(surface.projection_dense_grid.get_or_init(|| SampleGrid::with_tree(grid)))
850}
851
852const SAMPLE_BLOCK: usize = 32;
854
855const GROUP_BLOCKS: usize = 32;
858
859#[derive(Clone, Debug)]
864pub struct SampleGrid {
865 samples: Vec<(f64, f64, Vec3)>,
866 blocks: Vec<SampleBlock>,
867 groups: Vec<SampleBlock>,
872 tree: Vec<Vec<SampleBlock>>,
878}
879
880const TREE_FANOUT: usize = 4;
882
883fn union_boxes(boxes: &[SampleBlock]) -> Vec<SampleBlock> {
885 boxes
886 .chunks(TREE_FANOUT)
887 .map(|chunk| {
888 let mut union = chunk[0];
889 for block in chunk {
890 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));
891 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));
892 union.prunable &= block.prunable;
893 }
894 union
895 })
896 .collect()
897}
898
899#[derive(Clone, Copy, Debug)]
902struct SampleBlock {
903 low: Vec3,
904 high: Vec3,
905 prunable: bool,
906}
907
908impl SampleGrid {
909 fn new(samples: Vec<(f64, f64, Vec3)>) -> Self {
910 let blocks = samples
911 .chunks(SAMPLE_BLOCK)
912 .map(|chunk| {
913 let mut low = chunk[0].2;
914 let mut high = low;
915 let mut prunable = true;
916 for &(_, _, p) in chunk {
917 prunable &= p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
918 low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
919 high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
920 }
921 SampleBlock { low, high, prunable }
922 })
923 .collect::<Vec<_>>();
924 let groups = blocks
925 .chunks(GROUP_BLOCKS)
926 .map(|chunk| {
927 let mut group = chunk[0];
928 for block in chunk {
929 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));
930 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));
931 group.prunable &= block.prunable;
932 }
933 group
934 })
935 .collect();
936 Self { samples, blocks, groups, tree: Vec::new() }
937 }
938
939 fn with_tree(samples: Vec<(f64, f64, Vec3)>) -> Self {
946 let mut grid = Self::new(samples);
947 if grid.blocks.len() > GROUP_BLOCKS {
948 grid.tree.push(union_boxes(&grid.blocks));
949 while grid.tree.last().is_some_and(|level| level.len() > 1) {
950 let next = union_boxes(grid.tree.last().unwrap());
951 grid.tree.push(next);
952 }
953 }
954 grid
955 }
956}
957
958impl SampleBlock {
959 fn lower_bound(&self, point: Vec3) -> f64 {
967 let gap = |p: f64, low: f64, high: f64| {
968 if p < low {
969 low - p
970 } else if p > high {
971 p - high
972 } else {
973 0.0
974 }
975 };
976 let x = gap(point.x, self.low.x, self.high.x);
977 let y = gap(point.y, self.low.y, self.high.y);
978 let z = gap(point.z, self.low.z, self.high.z);
979 x * x + y * y + z * z
980 }
981}
982
983fn pruned_scan() -> bool {
986 switch!("BREP_PROJECTION_PRUNED_SCAN", true)
987}
988
989fn nearest_sample(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
999 if !grid.tree.is_empty() && scan_tree() && pruned_scan() && bound_first_scan() {
1000 nearest_sample_tree(grid, point, best);
1001 return;
1002 }
1003 nearest_sample_with(grid, point, best, pruned_scan(), bound_first_scan());
1004}
1005
1006fn scan_tree() -> bool {
1018 switch!("BREP_PROJECTION_SCAN_TREE", true)
1019}
1020
1021fn scan_hint() -> bool {
1031 switch!("BREP_PROJECTION_SCAN_HINT", true)
1032}
1033
1034const HINT_SLOTS: usize = 8;
1035
1036thread_local! {
1037 static SCAN_HINTS: std::cell::Cell<[(usize, usize); HINT_SLOTS]> =
1039 const { std::cell::Cell::new([(0, usize::MAX); HINT_SLOTS]) };
1040}
1041
1042fn hint_slot(grid: &SampleGrid) -> (usize, usize) {
1043 let address = grid.samples.as_ptr() as usize;
1044 (address, (address >> 4) % HINT_SLOTS)
1045}
1046
1047fn hinted_bound(grid: &SampleGrid, point: Vec3, mut bound: f64) -> f64 {
1054 if !scan_hint() {
1055 return bound;
1056 }
1057 let (address, slot) = hint_slot(grid);
1058 let (held, run) = SCAN_HINTS.with(|hints| hints.get()[slot]);
1059 if held != address || run >= grid.blocks.len() || !grid.blocks[run].prunable {
1060 return bound;
1061 }
1062 let start = run * SAMPLE_BLOCK;
1063 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1064 for &(_, _, sample) in &grid.samples[start..end] {
1065 let distance_squared = sample.sub(point).length_squared();
1066 if distance_squared < bound {
1067 bound = distance_squared;
1068 }
1069 }
1070 bound
1071}
1072
1073fn remember_hint(grid: &SampleGrid, run: Option<usize>) {
1075 if let Some(run) = run.filter(|_| scan_hint()) {
1076 let (address, slot) = hint_slot(grid);
1077 SCAN_HINTS.with(|hints| {
1078 let mut all = hints.get();
1079 all[slot] = (address, run);
1080 hints.set(all);
1081 });
1082 }
1083}
1084
1085fn nearest_sample_tree(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1096 let top = grid.tree.len() - 1;
1097 let mut bound = best.distance_squared;
1098 let mut node = 0usize;
1100 let mut reached = true;
1101 for level in (0..=top).rev() {
1102 let children = |count: usize| node * TREE_FANOUT..((node + 1) * TREE_FANOUT).min(count);
1103 let below = if level == 0 { &grid.blocks } else { &grid.tree[level - 1] };
1104 match lowest_floor(below, children(below.len()), point) {
1105 Some(child) => node = child,
1106 None => {
1107 reached = false;
1108 break;
1109 }
1110 }
1111 }
1112 if reached {
1113 let start = node * SAMPLE_BLOCK;
1114 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1115 for &(_, _, sample) in &grid.samples[start..end] {
1116 let distance_squared = sample.sub(point).length_squared();
1117 if distance_squared < bound {
1118 bound = distance_squared;
1119 }
1120 }
1121 }
1122 let bound = hinted_bound(grid, point, bound);
1123 let skip = |box_: &SampleBlock, held: f64| {
1124 if !box_.prunable {
1125 return false;
1126 }
1127 let floor = box_.lower_bound(point);
1128 floor >= held || floor > bound
1129 };
1130 let mut answer_run = None;
1131 let mut stack: Vec<(usize, usize)> = Vec::with_capacity(TREE_FANOUT * (top + 2));
1133 stack.push((top + 1, 0));
1134 while let Some((level, index)) = stack.pop() {
1135 if level == 0 {
1136 if skip(&grid.blocks[index], best.distance_squared) {
1137 continue;
1138 }
1139 let start = index * SAMPLE_BLOCK;
1140 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1141 let held = best.distance_squared;
1142 scan_run(&grid.samples[start..end], point, best);
1143 if best.distance_squared < held {
1144 answer_run = Some(index);
1145 }
1146 continue;
1147 }
1148 if skip(&grid.tree[level - 1][index], best.distance_squared) {
1149 continue;
1150 }
1151 let count = if level == 1 { grid.blocks.len() } else { grid.tree[level - 2].len() };
1152 let children = index * TREE_FANOUT..((index + 1) * TREE_FANOUT).min(count);
1153 for child in children.rev() {
1155 stack.push((level - 1, child));
1156 }
1157 }
1158 remember_hint(grid, answer_run);
1159}
1160
1161fn bound_first_scan() -> bool {
1177 switch!("BREP_PROJECTION_BOUND_FIRST", true)
1178}
1179
1180fn nearest_sample_with(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult, pruned: bool, bound_first: bool) {
1190 if !(pruned && bound_first) {
1191 for (block, chunk) in grid.blocks.iter().zip(grid.samples.chunks(SAMPLE_BLOCK)) {
1192 if pruned && block.prunable && block.lower_bound(point) >= best.distance_squared {
1193 continue;
1194 }
1195 scan_run(chunk, point, best);
1196 }
1197 return;
1198 }
1199 let mut bound = best.distance_squared;
1202 let lowest_group = lowest_floor(&grid.groups, 0..grid.groups.len(), point);
1203 if let Some(group) = lowest_group {
1204 let runs = group * GROUP_BLOCKS..((group + 1) * GROUP_BLOCKS).min(grid.blocks.len());
1205 if let Some(run) = lowest_floor(&grid.blocks, runs, point) {
1206 let start = run * SAMPLE_BLOCK;
1207 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1208 for &(_, _, sample) in &grid.samples[start..end] {
1209 let distance_squared = sample.sub(point).length_squared();
1210 if distance_squared < bound {
1211 bound = distance_squared;
1212 }
1213 }
1214 }
1215 }
1216 let bound = hinted_bound(grid, point, bound);
1217 let skip = |box_: &SampleBlock, held: f64| {
1218 if !box_.prunable {
1219 return false;
1220 }
1221 let floor = box_.lower_bound(point);
1222 floor >= held || floor > bound
1223 };
1224 let mut answer_run = None;
1225 for (group_index, group) in grid.groups.iter().enumerate() {
1226 if skip(group, best.distance_squared) {
1227 continue;
1228 }
1229 let first = group_index * GROUP_BLOCKS;
1230 let last = (first + GROUP_BLOCKS).min(grid.blocks.len());
1231 for run in first..last {
1232 if skip(&grid.blocks[run], best.distance_squared) {
1233 continue;
1234 }
1235 let start = run * SAMPLE_BLOCK;
1236 let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1237 let held = best.distance_squared;
1238 scan_run(&grid.samples[start..end], point, best);
1239 if best.distance_squared < held {
1240 answer_run = Some(run);
1241 }
1242 }
1243 }
1244 remember_hint(grid, answer_run);
1245}
1246
1247fn scan_run(run: &[(f64, f64, Vec3)], point: Vec3, best: &mut NewtonResult) {
1250 for &(u, v, sample) in run {
1251 let distance_squared = sample.sub(point).length_squared();
1252 if distance_squared < best.distance_squared {
1253 best.u = u;
1254 best.v = v;
1255 best.distance_squared = distance_squared;
1256 }
1257 }
1258}
1259
1260fn lowest_floor(boxes: &[SampleBlock], range: std::ops::Range<usize>, point: Vec3) -> Option<usize> {
1263 let mut lowest: Option<(usize, f64)> = None;
1264 for index in range {
1265 let box_ = &boxes[index];
1266 if !box_.prunable {
1267 continue;
1268 }
1269 let floor = box_.lower_bound(point);
1270 if lowest.is_none_or(|(_, held)| floor < held) {
1271 lowest = Some((index, floor));
1272 }
1273 }
1274 lowest.map(|(index, _)| index)
1275}
1276
1277const RING_EXPONENTS: usize = 22;
1281const RING_INDICES: usize = 33; #[inline]
1284fn ring_slot(side: usize, exponent_index: usize, index: usize) -> usize {
1285 (side * RING_EXPONENTS + exponent_index) * RING_INDICES + index
1286}
1287
1288fn projection_ring_grid(surface: &NurbsSurface) -> Result<&[Vec3], String> {
1295 if let Some(grid) = surface.projection_ring_grid.get() {
1296 return Ok(grid);
1297 }
1298 let [u0, u1] = surface.domain_u()?;
1299 let [v0, v1] = surface.domain_v()?;
1300 let mut grid = vec![Vec3::default(); 4 * RING_EXPONENTS * RING_INDICES];
1301 for exponent in 1..=RING_EXPONENTS as i32 {
1302 let offset = 1.0 / 2f64.powi(exponent);
1303 let e = exponent as usize - 1;
1304 let v_lo = v0 + (v1 - v0) * offset;
1305 let v_hi = v1 - (v1 - v0) * offset;
1306 let u_lo = u0 + (u1 - u0) * offset;
1307 let u_hi = u1 - (u1 - u0) * offset;
1308 for index in 0..=32 {
1309 let u = u0 + (u1 - u0) * index as f64 / 32.0;
1310 grid[ring_slot(0, e, index as usize)] = surface.evaluate(u, v_lo)?;
1311 grid[ring_slot(1, e, index as usize)] = surface.evaluate(u, v_hi)?;
1312 }
1313 for index in 0..=32 {
1314 let v = v0 + (v1 - v0) * index as f64 / 32.0;
1315 grid[ring_slot(2, e, index as usize)] = surface.evaluate(u_lo, v)?;
1316 grid[ring_slot(3, e, index as usize)] = surface.evaluate(u_hi, v)?;
1317 }
1318 }
1319 Ok(surface.projection_ring_grid.get_or_init(|| grid))
1320}
1321
1322fn nearest_seed_answer(
1332 surface: &NurbsSurface,
1333 point: Vec3,
1334 [u0, u1, v0, v1]: [f64; 4],
1335 closed_u: bool,
1336 closed_v: bool,
1337) -> Result<NewtonResult, String> {
1338 let mut best = NewtonResult {
1339 u: u0,
1340 v: v0,
1341 distance_squared: f64::INFINITY,
1342 converged: false,
1343 };
1344 nearest_sample(projection_seed_grid(surface)?, point, &mut best);
1345 if let Some(revolution) = project_linear_revolution(surface, point)? {
1346 if revolution.distance * revolution.distance < best.distance_squared {
1347 best.u = revolution.u;
1348 best.v = revolution.v;
1349 best.distance_squared = revolution.distance * revolution.distance;
1350 }
1351 }
1352 let first_newton = surface_newton(
1353 surface,
1354 point,
1355 best.u,
1356 best.v,
1357 [u0, u1, v0, v1],
1358 closed_u,
1359 closed_v,
1360 )?;
1361 if first_newton.distance_squared < best.distance_squared {
1362 best = first_newton;
1363 }
1364 let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1365 let degenerate = su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length());
1366 if degenerate || !first_newton.converged {
1367 let mut grid = best;
1368 nearest_sample(projection_dense_grid(surface)?, point, &mut grid);
1369 if grid.distance_squared < best.distance_squared {
1370 best = grid;
1371 }
1372 let polished = surface_newton(
1373 surface,
1374 point,
1375 grid.u,
1376 grid.v,
1377 [u0, u1, v0, v1],
1378 closed_u,
1379 closed_v,
1380 )?;
1381 if polished.distance_squared < best.distance_squared {
1382 best = polished;
1383 }
1384
1385 let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1386 if su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length()) {
1387 let ring_grid = projection_ring_grid(surface)?;
1388 let mut ring = best;
1389 let scan = |side: usize,
1393 exponent_index: usize,
1394 along_u: bool,
1395 fixed: f64,
1396 candidate: &mut NewtonResult| {
1397 for index in 0..=32 {
1398 let moving = if along_u {
1399 u0 + (u1 - u0) * index as f64 / 32.0
1400 } else {
1401 v0 + (v1 - v0) * index as f64 / 32.0
1402 };
1403 let (u, v) = if along_u {
1404 (moving, fixed)
1405 } else {
1406 (fixed, moving)
1407 };
1408 let distance_squared = ring_grid
1409 [ring_slot(side, exponent_index, index as usize)]
1410 .sub(point)
1411 .length_squared();
1412 if distance_squared < candidate.distance_squared {
1413 candidate.u = u;
1414 candidate.v = v;
1415 candidate.distance_squared = distance_squared;
1416 }
1417 }
1418 };
1419 for exponent in 1..=22 {
1420 let offset = 1.0 / 2f64.powi(exponent);
1421 let e = exponent as usize - 1;
1422 if (best.v - v0).abs() <= (v1 - v0) * 0.02 {
1423 scan(0, e, true, v0 + (v1 - v0) * offset, &mut ring);
1424 }
1425 if (best.v - v1).abs() <= (v1 - v0) * 0.02 {
1426 scan(1, e, true, v1 - (v1 - v0) * offset, &mut ring);
1427 }
1428 if (best.u - u0).abs() <= (u1 - u0) * 0.02 {
1429 scan(2, e, false, u0 + (u1 - u0) * offset, &mut ring);
1430 }
1431 if (best.u - u1).abs() <= (u1 - u0) * 0.02 {
1432 scan(3, e, false, u1 - (u1 - u0) * offset, &mut ring);
1433 }
1434 }
1435 if ring.distance_squared < best.distance_squared {
1436 best = ring;
1437 }
1438 let polished = surface_newton(
1439 surface,
1440 point,
1441 ring.u,
1442 ring.v,
1443 [u0, u1, v0, v1],
1444 closed_u,
1445 closed_v,
1446 )?;
1447 if polished.distance_squared < best.distance_squared {
1448 best = polished;
1449 }
1450 }
1451 }
1452 Ok(best)
1453}
1454
1455fn global_stage_enabled() -> bool {
1460 switch!("BREP_PROJECTION_GLOBAL", true)
1461}
1462
1463pub fn global_site_filter_active() -> bool {
1472 static ACTIVE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1477 *ACTIVE.get_or_init(|| {
1478 std::env::var_os("BREP_PROJECTION_GLOBAL_SITES").is_some() || std::env::var_os("BREP_PROJECTION_GLOBAL_EXCEPT").is_some()
1479 })
1480}
1481
1482fn global_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
1483 fn list(name: &str) -> Option<Vec<String>> {
1484 std::env::var(name)
1485 .ok()
1486 .map(|value| value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect())
1487 }
1488 static SITES: std::sync::OnceLock<(Option<Vec<String>>, Option<Vec<String>>)> =
1489 std::sync::OnceLock::new();
1490 let (only, except) = SITES.get_or_init(|| {
1491 (list("BREP_PROJECTION_GLOBAL_SITES"), list("BREP_PROJECTION_GLOBAL_EXCEPT"))
1492 });
1493 if only.is_none() && except.is_none() {
1494 return true;
1495 }
1496 let location = format!("{}:{}", caller.file(), caller.line());
1497 let named = |sites: &Vec<String>| sites.iter().any(|site| location.contains(site.as_str()));
1498 only.as_ref().is_none_or(named) && !except.as_ref().is_some_and(named)
1499}
1500
1501fn audit_record(caller: &std::panic::Location<'_>, surface: &NurbsSurface, local: &NewtonResult, global: &NewtonResult) {
1507 use std::io::Write;
1508 static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
1509 std::sync::OnceLock::new();
1510 let sink = SINK.get_or_init(|| {
1511 let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
1512 let path = std::path::Path::new(&directory)
1513 .join(format!("projection-audit-{}.tsv", std::process::id()));
1514 std::fs::OpenOptions::new()
1515 .create(true)
1516 .append(true)
1517 .open(path)
1518 .ok()
1519 .map(std::sync::Mutex::new)
1520 });
1521 if let Some(file) = sink {
1522 if let Ok(mut file) = file.lock() {
1523 let _ = writeln!(
1524 file,
1525 "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{}x{} cp {}x{}",
1526 caller.file(),
1527 caller.line(),
1528 local.distance_squared.sqrt(),
1529 global.distance_squared.sqrt(),
1530 local.u,
1531 local.v,
1532 global.u,
1533 global.v,
1534 surface.degree_u,
1535 surface.degree_v,
1536 surface.control_points.len(),
1537 surface.control_points.first().map(Vec::len).unwrap_or(0),
1538 );
1539 }
1540 }
1541}
1542
1543#[track_caller]
1619pub fn project_point_to_surface_general(
1620 surface: &NurbsSurface,
1621 point: Vec3,
1622) -> Result<SurfaceProjection, String> {
1623 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_GENERAL, surface);
1624 let [u0, u1] = surface.domain_u()?;
1625 let [v0, v1] = surface.domain_v()?;
1626 let (closed_u, closed_v) = surface.closed_directions()?;
1627 let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1628 let mut best = local;
1629 if global_stage_enabled() {
1630 global_minimum(
1631 surface,
1632 point,
1633 [u0, u1, v0, v1],
1634 (closed_u, closed_v),
1635 &mut best,
1636 &mut GlobalStats::default(),
1637 )?;
1638 if best.u != local.u || best.v != local.v {
1639 let caller = std::panic::Location::caller();
1640 if global_answer_admitted(caller) {
1641 audit_record(caller, surface, &local, &best);
1642 } else {
1643 best = local;
1644 }
1645 }
1646 }
1647 let projected = surface.evaluate(best.u, best.v)?;
1648 Ok(SurfaceProjection {
1649 u: best.u,
1650 v: best.v,
1651 point: projected,
1652 distance: projected.sub(point).length(),
1653 })
1654}
1655
1656pub fn project_point_to_surface_from_nearest_seed(
1666 surface: &NurbsSurface,
1667 point: Vec3,
1668) -> Result<SurfaceProjection, String> {
1669 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_NEAREST_SEED, surface);
1670 if let Some(analytic) = surface.analytic() {
1671 if let Some(projection) = analytic.project(surface, point) {
1672 return Ok(projection);
1673 }
1674 }
1675 if let Some(ellipsoid) = surface.affine_sphere() {
1676 if let Some(projection) = ellipsoid.project(surface, point) {
1677 return Ok(projection);
1678 }
1679 }
1680 let [u0, u1] = surface.domain_u()?;
1681 let [v0, v1] = surface.domain_v()?;
1682 let (closed_u, closed_v) = surface.closed_directions()?;
1683 let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1684 let projected = surface.evaluate(local.u, local.v)?;
1685 Ok(SurfaceProjection {
1686 u: local.u,
1687 v: local.v,
1688 point: projected,
1689 distance: projected.sub(point).length(),
1690 })
1691}
1692
1693#[doc(hidden)]
1696pub fn project_point_to_surface_general_lanes(
1697 surface: &NurbsSurface,
1698 point: Vec3,
1699 run_global: bool,
1700) -> Result<(SurfaceProjection, GlobalStats), String> {
1701 let [u0, u1] = surface.domain_u()?;
1702 let [v0, v1] = surface.domain_v()?;
1703 let (closed_u, closed_v) = surface.closed_directions()?;
1704 let mut best = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1705 let mut stats = GlobalStats::default();
1706 if run_global {
1707 global_minimum(surface, point, [u0, u1, v0, v1], (closed_u, closed_v), &mut best, &mut stats)?;
1708 }
1709 let projected = surface.evaluate(best.u, best.v)?;
1710 Ok((
1711 SurfaceProjection {
1712 u: best.u,
1713 v: best.v,
1714 point: projected,
1715 distance: projected.sub(point).length(),
1716 },
1717 stats,
1718 ))
1719}
1720
1721#[doc(hidden)]
1724#[derive(Clone, Debug, Default)]
1725pub struct BasinCensus {
1726 pub cells: usize,
1729 pub descents: usize,
1731 pub unconverged: usize,
1733 pub cells_with_two_basins: usize,
1737 pub foot_cells_with_two_basins: usize,
1740 pub least: f64,
1742 pub least_uv: (f64, f64),
1743 pub foot_cell_descents: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)>,
1747}
1748
1749#[doc(hidden)]
1754pub fn project_point_to_surface_basin_census(
1755 surface: &NurbsSurface,
1756 point: Vec3,
1757 answer_distance: f64,
1758 bar: f64,
1759) -> Result<BasinCensus, String> {
1760 let mut census = BasinCensus {
1761 least: f64::INFINITY,
1762 ..BasinCensus::default()
1763 };
1764 let Some(cells) = projection_cells(surface)? else {
1765 return Ok(census);
1766 };
1767 let columns = cells.vs.len() - 1;
1768 let mut spreads: Vec<(usize, f64)> = Vec::new();
1769 let mut runs: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)> = Vec::new();
1770 for (cell, cell_box) in cells.boxes.iter().enumerate() {
1771 if cell_box.lower_bound(point) >= answer_distance {
1772 continue;
1773 }
1774 census.cells += 1;
1775 let (row, column) = (cell / columns, cell % columns);
1776 let rectangle = [cells.us[row], cells.us[row + 1], cells.vs[column], cells.vs[column + 1]];
1777 let middle = ((rectangle[0] + rectangle[1]) * 0.5, (rectangle[2] + rectangle[3]) * 0.5);
1778 let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
1779 for seed in [
1780 (rectangle[0], rectangle[2]),
1781 (rectangle[1], rectangle[2]),
1782 (rectangle[0], rectangle[3]),
1783 (rectangle[1], rectangle[3]),
1784 middle,
1785 ] {
1786 census.descents += 1;
1787 let (found, _) = confined_descent(surface, point, seed, rectangle, (false, false))?;
1788 let distance = found.distance_squared.sqrt();
1789 runs.push((cell, rectangle, seed, (found.u, found.v), distance, found.converged));
1790 if distance < census.least {
1791 census.least = distance;
1792 census.least_uv = (found.u, found.v);
1793 }
1794 if !found.converged {
1795 census.unconverged += 1;
1796 continue;
1797 }
1798 low = low.min(distance.max(LINEAR_TOLERANCE));
1799 high = high.max(distance.max(LINEAR_TOLERANCE));
1800 }
1801 if high - low > bar {
1802 spreads.push((cell, high - low));
1803 }
1804 }
1805 census.cells_with_two_basins = spreads.len();
1806 let (u, v) = census.least_uv;
1807 let foot_cells: Vec<usize> = spreads
1808 .iter()
1809 .map(|&(cell, _)| cell)
1810 .filter(|&cell| {
1811 let (row, column) = (cell / columns, cell % columns);
1812 cells.us[row] <= u && u <= cells.us[row + 1] && cells.vs[column] <= v && v <= cells.vs[column + 1]
1813 })
1814 .collect();
1815 census.foot_cells_with_two_basins = foot_cells.len();
1816 census.foot_cell_descents = runs.into_iter().filter(|run| foot_cells.contains(&run.0)).collect();
1817 Ok(census)
1818}
1819
1820#[doc(hidden)]
1822#[derive(Clone, Copy, Debug, Default)]
1823pub struct GlobalStats {
1824 pub settled_by_floor: bool,
1826 pub candidates: usize,
1828 pub refinements: usize,
1830 pub continuations: usize,
1832 pub replaced: bool,
1834 pub hull_lower_bound: f64,
1837}
1838
1839#[derive(Clone, Debug)]
1842struct CellBox {
1843 axes: [Vec3; 3],
1844 low: [f64; 3],
1845 high: [f64; 3],
1846}
1847
1848impl CellBox {
1849 fn lower_bound(&self, point: Vec3) -> f64 {
1852 let mut squared = 0.0;
1853 for axis in 0..3 {
1854 let coordinate = point.dot(self.axes[axis]);
1855 let excess = (self.low[axis] - coordinate).max(coordinate - self.high[axis]).max(0.0);
1856 squared += excess * excess;
1857 }
1858 squared.sqrt()
1859 }
1860}
1861
1862#[derive(Clone, Copy, Debug)]
1865struct CellTreeNode {
1866 centre: Vec3,
1867 radius: f64,
1868 children: Option<(u32, u32)>,
1869 cell: u32,
1870}
1871
1872#[derive(Clone, Debug)]
1875pub struct ProjectionCells {
1876 us: Vec<f64>,
1877 vs: Vec<f64>,
1878 nodes: Vec<Vec3>,
1880 boxes: Vec<CellBox>,
1882 tree: Vec<CellTreeNode>,
1884 node_boxes: Vec<CellBox>,
1888 node_margin: f64,
1890 scale: f64,
1892 resolution: f64,
1893}
1894
1895fn lattice_parameters(knots: &[f64], degree: usize, closed: bool) -> Vec<f64> {
1899 let [start, end] = crate::curve::knot_domain(knots, degree);
1900 let samples = if closed {
1901 8usize.max(degree * 4)
1902 } else {
1903 3usize.max(degree + 1)
1904 };
1905 let mut breaks = vec![start];
1906 breaks.extend(interior_knots(knots, degree));
1907 breaks.push(end);
1908 let mut parameters = Vec::with_capacity((breaks.len() - 1) * samples + 1);
1909 for pair in breaks.windows(2) {
1910 for index in 0..samples {
1911 parameters.push(pair[0] + (pair[1] - pair[0]) * index as f64 / samples as f64);
1912 }
1913 }
1914 parameters.push(end);
1915 parameters
1916}
1917
1918fn refine_to_lattice(net: &mut Vec<Vec<Vec4>>, knots: &mut Vec<f64>, degree: usize, parameters: &[f64]) {
1927 let p = degree;
1928 let n = net.len() - 1;
1929 let mut inserted = Vec::new();
1930 for ¶meter in parameters {
1931 let multiplicity = knots.iter().filter(|&&knot| knot == parameter).count();
1932 for _ in multiplicity..p {
1933 inserted.push(parameter);
1934 }
1935 }
1936 if inserted.is_empty() || p == 0 {
1937 return;
1938 }
1939 inserted.sort_by(f64::total_cmp);
1940 let find_span = |parameter: f64| -> usize {
1941 if parameter >= knots[n + 1] {
1942 return n;
1943 }
1944 (knots.partition_point(|&knot| knot <= parameter) - 1).clamp(p, n)
1945 };
1946 let r = inserted.len() - 1;
1947 let m = n + p + 1;
1948 let a = find_span(inserted[0]);
1949 let b = find_span(inserted[r]) + 1;
1950 let columns = net[0].len();
1951 let blank = vec![
1952 Vec4 {
1953 x: 0.0,
1954 y: 0.0,
1955 z: 0.0,
1956 w: 0.0,
1957 };
1958 columns
1959 ];
1960 let mut refined = vec![blank; n + r + 2];
1961 let mut refined_knots = vec![0.0; m + r + 2];
1962 for j in 0..=a - p {
1963 refined[j] = net[j].clone();
1964 }
1965 for j in b - 1..=n {
1966 refined[j + r + 1] = net[j].clone();
1967 }
1968 refined_knots[..=a].copy_from_slice(&knots[..=a]);
1969 for j in b + p..=m {
1970 refined_knots[j + r + 1] = knots[j];
1971 }
1972 let mut i = b + p - 1;
1973 let mut k = b + p + r;
1974 for j in (0..=r).rev() {
1975 while inserted[j] <= knots[i] && i > a {
1976 refined[k - p - 1] = net[i - p - 1].clone();
1977 refined_knots[k] = knots[i];
1978 k -= 1;
1979 i -= 1;
1980 }
1981 refined[k - p - 1] = refined[k - p].clone();
1982 for l in 1..=p {
1983 let index = k - p + l;
1984 let numerator = refined_knots[k + l] - inserted[j];
1985 if numerator == 0.0 {
1986 refined[index - 1] = refined[index].clone();
1987 } else {
1988 let alpha = numerator / (refined_knots[k + l] - knots[i - p + l]);
1989 let (head, tail) = refined.split_at_mut(index);
1990 for (before, &here) in head[index - 1].iter_mut().zip(&tail[0]) {
1991 *before = before.scale(alpha).add(here.scale(1.0 - alpha));
1992 }
1993 }
1994 }
1995 refined_knots[k] = inserted[j];
1996 k = k.saturating_sub(1);
1997 }
1998 *net = refined;
1999 *knots = refined_knots;
2000}
2001
2002fn supporting_range(knots: &[f64], degree: usize, count: usize, low: f64, high: f64) -> (usize, usize) {
2005 let first_span = knots.partition_point(|&knot| knot <= low).saturating_sub(1);
2006 let last_span = knots.partition_point(|&knot| knot < high).saturating_sub(1);
2007 (
2008 first_span.saturating_sub(degree).min(count - 1),
2009 last_span.max(first_span).min(count - 1),
2010 )
2011}
2012
2013fn unit_or(vector: Vec3, fallback: Vec3) -> Vec3 {
2014 let length = vector.length();
2015 if length > 0.0 && length.is_finite() {
2016 vector.scale(1.0 / length)
2017 } else {
2018 fallback
2019 }
2020}
2021
2022fn enclosing_sphere(a: (Vec3, f64), b: (Vec3, f64)) -> (Vec3, f64) {
2023 let offset = b.0.sub(a.0);
2024 let separation = offset.length();
2025 if separation + b.1 <= a.1 {
2026 return a;
2027 }
2028 if separation + a.1 <= b.1 {
2029 return b;
2030 }
2031 let radius = (separation + a.1 + b.1) * 0.5;
2032 let centre = a.0.add(offset.scale((radius - a.1) / separation));
2033 (centre, radius)
2034}
2035
2036struct NodeBoxInputs<'a> {
2040 boxes: &'a [CellBox],
2041 nodes: &'a [Vec3],
2042 lattice_columns: usize,
2043 margin: f64,
2044}
2045
2046fn enclosing_node_box(corners: [Vec3; 4], children: [&CellBox; 2], margin: f64) -> CellBox {
2051 let unbounded = || CellBox {
2052 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)],
2053 low: [f64::NEG_INFINITY; 3],
2054 high: [f64::INFINITY; 3],
2055 };
2056 let [c00, c10, c01, c11] = corners;
2057 let along_u = c10.sub(c00).add(c11.sub(c01));
2058 let along_v = c01.sub(c00).add(c11.sub(c10));
2059 let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2060 let Ok(fallback) = e1.perpendicular() else {
2061 return unbounded();
2062 };
2063 let normal = unit_or(e1.cross(along_v), fallback);
2064 let e2 = unit_or(normal.cross(e1), fallback);
2065 let e3 = e1.cross(e2);
2066 let axes = [e1, e2, e3];
2067 let mut low = [f64::INFINITY; 3];
2068 let mut high = [f64::NEG_INFINITY; 3];
2069 for child in children {
2070 for corner in 0..8 {
2071 let mut point = Vec3::default();
2072 for axis in 0..3 {
2073 let value = if corner >> axis & 1 == 0 { child.low[axis] } else { child.high[axis] };
2074 point = point.add(child.axes[axis].scale(value));
2075 }
2076 for axis in 0..3 {
2077 let coordinate = point.dot(axes[axis]);
2078 low[axis] = low[axis].min(coordinate);
2079 high[axis] = high[axis].max(coordinate);
2080 }
2081 }
2082 }
2083 for axis in 0..3 {
2084 low[axis] -= margin;
2085 high[axis] += margin;
2086 }
2087 if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2088 return unbounded();
2089 }
2090 CellBox { axes, low, high }
2091}
2092
2093fn build_cell_tree(
2094 tree: &mut Vec<CellTreeNode>,
2095 node_boxes: &mut Vec<CellBox>,
2096 inputs: &NodeBoxInputs<'_>,
2097 spheres: &[(Vec3, f64)],
2098 columns: usize,
2099 [row_low, row_high, column_low, column_high]: [usize; 4],
2100) -> u32 {
2101 if row_high - row_low == 1 && column_high - column_low == 1 {
2102 let cell = row_low * columns + column_low;
2103 node_boxes.push(inputs.boxes[cell].clone());
2104 tree.push(CellTreeNode {
2105 centre: spheres[cell].0,
2106 radius: spheres[cell].1,
2107 children: None,
2108 cell: cell as u32,
2109 });
2110 return (tree.len() - 1) as u32;
2111 }
2112 let (first, second) = if row_high - row_low >= column_high - column_low {
2113 let middle = (row_low + row_high) / 2;
2114 (
2115 [row_low, middle, column_low, column_high],
2116 [middle, row_high, column_low, column_high],
2117 )
2118 } else {
2119 let middle = (column_low + column_high) / 2;
2120 (
2121 [row_low, row_high, column_low, middle],
2122 [row_low, row_high, middle, column_high],
2123 )
2124 };
2125 let first = build_cell_tree(tree, node_boxes, inputs, spheres, columns, first);
2126 let second = build_cell_tree(tree, node_boxes, inputs, spheres, columns, second);
2127 let a = tree[first as usize];
2128 let b = tree[second as usize];
2129 let lattice = |row: usize, column: usize| inputs.nodes[row * inputs.lattice_columns + column];
2130 node_boxes.push(enclosing_node_box(
2131 [
2132 lattice(row_low, column_low),
2133 lattice(row_high, column_low),
2134 lattice(row_low, column_high),
2135 lattice(row_high, column_high),
2136 ],
2137 [&node_boxes[first as usize], &node_boxes[second as usize]],
2138 inputs.margin,
2139 ));
2140 let (centre, radius) = enclosing_sphere((a.centre, a.radius), (b.centre, b.radius));
2144 tree.push(CellTreeNode {
2145 centre,
2146 radius: radius * (1.0 + 4.0 * f64::EPSILON),
2147 children: Some((first, second)),
2148 cell: u32::MAX,
2149 });
2150 (tree.len() - 1) as u32
2151}
2152
2153fn projection_cells(surface: &NurbsSurface) -> Result<Option<&ProjectionCells>, String> {
2154 if let Some(cells) = surface.projection_cells.get() {
2155 return Ok(cells.as_ref());
2156 }
2157 let cells = build_projection_cells(surface)?;
2158 Ok(surface.projection_cells.get_or_init(|| cells).as_ref())
2159}
2160
2161fn build_projection_cells(surface: &NurbsSurface) -> Result<Option<ProjectionCells>, String> {
2162 let (closed_u, closed_v) = surface.closed_directions()?;
2163 let us = lattice_parameters(&surface.knots_u, surface.degree_u, closed_u);
2164 let vs = lattice_parameters(&surface.knots_v, surface.degree_v, closed_v);
2165 if us.len() < 2 || vs.len() < 2 {
2166 return Ok(None);
2167 }
2168 let mut scale = 0.0f64;
2169 for control in surface.control_points.iter().flatten() {
2170 let point = control.point()?;
2171 scale = scale.max(point.x.abs()).max(point.y.abs()).max(point.z.abs());
2172 }
2173 let resolution =
2174 ((surface.degree_u + 1) * (surface.degree_v + 1)) as f64 * f64::EPSILON * scale;
2175
2176 let mut net = surface.control_points.clone();
2178 let mut knots_u = surface.knots_u.clone();
2179 refine_to_lattice(&mut net, &mut knots_u, surface.degree_u, &us);
2180 let columns = net.first().map(Vec::len).unwrap_or(0);
2181 let mut transposed: Vec<Vec<Vec4>> =
2182 (0..columns).map(|column| net.iter().map(|row| row[column]).collect()).collect();
2183 let mut knots_v = surface.knots_v.clone();
2184 refine_to_lattice(&mut transposed, &mut knots_v, surface.degree_v, &vs);
2185 let rows = transposed.first().map(Vec::len).unwrap_or(0);
2186 let columns = transposed.len();
2187 if rows == 0 || columns == 0 {
2188 return Ok(None);
2189 }
2190 let mut points = vec![Vec3::default(); rows * columns];
2191 for (column, fibre) in transposed.iter().enumerate() {
2192 for (row, control) in fibre.iter().enumerate() {
2193 points[row * columns + column] = control.point()?;
2194 }
2195 }
2196
2197 let mut nodes = Vec::with_capacity(us.len() * vs.len());
2198 for &u in &us {
2199 for &v in &vs {
2200 nodes.push(surface.evaluate(u, v)?);
2201 }
2202 }
2203
2204 let cell_rows = us.len() - 1;
2205 let cell_columns = vs.len() - 1;
2206 let mut boxes = Vec::with_capacity(cell_rows * cell_columns);
2207 let mut spheres = Vec::with_capacity(cell_rows * cell_columns);
2208 for i in 0..cell_rows {
2209 let (row_low, row_high) =
2210 supporting_range(&knots_u, surface.degree_u, rows, us[i], us[i + 1]);
2211 for j in 0..cell_columns {
2212 let (column_low, column_high) =
2213 supporting_range(&knots_v, surface.degree_v, columns, vs[j], vs[j + 1]);
2214 let at = |row: usize, column: usize| points[row * columns + column];
2215 let c00 = at(row_low, column_low);
2216 let c10 = at(row_high, column_low);
2217 let c01 = at(row_low, column_high);
2218 let c11 = at(row_high, column_high);
2219 let along_u = c10.sub(c00).add(c11.sub(c01));
2220 let along_v = c01.sub(c00).add(c11.sub(c10));
2221 let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2222 let normal = unit_or(e1.cross(along_v), e1.perpendicular()?);
2223 let e2 = unit_or(normal.cross(e1), e1.perpendicular()?);
2224 let e3 = e1.cross(e2);
2225 let axes = [e1, e2, e3];
2226 let mut low = [f64::INFINITY; 3];
2227 let mut high = [f64::NEG_INFINITY; 3];
2228 for row in row_low..=row_high {
2229 for column in column_low..=column_high {
2230 let point = at(row, column);
2231 for axis in 0..3 {
2232 let coordinate = point.dot(axes[axis]);
2233 low[axis] = low[axis].min(coordinate);
2234 high[axis] = high[axis].max(coordinate);
2235 }
2236 }
2237 }
2238 for axis in 0..3 {
2239 low[axis] -= resolution;
2240 high[axis] += resolution;
2241 }
2242 let mut centre = Vec3::default();
2243 let mut half_diagonal_squared = 0.0;
2244 for axis in 0..3 {
2245 centre = centre.add(axes[axis].scale((low[axis] + high[axis]) * 0.5));
2246 let half = (high[axis] - low[axis]) * 0.5;
2247 half_diagonal_squared += half * half;
2248 }
2249 if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2250 return Ok(None);
2251 }
2252 spheres.push((centre, half_diagonal_squared.sqrt() + resolution));
2253 boxes.push(CellBox { axes, low, high });
2254 }
2255 }
2256 let mut tree = Vec::with_capacity(2 * boxes.len());
2257 let mut node_boxes = Vec::with_capacity(2 * boxes.len());
2258 let node_margin = NODE_BOX_MARGIN * scale;
2263 let inputs = NodeBoxInputs { boxes: &boxes, nodes: &nodes, lattice_columns: vs.len(), margin: node_margin };
2264 build_cell_tree(&mut tree, &mut node_boxes, &inputs, &spheres, cell_columns, [0, cell_rows, 0, cell_columns]);
2265 if !(node_margin > 0.0 && node_margin.is_finite()) {
2266 node_boxes = Vec::new();
2267 }
2268 Ok(Some(ProjectionCells {
2269 us,
2270 vs,
2271 nodes,
2272 boxes,
2273 tree,
2274 node_boxes,
2275 node_margin,
2276 scale,
2277 resolution,
2278 }))
2279}
2280
2281fn optimality(
2286 derivatives: &[[Vec3; 3]; 3],
2287 point: Vec3,
2288 (u, v): (f64, f64),
2289 [ua, ub, va, vb]: [f64; 4],
2290 periodic: (bool, bool),
2291) -> Optimality {
2292 let residual = derivatives[0][0].sub(point);
2293 let residual_length = residual.length();
2294 let su = derivatives[1][0];
2295 let sv = derivatives[0][1];
2296 let f = su.dot(residual);
2297 let g = sv.dot(residual);
2298 let metric_u = su.length_squared();
2299 let metric_v = sv.length_squared();
2300 let stationary_u = metric_u.sqrt() * residual_length <= EPSILON
2301 || f.abs() <= 1e-10 * metric_u.sqrt() * residual_length;
2302 let stationary_v = metric_v.sqrt() * residual_length <= EPSILON
2303 || g.abs() <= 1e-10 * metric_v.sqrt() * residual_length;
2304 let pinned_u = !periodic.0 && ((u <= ua && f > 0.0) || (u >= ub && f < 0.0));
2305 let pinned_v = !periodic.1 && ((v <= va && g > 0.0) || (v >= vb && g < 0.0));
2306 let j00 = derivatives[2][0].dot(residual) + metric_u;
2307 let j01 = derivatives[1][1].dot(residual) + su.dot(sv);
2308 let j11 = derivatives[0][2].dot(residual) + metric_v;
2309 let determinant = j00 * j11 - j01 * j01;
2310 let convex = match (!pinned_u, !pinned_v) {
2311 (true, true) => j00 > 0.0 && determinant > 0.0,
2312 (true, false) => j00 > 0.0,
2313 (false, true) => j11 > 0.0,
2314 (false, false) => true,
2315 };
2316 Optimality {
2317 residual_length,
2318 gradient: (f, g),
2319 metric: (metric_u, metric_v),
2320 hessian: (j00, j01, j11),
2321 determinant,
2322 pinned: (pinned_u, pinned_v),
2323 convex,
2324 minimum: residual_length <= LINEAR_TOLERANCE
2325 || ((stationary_u || pinned_u) && (stationary_v || pinned_v) && convex),
2326 }
2327}
2328
2329struct Optimality {
2330 residual_length: f64,
2331 gradient: (f64, f64),
2332 metric: (f64, f64),
2333 hessian: (f64, f64, f64),
2334 determinant: f64,
2335 pinned: (bool, bool),
2336 convex: bool,
2337 minimum: bool,
2338}
2339
2340fn is_verified_minimum(
2341 surface: &NurbsSurface,
2342 point: Vec3,
2343 at: (f64, f64),
2344 rectangle: [f64; 4],
2345 periodic: (bool, bool),
2346) -> Result<bool, String> {
2347 let derivatives = surface.derivatives_small(at.0, at.1, 2)?;
2348 Ok(optimality(&derivatives, point, at, rectangle, periodic).minimum)
2349}
2350
2351fn confined_descent(
2367 surface: &NurbsSurface,
2368 point: Vec3,
2369 seed: (f64, f64),
2370 rectangle: [f64; 4],
2371 periodic: (bool, bool),
2372) -> Result<(NewtonResult, bool), String> {
2373 let [ua, ub, va, vb] = rectangle;
2374 let mut u = fit_parameter(seed.0, ua, ub, periodic.0);
2375 let mut v = fit_parameter(seed.1, va, vb, periodic.1);
2376 let mut converged = false;
2377 let mut current = surface.evaluate(u, v)?.sub(point).length_squared();
2378 for _ in 0..MAX_NEWTON_ITERATIONS {
2379 let derivatives = surface.derivatives_small(u, v, 2)?;
2380 let state = optimality(&derivatives, point, (u, v), rectangle, periodic);
2381 current = state.residual_length * state.residual_length;
2382 if state.minimum {
2383 converged = true;
2384 break;
2385 }
2386 let (f, g) = state.gradient;
2387 let (metric_u, metric_v) = state.metric;
2388 let (j00, j01, j11) = state.hessian;
2389 let determinant = state.determinant;
2390 let (free_u, free_v) = (!state.pinned.0, !state.pinned.1);
2391 let (mut du, mut dv) = match (free_u, free_v) {
2392 (true, true) if state.convex => (
2393 (-f * j11 + g * j01) / determinant,
2394 (-g * j00 + f * j01) / determinant,
2395 ),
2396 (true, false) if state.convex => (-f / j00, 0.0),
2397 (false, true) if state.convex => (0.0, -g / j11),
2398 _ => (
2399 if free_u && metric_u > 0.0 { -f / metric_u } else { 0.0 },
2400 if free_v && metric_v > 0.0 { -g / metric_v } else { 0.0 },
2401 ),
2402 };
2403 if !(du.is_finite() && dv.is_finite()) || (du == 0.0 && dv == 0.0) {
2404 break;
2405 }
2406 let mut moved = false;
2407 let taken = |next: f64, here: f64, low: f64, high: f64, wraps: bool| {
2409 let raw = next - here;
2410 if wraps {
2411 raw - (high - low) * (raw / (high - low)).round()
2412 } else {
2413 raw
2414 }
2415 };
2416 for _ in 0..40 {
2417 let next_u = fit_parameter(u + du, ua, ub, periodic.0);
2418 let next_v = fit_parameter(v + dv, va, vb, periodic.1);
2419 if next_u == u && next_v == v {
2420 break;
2421 }
2422 let trial = surface.evaluate(next_u, next_v)?.sub(point).length_squared();
2423 if trial <= current {
2424 moved = taken(next_u, u, ua, ub, periodic.0).abs() > 1e-15 * (ub - ua)
2425 || taken(next_v, v, va, vb, periodic.1).abs() > 1e-15 * (vb - va);
2426 u = next_u;
2427 v = next_v;
2428 current = trial;
2429 break;
2430 }
2431 du *= 0.5;
2432 dv *= 0.5;
2433 }
2434 if !moved {
2435 break;
2436 }
2437 }
2438 let result = NewtonResult {
2439 u,
2440 v,
2441 distance_squared: current,
2442 converged,
2443 };
2444 let on_edge =
2445 (!periodic.0 && (u <= ua || u >= ub)) || (!periodic.1 && (v <= va || v >= vb));
2446 Ok((result, on_edge))
2447}
2448
2449const NODE_BOX_MARGIN: f64 = 1e-9;
2452
2453fn node_boxes_enabled() -> bool {
2457 switch!("BREP_PROJECTION_NODE_BOXES", true)
2458}
2459
2460fn hull_candidates(cells: &ProjectionCells, point: Vec3, bound: f64, node_boxes: bool) -> (Vec<(f64, usize)>, f64) {
2481 let read_error = 32.0 * f64::EPSILON * (point.x.abs() + point.y.abs() + point.z.abs() + 4.0 * cells.scale);
2482 let boxes = node_boxes && !cells.node_boxes.is_empty() && 4.0 * read_error <= cells.node_margin;
2483 let mut candidates: Vec<(f64, usize)> = Vec::new();
2484 let mut excluded = f64::INFINITY;
2485 let mut stack: Vec<u32> = Vec::with_capacity(64);
2486 stack.push((cells.tree.len() - 1) as u32);
2487 while let Some(index) = stack.pop() {
2488 let node = cells.tree[index as usize];
2489 let sphere_bound = (point.sub(node.centre).length() - node.radius).max(0.0);
2490 if sphere_bound >= bound {
2491 excluded = excluded.min(sphere_bound);
2492 continue;
2493 }
2494 match node.children {
2495 Some((first, second)) => {
2496 if boxes {
2497 let box_bound = cells.node_boxes[index as usize].lower_bound(point);
2498 if box_bound >= bound && box_bound > 2.0 * read_error {
2499 excluded = excluded.min(box_bound);
2500 continue;
2501 }
2502 }
2503 stack.push(first);
2504 stack.push(second);
2505 }
2506 None => {
2507 let cell = node.cell as usize;
2508 let box_bound = cells.boxes[cell].lower_bound(point);
2509 if box_bound < bound {
2510 candidates.push((box_bound, cell));
2511 } else {
2512 excluded = excluded.min(box_bound);
2513 }
2514 }
2515 }
2516 }
2517 (candidates, excluded)
2518}
2519
2520#[allow(clippy::too_many_arguments)]
2523fn global_minimum(
2524 surface: &NurbsSurface,
2525 point: Vec3,
2526 domains: [f64; 4],
2527 periodic: (bool, bool),
2528 best: &mut NewtonResult,
2529 stats: &mut GlobalStats,
2530) -> Result<(), String> {
2531 if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
2532 stats.settled_by_floor = true;
2533 return Ok(());
2534 }
2535 let Some(cells) = projection_cells(surface)? else {
2536 return Ok(());
2537 };
2538 let resolution = cells.resolution;
2539 let columns = cells.vs.len() - 1;
2540 let columns_u = cells.us.len() - 1;
2541 let mut bound = best.distance_squared.sqrt() - resolution;
2542
2543 let (mut candidates, excluded) = hull_candidates(cells, point, bound, node_boxes_enabled());
2546 stats.candidates = candidates.len();
2547 candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
2548 stats.hull_lower_bound = candidates
2549 .first()
2550 .map_or(excluded, |&(least, _)| least.min(excluded));
2551
2552 let cell_of = |u: f64, v: f64| {
2558 let row = (cells.us.partition_point(|&value| value <= u).max(1) - 1).min(columns_u - 1);
2559 let column = (cells.vs.partition_point(|&value| value <= v).max(1) - 1).min(columns - 1);
2560 row * columns + column
2561 };
2562 let mut settled: Vec<usize> = Vec::new();
2563 if is_verified_minimum(surface, point, (best.u, best.v), domains, periodic)? {
2564 settled.push(cell_of(best.u, best.v));
2565 }
2566 for (cell_bound, cell) in candidates {
2567 if cell_bound >= bound {
2568 break;
2569 }
2570 let row = cell / columns;
2571 let column = cell % columns;
2572 let rectangle = [
2573 cells.us[row],
2574 cells.us[row + 1],
2575 cells.vs[column],
2576 cells.vs[column + 1],
2577 ];
2578 if settled.contains(&cell) {
2579 continue;
2580 }
2581 let mut seed = (rectangle[0], rectangle[2]);
2582 let mut seed_distance = f64::INFINITY;
2583 for (node_row, node_column) in
2584 [(row, column), (row + 1, column), (row, column + 1), (row + 1, column + 1)]
2585 {
2586 let distance = cells.nodes[node_row * cells.vs.len() + node_column]
2587 .sub(point)
2588 .length_squared();
2589 if distance < seed_distance {
2590 seed_distance = distance;
2591 seed = (cells.us[node_row], cells.vs[node_column]);
2592 }
2593 }
2594 stats.refinements += 1;
2595 let (confined, on_edge) = confined_descent(surface, point, seed, rectangle, (false, false))?;
2596 let mut found = confined;
2597 if on_edge && confined.distance_squared.sqrt() < bound {
2598 stats.continuations += 1;
2601 let (continued, _) =
2602 confined_descent(surface, point, (confined.u, confined.v), domains, periodic)?;
2603 if continued.distance_squared < found.distance_squared {
2604 found = continued;
2605 }
2606 if continued.converged {
2607 settled.push(cell_of(continued.u, continued.v));
2608 }
2609 }
2610 if found.distance_squared.sqrt() < bound {
2611 *best = found;
2612 bound = best.distance_squared.sqrt() - resolution;
2613 stats.replaced = true;
2614 if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
2615 return Ok(());
2616 }
2617 }
2618 }
2619 Ok(())
2620}
2621
2622
2623
2624#[derive(Clone, Copy)]
2626pub enum FootDomain {
2627 Clamp,
2628 Wrap,
2629 Extended,
2630}
2631
2632#[derive(Clone, Copy)]
2633pub struct CurveFootPolicy {
2634 pub domain: FootDomain,
2635 pub iterations: usize,
2636 pub slope_guard: f64,
2637 pub step_limit: f64,
2638 pub parameter_tolerance: f64,
2639 pub mode: FootMode,
2640}
2641
2642#[derive(Clone, Copy)]
2644pub enum FootMode {
2645 Monotone,
2646 Witness,
2647 Stationary { positive_slope: bool, relative_step: bool },
2648 Backtracked,
2649 Planar,
2650}
2651
2652fn curve_foot_newton_state(
2655 curve: &NurbsCurve,
2656 point: Vec3,
2657 seed: f64,
2658 bracket: [f64; 2],
2659 policy: CurveFootPolicy,
2660) -> Result<(f64, f64, f64), String> {
2661 let fit = |u| match policy.domain {
2662 FootDomain::Clamp => fit_parameter(u, bracket[0], bracket[1], false),
2663 FootDomain::Wrap => fit_parameter(u, bracket[0], bracket[1], true),
2664 FootDomain::Extended => u,
2665 };
2666 let extended = matches!(policy.domain, FootDomain::Extended) || matches!(policy.mode, FootMode::Backtracked);
2667 let planar = matches!(policy.mode, FootMode::Planar);
2668 let project = |p: Vec3| if planar { Vec3::new(p.x, p.y, 0.0) } else { p };
2669 let point = project(point);
2670 let distance = |u| -> Result<f64, String> {
2671 let p = if extended { curve.derivatives_extended(u, 0)?[0] } else { curve.evaluate(u)? };
2672 Ok(project(p).sub(point).length())
2673 };
2674 let monotone = matches!(policy.mode, FootMode::Monotone | FootMode::Backtracked);
2675 let witness = matches!(policy.mode, FootMode::Witness);
2676 let mut u = if witness { seed } else { fit(seed) };
2677 let mut nearest_u = seed;
2678 let mut nearest_squared = f64::INFINITY;
2679 let mut best = if monotone { distance(u)? } else { f64::INFINITY };
2680 for _ in 0..policy.iterations {
2681 let derivatives = if extended {
2682 let values = curve.derivatives_extended(u, 2)?;
2683 [values[0], values[1], values[2]]
2684 } else if matches!(policy.mode, FootMode::Stationary { .. })
2685 || (planar && !crate::curve::small_curve_derivatives_enabled()) {
2686 let values = curve.derivatives(u, 2)?;
2687 [values[0], values[1], values[2]]
2688 } else {
2689 curve.derivatives_small(u, 2)?
2690 }.map(project);
2691 let offset = derivatives[0].sub(point);
2692 let numerator = offset.dot(derivatives[1]);
2693 let denominator = derivatives[1].dot(derivatives[1]) + offset.dot(derivatives[2]);
2694 if witness {
2695 let squared = offset.length_squared();
2696 if squared < nearest_squared {
2697 nearest_u = u;
2698 nearest_squared = squared;
2699 }
2700 let residual_length = squared.sqrt();
2701 if residual_length <= LINEAR_TOLERANCE
2702 || numerator.abs() <= EPSILON + 1e-10 * derivatives[1].length() * residual_length {
2703 break;
2704 }
2705 }
2706 let singular = if planar { denominator.abs() < policy.slope_guard }
2707 else { denominator.abs() <= policy.slope_guard };
2708 if singular || (matches!(policy.mode, FootMode::Stationary { positive_slope: true, .. }) && !(denominator > 0.0)) { break; }
2709 let mut step = if matches!(policy.mode, FootMode::Backtracked) && !(denominator > 0.0) {
2710 policy.step_limit.copysign(numerator)
2711 } else {
2712 (numerator / denominator).clamp(-policy.step_limit, policy.step_limit)
2713 };
2714 let mut next = fit(u - step);
2715 let mut next_distance = if monotone { distance(next)? } else { f64::INFINITY };
2716 if matches!(policy.mode, FootMode::Backtracked) {
2717 for _ in 0..30 {
2718 if next_distance < best { break; }
2719 step *= 0.5;
2720 next = fit(u - step);
2721 next_distance = distance(next)?;
2722 }
2723 if !(next_distance < best) { break; }
2724 } else if monotone && next_distance >= best { break; }
2725 let moved = if planar || matches!(policy.domain, FootDomain::Extended) { step }
2726 else if matches!(policy.domain, FootDomain::Wrap) {
2727 let period = bracket[1] - bracket[0];
2728 let raw = next - u;
2729 raw - period * (raw / period).round()
2730 } else { next - u };
2731 let tolerance = if matches!(policy.mode, FootMode::Stationary { relative_step: true, .. }) {
2732 policy.parameter_tolerance * (1.0 + u.abs())
2733 } else { policy.parameter_tolerance };
2734 let small = if planar || matches!(policy.mode, FootMode::Backtracked) { moved.abs() < tolerance }
2735 else { moved.abs() <= tolerance };
2736 if small && matches!(policy.mode, FootMode::Monotone) { break; }
2737 u = next;
2738 best = next_distance;
2739 if small { break; }
2740 }
2741 if witness { return Ok((u, nearest_u, nearest_squared)); }
2742 if !monotone { best = distance(u)?; }
2743 Ok((u, u, best * best))
2744}
2745
2746pub fn curve_foot_newton(
2747 curve: &NurbsCurve, point: Vec3, seed: f64, bracket: [f64; 2], policy: CurveFootPolicy,
2748) -> Result<(f64, f64), String> {
2749 let (_, nearest, squared) = curve_foot_newton_state(curve, point, seed, bracket, policy)?;
2750 Ok((nearest, squared))
2751}
2752
2753
2754