Files
makeCAD/crates/sketch/src/link_loops.rs
T
JIJINBEI fe3b14e798 refactor: Aabb2 and point-built Aabb3 for every hand-rolled box (#2428)
* Iterate instead of indexing in nine loops

Replace index loops that look up neighbours by position with enumerate,
zip(cycle().skip(1)) for wrap-around pairs and zip(skip(1)) for
consecutive pairs. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* geom: ring_edges for the edges of a closed ring

Every walk over a polygon's edges, the last back to the first, spelled
x.iter().zip(x.iter().cycle().skip(1)); eighteen of them now call
geom::ring_edges. Three redundant take(len) calls go with them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* geom: Ring, a closed ring that knows it is closed

A Ring holds items in order around a closed polygon, loop or fan; edges()
walks each with the next and the last with the first, corners() each
with both neighbours. Ring<Vec2> has signed_area and even-odd contains.

Loop2::polyline returns a Ring, as do doc's face_loops and
boundary_loops, kernel's coplanar wire samples, CapLoop's segments,
tess pieces' rings, the gizmo's plane quads and the navigation cube's
facets. Their walks take edges() or corners() instead of wrapping an
index; sketch's text-hole test and doc's poly_area become contains and
signed_area. Loop2::joints pairs each segment with the next.

Replaces the ring_edges free function.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* geom: Chain, Ring and Path; bounds for a chain of points

Ring becomes Chain<T, Closed> beside Path = Chain<T, Open>: edges()
closes a ring and stops at a path's end, Path::close makes the ring,
and bounds() (the empty box for no points) serves both. Eight
hand-rolled min/max folds over a loop's polyline call bounds(); doc's
flat_polyline returns a Ring.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* geom: area and inside on Ring for any planar point

Ring's signed_area and contains take any Planar point (Vec2 or
[f64; 2]). The cam profile in joints_cam is a Ring: its own even-odd
test goes, and its edge walks, gap and area take edges(). face_params'
loop area, the text path's winding, tess pieces' ring area and the
copies in three tests call signed_area or contains; the formulas are
the same term for term.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* doc: sheet's closed outlines go through Ring

