fe3b14e798
* 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>
224 lines
7.2 KiB
Rust
224 lines
7.2 KiB
Rust
//! Chains of items in order: a [`Ring`] closes back on its first item (a polygon's corners, a
|
|
//! loop of segments, a fan of rays), a [`Path`] has two ends (a polyline, a sweep path). Which one
|
|
//! a chain is lives in its type, so code that walks its edges never wraps an index by hand, and
|
|
//! what only a closed chain has (an area, an inside) is only asked of a ring.
|
|
|
|
use std::marker::PhantomData;
|
|
use std::ops::Deref;
|
|
|
|
use crate::{Aabb2, Vec2, Vec3};
|
|
|
|
/// Whether a chain's last item joins its first.
|
|
pub trait Ends: sealed::Sealed {
|
|
const CLOSED: bool;
|
|
}
|
|
|
|
/// The last item joins the first: a [`Ring`].
|
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
|
pub struct Closed;
|
|
|
|
/// The first and last items are ends: a [`Path`].
|
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
|
pub struct Open;
|
|
|
|
impl Ends for Closed {
|
|
const CLOSED: bool = true;
|
|
}
|
|
|
|
impl Ends for Open {
|
|
const CLOSED: bool = false;
|
|
}
|
|
|
|
mod sealed {
|
|
pub trait Sealed {}
|
|
impl Sealed for super::Closed {}
|
|
impl Sealed for super::Open {}
|
|
}
|
|
|
|
/// Items in order, closed or open by `E`; as a slice it is the items once each.
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
|
|
pub struct Chain<T, E> {
|
|
items: Vec<T>,
|
|
ends: PhantomData<E>,
|
|
}
|
|
|
|
/// A closed chain: the last item joins the first.
|
|
pub type Ring<T> = Chain<T, Closed>;
|
|
|
|
/// An open chain from its first item to its last.
|
|
pub type Path<T> = Chain<T, Open>;
|
|
|
|
impl<T, E: Ends> Chain<T, E> {
|
|
pub fn new(items: Vec<T>) -> Chain<T, E> {
|
|
Chain { items, ends: PhantomData }
|
|
}
|
|
|
|
/// Each item with the next: as many edges as items around a ring (the last with the first;
|
|
/// a lone item pairs with itself), one fewer along a path.
|
|
pub fn edges(&self) -> impl Iterator<Item = (&T, &T)> + Clone {
|
|
let n = if E::CLOSED { self.items.len() } else { self.items.len().saturating_sub(1) };
|
|
self.items.iter().zip(self.items.iter().cycle().skip(1)).take(n)
|
|
}
|
|
|
|
pub fn into_vec(self) -> Vec<T> {
|
|
self.items
|
|
}
|
|
}
|
|
|
|
impl<T> Ring<T> {
|
|
/// Each item with the one before and the one after it: `(previous, item, next)`, once per
|
|
/// item.
|
|
pub fn corners(&self) -> impl Iterator<Item = (&T, &T, &T)> + Clone {
|
|
let before = self.items.iter().cycle().skip(self.items.len().saturating_sub(1));
|
|
before.zip(self.edges()).map(|(p, (c, x))| (p, c, x))
|
|
}
|
|
}
|
|
|
|
impl<T> Path<T> {
|
|
/// The ring through the same items: the last joined back to the first.
|
|
pub fn close(self) -> Ring<T> {
|
|
Chain::new(self.items)
|
|
}
|
|
}
|
|
|
|
impl<E: Ends> Chain<Vec2, E> {
|
|
/// The smallest box holding every item (empty for an empty chain).
|
|
pub fn bounds(&self) -> Aabb2 {
|
|
self.items.iter().copied().collect()
|
|
}
|
|
}
|
|
|
|
/// A point in a plane, whichever type holds it.
|
|
pub trait Planar: Copy {
|
|
fn xy(self) -> (f64, f64);
|
|
}
|
|
|
|
impl Planar for Vec2 {
|
|
fn xy(self) -> (f64, f64) {
|
|
(self.x, self.y)
|
|
}
|
|
}
|
|
|
|
impl Planar for [f64; 2] {
|
|
fn xy(self) -> (f64, f64) {
|
|
(self[0], self[1])
|
|
}
|
|
}
|
|
|
|
impl<P: Planar> Ring<P> {
|
|
/// The area the ring encloses, positive when it runs counter-clockwise.
|
|
pub fn signed_area(&self) -> f64 {
|
|
0.5 * self
|
|
.edges()
|
|
.map(|(a, b)| {
|
|
let ((ax, ay), (bx, by)) = (a.xy(), b.xy());
|
|
ax * by - ay * bx
|
|
})
|
|
.sum::<f64>()
|
|
}
|
|
|
|
/// Even-odd containment: whether a ray from `p` along +x crosses the ring an odd number of
|
|
/// times.
|
|
pub fn contains(&self, p: P) -> bool {
|
|
let (px, py) = p.xy();
|
|
let mut inside = false;
|
|
for (a, b) in self.edges() {
|
|
let ((ax, ay), (bx, by)) = (a.xy(), b.xy());
|
|
if (ay > py) != (by > py) && px < ax + (py - ay) / (by - ay) * (bx - ax) {
|
|
inside = !inside;
|
|
}
|
|
}
|
|
inside
|
|
}
|
|
}
|
|
|
|
impl Ring<Vec3> {
|
|
/// The ring's vector area (Newell's method): its direction the normal the ring turns about,
|
|
/// its length the area it encloses when flat; `area_vector().dot(n)` is the area seen along
|
|
/// the unit vector `n`, positive when the ring runs counter-clockwise about it.
|
|
pub fn area_vector(&self) -> Vec3 {
|
|
self.edges().fold(Vec3::ZERO, |s, (a, b)| s + a.cross(*b)) * 0.5
|
|
}
|
|
}
|
|
|
|
/// [`Ring::edges`] of items held elsewhere, for a type that keeps a closed ring in a field of its
|
|
/// own ([`crate::Loop2::joints`]).
|
|
pub(crate) fn around<T>(items: &[T]) -> impl Iterator<Item = (&T, &T)> + Clone {
|
|
items.iter().zip(items.iter().cycle().skip(1))
|
|
}
|
|
|
|
impl<T, E> Deref for Chain<T, E> {
|
|
type Target = [T];
|
|
fn deref(&self) -> &[T] {
|
|
&self.items
|
|
}
|
|
}
|
|
|
|
impl<T, E> IntoIterator for Chain<T, E> {
|
|
type Item = T;
|
|
type IntoIter = std::vec::IntoIter<T>;
|
|
fn into_iter(self) -> std::vec::IntoIter<T> {
|
|
self.items.into_iter()
|
|
}
|
|
}
|
|
|
|
impl<'a, T, E> IntoIterator for &'a Chain<T, E> {
|
|
type Item = &'a T;
|
|
type IntoIter = std::slice::Iter<'a, T>;
|
|
fn into_iter(self) -> std::slice::Iter<'a, T> {
|
|
self.items.iter()
|
|
}
|
|
}
|
|
|
|
impl<T, E: Ends> From<Vec<T>> for Chain<T, E> {
|
|
fn from(items: Vec<T>) -> Chain<T, E> {
|
|
Chain::new(items)
|
|
}
|
|
}
|
|
|
|
impl<T, E: Ends, const N: usize> From<[T; N]> for Chain<T, E> {
|
|
fn from(items: [T; N]) -> Chain<T, E> {
|
|
Chain::new(items.into())
|
|
}
|
|
}
|
|
|
|
impl<T, E: Ends> FromIterator<T> for Chain<T, E> {
|
|
fn from_iter<I: IntoIterator<Item = T>>(items: I) -> Chain<T, E> {
|
|
Chain::new(items.into_iter().collect())
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn a_ring_closes_and_a_path_does_not() {
|
|
assert_eq!(Ring::from([1, 2, 3]).edges().collect::<Vec<_>>(), vec![(&1, &2), (&2, &3), (&3, &1)]);
|
|
assert_eq!(Path::from([1, 2, 3]).edges().collect::<Vec<_>>(), vec![(&1, &2), (&2, &3)]);
|
|
assert_eq!(Path::from([1, 2, 3]).close().edges().count(), 3);
|
|
assert_eq!(Ring::from([7]).edges().collect::<Vec<_>>(), vec![(&7, &7)]);
|
|
assert_eq!(Path::from([7]).edges().count(), 0);
|
|
assert_eq!(Ring::<u8>::default().edges().count(), 0);
|
|
assert_eq!(Path::<u8>::default().edges().count(), 0);
|
|
assert_eq!(Ring::from([1, 2, 3]).corners().collect::<Vec<_>>(), vec![(&3, &1, &2), (&1, &2, &3), (&2, &3, &1)]);
|
|
assert_eq!(Ring::<u8>::default().corners().count(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn a_square_encloses_its_area_and_its_inside() {
|
|
let square = Ring::from([Vec2::new(0.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(2.0, 2.0), Vec2::new(0.0, 2.0)]);
|
|
assert_eq!(square.signed_area(), 4.0);
|
|
assert_eq!(square.iter().rev().copied().collect::<Ring<_>>().signed_area(), -4.0);
|
|
assert!(square.contains(Vec2::new(1.0, 1.0)));
|
|
assert!(!square.contains(Vec2::new(3.0, 1.0)));
|
|
let uv = Ring::from([[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]]);
|
|
assert_eq!(uv.signed_area(), 4.0);
|
|
let tilted = Ring::from([Vec3::new(0.0, 0.0, 1.0), Vec3::new(2.0, 0.0, 1.0), Vec3::new(2.0, 2.0, 1.0), Vec3::new(0.0, 2.0, 1.0)]);
|
|
assert_eq!(tilted.area_vector(), Vec3::new(0.0, 0.0, 4.0));
|
|
assert!(uv.contains([1.0, 1.0]) && !uv.contains([3.0, 1.0]));
|
|
assert_eq!(square.bounds(), Aabb2 { min: Vec2::new(0.0, 0.0), max: Vec2::new(2.0, 2.0) });
|
|
assert!(Path::<Vec2>::default().bounds().is_empty());
|
|
}
|
|
}
|