From 061ecd1cd67e0f23dceeaffe3e4f143e82bf2666 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:31:38 +0700 Subject: [PATCH] TRIM: a pick on a cut trims nothing; vertices in line don't cut Measured in AutoCAD 2024 (accoreconsole) and followed here: - A pick within 5e-7 of a cut along the polyline trims nothing, at any size; this replaces picking a side by cut index. - An edge through a closed polyline's start vertex cuts it there. - A closed polyline cut at one point is refused ("Curve must intersect cutting edges at least twice."); Quick mode leaves it in place. - A vertex between two line segments within 1e-8 of parallel, straight on or doubling back, is not a cut. - Crossing picks stay just inside a segment, off its vertices. A polyline's own crossings are searched only on the segment picked and those it runs straight on into, against the segments near them; past 2^24 pairs or 65,536 crossings the trim is refused instead of being made at some of its cuts. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify.rs | 2 +- crates/engine/src/cmd/modify/trim.rs | 194 ++++++++----- crates/engine/src/cmd/trimextend.rs | 13 +- .../tests/it/break_trim_polyline_rules.rs | 268 ++++++++++++++++-- .../engine/tests/it/trim_closed_polyline.rs | 10 +- 5 files changed, 373 insertions(+), 114 deletions(-) diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 02a9ab770..8270f5111 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -34,7 +34,7 @@ use select_then::{DisplaceM, Op, SelectThen}; use stretch::{StretchM, run_stretch}; pub(crate) use transform::transform_entities; use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale}; -pub(crate) use trim::{Edges, extend, trim}; +pub(crate) use trim::{CUT_ONCE, Edges, extend, trim}; pub fn specs() -> Vec { vec![ diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index e5bef9b8e..b8ec3965d 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -1,3 +1,5 @@ +use cadcraft_geom::Bounds2; + use super::{ Arc, EngineError, Entity, EntityKind, Handle, Line, PolyVertex, Polyline, Prim, Result, Segment, Session, TAU, Vec2, angle_in_sweep, arc, ccw_sweep, intersect_ext, line, lwpoly, norm_angle, @@ -171,7 +173,10 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu } keep.into_iter().collect() } - EntityKind::LwPolyline(p) => trim_polyline(p, &cut, pick, itself)?, + EntityKind::LwPolyline(p) => match trim_polyline(p, &cut, pick, itself)? { + Some(pieces) => pieces, + None => return Ok(vec![h]), + }, k => crate::cmd::modify2::trim_other(k, &cut, pick)?, }; replace_with_pieces(s, h, pieces) @@ -275,71 +280,122 @@ pub(super) fn sub_polyline(segs: &[Segment], a: f64, b: f64) -> Vec out } -/// Upper bounds on the segments of a polyline searched for crossings with itself (the pairs grow -/// with the square) and on the crossings kept (hostile files); a longer polyline still cuts itself -/// at its vertices. -const MAX_SELF_CROSSING_SEGMENTS: usize = 2048; -const MAX_SELF_CROSSINGS: usize = 10_000; +/// Two line segments of a polyline within this sine of parallel run on as one, straight on or +/// doubling back: the vertex between them doesn't cut it, and they don't cut each other. AutoCAD +/// 2024 cuts at a bend of 1e-8 and not at one of 8e-9, whatever the lengths. +const STRAIGHT: f64 = 1e-8; -/// Where a polyline cuts itself, as lengths along it: the vertices between its segments (every -/// vertex of a closed one, its start included), the points where two of its segments cross, and -/// those where a vertex of it (an end included) touches another of its segments. AutoCAD 2024 -/// trims a polyline that is one of the cutting edges at these. -fn self_cuts(segs: &[Segment], closed: bool) -> Vec { - let mut starts = Vec::with_capacity(segs.len()); +/// Upper bounds on one trim's search for where a polyline crosses itself (hostile files): the pairs +/// of segments searched (those the piece picked can reach, times those near them) and the +/// crossings found. Past either the trim is refused, rather than made at some of its cuts. +const MAX_SELF_PAIRS: usize = 1 << 24; +const MAX_SELF_CROSSINGS: usize = 1 << 16; + +/// How near a cut a pick is on it, along the object: AutoCAD 2024 trims nothing for a pick within +/// 5e-7 of a cut on an open polyline and trims for one 5.1e-7 away, from 1e-3 to 1e9 long (around +/// a closed rectangle it reached a little further, to 1e-6). +const ON_CUT: f64 = 5e-7; + +/// AutoCAD 2024's refusal to trim a closed polyline cut at one point only. +pub(crate) const CUT_ONCE: &str = "Curve must intersect cutting edges at least twice."; + +/// Whether segments `a` and `b` of a polyline run on as one ([`STRAIGHT`]). +fn runs_on(a: &Segment, b: &Segment) -> bool { + let (Segment::Line(a), Segment::Line(b)) = (a, b) else { return false }; + let (u, v) = (a.b - a.a, b.b - b.a); + u.cross(v).abs() < STRAIGHT * u.len() * v.len() +} + +/// Where a polyline that is one of the cutting edges cuts itself around segment `k`, the one +/// picked, as lengths along it: at its vertices (every vertex of a closed one, its start included) +/// but those it runs straight on through ([`runs_on`]), and, on `k` and the segments it runs +/// straight on into, where another of its segments crosses them or a vertex of it (an end +/// included) touches them. The piece picked lies within those segments, so crossings elsewhere +/// don't bound it. AutoCAD 2024 trims a polyline that is one of the cutting edges at these. +fn self_cuts(segs: &[Segment], closed: bool, k: usize) -> Result> { + let n = segs.len(); + let mut starts = Vec::with_capacity(n); let mut acc = 0.0; for s in segs { starts.push(acc); acc += s.len(); } - let mut ts: Vec = starts.iter().copied().skip(usize::from(!closed)).collect(); - if segs.len() > MAX_SELF_CROSSING_SEGMENTS { - return ts; + let before = |i: usize| { + if i > 0 { + Some(i - 1) + } else if closed { + n.checked_sub(1) + } else { + None + } + }; + let after = |i: usize| { + if i + 1 < n { + Some(i + 1) + } else if closed { + Some(0) + } else { + None + } + }; + // Whether the polyline runs straight on through the vertex segment `i` starts at. + let straight = |i: usize| matches!((before(i).and_then(|j| segs.get(j)), segs.get(i)), (Some(a), Some(b)) if runs_on(a, b)); + let mut ts: Vec = (usize::from(!closed)..n).filter(|i| !straight(*i)).filter_map(|i| starts.get(i).copied()).collect(); + let mut run = vec![k]; + let mut i = k; + while let Some(j) = before(i).filter(|_| straight(i) && run.len() < n) { + run.push(j); + i = j; } - let inside = |t: f64| t > 1e-9 && t < 1.0 - 1e-9; - let parts: Vec<_> = segs.iter().zip(starts).map(|(s, t0)| (s, s.bounds(), t0)).collect(); - let mut crossings = 0; - for (i, (a, box_a, a0)) in parts.iter().enumerate() { - for (b, box_b, b0) in parts.iter().skip(i + 1) { - if !box_a.intersects(box_b) { + let mut i = k; + while let Some(j) = after(i).filter(|j| straight(*j) && run.len() < n) { + run.push(j); + i = j; + } + let boxes: Vec<_> = segs.iter().map(Segment::bounds).collect(); + let reach = run.iter().filter_map(|i| boxes.get(*i)).fold(Bounds2::EMPTY, |r, b| r.union(b)); + let near: Vec = (0..n).filter(|j| boxes.get(*j).is_some_and(|b| b.intersects(&reach))).collect(); + if run.len().saturating_mul(near.len()) > MAX_SELF_PAIRS { + return Err(EngineError::Other("Too many segments to trim the polyline where it crosses itself.".into())); + } + // A crossing, or a vertex of another segment touching this one, cuts it; so does a crossing + // where it runs straight on into the next. Two segments meeting at a vertex cut nothing more. + let cuts = |t: f64, i: usize| (t > 1e-9 && t < 1.0 - 1e-9) || (t <= 1e-9 && straight(i)) || (t >= 1.0 - 1e-9 && after(i).is_some_and(straight)); + let vertices = ts.len(); + for &i in &run { + let (Some(a), Some(box_a), Some(a0)) = (segs.get(i), boxes.get(i), starts.get(i)) else { continue }; + for &j in &near { + let (Some(b), Some(box_b)) = (segs.get(j), boxes.get(j)) else { continue }; + if j == i || runs_on(a, b) || !box_a.intersects(box_b) { continue; } for x in intersect_ext(a, b, false) { - let (ta, tb) = (param_on(a, x), param_on(b, x)); - // A crossing cuts both segments; a vertex touching the other segment cuts that - // one (the vertex is a cut already). Two segments meeting at a vertex cut nothing - // more. - if inside(ta) || inside(tb) { - if inside(ta) { - ts.push(a0 + ta * a.len()); - } - if inside(tb) { - ts.push(b0 + tb * b.len()); - } - crossings += 1; - if crossings >= MAX_SELF_CROSSINGS { - return ts; + let t = param_on(a, x); + if cuts(t, i) { + ts.push(a0 + t * a.len()); + if ts.len() - vertices > MAX_SELF_CROSSINGS { + return Err(EngineError::Other("Too many crossings to trim the polyline where it crosses itself.".into())); } } } } } - ts + Ok(ts) } /// Trim a polyline at the piece containing `pick`, between the cuts by `cut` and, when it is one -/// of the cutting edges (`itself`), by its own vertices and crossings ([`self_cuts`]). -fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itself: bool) -> Result> { +/// of the cutting edges (`itself`), by its own ([`self_cuts`]). `None`: the pick is on a cut +/// ([`ON_CUT`]), which trims nothing. +fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itself: bool) -> Result>> { let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed }; let segs = pl.segments(); let total: f64 = segs.iter().map(Segment::len).sum(); let mut ts: Vec = Vec::new(); let mut acc = 0.0; - let mut tp = 0.0; - // The pick is at the start of the segment it was found on (1), at its end (-1), or between. - let mut at_end = 0.0; + // The pick's length along the polyline and the segment it is on. + let (mut tp, mut k) = (0.0, 0); let mut best = f64::INFINITY; - for s in &segs { + for (i, s) in segs.iter().enumerate() { let len = s.len(); for x in cut.iter().flat_map(|c| intersect_ext(s, c, false)) { ts.push(acc + param_on(s, x) * len); @@ -347,42 +403,34 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse let c = s.closest(pick); if c.dist(pick) < best { best = c.dist(pick); - let u = param_on(s, c); - tp = acc + u * len; - at_end = if u >= 1.0 - 1e-12 { - -1.0 - } else if u <= 1e-12 { - 1.0 - } else { - 0.0 - }; + tp = acc + param_on(s, c) * len; + k = i; } acc += len; } - ts.retain(|t| *t > 1e-9 && *t < total - 1e-9); if itself { - // A closed polyline also cuts itself at its start vertex. - ts.extend(self_cuts(&segs, p.closed).into_iter().filter(|t| (*t > 1e-9 || p.closed) && *t < total - 1e-9)); + ts.extend(self_cuts(&segs, p.closed, k)?); + } + // An open polyline's ends cut nothing; a closed one's start vertex cuts it like any other (a + // cut there is at 0 or at its length, which the pieces below take as one). + if !p.closed { + ts.retain(|t| *t > 1e-9 && *t < total - 1e-9); } ts.sort_by(f64::total_cmp); if ts.is_empty() { return Err(EngineError::Other("Object does not intersect a cutting edge.".into())); } - // A pick on a cut (a vertex picked exactly: the same length within rounding) takes the piece - // of the segment it was found on, rather than neither piece (which would erase the whole - // polyline): from that cut to the next when the pick is at its segment's start, from the one - // before to that cut otherwise. A pick off every cut takes the piece between the cuts either - // side of it. - let on = 4.0 * f64::EPSILON * (total + 1.0); - let on_cut = ts.iter().enumerate().map(|(i, t)| (i, (t - tp).abs())).filter(|(_, d)| *d <= on).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i); - let (lo, hi) = match on_cut { - Some(i) if at_end > 0.0 => (ts.get(i).copied().unwrap_or(f64::NEG_INFINITY), ts.get(i + 1).copied().unwrap_or(f64::INFINITY)), - Some(i) => (i.checked_sub(1).and_then(|j| ts.get(j)).copied().unwrap_or(f64::NEG_INFINITY), ts.get(i).copied().unwrap_or(f64::INFINITY)), - None => ( - ts.iter().copied().filter(|t| *t < tp).fold(f64::NEG_INFINITY, f64::max), - ts.iter().copied().filter(|t| *t > tp).fold(f64::INFINITY, f64::min), - ), - }; + // How far apart two lengths along the polyline are, round its start too when it is closed. + let apart = |s: f64, t: f64| if p.closed { (s - t).abs().min(total - (s - t).abs()) } else { (s - t).abs() }; + if p.closed && ts.first().is_some_and(|f| ts.iter().all(|t| apart(*f, *t) <= ON_CUT)) { + return Err(EngineError::Other(CUT_ONCE.into())); + } + // A pick on a cut trims nothing. + if ts.iter().any(|t| apart(*t, tp) <= ON_CUT) { + return Ok(None); + } + let lo = ts.iter().copied().filter(|t| *t < tp).fold(f64::NEG_INFINITY, f64::max); + let hi = ts.iter().copied().filter(|t| *t > tp).fold(f64::INFINITY, f64::min); let mk = |vs: Vec| lwpoly(vs, false); let mut out = Vec::new(); if p.closed { @@ -394,11 +442,7 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse if hi.is_finite() { hi } else { ts.first().copied().unwrap_or(total) + total }, ); let doubled: Vec = segs.iter().chain(segs.iter()).copied().collect(); - let (a, mut b) = if hi > total { (hi - total, lo) } else { (hi, lo + total) }; - // A single cut leaves the whole outline, opened there. - if b <= a + 1e-9 { - b += total; - } + let (a, b) = if hi > total { (hi - total, lo) } else { (hi, lo + total) }; out.push(mk(sub_polyline(&doubled, a, b))); } else { // A piece whose ends meet (the polyline touched itself there) is closed, without its @@ -419,7 +463,7 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse out.push(piece(sub_polyline(&segs, hi, total))); } } - Ok(out.into_iter().filter(|k| matches!(k, EntityKind::LwPolyline(l) if l.vertices.len() >= 2)).collect()) + Ok(Some(out.into_iter().filter(|k| matches!(k, EntityKind::LwPolyline(l) if l.vertices.len() >= 2)).collect())) } pub(super) fn param_on(s: &Segment, p: Vec2) -> f64 { diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index 7b061cd78..8b655765b 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -9,7 +9,7 @@ use cadcraft_geom::{Bounds2, Line, Vec2, line_line}; use serde_json::{Value, json}; use super::helpers::{line, lwpoly, rect_vertices}; -use super::modify::{Edges, extend, trim}; +use super::modify::{CUT_ONCE, Edges, extend, trim}; use super::{bad, point_param, points_param}; use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; @@ -31,8 +31,10 @@ fn proj_mode(s: &Session) -> i64 { } /// Whether a trim error says the object meets no cutting edge (a Quick-mode trim then erases it). +/// A closed polyline cut at one point meets one, and is left as it is. fn misses_edges(e: &EngineError) -> bool { - e.to_string().contains("intersect") + let m = e.to_string(); + m.contains("intersect") && m != CUT_ONCE } /// Trim or extend `h` at `at`. A Quick-mode (`quick`) trim of an object no cutting edge crosses @@ -103,7 +105,12 @@ fn crossing(s: &mut Session, a: Vec2, b: Vec2, extending: bool, edges: Edges, qu for w in pl.windows(2) { let (Some(p), Some(q)) = (w.first(), w.get(1)) else { continue }; let seg = Line::new(*p, *q); - let cands = [*p, *q, seg.closest(a)].into_iter().chain(sides.iter().filter_map(|sd| line_line(sd, &seg))); + // Kept `tol` inside the segment: a vertex, where two segments meet, is a cut of a + // polyline that is one of its own edges, and a pick on a cut trims nothing. + let e = (tol / seg.len()).min(0.5); + let cands = [seg.at(e), seg.at(1.0 - e), seg.at(seg.param_of(a).clamp(e, 1.0 - e))] + .into_iter() + .chain(sides.iter().filter_map(|sd| line_line(sd, &seg))); for c in cands.filter(|c| inside(*c)) { if best.is_none_or(|b| c.dist(a) < b.dist(a)) { best = Some(c); diff --git a/crates/engine/tests/it/break_trim_polyline_rules.rs b/crates/engine/tests/it/break_trim_polyline_rules.rs index 7fe34c08c..41bf5ae88 100644 --- a/crates/engine/tests/it/break_trim_polyline_rules.rs +++ b/crates/engine/tests/it/break_trim_polyline_rules.rs @@ -6,7 +6,10 @@ //! splits it there into two open polylines, and at its start vertex leaves it closed. //! - A polyline that is one of the cutting edges (picked, or with every object, in Standard or //! Quick mode) is also cut at its own vertices, where it crosses itself and where a vertex of it -//! touches another of its segments. A piece whose ends meet there is left closed. +//! touches another of its segments. A piece whose ends meet there is left closed. A vertex +//! between two line segments in line (within 1e-8, straight on or doubling back) doesn't cut it. +//! - A pick within 5e-7 of a cut along the polyline, whatever its size, trims nothing. An edge +//! through a closed polyline's start vertex cuts it there. //! //! Quick mode was measured in AutoCAD 2024 itself, picking on screen: its scripted TRIM runs //! Standard mode only. @@ -313,46 +316,221 @@ fn a_closed_piece_keeps_its_arcs() { } #[test] -fn a_pick_right_on_a_vertex_takes_the_segment_it_ends() { - // Not measured. The vertex (10, 0) is the only cut: the pick takes the segment before it - // instead of erasing the polyline. - let mut s = Session::new(); - let p = pline(&mut s, json!([[0, 0], [10, 0], [10, 10]]), false); - trim(&mut s, p, [10.0, 0.0], None); - expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); -} - -#[test] -fn a_pick_inside_a_segment_stays_on_its_side_of_a_cut() { - // A segment a millionth long between two vertices: a pick in it takes it, not the one before. - let mut s = Session::new(); - let p = pline(&mut s, json!([[0, 0], [10, 0], [10.000001, 0], [10000, 0]]), false); - trim(&mut s, p, [10.0000005, 0.0], None); - expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0)]), (false, false, &[(10.000001, 0.0, 0.0), (10000.0, 0.0, 0.0)])]); - // 1e9 long: half a unit up the second segment is on the second segment. +fn a_pick_half_a_unit_from_a_vertex_1e9_out_trims_the_segment_it_is_on() { let mut s = Session::new(); let p = pline(&mut s, json!([[0, 0], [1e9, 0], [1e9, 10]]), false); trim(&mut s, p, [1e9, 0.5], None); expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (1e9, 0.0, 0.0)])]); } -#[test] -fn a_pick_on_a_vertex_next_to_a_very_short_segment_takes_that_segment() { - // 1e9 out, a segment 5e-7 long, a few roundings of the length, so both its ends are within - // rounding of a pick on the vertex it ends at: that pick takes it, not the long segment before. +// ---------------- a pick on a cut ---------------- + +/// The polyline `v`, with a line from `a` to `b` when given, trimmed at `pick` with every object +/// as an edge, or only the line when `only_line`; returns the polyline's handle. +fn trimmed(v: Value, closed: bool, edge: Option<([f64; 2], [f64; 2])>, only_line: bool, pick: [f64; 2]) -> (Session, Handle) { let mut s = Session::new(); - let p = pline(&mut s, json!([[0, 0], [1e9, 0], [1e9, 5e-7], [1e9, 10]]), false); - trim(&mut s, p, [1e9, 5e-7], None); - expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (1e9, 0.0, 0.0)]), (false, false, &[(1e9, 5e-7, 0.0), (1e9, 10.0, 0.0)])]); + let p = pline(&mut s, v, closed); + let l = edge.map(|(a, b)| line(&mut s, a, b)); + trim(&mut s, p, pick, l.filter(|_| only_line).as_ref().map(std::slice::from_ref)); + (s, p) } #[test] -fn a_pick_on_a_closed_polylines_start_vertex_takes_its_first_segment() { - // Not measured. The pick is at the start of the first segment, which it was found on. - let mut s = Session::new(); - let p = pline(&mut s, json!([[0, 0], [10, 0], [10, 10], [0, 10]]), true); - trim(&mut s, p, [0.0, 0.0], None); - expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, 0.0)])]); +fn a_pick_on_a_cut_trims_nothing() { + // The vertex (10, 0) is the only cut. A pick whose nearest point is within 5e-7 of it, on it + // or off to the side, leaves the polyline as it was; one 6e-7 from it trims the segment it is + // on. + let v = || json!([[0, 0], [10, 0], [10, 10]]); + let whole: [Vertex; 3] = [(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0)]; + for pick in [[10.0, 0.0], [10.0, 4e-7], [10.5, 4e-7], [9.99999999, 0.0]] { + let (s, p) = trimmed(v(), false, None, false, pick); + expect(&s, p, &[(true, false, &whole)]); + } + let (s, p) = trimmed(v(), false, None, false, [10.0, 6e-7]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]); + let (s, p) = trimmed(v(), false, None, false, [9.9999994, 0.0]); + expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); +} + +#[test] +fn a_pick_on_a_cut_is_within_the_same_distance_at_any_size() { + // A polyline a thousandth across, and one 1e9 long with a line through its vertex: 1e-7 from + // the vertex is on the cut, 1e-6 off it. + let small = || json!([[0, 0], [0.001, 0], [0.001, 0.001]]); + let (s, p) = trimmed(small(), false, None, false, [0.001, 1e-7]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (0.001, 0.0, 0.0), (0.001, 0.001, 0.0)])]); + let (s, p) = trimmed(small(), false, None, false, [0.001, 1e-6]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (0.001, 0.0, 0.0)])]); + let long = || json!([[0, 0], [10, 0], [10, 1e9]]); + let through = Some(([0.0, -10.0], [20.0, 10.0])); + let (s, p) = trimmed(long(), false, through, false, [10.0, 1e-7]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 1e9, 0.0)])]); + let (s, p) = trimmed(long(), false, through, false, [10.0, 1e-6]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]); +} + +#[test] +fn a_pick_on_a_cut_by_another_edge_trims_nothing() { + // The line x = 5 is the edge: picks on it and 4e-7 past it leave the polyline as it was, one + // 6e-7 past it trims the rest. + let v = || json!([[0, 0], [10, 0], [10, 10]]); + let edge = Some(([5.0, -5.0], [5.0, 5.0])); + for pick in [[5.0, 0.0], [5.0000004, 0.0]] { + let (s, p) = trimmed(v(), false, edge, true, pick); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); + } + let (s, p) = trimmed(v(), false, edge, true, [5.0000006, 0.0]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (5.0, 0.0, 0.0)])]); +} + +#[test] +fn a_pick_on_a_vertex_an_edge_runs_through_trims_nothing() { + // The line's cut is found on the segments either side of the vertex, a rounding apart: the + // pick on the vertex still leaves the polyline as it was, rather than splitting it there. + let cases = [ + ([[5.5, 1.1], [23.3, 7.7], [30.1, 29.9]], ([23.3, 7.7], [45.7, 2.3])), + ([[5.5, 1.1], [23.3, 7.7], [30.1, 29.9]], ([2.0 * 23.3 - 45.7, 2.0 * 7.7 - 2.3], [45.7, 2.3])), + ([[1.3, 2.7], [37.9, 11.3], [55.1, 48.7]], ([4.5, 43.5], [71.3, -20.9])), + ]; + for (v, edge) in cases { + let (s, p) = trimmed(json!(v), false, Some(edge), true, v[1]); + let whole: Vec = v.iter().map(|q| (q[0], q[1], 0.0)).collect(); + expect(&s, p, &[(true, false, &whole)]); + } +} + +#[test] +fn an_edge_through_a_closed_polylines_start_vertex_cuts_it_there() { + // The line cuts the rectangle at (0, 0) and at (10, 10) on its top. The pick takes the piece + // it is on, whichever vertex the rectangle starts at; 4e-7 from (0, 0) it trims nothing. + let rect = || json!([[0, 0], [100, 0], [100, 10], [0, 10]]); + let edge = Some(([-5.0, -5.0], [15.0, 15.0])); + let left: [Vertex; 3] = [(10.0, 10.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, 0.0)]; + let (s, p) = trimmed(rect(), true, edge, true, [50.0, 0.0]); + expect(&s, p, &[(true, false, &left)]); + let (s, p) = trimmed(json!([[50, 0], [100, 0], [100, 10], [0, 10], [0, 0]]), true, edge, true, [50.0, 10.0]); + expect(&s, p, &[(true, false, &left)]); + let (s, p) = trimmed(rect(), true, edge, true, [0.0, 5.0]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (10.0, 10.0, 0.0)])]); + let whole: [Vertex; 4] = [(0.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (0.0, 10.0, 0.0)]; + let (s, p) = trimmed(rect(), true, edge, true, [0.0, 4e-7]); + expect(&s, p, &[(true, true, &whole)]); + // The rectangle alone, picked on its start vertex, and 4e-7 from it on its last segment. + for pick in [[0.0, 0.0], [0.0, 4e-7]] { + let (s, p) = trimmed(rect(), true, None, false, pick); + expect(&s, p, &[(true, true, &whole)]); + } +} + +#[test] +fn a_closed_polyline_cut_at_one_point_is_left_as_it_was() { + // A line touching the rectangle only at its start vertex, and one crossing its bottom once and + // ending inside: AutoCAD refuses either trim, and Quick mode doesn't erase the rectangle. + for (a, b, pick) in [([-5.0, 5.0], [5.0, -5.0], [50.0, 0.0]), ([50.0, -5.0], [50.0, 5.0], [20.0, 0.0])] { + for mode in ["standard", "quick"] { + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true); + let l = line(&mut s, a, b); + let before = polys(&s); + let r = s.execute("trim", &json!({ "handle": p.hex(), "pick": pick, "edges": [l.hex()], "mode": mode })); + assert!(r.is_err_and(|e| e.to_string() == "Curve must intersect cutting edges at least twice."), "{a:?} {mode}"); + assert_eq!(polys(&s), before, "{a:?} {mode}"); + } + } +} + +// ---------------- where a polyline runs straight on ---------------- + +#[test] +fn a_vertex_the_polyline_runs_straight_on_through_doesnt_cut_it() { + // (5, 0) lies between two segments in line: the pick takes everything back to the cut before + // it, the start of the polyline or the closed polyline's start vertex. + let v = || json!([[0, 0], [5, 0], [10, 0], [10, 10]]); + let (s, p) = trimmed(v(), false, None, false, [7.0, 0.0]); + expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); + let (s, p) = trimmed(v(), true, None, false, [7.0, 0.0]); + expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (0.0, 0.0, 0.0)])]); + // A crossing on the segment in line before the one picked bounds the piece, as does one on the + // segment in line after it, and one right at the vertex in line. + let (s, p) = trimmed(json!([[0, 0], [5, 0], [10, 0], [10, 10], [2, 10], [2, -5]]), false, None, false, [7.0, 0.0]); + expect( + &s, + p, + &[ + (true, false, &[(0.0, 0.0, 0.0), (2.0, 0.0, 0.0)]), + (false, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (2.0, 10.0, 0.0), (2.0, -5.0, 0.0)]), + ], + ); + let (s, p) = trimmed(json!([[0, 0], [5, 0], [10, 0], [10, 10], [8, 10], [8, -5]]), false, None, false, [3.5, 0.0]); + expect(&s, p, &[(true, false, &[(8.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (8.0, 10.0, 0.0), (8.0, -5.0, 0.0)])]); + let at_vertex = || json!([[0, 0], [5, 0], [10, 0], [10, 10], [5, 10], [5, -5]]); + let rest: [Vertex; 4] = [(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (5.0, 10.0, 0.0), (5.0, -5.0, 0.0)]; + let (s, p) = trimmed(at_vertex(), false, None, false, [7.0, 0.0]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (5.0, 0.0, 0.0)]), (false, false, &rest)]); + let (s, p) = trimmed(at_vertex(), false, None, false, [3.0, 0.0]); + expect(&s, p, &[(true, false, &[(5.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (5.0, 10.0, 0.0), (5.0, -5.0, 0.0)])]); + // Straight on, or doubling back over itself: no cut at all. + for (v, pick) in [(json!([[0, 0], [5, 0], [10, 0]]), [7.0, 0.0]), (json!([[0, 0], [10, 0], [5, 0]]), [2.0, 0.0])] { + let mut s = Session::new(); + let p = pline(&mut s, v, false); + let before = polys(&s); + assert!(s.execute("trim", &json!({ "handle": p.hex(), "pick": pick })).is_err()); + assert_eq!(polys(&s), before); + } +} + +#[test] +fn a_bend_of_1e_8_cuts_a_polyline_and_a_smaller_one_doesnt() { + // The bend at (5, 0), as the sine of its angle, whatever the segments' lengths. + for (end, pick, cuts) in [ + ([10.0, 4e-8], [7.0, 0.0], false), + ([10.0, 6e-8], [7.0, 0.0], true), + ([5005.0, 1e-6], [700.0, 0.0], false), + ([5005.0, 0.01], [700.0, 0.0], true), + ] { + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [5, 0], end]), false); + let r = s.execute("trim", &json!({ "handle": p.hex(), "pick": pick })); + assert_eq!((r.is_ok(), polys(&s)[0].2.len()), if cuts { (true, 2) } else { (false, 3) }, "{end:?}"); + } + // Two arcs of one circle, or a line and an arc on from it, cut where they meet. + let q = 0.41421356237309503; + let (s, p) = trimmed(json!([{ "p": [0, 0], "bulge": -q }, { "p": [5, 5], "bulge": -q }, [10, 0]]), false, None, false, [8.5355339, 3.5355339]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, -q), (5.0, 5.0, 0.0)])]); + let (s, p) = trimmed(json!([[0, 0], { "p": [5, 0], "bulge": q }, [10, 5]]), false, None, false, [8.5355339, 1.4644661]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (5.0, 0.0, 0.0)])]); +} + +#[test] +fn a_polyline_of_thousands_of_segments_is_cut_where_it_crosses_itself() { + // 3,003 segments, the last crossing the first at (50, 0): the pick on the first takes it from + // there to the vertex (100, 0), as with a few segments. + let mut v = vec![json!([0, 0]), json!([100, 0]), json!([100, 20])]; + v.extend((1..=3000).map(|i| json!([100.0 - f64::from(i) / 60.0, 20.0 + f64::from(i % 2)]))); + v.push(json!([50, -10])); + let (s, p) = trimmed(json!(v), false, None, false, [75.0, 0.0]); + let got = polys(&s); + assert_eq!(got.len(), 2, "{:?}", got.iter().map(|g| g.2.len()).collect::>()); + assert!(got[0].0 == p && same(&got[0].2, &[(0.0, 0.0, 0.0), (50.0, 0.0, 0.0)]), "{:?}", got[0]); + assert_eq!((got[1].2.len(), got[1].2.first().copied()), (3003, Some((100.0, 0.0, 0.0)))); +} + +#[test] +fn a_polyline_too_long_to_search_for_its_own_crossings_is_left_as_it_was() { + // 4,100 segments in line: the run picked times those near it is past the bound searched. 300 + // segments in line over the same stretch, back and forth, crossed by 300 more: 90,000 + // crossings, past the bound kept. The trim is refused, and Quick mode doesn't erase the + // polyline as one no edge crosses. + let mut back_and_forth: Vec<[f64; 2]> = (0..=300).map(|i| [if i % 2 == 0 { 0.0 } else { 10.0 }, 0.0]).collect(); + back_and_forth.extend((0..300).map(|i| [0.5 + f64::from(i) * 0.03, if i % 2 == 0 { 5.0 } else { -5.0 }])); + for (v, why) in [(json!((0..=4100).map(|i| [i, 0]).collect::>()), "Too many segments"), (json!(back_and_forth), "Too many crossings")] { + let mut s = Session::new(); + let p = pline(&mut s, v, false); + let before = polys(&s); + let r = s.execute("trim", &json!({ "handle": p.hex(), "pick": [0.2, 0], "mode": "quick" })); + assert!(r.is_err_and(|e| e.to_string().contains(why)), "{why}"); + assert_eq!(polys(&s), before); + } } #[test] @@ -392,3 +570,31 @@ fn a_polyline_is_cut_where_a_vertex_of_it_touches_it() { ], ); } + +#[test] +fn a_long_run_in_line_on_a_large_polyline_is_cut_where_it_is_crossed() { + // 1,000 segments in line along y = 0, then 20,002 more, the last crossing the run at x = 500.25: + // only the few segments near the run are searched, and the pick takes it from the crossing to + // the corner (1000, 0). + let mut v: Vec = (0..=1000).map(|i| json!([i, 0])).collect(); + v.push(json!([1000, 200])); + v.extend((1..=20000).map(|i| json!([1000.0 - f64::from(i) * 499.75 / 20000.0, 200.0 + f64::from(i % 2)]))); + v.push(json!([500.25, -10])); + let (s, p) = trimmed(json!(v), false, None, false, [999.5, 0.0]); + let got = polys(&s); + assert_eq!(got.len(), 2, "{:?}", got.iter().map(|g| g.2.len()).collect::>()); + assert!(got[0].0 == p && got[0].2.len() == 502 && got[0].2.last() == Some(&(500.25, 0.0, 0.0)), "{:?}", got[0].2.last()); + assert_eq!((got[1].2.first().copied(), got[1].2.last().copied()), (Some((1000.0, 0.0, 0.0)), Some((500.25, -10.0, 0.0)))); +} + +#[test] +fn a_crossing_window_whose_nearest_point_is_a_vertex_trims_the_segment_it_ends() { + // The window's first corner is nearest the vertex (10, 0), a cut of the polyline: the segment + // before it goes, either way round the window, as in AutoCAD. + for (a, b) in [([10.5, -0.5], [8.0, 2.0]), ([8.0, 2.0], [10.5, -0.5])] { + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [10, 0], [10, 10]]), false); + s.execute("trim", &json!({ "crossing": [a, b], "mode": "standard" })).unwrap(); + expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); + } +} diff --git a/crates/engine/tests/it/trim_closed_polyline.rs b/crates/engine/tests/it/trim_closed_polyline.rs index 921c06242..f3bc38432 100644 --- a/crates/engine/tests/it/trim_closed_polyline.rs +++ b/crates/engine/tests/it/trim_closed_polyline.rs @@ -123,11 +123,13 @@ fn undo_restores_the_closed_polyline() { } #[test] -fn a_single_cut_still_opens_the_outline_there() { +fn a_single_cut_leaves_the_outline_as_it_was() { + // As AutoCAD 2024 does (measured with accoreconsole on a 100 x 10 rectangle cut once on its + // bottom): it refuses, "Curve must intersect cutting edges at least twice." let mut s = Session::new(); let p = handle(s.execute("pline", &json!({ "vertices": square(), "closed": true })).unwrap()); let cutter = handle(s.execute("line", &json!({ "points": [[2, -1], [2, 1]] })).unwrap()); - s.execute("trim", &json!({ "handle": p, "pick": [0, 2], "edges": [cutter] })).unwrap(); - let all = [(2.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 4.0, 0.0), (0.0, 4.0, 0.0), (0.0, 0.0, 0.0), (2.0, 0.0, 0.0)]; - assert_eq!(polys(&s), vec![(false, all.to_vec())]); + let r = s.execute("trim", &json!({ "handle": p, "pick": [0, 2], "edges": [cutter] })); + assert!(r.is_err_and(|e| e.to_string() == "Curve must intersect cutting edges at least twice.")); + assert_eq!(polys(&s), vec![(true, vec![(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 4.0, 0.0), (0.0, 4.0, 0.0)])]); }