dedup takes and returns a Ring (dropping a last point back on the first
is what makes it a ring's), near_outline walks a Ring's edges, and the
copy of it beside fold checks calls it. point_in goes: its callers ask
the Ring. Its formula anchored each crossing on the other end of the
edge, so the two can differ only for a point on an edge to the last
digit; one caller sets such points aside first, the others test a
region's interior point, a cut's midpoint or another outline's corners.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* doc: cam tests build their outlines with Ring::from

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* geom: area_vector on Ring<Vec3>; three Newell sums use it

Ring<Vec3>::area_vector is half the sum of a × b round the ring. heal's
loop_area, lip's outer-loop turning and the revolve's loop orientation
summed it by hand with a wrapped index; they take it from the Ring
(the half is exact, and two of them only read its sign).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* geom: Aabb3 from points; boxes built and asked through it

Aabb3 collects from points (skipping non-finite ones, as add does) and
gains inflated, contains and meets. Fifteen hand-rolled min/max folds
over points or boxes in kernel, doc and engine become collect or union,
and their "within tol of the box" tests become inflated(tol).contains.
blend's refused-edge boxes and naming's face index hold an Aabb3.

A NaN point is now outside every box, where the old negated
comparisons let it in; an infinite point no longer stretches a box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* geom: Aabb2, the plane's box; 2D folds and box tuples use it

Aabb2 mirrors Aabb3 (collect, add, union, inflated, contains, meets)
and adds relative, a point's place in the box. sketch's link and
link_loops each had that formula; link_loops' boundaries, prism's
segment and loop boxes, profiles' shape boxes and grid, and ends'
segment box hold an Aabb2 instead of a (low, high) pair. Folds in the
cam, sketch bounds, sheet's perforation grid and the sketch clipboard
collect one.

Boxes are built from the same terms (a round's box keeps c - r - tol).
As with Aabb3, a NaN point is outside every box and an infinite point
no longer stretches one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kernel: prism's segment boxes are plain Aabb2s

The SegBox alias named a (low, high) pair; Aabb2 says it itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* geom: Chain::bounds is an Aabb2; the boxes #2382 left as pairs follow

Chain::bounds returns an Aabb2. Its callers keep it: sheet's hole and
cut boxes (loop_box), letter boxes, island outlines and line-near-cut
test use meets, contains and inflated; profile's outline overlap and
max_clearance, profiles' box tests and the cam test read its corners.
flat_size and the flat pattern's JSON size are the union of the loops'
boxes (0 × 0 for no loop, where the pair fold gave -∞).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* geom: Aabb3::intersection; hand-grown and hand-met boxes use the box

Aabb3::intersection is the box both hold. ops' four overlap boxes of a
boolean's operands take it, and seven boxes grown by hand (ops' body
boxes, the distance set's bounds, coplanar's face box, eval_more's
padded mesh box, compare's group and region boxes) call inflated with
the same amount on every side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
2026-10-20 03:44:49 +00:00

332 lines
14 KiB
Rust

//! Conservative analytic boundary roles for associative face identity.
//! Endpoint walks exclude support centres. Crossings/touches refuse before nesting.
use super::{LCurve, curve_points};
use crate::{Shape, intersections};
use solidcraft_geom::{Aabb2, Vec2};
use std::f64::consts::TAU;
struct Boundary {
curves: Vec<usize>,
shapes: Vec<Shape>,
bounds: Aabb2,
depth: usize,
signature: [usize; 3],
}
pub(super) struct Roles {
pub old: Vec<Vec<usize>>,
pub fresh: Vec<Vec<usize>>,
pub old_normal: Vec<Vec2>,
pub fresh_normal: Vec<Vec2>,
pub old_lines: Vec<Vec<Vec2>>,
pub fresh_lines: Vec<Vec<Vec2>>,
}
pub(super) fn same_lines(a: &[Vec2], b: &[Vec2]) -> bool {
a.len() == b.len() && a.iter().all(|x| b.iter().any(|y| x.dot(*y).abs() > 0.98))
}
fn on(s: &Shape, p: Vec2, tol: f64) -> bool {
match *s {
Shape::Line { a, b } => {
let d = b - a;
let t = (p - a).dot(d) / d.len2().max(1e-30);
t >= -tol / d.len().max(tol) && t <= 1.0 + tol / d.len().max(tol) && (a + d * t).dist(p) <= tol
}
Shape::Round { c, r, start, sweep } => {
(p.dist(c) - r).abs() <= tol && (sweep >= TAU - 1e-12 || ((p - c).angle() - start).rem_euclid(TAU) <= sweep + tol / r)
}
}
}
fn endpoints(s: &Shape) -> [Vec2; 2] {
let (_, end) = s.range();
[s.point(0.0), s.point(end)]
}
fn stable_intersections(a: &Shape, b: &Shape, tol: f64) -> Vec<Vec2> {
match (*a, *b) {
(Shape::Line { a, b }, Shape::Round { c, r, .. }) | (Shape::Round { c, r, .. }, Shape::Line { a, b }) => {
let Some(direction) = (b - a).normalized() else { return Vec::new() };
// Work in the circle's local orthonormal frame. The world-coordinate
// quadratic discriminant can lose every significant bit on long lines.
let foot = a + direction * (c - a).dot(direction);
let distance = foot.dist(c);
if distance > r + tol {
return Vec::new();
}
let half = ((r - distance).max(0.0) * (r + distance)).sqrt();
vec![foot - direction * half, foot + direction * half]
}
(Shape::Round { c: ac, r: ar, .. }, Shape::Round { c: bc, r: br, .. }) => {
let ((small, r), (large, radius)) = if ar <= br { ((ac, ar), (bc, br)) } else { ((bc, br), (ac, ar)) };
let delta = large - small;
let distance = delta.len();
if distance <= tol || distance > radius + r + tol || distance < radius - r - tol {
return Vec::new();
}
let direction = delta / distance;
// Compute from the smaller circle; factoring d^2-R^2 avoids the
// cancellation of R^2-a^2 for a small hole crossing a huge circle.
let along = ((distance - radius) * (distance + radius) + r * r) / (2.0 * distance);
let height = ((r - along).max(0.0) * (r + along).max(0.0)).sqrt();
let foot = small + direction * along;
vec![foot - direction.perp() * height, foot + direction.perp() * height]
}
_ => intersections(a, b),
}
}
fn clear(a: &Shape, b: &Shape, shared: &[Vec2], tol: f64) -> bool {
let allowed = |p: Vec2| {
shared.iter().any(|q| {
let joint_tol = 1e-7 + 128.0 * f64::EPSILON * (1.0 + p.len().max(q.len()));
q.dist(p) <= joint_tol
})
};
// Parallel coincident lines/circles have no isolated intersections.
// Interior overlap is nevertheless ambiguous, including duplicate boundaries.
for s in [a, b] {
let other = if std::ptr::eq(s, a) { b } else { a };
let (_, end) = s.range();
for t in [0.0, 0.5 * end, end] {
let p = s.point(t);
if on(other, p, tol) && !allowed(p) {
return false;
}
}
}
stable_intersections(a, b, tol).into_iter().all(|p| !on(a, p, tol) || !on(b, p, tol) || allowed(p))
}
fn contains(boundary: &Boundary, p: Vec2, tol: f64) -> Option<bool> {
let mut crossings = 0;
for shape in &boundary.shapes {
// Avoid ray/vertex coincidences rather than guessing a half-open arc rule.
if endpoints(shape).iter().any(|q| (q.y - p.y).abs() <= tol) {
return None;
}
match *shape {
Shape::Line { a, b } => {
if (a.y > p.y) != (b.y > p.y) {
let x = a.x + (p.y - a.y) * (b.x - a.x) / (b.y - a.y);
if (x - p.x).abs() <= tol {
return None;
}
crossings += usize::from(x > p.x);
}
}
Shape::Round { c, r, start, sweep } => {
let y = (p.y - c.y) / r;
if (y.abs() - 1.0).abs() <= tol / r {
return None;
}
if y.abs() < 1.0 {
let angle = y.asin();
for theta in [angle, std::f64::consts::PI - angle] {
let off = (theta - start).rem_euclid(TAU);
if off < sweep {
let x = c.x + r * theta.cos();
if (x - p.x).abs() <= tol {
return None;
}
crossings += usize::from(x > p.x);
}
}
}
}
}
}
Some(crossings % 2 == 1)
}
fn boundaries(curves: &[LCurve], pts: &[Vec2]) -> Option<Vec<Boundary>> {
let get = |i| pts.get(i).copied();
let mut shapes = Vec::new();
let mut ends = Vec::new();
let mut incidence = vec![Vec::new(); pts.len()];
for (i, curve) in curves.iter().enumerate() {
let (shape, ep) = match *curve {
LCurve::Line(a, b) => (Shape::Line { a: get(a)?, b: get(b)? }, Some((a, b))),
LCurve::Arc(c, a, b) => {
let (c, a_pos, b_pos) = (get(c)?, get(a)?, get(b)?);
let sweep = ((b_pos - c).angle() - (a_pos - c).angle()).rem_euclid(TAU);
(Shape::Round { c, r: c.dist(a_pos), start: (a_pos - c).angle(), sweep }, Some((a, b)))
}
LCurve::Circle(c, r) => (Shape::Round { c: get(c)?, r, start: 0.0, sweep: TAU }, None),
// Existing free-form identity matching remains conservative and unchanged.
_ => return None,
};
if let Some((a, b)) = ep {
incidence.get_mut(a)?.push(i);
incidence.get_mut(b)?.push(i);
}
shapes.push(shape);
ends.push(ep);
}
if incidence.iter().any(|v| !v.is_empty() && v.len() != 2) {
return None;
}
let mut visited = vec![false; curves.len()];
let mut out = Vec::new();
for first in 0..curves.len() {
if *visited.get(first)? {
continue;
}
let mut members = Vec::new();
let mut pending = vec![first];
while let Some(i) = pending.pop() {
if *visited.get(i)? {
continue;
}
*visited.get_mut(i)? = true;
members.push(i);
if let Some((a, b)) = *ends.get(i)? {
pending.extend(incidence.get(a)?);
pending.extend(incidence.get(b)?);
}
}
let mut bounds = Aabb2::EMPTY;
let mut signature = [0; 3];
let mut bound_shapes = Vec::new();
for i in &members {
let shape = *shapes.get(*i)?;
let mut candidates = endpoints(&shape).to_vec();
if let Shape::Round { c, r, .. } = shape {
for angle in [0.0, std::f64::consts::FRAC_PI_2, std::f64::consts::PI, 3.0 * std::f64::consts::FRAC_PI_2] {
let p = c + Vec2::from_angle(angle) * r;
if on(&shape, p, 1e-7) {
candidates.push(p);
}
}
}
bounds.extend(candidates);
signature[match curves.get(*i)? {
LCurve::Line(..) => 0,
LCurve::Arc(..) => 1,
_ => 2,
}] += 1;
bound_shapes.push(shape);
}
out.push(Boundary { curves: members, shapes: bound_shapes, bounds, depth: 0, signature });
}
let scale = out.iter().map(|b| b.bounds.diagonal()).fold(1.0, f64::max);
let tol = (scale * 1e-10).max(1e-7);
let mut work = 0usize;
for i in 0..out.len() {
for j in i..out.len() {
for (a_i, a) in out.get(i)?.shapes.iter().enumerate() {
for (b_i, b) in out.get(j)?.shapes.iter().enumerate() {
if i == j && a_i >= b_i {
continue;
}
work += 1;
if work > 262_144 {
return None;
}
let mut shared = Vec::new();
if i == j {
let ai = *out.get(i)?.curves.get(a_i)?;
let bi = *out.get(j)?.curves.get(b_i)?;
if let (Some((a0, a1)), Some((b0, b1))) = (*ends.get(ai)?, *ends.get(bi)?) {
for point in [a0, a1] {
if point == b0 || point == b1 {
shared.push(get(point)?);
}
}
}
}
if !clear(a, b, &shared, tol) {
return None;
}
}
}
}
}
for i in 0..out.len() {
let mut depth = 0;
for j in 0..out.len() {
if i == j {
continue;
}
let shape = out.get(i)?.shapes.first()?;
let (_, end) = shape.range();
let inside = [0.317, 0.613, 0.823].into_iter().find_map(|t| contains(out.get(j)?, shape.point(end * t), tol))?;
depth += usize::from(inside);
}
out.get_mut(i)?.depth = depth;
}
Some(out)
}
pub(super) fn valid(curves: &[LCurve], points: &[Vec2]) -> bool {
boundaries(curves, points).is_some()
}
pub(super) fn roles(old_curves: &[LCurve], a: &[Vec2], fresh_curves: &[LCurve], b: &[Vec2]) -> Option<Roles> {
let (previous, incoming) = (boundaries(old_curves, a)?, boundaries(fresh_curves, b)?);
if previous.len() != incoming.len() {
return None;
}
let bounds = |loops: &[Boundary]| loops.iter().fold(Aabb2::EMPTY, |a, x| a.union(&x.bounds));
let (outer_a, outer_b) = (bounds(&previous), bounds(&incoming));
let mut mapping = Vec::new();
for x in &previous {
let mut candidates: Vec<_> = incoming
.iter()
.enumerate()
.filter(|(_, y)| x.depth == y.depth && x.signature == y.signature)
.map(|(i, y)| (i, outer_a.relative(x.bounds.center()).dist(outer_b.relative(y.bounds.center()))))
.collect();
candidates.sort_by(|x, y| x.1.total_cmp(&y.1));
let (i, d) = *candidates.first()?;
if mapping.contains(&i) || (candidates.len() > 1 && (d >= 0.1 || candidates.get(1).is_some_and(|(_, second)| d >= second * 0.5))) {
return None;
}
let y = incoming.get(i)?;
// Preserve the conservative bound on relative boundary changes. This does
// not mistake a stationary hole's coordinates for the outer loop's scaling.
let old_size = outer_a.relative(x.bounds.max) - outer_a.relative(x.bounds.min);
let new_size = outer_b.relative(y.bounds.max) - outer_b.relative(y.bounds.min);
if old_size.dist(new_size) >= 0.1 {
return None;
}
mapping.push(i);
}
let membership = |loops: &[Boundary], curves: &[LCurve], pts: &[Vec2], remap: Option<&[usize]>| -> Option<(Vec<Vec<usize>>, Vec<Vec2>)> {
let mut roles = vec![Vec::new(); pts.len()];
let mut coordinates = vec![Vec2::ZERO; pts.len()];
for (i, loop_) in loops.iter().enumerate() {
let target = remap.and_then(|m| m.get(i)).copied().unwrap_or(i);
for curve in &loop_.curves {
for p in curve_points(curves.get(*curve)?) {
if !roles.get(p)?.contains(&target) {
roles.get_mut(p)?.push(target);
*coordinates.get_mut(p)? += loop_.bounds.relative(*pts.get(p)?);
}
}
}
}
for (role, coordinate) in roles.iter_mut().zip(&mut coordinates) {
if role.is_empty() {
return None;
}
role.sort_unstable();
*coordinate = *coordinate / role.len() as f64;
}
Some((roles, coordinates))
};
let ((old, old_normal), (fresh, fresh_normal)) =
(membership(&previous, old_curves, a, Some(&mapping))?, membership(&incoming, fresh_curves, b, None)?);
let line_roles = |loops: &[Boundary], curves: &[LCurve], pts: &[Vec2]| -> Option<Vec<Vec<Vec2>>> {
let mut roles = vec![Vec::new(); pts.len()];
for loop_ in loops {
let size = loop_.bounds.max - loop_.bounds.min;
for i in &loop_.curves {
if let LCurve::Line(a, b) = *curves.get(*i)? {
let d = *pts.get(b)? - *pts.get(a)?;
let direction = Vec2::new(d.x / size.x.max(1e-9), d.y / size.y.max(1e-9)).normalized()?;
roles.get_mut(a)?.push(direction);
roles.get_mut(b)?.push(direction);
}
}
}
Some(roles)
};
let old_lines = line_roles(&previous, old_curves, a)?;
let fresh_lines = line_roles(&incoming, fresh_curves, b)?;
Some(Roles { old, fresh, old_normal, fresh_normal, old_lines, fresh_lines })
}