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>
This commit is contained in:
JIJINBEI
2026-10-20 03:44:49 +00:00
committed by GitHub
parent e27d43553c
commit fe3b14e798
58 changed files with 762 additions and 693 deletions
+3 -3
View File
@@ -1,10 +1,10 @@
//! Navigation drawing definitions. Camera projection and picking remain in the UI widgets.
use crate::theme::Tokens;
use egui::{Align2, Color32, FontId, Pos2, Rect, Shape, Stroke, pos2, vec2};
use solidcraft_engine::geom::Vec3;
use solidcraft_engine::geom::{Ring, Vec3};
pub(crate) struct Facet {
pub(crate) direction: Vec3,
pub(crate) points: Vec<Pos2>,
pub(crate) points: Ring<Pos2>,
pub(crate) outer_edges: Vec<bool>,
pub(crate) centre: Pos2,
pub(crate) label: String,
@@ -89,7 +89,7 @@ pub(crate) fn paint_cube(painter: &egui::Painter, faces: &[Facet], hovered: Opti
for &p in &face.points {
fill_mesh.colored_vertex(p, fill);
}
for (j, (&a, &b)) in face.points.iter().zip(face.points.iter().cycle().skip(1)).take(face.points.len()).enumerate() {
for (j, (&a, &b)) in face.points.edges().enumerate() {
fill_mesh.add_triangle(centre, centre + 1 + j as u32, centre + 1 + ((j + 1) % face.points.len()) as u32);
// Coplanar picking regions have no visible seams. Only actual cube
// edges and the hovered target's boundary receive an outline.
+1 -6
View File
@@ -1944,12 +1944,7 @@ pub fn through_all_distance(st: &ModelState, plane: &Plane, targets: &[String])
/// Sample points inside a region (sketch coordinates).
fn region_samples(r: &Region2) -> Vec<Vec2> {
let mut out = vec![r.interior_point()];
let pts = r.outer.polyline(1e-2);
let (mut lo, mut hi) = (Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY));
for p in &pts {
lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y));
hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y));
}
let solidcraft_geom::Aabb2 { min: lo, max: hi } = r.outer.polyline(1e-2).bounds();
for i in 0..5 {
for j in 0..5 {
let p = Vec2::new(lo.x + (hi.x - lo.x) * (0.1 + 0.2 * i as f64), lo.y + (hi.y - lo.y) * (0.1 + 0.2 * j as f64));
+12 -19
View File
@@ -5,7 +5,7 @@ use super::*;
use crate::EmbossFace;
use crate::apply_point;
use crate::sheet;
use solidcraft_geom::{Aabb3, Loop2, Seg2};
use solidcraft_geom::{Aabb3, Loop2, Ring, Seg2};
pub(super) fn eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st: &mut ModelState) -> Result<()> {
match &f.kind {
@@ -775,11 +775,6 @@ pub(super) fn sheet_eval(
}
}
fn poly_area(p: &[Vec2]) -> f64 {
let m = p.len();
(0..m).filter_map(|i| Some(p.get(i)?.cross(*p.get((i + 1) % m)?))).sum::<f64>() / 2.0
}
/// Current unmodified extrusion caps, including placement, certify the tool's depth.
/// Tessellation can drift in thickness at distant coordinates and cannot certify a slab.
fn sheet_tool_span(body: &Body, source: &Plane) -> Option<(f64, f64, f64, Option<(Plane, Region2)>)> {
@@ -1363,9 +1358,7 @@ fn mesh_box(mb: &ModelBody) -> Option<Aabb3> {
fn padded_box(mesh: &solidcraft_geom::Mesh, tol: f64) -> Option<Aabb3> {
let b = mesh.bounds();
let pad = 2.0 * tol + 1e-6;
let pad = Vec3::new(pad, pad, pad);
(!b.is_empty() && b.min.is_finite() && b.max.is_finite()).then(|| Aabb3 { min: b.min - pad, max: b.max + pad })
(!b.is_empty() && b.min.is_finite() && b.max.is_finite()).then(|| b.inflated(2.0 * tol + 1e-6))
}
/// Whether two boxes are known to be apart (an unknown box is never apart).
@@ -1405,7 +1398,7 @@ fn parted_note(sh: &sheet::SheetBody, material: &[Region2], before: &sheet::Shee
/// Outline loops (in `plane` coordinates) of the mesh triangles lying in the plane at distance
/// `level` from `at` along `n`: the edges used by one of them only, chained.
fn face_loops(mesh: &solidcraft_geom::Mesh, plane: &Plane, at: Vec3, n: Vec3, level: f64, tol: f64) -> Vec<Vec<Vec2>> {
fn face_loops(mesh: &solidcraft_geom::Mesh, plane: &Plane, at: Vec3, n: Vec3, level: f64, tol: f64) -> Vec<Ring<Vec2>> {
face_outline(mesh, plane, at, n, level, tol).into_iter().map(|l| l.into_iter().map(|(p, _)| p).collect()).collect()
}
@@ -1443,7 +1436,7 @@ fn face_outline(mesh: &solidcraft_geom::Mesh, plane: &Plane, at: Vec3, n: Vec3,
}
/// The loops (in `plane` coordinates) that bound the triangles `on` of the mesh.
fn boundary_loops(mesh: &solidcraft_geom::Mesh, plane: &Plane, on: &[[u32; 3]]) -> Vec<Vec<Vec2>> {
fn boundary_loops(mesh: &solidcraft_geom::Mesh, plane: &Plane, on: &[[u32; 3]]) -> Vec<Ring<Vec2>> {
chain_loops(mesh, plane, on, |_, _| None).into_iter().map(|l| l.into_iter().map(|(p, _)| p).collect()).collect()
}
@@ -1640,7 +1633,7 @@ fn plate_recesses(body: &Body, mesh: &Mesh, plane: &Plane, at: Vec3, n: Vec3, (l
for (f, d, ..) in &floors {
let on: Vec<[u32; 3]> = fine.triangles.iter().zip(&fine.tri_face).filter(|(_, g)| **g as usize == *f).map(|(tri, _)| *tri).collect();
let mut loops = boundary_loops(&fine, plane, &on);
loops.sort_by(|a, b| poly_area(b).abs().total_cmp(&poly_area(a).abs()));
loops.sort_by(|a, b| b.signed_area().abs().total_cmp(&a.signed_area().abs()));
let mut it = loops.into_iter();
let Some(outline) = it.next() else { continue };
let region = Region2 { outer: Loop2::polygon(&outline).ccw(), holes: it.map(|l| Loop2::polygon(&l).ccw().reversed()).collect() };
@@ -1837,24 +1830,24 @@ pub(super) fn plastic_eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &F
let tol = (mb.body.size() * 1e-3).max(1e-3);
let mesh = mb.body.tessellate(tol)?;
let mut loops = face_loops(&mesh, &plane, face.0, n, 0.0, tol);
loops.sort_by(|a, b| poly_area(b).abs().total_cmp(&poly_area(a).abs()));
let ccw = |l: &[Vec2]| if poly_area(l) < 0.0 { l.iter().rev().copied().collect::<Vec<_>>() } else { l.to_vec() };
loops.sort_by(|a, b| b.signed_area().abs().total_cmp(&a.signed_area().abs()));
let ccw = |l: &Ring<Vec2>| if l.signed_area() < 0.0 { l.iter().rev().copied().collect::<Ring<_>>() } else { l.clone() };
// The inner edge is an opening (the cavity under a rim): not the foot of a boss or a
// wall standing on the face, whose side the band would run against.
let opening = |l: &[Vec2]| {
let opening = |l: &Ring<Vec2>| {
let eps = (tol * 4.0).max(1e-3);
l.iter().zip(l.iter().cycle().skip(1)).filter_map(|(a, b)| Some(((*a + *b) * 0.5, (*b - *a).normalized()?))).take(3).any(|(m, t)| {
l.edges().filter_map(|(a, b)| Some(((*a + *b) * 0.5, (*b - *a).normalized()?))).take(3).any(|(m, t)| {
// Just over the face, inside the loop (to the left of a ccw loop's edges).
let q = plane.to_world(m + Vec2::new(-t.y, t.x) * eps) + n * eps;
!mesh.contains(q)
})
};
let outer = loops.first().map(|l| ccw(l));
let openings: Vec<Vec<Vec2>> = loops.iter().skip(1).map(|l| ccw(l)).filter(|l| opening(l)).collect();
let outer = loops.first().map(ccw);
let openings: Vec<Ring<Vec2>> = loops.iter().skip(1).map(ccw).filter(|l| opening(l)).collect();
// A rim runs round one opening, the cavity; smaller ones (a screw hole) may sit in it.
// Openings alike in size (a plate's holes) leave no edge that is the rim's.
let alike = match openings.as_slice() {
[a, b, ..] => poly_area(b).abs() > 0.5 * poly_area(a).abs(),
[a, b, ..] => b.signed_area().abs() > 0.5 * a.signed_area().abs(),
_ => false,
};
let (Some(outer), Some(inner), false) = (outer, openings.first().cloned(), alike) else {
+9 -10
View File
@@ -17,7 +17,7 @@
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use serde::{Deserialize, Serialize};
use solidcraft_geom::Vec3;
use solidcraft_geom::{Aabb3, Vec3};
use solidcraft_sketch::linalg;
@@ -1209,15 +1209,14 @@ fn limit_bounds(tree: &Tree, vars: &[(u64, usize)]) -> Vec<(f64, f64)> {
/// The loops' size: the diagonal of the box around their joints' A frames, 1 mm to 1 km. Points
/// that far apart weigh turns like moves.
fn loop_scale(tree: &Tree, around: &BTreeSet<u64>, vals: &Values) -> f64 {
let (mut lo, mut hi) = (Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN));
for id in around {
let (Some(j), Some((fa, _))) = (tree.joints.get(id), tree.frames.get(id)) else { continue };
let Some(t) = tree.world(j.a.occurrence, vals) else { continue };
let p = apply_point(&mat_mul(&t, fa), Vec3::ZERO);
lo = Vec3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z));
hi = Vec3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z));
}
if lo.x <= hi.x { (hi - lo).len().clamp(1.0, 1e6) } else { 1.0 }
let joints: Aabb3 = around
.iter()
.filter_map(|id| {
let (j, (fa, _)) = (tree.joints.get(id)?, tree.frames.get(id)?);
Some(apply_point(&mat_mul(&tree.world(j.a.occurrence, vals)?, fa), Vec3::ZERO))
})
.collect();
if joints.is_empty() { 1.0 } else { joints.diagonal().clamp(1.0, 1e6) }
}
/// How far each closing joint is from meeting: three points of B's joint frame, `scale` apart,
+25 -53
View File
@@ -15,7 +15,7 @@
use std::f64::consts::TAU;
use serde::{Deserialize, Serialize};
use solidcraft_geom::{Vec2, Vec3};
use solidcraft_geom::{Aabb2, Aabb3, Ring, Vec2, Vec3};
use super::{JointKind, JointOrigin, MotionLink, Size, component_bodies, component_of, flip_of, occurrence_world, size_of};
use crate::{DocError, Document, IDENTITY, Mat, ModelState, Result, apply_point, apply_vector, mat_inverse, mat_mul};
@@ -108,7 +108,7 @@ fn rot(v: Vec2, a: f64) -> Vec2 {
/// Where a translating follower coming along `-d` from far along its line through `g` first
/// touches the closed polygon `poly`: the largest `t` of its point `g + t·d` (its roller's centre
/// for `r > 0`; for `flat`, its face square to `d`). `None` when it misses the profile.
pub fn first_contact_along(poly: &[Vec2], g: Vec2, d: Vec2, r: f64, flat: bool) -> Option<f64> {
pub fn first_contact_along(poly: &Ring<Vec2>, g: Vec2, d: Vec2, r: f64, flat: bool) -> Option<f64> {
let n = d.perp();
let mut best: Option<f64> = None;
let mut take = |t: f64| {
@@ -122,9 +122,7 @@ pub fn first_contact_along(poly: &[Vec2], g: Vec2, d: Vec2, r: f64, flat: bool)
}
return best;
}
let count = poly.len();
for i in 0..count {
let (Some(&p), Some(&q)) = (poly.get(i), poly.get((i + 1) % count)) else { continue };
for (&p, &q) in poly.edges() {
let (a, b) = ((p - g).dot(n), (q - g).dot(n));
// Edges wholly outside the band the follower sweeps.
if a.min(b) > r || a.max(b) < -r {
@@ -167,10 +165,8 @@ pub fn first_contact_along(poly: &[Vec2], g: Vec2, d: Vec2, r: f64, flat: bool)
/// The angles in [0, 2π) where an oscillating follower's tip touches the closed polygon `poly`:
/// its tip (a roller's centre for `r > 0`) at `arm` from the pivot `pivot`, turned from the angle
/// `start` the way `turn` says (+1 counter-clockwise), sorted.
fn touches_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, start: f64, turn: f64) -> Vec<f64> {
fn touches_turning(poly: &Ring<Vec2>, pivot: Vec2, arm: f64, r: f64, start: f64, turn: f64) -> Vec<f64> {
let tip = |a: f64| pivot + Vec2::from_angle(a) * arm;
let count = poly.len();
let edge = |i: usize| Some((*poly.get(i)?, *poly.get((i + 1) % count)?));
let mut out = Vec::new();
let mut take = |a: f64, keep: &dyn Fn(Vec2) -> bool| {
let turned = (turn * (a - start)).rem_euclid(TAU);
@@ -187,7 +183,7 @@ fn touches_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, start: f64, tur
let (base, spread) = (w.angle(), (h / len).clamp(-1.0, 1.0).acos());
vec![base + spread, base - spread]
};
for (p, q) in (0..count).filter_map(edge) {
for (&p, &q) in poly.edges() {
let near = dist_to_segment(pivot, p, q);
let far = (p - pivot).len().max((q - pivot).len());
if near > arm + r || far < arm - r {
@@ -216,19 +212,17 @@ fn touches_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, start: f64, tur
/// Whether an oscillating follower's tip, turned `turned` from `start` the way `turn` says,
/// overlaps the profile by more than `slack`.
fn overlaps_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, (start, turn): (f64, f64), turned: f64, slack: f64) -> bool {
fn overlaps_turning(poly: &Ring<Vec2>, pivot: Vec2, arm: f64, r: f64, (start, turn): (f64, f64), turned: f64, slack: f64) -> bool {
let at = pivot + Vec2::from_angle(start + turn * turned) * arm;
let n = poly.len();
let gap =
(0..n).filter_map(|i| Some((*poly.get(i)?, *poly.get((i + 1) % n)?))).map(|(p, q)| dist_to_segment(at, p, q)).fold(f64::INFINITY, f64::min);
let gap = poly.edges().map(|(p, q)| dist_to_segment(at, *p, *q)).fold(f64::INFINITY, f64::min);
// Inside counts only clear of the boundary: a knife on an edge touches it.
gap < r - slack || (gap > slack && inside(poly, at))
gap < r - slack || (gap > slack && poly.contains(at))
}
/// Where an oscillating follower first touches the closed polygon `poly` turning from `start`
/// (the angle it turns through, in (0, 2π)): see `touches_turning`. `None` when it misses the
/// profile or starts on it.
pub fn first_contact_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, start: f64, turn: f64) -> Option<f64> {
pub fn first_contact_turning(poly: &Ring<Vec2>, pivot: Vec2, arm: f64, r: f64, start: f64, turn: f64) -> Option<f64> {
if overlaps_turning(poly, pivot, arm, r, (start, turn), 0.0, -f64::EPSILON) {
return None;
}
@@ -239,7 +233,7 @@ pub fn first_contact_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, start
/// after the cam turned on a little: pushed back to where the profile now lets it be when its tip
/// overlaps the profile (by more than `slack`), else on to where it next touches. It stays on the
/// part of the profile it rides, however the profile crosses its tip's circle elsewhere.
pub fn next_contact_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, (start, turn): (f64, f64), from: f64, slack: f64) -> Option<f64> {
pub fn next_contact_turning(poly: &Ring<Vec2>, pivot: Vec2, arm: f64, r: f64, (start, turn): (f64, f64), from: f64, slack: f64) -> Option<f64> {
let touches = touches_turning(poly, pivot, arm, r, start, turn);
// A touch where the tip is clear of the rest of the profile (a roller inside the profile is a
// radius from the parallels of the edges near the one it overlaps too).
@@ -257,23 +251,10 @@ fn dist_to_segment(x: Vec2, p: Vec2, q: Vec2) -> f64 {
x.dist(p + d * t)
}
/// Even-odd containment in a closed polygon.
fn inside(poly: &[Vec2], x: Vec2) -> bool {
let n = poly.len();
let mut inside = false;
for i in 0..n {
let (Some(a), Some(b)) = (poly.get(i), poly.get((i + 1) % n)) else { continue };
if (a.y > x.y) != (b.y > x.y) && x.x < a.x + (x.y - a.y) / (b.y - a.y) * (b.x - a.x) {
inside = !inside;
}
}
inside
}
/// Everything a cam's table is worked out from, in the cam's fixed frame C.
struct Setup {
/// The profile at cam value 0.
poly: Vec<Vec2>,
poly: Ring<Vec2>,
/// +1 when the cam turns by +value about C's z (it is the joint's b side), −1 otherwise.
turn: f64,
/// A translating follower's line (a point and its unit direction, the slider's +z), or an
@@ -517,19 +498,11 @@ fn sampled(lp: &solidcraft_geom::Loop2, tol: f64) -> Option<Vec<Vec2>> {
/// The diagonal of the box around some points (0 for none).
fn extent<'a>(pts: impl Iterator<Item = &'a Vec3>) -> f64 {
let (lo, hi) = pts.fold((Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)), |(lo, hi), p| {
(Vec3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z)), Vec3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z)))
});
if lo.x <= hi.x { (hi - lo).len() } else { 0.0 }
pts.copied().collect::<Aabb3>().diagonal()
}
fn bounds_2d(pts: &[Vec2]) -> f64 {
let (mut lo, mut hi) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN));
for p in pts {
lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y));
hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y));
}
if lo.x <= hi.x { (hi - lo).len() } else { 0.0 }
pts.iter().copied().collect::<Aabb2>().diagonal()
}
/// The chord error a profile is sampled to: 0.1 µm per 100 mm of its size, at least 0.1 µm.
@@ -569,7 +542,7 @@ fn setup(doc: &Document, st: &ModelState, l: &MotionLink, c: &Cam) -> Result<Set
if v.iter().any(|p| (p.z - mean).abs() > 1e-6 * size + 1e-9) {
return Err(bad("the profile must lie in a plane square to the cam's axis"));
}
let poly: Vec<Vec2> = v.iter().map(|p| Vec2::new(p.x, p.y)).collect();
let poly: Ring<Vec2> = v.iter().map(|p| Vec2::new(p.x, p.y)).collect();
if !poly.iter().all(|p| p.is_finite()) || area(&poly).abs() <= 1e-12 * size * size {
return Err(bad("the profile encloses no area"));
}
@@ -709,9 +682,9 @@ fn follower_is_b(doc: &Document, cam_joint: &super::Joint, fol: &super::Joint, (
/// A polygon's signed area, from its first point (so a small profile far from the axis keeps its
/// digits).
fn area(poly: &[Vec2]) -> f64 {
let (n, o) = (poly.len(), poly.first().copied().unwrap_or(Vec2::ZERO));
(0..n).filter_map(|i| Some((*poly.get(i)? - o).cross(*poly.get((i + 1) % n)? - o))).sum::<f64>() / 2.0
fn area(poly: &Ring<Vec2>) -> f64 {
let o = poly.first().copied().unwrap_or(Vec2::ZERO);
poly.edges().map(|(p, q)| (*p - o).cross(*q - o)).sum::<f64>() / 2.0
}
/// The follower's places at the samples 0 ..= `CAM_SAMPLES` of a turn, `place(u, prev)` giving
@@ -816,7 +789,7 @@ mod tests {
use super::*;
/// A circle of radius `r` about `c` as a polygon of `n` points (its sag is r·(1 − cos π/n)).
fn circle(c: Vec2, r: f64, n: usize) -> Vec<Vec2> {
fn circle(c: Vec2, r: f64, n: usize) -> Ring<Vec2> {
(0..n).map(|k| c + Vec2::from_angle(TAU * k as f64 / n as f64) * r).collect()
}
@@ -874,10 +847,9 @@ mod tests {
}
// Followed on from where it touches, it stays on the part of the profile it rides: a C
// whose two arms both cross the tip's circle, the tip resting on the second arm.
let c: Vec<Vec2> = [(-10.0, 20.0), (30.0, 20.0), (30.0, 14.0), (-4.0, 14.0), (-4.0, -14.0), (30.0, -14.0), (30.0, -20.0), (-10.0, -20.0)]
.into_iter()
.map(|(x, y)| Vec2::new(x, y))
.collect();
let c = Ring::from(
[[-10.0, 20.0], [30.0, 20.0], [30.0, 14.0], [-4.0, 14.0], [-4.0, -14.0], [30.0, -14.0], [30.0, -20.0], [-10.0, -20.0]].map(Vec2::from),
);
let (pv, l) = (Vec2::new(40.0, 0.0), 22.0);
let touches = touches_turning(&c, pv, l, 0.0, 0.0, 1.0);
let on = |t: f64| (pv + Vec2::from_angle(t) * l).y;
@@ -887,12 +859,12 @@ mod tests {
let stay = next_contact_turning(&c, pv, l, 0.0, (0.0, 1.0), second, 1e-9).unwrap_or(f64::NAN);
assert!((stay - second).abs() < 1e-12, "{stay} vs {second}");
// A knife on an edge touches it, it doesn't overlap it; just inside, it does.
let square: Vec<Vec2> = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].into_iter().map(|(x, y)| Vec2::new(x, y)).collect();
let square = Ring::from([[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]].map(Vec2::from));
let (pv, l) = (Vec2::new(0.0, -4.0), 3.0);
let up = std::f64::consts::FRAC_PI_2;
assert!(!overlaps_turning(&square, pv, l, 0.0, (up, 1.0), 0.0, 1e-9));
assert!(overlaps_turning(&square, pv, l + 0.01, 0.0, (up, 1.0), 0.0, 1e-9));
assert!((area(&square.iter().map(|p| *p * 0.004 + Vec2::new(524_288.0, 524_288.0)).collect::<Vec<_>>()) - 6.4e-5).abs() < 1e-12);
assert!((area(&square.iter().map(|p| *p * 0.004 + Vec2::new(524_288.0, 524_288.0)).collect::<Ring<_>>()) - 6.4e-5).abs() < 1e-12);
// An arm that can't reach, and one that starts on the cam.
let poly = circle(Vec2::new(e, 0.0), r, 512);
assert_eq!(first_contact_turning(&poly, pivot, 5.0, 0.0, start, 1.0), None);
@@ -903,7 +875,7 @@ mod tests {
/// comes back after the turn: refused. On the eccentric circle it follows smoothly.
#[test]
fn a_follower_that_jumps_is_refused() {
let arm_round = |poly: &[Vec2], pivot: Vec2, arm: f64| {
let arm_round = |poly: &Ring<Vec2>, pivot: Vec2, arm: f64| {
let start = pivot.angle();
let place = |u: f64, prev: Option<f64>| -> Result<f64> {
let q = -TAU * u / CAM_SAMPLES as f64;
@@ -916,7 +888,7 @@ mod tests {
};
round(&place, true, 1e-6)
};
let lobes: Vec<Vec2> = (0..240)
let lobes: Ring<Vec2> = (0..240)
.map(|k| {
let t = TAU * f64::from(k) / 240.0;
Vec2::from_angle(t) * (28.0 + 2.0 / 3.0 + 13.0 * (3.0 * t).cos())
+9 -16
View File
@@ -17,7 +17,7 @@
use std::sync::{Arc, OnceLock};
use solidcraft_geom::{Mesh, Seg2, Vec2, Vec3};
use solidcraft_geom::{Aabb3, Mesh, Seg2, Vec2, Vec3};
use crate::history_names::Names;
use crate::lineage::Lineage;
@@ -156,20 +156,16 @@ pub(crate) fn closest(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> Vec3 {
/// A body's faces as triangle lists with bounding boxes, for "does this point lie on face f".
struct FaceIndex {
faces: Vec<(Vec3, Vec3, Vec<[Vec3; 3]>)>,
faces: Vec<(Aabb3, Vec<[Vec3; 3]>)>,
}
impl FaceIndex {
fn new(m: &Mesh, nf: usize) -> FaceIndex {
let mut faces: Vec<(Vec3, Vec3, Vec<[Vec3; 3]>)> =
vec![(Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN), Vec::new()); nf];
let mut faces: Vec<(Aabb3, Vec<[Vec3; 3]>)> = vec![(Aabb3::EMPTY, Vec::new()); nf];
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
if let (Some(slot), Some(tri)) = (faces.get_mut(*f as usize), m.tri(t)) {
for p in tri {
slot.0 = Vec3::new(slot.0.x.min(p.x), slot.0.y.min(p.y), slot.0.z.min(p.z));
slot.1 = Vec3::new(slot.1.x.max(p.x), slot.1.y.max(p.y), slot.1.z.max(p.z));
}
slot.2.push(tri);
slot.0.extend(tri);
slot.1.push(tri);
}
}
FaceIndex { faces }
@@ -178,8 +174,8 @@ impl FaceIndex {
/// The face a point lies on (within `tol`).
fn face_at(&self, p: Vec3, tol: f64) -> Option<usize> {
let mut best: Option<(f64, usize)> = None;
for (i, (lo, hi, tris)) in self.faces.iter().enumerate() {
if p.x < lo.x - tol || p.y < lo.y - tol || p.z < lo.z - tol || p.x > hi.x + tol || p.y > hi.y + tol || p.z > hi.z + tol {
for (i, (bounds, tris)) in self.faces.iter().enumerate() {
if !bounds.inflated(tol).contains(p) {
continue;
}
let d = tris.iter().map(|[a, b, c]| closest(p, *a, *b, *c).dist(p)).fold(f64::MAX, f64::min);
@@ -392,7 +388,7 @@ fn behind(ps: &[Vec3], ns: &[Vec3], inputs: &[(&ModelBody, FaceIndex, Arc<Vec<St
for p in ps {
let mut best: Option<(f64, String)> = None;
for (_, idx, nm) in inputs {
for (fi, (_, _, tris)) in idx.faces.iter().enumerate() {
for (fi, (_, tris)) in idx.faces.iter().enumerate() {
for [a, b, c] in tris {
if let Some(t) = ray_hit(*p, d, *a, *b, *c)
&& t > 1e-9
@@ -497,10 +493,7 @@ fn number_pieces(names: &mut [String], pts: &[Vec<Vec3>], mark: char) {
ps.iter().fold(Vec3::ZERO, |a, p| a + *p) * (1.0 / ps.len().max(1) as f64)
};
let cs: Vec<(usize, Vec3)> = same.iter().map(|j| (*j, centre(*j))).collect();
let (lo, hi) = cs.iter().fold((Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)), |(l, h), (_, c)| {
(Vec3::new(l.x.min(c.x), l.y.min(c.y), l.z.min(c.z)), Vec3::new(h.x.max(c.x), h.y.max(c.y), h.z.max(c.z)))
});
let ext = hi - lo;
let ext = cs.iter().map(|(_, c)| *c).collect::<Aabb3>().size();
let key = |c: Vec3| {
if ext.x >= ext.y && ext.x >= ext.z {
(c.x, c.y, c.z)
+4 -5
View File
@@ -767,14 +767,13 @@ fn merge_split_circles(geom: Vec<LinkGeom>) -> Vec<LinkGeom> {
const TOL: f64 = 1e-6;
let near = |p: Vec2, q: Vec2| p.dist(q) <= TOL * (1.0 + p.len().max(q.len()));
let mut out = geom.clone();
for i in 0..geom.len() {
let Some(LinkGeom::Arc { c, a, b }) = geom.get(i).cloned() else { continue };
for j in i + 1..geom.len() {
if let Some(LinkGeom::Arc { c: c2, a: a2, b: b2 }) = geom.get(j).cloned()
for (i, first) in geom.iter().enumerate() {
let LinkGeom::Arc { c, a, b } = *first else { continue };
for (second, slot) in geom.iter().zip(out.iter_mut()).skip(i + 1) {
if let LinkGeom::Arc { c: c2, a: a2, b: b2 } = *second
&& near(c, c2)
&& near(a, a2)
&& near(b, b2)
&& let Some(slot) = out.get_mut(j)
{
*slot = LinkGeom::Arc { c, a: b, b: a };
}
+3 -4
View File
@@ -3,7 +3,7 @@
use std::collections::{BTreeMap, BTreeSet};
use solidcraft_geom::{Mesh, Plane, Vec3};
use solidcraft_geom::{Aabb3, Mesh, Plane, Vec3};
use crate::{DocError, Result};
@@ -68,9 +68,8 @@ fn boundary_edges(mesh: &Mesh, mut edges: Vec<usize>, faces: &BTreeSet<usize>, p
}
let geometry_key = |e: usize| {
let pts = mesh.edges.get(e).map(Vec::as_slice).unwrap_or_default();
let lo = pts.iter().copied().fold(Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::min);
let hi = pts.iter().copied().fold(Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), Vec3::max);
(key(lo), key(hi))
let b: Aabb3 = pts.iter().copied().collect();
(key(b.min), key(b.max))
};
edges.sort_by_key(|e| geometry_key(*e));
let mut at: BTreeMap<Key, Vec<usize>> = BTreeMap::new();
+50 -118
View File
@@ -10,7 +10,7 @@
//! together; the flat solid is the outline extruded through the thickness.
use serde::{Deserialize, Serialize};
use solidcraft_geom::{LINEAR_TOL, Loop2, Plane, Region2, Seg2, Vec2, Vec3};
use solidcraft_geom::{Aabb2, LINEAR_TOL, Loop2, Plane, Region2, Ring, Seg2, Vec2, Vec3};
use solidcraft_kernel::{self as kernel, Body, EdgeSpec, FaceSpec, SurfSpec};
use crate::expr::{self, Kind, Value};
@@ -62,7 +62,7 @@ impl FlatWork {
}
}
fn flat_polyline(lp: &Loop2) -> Result<Vec<Vec2>> {
fn flat_polyline(lp: &Loop2) -> Result<Ring<Vec2>> {
if lp.segs.len() > MAX_FLAT_POINTS {
return Err(flat_budget_error());
}
@@ -75,7 +75,7 @@ fn flat_polyline(lp: &Loop2) -> Result<Vec<Vec2>> {
}
points.extend(p.iter().take(add));
}
Ok(points)
Ok(Ring::new(points))
}
fn flat_points(polys: &[Vec<Vec2>]) -> Result<usize> {
@@ -181,17 +181,13 @@ fn regions_complexity<'a>(regions: impl Iterator<Item = &'a Region2>) -> Result<
/// them (the result is the same: a cut-out clear of a tool's box can't change what it meets).
pub(crate) struct NearHoles<'a> {
region: &'a Region2,
boxes: Vec<(Vec2, Vec2)>,
boxes: Vec<Aabb2>,
}
/// A loop's bounding box, a little larger than its chords so arcs stay inside.
fn loop_box(lp: &Loop2) -> Result<(Vec2, Vec2)> {
let pts = flat_polyline(lp)?;
let (lo, hi) = pts.iter().fold((Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)), |(lo, hi), p| {
(Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y)))
});
let pad = 1e-3 + 1e-9 * (lo.x.abs() + lo.y.abs() + hi.x.abs() + hi.y.abs());
Ok((lo - Vec2::new(pad, pad), hi + Vec2::new(pad, pad)))
fn loop_box(lp: &Loop2) -> Result<Aabb2> {
let b = flat_polyline(lp)?.bounds();
Ok(b.inflated(1e-3 + 1e-9 * (b.min.x.abs() + b.min.y.abs() + b.max.x.abs() + b.max.y.abs())))
}
impl<'a> NearHoles<'a> {
@@ -204,15 +200,8 @@ impl<'a> NearHoles<'a> {
if self.region.holes.is_empty() {
return Ok(self.region.clone());
}
let (lo, hi) = loop_box(&tool.outer)?;
let holes = self
.region
.holes
.iter()
.zip(&self.boxes)
.filter(|(_, (a, b))| a.x <= hi.x && b.x >= lo.x && a.y <= hi.y && b.y >= lo.y)
.map(|(h, _)| h.clone())
.collect();
let near = loop_box(&tool.outer)?;
let holes = self.region.holes.iter().zip(&self.boxes).filter(|(_, b)| b.meets(&near)).map(|(h, _)| h.clone()).collect();
Ok(Region2 { outer: self.region.outer.clone(), holes })
}
}
@@ -599,7 +588,9 @@ fn bezier_at(c: &[Vec3], t: f64) -> Vec3 {
w.first().copied().unwrap_or(Vec3::ZERO)
}
fn dedup(p: &[Vec2]) -> Vec<Vec2> {
/// `p` without repeated points: a point on the one before it goes, and so does a last point back
/// on the first.
fn dedup(p: &Ring<Vec2>) -> Ring<Vec2> {
let mut v: Vec<Vec2> = Vec::new();
for q in p {
if v.last().is_none_or(|l| l.dist(*q) > 1e-9) {
@@ -609,7 +600,7 @@ fn dedup(p: &[Vec2]) -> Vec<Vec2> {
if v.len() > 1 && v.first().zip(v.last()).is_some_and(|(a, b)| a.dist(*b) < 1e-9) {
v.pop();
}
v
Ring::new(v)
}
/// How a flat edge of a bend zone folds: along the bend to a line, across it to an arc, or
@@ -757,7 +748,7 @@ struct Corner {
/// The corners of a straight-edged region (counter-clockwise).
fn corners_of(r: &Region2) -> Vec<Vec2> {
dedup(&r.outer.ccw().polyline(1e-3))
dedup(&r.outer.ccw().polyline(1e-3)).into_vec()
}
/// A corner relief planned but not yet cut (see [`SheetBody::plan_relief`]): the corner it is
@@ -1174,13 +1165,8 @@ impl SheetBody {
// Each piece meets only the cut-outs near it: arranging every cut-out of the sheet (a
// label's letters on its base) against each flange and bend zone too would charge the
// budget for all of them once per piece.
let (lo, hi) = loop_box(&panel.outer)?;
let near: Vec<Region2> = cuts
.iter()
.zip(&cut_boxes)
.filter(|(_, (a, b))| a.x <= hi.x && b.x >= lo.x && a.y <= hi.y && b.y >= lo.y)
.map(|(c, _)| c.clone())
.collect();
let panel_box = loop_box(&panel.outer)?;
let near: Vec<Region2> = cuts.iter().zip(&cut_boxes).filter(|(_, b)| b.meets(&panel_box)).map(|(c, _)| c.clone()).collect();
let material = if near.is_empty() { vec![panel] } else { material_boolean(&[panel], &near, kernel::BoolOp::Cut, work)? };
for region in material {
points = points.saturating_add(region_complexity(std::slice::from_ref(&region))?.1);
@@ -1708,14 +1694,11 @@ impl SheetBody {
.labels
.iter()
.map(|r| {
let (mut lo, mut hi) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN));
for p in r.outer.polyline(1e-3) {
lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y));
hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y));
}
// A polyline of 0.001 mm chords is within 0.001 mm of the curve.
let pad = Vec2::new(0.01, 0.01);
(lo - pad, hi + pad, std::iter::once(&r.outer).chain(&r.holes).flat_map(|lp| lp.segs.iter().copied()).collect())
(
r.outer.polyline(1e-3).bounds().inflated(0.01),
std::iter::once(&r.outer).chain(&r.holes).flat_map(|lp| lp.segs.iter().copied()).collect(),
)
})
.collect();
Letters { regions }
@@ -1812,19 +1795,18 @@ impl SheetBody {
Ok(common.iter().map(Region2::area).sum::<f64>() > TOUCH_AREA)
};
// The cheap test first: a piece inside another's outline is an island, whatever it holds.
let outlines: Vec<(Vec<Vec2>, Vec2, Vec2)> = after
let outlines: Vec<(Ring<Vec2>, Aabb2)> = after
.iter()
.map(|r| {
let pts = r.outer.polyline(1e-3);
let lo = pts.iter().fold(Vec2::new(f64::MAX, f64::MAX), |a, p| Vec2::new(a.x.min(p.x), a.y.min(p.y)));
let hi = pts.iter().fold(Vec2::new(f64::MIN, f64::MIN), |a, p| Vec2::new(a.x.max(p.x), a.y.max(p.y)));
(pts, lo, hi)
let b = pts.bounds();
(pts, b)
})
.collect();
let (mut open, mut islands) = (Vec::new(), Vec::new());
for (i, piece) in after.iter().enumerate() {
let p = piece.interior_point();
let inside = |(pts, lo, hi): &(Vec<Vec2>, Vec2, Vec2)| (lo.x..=hi.x).contains(&p.x) && (lo.y..=hi.y).contains(&p.y) && point_in(pts, p);
let inside = |(pts, b): &(Ring<Vec2>, Aabb2)| b.contains(p) && pts.contains(p);
if outlines.iter().enumerate().any(|(j, o)| j != i && inside(o)) {
islands.push(piece);
} else {
@@ -1874,11 +1856,11 @@ impl SheetBody {
if self.flanges.len().saturating_mul(2).saturating_add(1) > MAX_FLAT_PIECES {
return Err(flat_budget_error());
}
let mut polys: Vec<Vec<Vec2>> = vec![dedup(&flat_polyline(&self.base.outer.ccw())?)];
let mut polys: Vec<Vec<Vec2>> = vec![dedup(&flat_polyline(&self.base.outer.ccw())?).into_vec()];
for f in &self.flanges {
polys.push(dedup(&flat_polyline(&self.zone(f).outer.ccw())?));
polys.push(dedup(&flat_polyline(&self.zone(f).outer.ccw())?).into_vec());
if f.leg > 1e-9 {
polys.push(dedup(&flat_polyline(&self.panel(f).outer.ccw())?));
polys.push(dedup(&flat_polyline(&self.panel(f).outer.ccw())?).into_vec());
}
flat_points(&polys)?;
}
@@ -1940,10 +1922,8 @@ impl SheetBody {
let mut segs: Vec<(Vec2, Vec2)> = Vec::new();
let mut add = |l: &Loop2| {
let pts = l.polyline(1e-3);
for k in 0..pts.len() {
if let (Some(&a), Some(&b)) = (pts.get(k), pts.get((k + 1) % pts.len())) {
segs.push((a, b));
}
for (&a, &b) in pts.edges() {
segs.push((a, b));
}
};
for r in &regions {
@@ -1951,11 +1931,7 @@ impl SheetBody {
r.holes.iter().for_each(&mut add);
}
zones.iter().for_each(|z| add(&z.outer));
let (mut lo, mut hi) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN));
for (a, _) in &segs {
lo = Vec2::new(lo.x.min(a.x), lo.y.min(a.y));
hi = Vec2::new(hi.x.max(a.x), hi.y.max(a.y));
}
let Aabb2 { min: lo, max: hi } = segs.iter().map(|(a, _)| *a).collect();
if !(lo.x <= hi.x) || !(p.pitch > 0.0) {
return Ok(Vec::new());
}
@@ -2039,13 +2015,8 @@ impl SheetBody {
/// Bounding size of the flat pattern (x, y in the flat frame).
pub fn flat_size(&self) -> Result<(f64, f64)> {
let loops: Vec<Vec<Vec2>> = self.flat_regions()?.iter().map(|r| r.outer.polyline(1e-3)).collect();
let (mut lo, mut hi) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN));
for p in loops.iter().flatten() {
lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y));
hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y));
}
Ok((hi.x - lo.x, hi.y - lo.y))
let size = self.flat_regions()?.iter().fold(Aabb2::EMPTY, |b, r| b.union(&r.outer.polyline(1e-3).bounds())).size();
Ok((size.x, size.y))
}
/// Panels with their regions and world placements: (flange index or None, region).
@@ -2073,7 +2044,7 @@ impl SheetBody {
}
let q2 = Vec2::new(q.x, q.y);
let pts = dedup(&r.outer.ccw().polyline(1e-3));
if !point_in(&pts, q2) && !near_outline(&pts, q2, TOL) {
if !pts.contains(q2) && !near_outline(&pts, q2, TOL) {
continue;
}
// Panels `before` did not have yet came out of their parent's (bounded walk).
@@ -3254,7 +3225,7 @@ impl SheetBody {
}
let pts = dedup(&r.outer.ccw().polyline(1e-3));
let (a2, b2) = (Vec2::new(fa.x, fa.y), Vec2::new(fb.x, fb.y));
if point_in(&pts, (a2 + b2) * 0.5) || polys_cross(&pts, &[a2, b2, (a2 + b2) * 0.5]) {
if pts.contains((a2 + b2) * 0.5) || polys_cross(&pts, &[a2, b2, (a2 + b2) * 0.5]) {
found = Some((pi, inv, a2, b2, pts));
break;
}
@@ -3283,20 +3254,10 @@ impl SheetBody {
let q2 = Vec2::new(q.x, q.y);
// A point in the panel's slab must be on material: inside the outline and
// outside every cut-out (a side face of either counts as material).
let near = |poly: &[Vec2]| {
let m = poly.len();
(0..m).any(|i| match (poly.get(i), poly.get((i + 1) % m)) {
(Some(&a), Some(&b)) => {
let d = b - a;
let t = if d.len2() > 1e-18 { ((q2 - a).dot(d) / d.len2()).clamp(0.0, 1.0) } else { 0.0 };
(a + d * t).dist(q2) < 1e-3
}
_ => false,
})
};
let near = |poly: &Ring<Vec2>| near_outline(poly, q2, 1e-3);
let in_slab = q.z > -1e-4 && q.z < self.t + 1e-4;
let in_hole = self.holes.iter().any(|h| h.contains(q2) && !near(&h.outer.ccw().polyline(1e-3)));
if in_slab && ((!point_in(&pts, q2) && !near(&pts)) || in_hole) {
if in_slab && ((!pts.contains(q2) && !near(&pts)) || in_hole) {
*warning =
Some(format!("{FOLD_FIXED_OFF_SHEET} at ({:.3}, {:.3}, {:.3}); the side of the fold line it lies on stays", p.x, p.y, p.z));
}
@@ -3476,11 +3437,11 @@ impl SheetBody {
// What stays: the panel short of the zone plus the zone pieces (and what hangs from
// them) that don't fold.
let mut keep = vec![clip(pts, n * s0, n * -1.0)];
for i in 0..strips.len() {
for (i, strip) in strips.iter().enumerate() {
if chosen.contains(&i) {
continue;
}
keep.extend(strips.get(i).cloned());
keep.push(strip.clone());
keep.extend(hangs.get(i).into_iter().flatten().filter_map(|&k| beyond.get(k).cloned()));
}
let fixed = match merge_loops(&keep, &mut work)?.as_slice() {
@@ -3503,8 +3464,7 @@ impl SheetBody {
}
// Flanges already on this panel: those beyond a folding tab move with it.
let mut moves = Vec::new();
for k in 0..self.flanges.len() {
let Some(f) = self.flanges.get(k) else { continue };
for (k, f) in self.flanges.iter().enumerate() {
if f.parent != panel {
continue;
}
@@ -3683,9 +3643,7 @@ impl SheetBody {
let mut out = Vec::new();
for (pi, region) in self.panels() {
let pts = dedup(&region.outer.ccw().polyline(1e-3));
let m = pts.len();
for i in 0..m {
let (Some(&a), Some(&b)) = (pts.get(i), pts.get((i + 1) % m)) else { continue };
for (i, (&a, &b)) in pts.edges().enumerate() {
if a.dist(b) < 1e-9 {
continue;
}
@@ -3920,18 +3878,6 @@ impl SheetBody {
}
}
fn point_in(poly: &[Vec2], p: Vec2) -> bool {
let mut inside = false;
let m = poly.len();
for i in 0..m {
let (Some(&a), Some(&b)) = (poly.get(i), poly.get((i + m - 1) % m)) else { continue };
if (a.y > p.y) != (b.y > p.y) && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x {
inside = !inside;
}
}
inside
}
/// The boundary of a union of counter-clockwise polygons that meet edge to edge: edges are
/// split where corners touch them, edges running both ways cancel, the rest chain into loops
/// (outer loops counter-clockwise, holes clockwise; straight runs merged).
@@ -4015,15 +3961,11 @@ fn merge_loops(polys: &[Vec<Vec2>], work: &mut FlatWork) -> Result<Vec<Vec<Vec2>
}
/// Whether `q` lies within `tol` of the closed polygon `poly`'s outline.
fn near_outline(poly: &[Vec2], q: Vec2, tol: f64) -> bool {
let m = poly.len();
(0..m).any(|i| match (poly.get(i), poly.get((i + 1) % m)) {
(Some(&a), Some(&b)) => {
let d = b - a;
let t = if d.len2() > 1e-18 { ((q - a).dot(d) / d.len2()).clamp(0.0, 1.0) } else { 0.0 };
(a + d * t).dist(q) < tol
}
_ => false,
fn near_outline(poly: &Ring<Vec2>, q: Vec2, tol: f64) -> bool {
poly.edges().any(|(&a, &b)| {
let d = b - a;
let t = if d.len2() > 1e-18 { ((q - a).dot(d) / d.len2()).clamp(0.0, 1.0) } else { 0.0 };
(a + d * t).dist(q) < tol
})
}
@@ -4077,19 +4019,9 @@ fn clear_of(a: Vec2, d: Vec2, len: f64, cuts: &[Region2]) -> Vec<(f64, f64)> {
return Vec::new();
}
let b = a + d * len;
let (lo, hi) = (Vec2::new(a.x.min(b.x) - 1e-6, a.y.min(b.y) - 1e-6), Vec2::new(a.x.max(b.x) + 1e-6, a.y.max(b.y) + 1e-6));
let line = Aabb2 { min: Vec2::new(a.x.min(b.x), a.y.min(b.y)), max: Vec2::new(a.x.max(b.x), a.y.max(b.y)) }.inflated(1e-6);
// Only cut-outs whose box the line enters can hold or cross it.
let near: Vec<&Region2> = cuts
.iter()
.filter(|r| {
let pts = r.outer.polyline(1e-3);
let (mut p0, mut p1) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN));
for p in &pts {
(p0, p1) = (Vec2::new(p0.x.min(p.x), p0.y.min(p.y)), Vec2::new(p1.x.max(p.x), p1.y.max(p.y)));
}
p0.x <= hi.x && lo.x <= p1.x && p0.y <= hi.y && lo.y <= p1.y
})
.collect();
let near: Vec<&Region2> = cuts.iter().filter(|r| r.outer.polyline(1e-3).bounds().meets(&line)).collect();
let mut at = vec![0.0, len];
for e in near.iter().flat_map(|r| std::iter::once(&r.outer).chain(&r.holes)).flat_map(|l| &l.segs) {
line_hits(a, d, e, &mut at);
@@ -4242,8 +4174,8 @@ pub fn loop_lies_on(lp: &Loop2, curves: &[Seg2]) -> bool {
/// Tells which loops of a sheet's flat pattern are letters (see [`SheetBody::letters`]).
#[derive(Clone, Debug)]
pub struct Letters {
/// Each text region's corners (lowest, highest) and the segments of its outlines.
regions: Vec<(Vec2, Vec2, Vec<Seg2>)>,
/// Each text region's box and the segments of its outlines.
regions: Vec<(Aabb2, Vec<Seg2>)>,
}
impl Letters {
@@ -4251,7 +4183,7 @@ impl Letters {
/// counters.
pub fn is_letter(&self, lp: &Loop2) -> bool {
let Some(p) = lp.segs.first().map(Seg2::start) else { return false };
self.regions.iter().any(|(lo, hi, curves)| p.x >= lo.x && p.x <= hi.x && p.y >= lo.y && p.y <= hi.y && loop_lies_on(lp, curves))
self.regions.iter().any(|(b, curves)| b.contains(p) && loop_lies_on(lp, curves))
}
}
+6 -5
View File
@@ -50,10 +50,10 @@
use std::collections::BTreeMap;
use std::f64::consts::{FRAC_PI_2, PI, TAU};
use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Seg2, UnitVec3, Vec2, Vec3};
use solidcraft_geom::{Loop2, Mesh, Plane, Region2, Ring, Seg2, UnitVec3, Vec2, Vec3};
use solidcraft_kernel::{Body, FaceSurface, face_surface};
use super::{FlatWork, ReliefOverride, RuleValues, SheetBody, SheetFlange, base_flange, point_in, polys_cross, signed_area, snap};
use super::{FlatWork, ReliefOverride, RuleValues, SheetBody, SheetFlange, base_flange, polys_cross, signed_area, snap};
use crate::{DocError, ModelBody, Result, apply_point, mat_inverse};
const MAX_BENDS: usize = 1000;
@@ -788,7 +788,8 @@ pub fn convert_body(mb: &ModelBody, rule: &str, rv: &RuleValues, face: Vec3, ben
}
// The flat frame: on the fixed face, x along its longest edge, z into the material.
let Some(base) = panels.get(&f0) else { return err("fixed face") };
let corners = base.face.pts.iter().zip(base.face.pts.iter().cycle().skip(1));
let base_ring = Ring::from(base.face.pts.clone());
let corners = base_ring.edges();
let straight = corners.zip(&base.face.round).filter(|(_, r)| r.is_none()).map(|(c, _)| c);
let longest = straight.max_by(|x, y| x.0.dist(*x.1).total_cmp(&y.0.dist(*y.1)));
let frame = longest
@@ -889,7 +890,7 @@ pub fn convert_body(mb: &ModelBody, rule: &str, rv: &RuleValues, face: Vec3, ben
};
let back = skin_behind.get(&pf).and_then(|g| outline(b, &mesh, *g, tol).ok());
let skins: Vec<(&Face, bool)> = std::iter::once((&panel.face, true)).chain(back.as_ref().map(|f| (f, false))).collect();
let bound = if skins.iter().all(|(f, _)| f.holes.is_empty()) { Vec::new() } else { region.outer.ccw().polyline(1e-3) };
let bound = if skins.iter().all(|(f, _)| f.holes.is_empty()) { Ring::default() } else { region.outer.ccw().polyline(1e-3) };
for (face, front) in skins {
for (h, walls) in &face.holes {
let p = face.plane.to_world(h.centroid());
@@ -900,7 +901,7 @@ pub fn convert_body(mb: &ModelBody, rule: &str, rv: &RuleValues, face: Vec3, ben
}
let cut = sh.region_to_flat(fl, &face.plane, &Region2 { outer: h.clone(), holes: Vec::new() })?;
let ring = cut.outer.polyline(1e-3);
if !ring.iter().all(|q| point_in(&bound, *q)) || polys_cross(&bound, &ring) {
if !ring.iter().all(|q| bound.contains(*q)) || polys_cross(&bound, &ring) {
let kind = if through { "hole" } else { "pocket" };
return err(format!("not supported yet: the {kind} at {} reaches into a bend (cut it after converting)", at(p)));
}
@@ -1,7 +1,7 @@
//! Physical properties of an assembly placement, with original body material assignments.
use serde_json::{Value, json};
use solidcraft_doc::{Document, Mat};
use solidcraft_geom::Vec3;
use solidcraft_geom::{Aabb3, Vec3};
use crate::params::bad;
use crate::{Result, Session};
@@ -90,8 +90,7 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool,
let mut bodies = Vec::new();
let (mut volume, mut area, mut mass) = (0.0, 0.0, 0.0);
let mut moment = Vec3::ZERO;
let (mut min, mut max) =
(Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY));
let mut bounds = Aabb3::EMPTY;
let (mut faces, mut edges, mut vertices) = (0, 0, 0);
let mut placement_count = 0;
let selected_placements = if selected.is_empty() {
@@ -126,8 +125,7 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool,
area += measured.area;
mass += body_mass;
moment += measured.centroid * body_mass;
min = Vec3::new(min.x.min(measured.bbox.min.x), min.y.min(measured.bbox.min.y), min.z.min(measured.bbox.min.z));
max = Vec3::new(max.x.max(measured.bbox.max.x), max.y.max(measured.bbox.max.y), max.z.max(measured.bbox.max.z));
bounds = bounds.union(&measured.bbox);
faces += measured.merged.faces;
edges += measured.merged.edges;
vertices += measured.merged.vertices;
@@ -145,7 +143,7 @@ fn properties(s: &Session, doc: &Document, selected: &[u64], descendants: bool,
if centroid.is_some_and(|point| !point.is_finite()) {
return Err(bad(cmd, "center of mass exceeds supported numeric range"));
}
let bbox = if bodies.is_empty() { Value::Null } else { json!({"min": min, "max": max}) };
let bbox = if bodies.is_empty() { Value::Null } else { json!({"min": bounds.min, "max": bounds.max}) };
Ok(json!({"path": selected, "coordinate_frame": "world", "descendants": descendants,
"placement_count": placement_count, "body_count": bodies.len(), "bodies": bodies,
"total": {"volume_mm3": volume, "area_mm2": area, "mass_g": mass,
+5 -7
View File
@@ -6,7 +6,7 @@ use serde_json::{Value, json};
use solidcraft_doc::Mat;
use solidcraft_doc::joints::{self, JointKind};
use solidcraft_doc::motion::{ContactSet, ExplodedView, MotionStudy, StudyKey};
use solidcraft_geom::Vec3;
use solidcraft_geom::{Aabb3, Vec3};
use solidcraft_kernel::Body;
use super::CommandSpec;
@@ -904,16 +904,14 @@ fn centres(s: &Session) -> Vec<(u64, Vec3)> {
let bodies = placed(s);
let mut out = Vec::new();
for o in s.doc.occurrences.iter().filter(|o| o.parent == 0) {
let (mut lo, mut hi) = (Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN));
let mut bounds = Aabb3::EMPTY;
for (_, b) in bodies.iter().filter(|(path, _)| path.first() == Some(&o.id)) {
if let Ok(m) = b.tessellate((b.size() * 1e-2).max(1e-2)) {
let bb = m.bounds();
lo = Vec3::new(lo.x.min(bb.min.x), lo.y.min(bb.min.y), lo.z.min(bb.min.z));
hi = Vec3::new(hi.x.max(bb.max.x), hi.y.max(bb.max.y), hi.z.max(bb.max.z));
bounds = bounds.union(&m.bounds());
}
}
if lo.x <= hi.x {
out.push((o.id, (lo + hi) * 0.5));
if !bounds.is_empty() {
out.push((o.id, bounds.center()));
}
}
out
+6 -7
View File
@@ -523,13 +523,12 @@ mod tests {
fn bbox(s: &Session, prefix: &str) -> (solidcraft_geom::Vec3, solidcraft_geom::Vec3) {
let st = s.world_state();
let comp = s.doc.components.iter().find(|c| c.name.starts_with(prefix)).map(|c| c.id).unwrap_or(0);
let (mut lo, mut hi) = (solidcraft_geom::Vec3::new(f64::MAX, f64::MAX, f64::MAX), solidcraft_geom::Vec3::new(f64::MIN, f64::MIN, f64::MIN));
for b in st.bodies.iter().filter(|b| s.doc.model_body_component(b) == comp) {
let m = b.mesh().bounds();
lo = solidcraft_geom::Vec3::new(lo.x.min(m.min.x), lo.y.min(m.min.y), lo.z.min(m.min.z));
hi = solidcraft_geom::Vec3::new(hi.x.max(m.max.x), hi.y.max(m.max.y), hi.z.max(m.max.z));
}
(lo, hi)
let b = st
.bodies
.iter()
.filter(|b| s.doc.model_body_component(b) == comp)
.fold(solidcraft_geom::Aabb3::EMPTY, |a, b| a.union(&b.mesh().bounds()));
(b.min, b.max)
}
#[test]
+4 -8
View File
@@ -7,7 +7,7 @@ use solidcraft_doc::sheet::{self, SheetBody, SheetRule};
use solidcraft_doc::{BodyName, SketchId};
use solidcraft_doc::{FacePick, Position};
use solidcraft_doc::{FeatureKind, FlangeEdge};
use solidcraft_geom::{Vec2, Vec3};
use solidcraft_geom::{Aabb2, Ring, Vec2, Vec3};
use super::CommandSpec;
use super::features::{add_feature, check_expr, feature_sketch, profiles, sketch_id};
@@ -494,13 +494,9 @@ fn loop_shape(lp: &solidcraft_geom::Loop2) -> Value {
fn flat_json(sh: &SheetBody) -> Result<Value> {
let regions = sh.flat_regions()?;
let loops: Vec<Vec<Vec2>> = regions.iter().map(|r| r.outer.polyline(1e-3)).collect();
let (mut lo, mut hi) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN));
for p in loops.iter().flatten() {
lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y));
hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y));
}
let (w, h) = (hi.x - lo.x, hi.y - lo.y);
let loops: Vec<Ring<Vec2>> = regions.iter().map(|r| r.outer.polyline(1e-3)).collect();
let size = loops.iter().fold(Aabb2::EMPTY, |b, l| b.union(&l.bounds())).size();
let (w, h) = (size.x, size.y);
let pt = |v: &Vec2| json!([v.x, v.y]);
let outline: Vec<Value> = loops.iter().map(|l| Value::Array(l.iter().map(pt).collect())).collect();
let holes: Vec<Value> = regions.iter().flat_map(|r| &r.holes).map(|h| Value::Array(h.polyline(1e-3).iter().map(pt).collect())).collect();
+7 -10
View File
@@ -8,7 +8,7 @@
use std::collections::BTreeMap;
use serde_json::{Value, json};
use solidcraft_geom::Vec2;
use solidcraft_geom::{Aabb2, Vec2};
use solidcraft_sketch::{ConstraintKind, CurveKind, LinkKind, LinkSource, Sketch};
use super::sketch::{edit, target_sketch};
@@ -175,12 +175,8 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
clip.texts.push((src, path));
}
// Bounds of everything copied, as drawn.
let mut lo = Vec2::new(f64::INFINITY, f64::INFINITY);
let mut hi = Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY);
let mut add = |q: Vec2| {
lo = Vec2::new(lo.x.min(q.x), lo.y.min(q.y));
hi = Vec2::new(hi.x.max(q.x), hi.y.max(q.y));
};
let mut bounds = Aabb2::EMPTY;
let mut add = |q: Vec2| bounds.add(q);
let mut drawn: Vec<usize> = cs.clone();
for t in &texts {
drawn.extend(sk.link_curves(t));
@@ -193,11 +189,12 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
add(*q);
}
}
if !(lo.x.is_finite() && hi.x.is_finite()) {
if bounds.is_empty() {
return Err(bad(cmd, "nothing to copy"));
}
clip.center = (lo + hi) * 0.5;
clip.extent = (hi.x - lo.x).max(hi.y - lo.y);
clip.center = bounds.center();
let size = bounds.size();
clip.extent = size.x.max(size.y);
let out = json!({
"curves": clip.curves.len() + texts.iter().map(|t| sk.link_curves(t).len()).sum::<usize>(),
"points": clip.lone.len(),
+5 -7
View File
@@ -2,7 +2,7 @@
//! centre of mass of bodies.
use serde_json::{Value, json};
use solidcraft_geom::{Seg2, Vec2, Vec3};
use solidcraft_geom::{Aabb3, Seg2, Vec2, Vec3};
use super::CommandSpec;
use crate::params::{bad, num, string_list, vec3};
@@ -135,12 +135,10 @@ fn curvature_comb(s: &mut Session, p: &Value) -> Result<Value> {
}
// One scale for all combs: the longest tooth is a fifth of the largest curve's size.
let kmax = combs.iter().flat_map(|c| c.1.iter().map(|t| t.1.abs())).fold(0.0_f64, f64::max);
let size = combs.iter().flat_map(|c| c.1.iter().map(|t| t.0)).fold(
(Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY)),
|(lo, hi), q| (lo.min(q), hi.max(q)),
);
let diag = (size.1 - size.0).len();
let scale = num(p, "scale").filter(|x| *x > 0.0).unwrap_or(if kmax > 1e-12 && diag.is_finite() { 0.2 * diag / kmax } else { 1.0 });
let bounds: Aabb3 = combs.iter().flat_map(|c| c.1.iter().map(|t| t.0)).collect();
let diag = bounds.diagonal();
let scale =
num(p, "scale").filter(|x| *x > 0.0).unwrap_or(if kmax > 1e-12 && !bounds.is_empty() && diag.is_finite() { 0.2 * diag / kmax } else { 1.0 });
let out: Vec<Value> = combs
.iter()
.map(|(id, teeth)| {
+2 -7
View File
@@ -5,7 +5,7 @@
//! imports sit loose in a component open and rebuild as they did.
use serde_json::{Value, json};
use solidcraft_geom::Vec3;
use solidcraft_geom::{Aabb3, Vec3};
use solidcraft_kernel::{ExportBody, ExportProduct, StepHeader, box_solid, step_export_products};
use super::run;
@@ -113,12 +113,7 @@ fn corner_of(s: &Session, occurrence: &str) -> Vec3 {
let names = s.occurrence_bodies(&path, true).unwrap();
assert!(!names.is_empty());
let world = s.world_state();
let mut lo = Vec3::new(f64::MAX, f64::MAX, f64::MAX);
for b in world.bodies.iter().filter(|b| names.contains(&b.name)) {
let bb = solidcraft_kernel::measure(&b.body).unwrap().bbox;
lo = Vec3::new(lo.x.min(bb.min.x), lo.y.min(bb.min.y), lo.z.min(bb.min.z));
}
lo
world.bodies.iter().filter(|b| names.contains(&b.name)).fold(Aabb3::EMPTY, |a, b| a.union(&solidcraft_kernel::measure(&b.body).unwrap().bbox)).min
}
fn close(a: Vec3, b: Vec3) -> bool {
+104
View File
@@ -0,0 +1,104 @@
//! A box in the plane, the 2D [`crate::Aabb3`].
use crate::Vec2;
/// Axis-aligned box in the plane; [`Aabb2::EMPTY`] (low +∞, high −∞) holds nothing.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Aabb2 {
pub min: Vec2,
pub max: Vec2,
}
impl Default for Aabb2 {
fn default() -> Self {
Aabb2::EMPTY
}
}
impl Aabb2 {
pub const EMPTY: Aabb2 = Aabb2 { min: Vec2::new(f64::INFINITY, f64::INFINITY), max: Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY) };
pub fn is_empty(&self) -> bool {
!(self.min.x <= self.max.x && self.min.y <= self.max.y)
}
/// Grow to hold `p`; a point that is not finite is skipped.
pub fn add(&mut self, p: Vec2) {
if p.is_finite() {
self.min = Vec2::new(self.min.x.min(p.x), self.min.y.min(p.y));
self.max = Vec2::new(self.max.x.max(p.x), self.max.y.max(p.y));
}
}
pub fn union(&self, o: &Aabb2) -> Aabb2 {
if self.is_empty() {
return *o;
}
if o.is_empty() {
return *self;
}
Aabb2 { min: Vec2::new(self.min.x.min(o.min.x), self.min.y.min(o.min.y)), max: Vec2::new(self.max.x.max(o.max.x), self.max.y.max(o.max.y)) }
}
pub fn center(&self) -> Vec2 {
if self.is_empty() { Vec2::ZERO } else { (self.min + self.max) * 0.5 }
}
pub fn size(&self) -> Vec2 {
if self.is_empty() { Vec2::ZERO } else { self.max - self.min }
}
pub fn diagonal(&self) -> f64 {
self.size().len()
}
/// The box grown by `by` on every side; an empty box stays empty.
pub fn inflated(&self, by: f64) -> Aabb2 {
if self.is_empty() {
return *self;
}
let d = Vec2::new(by, by);
Aabb2 { min: self.min - d, max: self.max + d }
}
/// Whether `p` lies in the box, its sides included (never in an empty box, never for NaN).
pub fn contains(&self, p: Vec2) -> bool {
p.x >= self.min.x && p.y >= self.min.y && p.x <= self.max.x && p.y <= self.max.y
}
/// Whether the two boxes share a point (never when either is empty).
pub fn meets(&self, o: &Aabb2) -> bool {
self.min.x <= o.max.x && o.min.x <= self.max.x && self.min.y <= o.max.y && o.min.y <= self.max.y
}
/// Where `p` sits in the box: (0, 0) at `min`, (1, 1) at `max`, each side taken as at least
/// 1e-9 long so a flat box still divides.
pub fn relative(&self, p: Vec2) -> Vec2 {
Vec2::new((p.x - self.min.x) / (self.max.x - self.min.x).max(1e-9), (p.y - self.min.y) / (self.max.y - self.min.y).max(1e-9))
}
}
/// The box around the finite points (non-finite ones are skipped, as [`Aabb2::add`] does).
impl FromIterator<Vec2> for Aabb2 {
fn from_iter<I: IntoIterator<Item = Vec2>>(points: I) -> Aabb2 {
let mut b = Aabb2::EMPTY;
b.extend(points);
b
}
}
impl Extend<Vec2> for Aabb2 {
fn extend<I: IntoIterator<Item = Vec2>>(&mut self, points: I) {
for p in points {
self.add(p);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_box_from_points_holds_them_and_grows() {
let b: Aabb2 = [Vec2::new(1.0, 2.0), Vec2::new(-1.0, 0.0), Vec2::new(f64::INFINITY, 0.0)].into_iter().collect();
assert_eq!((b.min, b.max), (Vec2::new(-1.0, 0.0), Vec2::new(1.0, 2.0)), "the infinite point is skipped");
assert!(b.contains(Vec2::new(0.0, 1.0)) && !b.contains(Vec2::new(0.0, 3.0)) && !b.contains(Vec2::new(f64::NAN, 1.0)));
assert!(b.inflated(1.0).contains(Vec2::new(0.0, 3.0)));
assert!(Aabb2::EMPTY.inflated(1e9).is_empty() && !Aabb2::EMPTY.contains(Vec2::ZERO));
let far = Aabb2 { min: Vec2::new(2.0, 0.0), max: Vec2::new(3.0, 1.0) };
assert!(!b.meets(&far) && b.inflated(1.0).meets(&far) && !b.meets(&Aabb2::EMPTY));
assert_eq!(b.union(&far).max, Vec2::new(3.0, 2.0));
assert_eq!(b.relative(Vec2::new(0.0, 1.0)), Vec2::new(0.5, 0.5));
}
}
+223
View File
@@ -0,0 +1,223 @@
//! 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());
}
}
+2 -5
View File
@@ -644,7 +644,6 @@ fn clusters(pts: &[Pt], cell: f64) -> Vec<Vec<usize>> {
}
}
let groups_of = |parent: &mut [usize]| -> Vec<usize> { of_point.iter().map(|&c| find(parent, c)).collect() };
let grow = Vec3::new(cell, cell, cell);
// Join groups of one side whose grown boxes overlap, until none do (sort and sweep along X).
for _ in 0..16 {
let groups = groups_of(&mut parent);
@@ -652,8 +651,7 @@ fn clusters(pts: &[Pt], cell: f64) -> Vec<Vec<usize>> {
for (pt, g) in pts.iter().zip(&groups) {
boxes.entry(*g).or_insert((pt.side, Aabb3::EMPTY)).1.add(pt.off.p);
}
let mut list: Vec<(usize, Side, Aabb3)> =
boxes.into_iter().map(|(g, (s, b))| (g, s, Aabb3 { min: b.min - grow, max: b.max + grow })).collect();
let mut list: Vec<(usize, Side, Aabb3)> = boxes.into_iter().map(|(g, (s, b))| (g, s, b.inflated(cell))).collect();
list.sort_by(|a, b| a.2.min.x.total_cmp(&b.2.min.x).then(a.0.cmp(&b.0)));
let mut joined = false;
for (k, (ga, sa, ba)) in list.iter().enumerate() {
@@ -887,10 +885,9 @@ pub fn compare(a: &Mesh, b: &Mesh, o: &CompareOptions, each: Each) -> Comparison
found.sort_by(|x, y| y.weight.total_cmp(&x.weight).then(y.max.total_cmp(&x.max)));
let unlisted = found.len().saturating_sub(o.max_regions);
found.truncate(o.max_regions);
let grow = Vec3::new(cell, cell, cell);
let measured = gather(found.len(), each, |i| {
let f = found.get(i)?;
region_volume([&ta, &tb], &Aabb3 { min: f.bbox.min - grow, max: f.bbox.max + grow }, f.side, o.max_lines)
region_volume([&ta, &tb], &f.bbox.inflated(cell), f.side, o.max_lines)
});
let mut regions: Vec<Region> = found
.into_iter()
+2 -11
View File
@@ -878,17 +878,8 @@ mod tests {
/// The farthest the surface is from `z` over the polygon's inside (sampled on a grid).
fn off_inside(f: &LoopFill, corners: &[[f64; 2]], z: &dyn Fn(f64, f64) -> f64) -> f64 {
let inside = |x: f64, y: f64| {
let n = corners.len();
let mut w = false;
for k in 0..n {
let (a, b) = (corners[k], corners[(k + 1) % n]);
if (a[1] > y) != (b[1] > y) && x < a[0] + (y - a[1]) / (b[1] - a[1]) * (b[0] - a[0]) {
w = !w;
}
}
w
};
let polygon = crate::Ring::from(corners.to_vec());
let inside = |x: f64, y: f64| polygon.contains([x, y]);
let s = &f.surface;
let [du, dv] = s.domain();
let mut worst = 0.0f64;
+4
View File
@@ -9,11 +9,13 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod aabb2;
mod arcfit;
pub mod blend;
pub mod brep;
pub mod bspline;
mod bvh;
mod chain;
pub mod compare;
pub mod env;
pub mod fill;
@@ -31,9 +33,11 @@ pub mod tspline;
mod unit_vec3;
mod vec;
pub use aabb2::Aabb2;
pub use arcfit::MAX_FIT_PIECES;
pub use blend::hermite_bezier;
pub use bvh::{Bvh, MeshIndex};
pub use chain::{Chain, Closed, Ends, Open, Path, Planar, Ring};
pub use grid::Grid;
pub use mesh::{Aabb3, BoxedTriangle, InsideIndex, MassProperties, Mesh, MeshMeasure, find_close_pair};
pub use plane::Plane;
+43 -5
View File
@@ -47,6 +47,48 @@ impl Aabb3 {
pub fn diagonal(&self) -> f64 {
self.size().len()
}
/// The box grown by `by` on every side; an empty box stays empty.
pub fn inflated(&self, by: f64) -> Aabb3 {
if self.is_empty() {
return *self;
}
let d = Vec3::new(by, by, by);
Aabb3 { min: self.min - d, max: self.max + d }
}
/// Whether `p` lies in the box, its sides included (never in an empty box, never for NaN).
pub fn contains(&self, p: Vec3) -> bool {
p.x >= self.min.x && p.y >= self.min.y && p.z >= self.min.z && p.x <= self.max.x && p.y <= self.max.y && p.z <= self.max.z
}
/// The box both hold: empty when they do not meet.
pub fn intersection(&self, o: &Aabb3) -> Aabb3 {
Aabb3 { min: self.min.max(o.min), max: self.max.min(o.max) }
}
/// Whether the two boxes share a point (never when either is empty).
pub fn meets(&self, o: &Aabb3) -> bool {
self.min.x <= o.max.x
&& o.min.x <= self.max.x
&& self.min.y <= o.max.y
&& o.min.y <= self.max.y
&& self.min.z <= o.max.z
&& o.min.z <= self.max.z
}
}
/// The box around the finite points (non-finite ones are skipped, as [`Aabb3::add`] does).
impl FromIterator<Vec3> for Aabb3 {
fn from_iter<I: IntoIterator<Item = Vec3>>(points: I) -> Aabb3 {
let mut b = Aabb3::EMPTY;
b.extend(points);
b
}
}
impl Extend<Vec3> for Aabb3 {
fn extend<I: IntoIterator<Item = Vec3>>(&mut self, points: I) {
for p in points {
self.add(p);
}
}
}
/// An indexed triangle mesh with per-vertex normals, a face id per triangle (the B-rep face it
@@ -76,10 +118,6 @@ pub struct Mesh {
pub edge_faces: Vec<Vec<u32>>,
}
fn boxes_meet(a: &Aabb3, b: &Aabb3) -> bool {
a.min.x <= b.max.x && b.min.x <= a.max.x && a.min.y <= b.max.y && b.min.y <= a.max.y && a.min.z <= b.max.z && b.min.z <= a.max.z
}
/// A triangle with its bounding box, as [`find_close_pair`] takes them.
pub type BoxedTriangle = ([Vec3; 3], Aabb3);
@@ -559,7 +597,7 @@ impl Mesh {
let t = m.tri(t)?;
let mut bx = Aabb3::EMPTY;
t.iter().for_each(|p| bx.add(*p));
(!bx.is_empty() && boxes_meet(&bx, &region)).then(|| ((t, bx), m.tri_face.get(i).copied().unwrap_or(u32::MAX)))
(!bx.is_empty() && bx.meets(&region)).then(|| ((t, bx), m.tri_face.get(i).copied().unwrap_or(u32::MAX)))
})
.unzip()
};
+34 -43
View File
@@ -6,7 +6,7 @@ use std::f64::consts::TAU;
use serde::{Deserialize, Serialize};
use crate::Vec2;
use crate::{Aabb2, Ring, Vec2};
/// One boundary segment in sketch coordinates.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
@@ -530,29 +530,26 @@ impl Loop2 {
pub fn ccw(&self) -> Loop2 {
if self.is_ccw() { self.clone() } else { self.reversed() }
}
pub fn polyline(&self, tol: f64) -> Vec<Vec2> {
let mut out = Vec::new();
for s in &self.segs {
let p = s.polyline(tol);
out.extend(p.iter().take(p.len().saturating_sub(1)));
}
out
/// Each segment with the next and the last with the first: the loop's joints, where one
/// segment should end on the start of the next.
pub fn joints(&self) -> impl Iterator<Item = (&Seg2, &Seg2)> + Clone {
crate::chain::around(&self.segs)
}
/// The loop as a polyline within `tol`: each segment's points but its last, which the next
/// segment starts on.
pub fn polyline(&self, tol: f64) -> Ring<Vec2> {
self.segs
.iter()
.flat_map(|s| {
let p = s.polyline(tol);
let n = p.len().saturating_sub(1);
p.into_iter().take(n)
})
.collect()
}
/// Even-odd point containment against the polyline approximation.
pub fn contains(&self, p: Vec2) -> bool {
let poly = self.polyline(1e-3);
let n = poly.len();
let mut inside = false;
for i in 0..n {
let (Some(a), Some(b)) = (poly.get(i), poly.get((i + 1) % n)) else { continue };
if (a.y > p.y) != (b.y > p.y) {
let x = a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x);
if p.x < x {
inside = !inside;
}
}
}
inside
self.polyline(1e-3).contains(p)
}
/// Area-weighted centroid (of the polyline approximation).
pub fn centroid(&self) -> Vec2 {
@@ -634,25 +631,20 @@ impl Region2 {
/// before they meet (a taper going in closes it there). Found by a grid search refined
/// around the best point, to about `tol`.
pub fn inradius(&self, tol: f64) -> f64 {
let loops: Vec<Vec<Vec2>> = std::iter::once(&self.outer).chain(&self.holes).map(|l| l.polyline(tol)).collect();
let loops: Vec<Ring<Vec2>> = std::iter::once(&self.outer).chain(&self.holes).map(|l| l.polyline(tol)).collect();
max_clearance(&loops)
}
}
/// The largest distance from a point inside `loops` (even-odd) to their sides, by a grid search
/// over their box refined around the best point. Zero for an empty or degenerate outline.
fn max_clearance(loops: &[Vec<Vec2>]) -> f64 {
let sides: Vec<(Vec2, Vec2)> = loops
.iter()
.flat_map(|pl| (0..pl.len()).filter_map(move |i| Some((*pl.get(i)?, *pl.get((i + 1) % pl.len())?))))
.filter(|(a, b)| a.dist(*b) > 0.0)
.collect();
let (Some(lo), Some(hi)) = (
sides.iter().map(|s| s.0).reduce(|a, b| Vec2::new(a.x.min(b.x), a.y.min(b.y))),
sides.iter().map(|s| s.0).reduce(|a, b| Vec2::new(a.x.max(b.x), a.y.max(b.y))),
) else {
fn max_clearance(loops: &[Ring<Vec2>]) -> f64 {
let sides: Vec<(Vec2, Vec2)> = loops.iter().flat_map(|pl| pl.edges().map(|(a, b)| (*a, *b))).filter(|(a, b)| a.dist(*b) > 0.0).collect();
let corners: Aabb2 = sides.iter().map(|s| s.0).collect();
if corners.is_empty() {
return 0.0;
};
}
let Aabb2 { min: lo, max: hi } = corners;
let inside = |p: Vec2| {
let mut odd = false;
for (a, b) in &sides {
@@ -782,26 +774,24 @@ pub fn regions_apart(regions: &[Region2], gap: f64) -> bool {
let tol = gap / 4.0;
let reach = gap + 2.0 * tol;
struct Outline {
loops: Vec<Vec<Vec2>>,
lo: Vec2,
hi: Vec2,
loops: Vec<Ring<Vec2>>,
bounds: Aabb2,
inside: Vec2,
}
let mut outlines = Vec::with_capacity(regions.len());
for r in regions {
let loops: Vec<Vec<Vec2>> = std::iter::once(&r.outer).chain(&r.holes).map(|l| l.polyline(tol)).collect();
let loops: Vec<Ring<Vec2>> = std::iter::once(&r.outer).chain(&r.holes).map(|l| l.polyline(tol)).collect();
let Some(outer) = loops.first().filter(|l| l.len() >= 2) else { return false };
if outer.iter().any(|p| !p.is_finite()) {
return false;
}
let lo = outer.iter().fold(Vec2::new(f64::MAX, f64::MAX), |m, p| Vec2::new(m.x.min(p.x), m.y.min(p.y)));
let hi = outer.iter().fold(Vec2::new(f64::MIN, f64::MIN), |m, p| Vec2::new(m.x.max(p.x), m.y.max(p.y)));
let bounds = outer.bounds();
let Some(inside) = outer.first().copied() else { return false };
outlines.push(Outline { loops, lo, hi, inside });
outlines.push(Outline { loops, bounds, inside });
}
let mut order: Vec<usize> = (0..outlines.len()).collect();
order.sort_by(|&i, &j| {
let x = |k: usize| outlines.get(k).map(|o| o.lo.x).unwrap_or(0.0);
let x = |k: usize| outlines.get(k).map(|o| o.bounds.min.x).unwrap_or(0.0);
x(i).total_cmp(&x(j))
});
let mut work = 0usize;
@@ -809,10 +799,11 @@ pub fn regions_apart(regions: &[Region2], gap: f64) -> bool {
let Some(a) = outlines.get(i) else { return false };
for &j in order.iter().skip(k + 1) {
let Some(b) = outlines.get(j) else { return false };
if b.lo.x > a.hi.x + reach {
let (a_box, b_box) = (a.bounds, b.bounds);
if b_box.min.x > a_box.max.x + reach {
break;
}
if b.lo.y > a.hi.y + reach || a.lo.y > b.hi.y + reach {
if b_box.min.y > a_box.max.y + reach || a_box.min.y > b_box.max.y + reach {
continue;
}
// A boundary point of one inside the other: one holds the other (boundaries that do
+15
View File
@@ -730,3 +730,18 @@ mod blend {
assert_eq!(d[0], Vec2::ZERO);
}
}
#[test]
fn a_box_from_points_holds_them_and_grows() {
let b: Aabb3 = [Vec3::new(1.0, 2.0, 3.0), Vec3::new(-1.0, 0.0, 5.0), Vec3::new(f64::INFINITY, 0.0, 0.0)].into_iter().collect();
assert_eq!((b.min, b.max), (Vec3::new(-1.0, 0.0, 3.0), Vec3::new(1.0, 2.0, 5.0)), "the infinite point is skipped");
assert!(b.contains(Vec3::new(0.0, 1.0, 4.0)) && !b.contains(Vec3::new(0.0, 1.0, 6.0)));
assert!(!b.contains(Vec3::new(f64::NAN, 1.0, 4.0)));
assert!(b.inflated(1.0).contains(Vec3::new(0.0, 1.0, 6.0)));
assert!(Aabb3::EMPTY.inflated(1e9).is_empty() && !Aabb3::EMPTY.contains(Vec3::ZERO));
let far = Aabb3 { min: Vec3::new(2.0, 0.0, 3.0), max: Vec3::new(3.0, 1.0, 4.0) };
assert!(!b.meets(&far) && b.inflated(1.0).meets(&far) && !b.meets(&Aabb3::EMPTY));
let both = b.intersection(&b.inflated(1.0).intersection(&Aabb3 { min: Vec3::new(0.0, 1.0, 4.0), max: Vec3::new(9.0, 9.0, 9.0) }));
assert_eq!((both.min, both.max), (Vec3::new(0.0, 1.0, 4.0), Vec3::new(1.0, 2.0, 5.0)));
assert!(b.intersection(&far).is_empty());
}
+12 -20
View File
@@ -9,7 +9,7 @@
use std::collections::HashMap;
use solidcraft_geom::Vec3;
use solidcraft_geom::{Aabb3, Vec3};
use truck_modeling::{self as mt, builder};
use crate::body::{Body, Solid, from_p3, p3, v3};
@@ -1295,7 +1295,7 @@ fn blend_each(mut cur: Body, edges: &[Vec3], r: f64, shape: Shape, what: &str, c
// edge, the refusal). A blend only changes the body near the edges it rounds, so an edge
// refused away from every later blend would be refused the same way again: it is not tried
// again (a refusal costs a rolling-ball attempt, seconds each on a long curved edge).
let mut refused: Vec<(Vec3, (Vec3, Vec3), KernelError)> = Vec::new();
let mut refused: Vec<(Vec3, Aabb3, KernelError)> = Vec::new();
// A chain runs on along the edges smooth with a selected one in the body as given, not along
// a round this blend has made meanwhile (which would take in edges nobody selected, or not,
// by the order the edges come in).
@@ -1333,13 +1333,13 @@ fn blend_each(mut cur: Body, edges: &[Vec3], r: f64, shape: Shape, what: &str, c
&& let Ok(b) = guard(what, || Ok(res)).and_then(|res| record::rebuilt(res, &[&solid], &rec))
{
let near = edges_box(&solid, &ids, r + tol);
refused.retain(|(_, b, _)| !boxes_meet(*b, near));
refused.retain(|(_, b, _)| !boxes_meet(b, &near));
cur = record::after(b, &cur, &counts);
todo.retain(|p| !covered.iter().any(|q| q.dist(*p) < 1e-12));
continue;
}
let mut first_err: Option<KernelError> = None;
let mut done: Option<(Body, Vec<usize>, (Vec3, Vec3))> = None;
let mut done: Option<(Body, Vec<usize>, Aabb3)> = None;
for (j, p) in todo.iter().enumerate() {
if let Some((_, _, e)) = refused.iter().find(|(q, _, _)| q.dist(*p) < 1e-12) {
if first_err.is_none() || (matches!(e, KernelError::TooLarge(_)) && !matches!(first_err, Some(KernelError::TooLarge(_)))) {
@@ -1455,7 +1455,7 @@ fn blend_each(mut cur: Body, edges: &[Vec3], r: f64, shape: Shape, what: &str, c
}
match done {
Some((b, js, near)) => {
refused.retain(|(_, b2, _)| !boxes_meet(*b2, near));
refused.retain(|(_, b2, _)| !boxes_meet(b2, &near));
cur = record::after(b, &cur, &counts);
let mut k = 0;
todo.retain(|_| {
@@ -1477,27 +1477,19 @@ thread_local! {
}
/// The box around these edges of `solid` (their ends and middles), grown by `margin`.
fn edges_box(solid: &Solid, ids: &[mt::EdgeID], margin: f64) -> (Vec3, Vec3) {
fn edges_box(solid: &Solid, ids: &[mt::EdgeID], margin: f64) -> Aabb3 {
use mt::{BoundedCurve, ParametricCurve};
let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
let mut hi = -lo;
for e in Body::unique_edges(solid).iter().filter(|e| ids.contains(&e.id())) {
let points = Body::unique_edges(solid).into_iter().filter(|e| ids.contains(&e.id())).flat_map(|e| {
let c = e.curve();
let (t0, t1) = c.range_tuple();
for k in 0..=8 {
let q = from_p3(c.subs(t0 + (t1 - t0) * f64::from(k) / 8.0));
lo = lo.min(q);
hi = hi.max(q);
}
}
let m = Vec3::new(margin, margin, margin);
(lo - m, hi + m)
(0..=8).map(move |k| from_p3(c.subs(t0 + (t1 - t0) * f64::from(k) / 8.0)))
});
points.collect::<Aabb3>().inflated(margin)
}
/// Whether two boxes overlap (an empty box meets every box: nothing is known about it).
fn boxes_meet(a: (Vec3, Vec3), b: (Vec3, Vec3)) -> bool {
let empty = |x: (Vec3, Vec3)| !(x.0.x <= x.1.x && x.0.y <= x.1.y && x.0.z <= x.1.z);
empty(a) || empty(b) || (a.0.x <= b.1.x && b.0.x <= a.1.x && a.0.y <= b.1.y && b.0.y <= a.1.y && a.0.z <= b.1.z && b.0.z <= a.1.z)
fn boxes_meet(a: &Aabb3, b: &Aabb3) -> bool {
a.is_empty() || b.is_empty() || a.meets(b)
}
/// Neighbouring edges along one boundary loop of a planar face that between them hold at least
+3 -9
View File
@@ -1,5 +1,5 @@
use serde::Serialize;
use solidcraft_geom::{Mesh, Vec3};
use solidcraft_geom::{Aabb3, Mesh, Vec3};
use truck_meshalgo::prelude::*;
use truck_modeling as mt;
@@ -542,14 +542,8 @@ fn orientation_tolerance(span: f64) -> f64 {
/// Bounding-box diagonal of a solid's vertices (1 when it has no finite extent).
fn span_of(solid: &Solid) -> f64 {
let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
let mut hi = -lo;
for v in solid.vertex_iter() {
let p = from_p3(v.point());
lo = Vec3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z));
hi = Vec3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z));
}
if lo.x.is_finite() { (hi - lo).len() } else { 1.0 }
let bounds: Aabb3 = solid.vertex_iter().map(|v| from_p3(v.point())).collect();
if bounds.is_empty() { 1.0 } else { bounds.diagonal() }
}
/// Equal shared values: the same allocation (a clone of the body), else equal contents.
+3 -8
View File
@@ -1,7 +1,7 @@
//! Building bodies: extrude and revolve planar regions, primitives.
use mt::builder;
use solidcraft_geom::{Grid, Loop2, Plane, Region2, Seg2, Vec2, Vec3};
use solidcraft_geom::{Grid, Loop2, Plane, Region2, Ring, Seg2, Vec2, Vec3};
use truck_modeling as mt;
use crate::body::{Body, Solid, from_p3, p3, v3};
@@ -1584,8 +1584,7 @@ fn revolve_on_axis(plane: &Plane, numbered: &NumberedLoop, axis_origin: Vec2, d:
}
};
// The loop's turning (Newell) against the surface normal halfway round.
let mut nw = Vec3::ZERO;
let poly: Vec<Vec3> = wire
let poly: Ring<Vec3> = wire
.edge_iter()
.flat_map(|ed| {
let c = ed.oriented_curve();
@@ -1593,11 +1592,7 @@ fn revolve_on_axis(plane: &Plane, numbered: &NumberedLoop, axis_origin: Vec2, d:
(0..8).map(move |j| from_p3(c.subs(t0 + (t1 - t0) * j as f64 / 8.0))).collect::<Vec<_>>()
})
.collect();
for (j, p) in poly.iter().enumerate() {
if let Some(q) = poly.get((j + 1) % poly.len()) {
nw += p.cross(*q);
}
}
let nw = poly.area_vector();
let probe = turn(&half, plane.to_world(sg.mid()));
let sn = surface.search_nearest_parameter(p3(probe), None, 100).map(|(u, v)| surface.normal(u, v));
if sn.is_some_and(|m| nw.dot(Vec3::new(m.x, m.y, m.z)) < 0.0) {
+6 -7
View File
@@ -24,7 +24,7 @@
use std::collections::HashMap;
use solidcraft_geom::{Aabb3, UnitVec3, Vec3};
use solidcraft_geom::{Aabb3, Ring, UnitVec3, Vec3};
use truck_modeling::{self as mt, builder};
use crate::body::shell_groups::boxes_separate;
@@ -1098,7 +1098,7 @@ fn faces_box(body: &Body, faces: &[usize], gap: f64) -> Option<Aabb3> {
bb.add(b.min);
bb.add(b.max);
}
(!bb.is_empty()).then(|| Aabb3 { min: bb.min - Vec3::new(gap, gap, gap), max: bb.max + Vec3::new(gap, gap, gap) })
(!bb.is_empty()).then(|| bb.inflated(gap))
}
/// `body` (with its history `h` over its operand) with its faces in the plane (n, d) split
@@ -1396,7 +1396,7 @@ fn inset_into(outer: &Body, inner: &Body, outer_operand: usize) -> Option<Result
let tol = (size * 1e-7).max(1e-9) * 10.0;
// Clear of the outer face's edges by more than the samples' chord error.
let clear = (size * 2e-3).max(1e-6);
let sample = |w: &mt::Wire| -> Option<Vec<Vec3>> {
let sample = |w: &mt::Wire| -> Option<Ring<Vec3>> {
if w.len() > 1000 {
return None;
}
@@ -1406,7 +1406,7 @@ fn inset_into(outer: &Body, inner: &Body, outer_operand: usize) -> Option<Result
let (t0, t1) = c.range_tuple();
pts.extend((0..SAMPLES).map(|k| from_p3(c.subs(t0 + (t1 - t0) * k as f64 / SAMPLES as f64))));
}
(!pts.is_empty() && pts.iter().all(|p| p.is_finite())).then_some(pts)
(!pts.is_empty() && pts.iter().all(|p| p.is_finite())).then(|| Ring::new(pts))
};
let fo: Vec<&mt::Face> = outer.solid.face_iter().collect();
let fi: Vec<&mt::Face> = inner.solid.face_iter().collect();
@@ -1423,7 +1423,7 @@ fn inset_into(outer: &Body, inner: &Body, outer_operand: usize) -> Option<Result
let (Some(inner_pts), Some(outer_loops)) = (sample(&outline), face_o.boundaries().iter().map(sample).collect::<Option<Vec<_>>>()) else {
continue;
};
let outer_count: usize = outer_loops.iter().map(Vec::len).sum();
let outer_count: usize = outer_loops.iter().map(|l| l.len()).sum();
if inner_pts.len().saturating_mul(outer_count) > MAX_WORK {
continue;
}
@@ -1436,8 +1436,7 @@ fn inset_into(outer: &Body, inner: &Body, outer_operand: usize) -> Option<Result
let outer_polys: Vec<_> = outer_loops.iter().map(|l| flat(l)).collect();
let inner_poly = flat(&inner_pts);
let in_outer = |p: Vec3| outer_polys.iter().filter(|l| l.contains(flat_point(p))).count() % 2 == 1;
let near_outer =
|p: Vec3| outer_loops.iter().any(|l| l.iter().zip(l.iter().cycle().skip(1)).any(|(s, t)| p.dist_to_segment(*s, *t) < clear));
let near_outer = |p: Vec3| outer_loops.iter().any(|l| l.edges().any(|(s, t)| p.dist_to_segment(*s, *t) < clear));
let fits = inner_pts.iter().all(|p| in_outer(*p) && !near_outer(*p))
&& outer_loops.iter().flatten().all(|p| !inner_poly.contains(flat_point(*p)));
if !fits {
+1 -1
View File
@@ -286,7 +286,7 @@ fn gap(c1: Vec3, r1: f64, c2: Vec3, r2: f64, corner: Vec3, r: f64) -> Gap {
ring.push(c + Vec3::new(t.cos(), t.sin(), 0.0) * rr);
}
}
let area = ring.iter().zip(ring.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum::<f64>().abs() * 0.5;
let area = ring.iter().map(|p| solidcraft_geom::Vec2::new(p.x, p.y)).collect::<solidcraft_geom::Ring<_>>().signed_area().abs();
let (p, q) = ((t1 - f).normalized().unwrap(), (t2 - f).normalized().unwrap());
let arc = (0..=8).map(|i| angles[2] * i as f64 / 8.0).map(|t| f + (p * ((angles[2] - t).sin()) + q * t.sin()) * (r / angles[2].sin())).collect();
Gap { arc, angles, area }
+4 -14
View File
@@ -12,7 +12,7 @@
use std::collections::{BTreeSet, HashMap};
use solidcraft_geom::Vec3;
use solidcraft_geom::{Aabb3, Vec3};
use truck_modeling::{self as mt, builder};
use crate::body::{Body, Solid, from_p3, p3};
@@ -117,19 +117,9 @@ pub fn delete_faces(body: &Body, faces: &[usize]) -> Result<Body> {
}
}
// Corners across the gap: three neighbour planes meeting near the deleted faces.
let (mut lo, mut hi) =
(Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY));
for &f in &del {
for v in all.get(f).into_iter().flat_map(|x| x.vertex_iter()) {
let p = from_p3(v.point());
lo = lo.min(p);
hi = hi.max(p);
}
}
let reach = (hi - lo).len().max(size * 1e-3);
let near = |p: Vec3| {
p.x >= lo.x - reach && p.y >= lo.y - reach && p.z >= lo.z - reach && p.x <= hi.x + reach && p.y <= hi.y + reach && p.z <= hi.z + reach
};
let gap: Aabb3 = del.iter().flat_map(|f| all.get(*f).into_iter().flat_map(|x| x.vertex_iter())).map(|v| from_p3(v.point())).collect();
let near_gap = gap.inflated(gap.diagonal().max(size * 1e-3));
let near = |p: Vec3| near_gap.contains(p);
let on = |p: Vec3, f: usize| planes.get(&f).is_some_and(|(n, d)| (n.dot(p) - d).abs() <= size * 1e-6);
let nb: Vec<usize> = neighbours.iter().copied().collect();
let mut corners: Vec<Vec3> = Vec::new();
+1 -6
View File
@@ -67,12 +67,7 @@ impl<'a> DistanceShape<'a> {
/// The box around the body: its mesh's, grown by the chord tolerance.
pub fn bounds(&self) -> Aabb3 {
let b = self.set.bounds();
if b.is_empty() {
return b;
}
let g = Vec3::new(1.0, 1.0, 1.0) * self.chord;
Aabb3 { min: b.min - g, max: b.max + g }
self.set.bounds().inflated(self.chord)
}
/// How far the mesh may lie from the faces (mm).
+3 -10
View File
@@ -7,8 +7,8 @@
//! its holes first.
use mt::{BoundedCurve, Cut, InnerSpace, Invertible, MetricSpace, ParametricCurve, ParametricSurface, SearchNearestParameter, Transformed};
use solidcraft_geom::Vec3;
use solidcraft_geom::tess::EvalSurface;
use solidcraft_geom::{Ring, Vec3};
use truck_modeling as mt;
use crate::body::from_p3;
@@ -30,20 +30,13 @@ pub(crate) struct LoopSamples {
impl LoopSamples {
/// The loop as a polygon in parameters (each edge's samples but its last, which the next
/// edge starts on).
pub(crate) fn polygon(&self) -> Vec<[f64; 2]> {
pub(crate) fn polygon(&self) -> Ring<[f64; 2]> {
self.edges.iter().flat_map(|(_, s)| s.iter().take(s.len().saturating_sub(1)).map(|x| x.2)).collect()
}
/// Signed area of the loop in parameters (positive: counter-clockwise).
pub(crate) fn area(&self) -> f64 {
let poly = self.polygon();
let n = poly.len();
(0..n)
.filter_map(|i| {
let (a, b) = (poly.get(i)?, poly.get((i + 1) % n)?);
Some(0.5 * (a[0] * b[1] - b[0] * a[1]))
})
.sum()
self.polygon().signed_area()
}
/// How far `p` is from the loop (from its samples).
+3 -13
View File
@@ -505,21 +505,11 @@ mod tests {
/// vanishes on the rim, so cells across it add little error).
fn gained(fill: &Body, corners: &[Vec2]) -> f64 {
let s = fill.solid.face_iter().next().unwrap().surface();
let (lo, hi) = corners.iter().fold((Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)), |(lo, hi), p| {
(Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y)))
});
let polygon = solidcraft_geom::Ring::from(corners.to_vec());
let solidcraft_geom::Aabb2 { min: lo, max: hi } = polygon.bounds();
let n = 300;
let (dx, dy) = ((hi.x - lo.x) / n as f64, (hi.y - lo.y) / n as f64);
let inside = |x: f64, y: f64| {
let mut w = false;
for k in 0..corners.len() {
let (a, b) = (corners[k], corners[(k + 1) % corners.len()]);
if (a.y > y) != (b.y > y) && x < a.x + (y - a.y) / (b.y - a.y) * (b.x - a.x) {
w = !w;
}
}
w
};
let inside = |x: f64, y: f64| polygon.contains(Vec2::new(x, y));
let mut sum = 0.0;
let mut start = None;
for i in 0..n {
+4 -11
View File
@@ -3,7 +3,7 @@
use std::collections::{BTreeSet, HashMap};
use solidcraft_geom::Vec3;
use solidcraft_geom::{Ring, Vec3};
use truck_modeling::{self as mt, builder};
use crate::body::{Solid, from_p3};
@@ -51,15 +51,7 @@ fn samples(e: &mt::Edge) -> Vec<Vec3> {
}
fn loop_area(edges: &[mt::Edge], n: Vec3) -> f64 {
let pts: Vec<Vec3> = edges.iter().flat_map(samples).collect();
let k = pts.len();
let mut s = Vec3::ZERO;
for i in 0..k {
if let (Some(a), Some(b)) = (pts.get(i), pts.get((i + 1) % k)) {
s += a.cross(*b);
}
}
s.dot(n) * 0.5
edges.iter().flat_map(samples).collect::<Ring<Vec3>>().area_vector().dot(n)
}
fn inside(p: Vec3, edges: &[mt::Edge], n: Vec3) -> bool {
@@ -680,7 +672,8 @@ mod tests {
.map(|k| builder::vertex(mt::Point3::new(k as f64, 0.0, 0.0)))
.chain([builder::vertex(mt::Point3::new(n as f64, 3.0, 0.0)), builder::vertex(mt::Point3::new(0.0, 3.0, 0.0))])
.collect();
let edges: Vec<mt::Edge> = pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| builder::line(a, b)).collect();
let pts: solidcraft_geom::Ring<mt::Vertex> = pts.into();
let edges: Vec<mt::Edge> = pts.edges().map(|(a, b)| builder::line(a, b)).collect();
let face = builder::try_attach_plane(&[mt::Wire::from(edges)]).expect("a plane");
builder::tsweep(&face, mt::Vector3::new(0.0, 0.0, 2.0))
}
+3 -3
View File
@@ -3,7 +3,7 @@
//! directly from the body's faces (the band's walls continue the walls below, which a boolean
//! union can't join: their faces would coincide).
use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec3};
use solidcraft_geom::{Loop2, Plane, Region2, Ring, Seg2, Vec3};
use truck_modeling::{self as mt, builder};
use crate::body::{Body, Solid, from_p3, p3, v3};
@@ -141,7 +141,7 @@ fn pieces(wire: &mt::Wire, size: f64) -> Result<Vec<Piece>> {
/// vertices, whose polygon has zero area for both the inner and outer loops.
fn turn(wire: &mt::Wire, n: Vec3) -> f64 {
use mt::{BoundedCurve, ParametricCurve};
let pts: Vec<Vec3> = wire
let ring: Ring<Vec3> = wire
.edge_iter()
.flat_map(|e| {
let c = e.oriented_curve();
@@ -149,7 +149,7 @@ fn turn(wire: &mt::Wire, n: Vec3) -> f64 {
[from_p3(e.front().point()), from_p3(c.subs((a + b) * 0.5))]
})
.collect();
pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| a.cross(*b).dot(n)).sum()
ring.area_vector().dot(n)
}
fn rim_loops(wires: &[mt::Wire], n: Vec3) -> Result<(&mt::Wire, &mt::Wire)> {
+5 -6
View File
@@ -331,7 +331,7 @@ fn contradicted(
let (under_a, under_b) = (|p: Vec3, f: u32| shared().under_cap(p, f, true, tol), |p: Vec3, f: u32| shared().under_cap(p, f, false, tol));
if disjoint {
let (ba, bb) = (ma.bounds(), mb.bounds());
let meet = solidcraft_geom::Aabb3 { min: ba.min.max(bb.min), max: ba.max.min(bb.max) };
let meet = ba.intersection(&bb);
return !meet.is_empty()
&& (under_surface(ma, ia, ib, tol, true, Some(&meet), &under_a) || under_surface(mb, ib, ia, tol, true, Some(&meet), &under_b));
}
@@ -1136,7 +1136,7 @@ fn meeting_size(a: &Body, b: &Body) -> f64 {
bb
};
let (ba, bb) = (bbox(a), bbox(b));
let s = solidcraft_geom::Aabb3 { min: ba.min.max(bb.min), max: ba.max.min(bb.max) }.size();
let s = ba.intersection(&bb).size();
// A closed sweep's section seams need not span its geometry. Roundoff in a flat
// vertex box is not a thin meeting region: refining for it
// makes millions of triangles and skips the bounded containment shortcut (#2005).
@@ -1149,7 +1149,7 @@ fn meeting_size(a: &Body, b: &Body) -> f64 {
/// on its seam, so its vertex box says nothing about where its side reaches.
fn mesh_meeting_size(a: &solidcraft_geom::Mesh, b: &solidcraft_geom::Mesh) -> f64 {
let (ba, bb) = (a.bounds(), b.bounds());
let s = solidcraft_geom::Aabb3 { min: ba.min.max(bb.min), max: ba.max.min(bb.max) }.size();
let s = ba.intersection(&bb).size();
if s.x > 0.0 && s.y > 0.0 && s.z > 0.0 { s.x.min(s.y).min(s.z) } else { f64::INFINITY }
}
@@ -1477,7 +1477,7 @@ where
let fine_tols: Vec<f64> = match &meshes {
(Some(ma), Some(mb)) if a.solid.boundaries().len() == 1 && b.solid.boundaries().len() == 1 => {
let (ba, bb) = (ma.bounds(), mb.bounds());
let s = solidcraft_geom::Aabb3 { min: ba.min.max(bb.min), max: ba.max.min(bb.max) }.size();
let s = ba.intersection(&bb).size();
// The thinner operand's thickness (twice its volume over its area: a plate's
// thickness, a rod's radius) bounds what the tolerance must resolve as well.
let thickness = |m: &solidcraft_geom::Mesh| {
@@ -2005,8 +2005,7 @@ fn union_apart_untimed(bodies: &[Body]) -> Result<Option<Body>> {
if bb.is_empty() {
return Ok(None);
}
let pad = Vec3::new(1.0, 1.0, 1.0) * (2.0 * tol);
boxes.push(solidcraft_geom::Aabb3 { min: bb.min - pad, max: bb.max + pad });
boxes.push(bb.inflated(2.0 * tol));
}
// Sweep along x: only boxes whose x ranges overlap are compared.
let mut order: Vec<usize> = (0..boxes.len()).collect();
+2 -6
View File
@@ -5,7 +5,7 @@
use std::collections::{BTreeMap, BTreeSet, HashMap};
use solidcraft_geom::{Mesh, Vec3};
use solidcraft_geom::{Aabb3, Mesh, Vec3};
use truck_modeling::{self as mt, builder};
use crate::body::{Body, Solid, edge_order, from_p3, p3};
@@ -365,11 +365,7 @@ fn faceted_boolean_untimed(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result<O
if pa.len() + pb.len() > MAX_POLYS {
return Err(KernelError::Failed("the bodies are too detailed to facet".into()));
}
let (lo, hi) = b
.positions
.iter()
.fold((Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)), |(l, h), p| (l.min(*p), h.max(*p)));
let size = if b.positions.is_empty() { a.size() } else { a.size().max((hi - lo).len()) };
let size = if b.positions.is_empty() { a.size() } else { a.size().max(b.positions.iter().copied().collect::<Aabb3>().diagonal()) };
// Fine facets of curved faces meet at shallow angles, where the coplanar test decides
// whether the pieces' boundaries come out consistent: try a few tolerances, and take the
// first whose result is watertight and agrees with the complementary boolean (A − B and
+24 -35
View File
@@ -8,7 +8,7 @@
use std::borrow::Cow;
use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3};
use solidcraft_geom::{Aabb2, Loop2, Plane, Region2, Seg2, Vec2, Vec3};
use truck_modeling as mt;
use crate::body::{Body, from_p3};
@@ -903,11 +903,10 @@ fn inside_loop(lp: &Loop2, p: Vec2) -> bool {
let scale = 1.0 + p.x.abs().max(p.y.abs());
// A point clear of the loop's box (by more than the ray shifts below) is outside it: skip
// the costly tests, which a region with a thousand cut-outs runs for every probe (#732).
if let Some((lo, hi)) = loop_box(lp) {
let m = scale * 1e-6;
if p.x < lo.x - m || p.x > hi.x + m || p.y < lo.y - m || p.y > hi.y + m {
return false;
}
if let Some(b) = loop_box(lp)
&& !b.inflated(scale * 1e-6).contains(p)
{
return false;
}
// A point on the loop keeps the half-open answer.
if lp.segs.iter().any(|s| s.point_at(closest_param(s, p)).dist(p) < scale * 1e-9) {
@@ -928,21 +927,16 @@ fn inside_loop(lp: &Loop2, p: Vec2) -> bool {
}
/// A box holding a loop of lines and arcs (an arc's whole circle); None for other curves.
fn loop_box(lp: &Loop2) -> Option<(Vec2, Vec2)> {
let mut lo = Vec2::new(f64::MAX, f64::MAX);
let mut hi = Vec2::new(f64::MIN, f64::MIN);
let mut add = |a: Vec2, b: Vec2| {
lo = Vec2::new(lo.x.min(a.x), lo.y.min(a.y));
hi = Vec2::new(hi.x.max(b.x), hi.y.max(b.y));
};
fn loop_box(lp: &Loop2) -> Option<Aabb2> {
let mut b = Aabb2::EMPTY;
for seg in &lp.segs {
match *seg {
Seg2::Line { a, b } => add(Vec2::new(a.x.min(b.x), a.y.min(b.y)), Vec2::new(a.x.max(b.x), a.y.max(b.y))),
Seg2::Arc { center, radius, .. } => add(center - Vec2::new(radius.abs(), radius.abs()), center + Vec2::new(radius.abs(), radius.abs())),
b = b.union(&match *seg {
Seg2::Line { a, b } => Aabb2 { min: Vec2::new(a.x.min(b.x), a.y.min(b.y)), max: Vec2::new(a.x.max(b.x), a.y.max(b.y)) },
Seg2::Arc { center, radius, .. } => Aabb2 { min: center, max: center }.inflated(radius.abs()),
_ => return None,
}
});
}
(lo.x <= hi.x && lo.y <= hi.y && [lo.x, lo.y, hi.x, hi.y].iter().all(|v| v.is_finite())).then_some((lo, hi))
(!b.is_empty() && b.min.is_finite() && b.max.is_finite()).then_some(b)
}
/// [`inside_loop`] with the ray along +x from `p` taken as given.
@@ -1071,12 +1065,9 @@ fn dist_to(regions: &[Region2], p: Vec2) -> f64 {
}
/// The bounding box of a line or an arc, grown by twice the tolerance (and by the rounding of
/// its own corners): (min, max). Whatever lies within the tolerance of the segment lies in the
/// box. `None` for other segments and for values that are not finite: no box, and nothing is
/// skipped for it.
type SegBox = (Vec2, Vec2);
fn seg_box(s: &Seg2, tol: f64) -> Option<SegBox> {
/// its own corners). Whatever lies within the tolerance of the segment lies in the box. `None`
/// for other segments and for values that are not finite: no box, and nothing is skipped for it.
fn seg_box(s: &Seg2, tol: f64) -> Option<Aabb2> {
let mut pts = vec![s.start(), s.end()];
match *s {
Seg2::Line { .. } => {}
@@ -1093,31 +1084,29 @@ fn seg_box(s: &Seg2, tol: f64) -> Option<SegBox> {
}
_ => return None,
}
let lo = pts.iter().fold(Vec2::new(f64::INFINITY, f64::INFINITY), |m, p| Vec2::new(m.x.min(p.x), m.y.min(p.y)));
let hi = pts.iter().fold(Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY), |m, p| Vec2::new(m.x.max(p.x), m.y.max(p.y)));
let g = tol * 2.0 + 1e-12 * pts.iter().fold(0.0, |m: f64, p| m.max(p.x.abs()).max(p.y.abs()));
(pts.iter().all(|p| p.is_finite()) && g.is_finite()).then_some((Vec2::new(lo.x - g, lo.y - g), Vec2::new(hi.x + g, hi.y + g)))
(pts.iter().all(|p| p.is_finite()) && g.is_finite()).then(|| pts.iter().copied().collect::<Aabb2>().inflated(g))
}
fn boxes_meet(a: Option<SegBox>, b: Option<SegBox>) -> bool {
fn boxes_meet(a: Option<Aabb2>, b: Option<Aabb2>) -> bool {
match (a, b) {
(Some((a0, a1)), Some((b0, b1))) => a0.x <= b1.x && b0.x <= a1.x && a0.y <= b1.y && b0.y <= a1.y,
(Some(a), Some(b)) => a.meets(&b),
_ => true,
}
}
fn box_holds(b: Option<SegBox>, p: Vec2) -> bool {
b.is_none_or(|(lo, hi)| p.x >= lo.x && p.x <= hi.x && p.y >= lo.y && p.y <= hi.y)
fn box_holds(b: Option<Aabb2>, p: Vec2) -> bool {
b.is_none_or(|b| b.contains(p))
}
/// Distance from `p` to the nearest of `segs` whose box holds it: infinite when none does (no
/// segment is within the tolerance of `p` then).
fn near_dist(segs: &[Seg2], boxes: &[Option<SegBox>], p: Vec2) -> f64 {
fn near_dist(segs: &[Seg2], boxes: &[Option<Aabb2>], p: Vec2) -> f64 {
segs.iter().zip(boxes).filter(|(_, b)| box_holds(**b, p)).map(|(s, _)| s.point_at(closest_param(s, p)).dist(p)).fold(f64::INFINITY, f64::min)
}
/// Direction of the first of `segs` through `p` (within `tol`), as it runs.
fn near_dir(segs: &[Seg2], boxes: &[Option<SegBox>], p: Vec2, tol: f64) -> Option<Vec2> {
fn near_dir(segs: &[Seg2], boxes: &[Option<Aabb2>], p: Vec2, tol: f64) -> Option<Vec2> {
let (s, t) = segs
.iter()
.zip(boxes)
@@ -3194,10 +3183,10 @@ mod planar_tests {
let r = 10.0 * std::f64::consts::FRAC_1_SQRT_2;
let arc = Seg2::Arc { center: Vec2::ZERO, radius: 10.0, start: std::f64::consts::FRAC_PI_4, sweep: std::f64::consts::FRAC_PI_2 };
for s in [arc, arc.reversed()] {
let (lo, hi) = seg_box(&s, 1e-3).unwrap();
let Aabb2 { min: lo, max: hi } = seg_box(&s, 1e-3).unwrap();
assert!(lo.dist(Vec2::new(-r - 2e-3, r - 2e-3)) < 1e-9 && hi.dist(Vec2::new(r + 2e-3, 10.0 + 2e-3)) < 1e-9, "{lo:?} {hi:?}");
}
let (lo, hi) = seg_box(&Seg2::Line { a: Vec2::new(3.0, -1.0), b: Vec2::new(-2.0, 4.0) }, 0.5).unwrap();
let Aabb2 { min: lo, max: hi } = seg_box(&Seg2::Line { a: Vec2::new(3.0, -1.0), b: Vec2::new(-2.0, 4.0) }, 0.5).unwrap();
assert!(lo.dist(Vec2::new(-3.0, -2.0)) < 1e-9 && hi.dist(Vec2::new(4.0, 5.0)) < 1e-9, "{lo:?} {hi:?}");
// A line 3 tolerances above the arc's top meets its box (each is grown by two); one
// 5 tolerances above does not. No box (a free-form segment, a value that is not
+11 -10
View File
@@ -1,7 +1,7 @@
//! Independent current-geometry intervals for uniform prisms.
//! These are not mesh measurements or certificates of construction history.
use crate::body::from_p3;
use solidcraft_geom::{Plane, Seg2, Vec2, Vec3};
use solidcraft_geom::{Plane, Ring, Seg2, Vec2, Vec3};
use truck_modeling as mt;
#[derive(Clone, Copy, Debug)]
@@ -46,7 +46,7 @@ fn green_interval(segment: &Seg2, tolerance: f64) -> Option<Interval> {
}
struct CapLoop {
segments: Vec<Seg2>,
segments: Ring<Seg2>,
area: Interval,
}
@@ -331,15 +331,15 @@ fn wall_supports_cap(surface: &mt::Surface, edge: &mt::Edge, plane: &Plane, leve
let Some(fit) = crate::prism_curve::segment(&support, plane, tol, work) else {
continue;
};
let fit_loop = CapLoop { segments: fit.clone(), area: Interval::enclosing(0., 0.)? };
let fit_loop = CapLoop { segments: Ring::from(fit.clone()), area: Interval::enclosing(0., 0.)? };
if let Some((center, radius)) = circle(&fit_loop, tol * 8.)
&& cap.iter().all(|s| matches!(*s,Seg2::Arc {center:c,radius:r,..} if c.dist(center)+(r-radius).abs()<=tol*8.))
{
return Some(true);
}
let same = loops_same(
&CapLoop { segments: cap.clone(), area: Interval::enclosing(0., 0.)? },
&CapLoop { segments: fit, area: Interval::enclosing(0., 0.)? },
&CapLoop { segments: Ring::from(cap.clone()), area: Interval::enclosing(0., 0.)? },
&CapLoop { segments: Ring::from(fit), area: Interval::enclosing(0., 0.)? },
tol * 8.,
work,
)?;
@@ -442,11 +442,10 @@ fn separated_material(loops: &[CapLoop], clearance: f64, work: &mut usize) -> Op
}
let mut turn = 0.;
let mut angular_error = 0.;
for (i, s) in outer.segments.iter().enumerate() {
for (i, (s, next)) in outer.segments.edges().enumerate() {
let Seg2::Line { a, b } = *s else {
return None;
};
let next = outer.segments.get((i + 1) % outer.segments.len())?;
let x = b - a;
let y = next.end() - next.start();
turn += x.cross(y).atan2(x.dot(y));
@@ -735,8 +734,9 @@ fn cap_loop(wire: &mt::Wire, plane: &Plane, tolerance: f64, work: &mut usize) ->
}
// Curve endpoints already agree with actual shared vertices in the
// whole-span proof. Check the fitted representation's continuity too.
for i in 0..segments.len() {
if segments.get(i)?.end().dist(segments.get((i + 1) % segments.len())?.start()) > 2. * tolerance {
let segments = Ring::new(segments);
for (a, b) in segments.edges() {
if a.end().dist(b.start()) > 2. * tolerance {
return None;
}
}
@@ -872,7 +872,8 @@ mod tests {
#[test]
fn winding_retracing_and_uncertain_material_do_not_get_certificates() {
let arc = Seg2::Arc { center: Vec2::ZERO, radius: 6., start: 0., sweep: std::f64::consts::TAU };
let retraced = CapLoop { segments: vec![arc, arc.reversed(), arc], area: Interval::enclosing(36. * std::f64::consts::PI, 1e-8).unwrap() };
let retraced =
CapLoop { segments: Ring::from([arc, arc.reversed(), arc]), area: Interval::enclosing(36. * std::f64::consts::PI, 1e-8).unwrap() };
assert!(circle(&retraced, 1e-6).is_none());
let region = solidcraft_geom::Loop2::polygon(&[Vec2::ZERO, Vec2::new(20., 0.), Vec2::new(20., 20.), Vec2::new(0., 20.)]);
let doubled = CapLoop { segments: region.segs.iter().chain(&region.segs).copied().collect(), area: Interval::enclosing(800., 1e-8).unwrap() };
+5 -16
View File
@@ -10,7 +10,7 @@
use std::collections::BTreeSet;
use solidcraft_geom::{Mesh, Plane, Region2, Seg2, Vec2, Vec3};
use solidcraft_geom::{Aabb3, Mesh, Plane, Region2, Seg2, Vec2, Vec3};
use crate::Result;
use crate::body::Body;
@@ -22,30 +22,19 @@ const SAMPLES: usize = 24;
/// A face's triangles with their unit normals, and its box.
struct FaceTris {
tris: Vec<([Vec3; 3], Vec3)>,
lo: Vec3,
hi: Vec3,
bounds: Aabb3,
area: f64,
}
fn face_tris(m: &Mesh) -> Vec<FaceTris> {
let n = m.tri_face.iter().copied().max().map(|x| x as usize + 1).unwrap_or(0);
let mut out: Vec<FaceTris> = (0..n)
.map(|_| FaceTris {
tris: Vec::new(),
lo: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
hi: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
area: 0.0,
})
.collect();
let mut out: Vec<FaceTris> = (0..n).map(|_| FaceTris { tris: Vec::new(), bounds: Aabb3::EMPTY, area: 0.0 }).collect();
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
let (Some(slot), Some(p)) = (out.get_mut(*f as usize), m.tri(t)) else { continue };
let c = (p[1] - p[0]).cross(p[2] - p[0]);
let Some(nrm) = c.normalized() else { continue };
slot.area += c.len() * 0.5;
for q in p {
slot.lo = slot.lo.min(q);
slot.hi = slot.hi.max(q);
}
slot.bounds.extend(p);
slot.tris.push((p, nrm));
}
out
@@ -85,7 +74,7 @@ fn closest_on_tri(p: Vec3, [a, b, c]: [Vec3; 3]) -> Vec3 {
/// Does point `p` with normal `n` lie on the face (within `tol`, normals along each other)?
fn on_face(f: &FaceTris, p: Vec3, n: Vec3, tol: f64) -> bool {
if p.x < f.lo.x - tol || p.y < f.lo.y - tol || p.z < f.lo.z - tol || p.x > f.hi.x + tol || p.y > f.hi.y + tol || p.z > f.hi.z + tol {
if !f.bounds.inflated(tol).contains(p) {
return false;
}
// Either side: a cut's tool faces come out turned inside out.
+3 -2
View File
@@ -9,7 +9,7 @@ use std::collections::HashMap;
use std::sync::Arc;
use mt::builder;
use solidcraft_geom::Vec3;
use solidcraft_geom::{Ring, Vec3};
use truck_modeling as mt;
use crate::body::{Body, Solid, p3, v3};
@@ -428,7 +428,8 @@ fn edge_sheets(faces: &[FaceSpec], group: &[(EdgeUse, Vec3, Vec3)]) -> Result<[[
j -= 1;
}
}
let wedges: Vec<_> = rays.iter().zip(rays.iter().cycle().skip(1)).collect();
let rays = Ring::new(rays);
let wedges: Vec<_> = rays.edges().collect();
// Each wedge's faces must use the edge in opposite directions, and be told apart (faces
// leaving the same way and turning alike lie on each other).
let same_way = |p: f64, q: f64| {
+3 -2
View File
@@ -10,6 +10,7 @@
use std::f64::consts::{FRAC_PI_2, PI, TAU};
use mt::{BoundedCurve, Cut, InnerSpace, Invertible, MetricSpace, ParametricCurve, ParametricSurface3D, SearchNearestParameter};
use solidcraft_geom::Ring;
use truck_modeling as mt;
use super::Ctx;
@@ -711,8 +712,8 @@ fn largest_gap(angles: &[f64]) -> Option<(f64, f64)> {
}
a.sort_by(f64::total_cmp);
let (mut best, mut mid) = (0.0, 0.0);
for i in 0..a.len() {
let (Some(&x), Some(&y)) = (a.get(i), a.get((i + 1) % a.len())) else { continue };
let a = Ring::new(a);
for (i, (&x, &y)) in a.edges().enumerate() {
let gap = if i + 1 == a.len() { y + TAU - x } else { y - x };
if gap > best {
best = gap;
+7 -5
View File
@@ -5,6 +5,8 @@
//! added. The boundary stays exactly the shared edge nodes, so the face meets its neighbours
//! exactly, and only the band next to the boundary is irregular (cut-cell meshing).
use solidcraft_geom::Ring;
use super::cdt;
use super::motorcycle::Trace;
@@ -196,6 +198,7 @@ pub(crate) fn cut_grid(
across.push(c);
}
}
let poly = Ring::new(poly);
if poly.len() == 4 {
let [a, b, c, d] = [*poly.first()?, *poly.get(1)?, *poly.get(2)?, *poly.get(3)?];
tris.push([a, b, c]);
@@ -205,14 +208,13 @@ pub(crate) fn cut_grid(
let centre = [0.5 * (lu.at.get(i0)? + lu.at.get(i1)?), 0.5 * (lv.at.get(j0)? + lv.at.get(j1)?)];
let m = u32::try_from(n + extra.len()).ok()?;
extra.push(centre);
for k in 0..poly.len() {
tris.push([m, *poly.get(k)?, *poly.get((k + 1) % poly.len())?]);
for (&a, &b) in poly.edges() {
tris.push([m, a, b]);
}
}
for k in 0..poly.len() {
let (ci, cj) = *across.get(k)?;
for ((&a, &b), &(ci, cj)) in poly.edges().zip(&across) {
if !kept(ci, cj) {
stairs.push((*poly.get(k)?, *poly.get((k + 1) % poly.len())?));
stairs.push((a, b));
}
}
}
+2 -7
View File
@@ -469,7 +469,7 @@ fn plan_pieces(f: &Region) -> Option<(Vec<[f64; 2]>, Vec<[u32; 3]>)> {
let mut tris: Vec<[u32; 3]> = Vec::new();
for pc in &pieces {
// The patch's own loops, numbered from zero.
let mut ids: Vec<u32> = pc.ring.clone();
let mut ids: Vec<u32> = pc.ring.to_vec();
let mut ranges = vec![std::ops::Range { start: 0, end: pc.ring.len() }];
for hole in &pc.holes {
ranges.push(ids.len()..ids.len() + hole.len());
@@ -494,12 +494,7 @@ fn plan_pieces(f: &Region) -> Option<(Vec<[f64; 2]>, Vec<[u32; 3]>)> {
a >= n || b >= n || !f.ranges.iter().any(|r| r.contains(&a) && r.contains(&b) && (a.abs_diff(b) == 1 || a.abs_diff(b) == r.len() - 1))
};
let ring = &pc.ring;
let switches: Vec<usize> = (0..ring.len())
.filter(|&k| {
let (p, c, x) = (ring.get((k + ring.len() - 1) % ring.len()), ring.get(k), ring.get((k + 1) % ring.len()));
matches!((p, c, x), (Some(&p), Some(&c), Some(&x)) if is_cut(p, c) != is_cut(c, x))
})
.collect();
let switches: Vec<usize> = ring.corners().enumerate().filter(|&(_, (&p, &c, &x))| is_cut(p, c) != is_cut(c, x)).map(|(k, _)| k).collect();
// The patch is a rectangle in (u, v) with corners cut by free boundary (Lyon et al. §4;
// completed virtually in §4.2): its bounding box. A grid needs four real sides, so each
// corner is the node furthest out towards the box's corner (in the box's own
+13 -23
View File
@@ -8,6 +8,8 @@
use std::collections::HashMap;
use solidcraft_geom::Ring;
/// Where a cut segment ends.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum End {
@@ -33,8 +35,8 @@ pub(crate) struct Segment {
/// by the cut nodes, counter-clockwise (holes clockwise) in (u, v).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Piece {
pub ring: Vec<u32>,
pub holes: Vec<Vec<u32>>,
pub ring: Ring<u32>,
pub holes: Vec<Ring<u32>>,
}
/// Cut the face bounded by `loops` (ranges of `boundary`) along `segments`, measured in the
@@ -233,7 +235,7 @@ pub(crate) fn cut(
before.map(|(_, e)| *e).or_else(|| list.iter().find(|(_, e)| half.get(*e).is_some_and(|x| x.1 == u)).map(|(_, e)| *e))
};
let mut seen = vec![false; half.len()];
let mut rings: Vec<Vec<u32>> = Vec::new();
let mut rings: Vec<Ring<u32>> = Vec::new();
for h0 in 0..half.len() {
if *seen.get(h0)? {
continue;
@@ -251,18 +253,11 @@ pub(crate) fn cut(
return None;
}
}
rings.push(ring);
rings.push(Ring::new(ring));
}
let area = |ring: &[u32]| -> Option<f64> {
let mut s = 0.0;
for k in 0..ring.len() {
let (a, b) = (pos(*ring.get(k)?)?, pos(*ring.get((k + 1) % ring.len())?)?);
s += a[0] * b[1] - b[0] * a[1];
}
Some(0.5 * s)
};
let area = |ring: &Ring<u32>| -> Option<f64> { Some(ring.iter().map(|&k| pos(k)).collect::<Option<Ring<_>>>()?.signed_area()) };
let mut pieces: Vec<Piece> = Vec::new();
let mut holes: Vec<Vec<u32>> = Vec::new();
let mut holes: Vec<Ring<u32>> = Vec::new();
for r in rings {
if area(&r)? > 0.0 {
pieces.push(Piece { ring: r, holes: Vec::new() });
@@ -273,10 +268,10 @@ pub(crate) fn cut(
// A loop no cut reached is a hole of the patch around it.
for h in holes {
let p = pos(*h.first()?)?;
let contains = |ring: &[u32]| {
let contains = |ring: &Ring<u32>| {
let mut odd = false;
for k in 0..ring.len() {
let (Some(a), Some(b)) = (ring.get(k).and_then(|x| pos(*x)), ring.get((k + 1) % ring.len()).and_then(|x| pos(*x))) else { continue };
for (&a, &b) in ring.edges() {
let (Some(a), Some(b)) = (pos(a), pos(b)) else { continue };
if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < a[0] + (p[1] - a[1]) / (b[1] - a[1]) * (b[0] - a[0]) {
odd = !odd;
}
@@ -296,13 +291,8 @@ pub(crate) fn cut(
mod tests {
use super::*;
fn area(all: &[[f64; 2]], ring: &[u32]) -> f64 {
(0..ring.len())
.map(|k| {
let (a, b) = (all[ring[k] as usize], all[ring[(k + 1) % ring.len()] as usize]);
0.5 * (a[0] * b[1] - b[0] * a[1])
})
.sum()
fn area(all: &[[f64; 2]], ring: &Ring<u32>) -> f64 {
ring.iter().map(|&k| all[k as usize]).collect::<Ring<_>>().signed_area()
}
/// A square cut by four segments meeting at its centre (one point inside the face, shared)
+1 -2
View File
@@ -302,8 +302,7 @@ fn crosses(uv: &[[f64; 2]], x0: f64, x1: f64) -> bool {
fn clip(path: &[[f64; 2]], pts: &[Vec3], x0: f64, x1: f64, out: &mut Vec<Piece>) {
let inside = |q: &[f64; 2]| q[0] > x0 && q[0] < x1;
let mut cur: Option<Piece> = None;
for k in 0..path.len().saturating_sub(1) {
let (Some(a), Some(b), Some(pa), Some(pb)) = (path.get(k), path.get(k + 1), pts.get(k), pts.get(k + 1)) else { break };
for ((a, b), (pa, pb)) in path.iter().zip(path.iter().skip(1)).zip(pts.iter().zip(pts.iter().skip(1))) {
let at = |x: f64| {
let t = ((x - a[0]) / (b[0] - a[0])).clamp(0.0, 1.0);
([x, a[1] + (b[1] - a[1]) * t], *pa + (*pb - *pa) * t)
+1 -1
View File
@@ -621,7 +621,7 @@ fn tapered_extrude_swallows_a_short_tip() {
let meet = |(p0, t0): (Vec2, Vec2), (p1, t1): (Vec2, Vec2)| p0 + t0 * ((p1 - p0).cross(t1) / t0.cross(t1));
let (low, high, left) = (moved(pts[0], pts[1]), moved(pts[2], pts[3]), moved(pts[3], pts[0]));
let top = [meet(left, low), meet(low, high), meet(high, left)];
let area = |q: &[Vec2]| 0.5 * q.iter().zip(q.iter().cycle().skip(1)).map(|(a, b)| a.cross(*b)).sum::<f64>();
let area = |q: &[Vec2]| solidcraft_geom::Ring::from(q.to_vec()).signed_area();
// Halfway up, each side edge's midpoint (the two tip corners both run to the top's tip).
let mid = [pts[0].lerp(top[0], 0.5), pts[1].lerp(top[1], 0.5), pts[2].lerp(top[1], 0.5), pts[3].lerp(top[2], 0.5)];
let v = h / 6.0 * (area(&pts) + 4.0 * area(&mid) + area(&top));
+5 -12
View File
@@ -9,7 +9,7 @@
//! An end is tied when it is shared with another curve's end, joined to one by coincident
//! constraints, or held on a curve (point on curve, midpoint).
use solidcraft_geom::{Seg2, Vec2};
use solidcraft_geom::{Aabb2, Seg2, Vec2};
use crate::model::{ConstraintKind, CurveKind, Sketch};
use crate::union_find::{find, union};
@@ -59,18 +59,11 @@ fn profile_curve(sk: &Sketch, ci: usize) -> bool {
}
/// A box around a segment (conservative for curved ones).
fn seg_box(s: &Seg2) -> (Vec2, Vec2) {
let hull = |pts: &[Vec2]| {
pts.iter().fold((Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), p| {
(Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y)))
})
};
fn seg_box(s: &Seg2) -> Aabb2 {
let hull = |pts: &[Vec2]| pts.iter().copied().collect::<Aabb2>();
match *s {
Seg2::Line { a, b } => hull(&[a, b]),
Seg2::Arc { center, radius, .. } => {
let r = Vec2::new(radius.abs(), radius.abs());
(center - r, center + r)
}
Seg2::Arc { center, radius, .. } => Aabb2 { min: center, max: center }.inflated(radius.abs()),
Seg2::Cubic { p0, p1, p2, p3 } => hull(&[p0, p1, p2, p3]),
Seg2::Conic { a, apex, b, .. } => hull(&[a, apex, b]),
Seg2::Bezier { n, p } => hull(p.get(..=usize::from(n)).unwrap_or(p.as_slice())),
@@ -151,7 +144,7 @@ pub fn loose_ends(sk: &Sketch) -> EndReport {
}
let curve_ends = c.kind.ends();
for seg in sk.segs(ci) {
let (lo, hi) = seg_box(&seg);
let Aabb2 { min: lo, max: hi } = seg_box(&seg);
let first = free.partition_point(|f| f.2.x < lo.x - END_TOL);
for (k, &(p, own, at)) in free.iter().enumerate().skip(first) {
if at.x > hi.x + END_TOL {
+3 -4
View File
@@ -7,7 +7,7 @@
//! constants; they still bound profiles and take constraints and dimensions like any curve.
use serde::{Deserialize, Serialize};
use solidcraft_geom::{Vec2, Vec3};
use solidcraft_geom::{Aabb2, Vec2, Vec3};
use crate::model::{Curve, CurveKind, Result, Sketch, SketchError, in_range, radius_in_range};
@@ -822,9 +822,8 @@ impl Sketch {
{
let old: Vec<Vec2> = points.iter().filter_map(|i| self.point(*i)).collect();
let normalized = |ps: &[Vec2]| -> Vec<Vec2> {
let lo = ps.iter().fold(Vec2::new(f64::INFINITY, f64::INFINITY), |a, p| Vec2::new(a.x.min(p.x), a.y.min(p.y)));
let hi = ps.iter().fold(Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY), |a, p| Vec2::new(a.x.max(p.x), a.y.max(p.y)));
ps.iter().map(|p| Vec2::new((p.x - lo.x) / (hi.x - lo.x).max(1e-9), (p.y - lo.y) / (hi.y - lo.y).max(1e-9))).collect()
let b: Aabb2 = ps.iter().copied().collect();
ps.iter().map(|p| b.relative(*p)).collect()
};
let loop_roles_required = self.link(id).is_some_and(|l| matches!(l.source, LinkSource::Face { .. }))
&& cur.iter().chain(&lay.curves).all(|c| matches!(c, LCurve::Line(..) | LCurve::Arc(..) | LCurve::Circle(..)))
+13 -25
View File
@@ -2,14 +2,13 @@
//! Endpoint walks exclude support centres. Crossings/touches refuse before nesting.
use super::{LCurve, curve_points};
use crate::{Shape, intersections};
use solidcraft_geom::Vec2;
use solidcraft_geom::{Aabb2, Vec2};
use std::f64::consts::TAU;
struct Boundary {
curves: Vec<usize>,
shapes: Vec<Shape>,
lo: Vec2,
hi: Vec2,
bounds: Aabb2,
depth: usize,
signature: [usize; 3],
}
@@ -180,8 +179,7 @@ fn boundaries(curves: &[LCurve], pts: &[Vec2]) -> Option<Vec<Boundary>> {
pending.extend(incidence.get(b)?);
}
}
let mut lo = Vec2::new(f64::INFINITY, f64::INFINITY);
let mut hi = Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY);
let mut bounds = Aabb2::EMPTY;
let mut signature = [0; 3];
let mut bound_shapes = Vec::new();
for i in &members {
@@ -195,10 +193,7 @@ fn boundaries(curves: &[LCurve], pts: &[Vec2]) -> Option<Vec<Boundary>> {
}
}
}
for p in candidates {
lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y));
hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y));
}
bounds.extend(candidates);
signature[match curves.get(*i)? {
LCurve::Line(..) => 0,
LCurve::Arc(..) => 1,
@@ -206,9 +201,9 @@ fn boundaries(curves: &[LCurve], pts: &[Vec2]) -> Option<Vec<Boundary>> {
}] += 1;
bound_shapes.push(shape);
}
out.push(Boundary { curves: members, shapes: bound_shapes, lo, hi, depth: 0, signature });
out.push(Boundary { curves: members, shapes: bound_shapes, bounds, depth: 0, signature });
}
let scale = out.iter().map(|b| (b.hi - b.lo).len()).fold(1.0, f64::max);
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() {
@@ -260,27 +255,20 @@ fn boundaries(curves: &[LCurve], pts: &[Vec2]) -> Option<Vec<Boundary>> {
pub(super) fn valid(curves: &[LCurve], points: &[Vec2]) -> bool {
boundaries(curves, points).is_some()
}
fn normalize(p: Vec2, lo: Vec2, hi: Vec2) -> Vec2 {
Vec2::new((p.x - lo.x) / (hi.x - lo.x).max(1e-9), (p.y - lo.y) / (hi.y - lo.y).max(1e-9))
}
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((Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), x| {
(Vec2::new(lo.x.min(x.lo.x), lo.y.min(x.lo.y)), Vec2::new(hi.x.max(x.hi.x), hi.y.max(x.hi.y)))
})
};
let ((alo, ahi), (blo, bhi)) = (bounds(&previous), bounds(&incoming));
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, normalize((x.lo + x.hi) * 0.5, alo, ahi).dist(normalize((y.lo + y.hi) * 0.5, blo, bhi))))
.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()?;
@@ -290,8 +278,8 @@ pub(super) fn roles(old_curves: &[LCurve], a: &[Vec2], fresh_curves: &[LCurve],
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 = normalize(x.hi, alo, ahi) - normalize(x.lo, alo, ahi);
let new_size = normalize(y.hi, blo, bhi) - normalize(y.lo, blo, bhi);
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;
}
@@ -306,7 +294,7 @@ pub(super) fn roles(old_curves: &[LCurve], a: &[Vec2], fresh_curves: &[LCurve],
for p in curve_points(curves.get(*curve)?) {
if !roles.get(p)?.contains(&target) {
roles.get_mut(p)?.push(target);
*coordinates.get_mut(p)? += normalize(*pts.get(p)?, loop_.lo, loop_.hi);
*coordinates.get_mut(p)? += loop_.bounds.relative(*pts.get(p)?);
}
}
}
@@ -325,7 +313,7 @@ pub(super) fn roles(old_curves: &[LCurve], a: &[Vec2], fresh_curves: &[LCurve],
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_.hi - loop_.lo;
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)?;
+3 -14
View File
@@ -1,5 +1,5 @@
use serde::{Deserialize, Serialize};
use solidcraft_geom::{Seg2, Vec2, Vec3};
use solidcraft_geom::{Aabb2, Seg2, Vec2, Vec3};
use crate::union_find::{find, union};
@@ -1594,18 +1594,7 @@ impl Sketch {
/// Axis-aligned bounds of all geometry (for views).
pub fn bounds(&self) -> Option<(Vec2, Vec2)> {
let mut lo = Vec2::new(f64::INFINITY, f64::INFINITY);
let mut hi = Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY);
let mut any = false;
for i in 0..self.curves.len() {
for s in self.segs(i) {
for p in s.polyline(0.5) {
lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y));
hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y));
any = true;
}
}
}
any.then_some((lo, hi))
let b: Aabb2 = (0..self.curves.len()).flat_map(|i| self.segs(i)).flat_map(|s| s.polyline(0.5)).collect();
(!b.is_empty()).then_some((b.min, b.max))
}
}
+21 -46
View File
@@ -10,7 +10,7 @@
use std::f64::consts::TAU;
use serde::{Deserialize, Serialize};
use solidcraft_geom::{Loop2, Region2, Seg2, Vec2};
use solidcraft_geom::{Loop2, Region2, Ring, Seg2, Vec2};
use crate::model::{CurveKind, Sketch};
use crate::shape::{Shape, intersections_within};
@@ -423,12 +423,9 @@ struct Grid {
}
impl Grid {
fn new(boxes: &[(Vec2, Vec2)]) -> Grid {
let (mut lo, mut hi) = (Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY));
for (a, b) in boxes {
lo = Vec2::new(lo.x.min(a.x), lo.y.min(a.y));
hi = Vec2::new(hi.x.max(b.x), hi.y.max(b.y));
}
fn new(boxes: &[solidcraft_geom::Aabb2]) -> Grid {
let all = boxes.iter().fold(solidcraft_geom::Aabb2::EMPTY, |a, b| a.union(b));
let (lo, hi) = (all.min, all.max);
if !(lo.is_finite() && hi.is_finite()) {
return Grid { lo: Vec2::ZERO, size: 1.0 };
}
@@ -440,8 +437,8 @@ impl Grid {
(((p.x - self.lo.x) / self.size).floor() as i64, ((p.y - self.lo.y) / self.size).floor() as i64)
}
/// Cells a box covers; None for boxes spanning too many (they are checked against all).
fn cells(&self, b: &(Vec2, Vec2)) -> Option<Vec<(i64, i64)>> {
let (c0, c1) = (self.cell(b.0), self.cell(b.1));
fn cells(&self, b: &solidcraft_geom::Aabb2) -> Option<Vec<(i64, i64)>> {
let (c0, c1) = (self.cell(b.min), self.cell(b.max));
if (c1.0 - c0.0 + 1).saturating_mul(c1.1 - c0.1 + 1) > 2048 {
return None;
}
@@ -497,27 +494,9 @@ pub fn without_text_counters(sk: &Sketch, profiles: Vec<Profile>) -> Vec<Profile
return profiles;
}
// Outer polylines and their boxes, once.
let polys: Vec<Vec<Vec2>> = profiles.iter().map(|p| p.region.outer.polyline(1e-3)).collect();
let boxes: Vec<(Vec2, Vec2)> = polys
.iter()
.map(|pl| {
pl.iter().fold((Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), p| {
(Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y)))
})
})
.collect();
let polys: Vec<Ring<Vec2>> = profiles.iter().map(|p| p.region.outer.polyline(1e-3)).collect();
let boxes: Vec<solidcraft_geom::Aabb2> = polys.iter().map(|pl| pl.bounds()).collect();
let areas: Vec<f64> = profiles.iter().map(|p| p.region.outer.signed_area().abs()).collect();
let inside = |pl: &[Vec2], p: Vec2| {
let n = pl.len();
let mut odd = false;
for i in 0..n {
let (Some(a), Some(b)) = (pl.get(i), pl.get((i + 1) % n)) else { continue };
if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) {
odd = !odd;
}
}
odd
};
let keep: Vec<bool> = (0..profiles.len())
.map(|i| {
if !text_only.get(i).copied().unwrap_or(false) {
@@ -530,8 +509,8 @@ pub fn without_text_counters(sk: &Sketch, profiles: Vec<Profile>) -> Vec<Profile
j != i
&& text_only.get(j).copied().unwrap_or(false)
&& areas.get(j).copied().unwrap_or(0.0) > ai
&& boxes.get(j).is_some_and(|(lo, hi)| probe.x >= lo.x && probe.x <= hi.x && probe.y >= lo.y && probe.y <= hi.y)
&& polys.get(j).is_some_and(|pl| inside(pl, probe))
&& boxes.get(j).is_some_and(|b| b.contains(probe))
&& polys.get(j).is_some_and(|pl| pl.contains(probe))
})
.count();
depth % 2 == 0
@@ -627,15 +606,19 @@ fn find_profiles_bounded(sk: &Sketch, max_edges: usize) -> Vec<Profile> {
}
}
// Bounding boxes, and a uniform grid over them: only shapes sharing a cell can meet.
let boxes: Vec<(Vec2, Vec2)> = shapes
let boxes: Vec<solidcraft_geom::Aabb2> = shapes
.iter()
.map(|(_, sh)| match *sh {
Shape::Line { a, b } => (Vec2::new(a.x.min(b.x) - tol, a.y.min(b.y) - tol), Vec2::new(a.x.max(b.x) + tol, a.y.max(b.y) + tol)),
Shape::Round { c, r, .. } => (Vec2::new(c.x - r - tol, c.y - r - tol), Vec2::new(c.x + r + tol, c.y + r + tol)),
Shape::Line { a, b } => {
solidcraft_geom::Aabb2 { min: Vec2::new(a.x.min(b.x), a.y.min(b.y)), max: Vec2::new(a.x.max(b.x), a.y.max(b.y)) }.inflated(tol)
}
Shape::Round { c, r, .. } => {
solidcraft_geom::Aabb2 { min: Vec2::new(c.x - r - tol, c.y - r - tol), max: Vec2::new(c.x + r + tol, c.y + r + tol) }
}
})
.collect();
let overlap = |i: usize, j: usize| match (boxes.get(i), boxes.get(j)) {
(Some((a0, a1)), Some((b0, b1))) => a0.x <= b1.x && b0.x <= a1.x && a0.y <= b1.y && b0.y <= a1.y,
(Some(a), Some(b)) => a.meets(b),
_ => false,
};
let grid = Grid::new(&boxes);
@@ -711,8 +694,7 @@ fn find_profiles_bounded(sk: &Sketch, max_edges: usize) -> Vec<Profile> {
let mut anchors: Vec<Vec2> = Vec::new();
if shapes.len() <= 50_000 {
let mut whole: Vec<bool> = shapes.iter().map(|(_, s)| s.is_full()).collect();
for i in 0..shapes.len() {
let Some((ci, x)) = shapes.get(i) else { continue };
for (i, (ci, x)) in shapes.iter().enumerate() {
if carrier.get(i) != Some(&i) || !analytic(*ci) {
continue;
}
@@ -1029,15 +1011,8 @@ fn find_profiles_bounded(sk: &Sketch, max_edges: usize) -> Vec<Profile> {
// Nesting: parent = smallest containing loop from another component. Bounding boxes rule
// out most pairs before the point-in-loop test.
let areas: Vec<f64> = loops.iter().map(|(l, _, _, _)| l.signed_area().abs()).collect();
let boxes: Vec<(Vec2, Vec2)> = loops
.iter()
.map(|(l, _, _, _)| {
l.polyline(1e-3).iter().fold((Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), p| {
(Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y)))
})
})
.collect();
let inside_box = |j: usize, p: Vec2| boxes.get(j).is_some_and(|(lo, hi)| p.x >= lo.x && p.x <= hi.x && p.y >= lo.y && p.y <= hi.y);
let boxes: Vec<solidcraft_geom::Aabb2> = loops.iter().map(|(l, _, _, _)| l.polyline(1e-3).bounds()).collect();
let inside_box = |j: usize, p: Vec2| boxes.get(j).is_some_and(|b| b.contains(p));
let mut parent_of: Vec<Option<usize>> = vec![None; loops.len()];
for (i, (li, _, ci, _)) in loops.iter().enumerate() {
let probe = li.segs.first().map(Seg2::mid).unwrap_or_default();
+1 -4
View File
@@ -840,10 +840,7 @@ fn long_connected_chain_solves() {
fn exact_profiles_for_high_degree_and_cut_free_form_curves() {
use solidcraft_geom::Seg2;
let exact_loop = |p: &Profile| p.region.outer.segs.iter().all(|s| !matches!(s, Seg2::Line { .. }) || s.length() > 1.0);
let closed = |p: &Profile| {
let s = &p.region.outer.segs;
s.iter().zip(s.iter().cycle().skip(1)).all(|(a, b)| a.end().dist(b.start()) < 1e-9)
};
let closed = |p: &Profile| p.region.outer.joints().all(|(a, b)| a.end().dist(b.start()) < 1e-9);
// Degree 5 over six points, closed by a line.
let mut sk = Sketch::default();
let ids: Vec<usize> = [v(0.0, 0.0), v(4.0, 10.0), v(10.0, 12.0), v(16.0, 12.0), v(22.0, 10.0), v(26.0, 0.0)]
+2 -3
View File
@@ -7,7 +7,7 @@
//! ATTRIBUTION.md); [`crate::fonts`] finds others by file path or installed family name.
use serde::{Deserialize, Serialize};
use solidcraft_geom::Vec2;
use solidcraft_geom::{Ring, Vec2};
use crate::fonts::font_data_styled;
use crate::link::{LinkGeom, LinkKind, LinkSource, MAX_LINK_ENTITIES};
@@ -303,8 +303,7 @@ impl Path {
let closed = first.dist(last) <= 1e-9 * length.max(1.0);
let readable = if closed {
// Clockwise: the text stands on the outside.
let area: f64 = pts.iter().zip(pts.iter().skip(1)).map(|(a, b)| a.cross(*b)).sum::<f64>() + last.cross(first);
area <= 0.0
Ring::from(pts.clone()).signed_area() <= 0.0
} else {
last.x >= first.x - 1e-9 * length
};
+5 -6
View File
@@ -7,7 +7,7 @@
use std::cell::RefCell;
use egui::{Color32, Pos2, Rect, Sense, Shape, Stroke, vec2};
use solidcraft_engine::geom::Vec3;
use solidcraft_engine::geom::{Ring, Vec3};
use crate::theme::Tokens;
use crate::viewport::{Proj, projected_polygon};
@@ -121,13 +121,12 @@ fn seg_dist(p: Pos2, a: Pos2, b: Pos2) -> f32 {
(a + ab * t).distance(p)
}
fn in_quad(p: Pos2, q: &[Pos2]) -> bool {
fn in_quad(p: Pos2, q: &Ring<Pos2>) -> bool {
if q.len() < 3 {
return false;
}
let mut sign = 0.0f32;
for i in 0..q.len() {
let (a, b) = (q[i], q[(i + 1) % q.len()]);
for (&a, &b) in q.edges() {
let c = (b - a).x * (p - a).y - (b - a).y * (p - a).x;
if c.abs() < 1e-6 {
continue;
@@ -166,7 +165,7 @@ fn along(proj: &Proj, pos: Pos2, o: Vec3, d: Vec3) -> Option<f64> {
/// The triad's shapes: (handle, screen polygon or polyline, is it a filled area).
struct Shapes {
arrows: Vec<(usize, Pos2, Pos2)>,
planes: Vec<(usize, Vec<Pos2>)>,
planes: Vec<(usize, Ring<Pos2>)>,
rings: Vec<(usize, Vec<Pos2>)>,
ball: Pos2,
}
@@ -183,7 +182,7 @@ fn shapes(proj: &Proj, t: &Triad, l: f64) -> Option<Shapes> {
}
for i in 0..3 {
let (e1, e2) = ring_basis(i);
let q: Vec<Pos2> = [(0.25, 0.25), (0.45, 0.25), (0.45, 0.45), (0.25, 0.45)]
let q: Ring<Pos2> = [(0.25, 0.25), (0.45, 0.25), (0.45, 0.45), (0.25, 0.45)]
.iter()
.filter_map(|(a, b)| proj.to_screen(c + e1 * (a * l) + e2 * (b * l)))
.collect();
+5 -5
View File
@@ -1,6 +1,7 @@
//! Original, code-drawn navigation cube. Flat faces share invisible picking regions.
use super::*;
use crate::icons::navigation::{Facet, arrow, curved_arrow, paint_cube};
use solidcraft_engine::geom::Ring;
pub(super) const SIZE: f32 = 112.0;
// Paint and picking use the same original coordinate space, scaled as a group.
@@ -49,10 +50,9 @@ fn facets(cam: &Camera, c: Pos2, half: f64) -> Vec<Facet> {
let b = project(cam, *b - centre, half);
a.y.atan2(a.x).total_cmp(&b.y.atan2(b.x))
});
let vertices = Ring::new(vertices);
let outer_edges = vertices
.iter()
.zip(vertices.iter().cycle().skip(1))
.take(vertices.len())
.edges()
.map(|(a, b)| [(a.x, b.x), (a.y, b.y), (a.z, b.z)].into_iter().filter(|(a, b)| a.abs() == 1.0 && a == b).count() >= 2)
.collect();
let points = vertices.into_iter().map(|v| c + project(cam, v, half)).collect();
@@ -92,12 +92,12 @@ fn facets(cam: &Camera, c: Pos2, half: f64) -> Vec<Facet> {
out
}
fn contains(points: &[Pos2], p: Pos2) -> bool {
fn contains(points: &Ring<Pos2>, p: Pos2) -> bool {
if !p.is_finite() || points.len() < 3 {
return false;
}
let mut sign = 0.0_f32;
for (a, b) in points.iter().zip(points.iter().cycle().skip(1)).take(points.len()) {
for (a, b) in points.edges() {
let edge = *b - *a;
let offset = p - *a;
let cross = edge.x * offset.y - edge.y * offset.x;
+2 -2
View File
@@ -15,7 +15,7 @@ use std::sync::mpsc::{Receiver, TryRecvError};
use serde_json::Value;
use solidcraft_engine::Session;
use solidcraft_engine::doc::ModelState;
use solidcraft_engine::geom::{Aabb3, Mesh, Vec3};
use solidcraft_engine::geom::{Aabb3, Mesh, Ring, Vec3};
use crate::SolveApp;
use crate::gpu::{GpuScene, SceneSlot};
@@ -560,7 +560,7 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built {
sc.xray_tri(p.to_f32(), plane.normal().to_f32(), color);
}
}
for (a, b) in quad.iter().zip(quad.iter().cycle().skip(1)).take(4) {
for (a, b) in Ring::from(quad).edges() {
sc.line(a.to_f32(), b.to_f32(), c.added, 1.3, true);
}
}