1use crate::curve::interior_knot_count;
2use crate::{project_point_to_surface, NurbsCurve, NurbsSurface, Vec3};
3use serde::Serialize;
4
5const EPSILON: f64 = crate::tolerance::FP_FLOOR;
6
7use crate::spatial::Aabb as Bounds;
8
9
10fn surface_bounds(surface: &NurbsSurface) -> Result<Bounds, String> {
15 let mut bounds = Bounds::from_points([]);
16 for point in surface.control_points.iter().flatten() {
17 let point = point.point()?;
18 bounds.minimum.x = bounds.minimum.x.min(point.x);
19 bounds.minimum.y = bounds.minimum.y.min(point.y);
20 bounds.minimum.z = bounds.minimum.z.min(point.z);
21 bounds.maximum.x = bounds.maximum.x.max(point.x);
22 bounds.maximum.y = bounds.maximum.y.max(point.y);
23 bounds.maximum.z = bounds.maximum.z.max(point.z);
24 }
25 Ok(bounds)
26}
27
28
29fn span_bounds(surface: &NurbsSurface) -> Result<Vec<Bounds>, String> {
40 let (p, q) = (surface.degree_u, surface.degree_v);
41 let rows = surface.control_points.len();
42 let columns = surface.control_points.first().map_or(0, Vec::len);
43 let spans = |knots: &[f64], degree: usize, count: usize| -> Vec<usize> {
44 (degree..count).filter(|&i| i + 1 < knots.len() && knots[i] < knots[i + 1]).collect()
45 };
46 let (spans_u, spans_v) = (spans(&surface.knots_u, p, rows), spans(&surface.knots_v, q, columns));
47 if spans_u.is_empty() || spans_v.is_empty() {
49 return Ok(vec![surface_bounds(surface)?]);
50 }
51 let mut boxes = Vec::with_capacity(spans_u.len() * spans_v.len());
52 for &i in &spans_u {
53 for &j in &spans_v {
54 let mut bounds = Bounds::from_points([]);
55 for row in &surface.control_points[i - p..=i] {
56 for control in &row[j - q..=j] {
57 let point = control.point()?;
58 bounds.minimum.x = bounds.minimum.x.min(point.x);
59 bounds.minimum.y = bounds.minimum.y.min(point.y);
60 bounds.minimum.z = bounds.minimum.z.min(point.z);
61 bounds.maximum.x = bounds.maximum.x.max(point.x);
62 bounds.maximum.y = bounds.maximum.y.max(point.y);
63 bounds.maximum.z = bounds.maximum.z.max(point.z);
64 }
65 }
66 boxes.push(bounds);
67 }
68 }
69 Ok(boxes)
70}
71
72fn fit_parameter(value: f64, minimum: f64, maximum: f64, closed: bool) -> f64 {
73 crate::projection::fit_parameter(value, minimum, maximum, closed)
74}
75
76fn solve_three(matrix: [[f64; 3]; 3], rhs: Vec3) -> Option<[f64; 3]> {
77 let a = matrix;
78 let determinant = a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
79 - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
80 + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);
81 let scale: f64 = a.iter().flatten().map(|value| value.abs()).sum();
82 if determinant.abs() <= 1e-14 * scale.max(1.0).powi(3) {
83 return None;
84 }
85 let x = (rhs.x * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
86 - a[0][1] * (rhs.y * a[2][2] - a[1][2] * rhs.z)
87 + a[0][2] * (rhs.y * a[2][1] - a[1][1] * rhs.z))
88 / determinant;
89 let y = (a[0][0] * (rhs.y * a[2][2] - a[1][2] * rhs.z)
90 - rhs.x * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
91 + a[0][2] * (a[1][0] * rhs.z - rhs.y * a[2][0]))
92 / determinant;
93 let z = (a[0][0] * (a[1][1] * rhs.z - rhs.y * a[2][1])
94 - a[0][1] * (a[1][0] * rhs.z - rhs.y * a[2][0])
95 + rhs.x * (a[1][0] * a[2][1] - a[1][1] * a[2][0]))
96 / determinant;
97 Some([x, y, z])
98}
99
100pub fn newton_local_start_enabled() -> bool {
109 switch!("BREP_CS_NEWTON_LOCAL_START", true)
110}
111
112fn newton_local_start_check() -> bool {
117 switch!("BREP_CS_NEWTON_LOCAL_START_CHECK", false)
118}
119
120static START_CHECK_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
121static START_CHECK_FEET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
122static START_CHECK_FOOT_DISAGREEMENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
123static START_CHECK_HIT_DISAGREEMENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
124
125pub fn newton_start_check_counts() -> (u64, u64, u64, u64) {
128 use std::sync::atomic::Ordering::Relaxed;
129 (
130 START_CHECK_CALLS.load(Relaxed),
131 START_CHECK_FEET.load(Relaxed),
132 START_CHECK_FOOT_DISAGREEMENTS.load(Relaxed),
133 START_CHECK_HIT_DISAGREEMENTS.load(Relaxed),
134 )
135}
136
137fn opening_foot(surface: &NurbsSurface, point: Vec3, local: bool, check: bool) -> Result<[f64; 2], String> {
141 if !local {
142 let projection = project_point_to_surface(surface, point)?;
143 return Ok([projection.u, projection.v]);
144 }
145 let projection = crate::projection::project_point_to_surface_local(surface, point)?;
146 if check {
147 use std::sync::atomic::Ordering::Relaxed;
148 START_CHECK_FEET.fetch_add(1, Relaxed);
149 let nearest = project_point_to_surface(surface, point)?;
150 let apart = projection.point.sub(nearest.point).length();
151 if apart > crate::tolerance::DEFAULT_MODEL {
152 START_CHECK_FOOT_DISAGREEMENTS.fetch_add(1, Relaxed);
153 eprintln!(
154 "cs newton start check: foot apart {apart:.3e} (local {:.3e} at ({:.9},{:.9}), nearest {:.3e} at ({:.9},{:.9}))",
155 projection.distance, projection.u, projection.v, nearest.distance, nearest.u, nearest.v
156 );
157 }
158 }
159 Ok([projection.u, projection.v])
160}
161
162fn newton_curve_surface(
163 curve: &NurbsCurve,
164 surface: &NurbsSurface,
165 seed: f64,
166 local_start: bool,
167 check: bool,
168) -> Result<[f64; 3], String> {
169 let [t0, t1] = curve.domain()?;
170 let [u0, u1] = surface.domain_u()?;
171 let [v0, v1] = surface.domain_v()?;
172 let (closed_u, closed_v) = surface.closed_directions()?;
173 let mut t = seed;
174 let [mut u, mut v] = opening_foot(surface, curve.evaluate(t)?, local_start, check)?;
175 for _ in 0..60 {
176 let (curve_point, tangent) = curve.deriv1(t)?;
177 let (surface_point, du, dv) = surface.deriv1(u, v)?;
178 let residual = curve_point.sub(surface_point);
179 if residual.length() <= EPSILON {
180 return Ok([t, u, v]);
181 }
182 let Some([mut step_t, mut step_u, mut step_v]) = solve_three(
183 [
184 [tangent.x, -du.x, -dv.x],
185 [tangent.y, -du.y, -dv.y],
186 [tangent.z, -du.z, -dv.z],
187 ],
188 residual.scale(-1.0),
189 ) else {
190 if tangent.length_squared() <= EPSILON {
191 return Ok([t, u, v]);
192 }
193 let next_t = (t - residual.dot(tangent) / tangent.length_squared()).clamp(t0, t1);
194 if (next_t - t).abs() <= 1e-15 * (t1 - t0) {
195 return Ok([t, u, v]);
196 }
197 t = next_t;
198 let projection =
202 crate::projection::project_point_to_surface_from_seed(surface, curve.evaluate(t)?, [u, v])?;
203 u = projection.u;
204 v = projection.v;
205 continue;
206 };
207 step_t = step_t.clamp(-(t1 - t0) / 4.0, (t1 - t0) / 4.0);
208 step_u = step_u.clamp(-(u1 - u0) / 4.0, (u1 - u0) / 4.0);
209 step_v = step_v.clamp(-(v1 - v0) / 4.0, (v1 - v0) / 4.0);
210 let next_t = (t + step_t).clamp(t0, t1);
211 let next_u = fit_parameter(u + step_u, u0, u1, closed_u);
212 let next_v = fit_parameter(v + step_v, v0, v1, closed_v);
213 let stalled = (next_t - t).abs() <= 1e-15 * (t1 - t0)
214 && (next_u - u).abs() <= 1e-15 * (u1 - u0)
215 && (next_v - v).abs() <= 1e-15 * (v1 - v0);
216 t = next_t;
217 u = next_u;
218 v = next_v;
219 if stalled {
220 return Ok([t, u, v]);
221 }
222 }
223 Ok([t, u, v])
224}
225
226#[derive(Clone, Copy, Debug, Serialize)]
227pub struct CurveSurfaceIntersection {
228 pub t: f64,
229 pub u: f64,
230 pub v: f64,
231 pub point: Vec3,
232 pub gap: f64,
233 pub tangential: bool,
234}
235
236fn duplicate_cap_enabled() -> bool {
240 switch!("BREP_CS_DUPLICATE_CAP", true)
241}
242
243pub fn intersect_curve_surface(
244 curve: &NurbsCurve,
245 surface: &NurbsSurface,
246 tolerance: f64,
247) -> Result<Vec<CurveSurfaceIntersection>, String> {
248 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INTERSECT_CURVE_SURFACE, surface);
249 let seeds = sampled_seeds(curve, surface, tolerance)?;
250 intersect_curve_surface_from_seeds(curve, surface, tolerance, seeds)
251}
252
253fn sampled_seeds(curve: &NurbsCurve, surface: &NurbsSurface, tolerance: f64) -> Result<Vec<f64>, String> {
256 let [t0, t1] = curve.domain()?;
257 let surface_box = surface_bounds(surface)?.expanded(tolerance * 10.0);
258 let sample_count =
259 32usize.max((interior_knot_count(&curve.knots, curve.degree) + 1) * (curve.degree + 1) * 4);
260 let mut samples = Vec::with_capacity(sample_count + 1);
261 for index in 0..=sample_count {
262 let t = t0 + (t1 - t0) * index as f64 / sample_count as f64;
263 samples.push((t, curve.evaluate(t)?));
264 }
265 let span_boxes = span_bounds(surface)?;
266 let mut seeds = Vec::new();
267 for pair in samples.windows(2) {
268 let segment_box = Bounds::from_points([pair[0].1, pair[1].1]).expanded(tolerance * 10.0);
269 if segment_box.intersects_exact(surface_box)
270 && span_boxes.iter().any(|span_box| segment_box.intersects_exact(span_box.expanded(tolerance * 10.0)))
271 {
272 seeds.push((pair[0].0 + pair[1].0) * 0.5);
273 }
274 }
275 Ok(seeds)
276}
277
278pub fn intersect_curve_surface_from_seeds(
284 curve: &NurbsCurve,
285 surface: &NurbsSurface,
286 tolerance: f64,
287 seeds: Vec<f64>,
288) -> Result<Vec<CurveSurfaceIntersection>, String> {
289 solve_counted(curve, surface, tolerance, &seeds, false)
290}
291
292pub fn intersect_ray_surface(
300 curve: &NurbsCurve,
301 surface: &NurbsSurface,
302 tolerance: f64,
303) -> Result<Vec<CurveSurfaceIntersection>, String> {
304 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INTERSECT_CURVE_SURFACE, surface);
305 let seeds = sampled_seeds(curve, surface, tolerance)?;
306 if !ray_hull_seeds_enabled() {
307 return solve_counted(curve, surface, tolerance, &seeds, true);
308 }
309 let Some(kept) = hull_seeds(curve, surface, tolerance, &seeds) else {
310 return solve_counted(curve, surface, tolerance, &seeds, true);
311 };
312 let hits = solve_counted(curve, surface, tolerance, &kept, true)?;
313 if ray_hull_seeds_check() {
314 let every = solve_counted(curve, surface, tolerance, &seeds, true)?;
315 assert!(
316 same_hits(&hits, &every, tolerance),
317 "BREP_RAY_HULL_SEEDS_CHECK: {} of {} seeds read t {:?}, every seed read t {:?}",
318 kept.len(),
319 seeds.len(),
320 hits.iter().map(|hit| hit.t).collect::<Vec<_>>(),
321 every.iter().map(|hit| hit.t).collect::<Vec<_>>()
322 );
323 }
324 Ok(hits)
325}
326
327fn ray_hull_seeds_enabled() -> bool {
338 ray_hull_seeds_check() || switch!("BREP_RAY_HULL_SEEDS", true)
339}
340
341fn ray_hull_seeds_check() -> bool {
342 switch!("BREP_RAY_HULL_SEEDS_CHECK", false)
343}
344
345fn hull_seeds(curve: &NurbsCurve, surface: &NurbsSurface, tolerance: f64, seeds: &[f64]) -> Option<Vec<f64>> {
350 if seeds.is_empty() || curve.degree != 1 || curve.control_points.len() != 2 {
351 return None;
352 }
353 let [t0, t1] = curve.domain().ok()?;
354 let (start, end) = (curve.control_points[0].point().ok()?, curve.control_points[1].point().ok()?);
355 let (spans_u, spans_v) = crate::curve_clear::patch_span_counts(surface)?;
356 let sample_count = 32usize.max((interior_knot_count(&curve.knots, curve.degree) + 1) * (curve.degree + 1) * 4);
358 let step = 1.0 / sample_count as f64;
359 let pad = tolerance * 10.0;
360 let direction = end.sub(start);
361 let stretch = |lo: [f64; 3], hi: [f64; 3]| -> Option<[f64; 2]> {
363 let (mut s0, mut s1) = (0.0f64, 1.0f64);
364 for (k, (origin, delta)) in [(start.x, direction.x), (start.y, direction.y), (start.z, direction.z)].into_iter().enumerate() {
365 let (low, high) = (lo[k] - pad, hi[k] + pad);
366 if delta.abs() <= f64::MIN_POSITIVE {
367 if origin < low || origin > high {
368 return None;
369 }
370 continue;
371 }
372 let (a, b) = ((low - origin) / delta, (high - origin) / delta);
373 s0 = s0.max(a.min(b));
374 s1 = s1.min(a.max(b));
375 if s0 > s1 {
376 return None;
377 }
378 }
379 Some([s0, s1])
380 };
381 let mut stretches: Vec<[f64; 2]> = Vec::new();
382 let mut pending: Vec<(usize, usize, [f64; 2], [f64; 2], u32)> =
383 (0..spans_u).flat_map(|i| (0..spans_v).map(move |j| (i, j, [0.0, 1.0], [0.0, 1.0], 0))).collect();
384 let mut visits = 0usize;
387 while let Some((i, j, range_u, range_v, depth)) = pending.pop() {
388 visits += 1;
389 if visits > 4096 {
390 return None;
391 }
392 let (lo, hi) = crate::curve_clear::patch_piece_box(surface, i, j, range_u, range_v)?;
393 let Some(along) = stretch(lo, hi) else {
394 continue;
395 };
396 if along[1] - along[0] <= step || depth >= 12 {
397 stretches.push(along);
398 continue;
399 }
400 let (mu, mv) = (0.5 * (range_u[0] + range_u[1]), 0.5 * (range_v[0] + range_v[1]));
401 for (u, v) in [([range_u[0], mu], [range_v[0], mv]), ([mu, range_u[1]], [range_v[0], mv]), ([range_u[0], mu], [mv, range_v[1]]), ([mu, range_u[1]], [mv, range_v[1]])] {
402 pending.push((i, j, u, v, depth + 1));
403 }
404 }
405 let span = t1 - t0;
406 Some(
407 seeds
408 .iter()
409 .copied()
410 .filter(|&seed| {
411 let s = (seed - t0) / span;
412 stretches.iter().any(|&[a, b]| s + step >= a && s - step <= b)
413 })
414 .collect(),
415 )
416}
417
418fn solve_counted(
419 curve: &NurbsCurve,
420 surface: &NurbsSurface,
421 tolerance: f64,
422 seeds: &[f64],
423 ray: bool,
424) -> Result<Vec<CurveSurfaceIntersection>, String> {
425 if !ray || !newton_local_start_enabled() {
426 return solve_from_seeds(curve, surface, tolerance, seeds, false, false);
427 }
428 if !newton_local_start_check() {
429 return solve_from_seeds(curve, surface, tolerance, seeds, true, false);
430 }
431 let local = solve_from_seeds(curve, surface, tolerance, seeds, true, true)?;
432 let global = solve_from_seeds(curve, surface, tolerance, seeds, false, false)?;
433 START_CHECK_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
434 if !same_hits(&local, &global, tolerance) {
435 START_CHECK_HIT_DISAGREEMENTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
436 let read = |hits: &[CurveSurfaceIntersection]| hits.iter().map(|hit| hit.t).collect::<Vec<_>>();
437 eprintln!(
438 "cs newton start check: hits differ: local t {:?} global t {:?}",
439 read(&local),
440 read(&global)
441 );
442 }
443 Ok(local)
444}
445
446fn same_hits(first: &[CurveSurfaceIntersection], second: &[CurveSurfaceIntersection], tolerance: f64) -> bool {
449 first.len() == second.len()
450 && first.iter().zip(second).all(|(a, b)| {
451 a.point.sub(b.point).length() <= tolerance * 10.0 && a.tangential == b.tangential
452 })
453}
454
455fn solve_from_seeds(
456 curve: &NurbsCurve,
457 surface: &NurbsSurface,
458 tolerance: f64,
459 seeds: &[f64],
460 local_start: bool,
461 check: bool,
462) -> Result<Vec<CurveSurfaceIntersection>, String> {
463 let [t0, t1] = curve.domain()?;
464 let mut results: Vec<CurveSurfaceIntersection> = Vec::new();
465 for &seed in seeds {
466 let [t, u, v] = newton_curve_surface(curve, surface, seed, local_start, check)?;
467 let on_curve = curve.evaluate(t)?;
468 let on_surface = surface.evaluate(u, v)?;
469 let gap = on_curve.sub(on_surface).length();
470 if gap > tolerance {
471 continue;
472 }
473 let tangent = curve.deriv1(t)?.1;
474 let uncapped = ((tolerance / tangent.length().max(EPSILON)) * 10.0).max((t1 - t0) * 1e-9);
497 let capped = uncapped.min((t1 - t0) * 1e-6);
498 let parameter_tolerance = if duplicate_cap_enabled() { capped } else { uncapped };
499 if let Some(result) = results.iter().find(|result| {
500 (result.t - t).abs() <= parameter_tolerance
501 || result.point.sub(on_curve).length() <= tolerance * 10.0
502 }) {
503 let chord = result.point.sub(on_curve).length();
510 let gap = (result.t - t).abs();
511 if chord > tolerance * 10.0
512 && gap > capped
513 && std::env::var("BREP_DEBUG_CS_DUPLICATE").is_ok()
514 {
515 eprintln!(
516 "cs-duplicate: dropped t={t:.12} against t={:.12} gap={gap:.6e} ptol={parameter_tolerance:.6e} \
517 chord={chord:.6e} |tangent|={:.6e} domain=[{t0:.6},{t1:.6}] tolerance={tolerance:.3e}",
518 result.t,
519 tangent.length(),
520 );
521 }
522 continue;
523 }
524 let normal = surface.normal(u, v).ok();
525 let tangential = normal
526 .and_then(|normal| {
527 tangent
528 .normalized()
529 .ok()
530 .map(|unit| normal.dot(unit).abs() <= 1e-3)
531 })
532 .unwrap_or(false);
533 results.push(CurveSurfaceIntersection {
534 t,
535 u,
536 v,
537 point: on_curve.add(on_surface).scale(0.5),
538 gap,
539 tangential,
540 });
541 }
542 results.sort_by(|a, b| a.t.total_cmp(&b.t));
543 Ok(results)
544}
545