mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-19 20:30:42 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
198c36b406 | ||
|
|
2101a81d62 | ||
|
|
2827ccb6c8 | ||
|
|
8ec1e9a0a5 | ||
|
|
b184454275 | ||
|
|
077c054d18 | ||
|
|
5eafcc93bb | ||
|
|
7c366f7b5a | ||
|
|
a39d637814 | ||
|
|
dc7e5cdd6e | ||
|
|
e4f9b6aae3 | ||
|
|
140437e78e | ||
|
|
528e2698fe | ||
|
|
764204540a | ||
|
|
a516ce11eb | ||
|
|
03baa73ae5 | ||
|
|
797c5df792 | ||
|
|
736f56d320 | ||
|
|
a9b93676a4 | ||
|
|
19fc1f20be | ||
|
|
31866fcf05 | ||
|
|
ed8555875a | ||
|
|
6f862d7b4b | ||
|
|
b1a34dc0ef | ||
|
|
f24da7a85b | ||
|
|
6a240a7076 | ||
|
|
f903621540 | ||
|
|
063cbef279 | ||
|
|
51f38b4eda | ||
|
|
348d767b93 | ||
|
|
82779b50d0 | ||
|
|
09d2e06862 | ||
|
|
16e0fa5293 | ||
|
|
f13a1f2e39 | ||
|
|
44b0399aa6 | ||
|
|
bb91014ebd | ||
|
|
b439879181 | ||
|
|
5154f5757b | ||
|
|
661e5e2dd9 | ||
|
|
225407ca61 | ||
|
|
01c003e407 | ||
|
|
50644fb0c4 | ||
|
|
23c55fc1a8 | ||
|
|
1a1d8404b6 | ||
|
|
f998f2f663 | ||
|
|
f91d5ad38f | ||
|
|
aaaf654872 | ||
|
|
cfc4fc5e88 | ||
|
|
bcac20dd5f |
+76
-9
@@ -44,6 +44,11 @@ pub use store::EntityStore;
|
||||
pub use tables::*;
|
||||
pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES};
|
||||
|
||||
/// Handles at or above this are not followed: a file may name one (an object's handle, or its
|
||||
/// `$HANDSEED`), and the four billion handles above the limit stay free for the drawing's own
|
||||
/// growth. A file's handles keep their identity, however high they are (#913, #939).
|
||||
pub const HANDLE_LIMIT: u64 = u64::MAX - 0xFFFF_FFFF;
|
||||
|
||||
/// File data CADCraft doesn't model, kept for saving (#528).
|
||||
pub mod dynblock;
|
||||
pub mod foreign;
|
||||
@@ -127,6 +132,10 @@ pub struct Drawing {
|
||||
pub scales: Vec<AnnoScale>,
|
||||
/// Next free handle.
|
||||
pub handseed: u64,
|
||||
/// Handles a file's records hold in the reserved band, recorded while reading before the
|
||||
/// record is placed: [`Drawing::new_handle`] skips them meanwhile. [`Drawing::bump_handseed`]
|
||||
/// does not follow them (#913). Emptied once the file is read; never written to a file.
|
||||
pub reserved_handles: BTreeSet<u64>,
|
||||
/// Objects hidden for this session by ISOLATEOBJECTS / HIDEOBJECTS. Never written to a file:
|
||||
/// a drawing opens with everything shown again.
|
||||
pub hidden_objects: BTreeSet<Handle>,
|
||||
@@ -200,6 +209,7 @@ impl Drawing {
|
||||
parametric: Parametric::default(),
|
||||
scales: imperial_scales(),
|
||||
handseed: 0x100,
|
||||
reserved_handles: BTreeSet::new(),
|
||||
hidden_objects: BTreeSet::new(),
|
||||
read_notes: Vec::new(),
|
||||
refedit: None,
|
||||
@@ -209,26 +219,83 @@ impl Drawing {
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocate a fresh handle. It skips the handles the drawing's file gave the objects CADCraft
|
||||
/// writes itself ([`foreign::Foreign::handles`]): AutoLISP names those objects by them, and a
|
||||
/// file CADCraft wrote numbers them above its `$HANDSEED` (#495).
|
||||
/// Allocate a fresh handle: [`Drawing::next_handle`], with the seed moved past it. Past the
|
||||
/// top of the range the drawing goes on growing in the reserved band (#913).
|
||||
pub fn new_handle(&mut self) -> Handle {
|
||||
let h = self.next_handle();
|
||||
self.handseed = h.0.saturating_add(1);
|
||||
self.handseed = h.0.checked_add(1).unwrap_or(HANDLE_LIMIT);
|
||||
h
|
||||
}
|
||||
/// The handle [`Drawing::new_handle`] gives out next (AutoCAD's `HANDSEED`), without taking it.
|
||||
/// The handle [`Drawing::new_handle`] gives out next (AutoCAD's `HANDSEED`), without taking it:
|
||||
/// the first one at or above the seed that nothing holds. It skips
|
||||
/// - the handles the drawing's file gave the objects CADCraft writes itself
|
||||
/// ([`foreign::Foreign::handles`]): AutoLISP names those objects by them, and a file
|
||||
/// CADCraft wrote numbers them above its `$HANDSEED` (#495);
|
||||
/// - handles an object or a file record being read holds in the reserved band above
|
||||
/// [`HANDLE_LIMIT`]. A hostile or damaged file may name a `$HANDSEED` there, and a file
|
||||
/// object may hold that same handle; the seed does not follow a file's handles in the band,
|
||||
/// so taking it as-is would hand the file's object's handle to a new object and
|
||||
/// `EntityStore` would replace it (#913, #1921);
|
||||
/// - handle 0, which a file reads as "no handle".
|
||||
///
|
||||
/// Off the top of the range it goes on at the bottom of the band.
|
||||
///
|
||||
/// Cost: below the band the reader and [`Drawing::bump_handseed`] keep the seed above every
|
||||
/// handle an object holds (AUDIT repairs a drawing where that fails), and reserved handles are
|
||||
/// all in the band, so there only `foreign.handles` is looked up. The scan of every space and
|
||||
/// block definition runs only for a candidate in the band. Every handle skipped is a distinct
|
||||
/// one something holds, so the walk ends within one step more than the count of held handles.
|
||||
pub fn next_handle(&self) -> Handle {
|
||||
let held = |h: u64| {
|
||||
h == 0
|
||||
|| self.foreign.handles.contains_key(&Handle(h))
|
||||
|| (h >= HANDLE_LIMIT && (self.reserved_handles.contains(&h) || self.handle_in_use(Handle(h))))
|
||||
};
|
||||
let mut h = self.handseed;
|
||||
while self.foreign.handles.contains_key(&Handle(h)) && h < u64::MAX {
|
||||
h = h.saturating_add(1);
|
||||
// Counted only once a handle is skipped, so the usual first-try answer costs nothing.
|
||||
let mut steps_left: Option<usize> = None;
|
||||
while held(h) {
|
||||
let left = steps_left.get_or_insert_with(|| self.held_handle_count());
|
||||
let Some(rest) = left.checked_sub(1) else { break };
|
||||
*left = rest;
|
||||
h = h.checked_add(1).unwrap_or(HANDLE_LIMIT);
|
||||
}
|
||||
Handle(h)
|
||||
}
|
||||
|
||||
/// Whether an object in any space or block definition already holds `h`.
|
||||
fn handle_in_use(&self, h: Handle) -> bool {
|
||||
self.model.contains(h) || self.layouts.iter().any(|l| l.entities.contains(h)) || self.blocks.values().any(|b| b.entities.contains(h))
|
||||
}
|
||||
/// An upper bound on how many handles [`Drawing::next_handle`] can find held, plus handle 0.
|
||||
fn held_handle_count(&self) -> usize {
|
||||
let spaces = self.layouts.iter().map(|l| l.entities.len()).chain(self.blocks.values().map(|b| b.entities.len()));
|
||||
spaces
|
||||
.fold(self.model.len(), usize::saturating_add)
|
||||
.saturating_add(self.foreign.handles.len())
|
||||
.saturating_add(self.reserved_handles.len())
|
||||
.saturating_add(1)
|
||||
}
|
||||
/// Record a handle a file's record holds in the reserved band, before the record is placed in
|
||||
/// the drawing, so [`Drawing::new_handle`] does not hand it to an object read earlier (#1276).
|
||||
///
|
||||
/// Only handles at or above [`HANDLE_LIMIT`] are recorded: below it [`Drawing::bump_handseed`]
|
||||
/// already moves the seed past them. The reservation stays separate from the seed because the
|
||||
/// writer's growth lives above the limit and a file's handles there are not followed (#913).
|
||||
pub fn reserve_handle(&mut self, h: Handle) {
|
||||
if h.0 >= HANDLE_LIMIT {
|
||||
self.reserved_handles.insert(h.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Make sure future handles don't collide with `h` (after loading a file).
|
||||
///
|
||||
/// A handle at or above [`HANDLE_LIMIT`] is the file's own and stays as it is: it is not
|
||||
/// followed, so a new object is never given the top handle and the file's object is never
|
||||
/// replaced (#913). The handles above the limit are the drawing's room to grow.
|
||||
pub fn bump_handseed(&mut self, h: Handle) {
|
||||
if h.0 >= self.handseed {
|
||||
self.handseed = h.0.saturating_add(1);
|
||||
if h.0 >= self.handseed && h.0 < HANDLE_LIMIT {
|
||||
self.handseed = h.0 + 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -726,6 +726,34 @@ fn new_handles_skip_the_files_object_handles() {
|
||||
assert_eq!(d.new_handle(), Handle(next + 3));
|
||||
}
|
||||
|
||||
/// In the reserved band a new handle skips the file's kept object handles (#2514) and the handles
|
||||
/// objects hold in model space, a layout and a block definition, or that a file record reserved
|
||||
/// (#913); off the top of the range it goes on at the bottom of the band. HANDSEED reports the
|
||||
/// handle `new_handle` takes.
|
||||
#[test]
|
||||
fn new_handles_in_the_reserved_band_skip_every_held_handle_and_wrap() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let top = u64::MAX;
|
||||
d.model.push(Entity::new(Handle(top - 4), line((0.0, 0.0), (1.0, 0.0))));
|
||||
let mut sheet = Layout::new("Sheet", 1);
|
||||
sheet.entities.push(Entity::new(Handle(top - 3), line((0.0, 0.0), (1.0, 0.0))));
|
||||
d.layouts.push(sheet);
|
||||
let mut b = Block::new("B");
|
||||
b.entities.push(Entity::new(Handle(top - 2), line((0.0, 0.0), (1.0, 0.0))));
|
||||
d.blocks.insert("B".into(), std::sync::Arc::new(b));
|
||||
std::sync::Arc::make_mut(&mut d.foreign).handles.insert(Handle(top - 1), ("LAYER".into(), "0".into()));
|
||||
d.reserve_handle(Handle(top));
|
||||
d.model.push(Entity::new(Handle(HANDLE_LIMIT), line((0.0, 0.0), (1.0, 0.0))));
|
||||
d.handseed = top - 5;
|
||||
assert_eq!(d.new_handle(), Handle(top - 5));
|
||||
assert_eq!(d.next_handle(), Handle(HANDLE_LIMIT + 1), "a held handle was offered");
|
||||
assert_eq!(d.new_handle(), Handle(HANDLE_LIMIT + 1));
|
||||
assert_eq!(d.handseed, HANDLE_LIMIT + 2);
|
||||
// Handle 0 means "no handle" in a file; a seed there moves on.
|
||||
d.handseed = 0;
|
||||
assert_eq!(d.new_handle(), Handle(1));
|
||||
}
|
||||
|
||||
/// Several spellings of one DIM field apply once, the last in the map's order, and none is rejected.
|
||||
#[test]
|
||||
fn dim_style_spellings_of_one_field_apply_once() {
|
||||
|
||||
@@ -319,8 +319,14 @@ fn all_handles(d: &Drawing) -> HashSet<Handle> {
|
||||
}
|
||||
|
||||
/// The next handle is above every handle in use, so new objects never take an existing one.
|
||||
///
|
||||
/// A handle at or above [`cadcraft_doc::HANDLE_LIMIT`] is the file's own and is deliberately not
|
||||
/// followed: the seed never moves past it, and new objects take free handles in the band above
|
||||
/// the limit. Reporting it would repeat the same repair on every audit, so it is not an issue.
|
||||
/// Such a handle is left out of the maximum too, or the largest handle would hide every ordinary
|
||||
/// one behind it and the seed would never be repaired past them.
|
||||
fn handseed(d: &mut Drawing, out: &mut Vec<Issue>) {
|
||||
let Some(max) = each_entity(d).map(|e| e.handle).max() else { return };
|
||||
let Some(max) = each_entity(d).map(|e| e.handle).filter(|h| h.0 < cadcraft_doc::HANDLE_LIMIT).max() else { return };
|
||||
if max.0 >= d.handseed {
|
||||
out.push(issue(
|
||||
"handseed",
|
||||
|
||||
@@ -564,17 +564,7 @@ pub fn seg_param(s: &Segment, p: Vec2) -> f64 {
|
||||
match s {
|
||||
Segment::Line(l) => l.param_of(p).clamp(0.0, 1.0),
|
||||
Segment::Arc { arc, ccw } => {
|
||||
// A point just outside the sweep (on the arc within tolerance of an end) goes to the
|
||||
// nearer end: a hair before the start is the start, not round the circle to the end.
|
||||
let a = cadcraft_geom::norm_angle(arc.center.angle_to(p) - arc.start);
|
||||
let sweep = arc.sweep().max(1e-15);
|
||||
let t = if a <= sweep {
|
||||
a / sweep
|
||||
} else if a - sweep < TAU - a {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let t = (cadcraft_geom::norm_angle(arc.center.angle_to(p) - arc.start) / arc.sweep().max(1e-15)).clamp(0.0, 1.0);
|
||||
if *ccw { t } else { 1.0 - t }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -601,25 +601,6 @@ fn measure_spline_by_its_own_parameter() {
|
||||
assert!(pts.len() == 3 && [7.0, 4.0, 1.0].iter().all(|x| pts.iter().any(|p| near(*p, *x, 0.0))), "{pts:?}");
|
||||
}
|
||||
|
||||
/// A pick a hair outside an arc's sweep beside its start is at its start, for an arc and for a
|
||||
/// polyline's arc span alike: MEASURE runs from there (round the circle it was the far end).
|
||||
#[test]
|
||||
fn measure_from_a_pick_a_hair_before_an_arcs_start() {
|
||||
let curves = [
|
||||
("arc", json!({"center": [0, 0], "radius": 1, "start": 0, "end": 180})),
|
||||
("pline", json!({"vertices": [{"p": [1, 0], "bulge": 1}, [-1, 0]]})),
|
||||
];
|
||||
for (cmd, args) in curves {
|
||||
let mut s = Session::new();
|
||||
let e = h(&s.execute(cmd, &args).unwrap());
|
||||
s.execute("measure", &json!({"handle": e, "length": 1, "from": [1, -1e-13]})).unwrap();
|
||||
let pts: Vec<Vec2> =
|
||||
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Point(p) = &e.kind { Some(p.p.xy()) } else { None }).collect();
|
||||
// From (1, 0), a point every radian.
|
||||
assert!(pts.len() == 3 && [1.0f64, 2.0, 3.0].iter().all(|a| pts.iter().any(|p| near(*p, a.cos(), a.sin()))), "{cmd}: {pts:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// MEASURE counts every vertex in a polyline's parameter, coincident ones too (AutoCAD's polyline
|
||||
/// parameter is the vertex index; the chain drops zero-length spans), and picks an ellipse's end
|
||||
/// by the ellipse parameter like any other curve: AutoCAD 2024 runs both measured cases below from
|
||||
|
||||
@@ -18,8 +18,13 @@ use crate::{Result, Session};
|
||||
/// Most image files loaded per drawing.
|
||||
const MAX_IMAGE_FILES: usize = 1000;
|
||||
/// Largest image file read (bytes).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_IMAGE_BYTES: u64 = 256 << 20;
|
||||
/// Longest base64 text taken for `data`: what a file of [`MAX_IMAGE_BYTES`] encodes to.
|
||||
const MAX_IMAGE_BASE64: u64 = MAX_IMAGE_BYTES.div_ceil(3) * 4;
|
||||
/// Longest `data` text with the line breaks and spaces base64 may carry (MIME breaks every 76
|
||||
/// characters, under 3% more): the characters past [`MAX_IMAGE_BASE64`] are counted only up to
|
||||
/// here, which also bounds what decoding sets aside.
|
||||
const MAX_IMAGE_TEXT: u64 = MAX_IMAGE_BASE64 + MAX_IMAGE_BASE64 / 16;
|
||||
/// Most decoded pixel bytes kept per drawing; images past it stay unloaded.
|
||||
const MAX_LOADED_BYTES: u64 = 2 << 30;
|
||||
/// Most image files decoded at the same time when a drawing opens.
|
||||
@@ -70,11 +75,22 @@ fn paths(d: &Drawing) -> Vec<String> {
|
||||
paths
|
||||
}
|
||||
|
||||
/// Whether `path` is a full path here, or on Windows where a drawing may have been written (a
|
||||
/// drive, `C:\maps\a.png`, or a share, `\\server\maps`), which other systems read as relative.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn full_path(path: &str) -> bool {
|
||||
let b = path.trim().as_bytes();
|
||||
std::path::Path::new(path.trim()).is_absolute() || b.starts_with(b"\\\\") || matches!(b, [d, b':', b'\\' | b'/', ..] if d.is_ascii_alphabetic())
|
||||
}
|
||||
|
||||
/// The contents of the image file saved as `path` in a drawing at `host`.
|
||||
fn read_file(path: &str, host: Option<&str>) -> std::result::Result<Vec<u8>, String> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let file = super::blocks::xref::find_file(path, host).ok_or("file not found")?;
|
||||
let file = super::blocks::xref::find_file(path, host).ok_or_else(|| {
|
||||
// An unsaved drawing has no folder for a relative path to be relative to.
|
||||
if host.is_none() && !full_path(path) { "file not found (save the drawing first, or give a full path)" } else { "file not found" }
|
||||
})?;
|
||||
let len = std::fs::metadata(&file).map_err(|e| e.to_string())?.len();
|
||||
if len > MAX_IMAGE_BYTES {
|
||||
return Err(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20));
|
||||
@@ -304,7 +320,19 @@ fn pixels(s: &Session, p: &Value, path: &str) -> Result<Arc<Raster>> {
|
||||
let bytes = match p.get("data") {
|
||||
Some(data) => {
|
||||
let text = data.as_str().ok_or_else(|| bad(ID, "`data` must be base64 text"))?;
|
||||
base64_decode(text).ok_or_else(|| bad(ID, "`data` is not valid base64"))?
|
||||
// Refused before decoding, which would hold all of it in memory. Line breaks and
|
||||
// spaces, which decoding skips, don't count.
|
||||
let len = u64::try_from(text.len()).unwrap_or(u64::MAX);
|
||||
let digits = || u64::try_from(text.bytes().filter(|b| !matches!(b, b'\n' | b'\r' | b' ')).count()).unwrap_or(u64::MAX);
|
||||
if len > MAX_IMAGE_TEXT || (len > MAX_IMAGE_BASE64 && digits() > MAX_IMAGE_BASE64) {
|
||||
return Err(bad(ID, format!("`data` is larger than {} MB", MAX_IMAGE_BYTES >> 20)));
|
||||
}
|
||||
let bytes = base64_decode(text).ok_or_else(|| bad(ID, "`data` is not valid base64"))?;
|
||||
// The longest text allowed can still hold a byte or two more than the limit.
|
||||
if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_IMAGE_BYTES {
|
||||
return Err(bad(ID, format!("`data` is larger than {} MB", MAX_IMAGE_BYTES >> 20)));
|
||||
}
|
||||
bytes
|
||||
}
|
||||
None => {
|
||||
if let Some(loaded) = s.doc()?.rasters.get(path) {
|
||||
|
||||
@@ -26,7 +26,7 @@ mod stretch;
|
||||
mod transform;
|
||||
mod trim;
|
||||
|
||||
use break_join::{BreakAtPointM, BreakM, run_break, run_breakat, run_join};
|
||||
use break_join::{BreakM, run_break, run_breakat, run_join};
|
||||
use explode::run_explode;
|
||||
pub(crate) use explode::{explode_kind, explode_with};
|
||||
use fillet::{FilletM, run_chamfer, run_fillet};
|
||||
@@ -37,7 +37,7 @@ use select_then::{DisplaceM, Op, SelectThen};
|
||||
use stretch::{StretchM, run_stretch};
|
||||
pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
|
||||
use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
|
||||
pub(crate) use trim::{CUT_ONCE, Edges, extend, json_pick_error, trim};
|
||||
pub(crate) use trim::{Edges, extend, trim};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -85,24 +85,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("trim", "Trim", trimextend::run_trim)
|
||||
.menu(&["Modify", "Trim"])
|
||||
.alias(&["tr"])
|
||||
.params(concat!(
|
||||
"{handle, pick: [x,y]} | {fence: [[x,y],...]} | {crossing: [[x,y],[x,y]]}; edges?: [hex] (default: every object; a polyline that is one of them, or every object in Standard mode, also cuts itself at its vertices and crossings), edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\" ",
|
||||
"→ {handles: the object (kept, reshaped) then the new pieces; none when it was erased} (pick) | {trimmed} (fence, crossing). ",
|
||||
"For handle+pick: handle is the object to trim; pick selects the portion of that object to remove ",
|
||||
"(normally a point on it, away from a cutting intersection); edges are the cutting edges. The JSON default is standard mode."
|
||||
))
|
||||
.params(
|
||||
"{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\"} → {handles: the object (kept, reshaped) then the new pieces; none when it was erased} (pick) | {trimmed} (fence, crossing)",
|
||||
)
|
||||
.interactive(|_| Ok(Box::new(TrimM::new(false)))),
|
||||
CommandSpec::new("extend", "Extend", trimextend::run_extend)
|
||||
.menu(&["Modify", "Extend"])
|
||||
.alias(&["ex"])
|
||||
.params(concat!(
|
||||
"{handle, pick: [x,y]} | {fence: [[x,y],...]} | {crossing: [[x,y],[x,y]]}; ",
|
||||
"edges?: [hex], edgeMode?: \"extend\"|\"none\". ",
|
||||
"For handle+pick: handle is the object to extend; pick points toward the boundary to extend to ",
|
||||
"(normally a point on that boundary), selecting the nearer end of the object ",
|
||||
"(of an open polyline, the end on the pick's side of its middle parameter); ",
|
||||
"edges are the boundary edges, and the nearest forward intersection is used."
|
||||
))
|
||||
.params("{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\"}")
|
||||
.interactive(|_| Ok(Box::new(TrimM::new(true)))),
|
||||
CommandSpec::new("fillet", "Fillet", run_fillet)
|
||||
.menu(&["Modify", "Fillet"])
|
||||
@@ -124,10 +114,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.alias(&["br"])
|
||||
.params("{handle, p1, p2} → {handles: the object (kept, reshaped) then the new pieces; none when nothing is left}")
|
||||
.interactive(|_| Ok(Box::new(BreakM::default()))),
|
||||
CommandSpec::new("breakatpoint", "Break At Point", run_breakat)
|
||||
.menu(&["Modify", "Break At Point"])
|
||||
.params("{handle, at} → {handles: the object (kept, reshaped) then the new piece}")
|
||||
.interactive(|_| Ok(Box::new(BreakAtPointM::default()))),
|
||||
CommandSpec::new("breakatpoint", "Break At Point", run_breakat).menu(&["Modify", "Break At Point"]).params("{handle, at} → {handles: the object (kept, reshaped) then the new piece}"),
|
||||
CommandSpec::new("join", "Join", run_join)
|
||||
.menu(&["Modify", "Join"])
|
||||
.alias(&["j"])
|
||||
|
||||
@@ -4,6 +4,16 @@ use super::{
|
||||
Value, Vec2, arc, bad, json, lwpoly, norm_angle, point_param, point_req, targets,
|
||||
};
|
||||
|
||||
/// Gives a rebuilt arc piece its source centre Z, or a rebuilt polyline piece its source elevation.
|
||||
fn with_z(mut k: EntityKind, z: f64) -> EntityKind {
|
||||
match &mut k {
|
||||
EntityKind::Arc(a) => a.center.z = z,
|
||||
EntityKind::LwPolyline(p) => p.elevation = z,
|
||||
_ => {}
|
||||
}
|
||||
k
|
||||
}
|
||||
|
||||
/// Break `h` between two points (or at one point when p1 == p2).
|
||||
pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Result<Vec<Handle>> {
|
||||
if crate::cmd::curves::is_locked(s, h) {
|
||||
@@ -29,12 +39,12 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re
|
||||
}
|
||||
EntityKind::Circle(c) => {
|
||||
if p1.near(p2, 1e-12) {
|
||||
return Err(EngineError::Other("Arc cannot be full 360 degrees".into()));
|
||||
return Err(EngineError::Other("Arc cannot be full 360 degrees.".into()));
|
||||
}
|
||||
let a1 = c.center.xy().angle_to(p1);
|
||||
let a2 = c.center.xy().angle_to(p2);
|
||||
// AutoCAD removes the CCW portion from the first to the second point.
|
||||
vec![arc(&Arc::new(c.center.xy(), c.radius, a2, a1))]
|
||||
vec![with_z(arc(&Arc::new(c.center.xy(), c.radius, a2, a1)), c.center.z)]
|
||||
}
|
||||
EntityKind::Arc(a) => {
|
||||
let ga = Arc::new(a.center.xy(), a.radius, a.start, a.end);
|
||||
@@ -45,10 +55,10 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re
|
||||
}
|
||||
let mut v = Vec::new();
|
||||
if t1 > 1e-12 {
|
||||
v.push(arc(&Arc::new(ga.center, ga.radius, ga.start, ga.start + t1)));
|
||||
v.push(with_z(arc(&Arc::new(ga.center, ga.radius, ga.start, ga.start + t1)), a.center.z));
|
||||
}
|
||||
if t2 < ga.sweep() - 1e-12 {
|
||||
v.push(arc(&Arc::new(ga.center, ga.radius, ga.start + t2, ga.end)));
|
||||
v.push(with_z(arc(&Arc::new(ga.center, ga.radius, ga.start + t2, ga.end)), a.center.z));
|
||||
}
|
||||
v
|
||||
}
|
||||
@@ -71,32 +81,24 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re
|
||||
};
|
||||
let (mut t1, mut t2) = (lp(p1), lp(p2));
|
||||
if p.closed {
|
||||
let (lo, hi) = if t1 <= t2 { (t1, t2) } else { (t2, t1) };
|
||||
let tol = 1e-9 * (1.0 + total);
|
||||
if hi - lo < tol {
|
||||
// One point: the outline opens at its start vertex and splits at the point;
|
||||
// at the start vertex itself it stays whole and closed.
|
||||
if lo < tol || lo > total - tol {
|
||||
return Ok(vec![h]);
|
||||
}
|
||||
vec![lwpoly(sub_polyline(&segs, 0.0, lo), false), lwpoly(sub_polyline(&segs, lo, total), false)]
|
||||
} else {
|
||||
// The stretch between the points that doesn't run through the start vertex
|
||||
// goes, whichever point came first; what is left runs from the later point
|
||||
// round through the start vertex to the earlier one.
|
||||
let doubled: Vec<Segment> = segs.iter().chain(segs.iter()).copied().collect();
|
||||
vec![lwpoly(sub_polyline(&doubled, hi, lo + total), false)]
|
||||
if (t1 - t2).abs() < 1e-9 {
|
||||
return Err(EngineError::Other("Cannot break a closed polyline at a single point.".into()));
|
||||
}
|
||||
// Like a circle: the stretch from the first point to the second, along the
|
||||
// vertices, goes; what is left runs from the second point round to the first.
|
||||
let doubled: Vec<Segment> = segs.iter().chain(segs.iter()).copied().collect();
|
||||
let end = if t1 > t2 { t1 } else { t1 + total };
|
||||
vec![with_z(lwpoly(sub_polyline(&doubled, t2, end), false), p.elevation)]
|
||||
} else {
|
||||
if t1 > t2 {
|
||||
std::mem::swap(&mut t1, &mut t2);
|
||||
}
|
||||
let mut v = Vec::new();
|
||||
if t1 > 1e-12 {
|
||||
v.push(lwpoly(sub_polyline(&segs, 0.0, t1), false));
|
||||
v.push(with_z(lwpoly(sub_polyline(&segs, 0.0, t1), false), p.elevation));
|
||||
}
|
||||
if t2 < total - 1e-12 {
|
||||
v.push(lwpoly(sub_polyline(&segs, t2, total), false));
|
||||
v.push(with_z(lwpoly(sub_polyline(&segs, t2, total), false), p.elevation));
|
||||
}
|
||||
v
|
||||
}
|
||||
@@ -213,41 +215,6 @@ pub(super) fn run_join(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "handle": r.map(|h| h.hex()) }))
|
||||
}
|
||||
|
||||
/// The object picked at `p` for BREAK and BREAKATPOINT ("*Invalid selection*" when there is none).
|
||||
/// One on a locked layer is refused there, and the command asks for an object again, as AutoCAD
|
||||
/// 2024 does; the pick doesn't fall through to an object under it.
|
||||
fn pick_to_break(s: &mut Session, p: Vec2) -> Result<Option<Handle>> {
|
||||
let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5;
|
||||
let space = s.space();
|
||||
match s.pick_object(&space, p, ap)? {
|
||||
Some(h) if crate::cmd::curves::is_locked(s, h) => {
|
||||
s.echo("The object is on a locked layer.");
|
||||
Ok(None)
|
||||
}
|
||||
Some(h) => {
|
||||
s.set_selection(vec![h]);
|
||||
Ok(Some(h))
|
||||
}
|
||||
None => {
|
||||
s.echo("*Invalid selection*");
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Break `h` from `p1` to `p2` and end the command. As in AutoCAD 2024, a break that can't be made
|
||||
/// (a whole circle at one point: "Arc cannot be full 360 degrees") is reported and ends the
|
||||
/// command too, leaving the object as it was.
|
||||
fn break_and_end(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Result<Step> {
|
||||
match break_entity(s, h, p1, p2) {
|
||||
Ok(_) => {}
|
||||
Err(EngineError::Other(m)) => s.echo(m),
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct BreakM {
|
||||
obj: Option<(Handle, Vec2)>,
|
||||
@@ -269,8 +236,14 @@ impl Interactive for BreakM {
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match (self.obj, i) {
|
||||
(None, Input::Point(p)) => {
|
||||
if let Some(h) = pick_to_break(s, p)? {
|
||||
self.obj = Some((h, p));
|
||||
let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5;
|
||||
let space = s.space();
|
||||
match s.pick_object(&space, p, ap)? {
|
||||
Some(h) => {
|
||||
self.obj = Some((h, p));
|
||||
s.set_selection(vec![h]);
|
||||
}
|
||||
None => s.echo("*Invalid selection*"),
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
@@ -283,46 +256,12 @@ impl Interactive for BreakM {
|
||||
self.first_point = false;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Some((h, p1)), Input::Point(p2)) => break_and_end(s, h, p1, p2),
|
||||
(Some(_), Input::Enter) => {
|
||||
(Some((h, p1)), Input::Point(p2)) => {
|
||||
break_entity(s, h, p1, p2)?;
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(None, Input::Enter) => Ok(Step::Done),
|
||||
_ => Ok(Step::Continue),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// BREAKATPOINT at the command line, with AutoCAD 2024's prompts: "Select object:", then "Specify
|
||||
/// break point:"; the object is split there with no gap (the point projects onto it).
|
||||
#[derive(Default)]
|
||||
pub(super) struct BreakAtPointM {
|
||||
obj: Option<Handle>,
|
||||
}
|
||||
|
||||
impl Interactive for BreakAtPointM {
|
||||
fn name(&self) -> &'static str {
|
||||
"BREAKATPOINT"
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
match self.obj {
|
||||
None => Prompt::new("Select object", Accept::POINT),
|
||||
Some(_) => Prompt::new("Specify break point", Accept::POINT),
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match (self.obj, i) {
|
||||
(None, Input::Point(p)) => {
|
||||
self.obj = pick_to_break(s, p)?;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Some(h), Input::Point(p)) => break_and_end(s, h, p, p),
|
||||
(Some(_), Input::Enter) => {
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(None, Input::Enter) => Ok(Step::Done),
|
||||
(_, Input::Enter) => Ok(Step::Done),
|
||||
_ => Ok(Step::Continue),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
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,
|
||||
@@ -93,62 +91,13 @@ fn prim_to_segments(p: &Prim) -> Vec<Segment> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Explain the generic line failures for JSON handle+pick calls, and a line TRIM picked on its
|
||||
/// only cuts ([`ON_THE_CUT`]). Other curves retain their own diagnostics: their nearest-parameter
|
||||
/// rules do not prove that a pick is invalid.
|
||||
pub(crate) fn json_pick_error(s: &Session, h: Handle, pick: Vec2, edges: Edges, extending: bool, error: EngineError) -> EngineError {
|
||||
let generic = if extending { "Object does not intersect an edge." } else { "Object does not intersect a cutting edge." };
|
||||
if !matches!(&error, EngineError::Other(message) if message == generic || (!extending && message == ON_THE_CUT)) {
|
||||
return error;
|
||||
}
|
||||
let Ok(d) = s.doc() else { return error };
|
||||
let Some(e) = d.entity(h) else { return error };
|
||||
let EntityKind::Line(l) = &e.kind else { return error };
|
||||
let Ok(cut) = edge_segments(s, edges, h) else { return error };
|
||||
let ln = Line::new(l.a.xy(), l.b.xy());
|
||||
let message = if extending {
|
||||
// The selected end already failed. Check the opposite end with the same ray and
|
||||
// forward-intersection rules before attributing the failure to the pick's end choice.
|
||||
let (fixed, end) = if pick.dist(ln.b) < pick.dist(ln.a) { (ln.b, ln.a) } else { (ln.a, ln.b) };
|
||||
let dir = (end - fixed).normalized();
|
||||
let ray = Segment::Line(Line::new(end, end + dir * 1e8));
|
||||
let opposite_hit = cut.iter().flat_map(|c| intersect_ext(&ray, c, false)).any(|x| (x - end).dot(dir) > 1e-9);
|
||||
if opposite_hit {
|
||||
"The `pick` point selects an end with no boundary ahead; choose `pick` toward the boundary to extend to."
|
||||
} else {
|
||||
"No usable boundary intersection was found for either end of the object to extend."
|
||||
}
|
||||
} else {
|
||||
let pick_param = ln.param_of(pick).clamp(0.0, 1.0);
|
||||
let has_cut = cut.iter().flat_map(|c| intersect_ext(&Segment::Line(ln), c, false)).any(|x| {
|
||||
let t = ln.param_of(x);
|
||||
t > 1e-9 && t < 1.0 - 1e-9
|
||||
});
|
||||
if !has_cut {
|
||||
"No usable cutting-edge intersection in the interior of the object to trim."
|
||||
} else if pick_param.is_nan() {
|
||||
return error;
|
||||
} else if !ln.at(pick_param).near(pick, 1e-9_f64.max(64.0 * f64::EPSILON * (1.0 + pick.len().max(ln.a.len()).max(ln.b.len())))) {
|
||||
"The `pick` point is off the line and projects onto a cutting intersection; pick away from that intersection."
|
||||
} else {
|
||||
"The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection."
|
||||
}
|
||||
};
|
||||
EngineError::Other(message.into())
|
||||
}
|
||||
|
||||
/// Trim `h` at the piece containing `pick`. Returns the handles that replace it.
|
||||
/// Trim `h` at the piece containing `pick`. Returns what it became: its pieces, `h` first
|
||||
/// ([`replace_with_pieces`]).
|
||||
pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Result<Vec<Handle>> {
|
||||
if crate::cmd::curves::is_locked(s, h) {
|
||||
return Err(EngineError::Other("The object is on a locked layer.".into()));
|
||||
}
|
||||
let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?;
|
||||
let cut = edge_segments(s, edges, h)?;
|
||||
// A polyline that is one of the edges (picked, or with every object in either mode) cuts
|
||||
// itself too.
|
||||
let itself = edges.only.is_none_or(|o| o.contains(&h));
|
||||
let pieces: Vec<EntityKind> = match &e.kind {
|
||||
EntityKind::Line(l) => {
|
||||
let ln = Line::new(l.a.xy(), l.b.xy());
|
||||
@@ -160,12 +109,10 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
|
||||
.collect();
|
||||
ts.sort_by(f64::total_cmp);
|
||||
let tp = ln.param_of(pick).clamp(0.0, 1.0);
|
||||
let found = ts.len();
|
||||
ts.retain(|t| (t - tp).abs() * ln.len() > ON_CUT);
|
||||
let lo = ts.iter().copied().filter(|t| *t < tp).fold(0.0, f64::max);
|
||||
let hi = ts.iter().copied().filter(|t| *t > tp).fold(1.0, f64::min);
|
||||
if lo == 0.0 && hi == 1.0 {
|
||||
return Err(EngineError::Other(if ts.len() < found { ON_THE_CUT } else { "Object does not intersect a cutting edge." }.into()));
|
||||
return Err(EngineError::Other("Object does not intersect a cutting edge.".into()));
|
||||
}
|
||||
let mut v = Vec::new();
|
||||
if lo > 0.0 {
|
||||
@@ -184,14 +131,11 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
|
||||
let mut ts: Vec<f64> =
|
||||
cut.iter().flat_map(|c| intersect_ext(&seg, c, false)).map(param).filter(|t| *t > 1e-9 && *t < sweep - 1e-9).collect();
|
||||
ts.sort_by(f64::total_cmp);
|
||||
// A pick off the arc is at the end it is nearer, round the circle.
|
||||
let tp = crate::cmd::curves::seg_param(&seg, pick) * sweep;
|
||||
let found = ts.len();
|
||||
ts.retain(|t| (t - tp).abs() * ga.radius > ON_CUT);
|
||||
let tp = param(pick).min(sweep);
|
||||
let lo = ts.iter().copied().filter(|t| *t < tp).fold(0.0, f64::max);
|
||||
let hi = ts.iter().copied().filter(|t| *t > tp).fold(sweep, f64::min);
|
||||
if lo == 0.0 && hi == sweep {
|
||||
return Err(EngineError::Other(if ts.len() < found { ON_THE_CUT } else { "Object does not intersect a cutting edge." }.into()));
|
||||
return Err(EngineError::Other("Object does not intersect a cutting edge.".into()));
|
||||
}
|
||||
let mut v = Vec::new();
|
||||
if lo > 0.0 {
|
||||
@@ -207,16 +151,10 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
|
||||
let mut angs: Vec<f64> = cut.iter().flat_map(|x| intersect_ext(&full, x, false)).map(|p| c.center.xy().angle_to(p)).collect();
|
||||
angs.sort_by(f64::total_cmp);
|
||||
angs.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
|
||||
let ap = c.center.xy().angle_to(pick);
|
||||
let found = angs.len();
|
||||
angs.retain(|a| {
|
||||
let d = norm_angle(a - ap);
|
||||
d.min(TAU - d) * c.radius > ON_CUT
|
||||
});
|
||||
if angs.len() < 2 {
|
||||
let why = if found >= 2 { ON_THE_CUT } else { "Circle must intersect cutting edges at two or more points." };
|
||||
return Err(EngineError::Other(why.into()));
|
||||
return Err(EngineError::Other("Circle must intersect cutting edges at two or more points.".into()));
|
||||
}
|
||||
let ap = c.center.xy().angle_to(pick);
|
||||
// The removed arc runs between the two intersections around the pick.
|
||||
let n = angs.len();
|
||||
let mut keep = None;
|
||||
@@ -229,10 +167,7 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
|
||||
}
|
||||
keep.into_iter().collect()
|
||||
}
|
||||
EntityKind::LwPolyline(p) => match trim_polyline(p, &cut, pick, itself)? {
|
||||
Some(pieces) => pieces,
|
||||
None => return Ok(vec![h]),
|
||||
},
|
||||
EntityKind::LwPolyline(p) => trim_polyline(p, &cut, pick)?,
|
||||
k => crate::cmd::modify2::trim_other(k, &cut, pick)?,
|
||||
};
|
||||
replace_with_pieces(s, h, pieces)
|
||||
@@ -246,20 +181,19 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
|
||||
/// in its middle keeps its handle on the piece from its start point, the piece to its end point is
|
||||
/// new; a circle broken or trimmed becomes an arc with the circle's handle.)
|
||||
///
|
||||
/// Each piece keeps what the object had beyond its outline ([`inherit`]). Dimensions attached to
|
||||
/// the object follow [`crate::assoc::follow_pieces`]. Its parametric constraints are removed: its
|
||||
/// new shape no longer meets them, and solving them again would move the objects they tie it to.
|
||||
/// Dimensions attached to the object follow [`crate::assoc::follow_pieces`]. Its parametric
|
||||
/// constraints are removed: its new shape no longer meets them, and solving them again would move
|
||||
/// the objects they tie it to.
|
||||
pub(super) fn replace_with_pieces(s: &mut Session, h: Handle, pieces: Vec<EntityKind>) -> Result<Vec<Handle>> {
|
||||
let d = s.doc_mut()?;
|
||||
if pieces.is_empty() {
|
||||
let mut pieces = pieces.into_iter();
|
||||
let Some(first) = pieces.next() else {
|
||||
d.remove_entity(h);
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
};
|
||||
let (Some(space), Some(old)) = (d.space_of(h), d.entity(h).cloned()) else {
|
||||
return Err(EngineError::Other("no such object".into()));
|
||||
};
|
||||
let mut pieces = pieces.into_iter().map(|k| inherit(&old.kind, k));
|
||||
let Some(first) = pieces.next() else { return Ok(Vec::new()) };
|
||||
d.modify_entity(h, |e| e.kind = first)?;
|
||||
let mut out = vec![h];
|
||||
for kind in pieces {
|
||||
@@ -279,31 +213,6 @@ pub(super) fn replace_with_pieces(s: &mut Session, h: Handle, pieces: Vec<Entity
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `piece`, cut from `source`, with what it keeps of it as AutoCAD 2024's BREAK and TRIM leave
|
||||
/// pieces: a line's Z along it, an arc's (or a circle's) centre Z, and a polyline's elevation,
|
||||
/// constant width and linetype generation.
|
||||
fn inherit(source: &EntityKind, mut piece: EntityKind) -> EntityKind {
|
||||
match (source, &mut piece) {
|
||||
(EntityKind::Line(s), EntityKind::Line(p)) => {
|
||||
let ln = Line::new(s.a.xy(), s.b.xy());
|
||||
if ln.len() > 0.0 {
|
||||
let z = |t: f64| s.a.z + (s.b.z - s.a.z) * t;
|
||||
p.a.z = z(ln.param_of(p.a.xy()));
|
||||
p.b.z = z(ln.param_of(p.b.xy()));
|
||||
}
|
||||
}
|
||||
(EntityKind::Arc(s), EntityKind::Arc(p)) => p.center.z = s.center.z,
|
||||
(EntityKind::Circle(s), EntityKind::Arc(p)) => p.center.z = s.center.z,
|
||||
(EntityKind::LwPolyline(s), EntityKind::LwPolyline(p)) => {
|
||||
p.elevation = s.elevation;
|
||||
p.const_width = s.const_width;
|
||||
p.plinegen = s.plinegen;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
piece
|
||||
}
|
||||
|
||||
/// Sub-polyline between length parameters `a` and `b` (open polylines).
|
||||
pub(super) fn sub_polyline(segs: &[Segment], a: f64, b: f64) -> Vec<PolyVertex> {
|
||||
let mut out: Vec<PolyVertex> = Vec::new();
|
||||
@@ -336,128 +245,15 @@ pub(super) fn sub_polyline(segs: &[Segment], a: f64, b: f64) -> Vec<PolyVertex>
|
||||
out
|
||||
}
|
||||
|
||||
/// 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;
|
||||
|
||||
/// 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 that
|
||||
/// near one of a polyline's own cuts, and passes over a cut by another edge, the trim running on
|
||||
/// across it, on lines, arcs and circles too. On open polylines from 1e-3 to 1e9 long it was within
|
||||
/// 5e-7, and 5.1e-7 away trimmed at the cut (around a closed rectangle it reached a little further,
|
||||
/// to 1e-6; on a line, further still, to 5e-4 on one 10 long).
|
||||
const ON_CUT: f64 = 5e-7;
|
||||
|
||||
/// The refusal when every cut was passed over ([`ON_CUT`]): the object meets an edge, at the pick,
|
||||
/// so Quick mode leaves it in place rather than erasing it as one no edge crosses.
|
||||
const ON_THE_CUT: &str = "The pick is on the cut: nothing to trim.";
|
||||
|
||||
/// 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<Vec<f64>> {
|
||||
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 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<f64> = (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 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<usize> = (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 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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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 ([`self_cuts`]). `None`: the pick is on one of its
|
||||
/// own cuts ([`ON_CUT`]), which trims nothing.
|
||||
fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itself: bool) -> Result<Option<Vec<EntityKind>>> {
|
||||
fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2) -> Result<Vec<EntityKind>> {
|
||||
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<f64> = Vec::new();
|
||||
let mut acc = 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 tp = 0.0;
|
||||
let mut best = f64::INFINITY;
|
||||
for (i, s) in segs.iter().enumerate() {
|
||||
for s in &segs {
|
||||
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);
|
||||
@@ -466,34 +262,13 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse
|
||||
if c.dist(pick) < best {
|
||||
best = c.dist(pick);
|
||||
tp = acc + param_on(s, c) * len;
|
||||
k = i;
|
||||
}
|
||||
acc += len;
|
||||
}
|
||||
let mut own = if itself { self_cuts(&segs, p.closed, k)? } else { Vec::new() };
|
||||
// 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);
|
||||
own.retain(|t| *t > 1e-9 && *t < total - 1e-9);
|
||||
}
|
||||
// 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() };
|
||||
// A pick on one of its own cuts trims nothing; a cut by another edge there is passed over, and
|
||||
// the piece runs on across it.
|
||||
if own.iter().any(|t| apart(*t, tp) <= ON_CUT) {
|
||||
return Ok(None);
|
||||
}
|
||||
let found = ts.len();
|
||||
ts.retain(|t| apart(*t, tp) > ON_CUT);
|
||||
let passed = ts.len() < found;
|
||||
ts.extend(own);
|
||||
ts.retain(|t| *t > 1e-9 && *t < total - 1e-9);
|
||||
ts.sort_by(f64::total_cmp);
|
||||
if ts.is_empty() {
|
||||
return Err(EngineError::Other(if passed { ON_THE_CUT } else { "Object does not intersect a cutting edge." }.into()));
|
||||
}
|
||||
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()));
|
||||
return Err(EngineError::Other("Object does not intersect a cutting edge.".into()));
|
||||
}
|
||||
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);
|
||||
@@ -508,31 +283,33 @@ 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<Segment> = segs.iter().chain(segs.iter()).copied().collect();
|
||||
let (a, b) = if hi > total { (hi - total, lo) } else { (hi, lo + total) };
|
||||
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;
|
||||
}
|
||||
out.push(mk(sub_polyline(&doubled, a, b)));
|
||||
} else {
|
||||
// A piece whose ends meet (the polyline touched itself there) is closed, without its
|
||||
// repeated vertex, as AutoCAD leaves it.
|
||||
let piece = |mut vs: Vec<PolyVertex>| {
|
||||
// Within rounding of the coordinates, however far from the origin, and no more.
|
||||
let meets = vs.len() >= 4
|
||||
&& matches!((vs.first(), vs.last()), (Some(a), Some(b)) if a.p.near(b.p, 64.0 * f64::EPSILON * (1.0 + a.p.len().max(b.p.len()))));
|
||||
if meets {
|
||||
vs.pop();
|
||||
}
|
||||
lwpoly(vs, meets)
|
||||
};
|
||||
if lo.is_finite() {
|
||||
out.push(piece(sub_polyline(&segs, 0.0, lo)));
|
||||
out.push(mk(sub_polyline(&segs, 0.0, lo)));
|
||||
}
|
||||
if hi.is_finite() {
|
||||
out.push(piece(sub_polyline(&segs, hi, total)));
|
||||
out.push(mk(sub_polyline(&segs, hi, total)));
|
||||
}
|
||||
}
|
||||
Ok(Some(out.into_iter().filter(|k| matches!(k, EntityKind::LwPolyline(l) if l.vertices.len() >= 2)).collect()))
|
||||
Ok(out.into_iter().filter(|k| matches!(k, EntityKind::LwPolyline(l) if l.vertices.len() >= 2)).collect())
|
||||
}
|
||||
|
||||
pub(super) use crate::cmd::curves::seg_param as param_on;
|
||||
pub(super) fn param_on(s: &Segment, p: Vec2) -> f64 {
|
||||
match s {
|
||||
Segment::Line(l) => l.param_of(p).clamp(0.0, 1.0),
|
||||
Segment::Arc { arc, ccw } => {
|
||||
let t = norm_angle(arc.center.angle_to(p) - arc.start) / arc.sweep().max(1e-15);
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
if *ccw { t } else { 1.0 - t }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A polyline arc segment on `ga`'s circle that ends at `end` after turning through `sweep`
|
||||
/// (signed, positive counterclockwise), run on round the circle to the nearest boundary edge: the
|
||||
@@ -595,13 +372,7 @@ pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Re
|
||||
EntityKind::LwPolyline(p) if !p.closed && p.vertices.len() >= 2 => {
|
||||
let mut vs = p.vertices.clone();
|
||||
let n = vs.len();
|
||||
// The pick's parameter: the segment it is nearest, plus how far along it. AutoCAD 2024
|
||||
// extends the end on that side of the polyline's middle parameter, the last from the
|
||||
// middle on, not the end nearer the pick. A repeated vertex counts as a segment, so
|
||||
// these come from the vertices, not `Polyline::segments`, which skips it.
|
||||
let spans: Vec<_> = vs.windows(2).filter_map(|w| Some((w.first()?.p, w.get(1)?.p, w.first()?.bulge))).collect();
|
||||
let at = crate::cmd::curves::vertex_param_of(&spans, pick);
|
||||
let from_end = 2.0 * at >= (n - 1) as f64;
|
||||
let from_end = vs.last().is_some_and(|l| pick.dist(l.p) < vs.first().map(|f| pick.dist(f.p)).unwrap_or(f64::INFINITY));
|
||||
let (i_end, i_prev) = if from_end { (n - 1, n - 2) } else { (0, 1) };
|
||||
let end = vs.get(i_end).map(|v| v.p).unwrap_or_default();
|
||||
let prev = vs.get(i_prev).map(|v| v.p).unwrap_or_default();
|
||||
|
||||
@@ -8,9 +8,8 @@ use cadcraft_doc::{Drawing, EntityKind, Handle};
|
||||
use cadcraft_geom::{Bounds2, Line, Vec2, line_line};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::curves::KW;
|
||||
use super::helpers::{line, lwpoly, rect_vertices};
|
||||
use super::modify::{CUT_ONCE, Edges, extend, json_pick_error, trim};
|
||||
use super::modify::{Edges, extend, trim};
|
||||
use super::{bad, point_param, points_param};
|
||||
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
|
||||
|
||||
@@ -32,10 +31,8 @@ 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 {
|
||||
let m = e.to_string();
|
||||
m.contains("intersect") && m != CUT_ONCE
|
||||
e.to_string().contains("intersect")
|
||||
}
|
||||
|
||||
/// Trim or extend `h` at `at`. A Quick-mode (`quick`) trim of an object no cutting edge crosses
|
||||
@@ -106,12 +103,7 @@ 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);
|
||||
// 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)));
|
||||
let cands = [*p, *q, seg.closest(a)].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);
|
||||
@@ -181,6 +173,7 @@ fn run(s: &mut Session, p: &Value, extending: bool) -> Result<Value> {
|
||||
let cmd = if extending { "extend" } else { "trim" };
|
||||
let only: Option<Vec<Handle>> =
|
||||
p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().and_then(Handle::parse_hex)).collect());
|
||||
let edges = Edges { only: only.as_deref(), implied: edge_mode_param(cmd, p)? };
|
||||
let quick = match p.get("mode") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(v) => match v.as_str().map(|m| m.trim().to_ascii_lowercase()).as_deref() {
|
||||
@@ -189,7 +182,6 @@ fn run(s: &mut Session, p: &Value, extending: bool) -> Result<Value> {
|
||||
_ => return Err(bad(cmd, "`mode` must be \"quick\" or \"standard\"")),
|
||||
},
|
||||
};
|
||||
let edges = Edges { only: only.as_deref(), implied: edge_mode_param(cmd, p)? };
|
||||
let key = if extending { "extended" } else { "trimmed" };
|
||||
if p.get("fence").is_some_and(|v| !v.is_null()) {
|
||||
let pts = points_param(p, "fence")
|
||||
@@ -205,19 +197,8 @@ fn run(s: &mut Session, p: &Value, extending: bool) -> Result<Value> {
|
||||
return Ok(json!({ key: n }));
|
||||
}
|
||||
let h = super::targets(s, p)?.first().copied().ok_or_else(|| bad(cmd, "`handle` is required"))?;
|
||||
let pick = point_param(p, "pick").ok_or_else(|| {
|
||||
bad(
|
||||
cmd,
|
||||
if extending {
|
||||
"`pick` ([x, y]) is required: point toward the boundary to extend to, selecting the nearer end"
|
||||
} else {
|
||||
"`pick` ([x, y]) is required: select the portion of the object to trim away"
|
||||
},
|
||||
)
|
||||
})?;
|
||||
// Diagnose only an existing single-pick JSON failure. Successful calls, Quick-mode
|
||||
// erasure, fence/crossing and the interactive command keep their existing behavior.
|
||||
let r = apply(s, h, pick, extending, edges, quick).map_err(|e| json_pick_error(s, h, pick, edges, extending, e))?;
|
||||
let pick = point_param(p, "pick").ok_or_else(|| bad(cmd, "`pick` ([x, y]) is required"))?;
|
||||
let r = apply(s, h, pick, extending, edges, quick)?;
|
||||
if extending { Ok(Value::Null) } else { Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() })) }
|
||||
}
|
||||
|
||||
@@ -239,8 +220,6 @@ enum Stage {
|
||||
Edges(Vec<Handle>),
|
||||
/// Fence points so far.
|
||||
Fence(Vec<Vec2>),
|
||||
/// Quick mode's two-point fence, started by a pick in empty space: its first point.
|
||||
QuickFence(Vec2),
|
||||
/// A crossing window: its first corner once picked.
|
||||
Crossing(Option<Vec2>),
|
||||
Mode,
|
||||
@@ -377,12 +356,11 @@ impl Interactive for TrimM {
|
||||
None => Prompt::new("Specify first fence point", Accept::POINT),
|
||||
Some(l) => Prompt::new("Specify next fence point", Accept::POINT).kw(&["Undo"]).base(*l),
|
||||
},
|
||||
Stage::QuickFence(a) => Prompt::new("Specify next fence point", Accept::POINT).base(*a),
|
||||
Stage::Crossing(None) => Prompt::new("Specify first corner", Accept::POINT),
|
||||
Stage::Crossing(Some(_)) => Prompt::new("Specify opposite corner", Accept::POINT),
|
||||
Stage::Mode => {
|
||||
let msg = if self.extend { "Enter an extend mode option" } else { "Enter a trim mode option" };
|
||||
Prompt::new(msg, KW).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" })
|
||||
Prompt::new(msg, Accept::TEXT).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" })
|
||||
}
|
||||
Stage::Project => {
|
||||
let cur = match proj_mode(s) {
|
||||
@@ -390,9 +368,9 @@ impl Interactive for TrimM {
|
||||
2 => "View",
|
||||
_ => "Ucs",
|
||||
};
|
||||
Prompt::new("Enter a projection option", KW).kw(&["None", "Ucs", "View"]).default(cur)
|
||||
Prompt::new("Enter a projection option", Accept::TEXT).kw(&["None", "Ucs", "View"]).default(cur)
|
||||
}
|
||||
Stage::Edge => Prompt::new("Enter an implied edge extension mode", KW).kw(&["Extend", "No extend"]).default(if edge_mode(s) {
|
||||
Stage::Edge => Prompt::new("Enter an implied edge extension mode", Accept::TEXT).kw(&["Extend", "No extend"]).default(if edge_mode(s) {
|
||||
"Extend"
|
||||
} else {
|
||||
"No extend"
|
||||
@@ -477,16 +455,6 @@ impl Interactive for TrimM {
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Stage::QuickFence(a) => {
|
||||
self.stage = Stage::Pick;
|
||||
if let Input::Point(b) = i {
|
||||
let r = self.step(s, |m, s| fence(s, &[a, b], extending, m.edges(quick, implied), quick).map(|_| ()));
|
||||
if let Err(e) = r {
|
||||
s.echo(e.to_string());
|
||||
}
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Stage::Crossing(first) => {
|
||||
match (first, i) {
|
||||
(None, Input::Point(p)) => self.stage = Stage::Crossing(Some(p)),
|
||||
@@ -507,9 +475,8 @@ impl Interactive for TrimM {
|
||||
let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5;
|
||||
let space = s.space();
|
||||
let Some(h) = s.pick_object(&space, p, ap)? else {
|
||||
// A pick in empty space starts a two-point fence in Quick mode (as in
|
||||
// AutoCAD, #1594) and a crossing window in Standard mode.
|
||||
self.stage = if quick { Stage::QuickFence(p) } else { Stage::Crossing(Some(p)) };
|
||||
// A pick in empty space opens a crossing window there.
|
||||
self.stage = Stage::Crossing(Some(p));
|
||||
return Ok(Step::Continue);
|
||||
};
|
||||
let r = self.step(s, |m, s| apply(s, h, p, extending, m.edges(quick, implied), quick).map(|_| ()));
|
||||
@@ -558,7 +525,6 @@ impl Interactive for TrimM {
|
||||
.windows(2)
|
||||
.filter_map(|w| Some(line(*w.first()?, *w.get(1)?)))
|
||||
.collect(),
|
||||
Stage::QuickFence(a) => vec![line(*a, c)],
|
||||
Stage::Crossing(Some(a)) => vec![lwpoly(rect_vertices(*a, c), true)],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
|
||||
@@ -139,6 +139,9 @@ pub struct LispState {
|
||||
/// Interpreter steps all synchronous callbacks have run, nested ones included. A callback's
|
||||
/// allowance counts what ran since it started, so the callbacks it calls spend its steps.
|
||||
pub(crate) callback_used: u64,
|
||||
/// Work synchronous callbacks did inside the running step, already counted in `callback_used`:
|
||||
/// the step is charged it without charging the enclosing callback a second time.
|
||||
pub(crate) callback_work: u64,
|
||||
/// The `callback_used` value the callback running now (and so every one it calls) must not
|
||||
/// pass: the lowest of its own and its callers' allowances.
|
||||
pub(crate) callback_ceiling: Option<u64>,
|
||||
@@ -383,6 +386,14 @@ impl Session {
|
||||
let uid = run.uid;
|
||||
self.lisp_flush(&mut env, false);
|
||||
self.lisp_env_put(uid, env);
|
||||
// The work the slice did, which one step can take far past the slice. After a panic
|
||||
// `used` is still the previous slice's; the run ends with the error anyway.
|
||||
run.steps = run.steps.saturating_add(run.machine.used);
|
||||
if run.blocking && run.steps > BLOCKING_CAP && matches!(outcome, Outcome::Wait(_)) {
|
||||
self.lisp.run = Some(run);
|
||||
self.lisp_error(LispError::quit(format!("routine stopped after {BLOCKING_CAP} steps")));
|
||||
return;
|
||||
}
|
||||
match outcome {
|
||||
Outcome::Done(v) => {
|
||||
self.lisp.run = Some(run);
|
||||
@@ -395,13 +406,7 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
Outcome::Wait(Need::Yield) => {
|
||||
run.steps = run.steps.saturating_add(SLICE);
|
||||
if run.blocking {
|
||||
if run.steps > BLOCKING_CAP {
|
||||
self.lisp.run = Some(run);
|
||||
self.lisp_error(LispError::quit(format!("routine stopped after {BLOCKING_CAP} steps")));
|
||||
return;
|
||||
}
|
||||
self.lisp.run = Some(run);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -175,17 +175,19 @@ pub struct Machine {
|
||||
stack: Vec<Frame>,
|
||||
state: State,
|
||||
need: Option<Need>,
|
||||
/// Steps the last [`Machine::run`] took, with the work done inside them.
|
||||
pub(crate) used: u64,
|
||||
}
|
||||
|
||||
impl Machine {
|
||||
/// A machine evaluating `forms` in turn.
|
||||
pub fn forms(forms: Vec<Value>) -> Machine {
|
||||
Machine { stack: vec![Frame::Forms { rest: forms.into_iter().rev().collect() }], state: State::Ret(Value::Nil), need: None }
|
||||
Machine { stack: vec![Frame::Forms { rest: forms.into_iter().rev().collect() }], state: State::Ret(Value::Nil), need: None, used: 0 }
|
||||
}
|
||||
|
||||
/// A machine calling `f` with `args`.
|
||||
pub fn calling(f: Value, args: Vec<Value>) -> Machine {
|
||||
Machine { stack: Vec::new(), state: State::Call(f, args), need: None }
|
||||
Machine { stack: Vec::new(), state: State::Call(f, args), need: None, used: 0 }
|
||||
}
|
||||
|
||||
/// Give the value a [`Need`] waited for, and carry on.
|
||||
@@ -193,12 +195,31 @@ impl Machine {
|
||||
self.state = State::Ret(v);
|
||||
}
|
||||
|
||||
/// Run until done, waiting, or `budget` steps.
|
||||
/// Run until done, waiting, or `budget` steps. A step that walks a long list (`length`) or
|
||||
/// runs a synchronous callback counts that work too, so one slice stays short.
|
||||
pub fn run(&mut self, ctx: &mut Ctx<'_>, budget: u64) -> Outcome {
|
||||
let mut n = 0u64;
|
||||
let outcome = self.run_counted(ctx, budget, &mut n);
|
||||
// The last step's work too, so nothing is left for the next run.
|
||||
self.used = n.saturating_add(Machine::take_step_work(ctx));
|
||||
outcome
|
||||
}
|
||||
|
||||
/// The work the last step did besides itself: the lists it walked, which count against a
|
||||
/// callback's allowance too, and the callbacks it ran, which were counted there as they ran.
|
||||
fn take_step_work(ctx: &mut Ctx<'_>) -> u64 {
|
||||
let walked = super::value::take_work();
|
||||
let callbacks = std::mem::take(&mut ctx.s.lisp.callback_work);
|
||||
if ctx.depth > 0 {
|
||||
ctx.s.lisp.callback_used = ctx.s.lisp.callback_used.saturating_add(walked);
|
||||
}
|
||||
walked.saturating_add(callbacks)
|
||||
}
|
||||
|
||||
fn run_counted(&mut self, ctx: &mut Ctx<'_>, budget: u64, n: &mut u64) -> Outcome {
|
||||
loop {
|
||||
n += 1;
|
||||
if n > budget {
|
||||
*n = n.saturating_add(1).saturating_add(Machine::take_step_work(ctx));
|
||||
if *n > budget {
|
||||
return Outcome::Wait(Need::Yield);
|
||||
}
|
||||
// Charge a callback's step as it runs, so callbacks it calls see what it already spent.
|
||||
@@ -651,6 +672,10 @@ impl Ctx<'_> {
|
||||
return Ok(v);
|
||||
}
|
||||
let cap = self.s.lisp.limits.callback_steps;
|
||||
// Work the caller queued before this call (its list walks, earlier callbacks of the same
|
||||
// step) is not this callback's: set it aside and hand it back with this callback's.
|
||||
let pending = super::value::take_work();
|
||||
let pending_callbacks = std::mem::take(&mut self.s.lisp.callback_work);
|
||||
let start = self.s.lisp.callback_used;
|
||||
// This callback may run until `callback_used` reaches `ceiling`: `cap` steps from now, or
|
||||
// sooner where a caller's allowance ends, so callbacks nested in callbacks share one
|
||||
@@ -658,13 +683,20 @@ impl Ctx<'_> {
|
||||
let outer = self.s.lisp.callback_ceiling;
|
||||
let ceiling = start.saturating_add(cap).min(outer.unwrap_or(u64::MAX));
|
||||
self.s.lisp.callback_ceiling = Some(ceiling);
|
||||
let r = self.drive_callback(f, args, ceiling);
|
||||
let mut spent: u64 = 0;
|
||||
let r = self.drive_callback(f, args, ceiling, &mut spent);
|
||||
self.s.lisp.callback_ceiling = outer;
|
||||
super::value::charge_work(pending);
|
||||
// Its steps, nested callbacks' included, are work done inside the caller's one step: they
|
||||
// count against the caller's slice and every enclosing callback's. They are in
|
||||
// `callback_used` already, so they reach the caller apart from its list walks.
|
||||
self.s.lisp.callback_work = pending_callbacks.saturating_add(spent);
|
||||
r
|
||||
}
|
||||
|
||||
/// Run callback `f` in slices until it finishes or `callback_used` reaches `ceiling`.
|
||||
fn drive_callback(&mut self, f: &Value, args: Vec<Value>, ceiling: u64) -> Result<Value, LispError> {
|
||||
/// Run callback `f` in slices until it finishes or `callback_used` reaches `ceiling`, adding
|
||||
/// the work each slice did to `spent`.
|
||||
fn drive_callback(&mut self, f: &Value, args: Vec<Value>, ceiling: u64, spent: &mut u64) -> Result<Value, LispError> {
|
||||
let cap = self.s.lisp.limits.callback_steps;
|
||||
let mut m = Machine::calling(f.clone(), args);
|
||||
let mut sub = Ctx { s: &mut *self.s, env: &mut *self.env, depth: self.depth + 1 };
|
||||
@@ -680,6 +712,7 @@ impl Ctx<'_> {
|
||||
}
|
||||
let slice = remaining.min(SYNC_SLICE);
|
||||
let outcome = m.run(&mut sub, slice);
|
||||
*spent = spent.saturating_add(m.used);
|
||||
match outcome {
|
||||
// The steps were charged as they ran; finishing past the shared allowance is a failure too.
|
||||
Outcome::Done(_) if sub.s.lisp.callback_used > ceiling => {
|
||||
|
||||
@@ -247,6 +247,112 @@ fn synchronous_callback_loop_is_an_error_not_a_hang() {
|
||||
assert_eq!(ok(&mut s, "(vl-sort '(3 1 2) '<)"), "(1 2 3)");
|
||||
}
|
||||
|
||||
/// A step that walks a long list counts its work: one `length` of 32768 cells is past a 1000-step
|
||||
/// slice, so the slice yields after it.
|
||||
#[test]
|
||||
fn walking_a_long_list_counts_against_the_slice() {
|
||||
use super::eval::{Ctx, Machine, Need, Outcome};
|
||||
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = session();
|
||||
let mut env = super::Env::default();
|
||||
let mut ctx = Ctx { s: &mut s, env: &mut env, depth: 0 };
|
||||
// Built before the measured run, so only the `length` is counted.
|
||||
let mut build = Machine::forms(super::read::read_all("(setq l '(1)) (repeat 15 (setq l (append l l)))").unwrap());
|
||||
assert!(matches!(build.run(&mut ctx, u64::MAX), Outcome::Done(_)));
|
||||
let mut m = Machine::forms(super::read::read_all("(length l)").unwrap());
|
||||
// Counted as one step, the walk left the few steps of `(length l)` well inside the slice.
|
||||
assert!(matches!(m.run(&mut ctx, 1_000), Outcome::Wait(Need::Yield)), "the walk was not charged");
|
||||
assert!(m.used > 32_768, "{}", m.used);
|
||||
match m.run(&mut ctx, u64::MAX) {
|
||||
Outcome::Done(v) => assert_eq!(to_text(&v, true), "32768"),
|
||||
_ => panic!("the length did not finish"),
|
||||
}
|
||||
assert_eq!(super::value::take_work(), 0, "nothing is left for the next run");
|
||||
}
|
||||
|
||||
/// A routine is charged the work its slice did, not the slice's length: one `length` of 2^19
|
||||
/// cells is far past a 400000-step slice.
|
||||
#[test]
|
||||
fn a_routine_is_charged_the_work_of_its_slice() {
|
||||
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = session();
|
||||
ok(&mut s, "(setq l '(1)) (repeat 19 (setq l (append l l))) nil");
|
||||
let r = s.lisp_eval("(length l) (repeat 10 (setq x 1))", false, false, Vec::new()).unwrap();
|
||||
assert!(r.is_none(), "the routine gave the interface a frame");
|
||||
assert!(s.lisp_busy());
|
||||
let steps = s.lisp.run.as_ref().map(|r| r.steps).unwrap_or(0);
|
||||
assert!(steps >= 1 << 19, "{steps}");
|
||||
for _ in 0..100 {
|
||||
if !s.lisp_busy() {
|
||||
break;
|
||||
}
|
||||
s.lisp_tick();
|
||||
}
|
||||
assert!(!s.lisp_running());
|
||||
ok(&mut s, "(setq l nil)");
|
||||
}
|
||||
|
||||
/// A run's last step walking a long list is charged to that run, not left for the next one: here
|
||||
/// it fails after the walk (a list of numbers isn't a list of strings), so no step follows it.
|
||||
#[test]
|
||||
fn the_last_steps_list_walk_is_charged_to_its_run() {
|
||||
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = session();
|
||||
let mut env = super::Env::default();
|
||||
env.globals.insert(super::value::Sym::new("L"), Value::list(vec![Value::Int(1); 100_000]));
|
||||
let mut m = super::eval::Machine::forms(super::read::read_all("(acad_strlsort l)").unwrap());
|
||||
let mut ctx = super::eval::Ctx { s: &mut s, env: &mut env, depth: 0 };
|
||||
assert!(matches!(m.run(&mut ctx, u64::MAX), super::eval::Outcome::Error(_)));
|
||||
assert!(m.used > 100_000, "{}", m.used);
|
||||
assert_eq!(super::value::take_work(), 0, "nothing is left for the next run");
|
||||
}
|
||||
|
||||
/// Nested callbacks share one cap: an inner endless callback retried by an outer one stops.
|
||||
#[test]
|
||||
fn nested_callback_steps_count_against_the_outer_callback() {
|
||||
let mut s = session();
|
||||
s.lisp.limits.callback_steps = 10_000;
|
||||
// Each level retried the endless level inside it with a fresh cap: 10000^3 steps, a hang.
|
||||
let code = "(defun g (a b) (while t)) \
|
||||
(defun f (a b) (while t (vl-catch-all-apply 'vl-sort (list '(1 2) 'g)))) \
|
||||
(defun h (a b) (while t (vl-catch-all-apply 'vl-sort (list '(1 2) 'f)))) \
|
||||
(vl-sort '(1 2) 'h)";
|
||||
assert_eq!(eval(&mut s, code), Err("callback stopped after 10000 steps".into()));
|
||||
// A callback's own steps count once, however many slices it runs in: three slices do three
|
||||
// times the work of one.
|
||||
let counts: Vec<u64> = [400_000, 1_200_000]
|
||||
.into_iter()
|
||||
.map(|cap| {
|
||||
s.lisp.limits.callback_steps = cap;
|
||||
ok(&mut s, "(setq n 0)");
|
||||
assert!(eval(&mut s, "(vl-remove-if '(lambda (x) (while t (setq n (1+ n)))) '(1))").is_err());
|
||||
ok(&mut s, "n").parse().unwrap()
|
||||
})
|
||||
.collect();
|
||||
assert!(counts[1] * 10 >= counts[0] * 29, "{counts:?}");
|
||||
}
|
||||
|
||||
/// The callback cap holds for each callback: a sort's comparisons together take more steps than
|
||||
/// it, and all their work still reaches the enclosing run.
|
||||
#[test]
|
||||
fn each_callback_has_its_own_cap_and_its_work_reaches_the_caller() {
|
||||
let mut s = session();
|
||||
s.lisp.limits.callback_steps = 1_000;
|
||||
let mut env = super::Env::default();
|
||||
env.globals.insert(super::value::Sym::new("L"), Value::list((0..300).rev().map(Value::Int)));
|
||||
let mut m = super::eval::Machine::forms(super::read::read_all("(vl-sort l (function (lambda (a b) (< a b))))").unwrap());
|
||||
let mut ctx = super::eval::Ctx { s: &mut s, env: &mut env, depth: 0 };
|
||||
let v = match m.run(&mut ctx, u64::MAX) {
|
||||
super::eval::Outcome::Done(v) => v,
|
||||
super::eval::Outcome::Error(e) => panic!("the sort failed: {e:?}"),
|
||||
super::eval::Outcome::Wait(_) => panic!("the sort waited"),
|
||||
};
|
||||
assert_eq!(to_text(&v, true), to_text(&Value::list((0..300).map(Value::Int)), true));
|
||||
// Over a thousand comparisons of several steps each, together well past the cap.
|
||||
assert!(m.used > 3_000, "{}", m.used);
|
||||
assert_eq!(super::value::take_work(), 0, "nothing is left for the next run");
|
||||
}
|
||||
|
||||
/// A zero-step callback limit prevents even the first callback side effect.
|
||||
#[test]
|
||||
fn a_zero_callback_budget_does_not_run_the_callback() {
|
||||
|
||||
@@ -64,6 +64,8 @@ thread_local! {
|
||||
static STRING_BYTES: Cell<(u64, u64)> = const { Cell::new((0, STRING_BUDGET)) };
|
||||
/// The running slice's cap on live cons cells.
|
||||
static CELL_LIMIT: Cell<usize> = const { Cell::new(MAX_CELLS) };
|
||||
/// Work done inside the current machine step: list cells walked, steps of synchronous callbacks.
|
||||
static WORK: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Start a slice of a run on this thread: it fails when more than `limit` cells are alive.
|
||||
@@ -76,6 +78,16 @@ pub fn check_cells() -> Result<(), LispError> {
|
||||
if live_cells() > CELL_LIMIT.with(Cell::get) { Err(LispError::quit("out of memory: too many list cells")) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// Count `n` units of work done inside one machine step ([`super::eval::Machine::run`] charges them as steps).
|
||||
pub fn charge_work(n: u64) {
|
||||
WORK.with(|c| c.set(c.get().saturating_add(n)));
|
||||
}
|
||||
|
||||
/// The work counted since the last call.
|
||||
pub fn take_work() -> u64 {
|
||||
WORK.with(|c| c.replace(0))
|
||||
}
|
||||
|
||||
/// Start a slice of a run on this thread: it has made `used` bytes of its `budget`.
|
||||
pub fn set_string_budget(used: u64, budget: u64) {
|
||||
STRING_BYTES.with(|c| c.set((used, budget)));
|
||||
@@ -262,7 +274,10 @@ impl Value {
|
||||
loop {
|
||||
match v {
|
||||
Value::Nil => return true,
|
||||
Value::Cons(c) => v = c.cdr.clone(),
|
||||
Value::Cons(c) => {
|
||||
charge_work(1);
|
||||
v = c.cdr.clone();
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
@@ -318,6 +333,7 @@ impl Iterator for ListIter {
|
||||
fn next(&mut self) -> Option<Value> {
|
||||
match std::mem::take(&mut self.next) {
|
||||
Value::Cons(c) => {
|
||||
charge_work(1);
|
||||
self.next = c.cdr.clone();
|
||||
Some(c.car.clone())
|
||||
}
|
||||
|
||||
@@ -329,3 +329,39 @@ fn auditctl_generates_adt_report_file() {
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_handle_in_the_reserved_band_is_not_repaired_on_every_audit() {
|
||||
// A file object above HANDLE_LIMIT keeps its handle, and the seed deliberately does not move
|
||||
// past it (#913). AUDIT must not report that policy as an error its own repair never fixes.
|
||||
let band = Handle(cadcraft_engine::doc::HANDLE_LIMIT);
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.space_mut(&Space::Model).unwrap().push(Entity { handle: band, common: Common::default(), kind: line((0.0, 0.0), (1.0, 0.0)) });
|
||||
d.handseed = band.0;
|
||||
for _ in 0..3 {
|
||||
let r = cadcraft_engine::audit::check(&d);
|
||||
assert!(r.issues.iter().all(|i| i.kind != "handseed"), "{}", r.message());
|
||||
}
|
||||
let mut repaired = d.clone();
|
||||
let r = cadcraft_engine::audit::repair(&mut repaired);
|
||||
assert!(r.iter().all(|i| i.kind != "handseed"), "{r:?}");
|
||||
assert_eq!(repaired.handseed, band.0, "the seed moved past the file's own handle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordinary_handle_behind_a_reserved_band_one_is_still_repaired() {
|
||||
// The largest handle is in the reserved band, which the seed deliberately does not follow.
|
||||
// An ordinary handle above the seed must still be found behind it: it is the one the seed
|
||||
// has to move past, and skipping the check would leave AUDIT reporting a clean drawing.
|
||||
let band = Handle(cadcraft_engine::doc::HANDLE_LIMIT);
|
||||
let mut d = Drawing::new_imperial();
|
||||
let store = d.space_mut(&Space::Model).unwrap();
|
||||
store.push(Entity { handle: Handle(20), common: Common::default(), kind: line((0.0, 0.0), (1.0, 0.0)) });
|
||||
store.push(Entity { handle: band, common: Common::default(), kind: line((2.0, 0.0), (3.0, 0.0)) });
|
||||
d.handseed = 10;
|
||||
let r = cadcraft_engine::audit::repair(&mut d);
|
||||
assert!(r.iter().any(|i| i.kind == "handseed" && i.message.contains("(14)")), "the ordinary handle was hidden: {r:?}");
|
||||
assert_eq!(d.handseed, 21, "the seed was not moved past the ordinary handle");
|
||||
let r = cadcraft_engine::audit::repair(&mut d.clone());
|
||||
assert!(r.iter().all(|i| i.kind != "handseed"), "the repair does not stick: {r:?}");
|
||||
}
|
||||
|
||||
@@ -142,6 +142,51 @@ fn bad_input_is_refused_and_changes_nothing() {
|
||||
assert_eq!(listed(&mut s), json!([]));
|
||||
}
|
||||
|
||||
/// `data` longer than the largest image file encodes to is refused before it is decoded.
|
||||
#[test]
|
||||
fn oversized_data_is_refused_before_decoding() {
|
||||
hooks();
|
||||
const LIMIT: u64 = 256 << 20;
|
||||
let mut s = Session::new();
|
||||
// Not base64 at all: only the check before decoding tells it is too long ("not valid base64"
|
||||
// otherwise), and nothing is decoded.
|
||||
let too_long = "!".repeat(usize::try_from(LIMIT.div_ceil(3) * 4 + 1).unwrap());
|
||||
let e = s.execute("imageattach", &json!({ "path": "a.png", "data": too_long })).unwrap_err().to_string();
|
||||
assert!(e.contains("`data` is larger than 256 MB"), "{e}");
|
||||
// Line breaks don't count: base64 wrapped as MIME writes it is taken.
|
||||
let wrapped: String = base64_encode(&png()).as_bytes().chunks(76).map(|c| format!("{}\r\n", String::from_utf8_lossy(c))).collect();
|
||||
s.execute("imageattach", &json!({ "path": "wrapped.png", "data": wrapped })).unwrap();
|
||||
s.execute("undo", &json!({})).unwrap();
|
||||
|
||||
// The longest text allowed, holding one byte more than the limit, is refused once decoded.
|
||||
let groups = usize::try_from(LIMIT / 3).unwrap();
|
||||
let one_over = format!("{}AAA=", "AAAA".repeat(groups));
|
||||
assert_eq!(u64::try_from(one_over.len()).unwrap(), LIMIT.div_ceil(3) * 4, "as long as the text for the limit itself");
|
||||
let e = s.execute("imageattach", &json!({ "path": "a.png", "data": one_over })).unwrap_err().to_string();
|
||||
assert!(e.contains("`data` is larger than 256 MB"), "{e}");
|
||||
assert!(images(&s).is_empty());
|
||||
}
|
||||
|
||||
/// A relative path in an unsaved drawing has nothing to be relative to, and the error says so.
|
||||
#[test]
|
||||
fn a_relative_path_in_an_unsaved_drawing_says_what_to_do() {
|
||||
hooks();
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("imageattach", &json!({ "path": "missing.png" })).unwrap_err().to_string();
|
||||
assert!(e.contains("save the drawing first, or give a full path"), "{e}");
|
||||
|
||||
let dir = folder("unsaved");
|
||||
let full = dir.join("missing.png");
|
||||
let e = s.execute("imageattach", &json!({ "path": full.to_string_lossy() })).unwrap_err().to_string();
|
||||
assert!(e.contains("file not found") && !e.contains("save the drawing"), "{e}");
|
||||
// A full Windows path, read as relative elsewhere, is a full path all the same.
|
||||
for windows in [r"C:\nowhere\a.png", "D:/nowhere/a.png", r"\\server\maps\a.png"] {
|
||||
let e = s.execute("imageattach", &json!({ "path": windows })).unwrap_err().to_string();
|
||||
assert!(e.contains("file not found") && !e.contains("save the drawing"), "{windows}: {e}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_among_many_objects_keeps_its_pixels() {
|
||||
// More objects than one build task takes: the display list is built in parts and joined,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! BREAK on a closed polyline removes the stretch between the two points that doesn't run
|
||||
//! through its start vertex, whichever point comes first, and leaves one open polyline from the
|
||||
//! later point round to the earlier one (#1173; AutoCAD 2024, accoreconsole).
|
||||
//! BREAK on a closed polyline removes the stretch from the first to the second point along the
|
||||
//! vertex direction and leaves one open polyline (#1173).
|
||||
|
||||
use cadcraft_doc::{EntityKind, LwPolyline};
|
||||
use cadcraft_engine::Session;
|
||||
@@ -39,15 +38,14 @@ fn break_opens_a_closed_polyline_at_the_command_line() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_json_on_a_closed_polyline_ignores_the_order_of_the_points() {
|
||||
fn break_json_on_a_closed_polyline_follows_the_order_of_the_points() {
|
||||
let mut s = Session::new();
|
||||
let r = closed_rect(&mut s);
|
||||
// Second point before the first along the vertices: the same stretch goes as with the points
|
||||
// the other way round (measured with the first point after the second, and both ways on a
|
||||
// 100 x 10 rectangle broken at (10, 0) and (10, 10), where the long stretch went).
|
||||
// Second point before the first along the vertices: the long way round goes, the short
|
||||
// stretch between them stays.
|
||||
s.execute("break", &json!({ "handle": r["handle"], "p1": [100, 30], "p2": [50, 0] })).unwrap();
|
||||
let ps = polys(&s);
|
||||
assert_eq!(ps.len(), 1);
|
||||
assert!(!ps[0].closed);
|
||||
assert_eq!(pts(&ps[0]), vec![(100.0, 30.0), (100.0, 60.0), (0.0, 60.0), (0.0, 0.0), (50.0, 0.0)]);
|
||||
assert_eq!(pts(&ps[0]), vec![(50.0, 0.0), (100.0, 0.0), (100.0, 30.0)]);
|
||||
}
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
//! BREAKATPOINT and BREAK where the result is easy to get wrong, as AutoCAD 2024 runs them
|
||||
//! (accoreconsole, `entget` of every object after the command, on these drawings):
|
||||
//!
|
||||
//! - BREAKATPOINT at either end of a line, or at the end vertex of an open polyline, leaves the
|
||||
//! object whole;
|
||||
//! - at an open polyline's middle vertex it splits it there, the original keeping the first part;
|
||||
//! - BREAK of a closed polyline at two points of one side, either way round and on the side that
|
||||
//! closes it too, opens it with its own handle;
|
||||
//! - a circle trimmed or broken becomes an arc with its own handle.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn handle(v: &Value) -> Handle {
|
||||
Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The model space objects in order: handle and kind.
|
||||
fn objects(s: &Session) -> Vec<(Handle, EntityKind)> {
|
||||
s.doc().unwrap().model.iter().map(|e| (e.handle, e.kind.clone())).collect()
|
||||
}
|
||||
|
||||
/// A polyline's closed flag and vertices (rounded to 1e-9).
|
||||
fn pts(k: &EntityKind) -> (bool, Vec<(f64, f64)>) {
|
||||
let EntityKind::LwPolyline(p) = k else { panic!("not a polyline: {k:?}") };
|
||||
let r = |v: f64| (v * 1e9).round() / 1e9;
|
||||
(p.closed, p.vertices.iter().map(|v| (r(v.p.x), r(v.p.y))).collect())
|
||||
}
|
||||
|
||||
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
|
||||
handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap())
|
||||
}
|
||||
|
||||
fn pline(s: &mut Session, vertices: Value, closed: bool) -> Handle {
|
||||
handle(&s.execute("pline", &json!({ "vertices": vertices, "closed": closed })).unwrap())
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, script: &str) {
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_at_an_end_leaves_the_object_whole() {
|
||||
for at in ["100,0", "0,0"] {
|
||||
let mut s = Session::new();
|
||||
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
|
||||
run(&mut s, &format!("BREAKATPOINT {at} {at}\n"));
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 1, "{at}: {objs:?}");
|
||||
let EntityKind::Line(k) = &objs[0].1 else { panic!("{objs:?}") };
|
||||
assert!(objs[0].0 == l && (k.a.x, k.a.y, k.b.x, k.b.y) == (0.0, 0.0, 100.0, 0.0), "{at}: {objs:?}");
|
||||
}
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], [50, 0], [50, 30]]), false);
|
||||
run(&mut s, "BREAKATPOINT 50,30 50,30\n");
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 1, "{objs:?}");
|
||||
assert_eq!((objs[0].0, pts(&objs[0].1)), (p, (false, vec![(0.0, 0.0), (50.0, 0.0), (50.0, 30.0)])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_at_a_middle_vertex_splits_there_and_the_original_keeps_the_first_part() {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], [50, 0], [50, 30]]), false);
|
||||
run(&mut s, "BREAKATPOINT 50,0 50,0\n");
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 2, "{objs:?}");
|
||||
let first = objs.iter().find(|o| o.0 == p).expect("the original stays");
|
||||
let other = objs.iter().find(|o| o.0 != p).unwrap();
|
||||
assert_eq!(pts(&first.1), (false, vec![(0.0, 0.0), (50.0, 0.0)]));
|
||||
assert_eq!(pts(&other.1), (false, vec![(50.0, 0.0), (50.0, 30.0)]));
|
||||
// One undo brings back the polyline as it was, under its handle, and nothing else.
|
||||
s.undo().unwrap();
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 1, "{objs:?}");
|
||||
assert_eq!((objs[0].0, pts(&objs[0].1)), (p, (false, vec![(0.0, 0.0), (50.0, 0.0), (50.0, 30.0)])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_at_two_points_of_one_side_opens_a_closed_polyline_with_its_handle() {
|
||||
let bottom = vec![(30.0, 0.0), (100.0, 0.0), (100.0, 10.0), (0.0, 10.0), (0.0, 0.0), (20.0, 0.0)];
|
||||
// The side from (0, 10) back to the start vertex closes the rectangle.
|
||||
let closing = vec![(0.0, 3.0), (0.0, 0.0), (100.0, 0.0), (100.0, 10.0), (0.0, 10.0), (0.0, 8.0)];
|
||||
for (script, want) in [("BREAK 20,0 30,0\n", &bottom), ("BREAK 30,0 20,0\n", &bottom), ("BREAK 0,8 0,3\n", &closing)] {
|
||||
let mut s = Session::new();
|
||||
let r = pline(&mut s, json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true);
|
||||
run(&mut s, script);
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 1, "{script}: {objs:?}");
|
||||
assert_eq!((objs[0].0, pts(&objs[0].1)), (r, (false, want.clone())), "{script}");
|
||||
// Undo closes it again.
|
||||
s.undo().unwrap();
|
||||
let objs = objects(&s);
|
||||
let rect = vec![(0.0, 0.0), (100.0, 0.0), (100.0, 10.0), (0.0, 10.0)];
|
||||
assert_eq!(objs.iter().map(|o| (o.0, pts(&o.1))).collect::<Vec<_>>(), vec![(r, (true, rect))], "{script}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_trimmed_or_broken_becomes_an_arc_with_its_handle() {
|
||||
// Trimmed between the lines x = -5 and x = 5, picked at its top: the arc from 120 to 60
|
||||
// degrees, round the bottom.
|
||||
let mut s = Session::new();
|
||||
let c = handle(&s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap());
|
||||
let l = line(&mut s, [-5.0, -20.0], [-5.0, 20.0]);
|
||||
let m = line(&mut s, [5.0, -20.0], [5.0, 20.0]);
|
||||
s.execute("trim", &json!({ "handle": c.hex(), "pick": [0, 10], "edges": [l.hex(), m.hex()] })).unwrap();
|
||||
// The arc's handle, and whether it is AutoCAD's: radius 10 round (0, 0), from `start` to
|
||||
// `end` degrees (to 1e-9 radians, 0 and 360 alike).
|
||||
let arc_is = |s: &Session, start: f64, end: f64| {
|
||||
let objs = objects(s);
|
||||
let (h, k) = objs.iter().find(|o| matches!(o.1, EntityKind::Arc(_))).cloned().expect("an arc");
|
||||
let EntityKind::Arc(a) = k else { panic!("not an arc") };
|
||||
let same = |got: f64, want: f64| {
|
||||
let d = (got - want.to_radians()).rem_euclid(std::f64::consts::TAU);
|
||||
d < 1e-9 || std::f64::consts::TAU - d < 1e-9
|
||||
};
|
||||
let ok = (a.radius - 10.0).abs() < 1e-9 && a.center.x.abs() < 1e-9 && a.center.y.abs() < 1e-9 && same(a.start, start) && same(a.end, end);
|
||||
(h, ok)
|
||||
};
|
||||
assert_eq!(arc_is(&s, 120.0, 60.0), (c, true));
|
||||
// Broken from (10, 0) to (0, 10): the arc from 90 degrees round to 0.
|
||||
let mut s = Session::new();
|
||||
let c = handle(&s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap());
|
||||
run(&mut s, "BREAK 10,0 0,10\n");
|
||||
assert_eq!(objects(&s).len(), 1);
|
||||
assert_eq!(arc_is(&s, 90.0, 0.0), (c, true));
|
||||
// Undo gives the circle back under its handle.
|
||||
s.undo().unwrap();
|
||||
let objs = objects(&s);
|
||||
assert!(objs.len() == 1 && objs[0].0 == c && matches!(objs[0].1, EntityKind::Circle(_)), "{objs:?}");
|
||||
}
|
||||
@@ -1,647 +0,0 @@
|
||||
//! BREAK on a closed polyline and TRIM of a polyline that is one of its own cutting edges, as
|
||||
//! AutoCAD 2024 does them (measured with accoreconsole on these drawings):
|
||||
//!
|
||||
//! - BREAK between two points of a closed polyline removes the stretch between them that doesn't
|
||||
//! run through its start vertex, whichever point comes first; BREAK or BREAKATPOINT at one point
|
||||
//! 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. 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 one of the polyline's own cuts, whatever its size, trims nothing; a cut
|
||||
//! by another edge that near the pick is passed over. 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.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
type Vertex = (f64, f64, f64);
|
||||
|
||||
fn handle(v: &Value) -> Handle {
|
||||
Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn pline(s: &mut Session, vertices: Value, closed: bool) -> Handle {
|
||||
handle(&s.execute("pline", &json!({ "vertices": vertices, "closed": closed })).unwrap())
|
||||
}
|
||||
|
||||
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
|
||||
handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap())
|
||||
}
|
||||
|
||||
/// Every polyline in model space in order: its handle, closed flag and vertices with bulges.
|
||||
fn polys(s: &Session) -> Vec<(Handle, bool, Vec<Vertex>)> {
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::LwPolyline(p) => Some((e.handle, p.closed, p.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect())),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn same(got: &[Vertex], want: &[Vertex]) -> bool {
|
||||
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9 && (g.2 - w.2).abs() < 1e-9)
|
||||
}
|
||||
|
||||
/// The polylines are `want` in order, (`kept`, closed, vertices): `kept` is whether it has the
|
||||
/// handle `h`.
|
||||
fn expect(s: &Session, h: Handle, want: &[(bool, bool, &[Vertex])]) {
|
||||
let got = polys(s);
|
||||
assert_eq!(got.len(), want.len(), "{got:?}");
|
||||
for ((gh, gc, gv), (kept, closed, wv)) in got.iter().zip(want) {
|
||||
assert_eq!((*gh == h, *gc), (*kept, *closed), "{got:?}");
|
||||
assert!(same(gv, wv), "{gv:?} != {wv:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, script: &str) {
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||
}
|
||||
|
||||
// ---------------- BREAK on a closed polyline ----------------
|
||||
|
||||
#[test]
|
||||
fn break_removes_the_stretch_between_the_points_that_misses_the_start_vertex() {
|
||||
// 100 x 10 rectangle broken at (10, 0) and (10, 10): the 190-unit stretch between them goes,
|
||||
// the 20 units across the start vertex stay, with the points either way round.
|
||||
for script in ["BREAK 10,0 10,10\n", "BREAK 10,10 10,0\n"] {
|
||||
let mut s = Session::new();
|
||||
let r = pline(&mut s, json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true);
|
||||
run(&mut s, script);
|
||||
expect(&s, r, &[(true, false, &[(10.0, 10.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_with_the_first_point_after_the_second_keeps_the_run_through_the_start() {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], { "p": [40, 0], "bulge": 0.5 }, [60, 0], [60, 30], [0, 30]]), true);
|
||||
run(&mut s, "BREAK 60,20 10,0\n");
|
||||
expect(&s, p, &[(true, false, &[(60.0, 20.0, 0.0), (60.0, 30.0, 0.0), (0.0, 30.0, 0.0), (0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]);
|
||||
}
|
||||
|
||||
const SQUARE: [[f64; 2]; 4] = [[250.0, 0.0], [270.0, 0.0], [270.0, 20.0], [250.0, 20.0]];
|
||||
|
||||
#[test]
|
||||
fn break_at_one_point_splits_a_closed_polyline_in_two() {
|
||||
let first: &[Vertex] = &[(250.0, 0.0, 0.0), (260.0, 0.0, 0.0)];
|
||||
let second: &[Vertex] = &[(260.0, 0.0, 0.0), (270.0, 0.0, 0.0), (270.0, 20.0, 0.0), (250.0, 20.0, 0.0), (250.0, 0.0, 0.0)];
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!(SQUARE), true);
|
||||
run(&mut s, "BREAK 260,0 260,0\n");
|
||||
expect(&s, p, &[(true, false, first), (false, false, second)]);
|
||||
// BREAKATPOINT does the same.
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!(SQUARE), true);
|
||||
let r = s.execute("breakatpoint", &json!({ "handle": p.hex(), "at": [260, 0] })).unwrap();
|
||||
assert_eq!(r["handles"].as_array().unwrap().len(), 2);
|
||||
expect(&s, p, &[(true, false, first), (false, false, second)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_at_a_vertex_splits_there_and_at_the_start_vertex_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!(SQUARE), true);
|
||||
run(&mut s, "BREAK 270,20 270,20\n");
|
||||
expect(
|
||||
&s,
|
||||
p,
|
||||
&[
|
||||
(true, false, &[(250.0, 0.0, 0.0), (270.0, 0.0, 0.0), (270.0, 20.0, 0.0)]),
|
||||
(false, false, &[(270.0, 20.0, 0.0), (250.0, 20.0, 0.0), (250.0, 0.0, 0.0)]),
|
||||
],
|
||||
);
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!(SQUARE), true);
|
||||
run(&mut s, "BREAK 250,0 250,0\n");
|
||||
expect(&s, p, &[(true, true, &[(250.0, 0.0, 0.0), (270.0, 0.0, 0.0), (270.0, 20.0, 0.0), (250.0, 20.0, 0.0)])]);
|
||||
}
|
||||
|
||||
// ---------------- TRIM of a polyline that cuts itself ----------------
|
||||
|
||||
/// A polyline with an arc, and vertical lines at x = 20 and x = 60 crossing it.
|
||||
fn arc_polyline(s: &mut Session) -> (Handle, Handle, Handle) {
|
||||
let p = pline(s, json!([[0, 0], { "p": [40, 0], "bulge": 0.4 }, [70, 0], [90, 30]]), false);
|
||||
let b = line(s, [20.0, -10.0], [20.0, 40.0]);
|
||||
let c = line(s, [60.0, -20.0], [60.0, 40.0]);
|
||||
(p, b, c)
|
||||
}
|
||||
|
||||
/// The piece from the x = 60 cut on the arc to the end, as measured.
|
||||
const FROM_C: [Vertex; 3] = [(60.0, -5.417486860749438, 0.1330399827453447), (70.0, 0.0, 0.0), (90.0, 30.0, 0.0)];
|
||||
|
||||
fn trim(s: &mut Session, h: Handle, pick: [f64; 2], edges: Option<&[Handle]>) {
|
||||
let mut p = json!({ "handle": h.hex(), "pick": pick });
|
||||
if let Some(es) = edges {
|
||||
p["edges"] = json!(es.iter().map(|e| e.hex()).collect::<Vec<_>>());
|
||||
}
|
||||
s.execute("trim", &p).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_every_object_cutting_a_polyline_trims_to_its_own_vertex() {
|
||||
let mut s = Session::new();
|
||||
let (p, ..) = arc_polyline(&mut s);
|
||||
trim(&mut s, p, [55.0, -6.0], None);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edges_that_leave_the_polyline_out_cut_only_where_they_cross_it() {
|
||||
let mut s = Session::new();
|
||||
let (p, b, c) = arc_polyline(&mut s);
|
||||
trim(&mut s, p, [55.0, -6.0], Some(&[b, c]));
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (20.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_that_is_its_only_edge_loses_the_whole_segment_picked() {
|
||||
let mut s = Session::new();
|
||||
let (p, ..) = arc_polyline(&mut s);
|
||||
trim(&mut s, p, [55.0, -6.0], Some(&[p]));
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &[(70.0, 0.0, 0.0), (90.0, 30.0, 0.0)])]);
|
||||
// The first segment: one piece left, the polyline itself.
|
||||
let mut s = Session::new();
|
||||
let (p, ..) = arc_polyline(&mut s);
|
||||
trim(&mut s, p, [10.0, 0.0], Some(&[p]));
|
||||
expect(&s, p, &[(true, false, &[(40.0, 0.0, 0.4), (70.0, 0.0, 0.0), (90.0, 30.0, 0.0)])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_polyline_that_is_its_only_edge_opens_without_the_segment_picked() {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], [40, 0], [40, 30], [0, 30]]), true);
|
||||
trim(&mut s, p, [20.0, 0.0], Some(&[p]));
|
||||
expect(&s, p, &[(true, false, &[(40.0, 0.0, 0.0), (40.0, 30.0, 0.0), (0.0, 30.0, 0.0), (0.0, 0.0, 0.0)])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_crossing_itself_is_cut_at_the_crossing() {
|
||||
let x = json!([[0, 0], [40, 20], [40, 0], [0, 20]]);
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, x.clone(), false);
|
||||
trim(&mut s, p, [10.0, 5.0], Some(&[p]));
|
||||
expect(&s, p, &[(true, false, &[(20.0, 10.0, 0.0), (40.0, 20.0, 0.0), (40.0, 0.0, 0.0), (0.0, 20.0, 0.0)])]);
|
||||
// Every object (the polyline alone): cut between the crossing and the next vertex.
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, x, false);
|
||||
trim(&mut s, p, [30.0, 15.0], None);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (20.0, 10.0, 0.0)]), (false, false, &[(40.0, 20.0, 0.0), (40.0, 0.0, 0.0), (0.0, 20.0, 0.0)])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_polyline_at_survey_coordinates_trims_to_its_own_vertex() {
|
||||
let mut s = Session::new();
|
||||
let p = pline(
|
||||
&mut s,
|
||||
json!([[612345.678, 2398765.432], { "p": [612385.678, 2398765.432], "bulge": 0.4 }, [612415.678, 2398765.432], [612415.678, 2398795.432], [612345.678, 2398795.432]]),
|
||||
true,
|
||||
);
|
||||
let b = line(&mut s, [612365.678, 2398755.432], [612365.678, 2398805.432]);
|
||||
let c = line(&mut s, [612405.678, 2398745.432], [612405.678, 2398805.432]);
|
||||
trim(&mut s, p, [612400.678, 2398759.432], Some(&[p, b, c]));
|
||||
let got = polys(&s);
|
||||
assert_eq!(got.len(), 1);
|
||||
let (h, closed, vs) = &got[0];
|
||||
assert!(*h == p && !closed);
|
||||
let want: [Vertex; 6] = [
|
||||
(612405.678, 2398760.014513139, 0.1330399827461127),
|
||||
(612415.678, 2398765.432, 0.0),
|
||||
(612415.678, 2398795.432, 0.0),
|
||||
(612345.678, 2398795.432, 0.0),
|
||||
(612345.678, 2398765.432, 0.0),
|
||||
(612385.678, 2398765.432, 0.0),
|
||||
];
|
||||
// Survey coordinates: a micrometre on the points, the bulge to 1e-9.
|
||||
assert_eq!(vs.len(), want.len());
|
||||
for (g, w) in vs.iter().zip(&want) {
|
||||
assert!((g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6 && (g.2 - w.2).abs() < 1e-9, "{g:?} != {w:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standard_mode_at_the_command_line_with_every_object_cuts_at_the_polyline_vertex() {
|
||||
let mut s = Session::new();
|
||||
let (p, ..) = arc_polyline(&mut s);
|
||||
// Mode Standard, Enter: every object is a cutting edge.
|
||||
run(&mut s, "TRIM O S\n\n55,-6\n\n");
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_picked_as_an_edge_in_quick_mode_cuts_itself_too() {
|
||||
// Quick mode with the edges given (its cuTting edges option): picked is picked.
|
||||
let mut s = Session::new();
|
||||
let (p, _, c) = arc_polyline(&mut s);
|
||||
s.execute("trim", &json!({ "handle": p.hex(), "pick": [55, -6], "mode": "quick", "edges": [p.hex(), c.hex()] })).unwrap();
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_mode_with_every_object_cuts_a_polyline_at_its_own_vertex_too() {
|
||||
// As Standard mode with every object: from the vertex at (40, 0), not from the line at x = 20.
|
||||
let mut s = Session::new();
|
||||
let (p, ..) = arc_polyline(&mut s);
|
||||
s.execute("trim", &json!({ "handle": p.hex(), "pick": [55, -6], "mode": "quick" })).unwrap();
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
|
||||
}
|
||||
|
||||
/// A rectangle, then an open polyline whose last vertex (6.9, 6.2) touches its second segment
|
||||
/// inside the rectangle (reversed: whose first vertex does). The polyline's handle.
|
||||
fn touching(s: &mut Session, reversed: bool) -> Handle {
|
||||
pline(s, json!([[3.9, 3.8], [8.3, 3.8], [8.3, 6.9], [3.9, 6.9]]), true);
|
||||
let mut v = vec![[2.3, 3.3], [5.3, 8.0], [8.5, 4.4], [8.8, 7.8], [6.9, 6.2]];
|
||||
if reversed {
|
||||
v.reverse();
|
||||
}
|
||||
pline(s, json!(v), false)
|
||||
}
|
||||
|
||||
const RECT: [Vertex; 4] = [(3.9, 3.8, 0.0), (8.3, 3.8, 0.0), (8.3, 6.9, 0.0), (3.9, 6.9, 0.0)];
|
||||
/// Where the second segment crosses the rectangle's top and right sides.
|
||||
const TOP: Vertex = (6.277777777777777, 6.9, 0.0);
|
||||
const RIGHT: Vertex = (8.3, 4.625, 0.0);
|
||||
|
||||
#[test]
|
||||
fn a_polyline_is_cut_where_its_end_touches_it() {
|
||||
let start: [Vertex; 3] = [(2.3, 3.3, 0.0), (5.3, 8.0, 0.0), TOP];
|
||||
let looped: [Vertex; 3] = [(6.9, 6.2, 0.0), (8.5, 4.4, 0.0), (8.8, 7.8, 0.0)];
|
||||
// Picked above the touch, in the rectangle: cut from the top side to the touch. What is left
|
||||
// after it ends where it starts, so it is closed. Quick mode as picked on screen, and Standard
|
||||
// mode with every object at the command line.
|
||||
let mut s = Session::new();
|
||||
let p = touching(&mut s, false);
|
||||
s.execute("trim", &json!({ "handle": p.hex(), "pick": [6.58, 6.56], "mode": "quick" })).unwrap();
|
||||
expect(&s, p, &[(false, true, &RECT), (true, false, &start), (false, true, &looped)]);
|
||||
let mut s = Session::new();
|
||||
let p = touching(&mut s, false);
|
||||
run(&mut s, "TRIM O S\n\n6.58,6.56\n\n");
|
||||
expect(&s, p, &[(false, true, &RECT), (true, false, &start), (false, true, &looped)]);
|
||||
// Below the touch: cut from the touch to the right side.
|
||||
let mut s = Session::new();
|
||||
let p = touching(&mut s, false);
|
||||
trim(&mut s, p, [7.604, 5.408], None);
|
||||
let end: [Vertex; 4] = [RIGHT, (8.5, 4.4, 0.0), (8.8, 7.8, 0.0), (6.9, 6.2, 0.0)];
|
||||
expect(&s, p, &[(false, true, &RECT), (true, false, &[(2.3, 3.3, 0.0), (5.3, 8.0, 0.0), (6.9, 6.2, 0.0)]), (false, false, &end)]);
|
||||
// The first vertex touching: the closed loop is the piece that keeps the handle.
|
||||
let mut s = Session::new();
|
||||
let p = touching(&mut s, true);
|
||||
trim(&mut s, p, [6.58, 6.56], None);
|
||||
expect(
|
||||
&s,
|
||||
p,
|
||||
&[
|
||||
(false, true, &RECT),
|
||||
(true, true, &[(6.9, 6.2, 0.0), (8.8, 7.8, 0.0), (8.5, 4.4, 0.0)]),
|
||||
(false, false, &[TOP, (5.3, 8.0, 0.0), (2.3, 3.3, 0.0)]),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_piece_keeps_its_arcs() {
|
||||
let mut s = Session::new();
|
||||
pline(&mut s, json!([[3.9, 3.8], [8.3, 3.8], [8.3, 6.9], [3.9, 6.9]]), true);
|
||||
let p = pline(&mut s, json!([[2.3, 3.3], [5.3, 8.0], { "p": [8.5, 4.4], "bulge": 0.3 }, [8.8, 7.8], [6.9, 6.2]]), false);
|
||||
trim(&mut s, p, [6.58, 6.56], None);
|
||||
let looped: [Vertex; 3] = [(6.9, 6.2, 0.0), (8.5, 4.4, 0.3), (8.8, 7.8, 0.0)];
|
||||
expect(&s, p, &[(false, true, &RECT), (true, false, &[(2.3, 3.3, 0.0), (5.3, 8.0, 0.0), TOP]), (false, true, &looped)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
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)])]);
|
||||
}
|
||||
|
||||
// ---------------- a pick on a cut ----------------
|
||||
|
||||
type Edge = ([f64; 2], [f64; 2]);
|
||||
|
||||
/// The polyline `v`, with lines `edges`, trimmed at `pick` with every object as an edge, or only
|
||||
/// the lines when `only_lines`; the polyline's handle and whether the trim was made.
|
||||
fn attempt(v: Value, closed: bool, edges: &[Edge], only_lines: bool, pick: [f64; 2]) -> (Session, Handle, bool) {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, v, closed);
|
||||
let ls: Vec<String> = edges.iter().map(|(a, b)| line(&mut s, *a, *b).hex()).collect();
|
||||
let mut params = json!({ "handle": p.hex(), "pick": pick });
|
||||
if only_lines {
|
||||
params["edges"] = json!(ls);
|
||||
}
|
||||
let made = s.execute("trim", ¶ms).is_ok();
|
||||
(s, p, made)
|
||||
}
|
||||
|
||||
/// [`attempt`] with at most one line, which must trim.
|
||||
fn trimmed(v: Value, closed: bool, edge: Option<Edge>, only_line: bool, pick: [f64; 2]) -> (Session, Handle) {
|
||||
let (s, p, made) = attempt(v, closed, edge.as_slice(), only_line, pick);
|
||||
assert!(made, "{pick:?}");
|
||||
(s, p)
|
||||
}
|
||||
|
||||
/// A vertical line through x = `x`.
|
||||
fn at(x: f64) -> Edge {
|
||||
([x, -5.0], [x, 5.0])
|
||||
}
|
||||
|
||||
#[test]
|
||||
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_cut_by_another_edge_at_the_pick_is_passed_over() {
|
||||
// A pick within 5e-7 of a cut by another edge runs the piece on across it, to the next cut
|
||||
// either side; 6e-7 away the cut holds.
|
||||
let flat = || json!([[0, 0], [10, 0]]);
|
||||
let piece = |a: f64, b: f64| [(a, 0.0, 0.0), (b, 0.0, 0.0)];
|
||||
for pick in [[3.0, 0.0], [3.0000004, 0.0]] {
|
||||
let (s, p, _) = attempt(flat(), false, &[at(3.0), at(7.0)], true, pick);
|
||||
expect(&s, p, &[(true, false, &piece(7.0, 10.0))]);
|
||||
}
|
||||
let (s, p, _) = attempt(flat(), false, &[at(3.0), at(7.0)], true, [3.0000006, 0.0]);
|
||||
expect(&s, p, &[(true, false, &piece(0.0, 3.0)), (false, false, &piece(7.0, 10.0))]);
|
||||
// Lines at 3, 5 and 7: picked on 5, 3 to 7 goes; picked on 7, 5 to the end.
|
||||
let (s, p, _) = attempt(flat(), false, &[at(3.0), at(5.0), at(7.0)], true, [5.0, 0.0]);
|
||||
expect(&s, p, &[(true, false, &piece(0.0, 3.0)), (false, false, &piece(7.0, 10.0))]);
|
||||
let (s, p, _) = attempt(flat(), false, &[at(3.0), at(5.0), at(7.0)], true, [7.0, 0.0]);
|
||||
expect(&s, p, &[(true, false, &piece(0.0, 5.0))]);
|
||||
// Every object an edge: on to the polyline's own vertex (10, 0).
|
||||
let (s, p, _) = attempt(json!([[0, 0], [10, 0], [10, 10]]), false, &[at(5.0)], false, [5.0, 0.0]);
|
||||
expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]);
|
||||
// A closed rectangle cut at x = 30 and 70 top and bottom, picked on the bottom at 30: round
|
||||
// its start vertex, from 30 on the top to 70 on the bottom.
|
||||
let tall = |x: f64| ([x, -5.0], [x, 15.0]);
|
||||
let (s, p, _) = attempt(json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true, &[tall(30.0), tall(70.0)], true, [30.0, 0.0]);
|
||||
expect(&s, p, &[(true, false, &[(70.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (30.0, 10.0, 0.0)])]);
|
||||
// One line only, picked on its cut or 4e-7 past it: no cut is left, and nothing is trimmed.
|
||||
for pick in [[5.0, 0.0], [5.0000004, 0.0]] {
|
||||
let (s, p, made) = attempt(json!([[0, 0], [10, 0], [10, 10]]), false, &[at(5.0)], true, pick);
|
||||
assert!(!made);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]);
|
||||
}
|
||||
// In Quick mode too: the polyline meets the line, so it isn't erased as one no edge crosses.
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], [10, 0]]), false);
|
||||
line(&mut s, [5.0, -5.0], [5.0, 5.0]);
|
||||
assert!(s.execute("trim", &json!({ "handle": p.hex(), "pick": [5, 0], "mode": "quick" })).is_err());
|
||||
expect(&s, p, &[(true, false, &piece(0.0, 10.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. Both
|
||||
// are passed over, so no cut is left and the polyline stays as it was, not split 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, made) = attempt(json!(v), false, &[edge], true, v[1]);
|
||||
let whole: Vec<Vertex> = v.iter().map(|q| (q[0], q[1], 0.0)).collect();
|
||||
assert!(!made);
|
||||
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) that cut is passed
|
||||
// over, which leaves one, and the trim is refused.
|
||||
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, made) = attempt(rect(), true, edge.as_slice(), true, [0.0, 4e-7]);
|
||||
assert!(!made);
|
||||
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::<Vec<_>>());
|
||||
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::<Vec<_>>()), "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]
|
||||
fn a_piece_whose_ends_only_come_near_stays_open_far_from_the_origin() {
|
||||
// 1e9 out, as survey coordinates in millimetres are: the piece left runs from the line's cut
|
||||
// to the polyline's end, 0.58 away, and stays open.
|
||||
let o = 1e9;
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[o + 2.3, 3.3], [o + 5.3, 8.0], [o + 8.5, 4.4], [o + 8.8, 7.8], [o + 7.4, 6.5]]), false);
|
||||
line(&mut s, [o + 6.9, 5.0], [o + 6.9, 7.0]);
|
||||
trim(&mut s, p, [o + 6.1, 7.1], None);
|
||||
let got = polys(&s);
|
||||
assert_eq!(got.len(), 2, "{got:?}");
|
||||
let (h, closed, vs) = &got[1];
|
||||
assert!(*h != p && !closed && vs.len() == 4, "{got:?}");
|
||||
let last = vs[3];
|
||||
assert!((last.0 - (o + 7.4)).abs() < 1e-6 && (last.1 - 6.5).abs() < 1e-6, "{last:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_is_cut_where_a_vertex_of_it_touches_it() {
|
||||
// The vertex (6, 6) lies on the first segment, which is cut there.
|
||||
let v = json!([[0, 0], [10, 10], [12, 4], [6, 6], [4, 12]]);
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, v.clone(), false);
|
||||
trim(&mut s, p, [3.0, 3.0], None);
|
||||
expect(&s, p, &[(true, false, &[(6.0, 6.0, 0.0), (10.0, 10.0, 0.0), (12.0, 4.0, 0.0), (6.0, 6.0, 0.0), (4.0, 12.0, 0.0)])]);
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, v, false);
|
||||
trim(&mut s, p, [8.0, 8.0], None);
|
||||
expect(
|
||||
&s,
|
||||
p,
|
||||
&[
|
||||
(true, false, &[(0.0, 0.0, 0.0), (6.0, 6.0, 0.0)]),
|
||||
(false, false, &[(10.0, 10.0, 0.0), (12.0, 4.0, 0.0), (6.0, 6.0, 0.0), (4.0, 12.0, 0.0)]),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[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<Value> = (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::<Vec<_>>());
|
||||
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)])]);
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
//! BREAKATPOINT at the command line and from a script, with AutoCAD 2024's prompts ("Select
|
||||
//! object:", then "Specify break point:"); BREAK and BREAKATPOINT end the command when a circle
|
||||
//! can't be broken at one point, and refuse an object on a locked layer when it is picked. Measured
|
||||
//! in AutoCAD 2024 (accoreconsole) on these drawings.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn handle(v: &Value) -> Handle {
|
||||
Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The model space objects in order: handle and kind.
|
||||
fn objects(s: &Session) -> Vec<(Handle, EntityKind)> {
|
||||
s.doc().unwrap().model.iter().map(|e| (e.handle, e.kind.clone())).collect()
|
||||
}
|
||||
|
||||
fn line_ends(k: &EntityKind) -> ((f64, f64), (f64, f64)) {
|
||||
let EntityKind::Line(l) = k else { panic!("not a line: {k:?}") };
|
||||
((l.a.x, l.a.y), (l.b.x, l.b.y))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_asks_for_the_object_then_the_point_and_splits_the_line_there() {
|
||||
let mut s = Session::new();
|
||||
let l = handle(&s.execute("line", &json!({ "points": [[1000, 0], [1010, 0]] })).unwrap());
|
||||
s.cmdline("BREAKATPOINT").unwrap();
|
||||
assert!(s.prompt_text().ends_with("Select object:"), "{}", s.prompt_text());
|
||||
s.cmdline("1002,0").unwrap();
|
||||
assert!(s.prompt_text().ends_with("Specify break point:"), "{}", s.prompt_text());
|
||||
// Off the line: the point projects onto it.
|
||||
s.cmdline("1005,3").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 2);
|
||||
assert_eq!(objs[0].0, l);
|
||||
assert_eq!(line_ends(&objs[0].1), ((1000.0, 0.0), (1005.0, 0.0)));
|
||||
assert_eq!(line_ends(&objs[1].1), ((1005.0, 0.0), (1010.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_from_a_script_splits_an_arc_and_a_closed_polyline() {
|
||||
let mut s = Session::new();
|
||||
let a = handle(&s.execute("arc", &json!({ "center": [700, 0], "radius": 10, "start": 0, "end": 90 })).unwrap());
|
||||
let p = handle(&s.execute("pline", &json!({ "vertices": [[250, 0], [270, 0], [270, 20], [250, 20]], "closed": true })).unwrap());
|
||||
s.script("BREAKATPOINT 707.0710678,7.0710678 707.0710678,7.0710678\nBREAKATPOINT 260,0 260,0\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.iter().map(|o| o.0).take(2).collect::<Vec<_>>(), [a, p]);
|
||||
let EntityKind::Arc(arc) = &objs[0].1 else { panic!("not an arc") };
|
||||
assert!((arc.start - 0.0).abs() < 1e-9 && (arc.end.to_degrees() - 45.0).abs() < 1e-6, "{arc:?}");
|
||||
let EntityKind::Arc(rest) = &objs[2].1 else { panic!("not an arc") };
|
||||
assert!((rest.start.to_degrees() - 45.0).abs() < 1e-6 && (rest.end.to_degrees() - 90.0).abs() < 1e-9, "{rest:?}");
|
||||
let pts = |k: &EntityKind| match k {
|
||||
EntityKind::LwPolyline(l) => (l.closed, l.vertices.iter().map(|v| (v.p.x, v.p.y)).collect::<Vec<_>>()),
|
||||
k => panic!("not a polyline: {k:?}"),
|
||||
};
|
||||
assert_eq!(pts(&objs[1].1), (false, vec![(250.0, 0.0), (260.0, 0.0)]));
|
||||
assert_eq!(pts(&objs[3].1), (false, vec![(260.0, 0.0), (270.0, 0.0), (270.0, 20.0), (250.0, 20.0), (250.0, 0.0)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_and_break_at_one_point_of_a_circle_report_it_and_end() {
|
||||
for script in ["BREAKATPOINT 1300,10 1300,10\n", "BREAK 1300,10 1300,10\n"] {
|
||||
let mut s = Session::new();
|
||||
let c = handle(&s.execute("circle", &json!({ "center": [1300, 0], "radius": 10 })).unwrap());
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||
assert!(s.log.iter().any(|l| l == "Arc cannot be full 360 degrees"), "{script}: {:?}", s.log);
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 1);
|
||||
assert!(objs[0].0 == c && matches!(objs[0].1, EntityKind::Circle(_)), "{objs:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_ends_breakatpoint_and_leaves_nothing_selected() {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
s.script("BREAKATPOINT\n\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
// Enter at the break point after picking: the line is not left selected.
|
||||
s.script("BREAKATPOINT 5,0\n\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(s.selection().is_empty());
|
||||
assert_eq!(objects(&s).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_on_a_locked_layer_is_refused_when_picked() {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
s.execute("layer.set", &json!({ "name": "0", "locked": true })).unwrap();
|
||||
for cmd in ["BREAKATPOINT", "BREAK"] {
|
||||
s.cmdline(cmd).unwrap();
|
||||
s.cmdline("5,0").unwrap();
|
||||
assert!(s.prompt_text().ends_with("Select object:"), "{cmd}: {}", s.prompt_text());
|
||||
assert!(s.log.iter().any(|l| l == "The object is on a locked layer."), "{cmd}: {:?}", s.log);
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.running.is_none(), "{cmd}: {}", s.prompt_text());
|
||||
}
|
||||
assert_eq!(objects(&s).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_from_lisp_with_a_bare_entity_name() {
|
||||
let mut s = Session::new();
|
||||
let l = handle(&s.execute("line", &json!({ "points": [[1000, 0], [1010, 0]] })).unwrap());
|
||||
s.cmdline("(command \"_.BREAKATPOINT\" (entlast) '(1004.0 0.0))").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 2);
|
||||
assert_eq!(objs[0].0, l);
|
||||
assert_eq!(line_ends(&objs[0].1), ((1000.0, 0.0), (1004.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_from_lisp_with_an_entity_and_point() {
|
||||
let mut s = Session::new();
|
||||
let l = handle(&s.execute("line", &json!({ "points": [[1000, 0], [1010, 0]] })).unwrap());
|
||||
s.cmdline("(command \"_.BREAKATPOINT\" (list (entlast) '(1005.0 0.0)) '(1005.0 0.0))").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 2);
|
||||
assert_eq!(objs[0].0, l);
|
||||
assert_eq!(line_ends(&objs[0].1), ((1000.0, 0.0), (1005.0, 0.0)));
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
//! Which end of an open polyline EXTEND runs on, as AutoCAD 2024 chooses it (measured with
|
||||
//! accoreconsole on these drawings): the end on the pick's side of the polyline's middle parameter.
|
||||
//! The pick's parameter is the segment it is nearest, counted from 0, plus how far along that
|
||||
//! segment it is; from half the number of segments on, the last end extends, below it the first.
|
||||
//! Neither the end vertex nearer the pick nor the length along the polyline decides.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
type Vertex = (f64, f64, f64);
|
||||
|
||||
fn handle(v: &Value) -> String {
|
||||
v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_owned()
|
||||
}
|
||||
|
||||
/// The open polyline `vertices` with lines `edges`, extended at `pick` to the lines; its vertices
|
||||
/// with their bulges.
|
||||
fn extended(vertices: &[Vertex], edges: &[([f64; 2], [f64; 2])], pick: [f64; 2]) -> Vec<Vertex> {
|
||||
let mut s = Session::new();
|
||||
let vs: Vec<Value> = vertices.iter().map(|(x, y, b)| json!({ "p": [x, y], "bulge": b })).collect();
|
||||
let p = handle(&s.execute("pline", &json!({ "vertices": vs, "closed": false })).unwrap());
|
||||
let es: Vec<String> = edges.iter().map(|(a, b)| handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap())).collect();
|
||||
s.execute("extend", &json!({ "handle": p, "pick": pick, "edges": es })).unwrap();
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(&p).unwrap()).unwrap().kind {
|
||||
EntityKind::LwPolyline(l) => l.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect(),
|
||||
k => panic!("{k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn same(got: &[Vertex], want: &[Vertex]) -> bool {
|
||||
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6 && (g.2 - w.2).abs() < 1e-6)
|
||||
}
|
||||
|
||||
/// Vertical lines through x = `xs`, from `y0` to `y1`.
|
||||
fn at(xs: &[f64], y0: f64, y1: f64) -> Vec<([f64; 2], [f64; 2])> {
|
||||
xs.iter().map(|x| ([*x, y0], [*x, y1])).collect()
|
||||
}
|
||||
|
||||
fn flat(pts: &[(f64, f64)]) -> Vec<Vertex> {
|
||||
pts.iter().map(|(x, y)| (*x, *y, 0.0)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_on_the_picks_side_of_the_middle_parameter_extends() {
|
||||
// (name, vertices, edges, pick, the vertices AutoCAD leaves). Lines at both ends, so either
|
||||
// end could extend.
|
||||
let cases: Vec<(&str, Vec<Vertex>, Vec<([f64; 2], [f64; 2])>, [f64; 2], Vec<(f64, f64)>)> = vec![
|
||||
// 1.2 of 3 segments: the first end, though the pick is on a vertex of the middle one.
|
||||
(
|
||||
"1.2 of 3",
|
||||
flat(&[(0.0, 160.0), (10.0, 160.0), (10.0, 165.0), (20.0, 165.0)]),
|
||||
at(&[-5.0, 25.0], 155.0, 170.0),
|
||||
[10.0, 161.0],
|
||||
vec![(-5.0, 160.0), (10.0, 160.0), (10.0, 165.0), (20.0, 165.0)],
|
||||
),
|
||||
// 0.8: the first end, though the last vertex is nearer the pick.
|
||||
(
|
||||
"0.8, last vertex nearer",
|
||||
flat(&[(0.0, 220.0), (20.0, 220.0), (20.0, 230.0), (15.0, 221.0)]),
|
||||
vec![([-5.0, 215.0], [-5.0, 235.0]), ([0.0, 210.0], [30.0, 210.0])],
|
||||
[16.0, 220.0],
|
||||
vec![(-5.0, 220.0), (20.0, 220.0), (20.0, 230.0), (15.0, 221.0)],
|
||||
),
|
||||
(
|
||||
"0.2",
|
||||
flat(&[(0.0, 240.0), (20.0, 240.0), (20.0, 250.0), (5.0, 241.0)]),
|
||||
vec![([-5.0, 235.0], [-5.0, 255.0]), ([-10.0, 230.0], [30.0, 230.0])],
|
||||
[4.0, 240.0],
|
||||
vec![(-5.0, 240.0), (20.0, 240.0), (20.0, 250.0), (5.0, 241.0)],
|
||||
),
|
||||
(
|
||||
"1.9",
|
||||
flat(&[(0.0, 260.0), (2.0, 260.0), (2.0, 280.0), (4.0, 280.0)]),
|
||||
at(&[-5.0, 10.0], 255.0, 285.0),
|
||||
[2.0, 278.0],
|
||||
vec![(0.0, 260.0), (2.0, 260.0), (2.0, 280.0), (10.0, 280.0)],
|
||||
),
|
||||
// 0.9: the first end, though 18 of the 22 units along is nearer the last.
|
||||
(
|
||||
"0.9, length nearer the last",
|
||||
flat(&[(0.0, 300.0), (20.0, 300.0), (20.0, 301.0), (21.0, 301.0)]),
|
||||
at(&[-5.0, 25.0], 295.0, 305.0),
|
||||
[18.0, 300.0],
|
||||
vec![(-5.0, 300.0), (20.0, 300.0), (20.0, 301.0), (21.0, 301.0)],
|
||||
),
|
||||
(
|
||||
"1.1",
|
||||
flat(&[(0.0, 320.0), (2.0, 320.0), (2.0, 340.0), (4.0, 340.0)]),
|
||||
at(&[-5.0, 10.0], 315.0, 345.0),
|
||||
[2.0, 322.0],
|
||||
vec![(-5.0, 320.0), (2.0, 320.0), (2.0, 340.0), (4.0, 340.0)],
|
||||
),
|
||||
(
|
||||
"1.25",
|
||||
flat(&[(0.0, 400.0), (30.0, 400.0), (30.0, 420.0), (31.0, 420.0)]),
|
||||
at(&[-5.0, 40.0], 395.0, 425.0),
|
||||
[30.0, 405.0],
|
||||
vec![(-5.0, 400.0), (30.0, 400.0), (30.0, 420.0), (31.0, 420.0)],
|
||||
),
|
||||
(
|
||||
"1.75",
|
||||
flat(&[(0.0, 440.0), (1.0, 440.0), (1.0, 460.0), (31.0, 460.0)]),
|
||||
at(&[-5.0, 40.0], 435.0, 465.0),
|
||||
[1.0, 455.0],
|
||||
vec![(0.0, 440.0), (1.0, 440.0), (1.0, 460.0), (40.0, 460.0)],
|
||||
),
|
||||
("0.6 of 1", flat(&[(0.0, 480.0), (20.0, 480.0)]), at(&[-5.0, 25.0], 475.0, 485.0), [12.0, 480.0], vec![(0.0, 480.0), (25.0, 480.0)]),
|
||||
// 1.8 of 4, the end of the segment picked: the first end.
|
||||
(
|
||||
"1.8 of 4",
|
||||
flat(&[(0.0, 500.0), (10.0, 500.0), (10.0, 510.0), (20.0, 510.0), (20.0, 520.0)]),
|
||||
vec![([-5.0, 495.0], [-5.0, 525.0]), ([15.0, 530.0], [25.0, 530.0])],
|
||||
[10.0, 508.0],
|
||||
vec![(-5.0, 500.0), (10.0, 500.0), (10.0, 510.0), (20.0, 510.0), (20.0, 520.0)],
|
||||
),
|
||||
(
|
||||
"2.8 of 4",
|
||||
flat(&[(0.0, 540.0), (10.0, 540.0), (10.0, 550.0), (20.0, 550.0), (20.0, 560.0)]),
|
||||
vec![([-5.0, 535.0], [-5.0, 565.0]), ([15.0, 570.0], [25.0, 570.0])],
|
||||
[18.0, 550.0],
|
||||
vec![(0.0, 540.0), (10.0, 540.0), (10.0, 550.0), (20.0, 550.0), (20.0, 570.0)],
|
||||
),
|
||||
// Right on the middle parameter, 1.5 of 3: the last end.
|
||||
(
|
||||
"1.5 of 3",
|
||||
flat(&[(0.0, 600.0), (10.0, 600.0), (10.0, 610.0), (20.0, 610.0)]),
|
||||
at(&[-5.0, 25.0], 595.0, 615.0),
|
||||
[10.0, 605.0],
|
||||
vec![(0.0, 600.0), (10.0, 600.0), (10.0, 610.0), (25.0, 610.0)],
|
||||
),
|
||||
];
|
||||
for (name, vertices, edges, pick, want) in cases {
|
||||
let got = extended(&vertices, &edges, pick);
|
||||
assert!(same(&got, &flat(&want)), "{name}: {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parameter_runs_along_an_arc_segment_too() {
|
||||
// The middle segment an arc of bulge -18, swinging round to within 2 of the first vertex:
|
||||
// picked 60% along it (1.6 of 3), 3.6 from the first vertex and 18.3 from the last, the last
|
||||
// end extends.
|
||||
let got = extended(
|
||||
&[(0.0, 0.0, 0.0), (10.0, 0.0, -18.0), (10.0, 1.0, 0.0), (20.0, 1.0, 0.0)],
|
||||
&at(&[-5.0, 25.0], -10.0, 10.0),
|
||||
[1.804081304825758, 3.0714821777453793],
|
||||
);
|
||||
assert!(same(&got, &[(0.0, 0.0, 0.0), (10.0, 0.0, -18.0), (10.0, 1.0, 0.0), (25.0, 1.0, 0.0)]), "{got:?}");
|
||||
// The end segment an arc of bulge -0.5: picked on it (1.6 of 2) the last end runs on round
|
||||
// its circle to x = 14.3; the same polyline turned round, picked on its first segment (0.4),
|
||||
// the first end does.
|
||||
let got = extended(&[(0.0, 40.0, 0.0), (10.0, 40.0, -0.5), (14.0, 40.0, 0.0)], &at(&[14.3], 30.0, 50.0), [12.0, 41.0]);
|
||||
assert!(same(&got, &[(0.0, 40.0, 0.0), (10.0, 40.0, -0.5776771824075506), (14.3, 39.47979589711327, 0.0)]), "{got:?}");
|
||||
let got = extended(&[(0.0, 60.0, -0.5), (4.0, 60.0, 0.0), (14.0, 60.0, 0.0)], &at(&[-0.3], 50.0, 70.0), [2.0, 61.0]);
|
||||
assert!(same(&got, &[(-0.3, 59.47979589711327, -0.5776771824075504), (4.0, 60.0, 0.0), (14.0, 60.0, 0.0)]), "{got:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeated_vertex_counts_as_a_segment() {
|
||||
// (10, 0) twice: three segments, the middle one of no length. Picked on (10, 0), the end of
|
||||
// the first, 1.0 of 3: the first end extends (counting two segments it would be the last).
|
||||
// Picked 1 up the last segment, 2.1 of 3: the last end.
|
||||
let vs = flat(&[(0.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 10.0)]);
|
||||
let edges = vec![([-5.0, -10.0], [-5.0, 10.0]), ([-10.0, 15.0], [20.0, 15.0])];
|
||||
let got = extended(&vs, &edges, [10.0, 0.0]);
|
||||
assert!(same(&got, &flat(&[(-5.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 10.0)])), "{got:?}");
|
||||
let got = extended(&vs, &edges, [10.0, 1.0]);
|
||||
assert!(same(&got, &flat(&[(0.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 15.0)])), "{got:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_a_hair_outside_an_arc_end_counts_as_that_end() {
|
||||
// A single semicircle from (1, 0) to (-1, 0). Picked 1e-13 outside its sweep at the first
|
||||
// vertex, the pick is on the arc's start, not round the circle at its end: the first end runs
|
||||
// on to x = 0, three quarters of the way round.
|
||||
let b = 1.0 + 2f64.sqrt();
|
||||
let got = extended(&[(1.0, 0.0, 1.0), (-1.0, 0.0, 0.0)], &at(&[0.0], -2.0, -0.5), [1.0, -1e-13]);
|
||||
assert!(same(&got, &[(0.0, -1.0, b), (-1.0, 0.0, 0.0)]), "{got:?}");
|
||||
// A hair past its end is the last end.
|
||||
let got = extended(&[(1.0, 0.0, 1.0), (-1.0, 0.0, 0.0)], &at(&[0.0], -2.0, -0.5), [-1.0, -1e-13]);
|
||||
assert!(same(&got, &[(1.0, 0.0, b), (0.0, -1.0, 0.0)]), "{got:?}");
|
||||
// Turning clockwise, the arc's start angle is the polyline's last vertex: a hair outside it is
|
||||
// the last end.
|
||||
let got = extended(&[(1.0, 0.0, -1.0), (-1.0, 0.0, 0.0)], &at(&[0.0], 0.5, 2.0), [-1.0, 1e-13]);
|
||||
assert!(same(&got, &[(1.0, 0.0, -b), (0.0, 1.0, 0.0)]), "{got:?}");
|
||||
}
|
||||
@@ -17,12 +17,9 @@ mod block_keep;
|
||||
mod block_redefine;
|
||||
mod blockreplace;
|
||||
mod break_closed_polyline;
|
||||
mod break_ends_and_closing_side;
|
||||
mod break_join_locked_layers;
|
||||
mod break_keeps_z;
|
||||
mod break_trim_keep_handle;
|
||||
mod break_trim_polyline_rules;
|
||||
mod breakatpoint_command_line;
|
||||
mod burst;
|
||||
mod change_command;
|
||||
mod chprop_command;
|
||||
@@ -55,7 +52,6 @@ mod dynamic_block_data;
|
||||
mod dynamic_grips;
|
||||
mod explode_stretched;
|
||||
mod extend_polyline_arc_end;
|
||||
mod extend_polyline_end_choice;
|
||||
mod fillet_chamfer;
|
||||
mod fix_holds_grips;
|
||||
mod followups_626;
|
||||
@@ -174,11 +170,7 @@ mod text_left_justify;
|
||||
mod tolerance;
|
||||
mod transparent;
|
||||
mod trim_closed_polyline;
|
||||
mod trim_cut_at_the_pick;
|
||||
mod trim_cut_where_an_arc_span_starts;
|
||||
mod trim_extend_json_pick;
|
||||
mod trim_extend_options;
|
||||
mod trim_keeps_z_and_width;
|
||||
mod undo_count;
|
||||
mod undo_layout_tab;
|
||||
mod viewport_clip;
|
||||
|
||||
@@ -123,13 +123,11 @@ fn undo_restores_the_closed_polyline() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
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."
|
||||
fn a_single_cut_still_opens_the_outline_there() {
|
||||
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());
|
||||
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)])]);
|
||||
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())]);
|
||||
}
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
//! TRIM of a line, an arc or a circle picked on a cut, as AutoCAD 2024 does it (measured with
|
||||
//! accoreconsole on these drawings): a cut within 5e-7 of the pick, along the object, is passed
|
||||
//! over, and the piece runs on across it to the next cut either side. With no cut left, nothing is
|
||||
//! trimmed.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn handle(v: &Value) -> Handle {
|
||||
Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// Vertical lines through x = `xs`, from y = -15 to 15; their handles.
|
||||
fn edges(s: &mut Session, xs: &[f64]) -> Vec<String> {
|
||||
xs.iter().map(|x| handle(&s.execute("line", &json!({ "points": [[x, -15], [x, 15]] })).unwrap()).hex()).collect()
|
||||
}
|
||||
|
||||
/// Every object but the edges: lines as their ends, arcs and circles as their angles in degrees.
|
||||
fn shapes(s: &Session, edges: &[String]) -> Vec<(Handle, Vec<f64>)> {
|
||||
let r = |v: f64| (v * 1e9).round() / 1e9;
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.filter(|e| !edges.contains(&e.handle.hex()))
|
||||
.map(|e| {
|
||||
let v = match &e.kind {
|
||||
EntityKind::Line(l) => vec![l.a.x, l.a.y, l.b.x, l.b.y],
|
||||
EntityKind::Arc(a) => vec![a.start.to_degrees(), a.end.to_degrees()],
|
||||
EntityKind::Circle(_) => Vec::new(),
|
||||
k => panic!("{k:?}"),
|
||||
};
|
||||
(e.handle, v.into_iter().map(r).collect())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Trim `h` at `pick` with `edges`: whether the trim was made.
|
||||
fn trim(s: &mut Session, h: Handle, pick: [f64; 2], edges: &[String]) -> bool {
|
||||
s.execute("trim", &json!({ "handle": h.hex(), "pick": pick, "edges": edges })).is_ok()
|
||||
}
|
||||
|
||||
/// A line from (0, 0) to (10, 0) with vertical lines through `xs`, trimmed at `pick`.
|
||||
fn line_trimmed(xs: &[f64], pick: [f64; 2]) -> (bool, Vec<(Handle, Vec<f64>)>, Handle) {
|
||||
let mut s = Session::new();
|
||||
let h = handle(&s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap());
|
||||
let es = edges(&mut s, xs);
|
||||
let made = trim(&mut s, h, pick, &es);
|
||||
(made, shapes(&s, &es), h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_picked_on_its_only_cut_is_left_as_it_was() {
|
||||
for pick in [[5.0, 0.0], [5.0000004, 0.0], [4.9999996, 0.0]] {
|
||||
let (made, got, h) = line_trimmed(&[5.0], pick);
|
||||
assert!(!made, "{pick:?}");
|
||||
assert_eq!(got, vec![(h, vec![0.0, 0.0, 10.0, 0.0])], "{pick:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_picked_on_one_of_two_cuts_loses_the_pieces_both_sides() {
|
||||
// Cuts at x = 3 and 7: on 3, 0 to 7 goes; 4e-7 past 7, 3 to the end; between them, 3 to 7.
|
||||
let (_, got, h) = line_trimmed(&[3.0, 7.0], [3.0, 0.0]);
|
||||
assert_eq!(got, vec![(h, vec![7.0, 0.0, 10.0, 0.0])]);
|
||||
let (_, got, h) = line_trimmed(&[3.0, 7.0], [7.0000004, 0.0]);
|
||||
assert_eq!(got, vec![(h, vec![0.0, 0.0, 3.0, 0.0])]);
|
||||
let (_, got, h) = line_trimmed(&[3.0, 7.0], [5.0, 0.0]);
|
||||
assert_eq!(got.len(), 2);
|
||||
assert_eq!(got[0], (h, vec![0.0, 0.0, 3.0, 0.0]));
|
||||
assert_eq!(got[1].1, vec![7.0, 0.0, 10.0, 0.0]);
|
||||
}
|
||||
|
||||
/// An arc of radius 10 about the origin from 0 to 180 degrees, with vertical lines through `xs`,
|
||||
/// trimmed at `pick`.
|
||||
fn arc_trimmed(xs: &[f64], pick: [f64; 2]) -> (bool, Vec<(Handle, Vec<f64>)>, Handle) {
|
||||
let mut s = Session::new();
|
||||
let h = handle(&s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 180 })).unwrap());
|
||||
let es = edges(&mut s, xs);
|
||||
let made = trim(&mut s, h, pick, &es);
|
||||
(made, shapes(&s, &es), h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arc_picked_on_its_only_cut_is_left_as_it_was() {
|
||||
// The line x = 0 cuts it at 90 degrees: on the cut and 4e-7 along from it nothing is trimmed,
|
||||
// 6e-7 along the arc from 90 to 180 goes.
|
||||
for pick in [[0.0, 10.0], [-4e-7, 10.0]] {
|
||||
let (made, got, h) = arc_trimmed(&[0.0], pick);
|
||||
assert!(!made, "{pick:?}");
|
||||
assert_eq!(got, vec![(h, vec![0.0, 180.0])], "{pick:?}");
|
||||
}
|
||||
let (_, got, h) = arc_trimmed(&[0.0], [-6e-7, 10.0]);
|
||||
assert_eq!(got, vec![(h, vec![0.0, 90.0])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arc_picked_on_its_last_cut_loses_the_rest() {
|
||||
// Cuts at 60 and 120 degrees, picked on 120: from 60 to the end goes.
|
||||
let (_, got, h) = arc_trimmed(&[5.0, -5.0], [-5.0, 75f64.sqrt()]);
|
||||
assert_eq!(got, vec![(h, vec![0.0, 60.0])]);
|
||||
}
|
||||
|
||||
/// A circle of radius 10 about the origin, with vertical lines through `xs`, trimmed at `pick`.
|
||||
fn circle_trimmed(xs: &[f64], pick: [f64; 2]) -> (bool, Vec<(Handle, Vec<f64>)>, Handle) {
|
||||
let mut s = Session::new();
|
||||
let h = handle(&s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap());
|
||||
let es = edges(&mut s, xs);
|
||||
let made = trim(&mut s, h, pick, &es);
|
||||
(made, shapes(&s, &es), h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_picked_on_a_cut_loses_the_arcs_both_sides() {
|
||||
// Lines at x = 5 and -5 cut it at 60, 120, 240 and 300 degrees. Picked on 60, and 4e-7 along
|
||||
// from it, the arc from 300 round to 120 goes; picked at 90, the arc from 60 to 120.
|
||||
let y = 75f64.sqrt();
|
||||
for pick in [[5.0, y], [4.9999998, y + 2e-7 * 5.0 / y]] {
|
||||
let (_, got, h) = circle_trimmed(&[5.0, -5.0], pick);
|
||||
assert_eq!(got, vec![(h, vec![120.0, 300.0])], "{pick:?}");
|
||||
}
|
||||
let (_, got, h) = circle_trimmed(&[5.0, -5.0], [0.0, 10.0]);
|
||||
assert_eq!(got, vec![(h, vec![120.0, 60.0])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_picked_on_one_of_two_cuts_is_left_as_it_was() {
|
||||
// One line, cutting it at 60 and 300 degrees: picked on 60, one cut is left and the trim is
|
||||
// refused.
|
||||
let (made, got, h) = circle_trimmed(&[5.0], [5.0, 75f64.sqrt()]);
|
||||
assert!(!made);
|
||||
assert_eq!(got, vec![(h, Vec::new())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_mode_leaves_an_object_picked_on_its_only_cut() {
|
||||
// The line, the arc and the circle each meet the edges, at the pick, so Quick mode doesn't
|
||||
// erase them as objects no edge crosses.
|
||||
let y = 75f64.sqrt();
|
||||
let cases = [
|
||||
("line", json!({ "points": [[0, 0], [10, 0]] }), 5.0, [5.0, 0.0]),
|
||||
("arc", json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 180 }), 0.0, [0.0, 10.0]),
|
||||
("circle", json!({ "center": [0, 0], "radius": 10 }), 5.0, [5.0, y]),
|
||||
];
|
||||
for (cmd, shape, x, pick) in cases {
|
||||
let mut s = Session::new();
|
||||
let h = handle(&s.execute(cmd, &shape).unwrap());
|
||||
let es = edges(&mut s, &[x]);
|
||||
let r = s.execute("trim", &json!({ "handle": h.hex(), "pick": pick, "mode": "quick" }));
|
||||
assert!(r.is_err(), "{cmd}");
|
||||
assert!(s.doc().unwrap().entity(h).is_some(), "{cmd} was erased");
|
||||
assert_eq!(shapes(&s, &es).len(), 1, "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arc_picked_just_off_one_end_loses_the_piece_at_that_end() {
|
||||
// From 0 to 90 degrees, cut at 45: picked just before its start the piece from 0 goes, just
|
||||
// past its end the piece to 90.
|
||||
let x = 10.0 * std::f64::consts::FRAC_PI_4.cos();
|
||||
let trimmed = |pick: [f64; 2]| {
|
||||
let mut s = Session::new();
|
||||
let h = handle(&s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 90 })).unwrap());
|
||||
let es = edges(&mut s, &[x]);
|
||||
assert!(trim(&mut s, h, pick, &es));
|
||||
shapes(&s, &es)
|
||||
};
|
||||
assert_eq!(trimmed([10.0, -0.01])[0].1, vec![45.0, 90.0]);
|
||||
assert_eq!(trimmed([-0.01, 10.0])[0].1, vec![0.0, 45.0]);
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
//! TRIM on a polyline cut through the vertex where an arc span starts: the cut is at that vertex
|
||||
//! only. Where the crossing came out a hair before the arc's start angle it was also put at the
|
||||
//! arc's far end, round the circle, and TRIM took out the arc alone.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
use serde_json::json;
|
||||
|
||||
fn handle(v: serde_json::Value) -> String {
|
||||
v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cut_is_at_the_arc_spans_start_vertex_only() {
|
||||
// (0, 0) to (10, 0), a semicircle round (15, 5) to (10, 10), then on to (0, 10). A line
|
||||
// through (10, 0) running up to the left crosses the top span at x = 10 + 10 cot(angle);
|
||||
// picked on the arc, the polyline goes from (10, 0) to there.
|
||||
for k in 0..172 {
|
||||
let th = (91.0 + f64::from(k) * 0.25).to_radians();
|
||||
let d = [th.cos() * 30.0, th.sin() * 30.0];
|
||||
let mut s = Session::new();
|
||||
let p = handle(s.execute("pline", &json!({ "vertices": [[0, 0], { "p": [10, 0], "bulge": 1 }, [10, 10], [0, 10]] })).unwrap());
|
||||
let e = handle(s.execute("line", &json!({ "points": [[10.0 - d[0], -d[1]], [10.0 + d[0], d[1]]] })).unwrap());
|
||||
s.execute("trim", &json!({ "handle": p, "pick": [15, 5], "edges": [e] })).unwrap();
|
||||
let pieces: Vec<Vec<(f64, f64)>> = s
|
||||
.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::LwPolyline(l) => Some(l.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let x = 10.0 + 10.0 / th.tan();
|
||||
let near = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6;
|
||||
let ok = pieces.len() == 2
|
||||
&& pieces.iter().any(|v| v.len() == 2 && near(v[0], (0.0, 0.0)) && near(v[1], (10.0, 0.0)))
|
||||
&& pieces.iter().any(|v| v.len() == 2 && near(v[0], (x, 10.0)) && near(v[1], (0.0, 10.0)));
|
||||
assert!(ok, "{:.2} degrees: {pieces:?}", th.to_degrees());
|
||||
}
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
//! JSON execute pick roles and diagnostic-only refusals (#2750).
|
||||
|
||||
use cadcraft_doc::{Common, EntityKind, Handle, Line, Space};
|
||||
use cadcraft_engine::{Session, find_command};
|
||||
use cadcraft_geom::Vec3;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
type TestResult<T = ()> = Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
fn fixture(end: f64, edge_x: f64) -> TestResult<(Session, Handle, Handle)> {
|
||||
let mut s = Session::new();
|
||||
let a = s.doc_mut()?.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(end, 0.0, 0.0) }))?;
|
||||
let b = s.doc_mut()?.add(
|
||||
&Space::Model,
|
||||
Common::default(),
|
||||
EntityKind::Line(Line { a: Vec3::new(edge_x, -20.0, 0.0), b: Vec3::new(edge_x, 20.0, 0.0) }),
|
||||
)?;
|
||||
Ok((s, a, b))
|
||||
}
|
||||
|
||||
fn assert_line(s: &Session, h: Handle, start: f64, end: f64) -> TestResult {
|
||||
let e = s.doc()?.entity(h).ok_or("line missing")?;
|
||||
let EntityKind::Line(l) = &e.kind else { return Err("expected line".into()) };
|
||||
assert_eq!((l.a, l.b), (Vec3::new(start, 0.0, 0.0), Vec3::new(end, 0.0, 0.0)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn failure(s: &mut Session, cmd: &str, params: Value, message: &str) -> TestResult {
|
||||
let before = s.doc()?.clone();
|
||||
let selection = s.state()?.selection.clone();
|
||||
let error = s.execute(cmd, ¶ms).err().ok_or("expected refusal")?;
|
||||
assert_eq!(error.to_string(), message);
|
||||
assert_eq!(s.doc()?, &before, "a failed JSON call must leave the whole drawing unchanged");
|
||||
assert_eq!(s.state()?.selection, selection);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_execute_pick_selects_the_portion_to_remove() -> TestResult {
|
||||
// Off-object picks that already succeed by projection remain accepted.
|
||||
for (pick, start, end) in [([5, 0], 25.0, 50.0), ([40, 0], 0.0, 25.0), ([5, 3], 25.0, 50.0)] {
|
||||
let (mut s, a, b) = fixture(50.0, 25.0)?;
|
||||
let boundary = s.doc()?.entity(b).cloned().ok_or("boundary missing")?;
|
||||
let result = s.execute("trim", &json!({"handle": a.hex(), "edges": [b.hex()], "pick": pick}))?;
|
||||
let handles = result["handles"].as_array().ok_or("expected handles")?;
|
||||
assert_eq!(handles.len(), 1);
|
||||
let h = handles.first().and_then(Value::as_str).and_then(Handle::parse_hex).ok_or("expected trimmed handle")?;
|
||||
assert_eq!(h, a, "TRIM keeps the original handle on the surviving piece");
|
||||
assert_line(&s, h, start, end)?;
|
||||
assert_eq!(s.doc()?.entity(b), Some(&boundary));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extend_execute_pick_selects_the_end_toward_the_boundary() -> TestResult {
|
||||
for pick in [[25, 10], [25, -15], [19, 0], [40, 0]] {
|
||||
let (mut s, a, b) = fixture(20.0, 25.0)?;
|
||||
let boundary = s.doc()?.entity(b).cloned().ok_or("boundary missing")?;
|
||||
let result = s.execute("extend", &json!({"handle": a.hex(), "edges": [b.hex()], "pick": pick}))?;
|
||||
assert_eq!(result, Value::Null);
|
||||
assert_line(&s, a, 0.0, 25.0)?;
|
||||
assert_eq!(s.doc()?.entity(b), Some(&boundary));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_execute_distinguishes_picks_at_or_projecting_onto_a_cut_from_no_cut() -> TestResult {
|
||||
let (mut s, a, b) = fixture(50.0, 25.0)?;
|
||||
for (pick, message) in [
|
||||
([25, 10], "The `pick` point is off the line and projects onto a cutting intersection; pick away from that intersection."),
|
||||
([25, 0], "The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection."),
|
||||
] {
|
||||
failure(&mut s, "trim", json!({"handle": a.hex(), "edges": [b.hex()], "pick": pick, "mode": "standard"}), message)?;
|
||||
}
|
||||
let (mut s, a, b) = fixture(50.0, 75.0)?;
|
||||
failure(
|
||||
&mut s,
|
||||
"trim",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [5, 0]}),
|
||||
"No usable cutting-edge intersection in the interior of the object to trim.",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extend_execute_distinguishes_the_wrong_end_from_no_boundary_hit() -> TestResult {
|
||||
let (mut s, a, b) = fixture(20.0, 25.0)?;
|
||||
failure(
|
||||
&mut s,
|
||||
"extend",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [10, 0]}),
|
||||
"The `pick` point selects an end with no boundary ahead; choose `pick` toward the boundary to extend to.",
|
||||
)?;
|
||||
s.doc_mut()?.modify_entity(b, |e| {
|
||||
e.kind = EntityKind::Line(Line { a: Vec3::new(0.0, 20.0, 0.0), b: Vec3::new(25.0, 20.0, 0.0) });
|
||||
})?;
|
||||
failure(
|
||||
&mut s,
|
||||
"extend",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [25, 20]}),
|
||||
"No usable boundary intersection was found for either end of the object to extend.",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_erasure_and_unrelated_errors_keep_their_behavior() -> TestResult {
|
||||
let (mut s, a, b) = fixture(50.0, 25.0)?;
|
||||
// Quick mode leaves a line picked on its only cut in place (#2648), and the JSON form explains
|
||||
// the refusal as Standard mode does.
|
||||
failure(
|
||||
&mut s,
|
||||
"trim",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [25, 0], "mode": "quick"}),
|
||||
"The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection.",
|
||||
)?;
|
||||
assert!(s.doc()?.entity(a).is_some());
|
||||
assert!(s.doc()?.entity(b).is_some());
|
||||
failure(&mut s, "trim", json!({"handle": "DEAD", "pick": [5, 0]}), "no such object")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_contracts_and_missing_pick_errors_explain_the_roles() -> TestResult {
|
||||
let trim = find_command("trim").ok_or("trim not registered")?;
|
||||
assert!(trim.params.contains("pick selects the portion of that object to remove"));
|
||||
assert!(trim.params.contains("edges are the cutting edges"));
|
||||
let extend = find_command("extend").ok_or("extend not registered")?;
|
||||
assert!(extend.params.contains("pick points toward the boundary to extend to"));
|
||||
assert!(extend.params.contains("selecting the nearer end"));
|
||||
assert!(extend.params.contains("edges are the boundary edges"));
|
||||
let (mut s, a, b) = fixture(20.0, 25.0)?;
|
||||
failure(
|
||||
&mut s,
|
||||
"trim",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()]}),
|
||||
"invalid parameters for `trim`: `pick` ([x, y]) is required: select the portion of the object to trim away",
|
||||
)?;
|
||||
failure(
|
||||
&mut s,
|
||||
"extend",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()]}),
|
||||
"invalid parameters for `extend`: `pick` ([x, y]) is required: point toward the boundary to extend to, selecting the nearer end",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_on_the_line_far_from_the_origin_is_not_called_off_the_line() -> TestResult {
|
||||
// Survey coordinates: rounding there is far above 1e-9 (the pick below is 3.7e-9 off the line
|
||||
// after rounding), so a pick on the line still reads as on it.
|
||||
let (x0, y0, k) = (123_456_789.1, 9_876_543.3, 33.3333);
|
||||
let mut s = Session::new();
|
||||
let a = s.doc_mut()?.add(
|
||||
&Space::Model,
|
||||
Common::default(),
|
||||
EntityKind::Line(Line { a: Vec3::new(x0, y0, 0.0), b: Vec3::new(x0 + 50.0, y0 + 30.0, 0.0) }),
|
||||
)?;
|
||||
let b = s.doc_mut()?.add(
|
||||
&Space::Model,
|
||||
Common::default(),
|
||||
EntityKind::Line(Line { a: Vec3::new(x0 + k, y0 - 20.0, 0.0), b: Vec3::new(x0 + k, y0 + 50.0, 0.0) }),
|
||||
)?;
|
||||
failure(
|
||||
&mut s,
|
||||
"trim",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [x0 + k, y0 + k * 0.6]}),
|
||||
"The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection.",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_extend_contract_names_the_polyline_end_rule() -> TestResult {
|
||||
// An open polyline extends the end on the pick's side of its middle parameter (#2693), not
|
||||
// the nearer end.
|
||||
let extend = find_command("extend").ok_or("extend not registered")?;
|
||||
assert!(extend.params.contains("middle"), "{}", extend.params);
|
||||
Ok(())
|
||||
}
|
||||
@@ -112,33 +112,10 @@ fn crossing_window_trims_what_it_touches() {
|
||||
s.script("TRIM C 4,-1 6,1\n\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), with_edges(&[((-5.0, 0.0), (0.0, 0.0)), ((-5.0, 2.0), (15.0, 2.0)), ((10.0, 0.0), (15.0, 0.0))]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_in_empty_space_starts_a_fence_in_quick_mode_and_a_window_in_standard_mode() {
|
||||
// #1594: Quick mode's two-point fence trims what it crosses and returns to the first prompt.
|
||||
for cmd in ["TRIM", "EXTEND"] {
|
||||
let mut s = ladder();
|
||||
s.cmdline(cmd).unwrap();
|
||||
s.cmdline("4,-4").unwrap();
|
||||
assert!(s.prompt_text().contains("Specify next fence point"), "{cmd}: {}", s.prompt_text());
|
||||
}
|
||||
// A pick in empty space opens a crossing window too.
|
||||
let mut s = ladder();
|
||||
s.script("TRIM 4,-4 6,1\n").unwrap();
|
||||
assert!(s.prompt_text().contains("Select object to trim"), "{}", s.prompt_text());
|
||||
s.cmdline("").unwrap();
|
||||
s.script("TRIM 4,-4 6,1\n\n").unwrap();
|
||||
assert_eq!(lines(&s), with_edges(&[((-5.0, 0.0), (0.0, 0.0)), ((-5.0, 2.0), (15.0, 2.0)), ((10.0, 0.0), (15.0, 0.0))]));
|
||||
// EXTEND's fence extends both lines it crosses to the boundary at x = 10.
|
||||
let mut s = session(&["10,-5 10,5", "0,0 4,0", "0,2 4,2"]);
|
||||
s.script("EXTEND 3,-1 3,3\n").unwrap();
|
||||
assert!(s.prompt_text().contains("Select object to extend"), "{}", s.prompt_text());
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), vec![((0.0, 0.0), (10.0, 0.0)), ((0.0, 2.0), (10.0, 2.0)), ((10.0, -5.0), (10.0, 5.0))]);
|
||||
// Standard mode keeps the crossing window.
|
||||
let mut s = ladder();
|
||||
s.script("TRIM O S\n\n4,-4\n").unwrap();
|
||||
assert!(s.prompt_text().contains("Specify opposite corner"), "{}", s.prompt_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
//! TRIM keeps what the object has beyond its outline, as BREAK does: a line's Z, an arc's centre
|
||||
//! Z (a circle trimmed into an arc), a polyline's elevation, and a polyline's constant width on
|
||||
//! every piece. The Z cases and the width on BREAK were measured in AutoCAD 2024 (accoreconsole)
|
||||
//! on these drawings.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Circle, Common, Entity, EntityKind, Handle, Line, LwPolyline};
|
||||
use cadcraft_engine::geom::{PolyVertex, Vec2, Vec3};
|
||||
use serde_json::json;
|
||||
|
||||
fn add(s: &mut Session, kind: EntityKind, thickness: f64) -> Handle {
|
||||
let space = s.space();
|
||||
let d = s.doc_mut().unwrap();
|
||||
let handle = d.new_handle();
|
||||
d.space_mut(&space).unwrap().push(Entity { handle, common: Common { thickness, ..Common::default() }, kind });
|
||||
handle
|
||||
}
|
||||
|
||||
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
|
||||
let v = s.execute("line", &json!({ "points": [a, b] })).unwrap();
|
||||
Handle::parse_hex(v["handles"][0].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn trim(s: &mut Session, h: Handle, pick: [f64; 2], edge: Handle) {
|
||||
s.execute("trim", &json!({ "handle": h.hex(), "pick": pick, "edges": [edge.hex()] })).unwrap();
|
||||
}
|
||||
|
||||
fn kind(s: &Session, h: Handle) -> EntityKind {
|
||||
s.doc().unwrap().entity(h).unwrap().kind.clone()
|
||||
}
|
||||
|
||||
fn polyline(vertices: &[(f64, f64, f64)], const_width: f64, elevation: f64, plinegen: bool) -> EntityKind {
|
||||
let vertices = vertices.iter().map(|&(x, y, bulge)| PolyVertex { bulge, ..PolyVertex::new(Vec2::new(x, y)) }).collect();
|
||||
EntityKind::LwPolyline(LwPolyline { vertices, closed: false, const_width, elevation, plinegen })
|
||||
}
|
||||
|
||||
fn near(a: Vec3, b: Vec3, tol: f64) -> bool {
|
||||
(a.x - b.x).abs() < tol && (a.y - b.y).abs() < tol && (a.z - b.z).abs() < tol
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_keeps_a_lines_z() {
|
||||
let mut s = Session::new();
|
||||
let a = add(&mut s, EntityKind::Line(Line { a: Vec3::new(0.5, 0.25, 0.007), b: Vec3::new(0.54, 0.25, 0.007) }), 0.0);
|
||||
let b = line(&mut s, [0.52, 0.24], [0.52, 0.26]);
|
||||
trim(&mut s, a, [0.53, 0.25], b);
|
||||
let EntityKind::Line(l) = kind(&s, a) else { panic!("not a line") };
|
||||
assert!(near(l.a, Vec3::new(0.5, 0.25, 0.007), 1e-12) && near(l.b, Vec3::new(0.52, 0.25, 0.007), 1e-12), "{l:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_keeps_the_centre_z_of_a_circle_made_an_arc() {
|
||||
// At survey coordinates, with a thickness of 2.
|
||||
let mut s = Session::new();
|
||||
let c = add(&mut s, EntityKind::Circle(Circle { center: Vec3::new(612345.678, 2398765.432, 5.0), radius: 10.0 }), 2.0);
|
||||
let b = line(&mut s, [612350.678, 2398745.432], [612350.678, 2398785.432]);
|
||||
trim(&mut s, c, [612335.678, 2398765.432], b);
|
||||
let e = s.doc().unwrap().entity(c).unwrap().clone();
|
||||
let EntityKind::Arc(a) = &e.kind else { panic!("not an arc: {:?}", e.kind) };
|
||||
assert!(near(a.center, Vec3::new(612345.678, 2398765.432, 5.0), 1e-9), "{a:?}");
|
||||
assert!((a.start - 5.235987755978257).abs() < 1e-9 && (a.end - 1.047197551201328).abs() < 1e-9, "{a:?}");
|
||||
assert_eq!(e.common.thickness, 2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_keeps_a_polylines_elevation() {
|
||||
let mut s = Session::new();
|
||||
let p = add(&mut s, polyline(&[(0.0, 0.0, 0.0), (20.0, 0.0, 0.4), (30.0, 15.0, 0.0), (5.0, 20.0, 0.0)], 0.0, 12.5, false), 1.0);
|
||||
let b = line(&mut s, [10.0, -10.0], [10.0, 30.0]);
|
||||
trim(&mut s, p, [5.0, 0.0], b);
|
||||
let EntityKind::LwPolyline(l) = kind(&s, p) else { panic!("not a polyline") };
|
||||
assert_eq!(l.elevation, 12.5);
|
||||
let want = [(10.0, 0.0, 0.0), (20.0, 0.0, 0.4), (30.0, 15.0, 0.0), (5.0, 20.0, 0.0)];
|
||||
assert_eq!(l.vertices.len(), want.len());
|
||||
for (v, w) in l.vertices.iter().zip(want) {
|
||||
assert!(near(Vec3::new(v.p.x, v.p.y, v.bulge), Vec3::new(w.0, w.1, w.2), 1e-12), "{v:?} != {w:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_and_trim_keep_a_polylines_constant_width_on_every_piece() {
|
||||
// Measured for BREAK: a width-2 polyline broken from (705, 0) to (735, 0) leaves two width-2
|
||||
// pieces. TRIM leaves its pieces the same way. Linetype generation is the polyline's setting
|
||||
// too, so the pieces keep it (not measured).
|
||||
let shape = [(700.0, 0.0, 0.0), (720.0, 0.0, 0.0), (740.0, 0.0, 0.0)];
|
||||
let mut s = Session::new();
|
||||
let p = add(&mut s, polyline(&shape, 2.0, 0.0, true), 0.0);
|
||||
let r = s.execute("break", &json!({ "handle": p.hex(), "p1": [705, 0], "p2": [735, 0] })).unwrap();
|
||||
let mut s2 = Session::new();
|
||||
let q = add(&mut s2, polyline(&shape, 2.0, 0.0, true), 0.0);
|
||||
let k1 = line(&mut s2, [705.0, -5.0], [705.0, 5.0]);
|
||||
let k2 = line(&mut s2, [735.0, -5.0], [735.0, 5.0]);
|
||||
let t = s2.execute("trim", &json!({ "handle": q.hex(), "pick": [720, 0], "edges": [k1.hex(), k2.hex()] })).unwrap();
|
||||
for (s, r) in [(&s, &r), (&s2, &t)] {
|
||||
let hs = r["handles"].as_array().unwrap();
|
||||
assert_eq!(hs.len(), 2);
|
||||
for h in hs {
|
||||
let EntityKind::LwPolyline(l) = kind(s, Handle::parse_hex(h.as_str().unwrap()).unwrap()) else { panic!("not a polyline") };
|
||||
assert_eq!((l.const_width, l.plinegen), (2.0, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,11 +56,17 @@ pub struct ShxGlyph {
|
||||
pub advance: Vec2,
|
||||
}
|
||||
|
||||
/// Glyphs cached per font, keyed by (shape, vertical).
|
||||
type GlyphCache = HashMap<(u16, bool), Option<Arc<ShxGlyph>>>;
|
||||
/// Glyphs cached per font, keyed by (shape, vertical), and their points in all.
|
||||
#[derive(Default)]
|
||||
struct GlyphCache {
|
||||
glyphs: HashMap<(u16, bool), Option<Arc<ShxGlyph>>>,
|
||||
points: usize,
|
||||
}
|
||||
|
||||
/// Most glyphs cached per font (a big font has thousands; text uses a few hundred).
|
||||
const MAX_CACHED_GLYPHS: usize = 16_384;
|
||||
/// Most points cached per font (16 MB; a glyph may hold thousands of points).
|
||||
const MAX_CACHED_POINTS: usize = 1 << 20;
|
||||
|
||||
/// A parsed SHX file.
|
||||
pub struct ShxFont {
|
||||
@@ -203,15 +209,22 @@ impl ShxFont {
|
||||
}
|
||||
let vertical = vertical && self.dual;
|
||||
let key = (number, vertical);
|
||||
if let Some(g) = self.cache.read().unwrap_or_else(PoisonError::into_inner).get(&key) {
|
||||
if let Some(g) = self.cache.read().unwrap_or_else(PoisonError::into_inner).glyphs.get(&key) {
|
||||
return g.clone();
|
||||
}
|
||||
let g = program::outline(self, number, vertical).ok().map(Arc::new);
|
||||
let points = g.as_ref().map_or(0, |g| g.strokes.iter().map(Vec::len).sum::<usize>());
|
||||
let mut c = self.cache.write().unwrap_or_else(PoisonError::into_inner);
|
||||
if c.len() >= MAX_CACHED_GLYPHS {
|
||||
c.clear();
|
||||
// Another thread may have outlined it in the meantime: its points are counted already.
|
||||
if let Some(g) = c.glyphs.get(&key) {
|
||||
return g.clone();
|
||||
}
|
||||
c.insert(key, g.clone());
|
||||
if c.glyphs.len() >= MAX_CACHED_GLYPHS || c.points.saturating_add(points) > MAX_CACHED_POINTS {
|
||||
c.glyphs.clear();
|
||||
c.points = 0;
|
||||
}
|
||||
c.points = c.points.saturating_add(points);
|
||||
c.glyphs.insert(key, g.clone());
|
||||
g
|
||||
}
|
||||
}
|
||||
|
||||
@@ -309,6 +309,22 @@ fn hostile_files_never_panic() {
|
||||
assert!(compile("").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_glyph_cache_is_bounded_by_points() {
|
||||
// Hostile: every glyph at the point bound, so 16,384 cached glyphs would hold 2 GB.
|
||||
let mut src = format!("*2,1,HUNDRED\n{}0\n*3,3,V\n011,019,0\n", "7,3,".repeat(100));
|
||||
for n in 10..=200 {
|
||||
src.push_str(&format!("*{n},1,HEAVY\n{}0\n", "7,2,".repeat(40)));
|
||||
}
|
||||
let f = font(&src);
|
||||
for n in 10..=200 {
|
||||
assert!(f.glyph(n, false).is_some());
|
||||
}
|
||||
let c = f.cache.read().unwrap();
|
||||
let cached: usize = c.glyphs.values().flatten().map(|g| g.strokes.iter().map(Vec::len).sum::<usize>()).sum();
|
||||
assert!(cached <= MAX_CACHED_POINTS && cached == c.points, "{cached}");
|
||||
}
|
||||
|
||||
/// Register a compiled test font under `name` (each test its own names: the table is shared).
|
||||
fn reg(name: &str, src: &str) {
|
||||
register(name, &compile(src).unwrap()).unwrap();
|
||||
|
||||
@@ -1062,11 +1062,10 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
alive_memo
|
||||
});
|
||||
// New handles for the written kept objects, above every written handle and the seed.
|
||||
let mut next = seed(tags).max(max_handle(tags).saturating_add(1));
|
||||
let mut fresh = Fresh::new(tags);
|
||||
let mut alive: HashMap<String, String> = HashMap::new();
|
||||
for o in f.objects.iter().filter(|o| alive_memo.get(&o.handle.hex()) == Some(&true)) {
|
||||
alive.insert(o.handle.hex(), format!("{next:X}"));
|
||||
next = next.saturating_add(1);
|
||||
alive.insert(o.handle.hex(), format!("{:X}", fresh.take()));
|
||||
}
|
||||
let entities: HashSet<String> = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect();
|
||||
let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities };
|
||||
@@ -1389,19 +1388,18 @@ fn add_appids(out: &mut Vec<Tag>) {
|
||||
return;
|
||||
}
|
||||
// New handles above the seed, which is then moved past them.
|
||||
let mut next = seed(out).max(max_handle(out).saturating_add(1));
|
||||
let mut fresh = Fresh::new(out);
|
||||
let mut add = Vec::new();
|
||||
for app in &missing {
|
||||
add.extend([
|
||||
Tag::s(0, "APPID"),
|
||||
Tag::s(5, format!("{next:X}")),
|
||||
Tag::s(5, format!("{:X}", fresh.take())),
|
||||
Tag::s(330, table_h.clone()),
|
||||
Tag::s(100, "AcDbSymbolTableRecord"),
|
||||
Tag::s(100, "AcDbRegAppTableRecord"),
|
||||
Tag::s(2, (*app).clone()),
|
||||
Tag::i(70, 0),
|
||||
]);
|
||||
next = next.saturating_add(1);
|
||||
}
|
||||
let end_at = end.start;
|
||||
if let Some(count) = out.get_mut(t.start + 1..t.end).and_then(|b| b.iter_mut().find(|x| x.code == 70)) {
|
||||
@@ -1420,6 +1418,36 @@ fn seed(tags: &[Tag]) -> u64 {
|
||||
seed_index(tags).and_then(|i| tags.get(i)).and_then(|t| Handle::parse_hex(&t.str())).map_or(0, |h| h.0)
|
||||
}
|
||||
|
||||
/// New handles for records added to written tags: above the seed and every handle written, and
|
||||
/// never one a record already holds. A file may hold the top handle (#913): then counting on from
|
||||
/// it would give every added record that same handle, so past the top of the range the numbering
|
||||
/// goes on in the reserved band above [`cadcraft_doc::HANDLE_LIMIT`], skipping the handles there.
|
||||
struct Fresh {
|
||||
next: u64,
|
||||
used: HashSet<u64>,
|
||||
}
|
||||
|
||||
impl Fresh {
|
||||
fn new(tags: &[Tag]) -> Self {
|
||||
let used: HashSet<u64> =
|
||||
tags.iter().filter(|t| t.code == 5 || t.code == 105).filter_map(|t| Handle::parse_hex(&t.str())).map(|h| h.0).collect();
|
||||
let above = used.iter().max().map_or(0, |h| h.checked_add(1).unwrap_or(cadcraft_doc::HANDLE_LIMIT));
|
||||
Fresh { next: seed(tags).max(above), used }
|
||||
}
|
||||
/// The next free handle. Each handle skipped is one a record holds, so the walk is bounded
|
||||
/// by their count (and handle 0, which means "none").
|
||||
fn take(&mut self) -> u64 {
|
||||
for _ in 0..self.used.len().saturating_add(2) {
|
||||
let h = self.next;
|
||||
self.next = h.checked_add(1).unwrap_or(cadcraft_doc::HANDLE_LIMIT);
|
||||
if h != 0 && self.used.insert(h) {
|
||||
return h;
|
||||
}
|
||||
}
|
||||
self.next
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest handle of a record (groups 5 and 105).
|
||||
fn max_handle(tags: &[Tag]) -> u64 {
|
||||
tags.iter().filter(|t| t.code == 5 || t.code == 105).filter_map(|t| Handle::parse_hex(&t.str())).map(|h| h.0).max().unwrap_or(0)
|
||||
|
||||
@@ -102,11 +102,36 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result<Drawing> {
|
||||
// its $HANDSEED can be lower than its handles, and entities made while reading (the faces of
|
||||
// a polygon mesh) would otherwise get handles that records further on still have. A file
|
||||
// CADCraft wrote names its own next handle, above which its rebuilt records are numbered
|
||||
// (#495), so it is left to that.
|
||||
// (#495), so for it only the entity records are reserved. Handles in the reserved band are
|
||||
// reserved for allocation rather than followed (#913): a handle-less entity read before the
|
||||
// section that names one is placed would otherwise be given it and replace the record (#1276).
|
||||
let ours = secs.iter().any(|s| s.name == "OBJECTS" && s.tags.iter().any(|t| t.code == 3 && t.str() == crate::dxf_ext::HANDSEED_KEY));
|
||||
for t in secs.iter().filter(|_| !ours).flat_map(|s| s.tags.iter()).filter(|t| t.code == 5 || t.code == 105) {
|
||||
if let Some(h) = Handle::parse_hex(t.str().trim()) {
|
||||
d.bump_handseed(h);
|
||||
if ours {
|
||||
// Its table and object records are numbered above its seed and rebuilt on save (#495),
|
||||
// so only its entities are reserved. Reading is section by section: an entity that has
|
||||
// no handle, or repeats one within its section, gets a fresh handle, and that must not
|
||||
// be one an entity of a later section still names. `BLOCK` and `ENDBLK` are structural
|
||||
// records, not entities, and are left out so they don't move the saved seed.
|
||||
for (kind, tags) in secs.iter().filter(|s| s.name == "BLOCKS" || s.name == "ENTITIES").flat_map(|s| records(&s.tags)) {
|
||||
if matches!(kind.as_str(), "BLOCK" | "ENDBLK") {
|
||||
continue;
|
||||
}
|
||||
if let Some(h) = tags.iter().find(|t| t.code == 5).and_then(|t| Handle::parse_hex(t.str().trim())) {
|
||||
d.bump_handseed(h);
|
||||
d.reserve_handle(h);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for s in &secs {
|
||||
let entity_section = s.name == "BLOCKS" || s.name == "ENTITIES";
|
||||
for t in s.tags.iter().filter(|t| t.code == 5 || t.code == 105) {
|
||||
if let Some(h) = Handle::parse_hex(t.str().trim()) {
|
||||
d.bump_handseed(h);
|
||||
if entity_section {
|
||||
d.reserve_handle(h);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut skipped = std::collections::BTreeMap::new();
|
||||
@@ -148,6 +173,9 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result<Drawing> {
|
||||
crate::dxf_raw::read(&secs, &mut d);
|
||||
crate::dxf_clip::read(&mut d);
|
||||
d.skipped_records = skipped;
|
||||
// Every record is placed now, and an object holding a reserved handle keeps it from new
|
||||
// objects by itself. Kept, the set would be copied with every undo step of the drawing.
|
||||
d.reserved_handles.clear();
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ pub(super) fn parse_entities(
|
||||
}
|
||||
if let Some((c, mut k)) = kindent {
|
||||
let h = match handle {
|
||||
// A file's handles keep their identity, however high they are (#913, #939).
|
||||
Some(h) => {
|
||||
d.bump_handseed(h);
|
||||
h
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! the newer DIMSTYLE groups, and from 2007 in UTF-8 text (the caller picks the text encoding) and
|
||||
//! MULTILEADER entities (older files get LEADER + MTEXT).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_doc::{
|
||||
@@ -39,6 +39,9 @@ use sections::tags_for;
|
||||
struct W {
|
||||
t: Vec<Tag>,
|
||||
next: u64,
|
||||
/// Handles the drawing's objects already hold: structural records skip them, so writing a
|
||||
/// file whose own handles sit near the top of the range never repeats a handle (#913).
|
||||
used: HashSet<u64>,
|
||||
/// Upper-case plot style name → its `ACDBPLACEHOLDER` handle (group 390 of layers and objects).
|
||||
pstyles: HashMap<String, String>,
|
||||
/// Upper-case layer name → its LAYER table record handle (group 331/341 of viewports).
|
||||
@@ -48,6 +51,21 @@ struct W {
|
||||
reactors: HashMap<Handle, Vec<String>>,
|
||||
}
|
||||
|
||||
/// Where the writer's own records (tables, objects, dictionaries) start numbering: above every
|
||||
/// object handle and the drawing's seed, with headroom for handles the drawing allocates next.
|
||||
fn structural_start(d: &Drawing) -> u64 {
|
||||
let highest = entity_handles(d).max().unwrap_or(0);
|
||||
d.handseed.max(0x100).max(highest.saturating_add(1)).saturating_add(0x1000)
|
||||
}
|
||||
|
||||
/// Every handle an object holds, plus the drawing's next one.
|
||||
fn entity_handles(d: &Drawing) -> impl Iterator<Item = u64> + '_ {
|
||||
let model = d.model.iter().map(|e| e.handle.0);
|
||||
let layouts = d.layouts.iter().flat_map(|l| l.entities.iter()).map(|e| e.handle.0);
|
||||
let blocks = d.blocks.values().flat_map(|b| b.entities.iter()).map(|e| e.handle.0);
|
||||
model.chain(layouts).chain(blocks).chain(std::iter::once(d.handseed))
|
||||
}
|
||||
|
||||
impl W {
|
||||
fn s(&mut self, c: i32, v: impl Into<String>) {
|
||||
self.t.push(Tag::s(c, v));
|
||||
@@ -71,10 +89,20 @@ impl W {
|
||||
format!("{:X}", self.next_handle())
|
||||
}
|
||||
/// A new handle for a record the drawing doesn't hold (as [`W::h`]).
|
||||
///
|
||||
/// Skips every handle in use, so a file object carrying a handle above the seed (the
|
||||
/// reserved band) is not handed out again, and wraps into that band if the writer runs off
|
||||
/// the top of the range. Each handle skipped is one in use, so the walk is bounded by their
|
||||
/// count.
|
||||
fn next_handle(&mut self) -> u64 {
|
||||
let h = self.next;
|
||||
self.next = self.next.saturating_add(1);
|
||||
h
|
||||
for _ in 0..self.used.len().saturating_add(1) {
|
||||
let h = self.next;
|
||||
self.next = h.checked_add(1).unwrap_or(cadcraft_doc::HANDLE_LIMIT);
|
||||
if self.used.insert(h) {
|
||||
return h;
|
||||
}
|
||||
}
|
||||
self.next
|
||||
}
|
||||
/// A `102 {NAME` … `102 }` group of handles.
|
||||
fn group(&mut self, name: &str, code: i32, handles: &[&str]) {
|
||||
@@ -152,7 +180,8 @@ fn bridge_markers(tags: &mut [Tag]) {
|
||||
pub fn entity_groups(d: &Drawing, e: &Entity) -> (String, Vec<Tag>) {
|
||||
let mut w = W {
|
||||
t: Vec::new(),
|
||||
next: d.handseed.max(0x100).saturating_add(0x1000),
|
||||
next: structural_start(d),
|
||||
used: entity_handles(d).collect(),
|
||||
pstyles: HashMap::new(),
|
||||
layers: HashMap::new(),
|
||||
reactors: HashMap::new(),
|
||||
|
||||
@@ -16,7 +16,14 @@ pub(super) fn annotative_xdata(w: &mut W) {
|
||||
|
||||
/// Override (`ACAD` DSTYLE) and associativity (`CADCRAFT` ASSOC) xdata of a dimension.
|
||||
pub(super) fn dim_xdata(w: &mut W, dm: &Dimension, cx: &Ctx) {
|
||||
let mut ov = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() };
|
||||
let mut ov = W {
|
||||
t: Vec::new(),
|
||||
next: 0,
|
||||
used: std::collections::HashSet::new(),
|
||||
pstyles: HashMap::new(),
|
||||
layers: HashMap::new(),
|
||||
reactors: HashMap::new(),
|
||||
};
|
||||
let mut sah = false;
|
||||
for (k, v) in &dm.overrides {
|
||||
let Some(field) = DimStyle::field_name(k) else { continue };
|
||||
|
||||
@@ -7,9 +7,10 @@ use super::header::{code_page, header_vars};
|
||||
use super::layout::{paper_views, record_head, sheet_first, table_head, vport_table};
|
||||
use super::objects::{cadcraft_fonts_name, group_obj, mleader_style_obj, scale_list, table_style_obj};
|
||||
use super::{
|
||||
Block, Color, DimStyle, DimVal, Drawing, Entity, EntityKind, EntityStore, Group, HVal, Handle, HashMap, Layout, MLeaderStyle, PageSetup, Space,
|
||||
TableStyle, Tag, Vec2, Vec3, Version, W, dxf_ext,
|
||||
Block, Color, DimStyle, DimVal, Drawing, Entity, EntityKind, EntityStore, Group, HVal, Handle, HashMap, HashSet, Layout, MLeaderStyle, PageSetup,
|
||||
Space, TableStyle, Tag, Vec2, Vec3, Version, W, dxf_ext,
|
||||
};
|
||||
use super::{entity_handles, structural_start};
|
||||
|
||||
struct TableWritePlan<'a> {
|
||||
d: &'a Drawing,
|
||||
@@ -245,7 +246,7 @@ fn write_dimstyles(w: &mut W, d: &Drawing, cx: &mut Ctx, version: Version) {
|
||||
w.i(70, 0);
|
||||
let v = serde_json::to_value(s).unwrap_or_default();
|
||||
let defaults = serde_json::to_value(DimStyle::default()).unwrap_or_default();
|
||||
let mut newer = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() };
|
||||
let mut newer = W { t: Vec::new(), next: 0, used: HashSet::new(), pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() };
|
||||
for (field, code, kind) in dxf_ext::DIM_CODES {
|
||||
let Some(enc) = v.get(*field).and_then(|x| cx.encode(*kind, x)) else { continue };
|
||||
// DIMPOST is written even when empty: a reader that defaults a missing one to "<>"
|
||||
@@ -916,7 +917,8 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
|
||||
// Structural handles start above every entity handle.
|
||||
let mut w = W {
|
||||
t: Vec::new(),
|
||||
next: d.handseed.max(0x100).saturating_add(0x1000),
|
||||
next: structural_start(d),
|
||||
used: entity_handles(d).collect(),
|
||||
pstyles: HashMap::new(),
|
||||
layers: HashMap::new(),
|
||||
reactors: hatch_reactors(d),
|
||||
@@ -1093,11 +1095,11 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
|
||||
for (n, h, b) in &user_blocks {
|
||||
block(&mut w, (n, &b.description), h, b.base, if b.anonymous { 1 } else { 0 }, &mut b.entities.iter().map(|e| e.as_ref()), false);
|
||||
}
|
||||
// Generated geometry entities (dimension, arrowhead and table blocks) need handles.
|
||||
// Generated geometry entities (dimension, arrowhead and table blocks) need handles; take
|
||||
// them from the writer's allocator, which skips the drawing's own handles.
|
||||
for (_, _, ents) in dim_defs.iter_mut().chain(arrow_defs.iter_mut()).chain(table_defs.iter_mut()) {
|
||||
for e in ents.iter_mut().filter(|e| e.handle.0 == 0) {
|
||||
e.handle = Handle(w.next);
|
||||
w.next = w.next.saturating_add(1);
|
||||
e.handle = Handle(w.next_handle());
|
||||
}
|
||||
}
|
||||
for (n, h, ents) in &dim_defs {
|
||||
|
||||
+122
-16
@@ -17,7 +17,7 @@ use std::collections::BTreeMap;
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_doc::{Circle, Common, Drawing, Ellipse, EntityKind, Layer, Line, LwPolyline, Space};
|
||||
use cadcraft_geom::{Mat3, PolyVertex, Spline, Vec2, Vec3};
|
||||
use cadcraft_geom::{Mat3, PolyVertex, Spline, Vec2, Vec3, bulge_to_arc};
|
||||
|
||||
use crate::{IoError, Result};
|
||||
|
||||
@@ -70,6 +70,8 @@ struct Parser {
|
||||
verts_left: usize,
|
||||
/// What was left out, by kind ([`LeftOut`]).
|
||||
left_out: BTreeMap<LeftOut, usize>,
|
||||
/// Shapes left out because their coordinates or extents overflow: invalid, not unsupported.
|
||||
too_large: usize,
|
||||
}
|
||||
|
||||
/// Drawn content the reader leaves out, named in the drawing's read note.
|
||||
@@ -105,16 +107,23 @@ impl Parser {
|
||||
elements: 0,
|
||||
verts_left: MAX_TOTAL_VERTS,
|
||||
left_out: BTreeMap::new(),
|
||||
too_large: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The read note on what was left out, if anything was.
|
||||
fn note(&self) -> Option<String> {
|
||||
if self.left_out.is_empty() {
|
||||
return None;
|
||||
/// The read notes on what was left out: what isn't read yet, then what is invalid.
|
||||
fn notes(&self) -> Vec<String> {
|
||||
let mut notes = Vec::new();
|
||||
if !self.left_out.is_empty() {
|
||||
let list: Vec<String> = self.left_out.iter().map(|(k, n)| k.describe(*n)).collect();
|
||||
notes.push(format!("SVG: CADCraft doesn't read these yet, so they were left out: {}", list.join(", ")));
|
||||
}
|
||||
let list: Vec<String> = self.left_out.iter().map(|(k, n)| k.describe(*n)).collect();
|
||||
Some(format!("SVG: CADCraft doesn't read these yet, so they were left out: {}", list.join(", ")))
|
||||
match self.too_large {
|
||||
0 => {}
|
||||
1 => notes.push("SVG: 1 shape was left out as invalid: its coordinates or size are too large to represent".into()),
|
||||
n => notes.push(format!("SVG: {n} shapes were left out as invalid: their coordinates or size are too large to represent")),
|
||||
}
|
||||
notes
|
||||
}
|
||||
|
||||
fn parse(&mut self, text: &str) -> Result<()> {
|
||||
@@ -150,7 +159,7 @@ impl Parser {
|
||||
};
|
||||
self.left_out.insert(kind, count);
|
||||
}
|
||||
self.drawing.read_notes.extend(self.note());
|
||||
self.drawing.read_notes.extend(self.notes());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -218,12 +227,18 @@ impl Parser {
|
||||
}
|
||||
// Charge the vertices this entity retains against the shared document budget, so repeated
|
||||
// flattened arcs/curves cannot amplify a compact path into unbounded geometry (CWE-400).
|
||||
// A shape left out below was generated all the same, so it is charged too.
|
||||
let verts = match &kind {
|
||||
EntityKind::LwPolyline(p) => p.vertices.len(),
|
||||
EntityKind::Spline(s) => s.control.len(),
|
||||
_ => 1,
|
||||
};
|
||||
self.verts_left = self.verts_left.checked_sub(verts).ok_or_else(|| IoError::Format("SVG: too much generated geometry".into()))?;
|
||||
// Finite numbers can still overflow through transforms and relative steps (`l1e308 0` twice).
|
||||
if !finite(&kind) {
|
||||
self.too_large += 1;
|
||||
return Ok(());
|
||||
}
|
||||
let common = Common { layer: self.layer.clone(), ..Common::default() };
|
||||
self.drawing.add(&Space::Model, common, kind).map(|_| ()).map_err(parse_err)
|
||||
}
|
||||
@@ -231,7 +246,10 @@ impl Parser {
|
||||
/// A circle or ellipse through a transform. A circle stays a `CIRCLE` under rotations,
|
||||
/// uniform scales and reflections; anything else becomes an `ELLIPSE` holding the axes
|
||||
/// of the transformed shape — a linear map sends the unit circle to an ellipse whose
|
||||
/// semi-axes are the square roots of the eigenvalues of `A·Aᵀ`.
|
||||
/// semi-axes are the square roots of the eigenvalues of `A·Aᵀ`. With `B = [bx by]` the
|
||||
/// ellipse is `center + B·(cos t, sin t)`; `B·Bᵀ` lives in the drawing plane, so its leading
|
||||
/// eigenvector is the major axis's direction. `major` is that axis from the centre, as
|
||||
/// [`Ellipse::major`] is everywhere else.
|
||||
fn add_rounded(&mut self, center_user: Vec2, rx: f64, ry: f64) -> Result<()> {
|
||||
let center = self.map(center_user);
|
||||
let bx = self.map_vec(Vec2::new(rx, 0.0));
|
||||
@@ -253,18 +271,15 @@ impl Parser {
|
||||
if s_max <= f64::EPSILON {
|
||||
return Ok(());
|
||||
}
|
||||
let axis = if xy.abs() <= 1e-12 * trace.max(1.0) {
|
||||
let axis = if xy.abs() <= 1e-12 * trace {
|
||||
if yy > xx { Vec2::new(0.0, 1.0) } else { Vec2::new(1.0, 0.0) }
|
||||
} else {
|
||||
let v = Vec2::new(xy, l_max - xx);
|
||||
let l = len(v);
|
||||
if l <= f64::EPSILON {
|
||||
return Ok(());
|
||||
}
|
||||
v / l
|
||||
// |v| ≥ |xy| > 1e-12·trace ≥ 0 here, so the division is never by zero.
|
||||
v / len(v)
|
||||
};
|
||||
let ratio = (l_min.max(0.0).sqrt() / s_max).clamp(1e-9, 1.0);
|
||||
let major = center + axis * s_max;
|
||||
let major = axis * s_max;
|
||||
self.add(EntityKind::Ellipse(Ellipse { center: v3(center), major: v3(major), ratio, start: 0.0, end: std::f64::consts::TAU }))
|
||||
}
|
||||
|
||||
@@ -380,6 +395,79 @@ impl Parser {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every coordinate of an entity the reader makes is finite, and so are its extents: a finite
|
||||
/// centre and radius can still reach past the largest number.
|
||||
fn finite(kind: &EntityKind) -> bool {
|
||||
match kind {
|
||||
EntityKind::Line(l) => l.a.is_finite() && l.b.is_finite(),
|
||||
EntityKind::Circle(c) => {
|
||||
c.center.is_finite()
|
||||
&& c.radius.is_finite()
|
||||
&& cadcraft_geom::Circle::new(c.center.xy(), c.radius).bounds().corners().iter().all(|p| p.is_finite())
|
||||
}
|
||||
EntityKind::Ellipse(e) => {
|
||||
// Half the box is `hypot` of the major axis and the minor axis (`ratio` times it, turned).
|
||||
let (m, r) = (e.major.xy(), e.ratio);
|
||||
e.center.is_finite() && e.major.is_finite() && e.ratio.is_finite() && box_finite(e.center.xy(), m.x.hypot(r * m.y), m.y.hypot(r * m.x))
|
||||
}
|
||||
EntityKind::LwPolyline(p) => p.vertices.iter().all(|v| v.p.is_finite() && v.bulge.is_finite()) && bulges_finite(p),
|
||||
EntityKind::Spline(s) => s.control.iter().all(|p| p.is_finite()),
|
||||
// The SVG reader doesn't make these.
|
||||
EntityKind::Point(_)
|
||||
| EntityKind::Arc(_)
|
||||
| EntityKind::Polyline3d(_)
|
||||
| EntityKind::Helix(_)
|
||||
| EntityKind::Ray(_)
|
||||
| EntityKind::XLine(_)
|
||||
| EntityKind::Text(_)
|
||||
| EntityKind::MText(_)
|
||||
| EntityKind::AttDef(_)
|
||||
| EntityKind::Insert(_)
|
||||
| EntityKind::Dimension(_)
|
||||
| EntityKind::MLine(_)
|
||||
| EntityKind::Leader(_)
|
||||
| EntityKind::MLeader(_)
|
||||
| EntityKind::Hatch(_)
|
||||
| EntityKind::Solid(_)
|
||||
| EntityKind::Trace(_)
|
||||
| EntityKind::Face3d(_)
|
||||
| EntityKind::PolyfaceMesh(_)
|
||||
| EntityKind::Region(_)
|
||||
| EntityKind::Viewport(_)
|
||||
| EntityKind::Image(_)
|
||||
| EntityKind::Wipeout(_)
|
||||
| EntityKind::Table(_)
|
||||
| EntityKind::Tolerance(_)
|
||||
| EntityKind::Unknown(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The box `centre ± (hx, hy)` is finite.
|
||||
fn box_finite(c: Vec2, hx: f64, hy: f64) -> bool {
|
||||
[c.x - hx, c.x + hx, c.y - hy, c.y + hy].iter().all(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// Every arc segment of the polyline (a bulge between finite vertices) has a finite centre and
|
||||
/// radius, and the quadrant points it passes through are finite.
|
||||
fn bulges_finite(p: &LwPolyline) -> bool {
|
||||
let n = p.vertices.len();
|
||||
p.vertices.iter().enumerate().all(|(i, v)| {
|
||||
let next = if i + 1 < n {
|
||||
p.vertices.get(i + 1)
|
||||
} else if p.closed {
|
||||
p.vertices.first()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some((arc, _)) = next.and_then(|w| bulge_to_arc(v.p, w.p, v.bulge)) else { return true };
|
||||
arc.center.is_finite()
|
||||
&& arc.radius.is_finite()
|
||||
&& (0..4)
|
||||
.map(|k| f64::from(k) * std::f64::consts::FRAC_PI_2)
|
||||
.all(|a| !arc.contains_angle(a) || Vec2::polar(arc.center, arc.radius, a).is_finite())
|
||||
})
|
||||
}
|
||||
|
||||
/// One `M …` run of a `d` attribute.
|
||||
struct Subpath {
|
||||
start: Vec2,
|
||||
@@ -471,4 +559,22 @@ mod tests {
|
||||
assert_eq!(arc_of("M10 10 a20 20 0 1 0 20 20"), (true, false, spaced.2));
|
||||
assert!(arc_of("M10 10 a20 20 0 10-20 20").0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extents_past_the_largest_number_are_not_finite() {
|
||||
let ellipse = |c: Vec2, major: Vec2| EntityKind::Ellipse(Ellipse { center: v3(c), major: v3(major), ratio: 1.0, start: 0.0, end: 0.0 });
|
||||
assert!(!finite(&ellipse(Vec2::new(1e308, 0.0), Vec2::new(1e308, 0.0))));
|
||||
assert!(finite(&ellipse(Vec2::new(5e307, 0.0), Vec2::new(5e307, 0.0))));
|
||||
// Turned, its box is wider than its axis: `centre ± major` is finite, the box isn't.
|
||||
assert!(!finite(&ellipse(Vec2::new(6e307, 0.0), Vec2::new(9e307, 9e307))));
|
||||
assert!(finite(&ellipse(Vec2::ZERO, Vec2::new(9e307, 9e307))));
|
||||
// Half circles between the same finite points: bulging up passes 1.8e308, down doesn't.
|
||||
let half = |bulge: f64| {
|
||||
let (a, b) = (Vec2::new(0.0, 1.5e308), Vec2::new(1e308, 1.5e308));
|
||||
let vertices = vec![PolyVertex::with_bulge(a, bulge), PolyVertex::new(b)];
|
||||
EntityKind::LwPolyline(LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 0.0, plinegen: false })
|
||||
};
|
||||
assert!(!finite(&half(-1.0)));
|
||||
assert!(finite(&half(1.0)));
|
||||
}
|
||||
}
|
||||
|
||||
+117
-1
@@ -2915,12 +2915,75 @@ fn svg_shapes_become_entities_in_millimetres() {
|
||||
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
|
||||
assert!((c.radius - 2.0).abs() < 1e-9 && (c.center.x - 10.0).abs() < 1e-9 && (c.center.y - 5.0).abs() < 1e-9, "{c:?}");
|
||||
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
|
||||
let major = Vec2::new(e.major.x - e.center.x, e.major.y - e.center.y);
|
||||
let major = Vec2::new(e.major.x, e.major.y);
|
||||
assert!((major.len() - 4.0).abs() < 1e-9 && (e.ratio - 0.5).abs() < 1e-9, "{e:?}");
|
||||
let l = first(&d, |k| if let EntityKind::Line(l) = k { Some(l.clone()) } else { None });
|
||||
assert!((l.a.y - 10.0).abs() < 1e-9 && (l.b.y).abs() < 1e-9, "{l:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_ellipse_major_axis_is_relative_to_its_centre() {
|
||||
// Away from the origin: the major axis was stored as the absolute point centre + axis.
|
||||
let svg = format!("{SVG_PAGE}<ellipse cx=\"15\" cy=\"2\" rx=\"2\" ry=\"1\"/><circle cx=\"15\" cy=\"2\" r=\"1\"/></svg>");
|
||||
let d = read(svg.as_bytes(), "ellipse.svg").unwrap();
|
||||
assert_eq!(kinds(&d), ["Ellipse", "Circle"]);
|
||||
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
|
||||
assert!((e.center - Vec3::new(15.0, 8.0, 0.0)).len() < 1e-9, "{e:?}");
|
||||
assert!((e.major.x.abs() - 2.0).abs() < 1e-9 && e.major.y.abs() < 1e-9 && e.major.z == 0.0, "{e:?}");
|
||||
assert!((e.ratio - 0.5).abs() < 1e-9, "{e:?}");
|
||||
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
|
||||
assert!((c.center - Vec3::new(15.0, 8.0, 0.0)).len() < 1e-9 && (c.radius - 1.0).abs() < 1e-9, "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_rotated_ellipse_keeps_its_turn() {
|
||||
// The page maps SVG (x, y) to (x, 10 - y); undo that, then rotate by -30°, to get back to the ellipse's own frame.
|
||||
let svg = format!("{SVG_PAGE}<ellipse cx=\"0\" cy=\"0\" rx=\"20\" ry=\"10\" transform=\"rotate(30)\"/></svg>");
|
||||
let d = read(svg.as_bytes(), "rotated.svg").unwrap();
|
||||
assert_eq!(kinds(&d), ["Ellipse"]);
|
||||
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
|
||||
let major = Vec2::new(e.major.x, e.major.y);
|
||||
assert!((major.len() - 20.0).abs() < 1e-9 && (e.ratio - 0.5).abs() < 1e-9, "{e:?}");
|
||||
let (s, c) = 30f64.to_radians().sin_cos();
|
||||
let want = Vec2::new(20.0 * c, -20.0 * s);
|
||||
assert!((major - want).len() < 1e-9 || (major + want).len() < 1e-9, "{e:?}");
|
||||
let (ux, uy) = (e.center.x + major.x, 10.0 - (e.center.y + major.y));
|
||||
let (x, y) = (c * ux + s * uy, -s * ux + c * uy);
|
||||
assert!(((x / 20.0).powi(2) + (y / 10.0).powi(2) - 1.0).abs() < 1e-9, "{e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_sheared_circle_has_the_axes_of_its_image() {
|
||||
// matrix(1 0 1 1 0 0) is B = [[1, 1], [0, 1]]; the page then flips Y at one millimetre per unit.
|
||||
let svg = format!("{SVG_PAGE}<circle r=\"1\" transform=\"matrix(1 0 1 1 0 0)\"/></svg>");
|
||||
let d = read(svg.as_bytes(), "sheared.svg").unwrap();
|
||||
assert_eq!(kinds(&d), ["Ellipse"]);
|
||||
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
|
||||
let major = Vec2::new(e.major.x, e.major.y);
|
||||
let s_max = ((3.0 + 5f64.sqrt()) / 2.0).sqrt();
|
||||
let s_min = ((3.0 - 5f64.sqrt()) / 2.0).sqrt();
|
||||
assert!((major.len() - s_max).abs() < 1e-9 * s_max, "{e:?}");
|
||||
assert!((e.ratio - s_min / s_max).abs() < 1e-9, "{e:?}");
|
||||
let (ux, uy) = (major.x, -major.y);
|
||||
let pre = Vec2::new(ux - uy, uy);
|
||||
assert!((pre.len() - 1.0).abs() < 1e-9, "B⁻¹·major = {pre:?}, {e:?}");
|
||||
assert!(major.x.abs() > 1e-3 && major.y.abs() > 1e-3, "{e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_tiny_sheared_circle_has_the_axes_of_its_image() {
|
||||
// Columns (1, 0.5)·1e-6 and (1, -0.5)·1e-6: far from orthogonal, though their dot product is tiny.
|
||||
let svg = format!("{SVG_PAGE}<circle r=\"1\" transform=\"matrix(1e-6 0.5e-6 1e-6 -0.5e-6 0 0)\"/></svg>");
|
||||
let d = read(svg.as_bytes(), "tiny.svg").unwrap();
|
||||
assert_eq!(kinds(&d), ["Ellipse"]);
|
||||
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
|
||||
let major = Vec2::new(e.major.x, e.major.y);
|
||||
assert!(major.y.abs() <= 1e-9 * major.x.abs(), "{e:?}");
|
||||
let want = 2f64.sqrt() * 1e-6;
|
||||
assert!((major.len() - want).abs() < 1e-9 * want, "{e:?}");
|
||||
assert!((e.ratio - 0.5).abs() < 1e-9, "{e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_path_lines_curves_and_arcs() {
|
||||
let svg = format!("{SVG_PAGE}<path d=\"M1 1 L5 1 C6 1 7 2 8 3\"/><path d=\"M0 0 A5 5 0 0 1 10 0 Z\"/></svg>");
|
||||
@@ -3137,6 +3200,59 @@ fn svg_hostile_input_errors_without_panicking() {
|
||||
assert!(deep.is_err(), "200 nested groups are refused, not walked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_coordinates_that_overflow_are_left_out() {
|
||||
// Every number is finite; relative steps and transforms overflow them to infinity or NaN.
|
||||
let svg = format!(
|
||||
"{SVG_PAGE}<path d=\"M1e308 0 l1e308 0\"/><rect x=\"1e308\" width=\"1e308\" height=\"1\"/>\
|
||||
<g transform=\"scale(1e308)\"><line x1=\"1e308\" y1=\"0\" x2=\"1\" y2=\"1\"/><circle r=\"1e308\"/></g>\
|
||||
<g transform=\"scale(1e308,1)\"><ellipse rx=\"1e308\" ry=\"1\"/><path d=\"M0 0 C1e308 0 1 1 2 2\"/></g>\
|
||||
<line x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"/></svg>"
|
||||
);
|
||||
let d = read(svg.as_bytes(), "huge.svg").unwrap();
|
||||
assert_eq!(kinds(&d), ["Line"]);
|
||||
assert_eq!(d.read_notes, ["SVG: 6 shapes were left out as invalid: their coordinates or size are too large to represent"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_shapes_whose_extents_overflow_are_left_out() {
|
||||
// A finite centre and radius whose sum overflows; the same scale on smaller values stays
|
||||
// representable.
|
||||
let svg = format!("{SVG_PAGE}<g transform=\"scale(1e308)\"><circle cx=\"1\" cy=\"0\" r=\"1\"/><circle cx=\"0.5\" cy=\"0\" r=\"0.5\"/></g></svg>");
|
||||
let d = read(svg.as_bytes(), "huge.svg").unwrap();
|
||||
assert_eq!(kinds(&d), ["Circle"]);
|
||||
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
|
||||
assert!((c.radius - 5e307).abs() < 1e293, "{}", c.radius);
|
||||
assert_eq!(d.read_notes, ["SVG: 1 shape was left out as invalid: its coordinates or size are too large to represent"]);
|
||||
}
|
||||
|
||||
/// A shape too large to represent is invalid, not something CADCraft doesn't read yet: it gets a
|
||||
/// note of its own.
|
||||
#[test]
|
||||
fn svg_too_large_shapes_are_noted_apart_from_unread_content() {
|
||||
let svg = format!("{SVG_PAGE}<text x=\"0\" y=\"5\">one</text><path d=\"M1e308 0 l1e308 0\"/><line x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"/></svg>");
|
||||
let d = read(svg.as_bytes(), "huge.svg").unwrap();
|
||||
assert_eq!(kinds(&d), ["Line"]);
|
||||
assert_eq!(
|
||||
d.read_notes,
|
||||
[
|
||||
"SVG: CADCraft doesn't read these yet, so they were left out: 1 text",
|
||||
"SVG: 1 shape was left out as invalid: its coordinates or size are too large to represent"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_shapes_left_out_still_count_against_the_vertex_budget() {
|
||||
// Each arc flattens to 10,000 chords under the non-uniform scale, and the doubled translation
|
||||
// overflows to infinity, so each is left out; 820 of them make more than the 8,000,000 vertices
|
||||
// a file may generate.
|
||||
let arcs = "A1e9 1e9 0 0 1 2e9 0 A1e9 1e9 0 0 1 0 0 ".repeat(410);
|
||||
let svg = format!("{SVG_PAGE}<g transform=\"translate(1e308 0) translate(1e308 0) scale(2 1)\"><path d=\"M0 0 {arcs}\"/></g></svg>");
|
||||
let err = read(svg.as_bytes(), "huge.svg").err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(err.contains("SVG: too much generated geometry"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_no_geometry_yields_an_empty_drawing() {
|
||||
let svg = format!("{SVG_PAGE}</svg>");
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
//! A hostile or damaged file can name a handle at the top of the range: an object's own handle,
|
||||
//! or its `$HANDSEED`. A file's handles keep their identity, so a new object must take a free
|
||||
//! handle instead of replacing the file's own object (#913).
|
||||
#![cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
use cadcraft_doc::{Common, DimKind, Dimension, Drawing, Entity, EntityKind, Handle, Line, Space};
|
||||
use cadcraft_geom::Vec3;
|
||||
|
||||
const TOP: &str = "FFFFFFFFFFFFFFFF";
|
||||
const NEAR_TOP: &str = "FFFFFFFFFFFEFFFF";
|
||||
|
||||
fn read(text: &str) -> Drawing {
|
||||
cadcraft_io::read_dxf(text.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
fn line(x: f64, y: f64) -> EntityKind {
|
||||
EntityKind::Line(Line { a: Vec3::new(x, y, 0.0), b: Vec3::new(x + 1.0, y, 0.0) })
|
||||
}
|
||||
|
||||
/// One line, with `entity_handle` when given, under a `$HANDSEED` of `seed`.
|
||||
fn dxf(entity_handle: Option<&str>, seed: &str) -> String {
|
||||
let handle = entity_handle.map(|h| format!("5\n{h}\n")).unwrap_or_default();
|
||||
format!(
|
||||
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n{seed}\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nENTITIES\n0\nLINE\n{handle}8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n0.0\n31\n0.0\n0\nENDSEC\n0\nEOF\n"
|
||||
)
|
||||
}
|
||||
|
||||
fn distinct(d: &Drawing) -> Vec<Handle> {
|
||||
d.model.iter().map(|e| e.handle).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_at_the_top_of_the_handle_range_is_not_replaced_by_a_new_one() {
|
||||
let mut d = read(&dxf(Some(TOP), TOP));
|
||||
assert_eq!(d.model.len(), 1);
|
||||
// The file's handle is its own; the new object takes a free handle below it.
|
||||
assert!(d.entity(Handle::parse_hex(TOP).unwrap()).is_some(), "the file's handle was renumbered");
|
||||
d.add(&Space::Model, Common::default(), line(10.0, 10.0)).unwrap();
|
||||
assert_eq!(d.model.len(), 2, "the file's line was replaced by the new one");
|
||||
let handles = distinct(&d);
|
||||
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
|
||||
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
|
||||
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the file's line is gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_seed_at_the_top_of_the_handle_range_cannot_be_followed_twice() {
|
||||
let mut d = read(&dxf(None, TOP));
|
||||
let a = d.add(&Space::Model, Common::default(), line(0.0, 10.0)).unwrap();
|
||||
let b = d.add(&Space::Model, Common::default(), line(0.0, 20.0)).unwrap();
|
||||
assert_ne!(a, b, "two objects were given the same handle");
|
||||
assert_eq!(d.model.len(), 3, "the second line replaced the first");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordinary_high_handle_keeps_its_identity() {
|
||||
// Far below the top of the range a file's handles are its own: they stay as they are.
|
||||
let h = "FFFFFFFF";
|
||||
let mut d = read(&dxf(Some(h), h));
|
||||
assert!(d.entity(Handle::parse_hex(h).unwrap()).is_some(), "the file's handle was renumbered");
|
||||
let n = d.add(&Space::Model, Common::default(), line(0.0, 5.0)).unwrap();
|
||||
assert!(n.0 > Handle::parse_hex(h).unwrap().0, "a new handle below the file's own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_handle_just_below_the_top_survives_a_save() {
|
||||
// Main keeps a file's handles exactly as written, even near the top of the range: handles
|
||||
// are how other objects and other programs refer to an entity (#939's round-trip tests).
|
||||
let mut d = read(&dxf(Some(NEAR_TOP), NEAR_TOP));
|
||||
let n = d.add(&Space::Model, Common::default(), line(0.0, 5.0)).unwrap();
|
||||
let bytes = cadcraft_io::write(&d, "near-top.dxf").unwrap();
|
||||
let r = cadcraft_io::read_dxf(&bytes).unwrap();
|
||||
assert!(r.entity(Handle::parse_hex(NEAR_TOP).unwrap()).is_some(), "the file's handle did not survive the save");
|
||||
assert!(r.entity(n).is_some(), "the new handle did not survive the save");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nine_objects_drawn_after_a_saturated_seed_save_and_reopen_distinct() {
|
||||
// The nine-entity case from #2237: a saturated $HANDSEED, ordinary entity handles. Drawing
|
||||
// after the load gives every object its own handle, and a save/reopen keeps them apart.
|
||||
let mut d = read(&dxf(None, TOP));
|
||||
for i in 0..9 {
|
||||
d.add(&Space::Model, Common::default(), line(f64::from(i), 40.0)).unwrap();
|
||||
}
|
||||
let bytes = cadcraft_io::write(&d, "nine.dxf").unwrap();
|
||||
let r = cadcraft_io::read_dxf(&bytes).unwrap();
|
||||
assert_eq!(r.model.len(), 10, "the file's line and the nine drawn ones");
|
||||
let handles = distinct(&r);
|
||||
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
|
||||
assert_eq!(unique.len(), handles.len(), "repeated handles on reopen: {handles:?}");
|
||||
}
|
||||
|
||||
/// The first handle in the reserved band above [`HANDLE_LIMIT`].
|
||||
const BAND: &str = "FFFFFFFF00000000";
|
||||
|
||||
#[test]
|
||||
fn a_seed_in_the_reserved_band_does_not_hand_out_the_files_handle() {
|
||||
// #913's remaining case: a file says its next handle is FFFFFFFF00000000 and an object holds
|
||||
// that handle. Following the seed once would hand the object's handle to the new object, and
|
||||
// `EntityStore` would replace the file's line.
|
||||
let mut d = read(&dxf(Some(BAND), BAND));
|
||||
assert_eq!(d.model.len(), 1);
|
||||
let n = d.add(&Space::Model, Common::default(), line(10.0, 10.0)).unwrap();
|
||||
assert_ne!(n, Handle::parse_hex(BAND).unwrap(), "the new object took the file object's handle");
|
||||
assert_eq!(d.model.len(), 2, "the file's line was replaced");
|
||||
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the file's line is gone");
|
||||
|
||||
let bytes = cadcraft_io::write(&d, "band-seed.dxf").unwrap();
|
||||
let r = cadcraft_io::read_dxf(&bytes).unwrap();
|
||||
let handles = distinct(&r);
|
||||
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
|
||||
assert_eq!(unique.len(), handles.len(), "repeated handles on reopen: {handles:?}");
|
||||
assert_eq!(r.model.len(), 2, "a line did not survive the save");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_save_does_not_give_a_structural_record_an_objects_handle() {
|
||||
// The writer numbers its own records from `seed + 0x1000`; with the seed at the bottom of the
|
||||
// reserved band that lands on the file's own handle. The file must keep one record per handle.
|
||||
let object = "FFFFFFFF00001000";
|
||||
let d = read(&dxf(Some(object), "FFFFFFFEFFFFFFFF"));
|
||||
let bytes = cadcraft_io::write(&d, "band-structural.dxf").unwrap();
|
||||
let tags = craft_dxf::parse(&bytes).unwrap();
|
||||
// Record handles start with the TABLES section; before it the HEADER's `$HANDSEED` is the
|
||||
// next free handle, not a record's.
|
||||
let after_header = tags.iter().position(|t| t.code == 2 && t.str() == "TABLES").unwrap();
|
||||
let written: Vec<String> = tags[after_header..].iter().filter(|t| t.code == 5 || t.code == 105).map(|t| t.str().to_string()).collect();
|
||||
let unique: std::collections::HashSet<&String> = written.iter().collect();
|
||||
assert_eq!(unique.len(), written.len(), "the save repeats a handle: {written:?}");
|
||||
assert_eq!(written.iter().filter(|h| h.as_str() == object).count(), 1, "the object's handle was not written exactly once");
|
||||
|
||||
let r = cadcraft_io::read_dxf(&bytes).unwrap();
|
||||
assert!(r.entity(Handle::parse_hex(object).unwrap()).is_some(), "the file's object is gone");
|
||||
}
|
||||
|
||||
/// A CADCraft-marked file with a handle-less block entity and an `ENTITIES` record that names
|
||||
/// the handle the reader would give it. The marker means the reader skips the handle pre-scan,
|
||||
/// so the two sections must still reserve against each other.
|
||||
fn marked_file_with_handle_less_block_entity() -> String {
|
||||
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n1000\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nBLOCKS\n\
|
||||
0\nBLOCK\n8\n0\n2\n*MODEL_SPACE\n70\n0\n10\n0.0\n20\n0.0\n30\n0.0\n3\n*MODEL_SPACE\n1\n\n\
|
||||
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n0.0\n31\n0.0\n\
|
||||
0\nENDBLK\n8\n0\n\
|
||||
0\nENDSEC\n\
|
||||
0\nSECTION\n2\nENTITIES\n\
|
||||
0\nLINE\n5\n100\n8\n0\n10\n10.0\n20\n0.0\n30\n0.0\n11\n11.0\n21\n0.0\n31\n0.0\n\
|
||||
0\nENDSEC\n\
|
||||
0\nSECTION\n2\nOBJECTS\n\
|
||||
0\nXRECORD\n5\n300\n100\nAcDbXrecord\n3\nCADCRAFT_HANDSEED\n1\n1000\n\
|
||||
0\nENDSEC\n0\nEOF\n"
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marked_files_sections_reserve_handles_against_each_other() {
|
||||
// The block entity has no handle of its own, so the reader gives it one; a later ENTITIES
|
||||
// record must not be given the same handle, or one entity silently replaces the other.
|
||||
let d = read(&marked_file_with_handle_less_block_entity());
|
||||
assert_eq!(d.model.len(), 2, "one entity replaced the other");
|
||||
let handles = distinct(&d);
|
||||
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
|
||||
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
|
||||
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the block entity is gone");
|
||||
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 10.0)), "the ENTITIES line is gone");
|
||||
}
|
||||
|
||||
/// A file whose BLOCKS holds a handle-less model-space entity and whose ENTITIES names the
|
||||
/// last handle below the reserved band and the first handle in it. With `marked` the file names
|
||||
/// CADCraft's own seed record, which narrows the reader's handle pre-scan to the entity sections.
|
||||
fn file_with_reserved_band_entities(marked: bool) -> String {
|
||||
let below = format!("{:X}", cadcraft_doc::HANDLE_LIMIT - 1);
|
||||
let band = format!("{:X}", cadcraft_doc::HANDLE_LIMIT);
|
||||
let objects = if marked {
|
||||
"0\nSECTION\n2\nOBJECTS\n\
|
||||
0\nXRECORD\n5\n300\n100\nAcDbXrecord\n3\nCADCRAFT_HANDSEED\n1\n1000\n\
|
||||
0\nENDSEC\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
format!(
|
||||
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n1000\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nBLOCKS\n\
|
||||
0\nBLOCK\n8\n0\n2\n*MODEL_SPACE\n70\n0\n10\n0.0\n20\n0.0\n30\n0.0\n3\n*MODEL_SPACE\n1\n\n\
|
||||
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n0.0\n31\n0.0\n\
|
||||
0\nENDBLK\n8\n0\n\
|
||||
0\nENDSEC\n\
|
||||
0\nSECTION\n2\nENTITIES\n\
|
||||
0\nLINE\n5\n{below}\n8\n0\n10\n10.0\n20\n0.0\n30\n0.0\n11\n11.0\n21\n0.0\n31\n0.0\n\
|
||||
0\nLINE\n5\n{band}\n8\n0\n10\n20.0\n20\n0.0\n30\n0.0\n11\n21.0\n21\n0.0\n31\n0.0\n\
|
||||
0\nENDSEC\n{objects}0\nEOF\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// All three lines survive with their own handles: the handle-less block entity could not take
|
||||
/// the reserved-band handle of the file's own ENTITIES record.
|
||||
fn assert_three_lines_survive(d: &Drawing) {
|
||||
assert_eq!(d.model.len(), 3, "one entity replaced another");
|
||||
let handles = distinct(d);
|
||||
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
|
||||
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
|
||||
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the block entity is gone");
|
||||
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 10.0)), "the line below the band is gone");
|
||||
assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 20.0)), "the line in the band is gone");
|
||||
// The band's explicit handle stays with the record that names it.
|
||||
let band = Handle(cadcraft_doc::HANDLE_LIMIT);
|
||||
let owner = d.model.iter().find(|e| e.handle == band).expect("the band handle was renumbered");
|
||||
assert!(matches!(&owner.kind, EntityKind::Line(l) if l.a.x == 20.0), "the band handle moved to another line");
|
||||
// The handle just below the band is the file's too, and it stays with its own record.
|
||||
let below = Handle(cadcraft_doc::HANDLE_LIMIT - 1);
|
||||
let owner = d.model.iter().find(|e| e.handle == below).expect("the below-band handle was renumbered");
|
||||
assert!(matches!(&owner.kind, EntityKind::Line(l) if l.a.x == 10.0), "the below-band handle moved to another line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_band_handles_in_entities_are_not_handed_to_a_handle_less_block_entity() {
|
||||
// The handle below the reserved band is the file's, so the reader's next handle is the first
|
||||
// handle in the band, which an ENTITIES record already owns. The seed cannot follow it
|
||||
// (#913), so the handle is reserved for allocation instead: the handle-less model-space
|
||||
// block entity must not take it and replace the file's line.
|
||||
assert_three_lines_survive(&read(&file_with_reserved_band_entities(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_band_handles_are_reserved_without_the_cadcraft_seed_record() {
|
||||
// The same reservation holds when the pre-scan reads every section's handles: a handle in
|
||||
// the band is the file's own there too, and still must not be given away.
|
||||
assert_three_lines_survive(&read(&file_with_reserved_band_entities(false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reservations_end_with_the_read_and_placed_objects_still_keep_their_handles() {
|
||||
// The reservations only bridge the gap until a record is placed; a drawing does not carry
|
||||
// them on (every undo step copies the drawing). The placed objects keep new ones off.
|
||||
let mut d = read(&file_with_reserved_band_entities(true));
|
||||
assert!(d.reserved_handles.is_empty(), "the reader's reservations outlived the read");
|
||||
for i in 0..3 {
|
||||
d.add(&Space::Model, Common::default(), line(f64::from(i), 50.0)).unwrap();
|
||||
}
|
||||
assert_eq!(d.model.len(), 6, "a new object replaced one of the file's");
|
||||
assert_three_lines_survive_among(&d);
|
||||
}
|
||||
|
||||
fn assert_three_lines_survive_among(d: &Drawing) {
|
||||
let band = Handle(cadcraft_doc::HANDLE_LIMIT);
|
||||
assert!(d.model.iter().any(|e| e.handle == band && matches!(&e.kind, EntityKind::Line(l) if l.a.x == 20.0)), "the band line lost its handle");
|
||||
let handles = distinct(d);
|
||||
let unique: std::collections::HashSet<Handle> = handles.iter().copied().collect();
|
||||
assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_geometry_never_takes_a_handle_an_object_holds() {
|
||||
// The drawing's own handles sit in the reserved band and the seed is at the top of the
|
||||
// range, so the writer's structural numbering wraps into the band. Every other band handle
|
||||
// is taken, so without a check the generated dimension block's entities land on an occupied
|
||||
// one: the saved file would repeat a handle.
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.handseed = u64::MAX - 1;
|
||||
{
|
||||
let model = d.space_mut(&Space::Model).unwrap();
|
||||
for i in 0..200u64 {
|
||||
let handle = Handle(cadcraft_doc::HANDLE_LIMIT + 1 + 2 * i);
|
||||
model.push(Entity { handle, common: Common::default(), kind: line(i as f64, 0.0) });
|
||||
}
|
||||
model.push(Entity {
|
||||
handle: Handle(0x200),
|
||||
common: Common::default(),
|
||||
kind: EntityKind::Dimension(Dimension {
|
||||
kind: DimKind::Linear { rotation: 0.0 },
|
||||
defpt: Vec3::new(0.0, 1.0, 0.0),
|
||||
text_mid: Vec3::new(1.0, 1.0, 0.0),
|
||||
p13: Vec3::ZERO,
|
||||
p14: Vec3::new(2.0, 0.0, 0.0),
|
||||
p15: Vec3::ZERO,
|
||||
p16: Vec3::ZERO,
|
||||
text: String::new(),
|
||||
style: "Standard".into(),
|
||||
measurement: 2.0,
|
||||
text_rotation: 0.0,
|
||||
user_text_pos: false,
|
||||
block: None,
|
||||
insertion_point: Vec3::ZERO,
|
||||
overrides: serde_json::Map::new(),
|
||||
assoc: Vec::new(),
|
||||
marks: Default::default(),
|
||||
}),
|
||||
});
|
||||
}
|
||||
let bytes = cadcraft_io::write(&d, "generated.dxf").unwrap();
|
||||
let tags = craft_dxf::parse(&bytes).unwrap();
|
||||
let after_header = tags.iter().position(|t| t.code == 2 && t.str() == "TABLES").unwrap();
|
||||
let written: Vec<String> = tags[after_header..].iter().filter(|t| t.code == 5 || t.code == 105).map(|t| t.str().to_string()).collect();
|
||||
let unique: std::collections::HashSet<&String> = written.iter().collect();
|
||||
assert_eq!(unique.len(), written.len(), "the save repeats a handle");
|
||||
}
|
||||
|
||||
/// A line at the top handle with another application's xdata, and that application's object kept
|
||||
/// from the file: a dictionary in the named object dictionary holding an XRECORD.
|
||||
fn top_line_with_kept_objects() -> String {
|
||||
let groups: &[(i32, &str)] = &[
|
||||
(0, "SECTION"),
|
||||
(2, "ENTITIES"),
|
||||
(0, "LINE"),
|
||||
(5, TOP),
|
||||
(8, "0"),
|
||||
(10, "0"),
|
||||
(20, "0"),
|
||||
(11, "10"),
|
||||
(21, "0"),
|
||||
(1001, "OTHER_APP"),
|
||||
(1000, "tagged"),
|
||||
(0, "ENDSEC"),
|
||||
(0, "SECTION"),
|
||||
(2, "OBJECTS"),
|
||||
(0, "DICTIONARY"),
|
||||
(5, "C"),
|
||||
(330, "0"),
|
||||
(100, "AcDbDictionary"),
|
||||
(3, "OTHER_APP"),
|
||||
(350, "50"),
|
||||
(0, "DICTIONARY"),
|
||||
(5, "50"),
|
||||
(330, "C"),
|
||||
(100, "AcDbDictionary"),
|
||||
(281, "1"),
|
||||
(3, "DATA"),
|
||||
(360, "51"),
|
||||
(0, "XRECORD"),
|
||||
(5, "51"),
|
||||
(330, "50"),
|
||||
(100, "AcDbXrecord"),
|
||||
(280, "1"),
|
||||
(1, "kept"),
|
||||
(0, "ENDSEC"),
|
||||
(0, "EOF"),
|
||||
];
|
||||
groups.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_added_on_save_after_the_top_handle_take_free_handles() {
|
||||
// The writer adds the kept objects (and any application id the xdata needs) after its own
|
||||
// records, numbered above the largest handle written. That is the file's line at the top of
|
||||
// the range: counting on from it would give every added record the line's handle.
|
||||
let d = read(&top_line_with_kept_objects());
|
||||
let bytes = cadcraft_io::write(&d, "kept-top.dxf").unwrap();
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
assert!(text.contains("\nkept"), "the kept XRECORD was not written");
|
||||
let tags = craft_dxf::parse(&bytes).unwrap();
|
||||
let after_header = tags.iter().position(|t| t.code == 2 && t.str() == "TABLES").unwrap();
|
||||
let written: Vec<String> = tags[after_header..].iter().filter(|t| t.code == 5 || t.code == 105).map(|t| t.str().to_string()).collect();
|
||||
let unique: std::collections::HashSet<&String> = written.iter().collect();
|
||||
assert_eq!(unique.len(), written.len(), "the save repeats a handle: {written:?}");
|
||||
assert_eq!(written.iter().filter(|h| h.as_str() == TOP).count(), 1, "the line's handle was not written exactly once");
|
||||
|
||||
let r = read(&String::from_utf8_lossy(&bytes));
|
||||
assert!(r.entity(Handle::parse_hex(TOP).unwrap()).is_some(), "the file's line is gone");
|
||||
}
|
||||
@@ -26,7 +26,6 @@ fn preserves_or_refuses(path: &str, binary: bool) {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Confirmed DXF data loss: exhausted generated handles produce a successful save that reopens with no model entities"]
|
||||
fn dxf_exhausted_handles_are_preserved_or_refused() {
|
||||
for binary in [false, true] {
|
||||
preserves_or_refuses("memory.dxf", binary);
|
||||
|
||||
@@ -16,8 +16,8 @@ fn import(transform: &str) -> (f64, f64) {
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let (dx, dy) = (e.major.x - e.center.x, e.major.y - e.center.y);
|
||||
(dy.atan2(dx), e.ratio)
|
||||
// `major` is the axis from the centre (#2821).
|
||||
(e.major.y.atan2(e.major.x), e.ratio)
|
||||
}
|
||||
|
||||
/// Major-axis angle and ratio of the image of the ellipse under the 2x2 map `[a c; b d]`, with
|
||||
|
||||
@@ -36,7 +36,6 @@ mod selection_cycling;
|
||||
mod shared_controls;
|
||||
mod shortcut_menus;
|
||||
mod shortcuts_checked;
|
||||
mod space_at_options;
|
||||
mod status_bar_toggles;
|
||||
mod style_dialogs;
|
||||
mod system_cursor;
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
//! Space is Enter at TRIM's and EXTEND's option prompts, as at AutoCAD's (#3092): typing `O`,
|
||||
//! Space, `S`, Space switches to Standard mode instead of typing a space into the command line.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use egui::{Key, Modifiers, vec2};
|
||||
use egui_kittest::Harness;
|
||||
|
||||
fn harness() -> Harness<'static, CadApp> {
|
||||
let app = CadApp::new(Session::new(), Services::default());
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(3);
|
||||
h
|
||||
}
|
||||
|
||||
/// Type `text` at the keyboard: a space arrives as the Space key and as text, like a real press.
|
||||
fn type_keys(h: &mut Harness<'static, CadApp>, text: &str) {
|
||||
for c in text.chars() {
|
||||
if c == ' ' {
|
||||
h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
|
||||
}
|
||||
h.event(egui::Event::Text(c.to_string()));
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
fn header(h: &Harness<'static, CadApp>, name: &str) -> i64 {
|
||||
h.state().session.doc().unwrap().header.i64(name, -1)
|
||||
}
|
||||
|
||||
fn prompt(h: &Harness<'static, CadApp>) -> String {
|
||||
h.state().session.current_prompt().map(|p| p.message).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn space_answers_trim_and_extend_option_prompts() {
|
||||
let mut h = harness();
|
||||
type_keys(&mut h, "trim o s ");
|
||||
assert_eq!(h.state().cmd.buffer, "", "Space typed a space instead of entering the option");
|
||||
assert_eq!(header(&h, "TRIMEXTENDMODE"), 0, "S chose Standard mode");
|
||||
// Standard mode asks for cutting edges; Enter selects all, then Project and Edge.
|
||||
type_keys(&mut h, " p n e e ");
|
||||
assert_eq!(h.state().cmd.buffer, "");
|
||||
assert_eq!(header(&h, "PROJMODE"), 0, "N chose no projection");
|
||||
assert_eq!(header(&h, "EDGEMODE"), 1, "E chose Extend");
|
||||
assert!(prompt(&h).starts_with("Select object to trim"), "back at the trim prompt: {}", prompt(&h));
|
||||
h.key_press(Key::Escape);
|
||||
h.run_steps(2);
|
||||
type_keys(&mut h, "extend o q ");
|
||||
assert_eq!(h.state().cmd.buffer, "");
|
||||
assert_eq!(header(&h, "TRIMEXTENDMODE"), 1, "Q chose Quick mode in EXTEND");
|
||||
}
|
||||
Reference in New Issue
Block a user