use std::collections::HashMap;
use crate::{
check::{self, coedge_params},
edit::tweak,
geom::Surface,
math::{Aabb, Frame, Point3},
measure, tol,
topo::{Brep, FaceId, VertexId},
};
use super::{
csi::{Tracker, signed_distance},
ssi::same_domain,
};
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Reach {
Exact,
Grazing,
}
pub(crate) const SNAP: f64 = 1e-6;
pub(crate) const SNAP_GRAZING: f64 = 1e-4;
const MOST_MOVED: f64 = 10.0;
const COAXIAL_TILT: f64 = 1e-8;
fn boundary_points(b: &Brep, f: FaceId) -> Vec<Point3> {
let mut out = Vec::new();
for &lp in &b.face(f).loops {
for &c in &b.lp(lp).coedges {
let e = b.edge(b.coedge(c).edge);
match &e.curve {
Some(curve) => out.extend(coedge_params(b, c, 16).iter().map(|&t| curve.eval(t))),
None => out.push(b.vertex(e.start).point),
}
}
}
out
}
fn analytic(s: &Surface) -> bool {
matches!(
s,
Surface::Plane(_)
| Surface::Cylinder(_)
| Surface::Cone(_)
| Surface::Sphere(_)
| Surface::Torus(_)
)
}
fn alike(s: &Surface, t: &Surface) -> bool {
let near = |x: f64, y: f64| (x - y).abs() <= SNAP_GRAZING;
let parallel = |a: crate::math::Vec3, b: crate::math::Vec3| a.cross(b).norm() <= 1e-3;
match (s, t) {
(Surface::Plane(p), Surface::Plane(q)) => parallel(p.frame.z, q.frame.z),
(Surface::Cylinder(p), Surface::Cylinder(q)) => {
near(p.radius, q.radius) && parallel(p.frame.z, q.frame.z)
}
(Surface::Sphere(p), Surface::Sphere(q)) => near(p.radius, q.radius),
(Surface::Cone(p), Surface::Cone(q)) => {
(p.half_angle - q.half_angle).abs() <= 1e-3 && parallel(p.frame.z, q.frame.z)
}
(Surface::Torus(p), Surface::Torus(q)) => {
near(p.major, q.major) && near(p.minor, q.minor) && parallel(p.frame.z, q.frame.z)
}
(Surface::Extrusion(_), Surface::Extrusion(_))
| (Surface::Revolution(_), Surface::Revolution(_))
| (Surface::Ruled(_), Surface::Ruled(_))
| (Surface::Nurbs(_), Surface::Nurbs(_)) => s != t,
_ => false,
}
}
fn facing(s: &Surface, like: &Surface) -> Surface {
match (s, like) {
(Surface::Plane(p), Surface::Plane(q)) if p.frame.z.dot(q.frame.z) < 0.0 => {
match crate::math::Frame::new(p.frame.origin, -p.frame.z, p.frame.x) {
Ok(frame) => Surface::Plane(crate::geom::Plane { frame }),
Err(_) => s.clone(),
}
}
_ => s.clone(),
}
}
fn pins(
a: &Brep,
b: &Brep,
moved: &HashMap<FaceId, Surface>,
reach: f64,
) -> HashMap<VertexId, Point3> {
let mut on_moved: Vec<VertexId> = Vec::new();
for &f in moved.keys() {
for &lp in &b.face(f).loops {
for &c in &b.lp(lp).coedges {
on_moved.push(b.coedge_start(c));
}
}
}
on_moved.sort();
on_moved.dedup();
let mut zone = Aabb::EMPTY;
for &v in &on_moved {
zone.add(b.vertex(v).point);
}
let zone = padded(&zone, reach);
let theirs: Vec<Point3> = a
.vertex_ids()
.map(|w| a.vertex(w).point)
.filter(|p| (0..3).all(|k| p[k] >= zone.min[k] && p[k] <= zone.max[k]))
.collect();
on_moved
.into_iter()
.filter_map(|v| {
let p = b.vertex(v).point;
let (d, q) = theirs
.iter()
.map(|&q| (q.dist(p), q))
.min_by(|x, y| x.0.total_cmp(&y.0))?;
(d <= reach).then_some((v, q))
})
.collect()
}
fn snaps(sa: &Surface, sb: &Surface, pts: &[Point3]) -> Option<f64> {
let mut track = Tracker::new(sa);
let mut d = Vec::with_capacity(pts.len());
for &p in pts {
let x = track.at(p);
if x.abs() > SNAP_GRAZING {
return None;
}
d.push(x);
}
let worst = d.iter().fold(0.0f64, |m, x| m.max(x.abs()));
if worst <= SNAP {
return Some(worst);
}
if worst > SNAP_GRAZING {
return None;
}
let crosses = d.iter().any(|&x| x > 0.5 * worst) && d.iter().any(|&x| x < -0.5 * worst);
let grazing = pts.iter().all(|&p| {
let (ua, ub) = (sa.project(p), sb.project(p));
sa.normal(ua.x, ua.y).cross(sb.normal(ub.x, ub.y)).norm() <= tol::TANGENT
});
(crosses && grazing).then_some(worst)
}
fn tangent(sa: &Surface, sb: &Surface) -> Option<(Surface, f64)> {
let (Surface::Cylinder(a), Surface::Cylinder(b)) = (sa, sb) else {
return None;
};
let axis = a.frame.z;
if axis.cross(b.frame.z).norm() > tol::ANGULAR {
return None;
}
let w = b.frame.origin - a.frame.origin;
let off = w - axis * w.dot(axis);
let d = off.norm();
if d <= tol::LINEAR {
return None;
}
[a.radius + b.radius, (a.radius - b.radius).abs()]
.into_iter()
.filter(|&touch| touch > tol::LINEAR)
.map(|touch| touch - d)
.find(|&by| by != 0.0 && by.abs() <= SNAP)
.map(|by| {
let mut moved = b.clone();
moved.frame.origin = b.frame.origin + off * (by / d);
(Surface::Cylinder(moved), by.abs())
})
}
fn coaxial(sa: &Surface, sb: &Surface, reach: Reach) -> Option<(Surface, Option<f64>)> {
let frame = |s: &Surface| match s {
Surface::Cylinder(c) => Some(c.frame),
Surface::Cone(c) => Some(c.frame),
_ => None,
};
let (fa, fb) = (frame(sa)?, frame(sb)?);
let tilt = fa.z.cross(fb.z).norm();
if tilt > COAXIAL_TILT {
return None;
}
let w = fb.origin - fa.origin;
let along = fa.z * w.dot(fa.z);
let off = w - along;
let d = off.norm();
let across = match (reach, sa, sb) {
(Reach::Grazing, Surface::Cylinder(a), Surface::Cylinder(b)) => {
if (a.radius - b.radius).abs() <= d {
SNAP_GRAZING
} else {
SNAP
}
}
_ => SNAP,
};
let onto_axis = d <= across;
let near = match (sa, sb) {
(Surface::Cylinder(a), Surface::Cylinder(b)) => {
[a.radius + b.radius, (a.radius - b.radius).abs()]
.iter()
.any(|&touch| (touch - d).abs() <= SNAP_GRAZING)
}
_ => false,
};
if !onto_axis && (tilt <= tol::ANGULAR || !near) {
return None;
}
let origin = if onto_axis {
fa.origin + along
} else {
fb.origin
};
let z = if fa.z.dot(fb.z) < 0.0 { -fa.z } else { fa.z };
let onto = Frame::new(origin, z, fb.x).ok()?;
if onto == fb {
return None;
}
let moved = match sb {
Surface::Cylinder(c) => {
let mut c = c.clone();
c.frame = onto;
Surface::Cylinder(c)
}
Surface::Cone(c) => {
let mut c = c.clone();
c.frame = onto;
Surface::Cone(c)
}
_ => return None,
};
Some((moved, onto_axis.then_some(d)))
}
fn padded(b: &Aabb, by: f64) -> Aabb {
let d = crate::math::Vec3::new(by, by, by);
Aabb {
min: b.min - d,
max: b.max + d,
}
}
fn overlap(a: &Aabb, b: &Aabb) -> bool {
(0..3).all(|k| a.min[k] <= b.max[k] && b.min[k] <= a.max[k])
}
pub(crate) fn snapped(a: &Brep, b: &Brep, how: Reach) -> Option<Brep> {
let mut reach = Aabb::EMPTY;
for f in b.face_ids() {
reach.union(&measure::face_hull_box(b, f));
}
let reach = padded(&reach, SNAP_GRAZING);
let a_faces: Vec<(FaceId, Aabb)> = a
.face_ids()
.filter(|&f| overlap(&measure::face_hull_box(a, f), &reach))
.map(|f| (f, padded(&measure::face_box(a, f), SNAP_GRAZING)))
.collect();
let mut moved: HashMap<FaceId, Surface> = HashMap::new();
let mut gap: f64 = SNAP;
let mut within: HashMap<FaceId, Surface> = HashMap::new();
for fb in b.face_ids() {
let sb = &b.face(fb).surface;
let bb = measure::face_box(b, fb);
let mut points: Option<Vec<Point3>> = None;
let mut turn: Option<Surface> = None;
for (fa, ab) in &a_faces {
let sa = &a.face(*fa).surface;
if !overlap(ab, &bb) {
continue;
}
let turned = match coaxial(sa, sb, how) {
Some((onto, Some(by))) => {
moved.insert(fb, onto);
gap = gap.max(by);
break;
}
Some((onto, None)) => Some(onto),
None => None,
};
let sb = turned.as_ref().unwrap_or(sb);
if turn.is_none() {
turn = turned.clone();
}
if let Some((touching, by)) = tangent(sa, sb) {
moved.insert(fb, touching);
gap = gap.max(by);
break;
}
if !alike(sa, sb) {
continue;
}
if same_domain(sa, sb) {
if sa != sb {
within.entry(fb).or_insert_with(|| facing(sa, sb));
let pts = points.get_or_insert_with(|| boundary_points(b, fb));
if pts
.iter()
.all(|&p| signed_distance(sa, p).abs() >= 0.5 * tol::LINEAR)
{
moved.insert(fb, facing(sa, sb));
}
}
continue;
}
let pts = points.get_or_insert_with(|| boundary_points(b, fb));
if let Some(worst) = snaps(sa, sb, pts) {
if worst <= tol::LINEAR && !analytic(sb) {
within.entry(fb).or_insert_with(|| facing(sa, sb));
break;
}
moved.insert(fb, facing(sa, sb));
gap = gap.max(worst);
break;
}
}
if let Some(t) = turn
&& !moved.contains_key(&fb)
&& !within.contains_key(&fb)
{
moved.insert(fb, t);
}
}
if moved.is_empty() {
return None;
}
for (f, s) in within {
moved.entry(f).or_insert(s);
}
if let Some(out) = moved_whole(a, b, &moved, gap) {
return Some(out);
}
let mut order: Vec<FaceId> = moved.keys().copied().collect();
order.sort();
let mut kept: HashMap<FaceId, Surface> = HashMap::new();
let mut out = None;
for f in order {
let mut trial = kept.clone();
trial.insert(f, moved[&f].clone());
if let Some(o) = moved_whole(a, b, &trial, gap) {
kept = trial;
out = Some(o);
}
}
out
}
fn moved_whole(a: &Brep, b: &Brep, moved: &HashMap<FaceId, Surface>, gap: f64) -> Option<Brep> {
let out = tweak::move_faces_pinned(b, moved, &pins(a, b, moved, MOST_MOVED * gap)).ok()?;
let far = b
.vertex_ids()
.zip(out.vertex_ids())
.map(|(v, w)| b.vertex(v).point.dist(out.vertex(w).point))
.fold(0.0, f64::max);
(far <= MOST_MOVED * gap && check::check(&out).is_empty()).then_some(out)
}