use crate::curve::interior_knot_count;
use crate::{project_point_to_surface, NurbsCurve, NurbsSurface, Vec3};
use serde::Serialize;
const EPSILON: f64 = crate::tolerance::FP_FLOOR;
use crate::spatial::Aabb as Bounds;
fn surface_bounds(surface: &NurbsSurface) -> Result<Bounds, String> {
let mut bounds = Bounds::from_points([]);
for point in surface.control_points.iter().flatten() {
let point = point.point()?;
bounds.minimum.x = bounds.minimum.x.min(point.x);
bounds.minimum.y = bounds.minimum.y.min(point.y);
bounds.minimum.z = bounds.minimum.z.min(point.z);
bounds.maximum.x = bounds.maximum.x.max(point.x);
bounds.maximum.y = bounds.maximum.y.max(point.y);
bounds.maximum.z = bounds.maximum.z.max(point.z);
}
Ok(bounds)
}
fn span_bounds(surface: &NurbsSurface) -> Result<Vec<Bounds>, String> {
let (p, q) = (surface.degree_u, surface.degree_v);
let rows = surface.control_points.len();
let columns = surface.control_points.first().map_or(0, Vec::len);
let spans = |knots: &[f64], degree: usize, count: usize| -> Vec<usize> {
(degree..count).filter(|&i| i + 1 < knots.len() && knots[i] < knots[i + 1]).collect()
};
let (spans_u, spans_v) = (spans(&surface.knots_u, p, rows), spans(&surface.knots_v, q, columns));
if spans_u.is_empty() || spans_v.is_empty() {
return Ok(vec![surface_bounds(surface)?]);
}
let mut boxes = Vec::with_capacity(spans_u.len() * spans_v.len());
for &i in &spans_u {
for &j in &spans_v {
let mut bounds = Bounds::from_points([]);
for row in &surface.control_points[i - p..=i] {
for control in &row[j - q..=j] {
let point = control.point()?;
bounds.minimum.x = bounds.minimum.x.min(point.x);
bounds.minimum.y = bounds.minimum.y.min(point.y);
bounds.minimum.z = bounds.minimum.z.min(point.z);
bounds.maximum.x = bounds.maximum.x.max(point.x);
bounds.maximum.y = bounds.maximum.y.max(point.y);
bounds.maximum.z = bounds.maximum.z.max(point.z);
}
}
boxes.push(bounds);
}
}
Ok(boxes)
}
fn fit_parameter(value: f64, minimum: f64, maximum: f64, closed: bool) -> f64 {
crate::projection::fit_parameter(value, minimum, maximum, closed)
}
fn solve_three(matrix: [[f64; 3]; 3], rhs: Vec3) -> Option<[f64; 3]> {
let a = matrix;
let determinant = a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
- a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
+ a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);
let scale: f64 = a.iter().flatten().map(|value| value.abs()).sum();
if determinant.abs() <= 1e-14 * scale.max(1.0).powi(3) {
return None;
}
let x = (rhs.x * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
- a[0][1] * (rhs.y * a[2][2] - a[1][2] * rhs.z)
+ a[0][2] * (rhs.y * a[2][1] - a[1][1] * rhs.z))
/ determinant;
let y = (a[0][0] * (rhs.y * a[2][2] - a[1][2] * rhs.z)
- rhs.x * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
+ a[0][2] * (a[1][0] * rhs.z - rhs.y * a[2][0]))
/ determinant;
let z = (a[0][0] * (a[1][1] * rhs.z - rhs.y * a[2][1])
- a[0][1] * (a[1][0] * rhs.z - rhs.y * a[2][0])
+ rhs.x * (a[1][0] * a[2][1] - a[1][1] * a[2][0]))
/ determinant;
Some([x, y, z])
}
pub fn newton_local_start_enabled() -> bool {
switch!("BREP_CS_NEWTON_LOCAL_START", true)
}
fn newton_local_start_check() -> bool {
switch!("BREP_CS_NEWTON_LOCAL_START_CHECK", false)
}
static START_CHECK_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static START_CHECK_FEET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static START_CHECK_FOOT_DISAGREEMENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static START_CHECK_HIT_DISAGREEMENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
pub fn newton_start_check_counts() -> (u64, u64, u64, u64) {
use std::sync::atomic::Ordering::Relaxed;
(
START_CHECK_CALLS.load(Relaxed),
START_CHECK_FEET.load(Relaxed),
START_CHECK_FOOT_DISAGREEMENTS.load(Relaxed),
START_CHECK_HIT_DISAGREEMENTS.load(Relaxed),
)
}
fn opening_foot(surface: &NurbsSurface, point: Vec3, local: bool, check: bool) -> Result<[f64; 2], String> {
if !local {
let projection = project_point_to_surface(surface, point)?;
return Ok([projection.u, projection.v]);
}
let projection = crate::projection::project_point_to_surface_local(surface, point)?;
if check {
use std::sync::atomic::Ordering::Relaxed;
START_CHECK_FEET.fetch_add(1, Relaxed);
let nearest = project_point_to_surface(surface, point)?;
let apart = projection.point.sub(nearest.point).length();
if apart > crate::tolerance::DEFAULT_MODEL {
START_CHECK_FOOT_DISAGREEMENTS.fetch_add(1, Relaxed);
eprintln!(
"cs newton start check: foot apart {apart:.3e} (local {:.3e} at ({:.9},{:.9}), nearest {:.3e} at ({:.9},{:.9}))",
projection.distance, projection.u, projection.v, nearest.distance, nearest.u, nearest.v
);
}
}
Ok([projection.u, projection.v])
}
fn newton_curve_surface(
curve: &NurbsCurve,
surface: &NurbsSurface,
seed: f64,
local_start: bool,
check: bool,
) -> Result<[f64; 3], String> {
let [t0, t1] = curve.domain()?;
let [u0, u1] = surface.domain_u()?;
let [v0, v1] = surface.domain_v()?;
let (closed_u, closed_v) = surface.closed_directions()?;
let mut t = seed;
let [mut u, mut v] = opening_foot(surface, curve.evaluate(t)?, local_start, check)?;
for _ in 0..60 {
let (curve_point, tangent) = curve.deriv1(t)?;
let (surface_point, du, dv) = surface.deriv1(u, v)?;
let residual = curve_point.sub(surface_point);
if residual.length() <= EPSILON {
return Ok([t, u, v]);
}
let Some([mut step_t, mut step_u, mut step_v]) = solve_three(
[
[tangent.x, -du.x, -dv.x],
[tangent.y, -du.y, -dv.y],
[tangent.z, -du.z, -dv.z],
],
residual.scale(-1.0),
) else {
if tangent.length_squared() <= EPSILON {
return Ok([t, u, v]);
}
let next_t = (t - residual.dot(tangent) / tangent.length_squared()).clamp(t0, t1);
if (next_t - t).abs() <= 1e-15 * (t1 - t0) {
return Ok([t, u, v]);
}
t = next_t;
let projection =
crate::projection::project_point_to_surface_from_seed(surface, curve.evaluate(t)?, [u, v])?;
u = projection.u;
v = projection.v;
continue;
};
step_t = step_t.clamp(-(t1 - t0) / 4.0, (t1 - t0) / 4.0);
step_u = step_u.clamp(-(u1 - u0) / 4.0, (u1 - u0) / 4.0);
step_v = step_v.clamp(-(v1 - v0) / 4.0, (v1 - v0) / 4.0);
let next_t = (t + step_t).clamp(t0, t1);
let next_u = fit_parameter(u + step_u, u0, u1, closed_u);
let next_v = fit_parameter(v + step_v, v0, v1, closed_v);
let stalled = (next_t - t).abs() <= 1e-15 * (t1 - t0)
&& (next_u - u).abs() <= 1e-15 * (u1 - u0)
&& (next_v - v).abs() <= 1e-15 * (v1 - v0);
t = next_t;
u = next_u;
v = next_v;
if stalled {
return Ok([t, u, v]);
}
}
Ok([t, u, v])
}
#[derive(Clone, Copy, Debug, Serialize)]
pub struct CurveSurfaceIntersection {
pub t: f64,
pub u: f64,
pub v: f64,
pub point: Vec3,
pub gap: f64,
pub tangential: bool,
}
fn duplicate_cap_enabled() -> bool {
switch!("BREP_CS_DUPLICATE_CAP", true)
}
pub fn intersect_curve_surface(
curve: &NurbsCurve,
surface: &NurbsSurface,
tolerance: f64,
) -> Result<Vec<CurveSurfaceIntersection>, String> {
let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INTERSECT_CURVE_SURFACE, surface);
let seeds = sampled_seeds(curve, surface, tolerance)?;
intersect_curve_surface_from_seeds(curve, surface, tolerance, seeds)
}
fn sampled_seeds(curve: &NurbsCurve, surface: &NurbsSurface, tolerance: f64) -> Result<Vec<f64>, String> {
let [t0, t1] = curve.domain()?;
let surface_box = surface_bounds(surface)?.expanded(tolerance * 10.0);
let sample_count =
32usize.max((interior_knot_count(&curve.knots, curve.degree) + 1) * (curve.degree + 1) * 4);
let mut samples = Vec::with_capacity(sample_count + 1);
for index in 0..=sample_count {
let t = t0 + (t1 - t0) * index as f64 / sample_count as f64;
samples.push((t, curve.evaluate(t)?));
}
let span_boxes = span_bounds(surface)?;
let mut seeds = Vec::new();
for pair in samples.windows(2) {
let segment_box = Bounds::from_points([pair[0].1, pair[1].1]).expanded(tolerance * 10.0);
if segment_box.intersects_exact(surface_box)
&& span_boxes.iter().any(|span_box| segment_box.intersects_exact(span_box.expanded(tolerance * 10.0)))
{
seeds.push((pair[0].0 + pair[1].0) * 0.5);
}
}
Ok(seeds)
}
pub fn intersect_curve_surface_from_seeds(
curve: &NurbsCurve,
surface: &NurbsSurface,
tolerance: f64,
seeds: Vec<f64>,
) -> Result<Vec<CurveSurfaceIntersection>, String> {
solve_counted(curve, surface, tolerance, &seeds, false)
}
pub fn intersect_ray_surface(
curve: &NurbsCurve,
surface: &NurbsSurface,
tolerance: f64,
) -> Result<Vec<CurveSurfaceIntersection>, String> {
let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INTERSECT_CURVE_SURFACE, surface);
let seeds = sampled_seeds(curve, surface, tolerance)?;
if !ray_hull_seeds_enabled() {
return solve_counted(curve, surface, tolerance, &seeds, true);
}
let Some(kept) = hull_seeds(curve, surface, tolerance, &seeds) else {
return solve_counted(curve, surface, tolerance, &seeds, true);
};
let hits = solve_counted(curve, surface, tolerance, &kept, true)?;
if ray_hull_seeds_check() {
let every = solve_counted(curve, surface, tolerance, &seeds, true)?;
assert!(
same_hits(&hits, &every, tolerance),
"BREP_RAY_HULL_SEEDS_CHECK: {} of {} seeds read t {:?}, every seed read t {:?}",
kept.len(),
seeds.len(),
hits.iter().map(|hit| hit.t).collect::<Vec<_>>(),
every.iter().map(|hit| hit.t).collect::<Vec<_>>()
);
}
Ok(hits)
}
fn ray_hull_seeds_enabled() -> bool {
ray_hull_seeds_check() || switch!("BREP_RAY_HULL_SEEDS", true)
}
fn ray_hull_seeds_check() -> bool {
switch!("BREP_RAY_HULL_SEEDS_CHECK", false)
}
fn hull_seeds(curve: &NurbsCurve, surface: &NurbsSurface, tolerance: f64, seeds: &[f64]) -> Option<Vec<f64>> {
if seeds.is_empty() || curve.degree != 1 || curve.control_points.len() != 2 {
return None;
}
let [t0, t1] = curve.domain().ok()?;
let (start, end) = (curve.control_points[0].point().ok()?, curve.control_points[1].point().ok()?);
let (spans_u, spans_v) = crate::curve_clear::patch_span_counts(surface)?;
let sample_count = 32usize.max((interior_knot_count(&curve.knots, curve.degree) + 1) * (curve.degree + 1) * 4);
let step = 1.0 / sample_count as f64;
let pad = tolerance * 10.0;
let direction = end.sub(start);
let stretch = |lo: [f64; 3], hi: [f64; 3]| -> Option<[f64; 2]> {
let (mut s0, mut s1) = (0.0f64, 1.0f64);
for (k, (origin, delta)) in [(start.x, direction.x), (start.y, direction.y), (start.z, direction.z)].into_iter().enumerate() {
let (low, high) = (lo[k] - pad, hi[k] + pad);
if delta.abs() <= f64::MIN_POSITIVE {
if origin < low || origin > high {
return None;
}
continue;
}
let (a, b) = ((low - origin) / delta, (high - origin) / delta);
s0 = s0.max(a.min(b));
s1 = s1.min(a.max(b));
if s0 > s1 {
return None;
}
}
Some([s0, s1])
};
let mut stretches: Vec<[f64; 2]> = Vec::new();
let mut pending: Vec<(usize, usize, [f64; 2], [f64; 2], u32)> =
(0..spans_u).flat_map(|i| (0..spans_v).map(move |j| (i, j, [0.0, 1.0], [0.0, 1.0], 0))).collect();
let mut visits = 0usize;
while let Some((i, j, range_u, range_v, depth)) = pending.pop() {
visits += 1;
if visits > 4096 {
return None;
}
let (lo, hi) = crate::curve_clear::patch_piece_box(surface, i, j, range_u, range_v)?;
let Some(along) = stretch(lo, hi) else {
continue;
};
if along[1] - along[0] <= step || depth >= 12 {
stretches.push(along);
continue;
}
let (mu, mv) = (0.5 * (range_u[0] + range_u[1]), 0.5 * (range_v[0] + range_v[1]));
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]])] {
pending.push((i, j, u, v, depth + 1));
}
}
let span = t1 - t0;
Some(
seeds
.iter()
.copied()
.filter(|&seed| {
let s = (seed - t0) / span;
stretches.iter().any(|&[a, b]| s + step >= a && s - step <= b)
})
.collect(),
)
}
fn solve_counted(
curve: &NurbsCurve,
surface: &NurbsSurface,
tolerance: f64,
seeds: &[f64],
ray: bool,
) -> Result<Vec<CurveSurfaceIntersection>, String> {
if !ray || !newton_local_start_enabled() {
return solve_from_seeds(curve, surface, tolerance, seeds, false, false);
}
if !newton_local_start_check() {
return solve_from_seeds(curve, surface, tolerance, seeds, true, false);
}
let local = solve_from_seeds(curve, surface, tolerance, seeds, true, true)?;
let global = solve_from_seeds(curve, surface, tolerance, seeds, false, false)?;
START_CHECK_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if !same_hits(&local, &global, tolerance) {
START_CHECK_HIT_DISAGREEMENTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let read = |hits: &[CurveSurfaceIntersection]| hits.iter().map(|hit| hit.t).collect::<Vec<_>>();
eprintln!(
"cs newton start check: hits differ: local t {:?} global t {:?}",
read(&local),
read(&global)
);
}
Ok(local)
}
fn same_hits(first: &[CurveSurfaceIntersection], second: &[CurveSurfaceIntersection], tolerance: f64) -> bool {
first.len() == second.len()
&& first.iter().zip(second).all(|(a, b)| {
a.point.sub(b.point).length() <= tolerance * 10.0 && a.tangential == b.tangential
})
}
fn solve_from_seeds(
curve: &NurbsCurve,
surface: &NurbsSurface,
tolerance: f64,
seeds: &[f64],
local_start: bool,
check: bool,
) -> Result<Vec<CurveSurfaceIntersection>, String> {
let [t0, t1] = curve.domain()?;
let mut results: Vec<CurveSurfaceIntersection> = Vec::new();
for &seed in seeds {
let [t, u, v] = newton_curve_surface(curve, surface, seed, local_start, check)?;
let on_curve = curve.evaluate(t)?;
let on_surface = surface.evaluate(u, v)?;
let gap = on_curve.sub(on_surface).length();
if gap > tolerance {
continue;
}
let tangent = curve.deriv1(t)?.1;
let uncapped = ((tolerance / tangent.length().max(EPSILON)) * 10.0).max((t1 - t0) * 1e-9);
let capped = uncapped.min((t1 - t0) * 1e-6);
let parameter_tolerance = if duplicate_cap_enabled() { capped } else { uncapped };
if let Some(result) = results.iter().find(|result| {
(result.t - t).abs() <= parameter_tolerance
|| result.point.sub(on_curve).length() <= tolerance * 10.0
}) {
let chord = result.point.sub(on_curve).length();
let gap = (result.t - t).abs();
if chord > tolerance * 10.0
&& gap > capped
&& std::env::var("BREP_DEBUG_CS_DUPLICATE").is_ok()
{
eprintln!(
"cs-duplicate: dropped t={t:.12} against t={:.12} gap={gap:.6e} ptol={parameter_tolerance:.6e} \
chord={chord:.6e} |tangent|={:.6e} domain=[{t0:.6},{t1:.6}] tolerance={tolerance:.3e}",
result.t,
tangent.length(),
);
}
continue;
}
let normal = surface.normal(u, v).ok();
let tangential = normal
.and_then(|normal| {
tangent
.normalized()
.ok()
.map(|unit| normal.dot(unit).abs() <= 1e-3)
})
.unwrap_or(false);
results.push(CurveSurfaceIntersection {
t,
u,
v,
point: on_curve.add(on_surface).scale(0.5),
gap,
tangential,
});
}
results.sort_by(|a, b| a.t.total_cmp(&b.t));
Ok(results)
}