mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-19 20:30:42 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5a5cb1a676 | ||
|
|
cbacaff9e0 | ||
|
|
b86caba676 | ||
|
|
23962d68e2 | ||
|
|
61d0575611 | ||
|
|
7cb74443c4 | ||
|
|
7515b2bc69 | ||
|
|
9e3d38fd5f | ||
|
|
8c2d67531c | ||
|
|
1d16bb8ba0 | ||
|
|
7a65b01453 | ||
|
|
ead93c6797 | ||
|
|
c0cc3f8509 | ||
|
|
ee8922b1d7 | ||
|
|
e04ceb2d5d | ||
|
|
81b3e6ba08 | ||
|
|
78506d3bd2 | ||
|
|
03f9139344 | ||
|
|
9cfe8a6daa | ||
|
|
41f1496f7d | ||
|
|
67124500c6 | ||
|
|
30e3ae0767 | ||
|
|
a284313f27 | ||
|
|
026f7d906b | ||
|
|
5b622c3d32 | ||
|
|
56246049bc | ||
|
|
97f753d6c1 | ||
|
|
404988f67a | ||
|
|
d75bc7fa60 | ||
|
|
935e13cc52 | ||
|
|
8157cd2fc1 | ||
|
|
f99307f2cd | ||
|
|
a8be418d8c | ||
|
|
a0c76b6726 | ||
|
|
51b3e8b112 | ||
|
|
f1790d2be7 | ||
|
|
deca6b1062 | ||
|
|
cddef1755b | ||
|
|
abd72f3f19 | ||
|
|
d80c055839 | ||
|
|
7ce2eea0c0 | ||
|
|
2616d46ec4 | ||
|
|
adc1876809 | ||
|
|
54d6c4eed8 | ||
|
|
a06bb18b58 | ||
|
|
9938d5aa0e | ||
|
|
a3b81b6ac2 | ||
|
|
2cfd068c1f | ||
|
|
9c862c01ba | ||
|
|
37a8c6e036 | ||
|
|
07a78159e4 | ||
|
|
9419abb274 | ||
|
|
5dd37f917f | ||
|
|
4a4012d22f | ||
|
|
fb5f68328d | ||
|
|
d204518d8a | ||
|
|
25014b77b8 | ||
|
|
e98201c282 | ||
|
|
97f889733d | ||
|
|
3f347ea431 | ||
|
|
a44308f4aa | ||
|
|
f6e56d97f6 | ||
|
|
940e3de914 | ||
|
|
b29a1398a4 | ||
|
|
4346beec72 | ||
|
|
f8f81b431d | ||
|
|
3711c8c762 | ||
|
|
e660b0dbe4 | ||
|
|
b077e22f40 | ||
|
|
33aaf7096c | ||
|
|
baf1889912 | ||
|
|
6125f57084 | ||
|
|
3203a607e2 | ||
|
|
ef4bb85059 | ||
|
|
5da9d3f539 | ||
|
|
72add0b90e | ||
|
|
a0e023d758 | ||
|
|
44547941cc | ||
|
|
99e3b93bd5 | ||
|
|
b692cbe0dd | ||
|
|
99b7dc808f | ||
|
|
fed42f45b2 | ||
|
|
be56597e5f | ||
|
|
1350e1b18f | ||
|
|
d7de5ccdf3 | ||
|
|
0bf32bba90 | ||
|
|
821b8ad18c | ||
|
|
5cfe5f84b0 | ||
|
|
e3aeff2a9b | ||
|
|
3f14431a33 | ||
|
|
9f833f3d16 | ||
|
|
4fee981bd4 | ||
|
|
bc7357ffb8 |
@@ -44,7 +44,6 @@ fn snapshot(ui: &UiState) -> Result<Value, String> {
|
||||
"showStatusBar": ui.show_status_bar,
|
||||
"showCommandLine": ui.show_command_line,
|
||||
"showViewcube": ui.show_viewcube,
|
||||
"showUcsIcon": ui.show_ucs_icon,
|
||||
"showLayerList": ui.show_layer_list,
|
||||
"toolsetTab": ui.toolset_tab,
|
||||
"collapsedGroups": ui.collapsed_groups,
|
||||
|
||||
@@ -130,6 +130,10 @@ pub struct Drawing {
|
||||
/// 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>,
|
||||
/// Model space's earlier UCSs for UCS Previous, oldest first (each layout keeps its own,
|
||||
/// [`Layout::ucs_previous`]). Part of the drawing so undo restores them with the UCS. Never
|
||||
/// written to a file.
|
||||
pub ucs_previous: Vec<Ucs>,
|
||||
/// What reading the file left out (a DWG's object records the reader couldn't decode), told
|
||||
/// to the user when the drawing opens. Never written to a file.
|
||||
pub read_notes: Vec<String>,
|
||||
@@ -201,6 +205,7 @@ impl Drawing {
|
||||
scales: imperial_scales(),
|
||||
handseed: 0x100,
|
||||
hidden_objects: BTreeSet::new(),
|
||||
ucs_previous: Vec::new(),
|
||||
read_notes: Vec::new(),
|
||||
refedit: None,
|
||||
skipped_records: BTreeMap::new(),
|
||||
|
||||
@@ -857,6 +857,14 @@ pub struct Layout {
|
||||
/// Saved paper-space view (centre, height).
|
||||
#[serde(default)]
|
||||
pub view: Option<(Vec2, f64)>,
|
||||
/// The layout's current paper-space UCS (the LAYOUT object's groups 13, 16, 17 and 345);
|
||||
/// `None`: the World UCS. Its name is empty when it isn't a named UCS.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub ucs: Option<Ucs>,
|
||||
/// The layout's earlier UCSs for UCS Previous, oldest first: they go with the layout when it
|
||||
/// is renamed and with it when it is deleted. Never written to a file.
|
||||
#[serde(skip)]
|
||||
pub ucs_previous: Vec<Ucs>,
|
||||
/// The layout's limits (LAYOUT groups 10/11, lower left and upper right) as the file had
|
||||
/// them; `None` for a layout CADCraft made, written as 0,0 to 12,9 (#2109).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -865,7 +873,16 @@ pub struct Layout {
|
||||
|
||||
impl Layout {
|
||||
pub fn new(name: &str, tab_order: u32) -> Self {
|
||||
Layout { name: name.into(), tab_order, page: PageSetup::default(), entities: EntityStore::new(), view: None, limits: None }
|
||||
Layout {
|
||||
name: name.into(),
|
||||
tab_order,
|
||||
page: PageSetup::default(),
|
||||
entities: EntityStore::new(),
|
||||
view: None,
|
||||
ucs: None,
|
||||
ucs_previous: Vec::new(),
|
||||
limits: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ mod tolerance;
|
||||
mod trimextend;
|
||||
mod txt2mtxt;
|
||||
pub use txt2mtxt::Txt2MtxtOptions;
|
||||
mod ucs;
|
||||
mod utility;
|
||||
mod view;
|
||||
|
||||
@@ -187,6 +188,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(qselect::specs());
|
||||
v.extend(selecttools::specs());
|
||||
v.extend(view::specs());
|
||||
v.extend(ucs::specs());
|
||||
v.extend(draw::specs());
|
||||
v.extend(draw2::specs());
|
||||
v.extend(annotate::specs());
|
||||
|
||||
@@ -35,8 +35,15 @@ fn auto_rotation(p1: Vec2, p2: Vec2, at: Vec2) -> f64 {
|
||||
if outside_x && !outside_y { std::f64::consts::FRAC_PI_2 } else { 0.0 }
|
||||
}
|
||||
|
||||
pub(super) fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option<f64>, aligned: bool) -> DimKind {
|
||||
if aligned { DimKind::Aligned } else { DimKind::Linear { rotation: rotation.unwrap_or_else(|| auto_rotation(p1, p2, at)) } }
|
||||
/// A linear or aligned dimension's kind; without a rotation, horizontal or vertical along axes turned
|
||||
/// `ucs` radians (the current UCS's at the command line; the world's for JSON).
|
||||
pub(super) fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option<f64>, aligned: bool, ucs: f64) -> DimKind {
|
||||
if aligned {
|
||||
return DimKind::Aligned;
|
||||
}
|
||||
let ucs = if ucs.is_finite() { ucs } else { 0.0 };
|
||||
let auto = || auto_rotation(p1.rotate(-ucs), p2.rotate(-ucs), at.rotate(-ucs)) + ucs;
|
||||
DimKind::Linear { rotation: rotation.unwrap_or_else(auto) }
|
||||
}
|
||||
|
||||
/// Add a dimension. With DIMASSOC on, definition points that sit on object endpoints,
|
||||
|
||||
@@ -11,7 +11,7 @@ pub(super) fn run_linear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let at = point_req("dimlinear", p, "at")?;
|
||||
let rot = p.get("rotation").and_then(Value::as_f64).map(f64::to_radians);
|
||||
let k = dim(s, linear_kind(a, b, at, rot, false), at, a, b, Vec2::ZERO, str_param(p, "text").unwrap_or(""));
|
||||
let k = dim(s, linear_kind(a, b, at, rot, false, 0.0), at, a, b, Vec2::ZERO, str_param(p, "text").unwrap_or(""));
|
||||
Ok(json!({ "handle": add_dim(s, k)?.hex() }))
|
||||
}
|
||||
|
||||
@@ -216,7 +216,8 @@ impl Interactive for LinearM {
|
||||
}
|
||||
(_, Input::Point(at)) => {
|
||||
let (Some(&a), Some(&b)) = (self.pts.first(), self.pts.get(1)) else { return Ok(Step::Continue) };
|
||||
let k = self.text.apply(dim(s, linear_kind(a, b, at, self.rotation, self.aligned), at, a, b, Vec2::ZERO, ""));
|
||||
let k =
|
||||
self.text.apply(dim(s, linear_kind(a, b, at, self.rotation, self.aligned, s.input_ucs().rotation()), at, a, b, Vec2::ZERO, ""));
|
||||
add_dim(s, k)?;
|
||||
if let Some(EntityKind::Dimension(d)) = s.last_dim.and_then(|h| s.doc().ok()?.entity(h).map(|e| e.kind.clone())) {
|
||||
let st = s.doc()?.dim_style(&d.style).cloned().unwrap_or_default();
|
||||
@@ -227,8 +228,8 @@ impl Interactive for LinearM {
|
||||
}
|
||||
(_, Input::Keyword(k)) => {
|
||||
match k.as_str() {
|
||||
"Horizontal" => self.rotation = Some(0.0),
|
||||
"Vertical" => self.rotation = Some(std::f64::consts::FRAC_PI_2),
|
||||
"Horizontal" => self.rotation = Some(s.input_ucs().rotation()),
|
||||
"Vertical" => self.rotation = Some(s.input_ucs().rotation() + std::f64::consts::FRAC_PI_2),
|
||||
"Rotated" => self.rotating = true,
|
||||
other => {
|
||||
self.text.keyword(other);
|
||||
@@ -243,7 +244,15 @@ impl Interactive for LinearM {
|
||||
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
match self.pts.as_slice() {
|
||||
[a] => vec![crate::cmd::helpers::line(*a, c)],
|
||||
[a, b] => vec![self.text.apply(dim(s, linear_kind(*a, *b, c, self.rotation, self.aligned), c, *a, *b, Vec2::ZERO, ""))],
|
||||
[a, b] => vec![self.text.apply(dim(
|
||||
s,
|
||||
linear_kind(*a, *b, c, self.rotation, self.aligned, s.input_ucs().rotation()),
|
||||
c,
|
||||
*a,
|
||||
*b,
|
||||
Vec2::ZERO,
|
||||
"",
|
||||
))],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("dist", "Distance", run_dist)
|
||||
.menu(&["Tools", "Inquiry", "Distance"])
|
||||
.alias(&["di"])
|
||||
.params("{p1, p2}")
|
||||
.params("{p1, p2} -> {distance, angle, angleFromXY, dx, dy, dz (world), ucs: {angle, angleFromXY, dx, dy, dz} (in the frame typed points are read in: the current UCS, or the World UCS while the UCS is tilted; as the message), message}")
|
||||
.noundo()
|
||||
.transparent()
|
||||
.interactive(|_| Ok(Box::new(DistM::default()))),
|
||||
@@ -192,11 +192,18 @@ fn angle_from_xy(d: Vec3) -> f64 {
|
||||
d.z.atan2(d.xy().len())
|
||||
}
|
||||
|
||||
fn dist_text(s: &Session, a: Vec3, b: Vec3) -> String {
|
||||
let d = b - a;
|
||||
/// The delta from `a` to `b` along the axes of the current UCS (the World UCS while that is
|
||||
/// tilted): what DIST's report shows.
|
||||
fn dist_delta(s: &Session, a: Vec3, b: Vec3) -> Vec3 {
|
||||
let u = s.input_ucs();
|
||||
u.to_ucs3(b) - u.to_ucs3(a)
|
||||
}
|
||||
|
||||
/// DIST's report: the distance, the angles and the deltas `d`, measured in the current UCS.
|
||||
fn dist_text(s: &Session, dist: f64, d: Vec3) -> String {
|
||||
format!(
|
||||
"Distance = {}, Angle in XY Plane = {}, Angle from XY Plane = {}\nDelta X = {}, Delta Y = {}, Delta Z = {}",
|
||||
fmt_d(s, (b - a).len()),
|
||||
fmt_d(s, dist),
|
||||
fmt_a(s, d.xy().angle()),
|
||||
fmt_a(s, angle_from_xy(d)),
|
||||
fmt_d(s, d.x),
|
||||
@@ -222,6 +229,8 @@ fn run_dist(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.distance = d.len();
|
||||
s.last_point = a.xy();
|
||||
// Top level: the world values, as ID's x, y, z are; `ucs` has what the message shows.
|
||||
let du = dist_delta(s, a, b);
|
||||
Ok(json!({
|
||||
"distance": d.len(),
|
||||
"angle": d.xy().angle().to_degrees(),
|
||||
@@ -229,18 +238,28 @@ fn run_dist(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"dx": d.x,
|
||||
"dy": d.y,
|
||||
"dz": d.z,
|
||||
"message": dist_text(s, a, b),
|
||||
"ucs": {
|
||||
"angle": du.xy().angle().to_degrees(),
|
||||
"angleFromXY": angle_from_xy(du).to_degrees(),
|
||||
"dx": du.x,
|
||||
"dy": du.y,
|
||||
"dz": du.z,
|
||||
},
|
||||
"message": dist_text(s, d.len(), du),
|
||||
}))
|
||||
}
|
||||
|
||||
/// ID's report: the point in the current UCS.
|
||||
fn id_text(s: &Session, a: Vec3) -> String {
|
||||
format!("X = {} Y = {} Z = {}", fmt_d(s, a.x), fmt_d(s, a.y), fmt_d(s, a.z))
|
||||
let u = s.input_ucs().to_ucs3(a);
|
||||
format!("X = {} Y = {} Z = {}", fmt_d(s, u.x), fmt_d(s, u.y), fmt_d(s, u.z))
|
||||
}
|
||||
|
||||
fn run_id(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = point3_req(s, "id", p, "at")?;
|
||||
s.last_point = a.xy();
|
||||
Ok(json!({ "x": a.x, "y": a.y, "z": a.z, "message": id_text(s, a) }))
|
||||
let u = s.input_ucs().to_ucs3(a);
|
||||
Ok(json!({ "x": a.x, "y": a.y, "z": a.z, "ucs": [u.x, u.y, u.z], "message": id_text(s, a) }))
|
||||
}
|
||||
|
||||
/// The Z of what is drawn at `p`: the object a pick finds there, at that point, or the current
|
||||
@@ -900,7 +919,7 @@ impl Interactive for DistM {
|
||||
s.last_point = first;
|
||||
return Err(bad("dist", "the distance is too large"));
|
||||
}
|
||||
let t = dist_text(s, a, b);
|
||||
let t = dist_text(s, (b - a).len(), dist_delta(s, a, b));
|
||||
for l in t.lines() {
|
||||
s.echo(l.to_string());
|
||||
}
|
||||
|
||||
@@ -313,7 +313,16 @@ fn run_copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let h = d.new_handle();
|
||||
store.push(Entity { handle: h, ..Entity::clone(e) });
|
||||
}
|
||||
d.layouts.push(Layout { name: to.clone(), tab_order: order, page: src.page, entities: store, view: src.view, limits: src.limits });
|
||||
d.layouts.push(Layout {
|
||||
name: to.clone(),
|
||||
tab_order: order,
|
||||
page: src.page,
|
||||
entities: store,
|
||||
view: src.view,
|
||||
ucs: src.ucs,
|
||||
ucs_previous: Vec::new(),
|
||||
limits: src.limits,
|
||||
});
|
||||
Ok(json!({ "name": to }))
|
||||
}
|
||||
|
||||
|
||||
@@ -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(),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,675 @@
|
||||
//! UCS an UCSICON: the current user coordinate system ([`crate::ucs`]) and its icon.
|
||||
//!
|
||||
//! UCS sets the current UCS of the space commands act on: by an origin and points on the new X
|
||||
//! axis and XY plane (the default option), World, Previous, NAmed (Restore, Save, Delete, `?`),
|
||||
//! OBject (lined up with an object), View and Z (a turn about Z). X, Y, ZAxis and Face tilt the
|
||||
//! UCS out of the XY plane, which CADCraft doesn't draw in yet; they say so. A UCS change is part
|
||||
//! of the command's undo step, as an edit is.
|
||||
|
||||
use cadcraft_doc::{Drawing, EntityKind, Ucs};
|
||||
use cadcraft_geom::{Vec2, Vec3};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::utility::num_text;
|
||||
use super::{CommandSpec, bad, str_param};
|
||||
use crate::prompt::{Accept, Input, Interactive, Prompt, Step};
|
||||
use crate::ucs::{UcsFrame, named};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// The UCS command's options, as typed.
|
||||
const OPTIONS: &[&str] = &["Face", "NAmed", "OBject", "Previous", "View", "World", "X", "Y", "Z", "ZAxis"];
|
||||
|
||||
/// Characters a UCS name can't hold.
|
||||
const BAD_NAME_CHARS: &[char] = &['<', '>', '/', '\\', '"', ':', ';', '?', '*', '|', ',', '=', '`'];
|
||||
|
||||
/// Longest UCS name.
|
||||
const MAX_NAME: usize = 255;
|
||||
|
||||
/// Most UCS table records a drawing keeps (a hostile script can't grow it without bound).
|
||||
const MAX_NAMED: usize = 10_000;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("ucs", "UCS", run_ucs)
|
||||
.params(
|
||||
"{option?: origin|world|previous|named|object|view|z|x|y|zaxis|face (default origin), origin?: [x,y(,z)], xPoint?, xyPoint? \
|
||||
(origin: the new origin, and points on its positive X axis and on the positive-Y side of its XY plane; without them \
|
||||
the axes stay), angle? (z: degrees counterclockwise about Z, default UCSAXISANG), action?: restore|save|delete|list \
|
||||
(named), name? (named; delete and list take wildcards and commas), replace?: bool (save over an existing name), \
|
||||
handle?, at? (object: the object and the point it is picked at)} → {ucs: {name, origin, xAxis, yAxis}}. Points \
|
||||
are world coordinates. x, y, zaxis and face tilt the UCS out of the XY plane and are not available yet.",
|
||||
)
|
||||
.interactive(|_| Ok(Box::new(UcsM::default()))),
|
||||
CommandSpec::new("ucs.world", "World", |s, p| run_ucs(s, &with_option(p, "world")))
|
||||
.menu(&["Tools", "New UCS", "World"])
|
||||
.params("{} (the World UCS)"),
|
||||
CommandSpec::new("ucs.origin", "Origin", |s, p| run_ucs(s, &with_option(p, "origin")))
|
||||
.menu(&["Tools", "New UCS", "Origin"])
|
||||
.params("{origin: [x,y(,z)]} (moves the UCS, keeping its axes)")
|
||||
.interactive(|_| Ok(Box::new(UcsM::starting(Stage::OriginOnly)))),
|
||||
CommandSpec::new("ucs.3point", "3 Point", |s, p| run_ucs(s, &with_option(p, "origin")))
|
||||
.menu(&["Tools", "New UCS", "3 Point"])
|
||||
.params("{origin, xPoint?, xyPoint?} (as `ucs` origin)")
|
||||
.interactive(|_| Ok(Box::new(UcsM::starting(Stage::ThreePoint)))),
|
||||
CommandSpec::new("ucs.view", "View", |s, p| run_ucs(s, &with_option(p, "view")))
|
||||
.menu(&["Tools", "New UCS", "View"])
|
||||
.params("{} (XY plane square to the view, X along the screen's horizontal so it follows the view twist, origin kept)"),
|
||||
CommandSpec::new("ucs.z", "Z", |s, p| run_ucs(s, &with_option(p, "z")))
|
||||
.menu(&["Tools", "New UCS", "Z"])
|
||||
.params("{angle?} (degrees counterclockwise about Z, default UCSAXISANG)")
|
||||
.interactive(|_| Ok(Box::new(UcsM::starting(Stage::ZAngle)))),
|
||||
CommandSpec::new("ucsicon", "UCS Icon", run_ucsicon)
|
||||
.params("{on?: bool, origin?: bool} (UCSICON: the icon shown, and at the UCS origin when that is on screen) → {on, origin}")
|
||||
// Undoable like SETVAR: UCSICON lives in the drawing, so without a step of its own an
|
||||
// undo of the edit before it would put the old value back.
|
||||
.interactive(|_| Ok(Box::new(UcsIconM))),
|
||||
]
|
||||
}
|
||||
|
||||
fn with_option(p: &Value, option: &str) -> Value {
|
||||
let mut p = if p.is_object() { p.clone() } else { json!({}) };
|
||||
if let Some(o) = p.as_object_mut() {
|
||||
o.insert("option".into(), json!(option));
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// A JSON point with an optional Z: `[x, y]`, `[x, y, z]` or `{x, y, z?}`.
|
||||
fn point3(v: &Value) -> Option<Vec3> {
|
||||
let p = if let Some(a) = v.as_array() {
|
||||
Vec3::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2).and_then(Value::as_f64).unwrap_or(0.0))
|
||||
} else {
|
||||
Vec3::new(v.get("x")?.as_f64()?, v.get("y")?.as_f64()?, v.get("z").and_then(Value::as_f64).unwrap_or(0.0))
|
||||
};
|
||||
p.is_finite().then_some(p)
|
||||
}
|
||||
|
||||
fn point3_param(cmd: &str, p: &Value, key: &str) -> Result<Option<Vec3>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => point3(v).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a finite point [x, y] or [x, y, z]"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `UCS` as JSON: the result is the new current UCS.
|
||||
fn run_ucs(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let option = str_param(p, "option").unwrap_or("origin").trim().to_ascii_lowercase();
|
||||
match option.as_str() {
|
||||
"origin" | "3point" => {
|
||||
let origin = point3_param("ucs", p, "origin")?.ok_or_else(|| bad("ucs", "`origin` ([x, y] or [x, y, z]) is required"))?;
|
||||
let x = point3_param("ucs", p, "xPoint")?;
|
||||
let xy = point3_param("ucs", p, "xyPoint")?;
|
||||
if xy.is_some() && x.is_none() {
|
||||
return Err(bad("ucs", "`xyPoint` needs `xPoint`"));
|
||||
}
|
||||
set_by_points(s, origin, x, xy)?;
|
||||
}
|
||||
"world" | "w" => s.set_ucs(UcsFrame::WORLD, "")?,
|
||||
"previous" | "p" => {
|
||||
if !s.ucs_previous()? {
|
||||
return Err(bad("ucs", "there is no previous UCS"));
|
||||
}
|
||||
}
|
||||
"view" | "v" => s.set_ucs(view_ucs(s), "")?,
|
||||
"z" => {
|
||||
let deg = match p.get("angle") {
|
||||
None | Some(Value::Null) => axis_angle(s),
|
||||
Some(v) => v.as_f64().filter(|a| a.is_finite()).ok_or_else(|| bad("ucs", "`angle` must be a finite number of degrees"))?,
|
||||
};
|
||||
rotate_z(s, deg.to_radians())?;
|
||||
}
|
||||
"object" | "ob" => {
|
||||
let h = super::targets(s, p)?.first().copied().ok_or_else(|| bad("ucs", "`handle` (the object) is required"))?;
|
||||
let at = p.get("at").and_then(super::point_value);
|
||||
set_by_object(s, h, at)?;
|
||||
}
|
||||
"named" | "na" => {
|
||||
let action = str_param(p, "action").unwrap_or("restore").trim().to_ascii_lowercase();
|
||||
let name = str_param(p, "name").map(str::trim).unwrap_or_default().to_string();
|
||||
match action.as_str() {
|
||||
"restore" | "r" => restore(s, &name).map_err(|e| bad("ucs", e))?,
|
||||
"save" | "s" => save(s, &name, p.get("replace").and_then(Value::as_bool).unwrap_or(false)).map_err(|e| bad("ucs", e))?,
|
||||
"delete" | "d" => {
|
||||
let n = delete(s, if name.is_empty() { "" } else { &name })?;
|
||||
return Ok(json!({ "deleted": n, "ucs": ucs_json(s) }));
|
||||
}
|
||||
"list" | "?" => return Ok(json!({ "list": list(s, if name.is_empty() { "*" } else { &name }), "ucs": ucs_json(s) })),
|
||||
other => return Err(bad("ucs", format!("unknown named action `{other}` (restore, save, delete or list)"))),
|
||||
}
|
||||
}
|
||||
"x" | "y" | "zaxis" | "za" | "face" | "f" => return Err(bad("ucs", tilted_message(&option))),
|
||||
other => return Err(bad("ucs", format!("unknown option `{other}`"))),
|
||||
}
|
||||
Ok(json!({ "ucs": ucs_json(s) }))
|
||||
}
|
||||
|
||||
fn ucs_json(s: &Session) -> Value {
|
||||
let (u, name) = s.ucs_named();
|
||||
let p = |v: Vec3| json!([v.x, v.y, v.z]);
|
||||
json!({ "name": name, "origin": p(u.origin), "xAxis": p(u.x), "yAxis": p(u.y), "world": u.is_world() })
|
||||
}
|
||||
|
||||
fn tilted_message(option: &str) -> String {
|
||||
let label = match option {
|
||||
"x" => "UCS X",
|
||||
"y" => "UCS Y",
|
||||
"zaxis" | "za" => "UCS ZAxis",
|
||||
_ => "UCS Face",
|
||||
};
|
||||
format!("{label} tilts the UCS out of the XY plane, which is not available yet.")
|
||||
}
|
||||
|
||||
/// The UCSAXISANG default for Z, in degrees.
|
||||
fn axis_angle(s: &Session) -> f64 {
|
||||
s.doc().map(|d| d.header.i64("UCSAXISANG", 90)).unwrap_or(90) as f64
|
||||
}
|
||||
|
||||
/// A 2D point of the current UCS's XY plane as a 3D world point.
|
||||
fn on_plane(s: &Session, p: Vec2) -> Vec3 {
|
||||
p.to3(s.ucs().origin.z)
|
||||
}
|
||||
|
||||
/// The UCS through `origin`, with points on its X axis and in its XY plane (world points).
|
||||
fn set_by_points(s: &mut Session, origin: Vec3, x: Option<Vec3>, xy: Option<Vec3>) -> Result<()> {
|
||||
let f = s.ucs().from_points(origin, x, xy).ok_or_else(|| EngineError::Other("Those points don't define a UCS: they lie on one line.".into()))?;
|
||||
if !f.is_planar() {
|
||||
return Err(EngineError::Other("That UCS is tilted out of the XY plane (or turned over), which is not available yet.".into()));
|
||||
}
|
||||
s.set_ucs(f, "")
|
||||
}
|
||||
|
||||
/// UCS View: the XY plane square to the view (a plan view), at the current origin, with X
|
||||
/// along the screen's horizontal. The drawing appears turned by the view twist (the Model tab's,
|
||||
/// or the active layout viewport's), so the screen's X is the world direction at -twist.
|
||||
fn view_ucs(s: &Session) -> UcsFrame {
|
||||
let twist = cadcraft_geom::norm_angle(s.state().map_or(0.0, |st| st.view().twist));
|
||||
UcsFrame::WORLD.rotated_z(-twist).with_origin(s.ucs().origin)
|
||||
}
|
||||
|
||||
fn rotate_z(s: &mut Session, angle: f64) -> Result<()> {
|
||||
let f = s.ucs().rotated_z(angle);
|
||||
s.set_ucs(f, "")
|
||||
}
|
||||
|
||||
/// UCS OBject: the UCS lined up with object `h`, picked at `at` (world) when known.
|
||||
fn set_by_object(s: &mut Session, h: cadcraft_doc::Handle, at: Option<Vec2>) -> Result<()> {
|
||||
let d = s.doc()?;
|
||||
let e = d.entity(h).ok_or_else(|| EngineError::Other("No such object.".into()))?;
|
||||
let ext = e.common.extrusion;
|
||||
if ext.is_finite() && (ext.x.abs() > 1e-9 || ext.y.abs() > 1e-9 || ext.z < 0.0) {
|
||||
return Err(EngineError::Other("That object lies in a tilted plane; a UCS out of the XY plane is not available yet.".into()));
|
||||
}
|
||||
let f = object_frame(&s.ucs(), &e.kind, at)?;
|
||||
s.set_ucs(f, "")
|
||||
}
|
||||
|
||||
/// A frame at `o` whose X axis points along `dir` in the XY plane.
|
||||
fn along(o: Vec3, dir: Vec2) -> Result<UcsFrame> {
|
||||
UcsFrame::new(o, dir.to3(0.0), dir.perp().to3(0.0))
|
||||
.ok_or_else(|| EngineError::Other("That object has no direction to line the UCS up with.".into()))
|
||||
}
|
||||
|
||||
/// The UCS OBject rules: where each kind of object puts the origin and the X axis.
|
||||
fn object_frame(cur: &UcsFrame, kind: &EntityKind, at: Option<Vec2>) -> Result<UcsFrame> {
|
||||
let near = |a: Vec2, b: Vec2| at.is_none_or(|p| p.dist(a) <= p.dist(b));
|
||||
match kind {
|
||||
// The endpoint nearer the pick; X along the line.
|
||||
EntityKind::Line(l) => {
|
||||
let (o, other) = if near(l.a.xy(), l.b.xy()) { (l.a, l.b) } else { (l.b, l.a) };
|
||||
along(o, other.xy() - o.xy())
|
||||
}
|
||||
// The centre; X through the endpoint nearer the pick.
|
||||
EntityKind::Arc(a) => {
|
||||
let (e0, e1) = (Vec2::polar(a.center.xy(), a.radius, a.start), Vec2::polar(a.center.xy(), a.radius, a.end));
|
||||
let e = if near(e0, e1) { e0 } else { e1 };
|
||||
along(a.center, e - a.center.xy())
|
||||
}
|
||||
// The centre; X through the pick.
|
||||
EntityKind::Circle(c) => {
|
||||
let d = at.map(|p| p - c.center.xy()).filter(|d| d.len() > 1e-12).unwrap_or(cur.x.xy());
|
||||
along(c.center, d)
|
||||
}
|
||||
// The first vertex; X toward the next one.
|
||||
EntityKind::LwPolyline(p) => {
|
||||
let first = p.vertices.first().map(|v| v.p).ok_or_else(|| EngineError::Other("That polyline has no vertices.".into()))?;
|
||||
let next = p.vertices.iter().map(|v| v.p).find(|q| q.dist(first) > 1e-12).ok_or_else(|| EngineError::Other("That polyline has no length.".into()))?;
|
||||
along(first.to3(p.elevation), next - first)
|
||||
}
|
||||
// The point; the X axis stays as it is.
|
||||
EntityKind::Point(p) => along(p.p, cur.x.xy()),
|
||||
// The insertion point; X along the object's rotation.
|
||||
EntityKind::Text(t) => along(t.insert, Vec2::from_angle(t.rotation)),
|
||||
EntityKind::AttDef(a) => along(a.text.insert, Vec2::from_angle(a.text.rotation)),
|
||||
EntityKind::Insert(i) => along(i.insert, Vec2::from_angle(i.rotation)),
|
||||
// The first corner; X toward the second.
|
||||
EntityKind::Solid(so) | EntityKind::Trace(so) => {
|
||||
let [a, b, ..] = so.corners;
|
||||
along(a, b.xy() - a.xy())
|
||||
}
|
||||
// The first corner; X toward the second, Y toward the fourth.
|
||||
EntityKind::Face3d(f) => {
|
||||
let [a, b, _, d] = f.corners;
|
||||
let frame = UcsFrame::new(a, b - a, d - a).ok_or_else(|| EngineError::Other("That face has no area to line the UCS up with.".into()))?;
|
||||
if frame.is_planar() {
|
||||
Ok(frame)
|
||||
} else {
|
||||
Err(EngineError::Other("That face lies out of the XY plane; a UCS out of it is not available yet.".into()))
|
||||
}
|
||||
}
|
||||
// The middle of the text; the X axis stays as it is.
|
||||
EntityKind::Dimension(dm) => along(dm.text_mid, cur.x.xy()),
|
||||
_ => Err(EngineError::Other("The UCS can't be lined up with that kind of object (lines, arcs, circles, polylines, points, text, blocks, 2D solids, 3D faces and dimensions can).".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// A usable UCS name, or why not.
|
||||
fn check_name(name: &str) -> std::result::Result<String, String> {
|
||||
let n = name.trim();
|
||||
if n.is_empty() {
|
||||
return Err("A UCS name is required.".into());
|
||||
}
|
||||
if n.chars().count() > MAX_NAME {
|
||||
return Err(format!("A UCS name has at most {MAX_NAME} characters."));
|
||||
}
|
||||
if n.contains(BAD_NAME_CHARS) || n.chars().any(char::is_control) {
|
||||
return Err(format!("\"{n}\" is not a valid UCS name."));
|
||||
}
|
||||
if n.eq_ignore_ascii_case("*WORLD*") || n.eq_ignore_ascii_case("WORLD") {
|
||||
return Err("\"World\" is the World UCS; save under another name.".into());
|
||||
}
|
||||
Ok(n.to_string())
|
||||
}
|
||||
|
||||
fn restore(s: &mut Session, name: &str) -> std::result::Result<(), String> {
|
||||
let d = s.doc().map_err(|e| e.to_string())?;
|
||||
let (f, n) = named(d, name).ok_or_else(|| format!("Cannot find UCS \"{}\".", name.trim()))?;
|
||||
if !f.is_planar() {
|
||||
// Kept and saved as read, but not current until tilted UCSs are available.
|
||||
return Err(format!("UCS \"{n}\" is tilted out of the XY plane, which is not available yet."));
|
||||
}
|
||||
s.set_ucs(f, &n).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn exists(d: &Drawing, name: &str) -> bool {
|
||||
d.ucss.iter().any(|u| u.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// Save the current UCS as `name` (replacing a UCS of that name only with `replace`); it is then
|
||||
/// the current UCS's name.
|
||||
fn save(s: &mut Session, name: &str, replace: bool) -> std::result::Result<(), String> {
|
||||
let n = check_name(name)?;
|
||||
let frame = s.ucs();
|
||||
let d = s.doc_mut().map_err(|e| e.to_string())?;
|
||||
match d.ucss.iter_mut().find(|u| u.name.eq_ignore_ascii_case(&n)) {
|
||||
Some(_) if !replace => return Err(format!("UCS \"{n}\" already exists.")),
|
||||
Some(u) => *u = frame.record(&u.name.clone()),
|
||||
None => {
|
||||
if d.ucss.len() >= MAX_NAMED {
|
||||
return Err(format!("A drawing keeps at most {MAX_NAMED} named UCSs."));
|
||||
}
|
||||
d.ucss.push(frame.record(&n));
|
||||
}
|
||||
}
|
||||
let kept = d.ucss.iter().find(|u| u.name.eq_ignore_ascii_case(&n)).map(|u| u.name.clone()).unwrap_or(n);
|
||||
s.set_ucs(frame, &kept).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Whether `name` matches one of the comma-separated wildcard patterns.
|
||||
fn matches(patterns: &str, name: &str) -> bool {
|
||||
patterns
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|p| !p.is_empty())
|
||||
.any(|p| super::qselect::wildcard(&p.to_ascii_uppercase(), &name.to_ascii_uppercase()))
|
||||
}
|
||||
|
||||
/// Delete the named UCSs matching `patterns`; the current UCS keeps its axes but loses a deleted
|
||||
/// name. Returns how many went.
|
||||
fn delete(s: &mut Session, patterns: &str) -> Result<usize> {
|
||||
let gone: Vec<String> = s.doc()?.ucss.iter().filter(|u| matches(patterns, &u.name)).map(|u| u.name.clone()).collect();
|
||||
if gone.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
s.doc_mut()?.ucss.retain(|u| !gone.iter().any(|g| g == &u.name));
|
||||
// Wherever a deleted name is current (model space's UCSNAME, every layout's UCS) the UCS keeps
|
||||
// its axes and loses the name; the UCS Previous histories keep their frames the same way.
|
||||
let d = s.doc_mut()?;
|
||||
let is_gone = |n: &str| gone.iter().any(|g| g.eq_ignore_ascii_case(n.trim()));
|
||||
if is_gone(&d.header.str("UCSNAME", "")) {
|
||||
d.header.set_str("UCSNAME", "");
|
||||
}
|
||||
let unname = |u: &mut Ucs| {
|
||||
if is_gone(&u.name) {
|
||||
u.name.clear();
|
||||
}
|
||||
};
|
||||
d.ucs_previous.iter_mut().for_each(unname);
|
||||
for l in &mut d.layouts {
|
||||
l.ucs.iter_mut().for_each(unname);
|
||||
// A layout whose UCS is the World UCS again holds none, as `set_current` leaves it.
|
||||
if l.ucs.as_ref().is_some_and(|u| u.name.is_empty() && UcsFrame::of(u).is_some_and(|f| f.is_world())) {
|
||||
l.ucs = None;
|
||||
}
|
||||
l.ucs_previous.iter_mut().for_each(unname);
|
||||
}
|
||||
Ok(gone.len())
|
||||
}
|
||||
|
||||
/// How the current UCS is named in messages.
|
||||
fn shown_name(s: &Session) -> String {
|
||||
let (u, name) = s.ucs_named();
|
||||
if !name.is_empty() {
|
||||
name
|
||||
} else if u.is_world() {
|
||||
"*WORLD*".into()
|
||||
} else {
|
||||
"*NO NAME*".into()
|
||||
}
|
||||
}
|
||||
|
||||
/// `?`: the named UCSs matching `patterns`, their origins and axes relative to the current UCS.
|
||||
fn list(s: &Session, patterns: &str) -> String {
|
||||
let Ok(d) = s.doc() else { return String::new() };
|
||||
let cur = s.input_ucs();
|
||||
let (lu, lp) = (d.header.i64("LUNITS", 2), d.header.i64("LUPREC", 4));
|
||||
let f = |v: f64| crate::units::format_distance(v, lu, lp);
|
||||
let pt = |v: Vec3| format!("<{},{},{}>", f(v.x), f(v.y), f(v.z));
|
||||
let axis = |o: Vec3, a: Vec3| cur.to_ucs3(o + a) - cur.to_ucs3(o);
|
||||
let mut out = format!("Current ucs name: {}\nSaved coordinate systems:", shown_name(s));
|
||||
let mut any = false;
|
||||
for u in d.ucss.iter().filter(|u| matches(patterns, &u.name)) {
|
||||
any = true;
|
||||
let Some(fr) = UcsFrame::of(u) else { continue };
|
||||
out.push_str(&format!(
|
||||
"\n\n{}\n Origin = {}, X Axis = {}\n Y Axis = {}, Z Axis = {}",
|
||||
u.name,
|
||||
pt(cur.to_ucs3(fr.origin)),
|
||||
pt(axis(fr.origin, fr.x)),
|
||||
pt(axis(fr.origin, fr.y)),
|
||||
pt(axis(fr.origin, fr.z()))
|
||||
));
|
||||
}
|
||||
if !any {
|
||||
out.push_str("\n\n(none)");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where the interactive UCS is.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
enum Stage {
|
||||
#[default]
|
||||
Main,
|
||||
/// Tools > New UCS > Origin: only the origin.
|
||||
OriginOnly,
|
||||
/// Tools > New UCS > 3 Point: the origin first, then the axes.
|
||||
ThreePoint,
|
||||
XPoint(Vec3),
|
||||
XyPoint(Vec3, Vec3),
|
||||
Named,
|
||||
Restore,
|
||||
Save,
|
||||
Replace(String),
|
||||
Delete,
|
||||
List,
|
||||
Object,
|
||||
ZAngle,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct UcsM {
|
||||
stage: Stage,
|
||||
}
|
||||
|
||||
impl UcsM {
|
||||
fn starting(stage: Stage) -> Self {
|
||||
UcsM { stage }
|
||||
}
|
||||
}
|
||||
|
||||
fn other(msg: impl Into<String>) -> EngineError {
|
||||
EngineError::Other(msg.into())
|
||||
}
|
||||
|
||||
impl Interactive for UcsM {
|
||||
fn name(&self) -> &'static str {
|
||||
"UCS"
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
s.echo(format!("Current ucs name: {}", shown_name(s)));
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
match &self.stage {
|
||||
Stage::Main => Prompt::new("Specify origin of UCS", Accept::POINT).kw(OPTIONS).default("World"),
|
||||
Stage::OriginOnly | Stage::ThreePoint => {
|
||||
// The origin as input is read: in the UCS where that is the current one (so 0,0,0),
|
||||
// in the world while the current UCS is tilted out of the XY plane.
|
||||
let o = s.ucs().origin;
|
||||
let (p, z) = if s.ucs().is_planar() { (s.input_ucs().to_ucs(o.xy()), 0.0) } else { (o.xy(), o.z) };
|
||||
Prompt::new("Specify new origin point", Accept::POINT).default(format!("{},{},{}", num_text(p.x), num_text(p.y), num_text(z)))
|
||||
}
|
||||
Stage::XPoint(o) => Prompt::new("Specify point on X-axis", Accept::POINT).default("Accept").base(o.xy()),
|
||||
Stage::XyPoint(o, _) => Prompt::new("Specify point on the XY plane", Accept::POINT).default("Accept").base(o.xy()),
|
||||
Stage::Named => Prompt::new("Enter an option", Accept::TEXT).kw(&["Restore", "Save", "Delete", "?"]),
|
||||
Stage::Restore => Prompt::new("Enter name of UCS to restore", Accept::TEXT).kw(&["?"]),
|
||||
Stage::Save => Prompt::new("Enter name to save current UCS", Accept::TEXT).kw(&["?"]),
|
||||
Stage::Replace(n) => Prompt::new(format!("UCS \"{n}\" already exists. Replace it?"), Accept::TEXT).kw(&["Yes", "No"]).default("No"),
|
||||
Stage::Delete => Prompt::new("Enter UCS name(s) to delete", Accept::TEXT).default("none"),
|
||||
Stage::List => Prompt::new("Enter UCS name(s) to list", Accept::TEXT).default("*"),
|
||||
Stage::Object => Prompt::new("Select object to align UCS", Accept::POINT),
|
||||
Stage::ZAngle => Prompt::new("Specify rotation angle about Z axis", Accept::NUMBER).default(format!("{}", axis_angle(s))),
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
if i == Input::Cancel {
|
||||
return Ok(Step::Cancel);
|
||||
}
|
||||
match (self.stage.clone(), i) {
|
||||
(Stage::Main, Input::Enter) => {
|
||||
s.set_ucs(UcsFrame::WORLD, "")?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::Main, Input::Keyword(k)) => match k.as_str() {
|
||||
"World" => {
|
||||
s.set_ucs(UcsFrame::WORLD, "")?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
"Previous" => {
|
||||
if !s.ucs_previous()? {
|
||||
s.echo("There is no previous UCS.");
|
||||
}
|
||||
Ok(Step::Done)
|
||||
}
|
||||
"View" => {
|
||||
let f = view_ucs(s);
|
||||
s.set_ucs(f, "")?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
"NAmed" => {
|
||||
self.stage = Stage::Named;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
"OBject" => {
|
||||
self.stage = Stage::Object;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
"Z" => {
|
||||
self.stage = Stage::ZAngle;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
"X" | "Y" | "ZAxis" | "Face" => {
|
||||
s.echo(tilted_message(&k.to_ascii_lowercase()));
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
_ => Ok(Step::Continue),
|
||||
},
|
||||
(Stage::Main | Stage::ThreePoint, Input::Point(p)) => {
|
||||
self.stage = Stage::XPoint(on_plane(s, p));
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Stage::OriginOnly, Input::Point(p)) => {
|
||||
let f = s.ucs().with_origin(on_plane(s, p));
|
||||
s.set_ucs(f, "")?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::OriginOnly, Input::Enter) => Ok(Step::Done),
|
||||
// Enter keeps the origin and goes on to the axes, as a typed point would.
|
||||
(Stage::ThreePoint, Input::Enter) => {
|
||||
self.stage = Stage::XPoint(s.ucs().origin);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Stage::XPoint(o), Input::Enter) => {
|
||||
set_by_points(s, o, None, None)?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::XPoint(o), Input::Point(p)) => {
|
||||
let x = on_plane(s, p);
|
||||
if x.xy().dist(o.xy()) <= 1e-12 {
|
||||
return Err(other("The point on the X axis must differ from the origin."));
|
||||
}
|
||||
self.stage = Stage::XyPoint(o, x);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Stage::XyPoint(o, x), Input::Enter) => {
|
||||
set_by_points(s, o, Some(x), None)?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::XyPoint(o, x), Input::Point(p)) => {
|
||||
set_by_points(s, o, Some(x), Some(on_plane(s, p)))?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::Named, Input::Keyword(k)) => {
|
||||
self.stage = match k.as_str() {
|
||||
"Restore" => Stage::Restore,
|
||||
"Save" => Stage::Save,
|
||||
"Delete" => Stage::Delete,
|
||||
_ => Stage::List,
|
||||
};
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Stage::Named, Input::Enter) => Ok(Step::Done),
|
||||
(Stage::Restore | Stage::Save, Input::Keyword(_)) => {
|
||||
let l = list(s, "*");
|
||||
s.echo(l);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Stage::Restore, Input::Text(t)) => {
|
||||
restore(s, &t).map_err(other)?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::Save, Input::Text(t)) => {
|
||||
let n = check_name(&t).map_err(other)?;
|
||||
if s.doc().is_ok_and(|d| exists(d, &n)) {
|
||||
self.stage = Stage::Replace(n);
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
save(s, &n, false).map_err(other)?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::Replace(n), Input::Keyword(k)) => {
|
||||
if k == "Yes" {
|
||||
save(s, &n, true).map_err(other)?;
|
||||
}
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::Replace(_), Input::Enter) | (Stage::Restore | Stage::Save | Stage::Delete, Input::Enter) => Ok(Step::Done),
|
||||
(Stage::Delete, Input::Text(t)) => {
|
||||
let n = delete(s, &t)?;
|
||||
s.echo(format!("{n} UCS name(s) deleted."));
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::List, Input::Enter) => {
|
||||
let l = list(s, "*");
|
||||
s.echo(l);
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::List, Input::Text(t)) => {
|
||||
let l = list(s, &t);
|
||||
s.echo(l);
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::Object, Input::Point(p)) => {
|
||||
let h = super::curves::pick_at(s, p).ok_or_else(|| other("No object found there; select an object."))?;
|
||||
set_by_object(s, h, Some(p))?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::Object, Input::Enter) => Ok(Step::Done),
|
||||
(Stage::ZAngle, Input::Enter) => {
|
||||
let a = axis_angle(s).to_radians();
|
||||
rotate_z(s, a)?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::ZAngle, Input::Text(t)) => {
|
||||
let a = s.angle_settings().amount(&t).filter(|a| a.is_finite()).ok_or_else(|| other("Requires a valid angle."))?;
|
||||
rotate_z(s, a)?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(Stage::Main, Input::Text(_)) => Err(other("Requires a point or an option keyword.")),
|
||||
_ => Err(other("Invalid input.")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_ucsicon(s: &mut Session, on: Option<bool>, origin: Option<bool>) -> Result<Value> {
|
||||
let before = s.ucsicon_bits();
|
||||
let mut bits = before;
|
||||
if let Some(on) = on {
|
||||
bits = if on { bits | 1 } else { bits & !1 };
|
||||
}
|
||||
if let Some(o) = origin {
|
||||
bits = if o { bits | 2 } else { bits & !2 };
|
||||
}
|
||||
// Asking (or setting what is already set) leaves the drawing unmodified.
|
||||
if bits != before {
|
||||
s.doc_mut()?.header.set_i64("UCSICON", bits);
|
||||
}
|
||||
Ok(json!({ "on": bits & 1 != 0, "origin": bits & 2 != 0 }))
|
||||
}
|
||||
|
||||
fn run_ucsicon(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let flag = |k: &str| -> Result<Option<bool>> {
|
||||
match p.get(k) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Bool(b)) => Ok(Some(*b)),
|
||||
Some(v) => Err(bad("ucsicon", format!("`{k}` must be true or false, got {v}"))),
|
||||
}
|
||||
};
|
||||
let (on, origin) = (flag("on")?, flag("origin")?);
|
||||
set_ucsicon(s, on, origin)
|
||||
}
|
||||
|
||||
struct UcsIconM;
|
||||
|
||||
impl Interactive for UcsIconM {
|
||||
fn name(&self) -> &'static str {
|
||||
"UCSICON"
|
||||
}
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
let on = s.ucsicon_bits() & 1 != 0;
|
||||
Prompt::new("Enter an option", Accept::TEXT).kw(&["ON", "OFF", "All", "Noorigin", "ORigin", "Selectable", "Properties"]).default(if on {
|
||||
"ON"
|
||||
} else {
|
||||
"OFF"
|
||||
})
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match i {
|
||||
Input::Keyword(k) => {
|
||||
match k.as_str() {
|
||||
"ON" => set_ucsicon(s, Some(true), None).map(|_| ())?,
|
||||
"OFF" => set_ucsicon(s, Some(false), None).map(|_| ())?,
|
||||
"Noorigin" => set_ucsicon(s, None, Some(false)).map(|_| ())?,
|
||||
"ORigin" => set_ucsicon(s, None, Some(true)).map(|_| ())?,
|
||||
other => {
|
||||
s.echo(format!("UCSICON {other} is not available yet."));
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
}
|
||||
Ok(Step::Done)
|
||||
}
|
||||
Input::Enter | Input::Cancel => Ok(Step::Done),
|
||||
_ => Err(other("Requires an option keyword.")),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// ---------------- CAL ----------------
|
||||
|
||||
mod calc;
|
||||
pub(super) use calc::num_text;
|
||||
|
||||
/// What QuickCalc's "get from the drawing" picks put on the command line before the value (the
|
||||
/// palette reads it back from there).
|
||||
|
||||
@@ -41,6 +41,8 @@ pub struct DocState {
|
||||
/// The Block Editor (BEDIT), when it is open: `doc` is then the editor's drawing, and the
|
||||
/// drawing itself waits in it ([`DocState::drawing`]).
|
||||
pub block_edit: Option<blockedit::BlockEdit>,
|
||||
/// The user was told that the current UCS is tilted ([`Session::note_tilted_ucs`]).
|
||||
pub ucs_tilted_noted: bool,
|
||||
/// What the last erase removed, for OOPS.
|
||||
pub(crate) erased: crate::cmd::Erased,
|
||||
/// The fonts missing on Windows that a save last named: the next save names them again only
|
||||
@@ -72,6 +74,7 @@ impl DocState {
|
||||
uid: NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
binary_dxf: false,
|
||||
block_edit: None,
|
||||
ucs_tilted_noted: false,
|
||||
erased: Default::default(),
|
||||
fonts_noted: String::new(),
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ pub mod settings_dir;
|
||||
pub mod snap;
|
||||
pub mod spatial;
|
||||
pub mod sysvars;
|
||||
pub mod ucs;
|
||||
pub mod undoctl;
|
||||
pub mod units;
|
||||
|
||||
@@ -239,6 +240,8 @@ impl Session {
|
||||
settings.snapunit = d.header.snap_unit();
|
||||
settings.gridunit = d.header.grid_unit();
|
||||
}
|
||||
let a = self.input_ucs().rotation();
|
||||
settings.ucs_angle = if a.is_finite() { a } else { 0.0 };
|
||||
settings
|
||||
}
|
||||
/// The space commands act on (model space while working inside a layout viewport).
|
||||
|
||||
@@ -558,7 +558,7 @@ impl Session {
|
||||
/// A routine waits for the user's answer to a `get…` function: its prompt.
|
||||
pub(crate) fn lisp_prompt(&self) -> Option<Prompt> {
|
||||
match self.lisp.run.as_ref()?.waiting.as_ref()? {
|
||||
Need::Get(req) => Some(req.prompt()),
|
||||
Need::Get(req) => Some(req.prompt(&self.input_ucs())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -569,10 +569,15 @@ impl Session {
|
||||
let Need::Get(req) = self.lisp.run.as_ref()?.waiting.as_ref()? else { return None };
|
||||
let line =
|
||||
|a: cadcraft_geom::Vec2, b: cadcraft_geom::Vec2| cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: a.to3(0.0), b: b.to3(0.0) });
|
||||
let Some(b) = req.first.or(req.base).map(|p| cadcraft_geom::Vec2::new(p[0], p[1])) else { return Some(Vec::new()) };
|
||||
// The base is a UCS point (as the routine gave it); the preview is drawn in world space.
|
||||
let ucs = self.input_ucs();
|
||||
let Some(bu) = req.first.or(req.base).map(|p| cadcraft_geom::Vec2::new(p[0], p[1])) else { return Some(Vec::new()) };
|
||||
let b = ucs.to_wcs(bu);
|
||||
Some(match req.kind {
|
||||
input::GetKind::Corner => {
|
||||
let (c1, c2) = (cadcraft_geom::Vec2::new(cursor.x, b.y), cadcraft_geom::Vec2::new(b.x, cursor.y));
|
||||
// The rectangle runs along the UCS axes, as the corner it returns is measured.
|
||||
let cu = ucs.to_ucs(cursor);
|
||||
let (c1, c2) = (ucs.to_wcs(cadcraft_geom::Vec2::new(cu.x, bu.y)), ucs.to_wcs(cadcraft_geom::Vec2::new(bu.x, cu.y)));
|
||||
vec![line(b, c1), line(c1, cursor), line(cursor, c2), line(c2, b)]
|
||||
}
|
||||
input::GetKind::Point | input::GetKind::Dist | input::GetKind::Angle { .. } => vec![line(b, cursor)],
|
||||
@@ -751,6 +756,8 @@ fn file_key(name: &str) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod ucs_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod block_tests;
|
||||
|
||||
@@ -117,10 +117,14 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
Value::PickSet(p) => feed(ctx.s, Input::Pick(items(p))),
|
||||
Value::Cons(_) => {
|
||||
if let Some(p) = arg.as_point() {
|
||||
feed(ctx.s, Input::Point(Vec2::new(p[0], p[1])));
|
||||
// A routine's points are in the current UCS, as typed ones are.
|
||||
let w = ctx.s.input_ucs().to_wcs(Vec2::new(p[0], p[1]));
|
||||
feed(ctx.s, Input::Point(w));
|
||||
} else if let Value::Ename(h) = arg.car() {
|
||||
// An `entsel` result: (ename point).
|
||||
named(ctx.s, h, arg.cdr().car().as_point().map(|p| Vec2::new(p[0], p[1])));
|
||||
// The pick point is what `entsel` gave: a UCS point, like the ones above.
|
||||
let frame = ctx.s.input_ucs();
|
||||
named(ctx.s, h, arg.cdr().car().as_point().map(|p| frame.to_wcs(Vec2::new(p[0], p[1]))));
|
||||
} else {
|
||||
return Err(LispError::bad_arg("command argument", arg));
|
||||
}
|
||||
@@ -714,10 +718,13 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
}
|
||||
_ => (rest, None),
|
||||
};
|
||||
// The points are UCS points, as `getpoint` and `getcorner` give them: the selection runs in
|
||||
// the world.
|
||||
let frame = ctx.s.input_ucs();
|
||||
let point = |i: usize| -> Result<Vec2, LispError> {
|
||||
let v = pts.get(i).ok_or_else(|| args_err(true))?;
|
||||
let p = v.as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", v))?;
|
||||
Ok(Vec2::new(p[0], p[1]))
|
||||
Ok(frame.to_wcs(Vec2::new(p[0], p[1])))
|
||||
};
|
||||
let s = &mut *ctx.s;
|
||||
let all = |s: &Session, all_spaces: bool| -> Vec<Handle> {
|
||||
@@ -745,6 +752,8 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
Some("P") => ctx.s.state().map(|st| st.drawn_in_viewport(&st.previous_selection)).unwrap_or_default(),
|
||||
Some("I") => ctx.s.selection(),
|
||||
Some("W") | Some("C") => {
|
||||
// A selection window is the box around its corners in the world, like SELECT's: the
|
||||
// same corners typed at either pick the same objects.
|
||||
let (p1, p2) = (point(0)?, point(1)?);
|
||||
let s = &*ctx.s;
|
||||
let Ok(d) = s.doc() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
@@ -753,7 +762,7 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
}
|
||||
Some("F") | Some("WP") | Some("CP") => {
|
||||
let poly: Vec<Vec2> =
|
||||
pts.first().map(|l| l.iter().filter_map(|p| p.as_point().map(|q| Vec2::new(q[0], q[1]))).collect()).unwrap_or_default();
|
||||
pts.first().map(|l| l.iter().filter_map(|p| p.as_point().map(|q| frame.to_wcs(Vec2::new(q[0], q[1])))).collect()).unwrap_or_default();
|
||||
let s = &*ctx.s;
|
||||
let Ok(d) = s.doc() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
match mode.as_deref() {
|
||||
@@ -1203,7 +1212,8 @@ pub fn distof(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
pub fn angtof(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 2)?;
|
||||
let s = string(&a[0])?;
|
||||
let mut settings = ctx.s.angle_settings();
|
||||
// A pure string-to-angle conversion: ANGBASE and ANGDIR apply, the UCS does not.
|
||||
let mut settings = ctx.s.angle_settings().world();
|
||||
// AUNITS 0..=4; any other units argument is an error in AutoCAD, nil here.
|
||||
match a.get(1) {
|
||||
None | Some(Value::Nil) => {}
|
||||
@@ -1213,11 +1223,67 @@ pub fn angtof(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
Ok(Flow::Value(settings.direction(&s).map(Value::Real).unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// `(trans pt from to [disp])`: points are in the world system throughout (no UCS yet).
|
||||
pub fn trans(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
/// A coordinate system `trans` converts from or to: its origin and axes in world coordinates.
|
||||
fn trans_system(ctx: &Ctx<'_>, v: &Value) -> Result<crate::ucs::UcsFrame, LispError> {
|
||||
use crate::ucs::UcsFrame;
|
||||
match v {
|
||||
// 0 the WCS; 3 paper space's display system, which lines up with paper space's WCS.
|
||||
Value::Int(0 | 3) => Ok(UcsFrame::WORLD),
|
||||
// 2 the display system: in a plan view, the WCS turned back by the view's twist (X runs
|
||||
// right across the screen).
|
||||
Value::Int(2) => {
|
||||
let twist = cadcraft_geom::norm_angle(ctx.s.state().map_or(0.0, |st| st.view().twist));
|
||||
Ok(UcsFrame::WORLD.rotated_z(-twist))
|
||||
}
|
||||
Value::Int(1) => Ok(ctx.s.input_ucs()),
|
||||
// An object: its OCS.
|
||||
Value::Ename(h) => {
|
||||
let d = ctx.s.doc().map_err(|e| LispError::new(e.to_string()))?;
|
||||
let e = d.entity(*h).ok_or_else(|| LispError::bad_arg("lentityp", v))?;
|
||||
ocs(e.common.extrusion).ok_or_else(|| LispError::bad_arg("lentityp", v))
|
||||
}
|
||||
// An extrusion direction: the OCS of objects with it.
|
||||
Value::Cons(_) => {
|
||||
let n = v.as_point().ok_or_else(|| LispError::bad_arg("coordinate system", v))?;
|
||||
ocs(cadcraft_geom::Vec3::new(n[0], n[1], n[2])).ok_or_else(|| LispError::bad_arg("coordinate system", v))
|
||||
}
|
||||
other => Err(LispError::bad_arg("coordinate system", other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The object coordinate system of extrusion direction `n` (the arbitrary axis algorithm of the
|
||||
/// DXF Reference): `None` for a direction with no length.
|
||||
fn ocs(n: cadcraft_geom::Vec3) -> Option<crate::ucs::UcsFrame> {
|
||||
use cadcraft_geom::Vec3;
|
||||
let l = n.len();
|
||||
if !(l > 1e-12 && l.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let n = n * (1.0 / l);
|
||||
let w = if n.x.abs() < 1.0 / 64.0 && n.y.abs() < 1.0 / 64.0 { Vec3::new(0.0, 1.0, 0.0) } else { Vec3::Z };
|
||||
let ax = w.cross(n);
|
||||
crate::ucs::UcsFrame::new(Vec3::ZERO, ax, n.cross(ax))
|
||||
}
|
||||
|
||||
/// `(trans pt from to [disp])`: `pt` from coordinate system `from` to `to` (0 WCS, 1 UCS, 2 and 3
|
||||
/// display, an entity name for its OCS, or an extrusion direction); with `disp` non-nil `pt` is a
|
||||
/// displacement, which the systems' origins don't move.
|
||||
pub fn trans(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 3, 4)?;
|
||||
let p = a[0].as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", &a[0]))?;
|
||||
Ok(Flow::Value(Value::point(&p)))
|
||||
let (from, to) = (trans_system(ctx, &a[1])?, trans_system(ctx, &a[2])?);
|
||||
let disp = a.get(3).is_some_and(|v| !v.is_nil());
|
||||
let p = cadcraft_geom::Vec3::new(p[0], p[1], p[2]);
|
||||
let q = if disp {
|
||||
let w = from.x * p.x + from.y * p.y + from.z() * p.z;
|
||||
cadcraft_geom::Vec3::new(w.dot(to.x), w.dot(to.y), w.dot(to.z()))
|
||||
} else {
|
||||
to.to_ucs3(from.to_wcs3(p))
|
||||
};
|
||||
if !q.is_finite() {
|
||||
return Err(LispError::bad_arg("2D/3D point", &a[0]));
|
||||
}
|
||||
Ok(Flow::Value(Value::point(&[q.x, q.y, q.z])))
|
||||
}
|
||||
|
||||
/// What `(load name)` reads: a file loaded through APPLOAD (the web), or one on disk, with
|
||||
|
||||
@@ -49,8 +49,8 @@ pub struct GetRequest {
|
||||
}
|
||||
|
||||
impl GetRequest {
|
||||
/// The prompt the command line shows.
|
||||
pub fn prompt(&self) -> Prompt {
|
||||
/// The prompt the command line shows (`ucs`: the UCS the routine's points are in).
|
||||
pub fn prompt(&self, ucs: &crate::ucs::UcsFrame) -> Prompt {
|
||||
let any = self.initget.bits & 128 != 0 || !self.initget.keywords.is_empty();
|
||||
let accept = match self.kind {
|
||||
GetKind::Point | GetKind::Corner | GetKind::EntSel => Accept { text: any, ..Accept::POINT },
|
||||
@@ -63,7 +63,7 @@ impl GetRequest {
|
||||
(None, true) => default_message(self.kind).to_string(),
|
||||
(None, false) => self.message.clone(),
|
||||
};
|
||||
let base = self.first.or(self.base).map(|p| Vec2::new(p[0], p[1]));
|
||||
let base = self.first.or(self.base).map(|p| ucs.to_wcs(Vec2::new(p[0], p[1])));
|
||||
let mut p = Prompt::new(message, accept).base_opt(base);
|
||||
p.keywords = self.initget.keywords.clone();
|
||||
p.raw = true;
|
||||
@@ -106,11 +106,21 @@ impl GetRequest {
|
||||
Ok(Value::Nil)
|
||||
}
|
||||
Input::Keyword(k) => Ok(Value::str(&k)),
|
||||
Input::Point(p) => self.point(s, [p.x, p.y, 0.0]),
|
||||
// Points come back in the current UCS, on its XY plane.
|
||||
Input::Point(p) => {
|
||||
let u = s.ucs_point(p);
|
||||
self.point(s, [u.x, u.y, 0.0])
|
||||
}
|
||||
// A deferred tangent/perpendicular snap is the point it was picked at here.
|
||||
Input::Deferred(d) => self.point(s, [d.at.x, d.at.y, 0.0]),
|
||||
Input::Deferred(d) => {
|
||||
let u = s.ucs_point(d.at);
|
||||
self.point(s, [u.x, u.y, 0.0])
|
||||
}
|
||||
Input::Pick(hs) => match (self.kind, hs.first()) {
|
||||
(GetKind::EntSel, Some(h)) => Ok(Value::list(vec![Value::Ename(*h), Value::point(&[s.last_point.x, s.last_point.y, 0.0])])),
|
||||
(GetKind::EntSel, Some(h)) => {
|
||||
let u = s.ucs_point(s.last_point);
|
||||
Ok(Value::list(vec![Value::Ename(*h), Value::point(&[u.x, u.y, 0.0])]))
|
||||
}
|
||||
_ => Err("Invalid point.".into()),
|
||||
},
|
||||
Input::Text(t) => self.text(s, &t),
|
||||
@@ -141,7 +151,8 @@ impl GetRequest {
|
||||
let ap = s.settings.pickbox.max(1.0) * s.pixel_size();
|
||||
let space = s.state().map(|st| st.edit_space()).map_err(|e| Again::Msg(e.to_string()))?;
|
||||
let d = s.doc().map_err(|e| Again::Msg(e.to_string()))?;
|
||||
match crate::select::pick_in(d, &space, s.viewport_frozen(), Vec2::new(p[0], p[1]), ap) {
|
||||
// `p` is in the UCS; objects are picked at the world point.
|
||||
match crate::select::pick_in(d, &space, s.viewport_frozen(), s.input_ucs().to_wcs(Vec2::new(p[0], p[1])), ap) {
|
||||
Some(h) => Ok(Value::list(vec![Value::Ename(h), Value::point(&p)])),
|
||||
None => Err("Missed, try again.".into()),
|
||||
}
|
||||
@@ -187,6 +198,8 @@ impl GetRequest {
|
||||
},
|
||||
GetKind::Angle { orient } => match s.angle_settings().direction(t) {
|
||||
Some(a) => {
|
||||
// Measured in the UCS, as an angle from two points is.
|
||||
let a = a - s.angle_settings().ucs;
|
||||
let a = if orient { a } else { a - s.lisp_angbase() };
|
||||
self.check_number(a.rem_euclid(std::f64::consts::TAU), false)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
//! AutoLISP in a UCS (#1106): `getpoint` and friends answer in the current UCS, `command` takes
|
||||
//! UCS points, `trans` converts between the WCS, the UCS, display coordinates and an object's
|
||||
//! OCS, and entity lists stay in world coordinates.
|
||||
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use cadcraft_geom::Vec2;
|
||||
use serde_json::json;
|
||||
|
||||
use super::value::to_text;
|
||||
use crate::Session;
|
||||
use crate::cmd::file::{EntityCodec, set_entity_codec};
|
||||
|
||||
fn session() -> Session {
|
||||
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
|
||||
let mut s = Session::new();
|
||||
s.new_drawing(false);
|
||||
s
|
||||
}
|
||||
|
||||
fn ok(s: &mut Session, code: &str) -> String {
|
||||
match s.lisp_eval(code, false, true, Vec::new()) {
|
||||
Ok(Some(Ok(v))) => to_text(&v, true),
|
||||
other => panic!("{code}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn err(s: &mut Session, code: &str) -> bool {
|
||||
matches!(s.lisp_eval(code, false, true, Vec::new()), Ok(Some(Err(_))) | Err(_))
|
||||
}
|
||||
|
||||
/// The three numbers of a printed point.
|
||||
fn pt(text: &str) -> [f64; 3] {
|
||||
let v: Vec<f64> = text.trim_matches(['(', ')']).split_whitespace().map(|x| x.parse().unwrap()).collect();
|
||||
[v[0], v[1], v.get(2).copied().unwrap_or(0.0)]
|
||||
}
|
||||
|
||||
fn close(a: [f64; 3], b: [f64; 3]) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9)
|
||||
}
|
||||
|
||||
/// The UCS at (100, 50) turned 90° (UCS X is world +Y).
|
||||
fn turned(s: &mut Session) {
|
||||
s.execute("ucs", &json!({"option": "origin", "origin": [100, 50]})).unwrap();
|
||||
s.execute("ucs", &json!({"option": "z", "angle": 90})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trans_between_world_ucs_and_display() {
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
// UCS (10, 0) is world (100, 60).
|
||||
assert!(close(pt(&ok(&mut s, "(trans '(10 0 0) 1 0)")), [100.0, 60.0, 0.0]));
|
||||
assert!(close(pt(&ok(&mut s, "(trans '(100 60 0) 0 1)")), [10.0, 0.0, 0.0]));
|
||||
// A 2D point is at Z 0.
|
||||
assert!(close(pt(&ok(&mut s, "(trans '(10 0) 1 0)")), [100.0, 60.0, 0.0]));
|
||||
// Displacements turn but don't move.
|
||||
assert!(close(pt(&ok(&mut s, "(trans '(10 0 0) 1 0 T)")), [0.0, 10.0, 0.0]));
|
||||
// The display system lines up with the world one in a plan view.
|
||||
assert!(close(pt(&ok(&mut s, "(trans '(10 0 0) 1 2)")), [100.0, 60.0, 0.0]));
|
||||
assert!(close(pt(&ok(&mut s, "(trans '(3 4 5) 2 0)")), [3.0, 4.0, 5.0]));
|
||||
// UCS → UCS and back is the identity.
|
||||
assert!(close(pt(&ok(&mut s, "(trans (trans '(7 -3 2) 1 0) 0 1)")), [7.0, -3.0, 2.0]));
|
||||
// In a view twisted 90° counterclockwise, world +X points up the screen and world -Y runs
|
||||
// right across it: display X.
|
||||
s.execute("dview", &json!({"twist": 90.0})).unwrap();
|
||||
assert!(close(pt(&ok(&mut s, "(trans '(0 -10 0) 0 2)")), [10.0, 0.0, 0.0]));
|
||||
assert!(close(pt(&ok(&mut s, "(trans '(10 0 0) 2 0)")), [0.0, -10.0, 0.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trans_to_and_from_an_objects_ocs() {
|
||||
let mut s = session();
|
||||
// A circle in the world XY plane: its OCS is the WCS.
|
||||
ok(&mut s, "(command \"_.CIRCLE\" '(5 5) 2)");
|
||||
assert!(close(pt(&ok(&mut s, "(trans '(5 5 0) 0 (entlast))")), [5.0, 5.0, 0.0]));
|
||||
// An extrusion direction straight up is the WCS too; one along +X follows the arbitrary
|
||||
// axis algorithm (OCS X = world Y × N = (0, 0, -1)... the DXF Reference's rule).
|
||||
assert!(close(pt(&ok(&mut s, "(trans '(1 2 3) '(0 0 1) 0)")), [1.0, 2.0, 3.0]));
|
||||
let w = pt(&ok(&mut s, "(trans '(1 0 0) '(1 0 0) 0)"));
|
||||
assert!(close(w, [0.0, 1.0, 0.0]), "{w:?}");
|
||||
let back = pt(&ok(&mut s, "(trans (trans '(1 2 3) '(1 0 0) 0) 0 '(1 0 0))"));
|
||||
assert!(close(back, [1.0, 2.0, 3.0]), "{back:?}");
|
||||
// Bad systems and points are errors, not crashes.
|
||||
for bad in [
|
||||
"(trans '(1 2) 7 0)",
|
||||
"(trans '(1 2) \"x\" 0)",
|
||||
"(trans '(1 2) '(0 0 0) 0)",
|
||||
"(trans \"p\" 0 1)",
|
||||
"(trans '(1 2) 0)",
|
||||
"(trans '(1e308 1e308) '(1e-320 0 0) 0)",
|
||||
] {
|
||||
assert!(err(&mut s, bad), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn getpoint_answers_in_the_ucs_and_command_reads_ucs_points() {
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
s.cmdline("(setq p (getpoint))").unwrap();
|
||||
// The user clicks world (100, 60): the routine gets UCS (10, 0).
|
||||
s.input(crate::Input::Point(Vec2::new(100.0, 60.0))).unwrap();
|
||||
assert!(close(pt(&to_text(&s.lisp_var("P"), true)), [10.0, 0.0, 0.0]), "{}", to_text(&s.lisp_var("P"), true));
|
||||
// Typed at getpoint: read in the UCS, given back in it.
|
||||
s.cmdline("(setq q (getpoint))").unwrap();
|
||||
s.cmdline("3,4").unwrap();
|
||||
assert!(close(pt(&to_text(&s.lisp_var("Q"), true)), [3.0, 4.0, 0.0]));
|
||||
// `command` takes those points as UCS points: the line lands at the world places clicked.
|
||||
ok(&mut s, "(command \"_.LINE\" p q \"\")");
|
||||
let d = s.doc().unwrap();
|
||||
let l = d.model.iter().find_map(|e| if let cadcraft_doc::EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).unwrap();
|
||||
assert!(l.a.xy().dist(Vec2::new(100.0, 60.0)) < 1e-9 && l.b.xy().dist(Vec2::new(96.0, 53.0)) < 1e-9, "{l:?}");
|
||||
// Entity lists stay in world coordinates.
|
||||
let g = ok(&mut s, "(cdr (assoc 10 (entget (entlast))))");
|
||||
assert!(close(pt(&g), [100.0, 60.0, 0.0]), "{g}");
|
||||
// `!expr` at the command line is a UCS point too.
|
||||
s.cmdline("line").unwrap();
|
||||
s.cmdline("!p").unwrap();
|
||||
s.cmdline("!q").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
let n = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_doc::EntityKind::Line(_))).count();
|
||||
assert_eq!(n, 2);
|
||||
let d = s.doc().unwrap();
|
||||
let last = d.model.iter().filter_map(|e| if let cadcraft_doc::EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).last().unwrap();
|
||||
assert!(last.a.xy().dist(Vec2::new(100.0, 60.0)) < 1e-9 && last.b.xy().dist(Vec2::new(96.0, 53.0)) < 1e-9, "{last:?}");
|
||||
}
|
||||
|
||||
/// The rubber band of `getpoint`/`getcorner` with a base point starts where that UCS point is in
|
||||
/// the world, and `getcorner`'s rectangle runs along the UCS axes.
|
||||
#[test]
|
||||
fn getpoint_and_getcorner_previews_start_at_the_ucs_base() {
|
||||
let ends = |k: &cadcraft_doc::EntityKind| match k {
|
||||
cadcraft_doc::EntityKind::Line(l) => (l.a.xy(), l.b.xy()),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let near = |a: Vec2, b: Vec2| a.dist(b) < 1e-9;
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
// UCS (0, 0) is world (100, 50); the cursor is at world (90, 70), UCS (20, 10).
|
||||
let cursor = Vec2::new(90.0, 70.0);
|
||||
s.cmdline("(setq p (getpoint '(0 0)))").unwrap();
|
||||
let band = s.lisp_preview(cursor).unwrap();
|
||||
assert_eq!(band.len(), 1);
|
||||
let (a, b) = ends(&band[0]);
|
||||
assert!(near(a, Vec2::new(100.0, 50.0)) && near(b, cursor), "{a:?} {b:?}");
|
||||
s.input(crate::Input::Point(cursor)).unwrap();
|
||||
s.cmdline("(setq c (getcorner '(0 0)))").unwrap();
|
||||
let rect: Vec<(Vec2, Vec2)> = s.lisp_preview(cursor).unwrap().iter().map(ends).collect();
|
||||
// Along UCS X (world +Y) to UCS (20, 0), the cursor, UCS (0, 10) (world (90, 50)), back.
|
||||
let want = [(100.0, 50.0), (100.0, 70.0), (90.0, 70.0), (90.0, 50.0)].map(|(x, y)| Vec2::new(x, y));
|
||||
assert_eq!(rect.len(), 4);
|
||||
for (i, (a, b)) in rect.iter().enumerate() {
|
||||
assert!(near(*a, want[i]) && near(*b, want[(i + 1) % 4]), "side {i}: {a:?} {b:?}");
|
||||
}
|
||||
s.input(crate::Input::Point(cursor)).unwrap();
|
||||
assert!(close(pt(&to_text(&s.lisp_var("C"), true)), [20.0, 10.0, 0.0]), "the corner it returns, in the UCS");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn getangle_and_getdist_measure_in_the_ucs() {
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
// Two clicks one above the other in the world: along the UCS X axis, angle 0.
|
||||
s.cmdline("(setq a (getangle))").unwrap();
|
||||
s.input(crate::Input::Point(Vec2::new(100.0, 50.0))).unwrap();
|
||||
s.input(crate::Input::Point(Vec2::new(100.0, 70.0))).unwrap();
|
||||
let a: f64 = to_text(&s.lisp_var("A"), true).parse().unwrap();
|
||||
assert!(a.abs() < 1e-6 || (a - std::f64::consts::TAU).abs() < 1e-6, "{a}");
|
||||
// A typed angle is measured in the UCS as well.
|
||||
s.cmdline("(setq b (getangle))").unwrap();
|
||||
s.cmdline("45").unwrap();
|
||||
let b: f64 = to_text(&s.lisp_var("B"), true).parse().unwrap();
|
||||
assert!((b - std::f64::consts::FRAC_PI_4).abs() < 1e-6, "{b} (printed to 6 places)");
|
||||
// Distances don't depend on the UCS.
|
||||
s.cmdline("(setq d (getdist '(0 0)))").unwrap();
|
||||
s.cmdline("3,4").unwrap();
|
||||
assert_eq!(to_text(&s.lisp_var("D"), true), "5.0");
|
||||
// The UCS variables read from LISP.
|
||||
assert!(close(pt(&ok(&mut s, "(getvar \"UCSORG\")")), [100.0, 50.0, 0.0]));
|
||||
assert!(close(pt(&ok(&mut s, "(getvar \"UCSXDIR\")")), [0.0, 1.0, 0.0]));
|
||||
assert_eq!(ok(&mut s, "(getvar \"WORLDUCS\")"), "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entsel_and_getcorner_answer_in_the_ucs() {
|
||||
let mut s = session();
|
||||
s.execute("line", &json!({"points": [[100, 60], [100, 80]]})).unwrap();
|
||||
turned(&mut s);
|
||||
// entsel: the object, and the pick point in the UCS.
|
||||
s.cmdline("(setq e (entsel))").unwrap();
|
||||
s.input(crate::Input::Point(Vec2::new(100.0, 70.0))).unwrap();
|
||||
let v = to_text(&s.lisp_var("E"), true);
|
||||
assert!(v.contains("<Entity name"), "{v}");
|
||||
let p = ok(&mut s, "(cadr e)");
|
||||
assert!(close(pt(&p), [20.0, 0.0, 0.0]), "{p}");
|
||||
// entsel with the point typed in the UCS picks the object at its world place.
|
||||
s.cmdline("(setq e2 (entsel))").unwrap();
|
||||
s.cmdline("15,0").unwrap();
|
||||
assert!(to_text(&s.lisp_var("E2"), true).contains("<Entity name"), "{}", to_text(&s.lisp_var("E2"), true));
|
||||
// getcorner: the base point is a UCS point; the answer is in the UCS.
|
||||
s.cmdline("(setq c (getcorner '(0 0) \"Corner: \"))").unwrap();
|
||||
s.input(crate::Input::Point(Vec2::new(95.0, 60.0))).unwrap();
|
||||
assert!(close(pt(&to_text(&s.lisp_var("C"), true)), [10.0, 5.0, 0.0]), "{}", to_text(&s.lisp_var("C"), true));
|
||||
// A miss asks again rather than answering.
|
||||
s.cmdline("(setq e3 (entsel))").unwrap();
|
||||
s.input(crate::Input::Point(Vec2::new(500.0, 500.0))).unwrap();
|
||||
assert!(s.lisp_running(), "Missed, try again");
|
||||
s.cancel();
|
||||
}
|
||||
|
||||
fn model_lines(s: &Session) -> Vec<(Vec2, Vec2)> {
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| if let cadcraft_doc::EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The pick point of an `entsel` result handed to `command` is a UCS point, like the others.
|
||||
#[test]
|
||||
fn command_with_entsel_converts_the_pick_point_to_world() {
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
// World (100, 50) to (100, 150): UCS (0, 0) to (100, 0).
|
||||
s.execute("line", &json!({"points": [[100, 50], [100, 150]]})).unwrap();
|
||||
ok(&mut s, "(setq e (entlast))");
|
||||
// Break it from UCS (30, 0) to UCS (60, 0), picked the way `entsel` answers: (ename point).
|
||||
ok(&mut s, "(command \"_.BREAK\" (list e '(30 0)) '(60 0))");
|
||||
let mut l = model_lines(&s);
|
||||
l.sort_by(|a, b| a.0.y.total_cmp(&b.0.y));
|
||||
assert_eq!(l.len(), 2, "{l:?}");
|
||||
assert!(l[0].0.dist(Vec2::new(100.0, 50.0)) < 1e-9 && l[0].1.dist(Vec2::new(100.0, 80.0)) < 1e-9, "{l:?}");
|
||||
assert!(l[1].0.dist(Vec2::new(100.0, 110.0)) < 1e-9 && l[1].1.dist(Vec2::new(100.0, 150.0)) < 1e-9, "{l:?}");
|
||||
}
|
||||
|
||||
/// `ssget` windows, fences, polygons and single picks take UCS points, as `getpoint` gives them.
|
||||
#[test]
|
||||
fn ssget_window_takes_ucs_points() {
|
||||
let mut s = session();
|
||||
s.execute("ucs", &json!({"option": "origin", "origin": [1000, 1000]})).unwrap();
|
||||
s.execute("circle", &json!({"center": [1005, 1005], "radius": 1})).unwrap();
|
||||
s.execute("circle", &json!({"center": [5, 5], "radius": 1})).unwrap();
|
||||
assert_eq!(ok(&mut s, "(sslength (ssget \"W\" '(0 0) '(10 10)))"), "1");
|
||||
let found = ok(&mut s, "(cdr (assoc 10 (entget (ssname (ssget \"W\" '(0 0) '(10 10)) 0))))");
|
||||
assert!(close(pt(&found), [1005.0, 1005.0, 0.0]), "{found}");
|
||||
assert_eq!(ok(&mut s, "(sslength (ssget \"C\" '(-1 -1) '(11 11)))"), "1");
|
||||
assert_eq!(ok(&mut s, "(sslength (ssget \"WP\" '((0 0) (10 0) (10 10) (0 10))))"), "1");
|
||||
assert_eq!(ok(&mut s, "(sslength (ssget \"F\" '((0 0) (10 10))))"), "1");
|
||||
}
|
||||
|
||||
/// `angtof` converts text to radians: ANGBASE and ANGDIR apply, the UCS does not.
|
||||
#[test]
|
||||
fn angtof_ignores_the_ucs() {
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
assert_eq!(ok(&mut s, "(angtof \"0\")"), "0.0");
|
||||
assert_eq!(ok(&mut s, "(angtos (angtof \"45\"))"), "\"45\"");
|
||||
}
|
||||
|
||||
/// A selection window is the world box around its corners whatever the UCS: `ssget` and a SELECT
|
||||
/// window typed with the same corners pick the same objects.
|
||||
#[test]
|
||||
fn ssget_window_matches_select_in_a_turned_ucs() {
|
||||
let mut s = session();
|
||||
s.execute("ucs", &json!({"option": "z", "angle": 45})).unwrap();
|
||||
// The window's corners (UCS 0,0 and 10,4) are world (0,0) and (4.2,9.9): its world box.
|
||||
for c in [[3.0, 8.0], [1.0, 2.0], [0.0, 7.0], [5.0, 3.0], [40.0, 40.0]] {
|
||||
s.execute("circle", &json!({"center": c, "radius": 0.5})).unwrap();
|
||||
}
|
||||
let count = |s: &mut Session, w: &str| ok(s, &format!("(if (setq ss (ssget \"{w}\" '(0 0) '(10 4))) (sslength ss) 0)"));
|
||||
let (w, c) = (count(&mut s, "W"), count(&mut s, "C"));
|
||||
for (key, ssget) in [("w", w), ("c", c)] {
|
||||
s.cancel();
|
||||
s.cmdline("select").unwrap();
|
||||
s.cmdline(key).unwrap();
|
||||
s.cmdline("0,0").unwrap();
|
||||
s.cmdline("10,4").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert_ne!(ssget, "0", "window {key} finds something");
|
||||
assert_eq!(s.selection().len().to_string(), ssget, "window {key}");
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,13 @@ impl Axes {
|
||||
pub fn combine(self, first: Vec2, second: Vec2) -> Vec2 {
|
||||
Vec2::new(if self.x { first.x } else { second.x }, if self.y { first.y } else { second.y })
|
||||
}
|
||||
|
||||
/// [`Axes::combine`] with the coordinates read in the UCS `ucs`, where the user typed and saw
|
||||
/// the points: `.X` takes the first point's X along the UCS X axis, not the world's.
|
||||
pub fn combine_in(self, ucs: &crate::ucs::UcsFrame, first: Vec2, second: Vec2) -> Vec2 {
|
||||
let r = ucs.to_wcs(self.combine(ucs.to_ucs(first), ucs.to_ucs(second)));
|
||||
if r.is_finite() { r } else { self.combine(first, second) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A pending point modifier.
|
||||
@@ -236,16 +243,16 @@ impl Session {
|
||||
// A distance at "Next point" of TK: straight across or up from the last tracking point,
|
||||
// the way the cursor lies from it.
|
||||
if let Some(Frame::Track { last: Some(l) }) = self.point_mods.last().copied()
|
||||
&& crate::prompt::parse_point_with(t, self.last_point, &self.angle_settings()).is_none()
|
||||
&& self.parse_typed_point(t, self.last_point).is_none()
|
||||
&& let Some(d) = crate::units::parse_distance(t)
|
||||
{
|
||||
let dir = (crate::snap::ortho(l, self.cursor) - l).normalized();
|
||||
let dir = (crate::snap::ortho_at(l, self.cursor, self.drafting_settings().ucs_angle) - l).normalized();
|
||||
let dir = if dir == Vec2::ZERO || !dir.is_finite() { Vec2::X } else { dir };
|
||||
return Some(self.modifier_point(l + dir * d));
|
||||
}
|
||||
if let Some(Frame::Angle { base, dir }) = self.point_mods.last().copied() {
|
||||
// Typed coordinates are explicit: they win over the override.
|
||||
if crate::prompt::parse_point_with(t, self.last_point, &self.angle_settings()).is_some() {
|
||||
if self.parse_typed_point(t, self.last_point).is_some() {
|
||||
self.point_mods.pop();
|
||||
return None;
|
||||
}
|
||||
@@ -328,7 +335,7 @@ impl Session {
|
||||
}
|
||||
Frame::Track { last } => {
|
||||
// Each point after the first goes straight across or up from the last one.
|
||||
let q = last.map_or(p, |l| crate::snap::ortho(l, p));
|
||||
let q = last.map_or(p, |l| crate::snap::ortho_at(l, p, self.drafting_settings().ucs_angle));
|
||||
self.point_mods.push(Frame::Track { last: Some(q) });
|
||||
self.last_point = q;
|
||||
return Ok(());
|
||||
@@ -336,7 +343,7 @@ impl Session {
|
||||
// The offset point is already measured from the base (`@` reads the last point).
|
||||
Frame::From { base: Some(_) } => {}
|
||||
Frame::Mid { first: Some(f) } => p = (f + p) * 0.5,
|
||||
Frame::Filter { keep, first: Some(f) } => p = keep.combine(f, p),
|
||||
Frame::Filter { keep, first: Some(f) } => p = keep.combine_in(&self.input_ucs(), f, p),
|
||||
Frame::Angle { base, dir } => p = base + dir * (p - base).dot(dir),
|
||||
Frame::Snap { mode: 0 } => {}
|
||||
Frame::Snap { mode } => {
|
||||
|
||||
+33
-10
@@ -114,7 +114,10 @@ pub fn parse_polar_text(text: &str, angles: &crate::units::AngleSettings) -> Opt
|
||||
let body = text.trim().strip_prefix('@')?; // relative form only
|
||||
let (d, a) = body.split_once('<')?;
|
||||
let dist = d.trim().parse::<f64>().ok()?;
|
||||
let angle = angles.amount(a.trim())?;
|
||||
// The direction `@d<a` draws along, as `parse_point_in` reads it (ANGBASE, ANGDIR and the
|
||||
// UCS applied): a world angle.
|
||||
let a = a.trim();
|
||||
let angle = if a.starts_with('<') { angles.direction(&format!("<{a}"))? } else { angles.direction(a)? };
|
||||
(dist.is_finite() && angle.is_finite()).then_some((dist, angle))
|
||||
}
|
||||
|
||||
@@ -350,10 +353,9 @@ pub struct Drag {
|
||||
}
|
||||
|
||||
/// Parse a typed point: `x,y[,z]`, `@dx,dy`, `@dist<angle`, `dist<angle`, `#x,y` (absolute),
|
||||
/// `*x,y` and `*@dx,dy`/`@*dx,dy` (world coordinates: the same as the plain forms, as there is no
|
||||
/// UCS yet).
|
||||
/// `*x,y` and `*@dx,dy`/`@*dx,dy` (world coordinates).
|
||||
/// Relative forms use `last`. Polar angles read the default angle settings (degrees from +X,
|
||||
/// counterclockwise); `parse_point_with` reads a drawing's.
|
||||
/// counterclockwise); `parse_point_with` reads a drawing's, `parse_point_in` a UCS too.
|
||||
pub fn parse_point(text: &str, last: Vec2) -> Option<Vec2> {
|
||||
parse_point_with(text, last, &crate::units::AngleSettings::default())
|
||||
}
|
||||
@@ -361,14 +363,31 @@ pub fn parse_point(text: &str, last: Vec2) -> Option<Vec2> {
|
||||
/// `parse_point` with polar angles read per `angles` (AUNITS, ANGBASE, ANGDIR); `d<<a` and
|
||||
/// `d<<<a` measure from +X counterclockwise (in degrees and in AUNITS).
|
||||
pub fn parse_point_with(text: &str, last: Vec2, angles: &crate::units::AngleSettings) -> Option<Vec2> {
|
||||
parse_point_in(text, last, angles, &crate::ucs::UcsFrame::WORLD)
|
||||
}
|
||||
|
||||
/// `parse_point_with` in a UCS: coordinates are UCS coordinates (`x,y` from its origin along its
|
||||
/// axes, `@dx,dy` along its axes), and polar angles are measured as `angles` says (which carries
|
||||
/// the UCS rotation, [`crate::units::AngleSettings::ucs`]). A `*` prefix reads the point in
|
||||
/// world coordinates instead. `last` and the result are world points.
|
||||
pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettings, ucs: &crate::ucs::UcsFrame) -> Option<Vec2> {
|
||||
let t = text.trim();
|
||||
if t.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let t = t.strip_prefix('*').map_or(t, str::trim_start);
|
||||
let (mut world, t) = match t.strip_prefix('*') {
|
||||
Some(r) => (true, r.trim_start()),
|
||||
None => (false, t),
|
||||
};
|
||||
let (rel, body) = if let Some(b) = t.strip_prefix('@') {
|
||||
let b = b.trim();
|
||||
(true, b.strip_prefix('*').map_or(b, str::trim_start))
|
||||
match b.strip_prefix('*') {
|
||||
Some(r) => {
|
||||
world = true;
|
||||
(true, r.trim_start())
|
||||
}
|
||||
None => (true, b),
|
||||
}
|
||||
} else if let Some(b) = t.strip_prefix('#') {
|
||||
(false, b.trim())
|
||||
} else {
|
||||
@@ -377,11 +396,15 @@ pub fn parse_point_with(text: &str, last: Vec2, angles: &crate::units::AngleSett
|
||||
if rel && body.is_empty() {
|
||||
return Some(last);
|
||||
}
|
||||
let (frame, angles) = if world { (crate::ucs::UcsFrame::WORLD, angles.world()) } else { (*ucs, *angles) };
|
||||
// `p`: a world displacement (polar, whose angle already says the UCS's direction), or UCS
|
||||
// coordinates (`x,y`).
|
||||
let p = if let Some((d, a)) = body.split_once('<') {
|
||||
let dist = crate::units::parse_distance(d)?;
|
||||
// `d<<a` / `d<<<a`: the override prefixes keep their `<<` / `<<<`.
|
||||
let ang = if a.starts_with('<') { angles.direction(&format!("<{a}"))? } else { angles.direction(a)? };
|
||||
Vec2::from_angle(ang) * dist
|
||||
let v = Vec2::from_angle(ang) * dist;
|
||||
if rel { last + v } else { frame.origin.xy() + v }
|
||||
} else {
|
||||
let parts: Vec<&str> = body.split(',').collect();
|
||||
if parts.len() < 2 || parts.len() > 3 {
|
||||
@@ -392,10 +415,10 @@ pub fn parse_point_with(text: &str, last: Vec2, angles: &crate::units::AngleSett
|
||||
if let Some(z) = parts.get(2) {
|
||||
crate::units::parse_distance(z)?;
|
||||
}
|
||||
Vec2::new(x, y)
|
||||
let v = Vec2::new(x, y);
|
||||
if rel { last + frame.vec_to_wcs(v) } else { frame.to_wcs(v) }
|
||||
};
|
||||
let r = if rel { last + p } else { p };
|
||||
r.is_finite().then_some(r)
|
||||
p.is_finite().then_some(p)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -107,7 +107,8 @@ impl Session {
|
||||
lisp::value::Value::Real(r) => self.typed_token(&format!("{r}"), false),
|
||||
lisp::value::Value::Str(s) => self.typed_token(&s, false),
|
||||
other => match other.as_point() {
|
||||
Some(p) => self.input(Input::Point(Vec2::new(p[0], p[1]))),
|
||||
// A point from LISP is in the current UCS, as typed coordinates are.
|
||||
Some(p) => self.input(Input::Point(self.input_ucs().to_wcs(Vec2::new(p[0], p[1])))),
|
||||
None => {
|
||||
self.echo(format!("Invalid input: {}", lisp::value::to_text(&other, true)));
|
||||
Ok(())
|
||||
@@ -146,7 +147,8 @@ impl Session {
|
||||
return self.input(Input::Keyword(k));
|
||||
}
|
||||
if prompt.accept.point {
|
||||
if let Some(p) = prompt::parse_point_with(tt, self.last_point, &self.angle_settings()) {
|
||||
self.note_tilted_ucs();
|
||||
if let Some(p) = self.parse_typed_point(tt, self.last_point) {
|
||||
self.last_polar = prompt::parse_polar_text(tt, &self.angle_settings());
|
||||
return self.input(Input::Point(p));
|
||||
}
|
||||
|
||||
@@ -125,6 +125,10 @@ pub struct Settings {
|
||||
pub polarsnap: bool,
|
||||
/// POLARDIST: the PolarSnap step; 0 uses the snap X spacing.
|
||||
pub polardist: f64,
|
||||
/// The current UCS's X axis, radians from world +X: ortho, polar and object snap tracking
|
||||
/// work along the UCS axes. Filled in by [`Session::drafting_settings`]; not a setting.
|
||||
#[serde(skip)]
|
||||
pub ucs_angle: f64,
|
||||
/// AUDITCTL: 1 creates an audit report (.adt) file when AUDIT is run (default: 0).
|
||||
pub auditctl: bool,
|
||||
/// ATTREQ: 0 inserts blocks with their attributes' default values instead of asking for them
|
||||
@@ -193,6 +197,7 @@ impl Default for Settings {
|
||||
polaraddang: Vec::new(),
|
||||
polarsnap: false,
|
||||
polardist: 0.0,
|
||||
ucs_angle: 0.0,
|
||||
auditctl: false,
|
||||
attreq: true,
|
||||
}
|
||||
|
||||
@@ -1025,6 +1025,17 @@ pub fn ortho(base: Vec2, p: Vec2) -> Vec2 {
|
||||
if d.x.abs() >= d.y.abs() { Vec2::new(p.x, base.y) } else { Vec2::new(base.x, p.y) }
|
||||
}
|
||||
|
||||
/// [`ortho`] along axes turned by `angle` radians (the current UCS's).
|
||||
pub fn ortho_at(base: Vec2, p: Vec2, angle: f64) -> Vec2 {
|
||||
if !angle.is_finite() || angle == 0.0 {
|
||||
return ortho(base, p);
|
||||
}
|
||||
let d = (p - base).rotate(-angle);
|
||||
let along = if d.x.abs() >= d.y.abs() { Vec2::new(d.x, 0.0) } else { Vec2::new(0.0, d.y) };
|
||||
let r = base + along.rotate(angle);
|
||||
if r.is_finite() { r } else { p }
|
||||
}
|
||||
|
||||
/// Polar tracking: if the direction base→p is within `tol` radians of a multiple of `inc`,
|
||||
/// return the point projected onto that ray and the angle.
|
||||
pub fn polar(base: Vec2, p: Vec2, inc: f64, tol: f64) -> Option<(Vec2, f64)> {
|
||||
@@ -1058,12 +1069,26 @@ pub fn grid_snap(p: Vec2, unit: Vec2, origin: Vec2, angle: f64) -> Vec2 {
|
||||
if s.is_finite() { s } else { p }
|
||||
}
|
||||
|
||||
/// The snap grid's origin (SNAPBASE) and rotation in radians (SNAPANG, in degrees) of a drawing.
|
||||
/// The snap grid's origin (SNAPBASE) and rotation in radians (SNAPANG, in degrees) of a drawing,
|
||||
/// as stored: in the UCS ([`grid_frame_in`] places them in the world).
|
||||
pub fn grid_frame(d: &Drawing) -> (Vec2, f64) {
|
||||
let base = d.header.point("SNAPBASE").map(|p| p.xy()).filter(|p| p.is_finite()).unwrap_or(Vec2::ZERO);
|
||||
(base, d.header.f64("SNAPANG", 0.0).to_radians())
|
||||
}
|
||||
|
||||
/// The snap grid's origin and rotation in world coordinates, for `space`: SNAPBASE is a point of
|
||||
/// the current UCS and SNAPANG is measured from its X axis, so the grid and grid snap lie in the
|
||||
/// UCS (in the World UCS while it is tilted out of the XY plane).
|
||||
pub fn grid_frame_in(d: &Drawing, space: &Space) -> (Vec2, f64) {
|
||||
let (base, angle) = grid_frame(d);
|
||||
let ucs = crate::ucs::current_frame(d, space);
|
||||
if !ucs.is_planar() {
|
||||
return (base, angle);
|
||||
}
|
||||
let (o, a) = (ucs.to_wcs(base), ucs.rotation() + angle);
|
||||
if o.is_finite() && a.is_finite() { (o, a) } else { (base, angle) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -118,11 +118,11 @@ pub fn lattice_snap(p: Vec2, d: f64, origin: Vec2, angle: f64) -> Vec2 {
|
||||
/// isometric lattice, and the settings with grid snap off so the rectangular grid leaves it be.
|
||||
/// Otherwise both unchanged, also when PolarSnap (SNAPTYPE 1) is the snap type: snap mode then
|
||||
/// steps along the tracking paths instead.
|
||||
pub(crate) fn grid_snap(doc: &cadcraft_doc::Drawing, mut s: Settings, p: Vec2) -> (Vec2, Settings) {
|
||||
pub(crate) fn grid_snap(doc: &cadcraft_doc::Drawing, space: &cadcraft_doc::Space, mut s: Settings, p: Vec2) -> (Vec2, Settings) {
|
||||
if !(s.snapmode && s.isodraft) || s.polarsnap {
|
||||
return (p, s);
|
||||
}
|
||||
let (origin, angle) = super::grid_frame(doc);
|
||||
let (origin, angle) = super::grid_frame_in(doc, space);
|
||||
s.snapmode = false;
|
||||
(lattice_snap(p, s.snapunit.y, origin, angle), s)
|
||||
}
|
||||
@@ -144,10 +144,12 @@ fn nearest_axis(plane: IsoPlane, d: Vec2) -> Vec2 {
|
||||
/// Ortho without snapping: `p` constrained relative to `base` to the nearest axis of the current
|
||||
/// isometric plane (or to horizontal/vertical when isometric drafting is off).
|
||||
pub fn constrain(s: &Settings, base: Vec2, p: Vec2) -> Vec2 {
|
||||
// Along the current UCS's axes (`s.ucs_angle`), the isometric ones turned with it.
|
||||
if !s.isodraft {
|
||||
return super::ortho(base, p);
|
||||
return super::ortho_at(base, p, s.ucs_angle);
|
||||
}
|
||||
let dir = nearest_axis(s.isoplane, p - base);
|
||||
let a = if s.ucs_angle.is_finite() { s.ucs_angle } else { 0.0 };
|
||||
let dir = nearest_axis(s.isoplane, (p - base).rotate(-a)).rotate(a);
|
||||
let r = base + dir * (p - base).dot(dir);
|
||||
if r.is_finite() { r } else { p }
|
||||
}
|
||||
@@ -214,16 +216,29 @@ pub struct GridLine {
|
||||
/// major line. Empty when a family would need more than [`MAX_GRID_LINES`] lines.
|
||||
pub fn grid_lines(view: Bounds2, d: f64, origin: Vec2, angle: f64, major_every: u32) -> Vec<GridLine> {
|
||||
let Some(d) = spacing(d) else { return Vec::new() };
|
||||
// Neighbouring lines of a family are d·cos 30° apart.
|
||||
families(view, &[30.0, 90.0, 150.0], d * COS30, origin, angle, major_every)
|
||||
}
|
||||
|
||||
/// The rectangular grid lines (lines along X and along Y, `d` apart, through `origin`, turned by
|
||||
/// `angle`) that cross `view`; every `major_every`th line of a family is a major line. Empty when
|
||||
/// a family would need more than [`MAX_GRID_LINES`] lines.
|
||||
pub fn rect_grid_lines(view: Bounds2, d: f64, origin: Vec2, angle: f64, major_every: u32) -> Vec<GridLine> {
|
||||
let Some(d) = spacing(d) else { return Vec::new() };
|
||||
families(view, &[0.0, 90.0], d, origin, angle, major_every)
|
||||
}
|
||||
|
||||
/// Lines along each of `degs` (turned by `angle`), `gap` apart, one through `origin`, clipped to
|
||||
/// `view`.
|
||||
fn families(view: Bounds2, degs: &[f64], gap: f64, origin: Vec2, angle: f64, major_every: u32) -> Vec<GridLine> {
|
||||
let angle = if angle.is_finite() { angle } else { 0.0 };
|
||||
if !(view.min.is_finite() && view.max.is_finite() && origin.is_finite()) {
|
||||
return Vec::new();
|
||||
}
|
||||
let corners = [view.min, Vec2::new(view.max.x, view.min.y), view.max, Vec2::new(view.min.x, view.max.y)];
|
||||
// Neighbouring lines of a family are d·cos 30° apart.
|
||||
let gap = d * COS30;
|
||||
let major_every = i64::from(major_every.max(1));
|
||||
let mut out = Vec::new();
|
||||
for deg in [30.0f64, 90.0, 150.0] {
|
||||
for ° in degs {
|
||||
let dir = Vec2::from_angle(deg.to_radians() + angle);
|
||||
let n = dir.perp();
|
||||
let off = origin.dot(n);
|
||||
@@ -289,4 +304,50 @@ mod tests {
|
||||
assert!(grid_lines(v, 1e-9, Vec2::ZERO, 0.0, 5).is_empty());
|
||||
assert!(grid_lines(v, f64::NAN, Vec2::ZERO, 0.0, 5).is_empty());
|
||||
}
|
||||
|
||||
/// The rectangular grid: lines along X and Y through the snap base, `d` apart, every
|
||||
/// `major_every`th major, all turned by SNAPANG (in the World UCS too) and clipped to the view.
|
||||
#[test]
|
||||
fn rect_grid_lines_lie_in_the_snap_frame() {
|
||||
let v = Bounds2 { min: Vec2::new(0.0, 0.0), max: Vec2::new(10.0, 10.0) };
|
||||
let lines = rect_grid_lines(v, 1.0, Vec2::ZERO, 0.0, 5);
|
||||
// 0..=10 along each axis.
|
||||
assert_eq!(lines.len(), 22);
|
||||
let inside = |p: Vec2| p.x >= -1e-9 && p.x <= 10.0 + 1e-9 && p.y >= -1e-9 && p.y <= 10.0 + 1e-9;
|
||||
assert!(lines.iter().all(|l| inside(l.a) && inside(l.b)));
|
||||
let vertical_major: Vec<f64> = lines.iter().filter(|l| (l.a.x - l.b.x).abs() < 1e-9 && l.major).map(|l| l.a.x).collect();
|
||||
assert_eq!(vertical_major.len(), 3, "x = 0, 5 and 10");
|
||||
assert!(vertical_major.iter().all(|x| (x / 5.0 - (x / 5.0).round()).abs() < 1e-9));
|
||||
// Turned 30° about a base at (0.5, 0.25): every line runs at 30° or 120°, and one of each
|
||||
// passes through the base.
|
||||
let (base, a) = (Vec2::new(0.5, 0.25), 30f64.to_radians());
|
||||
let turned = rect_grid_lines(v, 1.0, base, a, 5);
|
||||
assert!(!turned.is_empty());
|
||||
let (ux, uy) = (Vec2::from_angle(a), Vec2::from_angle(a).perp());
|
||||
for l in &turned {
|
||||
let d = (l.b - l.a).normalized();
|
||||
assert!(d.cross(ux).abs() < 1e-9 || d.cross(uy).abs() < 1e-9, "{l:?}");
|
||||
// Each line is a whole number of steps from the base across its direction.
|
||||
let k = (l.a - base).cross(d);
|
||||
assert!((k - k.round()).abs() < 1e-9, "{l:?}");
|
||||
}
|
||||
let through = |dir: Vec2| turned.iter().any(|l| (l.b - l.a).normalized().cross(dir).abs() < 1e-9 && (base - l.a).cross(dir).abs() < 1e-9);
|
||||
assert!(through(ux) && through(uy));
|
||||
// Too many lines, or no spacing: nothing drawn.
|
||||
assert!(rect_grid_lines(v, 1e-6, Vec2::ZERO, 0.0, 5).is_empty());
|
||||
assert!(rect_grid_lines(v, f64::NAN, Vec2::ZERO, 0.0, 5).is_empty());
|
||||
assert!(rect_grid_lines(v, 1.0, Vec2::new(f64::INFINITY, 0.0), 0.0, 5).is_empty());
|
||||
}
|
||||
|
||||
/// A view far larger than any grid (a zoom to hostile extents) draws no grid instead of
|
||||
/// overflowing the line count.
|
||||
#[test]
|
||||
fn rect_grid_lines_survive_extreme_views() {
|
||||
let huge = Bounds2::new(Vec2::new(-1e300, -1e300), Vec2::new(1e300, 1e300));
|
||||
assert!(rect_grid_lines(huge, 1.0, Vec2::ZERO, 0.0, 5).is_empty());
|
||||
let far = Bounds2::new(Vec2::new(1e300, 1e300), Vec2::new(1e300 + 1.0, 1e300 + 1.0));
|
||||
assert!(rect_grid_lines(far, 1.0, Vec2::ZERO, 0.0, 5).len() <= 2 * (MAX_GRID_LINES + 1));
|
||||
let normal = Bounds2::new(Vec2::new(-5.0, 0.0), Vec2::new(5.0, 10.0));
|
||||
assert_eq!(rect_grid_lines(normal, 1.0, Vec2::ZERO, 0.0, 5).len(), 22);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,12 +259,14 @@ impl TrackConfig {
|
||||
/// direction (radians) of the last segment when the base point ends it.
|
||||
pub fn relative_to(s: &crate::Settings, angbase: f64, last: Option<f64>) -> Self {
|
||||
let additional: &[f64] = if s.polar_flags & polarmode::ADDITIONAL != 0 { &s.polaraddang } else { &[] };
|
||||
let absolute = polar_angles(s.polarang, additional, angbase);
|
||||
// Measured in the current UCS: from ANGBASE off its X axis.
|
||||
let ucs = if s.ucs_angle.is_finite() { s.ucs_angle } else { 0.0 };
|
||||
let absolute = polar_angles(s.polarang, additional, angbase + ucs);
|
||||
let polar = match last.filter(|a| a.is_finite() && s.polar_flags & polarmode::RELATIVE != 0) {
|
||||
Some(a) => polar_angles(s.polarang, additional, a),
|
||||
None => absolute.clone(),
|
||||
};
|
||||
let track_angles = if s.polar_flags & polarmode::TRACK_POLAR != 0 { absolute } else { orthogonal() };
|
||||
let track_angles = if s.polar_flags & polarmode::TRACK_POLAR != 0 { absolute } else { orthogonal(ucs) };
|
||||
TrackConfig {
|
||||
otrack: s.otrack,
|
||||
osmode: s.osmode,
|
||||
@@ -279,9 +281,9 @@ impl TrackConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Horizontal and vertical, both ways.
|
||||
fn orthogonal() -> Vec<f64> {
|
||||
vec![0.0, PI / 2.0, PI, 1.5 * PI]
|
||||
/// Along the UCS axes (turned `ucs` radians from the world's), both ways.
|
||||
fn orthogonal(ucs: f64) -> Vec<f64> {
|
||||
[0.0, PI / 2.0, PI, 1.5 * PI].iter().map(|a| norm_angle(a + ucs)).collect()
|
||||
}
|
||||
|
||||
/// Every multiple of the increment `inc` (POLARANG) around the circle, plus the `additional`
|
||||
@@ -807,10 +809,11 @@ impl crate::Session {
|
||||
return CursorSnap { point: h.point, snap: Some(h), track: None, wait };
|
||||
}
|
||||
// Isometric snap (SNAPSTYL 1): its lattice in place of the rectangular grid.
|
||||
let (raw, s) = super::iso::grid_snap(&doc, s, raw);
|
||||
let snapmode = s.snapmode;
|
||||
let (raw, mut s) = super::iso::grid_snap(&doc, &space, s, raw);
|
||||
let mut p = raw;
|
||||
if s.snapmode && !s.polarsnap {
|
||||
let (origin, angle) = super::grid_frame(&doc);
|
||||
let (origin, angle) = super::grid_frame_in(&doc, &space);
|
||||
p = super::grid_snap(p, doc.header.snap_unit(), origin, angle);
|
||||
}
|
||||
if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) {
|
||||
@@ -829,7 +832,10 @@ impl crate::Session {
|
||||
&& s.orthomode
|
||||
&& !q.corner
|
||||
{
|
||||
p = super::iso::ortho(&self.settings, b, p);
|
||||
// Grid snap as it was before the isometric lattice took it (`grid_snap` turns it off),
|
||||
// so ortho keeps whole snap steps along the isometric axes.
|
||||
s.snapmode = snapmode;
|
||||
p = super::iso::ortho(&s, b, p);
|
||||
}
|
||||
CursorSnap { point: p, snap: None, track: None, wait }
|
||||
}
|
||||
|
||||
@@ -188,6 +188,19 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
json!([v.center.x, v.center.y, 0.0])
|
||||
}
|
||||
"VIEWSIZE" => json!(s.state().ok()?.view().height),
|
||||
// The current UCS of the space commands act on (paper space has its own per layout),
|
||||
// set by the UCS command.
|
||||
"UCSNAME" | "UCSORG" | "UCSXDIR" | "UCSYDIR" | "WORLDUCS" => {
|
||||
let (u, name) = s.ucs_named();
|
||||
let p = |v: cadcraft_geom::Vec3| json!([v.x, v.y, v.z]);
|
||||
match n.as_str() {
|
||||
"UCSNAME" => json!(name),
|
||||
"UCSORG" => p(u.origin),
|
||||
"UCSXDIR" => p(u.x),
|
||||
"UCSYDIR" => p(u.y),
|
||||
_ => json!(i32::from(u.is_world())),
|
||||
}
|
||||
}
|
||||
// The view twist (DVIEW TWist), in degrees counterclockwise.
|
||||
"VIEWTWIST" => json!(s.state().ok()?.view().twist.to_degrees()),
|
||||
"EXTMIN" | "EXTMAX" => {
|
||||
@@ -272,6 +285,11 @@ const READ_ONLY: &[&str] = &[
|
||||
"EXTMAX",
|
||||
"UNDOCTL",
|
||||
"UNDOMARKS",
|
||||
"UCSNAME",
|
||||
"UCSORG",
|
||||
"UCSXDIR",
|
||||
"UCSYDIR",
|
||||
"WORLDUCS",
|
||||
];
|
||||
|
||||
pub fn is_read_only(name: &str) -> bool {
|
||||
|
||||
@@ -73,6 +73,9 @@ const HEADER: &[(&str, Kind, Def)] = &[
|
||||
("TEXTFILL", Kind::Choice(&[0, 1]), Def::Int(1)),
|
||||
("TRIMEXTENDMODE", Kind::Choice(&[0, 1]), Def::Int(1)),
|
||||
("TRIMMODE", Kind::Choice(&[0, 1]), Def::Int(1)),
|
||||
("UCSAXISANG", Kind::Choice(&[5, 10, 15, 18, 22, 30, 45, 90, 180]), Def::Int(90)),
|
||||
// 1: the UCS icon is shown; 2: at the UCS origin when that is on screen.
|
||||
("UCSICON", Kind::Int(0, 3), Def::Int(3)),
|
||||
("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
|
||||
// XCLIP boundaries: 0 hidden, 1 shown and plotted, 2 shown but not plotted.
|
||||
("XCLIPFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(2)),
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
//! The user coordinate system (UCS): the coordinate system points are typed in, coordinates are
|
||||
//! shown in and directions are measured in.
|
||||
//!
|
||||
//! Model space keeps its current UCS in the drawing header (UCSORG, UCSXDIR, UCSYDIR, UCSNAME,
|
||||
//! as a DXF file does), each layout its paper-space UCS ([`cadcraft_doc::Layout::ucs`]). The
|
||||
//! drawing itself stays in world coordinates: a UCS changes how points are read and shown,
|
||||
//! never the stored geometry, so it costs nothing while drawing or regenerating.
|
||||
//!
|
||||
//! CADCraft draws in the world XY plane. A UCS whose XY plane is that plane (any origin, any
|
||||
//! rotation about Z) is used in full; one tilted out of it is kept and saved as it is, while
|
||||
//! points are read in the World UCS ([`Session::input_ucs`]).
|
||||
|
||||
use cadcraft_doc::{Drawing, HVal, Space, Ucs};
|
||||
use cadcraft_geom::{Vec2, Vec3};
|
||||
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// How many earlier UCSs UCS Previous goes back through, in each space.
|
||||
pub const MAX_PREVIOUS: usize = 10;
|
||||
|
||||
/// How close to the World UCS, or to the world XY plane, counts as on it.
|
||||
const TOL: f64 = 1e-9;
|
||||
|
||||
/// A coordinate system: its origin and unit X and Y axes, in world coordinates.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct UcsFrame {
|
||||
pub origin: Vec3,
|
||||
pub x: Vec3,
|
||||
pub y: Vec3,
|
||||
}
|
||||
|
||||
impl Default for UcsFrame {
|
||||
fn default() -> Self {
|
||||
Self::WORLD
|
||||
}
|
||||
}
|
||||
|
||||
impl UcsFrame {
|
||||
pub const WORLD: UcsFrame = UcsFrame { origin: Vec3::ZERO, x: Vec3::new(1.0, 0.0, 0.0), y: Vec3::new(0.0, 1.0, 0.0) };
|
||||
|
||||
/// A frame from an origin and X and Y directions: X is normalised and Y made square to it in
|
||||
/// their plane. `None` for non-finite values or directions with no length or along each other.
|
||||
pub fn new(origin: Vec3, x: Vec3, y: Vec3) -> Option<UcsFrame> {
|
||||
if !(origin.is_finite() && x.is_finite() && y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let xl = x.len();
|
||||
if !(xl > TOL && xl.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let x = x * (1.0 / xl);
|
||||
let yo = y.len();
|
||||
if !(yo > TOL && yo.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
// What is left of Y square to X: next to nothing means the two lie along each other.
|
||||
let y = y - x * x.dot(y);
|
||||
let yl = y.len();
|
||||
if !yl.is_finite() || yl <= 1e-9 * yo {
|
||||
return None;
|
||||
}
|
||||
Some(UcsFrame { origin, x, y: y * (1.0 / yl) })
|
||||
}
|
||||
|
||||
/// A UCS table record's frame (`None`: unusable axes).
|
||||
pub fn of(u: &Ucs) -> Option<UcsFrame> {
|
||||
UcsFrame::new(u.origin, u.x_axis, u.y_axis)
|
||||
}
|
||||
|
||||
/// This frame as a UCS table record named `name`.
|
||||
pub fn record(&self, name: &str) -> Ucs {
|
||||
Ucs { name: name.to_string(), origin: self.origin, x_axis: self.x, y_axis: self.y }
|
||||
}
|
||||
|
||||
pub fn z(&self) -> Vec3 {
|
||||
self.x.cross(self.y)
|
||||
}
|
||||
|
||||
/// The World UCS (to within rounding).
|
||||
pub fn is_world(&self) -> bool {
|
||||
self.origin.len() <= TOL * (1.0 + self.origin.len()) && self.is_planar() && (self.x - Vec3::new(1.0, 0.0, 0.0)).len() <= TOL
|
||||
}
|
||||
|
||||
/// Its XY plane is the world XY plane with Z up (any origin height, any rotation about Z).
|
||||
pub fn is_planar(&self) -> bool {
|
||||
self.x.z.abs() <= TOL && self.y.z.abs() <= TOL && self.z().z > 0.0
|
||||
}
|
||||
|
||||
/// The direction of its X axis in the world XY plane, radians counterclockwise from +X.
|
||||
pub fn rotation(&self) -> f64 {
|
||||
self.x.xy().angle()
|
||||
}
|
||||
|
||||
/// A point of the UCS XY plane, in world coordinates (planar frames; a tilted frame's XY
|
||||
/// plane seen from above).
|
||||
pub fn to_wcs(&self, p: Vec2) -> Vec2 {
|
||||
self.origin.xy() + self.vec_to_wcs(p)
|
||||
}
|
||||
|
||||
/// A world point in UCS coordinates (planar frames).
|
||||
pub fn to_ucs(&self, p: Vec2) -> Vec2 {
|
||||
self.vec_to_ucs(p - self.origin.xy())
|
||||
}
|
||||
|
||||
/// A displacement in the UCS XY plane, in world coordinates.
|
||||
pub fn vec_to_wcs(&self, v: Vec2) -> Vec2 {
|
||||
self.x.xy() * v.x + self.y.xy() * v.y
|
||||
}
|
||||
|
||||
/// A world displacement in UCS coordinates.
|
||||
pub fn vec_to_ucs(&self, v: Vec2) -> Vec2 {
|
||||
Vec2::new(v.dot(self.x.xy()), v.dot(self.y.xy()))
|
||||
}
|
||||
|
||||
/// A UCS point in world coordinates, in 3D.
|
||||
pub fn to_wcs3(&self, p: Vec3) -> Vec3 {
|
||||
self.origin + self.x * p.x + self.y * p.y + self.z() * p.z
|
||||
}
|
||||
|
||||
/// A world point in UCS coordinates, in 3D.
|
||||
pub fn to_ucs3(&self, p: Vec3) -> Vec3 {
|
||||
let d = p - self.origin;
|
||||
Vec3::new(d.dot(self.x), d.dot(self.y), d.dot(self.z()))
|
||||
}
|
||||
|
||||
/// The same axes at another origin.
|
||||
pub fn with_origin(&self, origin: Vec3) -> UcsFrame {
|
||||
UcsFrame { origin, ..*self }
|
||||
}
|
||||
|
||||
/// Turned by `angle` radians about its own Z axis (counterclockwise looking down Z).
|
||||
pub fn rotated_z(&self, angle: f64) -> UcsFrame {
|
||||
let (s, c) = angle.sin_cos();
|
||||
UcsFrame { origin: self.origin, x: self.x * c + self.y * s, y: self.y * c - self.x * s }
|
||||
}
|
||||
|
||||
/// UCS from points (world coordinates): a new origin; with a point on the positive X axis,
|
||||
/// X points at it; with a point on the positive-Y half of the XY plane too, that fixes Y.
|
||||
/// Without the third point Y stays square to X and to this frame's Z. `None` when the
|
||||
/// points don't fix an axis (on top of each other, or all three on a line).
|
||||
pub fn from_points(&self, origin: Vec3, x_point: Option<Vec3>, xy_point: Option<Vec3>) -> Option<UcsFrame> {
|
||||
let Some(xp) = x_point else { return origin.is_finite().then(|| self.with_origin(origin)) };
|
||||
let x = xp - origin;
|
||||
match xy_point {
|
||||
Some(yp) => UcsFrame::new(origin, x, yp - origin),
|
||||
None => {
|
||||
let xl = x.len();
|
||||
if !(xl > TOL && xl.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let y = self.z().cross(x * (1.0 / xl));
|
||||
UcsFrame::new(origin, x, y)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The usable current UCS of `space` in `d`, if it has one.
|
||||
fn frame_of(d: &Drawing, space: &Space) -> Option<UcsFrame> {
|
||||
match space {
|
||||
Space::Model => {
|
||||
let h = &d.header;
|
||||
match (h.point("UCSORG"), h.point("UCSXDIR"), h.point("UCSYDIR")) {
|
||||
(Some(o), Some(x), Some(y)) => UcsFrame::new(o, x, y),
|
||||
(o, None, None) => o.filter(|o| o.is_finite()).map(|o| UcsFrame::WORLD.with_origin(o)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
Space::Paper(name) => d.layout(name).and_then(|l| l.ucs.as_ref()).and_then(UcsFrame::of),
|
||||
}
|
||||
}
|
||||
|
||||
/// The current UCS of `space` in `d` without its name, so nothing is allocated: what the
|
||||
/// per-point and per-angle paths need. A missing or unusable one is the World UCS.
|
||||
pub fn current_frame(d: &Drawing, space: &Space) -> UcsFrame {
|
||||
frame_of(d, space).unwrap_or(UcsFrame::WORLD)
|
||||
}
|
||||
|
||||
/// The current UCS of `space` in `d` and its name (empty when it isn't a named UCS). A missing
|
||||
/// or unusable one is the World UCS.
|
||||
pub fn current(d: &Drawing, space: &Space) -> (UcsFrame, String) {
|
||||
let Some(frame) = frame_of(d, space) else { return (UcsFrame::WORLD, String::new()) };
|
||||
let name = match space {
|
||||
Space::Model => d.header.str("UCSNAME", "").trim().to_string(),
|
||||
Space::Paper(name) => d.layout(name).and_then(|l| l.ucs.as_ref()).map(|u| u.name.trim().to_string()).unwrap_or_default(),
|
||||
};
|
||||
(frame, name)
|
||||
}
|
||||
|
||||
/// Make `frame` (named `name`, empty for an unnamed one) the current UCS of `space`.
|
||||
pub fn set_current(d: &mut Drawing, space: &Space, frame: &UcsFrame, name: &str) {
|
||||
match space {
|
||||
Space::Model => {
|
||||
let h = &mut d.header;
|
||||
h.set("UCSORG", HVal::Point(frame.origin));
|
||||
h.set("UCSXDIR", HVal::Point(frame.x));
|
||||
h.set("UCSYDIR", HVal::Point(frame.y));
|
||||
h.set_str("UCSNAME", name);
|
||||
}
|
||||
Space::Paper(layout) => {
|
||||
if let Some(l) = d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)) {
|
||||
l.ucs = (!(frame.is_world() && name.is_empty())).then(|| frame.record(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `space`'s UCS Previous history, kept in the drawing (so undo restores it) and, for a layout,
|
||||
/// with the layout (so it follows a rename and goes with a delete). `None`: no such layout.
|
||||
fn previous_mut<'a>(d: &'a mut Drawing, space: &Space) -> Option<&'a mut Vec<Ucs>> {
|
||||
match space {
|
||||
Space::Model => Some(&mut d.ucs_previous),
|
||||
Space::Paper(layout) => d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)).map(|l| &mut l.ucs_previous),
|
||||
}
|
||||
}
|
||||
|
||||
/// The named UCS `name` of the drawing's UCS table, if it has one with usable axes.
|
||||
pub fn named(d: &Drawing, name: &str) -> Option<(UcsFrame, String)> {
|
||||
let u = d.ucss.iter().find(|u| u.name.eq_ignore_ascii_case(name.trim()))?;
|
||||
Some((UcsFrame::of(u)?, u.name.clone()))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The current UCS of the space commands act on, and its name.
|
||||
pub fn ucs_named(&self) -> (UcsFrame, String) {
|
||||
self.doc().map(|d| current(d, &self.space())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The current UCS of the space commands act on.
|
||||
pub fn ucs(&self) -> UcsFrame {
|
||||
self.doc().map(|d| current_frame(d, &self.space())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The UCS points are typed in and shown in: the current one, or the World UCS while the
|
||||
/// current one is tilted out of the XY plane (CADCraft draws in that plane).
|
||||
pub fn input_ucs(&self) -> UcsFrame {
|
||||
let u = self.ucs();
|
||||
if u.is_planar() { u } else { UcsFrame::WORLD }
|
||||
}
|
||||
|
||||
/// A typed point as the user means it: in the current UCS (`*` for world coordinates), with
|
||||
/// the drawing's angle settings; relative forms from `last`. A world point.
|
||||
pub fn parse_typed_point(&self, text: &str, last: Vec2) -> Option<Vec2> {
|
||||
crate::prompt::parse_point_in(text, last, &self.angle_settings(), &self.input_ucs())
|
||||
}
|
||||
|
||||
/// A world point in the coordinates shown to the user (the current UCS).
|
||||
pub fn ucs_point(&self, p: Vec2) -> Vec2 {
|
||||
self.input_ucs().to_ucs(p)
|
||||
}
|
||||
|
||||
/// A world direction (radians from world +X) measured from the current UCS X axis.
|
||||
pub fn ucs_angle(&self, a: f64) -> f64 {
|
||||
cadcraft_geom::norm_angle(a - self.input_ucs().rotation())
|
||||
}
|
||||
|
||||
/// Make `frame` the current UCS (named `name`; empty for an unnamed one), remembering the one
|
||||
/// it replaces for UCS Previous. Part of the running command's undo step.
|
||||
pub fn set_ucs(&mut self, frame: UcsFrame, name: &str) -> Result<()> {
|
||||
let space = self.space();
|
||||
let (old, old_name) = self.ucs_named();
|
||||
if old == frame && old_name.eq_ignore_ascii_case(name) {
|
||||
return Ok(());
|
||||
}
|
||||
let d = self.doc_mut()?;
|
||||
set_current(d, &space, &frame, name);
|
||||
if let Some(h) = previous_mut(d, &space) {
|
||||
h.push(old.record(&old_name));
|
||||
// At most MAX_PREVIOUS: drop the oldest.
|
||||
if h.len() > MAX_PREVIOUS {
|
||||
h.remove(0);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Go back to the UCS before the current one in this space; `false` when there is none.
|
||||
pub fn ucs_previous(&mut self) -> Result<bool> {
|
||||
let space = self.space();
|
||||
// Nothing to go back to: the drawing stays unmodified.
|
||||
let none = self.doc().map_or(true, |d| match &space {
|
||||
Space::Model => d.ucs_previous.is_empty(),
|
||||
Space::Paper(layout) => d.layout(layout).is_none_or(|l| l.ucs_previous.is_empty()),
|
||||
});
|
||||
if none {
|
||||
return Ok(false);
|
||||
}
|
||||
let d = self.doc_mut()?;
|
||||
// An entry with unusable axes (none is ever stored) is skipped, not restored.
|
||||
while let Some(u) = previous_mut(d, &space).and_then(|h| h.pop()) {
|
||||
if let Some(frame) = UcsFrame::of(&u) {
|
||||
set_current(d, &space, &frame, &u.name);
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// UCSICON: 1 the icon is shown, 2 at the UCS origin (when that is on screen).
|
||||
pub fn ucsicon_bits(&self) -> i64 {
|
||||
self.doc().map(|d| d.header.i64("UCSICON", 3)).unwrap_or(3).clamp(0, 3)
|
||||
}
|
||||
|
||||
/// Tell the user once per drawing that its current UCS is tilted and points are read in the
|
||||
/// World UCS for now.
|
||||
pub(crate) fn note_tilted_ucs(&mut self) {
|
||||
if self.ucs().is_planar() {
|
||||
return;
|
||||
}
|
||||
let Ok(st) = self.state_mut() else { return };
|
||||
if std::mem::replace(&mut st.ucs_tilted_noted, true) {
|
||||
return;
|
||||
}
|
||||
self.echo("The current UCS is tilted out of the XY plane; points are read and shown in the World UCS for now.");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn near(a: Vec2, b: Vec2) -> bool {
|
||||
a.dist(b) < 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn world_is_the_identity() {
|
||||
let w = UcsFrame::WORLD;
|
||||
assert!(w.is_world() && w.is_planar());
|
||||
assert_eq!(w.rotation(), 0.0);
|
||||
let p = Vec2::new(3.5, -2.25);
|
||||
assert_eq!(w.to_wcs(p), p);
|
||||
assert_eq!(w.to_ucs(p), p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_moved_frame_maps_both_ways() {
|
||||
let f = UcsFrame::WORLD.with_origin(Vec3::new(100.0, 50.0, 0.0)).rotated_z(30f64.to_radians());
|
||||
assert!(f.is_planar() && !f.is_world());
|
||||
assert!((f.rotation() - 30f64.to_radians()).abs() < 1e-12);
|
||||
// The UCS X axis one unit out is 30° from world +X.
|
||||
assert!(near(f.to_wcs(Vec2::new(1.0, 0.0)), Vec2::new(100.0 + 30f64.to_radians().cos(), 50.0 + 30f64.to_radians().sin())));
|
||||
for p in [Vec2::new(0.0, 0.0), Vec2::new(12.0, -7.0), Vec2::new(-1e6, 3e5)] {
|
||||
assert!(near(f.to_ucs(f.to_wcs(p)), p), "{p:?}");
|
||||
let q = Vec3::new(p.x, p.y, 4.0);
|
||||
assert!((f.to_ucs3(f.to_wcs3(q)) - q).len() < 1e-9);
|
||||
}
|
||||
assert!(near(f.vec_to_ucs(f.vec_to_wcs(Vec2::new(2.0, 3.0))), Vec2::new(2.0, 3.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_squares_and_rejects() {
|
||||
let f = UcsFrame::new(Vec3::ZERO, Vec3::new(2.0, 0.0, 0.0), Vec3::new(1.0, 5.0, 0.0)).unwrap();
|
||||
assert_eq!((f.x, f.y), (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)));
|
||||
assert!(UcsFrame::new(Vec3::ZERO, Vec3::ZERO, Vec3::new(0.0, 1.0, 0.0)).is_none());
|
||||
assert!(UcsFrame::new(Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0), Vec3::new(3.0, 0.0, 0.0)).is_none());
|
||||
assert!(UcsFrame::new(Vec3::new(f64::NAN, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)).is_none());
|
||||
assert!(UcsFrame::new(Vec3::ZERO, Vec3::new(f64::INFINITY, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tilted_and_flipped_frames_are_not_planar() {
|
||||
let front = UcsFrame::new(Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0)).unwrap();
|
||||
assert!(!front.is_planar());
|
||||
let bottom = UcsFrame::new(Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, -1.0, 0.0)).unwrap();
|
||||
assert!(!bottom.is_planar(), "Z down");
|
||||
let raised = UcsFrame::WORLD.with_origin(Vec3::new(0.0, 0.0, 25.0));
|
||||
assert!(raised.is_planar() && !raised.is_world());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_points() {
|
||||
let w = UcsFrame::WORLD;
|
||||
let o = Vec3::new(10.0, 10.0, 0.0);
|
||||
assert_eq!(w.from_points(o, None, None), Some(w.with_origin(o)));
|
||||
let f = w.from_points(o, Some(Vec3::new(10.0, 20.0, 0.0)), None).unwrap();
|
||||
assert!((f.rotation() - std::f64::consts::FRAC_PI_2).abs() < 1e-12 && f.is_planar());
|
||||
// A third point on the negative-Y side of the X axis turns the UCS over.
|
||||
let g = w.from_points(o, Some(Vec3::new(20.0, 10.0, 0.0)), Some(Vec3::new(15.0, 0.0, 0.0))).unwrap();
|
||||
assert!(!g.is_planar());
|
||||
assert!(w.from_points(o, Some(o), None).is_none());
|
||||
assert!(w.from_points(o, Some(Vec3::new(20.0, 10.0, 0.0)), Some(Vec3::new(30.0, 10.0, 0.0))).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_per_space() {
|
||||
let mut d = Drawing::default();
|
||||
let paper = Space::Paper(d.layouts[0].name.clone());
|
||||
let f = UcsFrame::WORLD.with_origin(Vec3::new(5.0, 5.0, 0.0)).rotated_z(0.5);
|
||||
set_current(&mut d, &Space::Model, &f, "SITE");
|
||||
let (m, n) = current(&d, &Space::Model);
|
||||
assert!((m.origin - f.origin).len() < 1e-12 && (m.x - f.x).len() < 1e-12 && n == "SITE");
|
||||
assert_eq!(current(&d, &paper).0, UcsFrame::WORLD, "paper space has its own");
|
||||
set_current(&mut d, &paper, &f, "");
|
||||
assert!(d.layouts[0].ucs.is_some());
|
||||
set_current(&mut d, &paper, &UcsFrame::WORLD, "");
|
||||
assert!(d.layouts[0].ucs.is_none());
|
||||
// Broken header values are the World UCS.
|
||||
d.header.set("UCSXDIR", HVal::Point(Vec3::ZERO));
|
||||
assert_eq!(current(&d, &Space::Model).0, UcsFrame::WORLD);
|
||||
d.header.set("UCSXDIR", HVal::Point(Vec3::new(f64::NAN, 0.0, 0.0)));
|
||||
assert_eq!(current(&d, &Space::Model).0, UcsFrame::WORLD);
|
||||
}
|
||||
}
|
||||
+54
-17
@@ -269,11 +269,20 @@ pub struct AngleSettings {
|
||||
pub angbase: f64,
|
||||
/// ANGDIR 1: positive angles turn clockwise.
|
||||
pub clockwise: bool,
|
||||
/// The current UCS's X axis, radians counterclockwise from world +X: directions are measured
|
||||
/// in the UCS (ANGBASE from its X axis, the overrides and bearings too). Sizes of angles
|
||||
/// ([`AngleSettings::amount`], [`AngleSettings::rotation`]) don't depend on it.
|
||||
pub ucs: f64,
|
||||
}
|
||||
|
||||
impl AngleSettings {
|
||||
pub fn from_header(h: &cadcraft_doc::Header) -> Self {
|
||||
AngleSettings { aunits: h.i64("AUNITS", 0), angbase: h.f64("ANGBASE", 0.0), clockwise: h.i64("ANGDIR", 0) != 0 }
|
||||
AngleSettings { aunits: h.i64("AUNITS", 0), angbase: h.f64("ANGBASE", 0.0), clockwise: h.i64("ANGDIR", 0) != 0, ucs: 0.0 }
|
||||
}
|
||||
|
||||
/// The same settings with directions measured in the World UCS (`*` coordinates).
|
||||
pub fn world(&self) -> Self {
|
||||
AngleSettings { ucs: 0.0, ..*self }
|
||||
}
|
||||
|
||||
/// A typed angle size in radians (included angles, sweeps, angles from an axis): a bare
|
||||
@@ -295,29 +304,31 @@ impl AngleSettings {
|
||||
/// (AutoCAD refuses `<<N45dE` and `<<N`).
|
||||
pub fn direction(&self, s: &str) -> Option<f64> {
|
||||
let t = s.trim();
|
||||
let ucs = |a: f64| Some(a + self.ucs).filter(|v| v.is_finite());
|
||||
if let Some(r) = t.strip_prefix("<<<") {
|
||||
return parse_units(r, self.aunits).map(|(a, _)| a);
|
||||
return parse_units(r, self.aunits).and_then(|(a, _)| ucs(a));
|
||||
}
|
||||
if let Some(r) = t.strip_prefix("<<") {
|
||||
return parse_units(r, 0).filter(|(_, bearing)| !bearing).map(|(a, _)| a);
|
||||
return parse_units(r, 0).filter(|(_, bearing)| !bearing).and_then(|(a, _)| ucs(a));
|
||||
}
|
||||
let (a, _) = parse_units(t, self.aunits)?;
|
||||
let v = self.angbase + if self.clockwise { -a } else { a };
|
||||
v.is_finite().then_some(v)
|
||||
ucs(self.angbase + if self.clockwise { -a } else { a })
|
||||
}
|
||||
|
||||
/// Direction `dir` (radians counterclockwise from +X) as the drawing shows directions, in
|
||||
/// radians: from ANGBASE in the ANGDIR sense, 0 up to a full turn. (A block turned 2.23°
|
||||
/// shows as 87.77 in a drawing measured clockwise from north, as in AutoCAD's Properties.)
|
||||
/// Direction `dir` (radians counterclockwise from world +X) as the drawing shows directions,
|
||||
/// in radians: from ANGBASE in the ANGDIR sense, measured in the current UCS (`ucs`) as typed
|
||||
/// directions are read ([`AngleSettings::direction`]), 0 up to a full turn. (A block turned
|
||||
/// 2.23° shows as 87.77 in a drawing measured clockwise from north, as in AutoCAD's Properties.)
|
||||
pub fn shown(&self, dir: f64) -> f64 {
|
||||
let a = if self.clockwise { self.angbase - dir } else { dir - self.angbase };
|
||||
let local = dir - self.ucs;
|
||||
let a = if self.clockwise { self.angbase - local } else { local - self.angbase };
|
||||
a.rem_euclid(std::f64::consts::TAU)
|
||||
}
|
||||
|
||||
/// The direction (radians counterclockwise from +X) the drawing shows as `v` (radians): the
|
||||
/// inverse of [`AngleSettings::shown`].
|
||||
/// The direction (radians counterclockwise from world +X) the drawing shows as `v`
|
||||
/// (radians): the inverse of [`AngleSettings::shown`].
|
||||
pub fn unshown(&self, v: f64) -> f64 {
|
||||
(self.angbase + if self.clockwise { -v } else { v }).rem_euclid(std::f64::consts::TAU)
|
||||
(self.ucs + self.angbase + if self.clockwise { -v } else { v }).rem_euclid(std::f64::consts::TAU)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -418,9 +429,12 @@ fn parse_dms(t: &str) -> Option<f64> {
|
||||
}
|
||||
|
||||
impl crate::Session {
|
||||
/// How typed angles are read in the current drawing (the defaults without one).
|
||||
/// How typed angles are read in the current drawing (the defaults without one): directions
|
||||
/// are measured in the current UCS.
|
||||
pub fn angle_settings(&self) -> AngleSettings {
|
||||
self.doc().map(|d| AngleSettings::from_header(&d.header)).unwrap_or_default()
|
||||
let a = self.doc().map(|d| AngleSettings::from_header(&d.header)).unwrap_or_default();
|
||||
let ucs = self.input_ucs().rotation();
|
||||
AngleSettings { ucs: if ucs.is_finite() { ucs } else { 0.0 }, ..a }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -464,7 +478,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn directions_show_from_angbase_in_the_angdir_sense() {
|
||||
let north_clockwise = AngleSettings { aunits: 0, angbase: 90f64.to_radians(), clockwise: true };
|
||||
let north_clockwise = AngleSettings { aunits: 0, angbase: 90f64.to_radians(), clockwise: true, ucs: 0.0 };
|
||||
// AutoCAD shows a block turned 2.22729505553431° as 87.77 in such a drawing.
|
||||
let shown = north_clockwise.shown(2.22729505553431f64.to_radians()).to_degrees();
|
||||
assert!((shown - 87.77270494446569).abs() < 1e-9, "{shown}");
|
||||
@@ -474,10 +488,33 @@ mod tests {
|
||||
let plain = AngleSettings::default();
|
||||
assert!((plain.shown(0.5) - 0.5).abs() < 1e-12 && (plain.unshown(0.5) - 0.5).abs() < 1e-12);
|
||||
// Counterclockwise from a base of 30°: 45° shows as 15.
|
||||
let based = AngleSettings { aunits: 0, angbase: 30f64.to_radians(), clockwise: false };
|
||||
let based = AngleSettings { aunits: 0, angbase: 30f64.to_radians(), clockwise: false, ucs: 0.0 };
|
||||
assert!((based.shown(45f64.to_radians()).to_degrees() - 15.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// In a turned UCS, a shown direction (the Properties palette's Rotation) is measured from
|
||||
/// the UCS X axis, as typed directions are: what is typed as 0 shows as 0, and back.
|
||||
#[test]
|
||||
fn shown_directions_are_measured_in_the_ucs() {
|
||||
let turned = AngleSettings { ucs: 90f64.to_radians(), ..AngleSettings::default() };
|
||||
let typed = turned.direction("0").unwrap();
|
||||
assert!((typed - 90f64.to_radians()).abs() < 1e-12, "0 in the UCS is world 90°");
|
||||
assert!(turned.shown(typed).abs() < 1e-12, "and shows as 0");
|
||||
assert!((turned.unshown(0.0) - typed).abs() < 1e-12, "0 entered is that direction");
|
||||
// With ANGBASE and ANGDIR too: every direction shown and entered back is itself.
|
||||
let s = AngleSettings { aunits: 0, angbase: 30f64.to_radians(), clockwise: true, ucs: 50f64.to_radians() };
|
||||
for deg in [0.0, 12.5, 90.0, 181.0, 359.0] {
|
||||
let dir = f64::to_radians(deg);
|
||||
let back = s.unshown(s.shown(dir));
|
||||
assert!((back - dir).rem_euclid(std::f64::consts::TAU).min((dir - back).rem_euclid(std::f64::consts::TAU)) < 1e-9, "{deg}");
|
||||
let typed = s.direction(&format!("{}", s.shown(dir).to_degrees())).unwrap();
|
||||
assert!(
|
||||
((typed - dir).rem_euclid(std::f64::consts::TAU)).min((dir - typed).rem_euclid(std::f64::consts::TAU)) < 1e-9,
|
||||
"{deg}: shown then typed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimal_and_arch() {
|
||||
assert_eq!(format_distance(28.98524, 2, 4), "28.9852");
|
||||
@@ -569,7 +606,7 @@ mod tests {
|
||||
// What surveyor's units show for a due bearing can be typed back, e.g. `@10<E`. AutoCAD 2024
|
||||
// reads the letter as an angle like any other, from ANGBASE in the ANGDIR sense: with
|
||||
// ANGBASE 90 and ANGDIR 1, `@10<N` draws east.
|
||||
let a = AngleSettings { aunits: 4, angbase: PI / 2.0, clockwise: true };
|
||||
let a = AngleSettings { aunits: 4, angbase: PI / 2.0, clockwise: true, ucs: 0.0 };
|
||||
for (t, want) in [("E", PI / 2.0), ("n", 0.0), ("W", 1.5 * PI), ("s", PI)] {
|
||||
let got = a.direction(t).unwrap().rem_euclid(2.0 * PI);
|
||||
assert!((got - want).abs() < 1e-12, "{t}: {got}");
|
||||
|
||||
@@ -84,7 +84,7 @@ fn bearings_and_compass_points_turn_with_angbase_and_angdir() {
|
||||
assert_near(line_end(&mut s, to), 10.0 * a.cos(), 10.0 * a.sin(), &format!("{to} AUNITS {aunits} ANGBASE {angbase} ANGDIR {angdir}"));
|
||||
}
|
||||
// `<<` is in degrees only: AutoCAD refuses a bearing or a compass point there.
|
||||
let settings = AngleSettings { aunits: 0, angbase: std::f64::consts::FRAC_PI_2, clockwise: true };
|
||||
let settings = AngleSettings { aunits: 0, angbase: std::f64::consts::FRAC_PI_2, clockwise: true, ucs: 0.0 };
|
||||
assert_eq!(settings.direction("<<N45dE"), None);
|
||||
assert_eq!(settings.direction("<<N"), None);
|
||||
assert!(settings.direction("<<45").is_some_and(|a| (a - std::f64::consts::FRAC_PI_4).abs() < 1e-12));
|
||||
@@ -161,7 +161,7 @@ fn json_and_default_parsing_keep_degrees_from_east() {
|
||||
// SETVAR reports ANGBASE in degrees.
|
||||
let v = cadcraft_engine::sysvars::get(&s, "ANGBASE").unwrap();
|
||||
assert!((v.as_f64().unwrap() - 90.0).abs() < 1e-9, "{v}");
|
||||
let a = AngleSettings { aunits: 0, angbase: 0.0, clockwise: false };
|
||||
let a = AngleSettings { aunits: 0, angbase: 0.0, clockwise: false, ucs: 0.0 };
|
||||
assert_eq!(a.direction(""), None);
|
||||
assert_eq!(a.direction("nan"), None);
|
||||
assert_eq!(a.direction("1e400"), None);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
//! The user coordinate system (#1106): the UCS command and its options, typed coordinates and
|
||||
//! directions read in the current UCS, coordinates shown in it, the UCS system variables,
|
||||
//! UCSICON, paper space's own UCS, undo, and hostile input.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, HVal, Space};
|
||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||
use cadcraft_engine::ucs::UcsFrame;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const TAU: f64 = std::f64::consts::TAU;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_drawing(false);
|
||||
s
|
||||
}
|
||||
|
||||
fn typed(s: &mut Session, lines: &[&str]) {
|
||||
for l in lines {
|
||||
s.cmdline(l).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn near(a: Vec2, x: f64, y: f64) -> bool {
|
||||
a.dist(Vec2::new(x, y)) < 1e-9
|
||||
}
|
||||
|
||||
fn near3(a: Vec3, b: Vec3) -> bool {
|
||||
(a - b).len() < 1e-9
|
||||
}
|
||||
|
||||
fn ang_eq(a: f64, b: f64) -> bool {
|
||||
let d = (a - b).rem_euclid(TAU);
|
||||
d < 1e-9 || TAU - d < 1e-9
|
||||
}
|
||||
|
||||
fn lines(s: &Session) -> Vec<(Vec2, Vec2)> {
|
||||
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).collect()
|
||||
}
|
||||
|
||||
fn last_line(s: &Session) -> (Vec2, Vec2) {
|
||||
*lines(s).last().expect("a line")
|
||||
}
|
||||
|
||||
fn logged(s: &Session, text: &str) -> bool {
|
||||
s.log.iter().any(|l| l.contains(text))
|
||||
}
|
||||
|
||||
fn var(s: &Session, name: &str) -> Value {
|
||||
cadcraft_engine::sysvars::get(s, name).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
fn vec3(v: &Value) -> Vec3 {
|
||||
Vec3::new(v[0].as_f64().unwrap(), v[1].as_f64().unwrap(), v[2].as_f64().unwrap())
|
||||
}
|
||||
|
||||
/// A UCS at (100, 50) turned 90°: UCS X is world +Y, UCS Y is world -X.
|
||||
fn turned(s: &mut Session) {
|
||||
s.execute("ucs", &json!({"option": "origin", "origin": [100, 50]})).unwrap();
|
||||
s.execute("ucs", &json!({"option": "z", "angle": 90})).unwrap();
|
||||
let u = s.ucs();
|
||||
assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)) && near3(u.x, Vec3::new(0.0, 1.0, 0.0)), "{u:?}");
|
||||
}
|
||||
|
||||
// ---------------- the UCS command ----------------
|
||||
|
||||
#[test]
|
||||
fn a_new_drawing_is_in_the_world_ucs() {
|
||||
let s = session();
|
||||
assert!(s.ucs().is_world());
|
||||
assert_eq!(var(&s, "WORLDUCS"), json!(1));
|
||||
assert_eq!(var(&s, "UCSNAME"), json!(""));
|
||||
assert!(near3(vec3(&var(&s, "UCSORG")), Vec3::ZERO));
|
||||
assert!(near3(vec3(&var(&s, "UCSXDIR")), Vec3::new(1.0, 0.0, 0.0)));
|
||||
assert!(near3(vec3(&var(&s, "UCSYDIR")), Vec3::new(0.0, 1.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ucs_origin_then_enter_moves_the_origin_and_keeps_the_axes() {
|
||||
let mut s = session();
|
||||
typed(&mut s, &["ucs 100,50 "]);
|
||||
assert!(logged(&s, "Current ucs name: *WORLD*"));
|
||||
let u = s.ucs();
|
||||
assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)) && near3(u.x, Vec3::new(1.0, 0.0, 0.0)));
|
||||
assert_eq!(var(&s, "WORLDUCS"), json!(0));
|
||||
assert!(near3(vec3(&var(&s, "UCSORG")), Vec3::new(100.0, 50.0, 0.0)));
|
||||
typed(&mut s, &["ucs "]);
|
||||
assert!(logged(&s, "Current ucs name: *NO NAME*"), "{:?}", s.log);
|
||||
assert!(s.ucs().is_world(), "Enter at the first prompt is World");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ucs_by_three_points() {
|
||||
let mut s = session();
|
||||
// Origin, a point on the new X axis (straight up), Enter: Y square to it.
|
||||
typed(&mut s, &["ucs 10,10 10,30 "]);
|
||||
let u = s.ucs();
|
||||
assert!(near3(u.origin, Vec3::new(10.0, 10.0, 0.0)) && near3(u.x, Vec3::new(0.0, 1.0, 0.0)) && near3(u.y, Vec3::new(-1.0, 0.0, 0.0)), "{u:?}");
|
||||
// All three points; typed points are read in the UCS current while UCS runs.
|
||||
typed(&mut s, &["ucs w", "ucs 0,0 1,1 -1,1"]);
|
||||
let u = s.ucs();
|
||||
let r = std::f64::consts::FRAC_1_SQRT_2;
|
||||
assert!(near3(u.x, Vec3::new(r, r, 0.0)) && near3(u.y, Vec3::new(-r, r, 0.0)) && u.is_planar(), "{u:?}");
|
||||
// A third point below the X axis would turn the UCS over: refused, and the UCS is kept.
|
||||
let before = s.ucs();
|
||||
let _ = s.cmdline("ucs 0,0 10,0 5,-5");
|
||||
assert!(near3(s.ucs().x, before.x), "a turned-over UCS is not taken");
|
||||
s.cancel();
|
||||
// Points on one line define nothing.
|
||||
assert!(s.execute("ucs", &json!({"origin": [0, 0], "xPoint": [10, 0], "xyPoint": [20, 0]})).is_err());
|
||||
assert!(s.execute("ucs", &json!({"origin": [0, 0], "xPoint": [0, 0]})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ucs_z_turns_about_z_and_defaults_to_ucsaxisang() {
|
||||
let mut s = session();
|
||||
typed(&mut s, &["ucs z 30"]);
|
||||
assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()));
|
||||
typed(&mut s, &["ucs z "]);
|
||||
assert!(ang_eq(s.ucs().rotation(), 120f64.to_radians()), "Enter takes UCSAXISANG (90)");
|
||||
cadcraft_engine::sysvars::set(&mut s, "UCSAXISANG", &json!(45)).unwrap();
|
||||
typed(&mut s, &["ucs z "]);
|
||||
assert!(ang_eq(s.ucs().rotation(), 165f64.to_radians()));
|
||||
assert!(cadcraft_engine::sysvars::set(&mut s, "UCSAXISANG", &json!(33)).is_err(), "only the listed angles");
|
||||
typed(&mut s, &["ucs z -165"]);
|
||||
assert!(ang_eq(s.ucs().rotation(), 0.0));
|
||||
// 30 is one of the listed angles too.
|
||||
cadcraft_engine::sysvars::set(&mut s, "UCSAXISANG", &json!(30)).unwrap();
|
||||
typed(&mut s, &["ucs z "]);
|
||||
assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ucs_previous_walks_back_ten_steps_per_space() {
|
||||
let mut s = session();
|
||||
for i in 1..=12 {
|
||||
s.execute("ucs", &json!({"option": "origin", "origin": [i, 0]})).unwrap();
|
||||
}
|
||||
for i in (2..=11).rev() {
|
||||
typed(&mut s, &["ucs p"]);
|
||||
assert!(near3(s.ucs().origin, Vec3::new(f64::from(i), 0.0, 0.0)), "back to {i}: {:?}", s.ucs());
|
||||
}
|
||||
let at = s.ucs();
|
||||
typed(&mut s, &["ucs p"]);
|
||||
assert!(logged(&s, "There is no previous UCS."));
|
||||
assert_eq!(s.ucs(), at, "only ten are kept");
|
||||
assert!(s.execute("ucs", &json!({"option": "previous"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_ucs_save_restore_list_delete() {
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
typed(&mut s, &["ucs na s SITE"]);
|
||||
assert_eq!(var(&s, "UCSNAME"), json!("SITE"));
|
||||
assert_eq!(s.doc().unwrap().ucss.len(), 1);
|
||||
typed(&mut s, &["ucs w"]);
|
||||
assert!(s.ucs().is_world());
|
||||
typed(&mut s, &["ucs na r site"]);
|
||||
assert!(near3(s.ucs().x, Vec3::new(0.0, 1.0, 0.0)) && var(&s, "UCSNAME") == json!("SITE"), "restored by any case");
|
||||
// Saving over a name asks first.
|
||||
typed(&mut s, &["ucs z 10", "ucs na s SITE", "n"]);
|
||||
let saved = s.doc().unwrap().ucss[0].clone();
|
||||
assert!(near3(saved.x_axis, Vec3::new(0.0, 1.0, 0.0)), "No keeps the saved one");
|
||||
typed(&mut s, &["ucs na s SITE", "y"]);
|
||||
assert!(!near3(s.doc().unwrap().ucss[0].x_axis, Vec3::new(0.0, 1.0, 0.0)), "Yes replaces it");
|
||||
// Listing.
|
||||
s.execute("ucs", &json!({"option": "named", "action": "save", "name": "Base 2"})).unwrap();
|
||||
let list = s.execute("ucs", &json!({"option": "named", "action": "list"})).unwrap()["list"].as_str().unwrap().to_string();
|
||||
assert!(list.contains("SITE") && list.contains("Base 2") && list.contains("Origin = <") && list.contains("Z Axis = <"), "{list}");
|
||||
typed(&mut s, &["ucs na ? *"]);
|
||||
assert!(logged(&s, "Saved coordinate systems:"));
|
||||
// Deleting by wildcard, and the current UCS loses a deleted name.
|
||||
let r = s.execute("ucs", &json!({"option": "named", "action": "delete", "name": "BASE*"})).unwrap();
|
||||
assert_eq!(r["deleted"], json!(1));
|
||||
assert_eq!(var(&s, "UCSNAME"), json!(""), "the current one was Base 2");
|
||||
typed(&mut s, &["ucs na d SITE"]);
|
||||
assert!(s.doc().unwrap().ucss.is_empty());
|
||||
// Unknown and invalid names.
|
||||
assert!(s.execute("ucs", &json!({"option": "named", "action": "restore", "name": "NOPE"})).is_err());
|
||||
for bad in ["", " ", "a<b", "x*", "semi;colon", "World", "*WORLD*", &"n".repeat(300)] {
|
||||
assert!(s.execute("ucs", &json!({"option": "named", "action": "save", "name": bad})).is_err(), "{bad:?}");
|
||||
}
|
||||
assert!(s.execute("ucs", &json!({"option": "named", "action": "save", "name": "SITE"})).is_ok());
|
||||
assert!(s.execute("ucs", &json!({"option": "named", "action": "save", "name": "site"})).is_err(), "names are case-blind");
|
||||
assert!(s.execute("ucs", &json!({"option": "named", "action": "save", "name": "site", "replace": true})).is_ok());
|
||||
assert_eq!(s.doc().unwrap().ucss.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ucs_object_follows_each_kind_of_object() {
|
||||
let mut s = session();
|
||||
let at = |s: &mut Session, kind: EntityKind, pick: [f64; 2]| -> Result<UcsFrame, String> {
|
||||
let h = s.add_entity(kind).unwrap();
|
||||
s.execute("ucs", &json!({"option": "world"})).unwrap();
|
||||
s.execute("ucs", &json!({"option": "object", "handle": h.hex(), "at": pick})).map_err(|e| e.to_string())?;
|
||||
Ok(s.ucs())
|
||||
};
|
||||
use cadcraft_engine::doc::{Arc, Circle, Face3d, Line, LwPolyline, Point};
|
||||
// A line: the nearer end; X along the line.
|
||||
let u = at(&mut s, EntityKind::Line(Line { a: Vec3::new(10.0, 10.0, 0.0), b: Vec3::new(10.0, 30.0, 0.0) }), [10.0, 29.0]).unwrap();
|
||||
assert!(near3(u.origin, Vec3::new(10.0, 30.0, 0.0)) && near3(u.x, Vec3::new(0.0, -1.0, 0.0)), "{u:?}");
|
||||
// A circle: the centre; X through the pick.
|
||||
let u = at(&mut s, EntityKind::Circle(Circle { center: Vec3::new(5.0, 5.0, 2.0), radius: 3.0 }), [5.0, 8.0]).unwrap();
|
||||
assert!(near3(u.origin, Vec3::new(5.0, 5.0, 2.0)) && near3(u.x, Vec3::new(0.0, 1.0, 0.0)), "{u:?}");
|
||||
// An arc: the centre; X through the nearer end.
|
||||
let u = at(&mut s, EntityKind::Arc(Arc { center: Vec3::ZERO, radius: 2.0, start: 0.0, end: std::f64::consts::FRAC_PI_2 }), [0.1, 2.0]).unwrap();
|
||||
assert!(near3(u.x, Vec3::new(0.0, 1.0, 0.0)), "{u:?}");
|
||||
// A polyline: its first vertex; X toward the next.
|
||||
let pl = LwPolyline {
|
||||
vertices: vec![
|
||||
cadcraft_engine::geom::PolyVertex::new(Vec2::new(1.0, 1.0)),
|
||||
cadcraft_engine::geom::PolyVertex::new(Vec2::new(1.0, 1.0)),
|
||||
cadcraft_engine::geom::PolyVertex::new(Vec2::new(-4.0, 1.0)),
|
||||
],
|
||||
closed: false,
|
||||
const_width: 0.0,
|
||||
elevation: 3.0,
|
||||
plinegen: false,
|
||||
};
|
||||
let u = at(&mut s, EntityKind::LwPolyline(pl), [0.0, 0.0]).unwrap();
|
||||
assert!(near3(u.origin, Vec3::new(1.0, 1.0, 3.0)) && near3(u.x, Vec3::new(-1.0, 0.0, 0.0)), "{u:?}");
|
||||
// Text (and blocks, by the same rule): the insertion point; X along its rotation.
|
||||
s.execute("ucs", &json!({"option": "world"})).unwrap();
|
||||
typed(&mut s, &["text 2,3 1 28.64788975654116 A", ""]);
|
||||
let th = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Text(_))).map(|e| e.handle).last().unwrap();
|
||||
s.execute("ucs", &json!({"option": "object", "handle": th.hex()})).unwrap();
|
||||
let u = s.ucs();
|
||||
assert!(near3(u.origin, Vec3::new(2.0, 3.0, 0.0)) && ang_eq(u.rotation(), 0.5), "{u:?}");
|
||||
// A point: there, the X axis kept.
|
||||
let u = at(&mut s, EntityKind::Point(Point { p: Vec3::new(4.0, 4.0, 0.0), angle: 0.0 }), [0.0, 0.0]).unwrap();
|
||||
assert!(near3(u.origin, Vec3::new(4.0, 4.0, 0.0)) && near3(u.x, Vec3::new(1.0, 0.0, 0.0)));
|
||||
// A flat 3D face works; a tilted one, an ellipse and a zero-length line don't.
|
||||
let flat = Face3d { corners: [Vec3::ZERO, Vec3::new(0.0, 5.0, 0.0), Vec3::new(-5.0, 5.0, 0.0), Vec3::new(-5.0, 0.0, 0.0)], hidden_edges: 0 };
|
||||
let u = at(&mut s, EntityKind::Face3d(flat), [0.0, 0.0]).unwrap();
|
||||
assert!(near3(u.x, Vec3::new(0.0, 1.0, 0.0)) && u.is_planar());
|
||||
let tilted = Face3d { corners: [Vec3::ZERO, Vec3::new(5.0, 0.0, 0.0), Vec3::new(5.0, 0.0, 5.0), Vec3::new(0.0, 0.0, 5.0)], hidden_edges: 0 };
|
||||
assert!(at(&mut s, EntityKind::Face3d(tilted), [0.0, 0.0]).unwrap_err().contains("not available yet"));
|
||||
let ell = cadcraft_engine::doc::Ellipse { center: Vec3::ZERO, major: Vec3::new(2.0, 0.0, 0.0), ratio: 0.5, start: 0.0, end: TAU };
|
||||
assert!(at(&mut s, EntityKind::Ellipse(ell), [0.0, 0.0]).is_err());
|
||||
assert!(at(&mut s, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(0.0, 0.0, 9.0) }), [0.0, 0.0]).is_err());
|
||||
assert!(s.ucs().is_world(), "a refused object leaves the UCS");
|
||||
// Interactively: a pick on the object.
|
||||
s.execute("line", &json!({"points": [[50, 50], [50, 80]]})).unwrap();
|
||||
typed(&mut s, &["ucs ob 50,79"]);
|
||||
assert!(near3(s.ucs().origin, Vec3::new(50.0, 80.0, 0.0)), "{:?}", s.ucs());
|
||||
let _ = s.cmdline("ucs ob 900,900");
|
||||
assert!(s.running.is_some() || logged(&s, "No object found"), "a miss asks again");
|
||||
s.cancel();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ucs_view_and_the_tilted_options() {
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
typed(&mut s, &["ucs v"]);
|
||||
let u = s.ucs();
|
||||
assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)) && near3(u.x, Vec3::new(1.0, 0.0, 0.0)), "square to the plan view, origin kept");
|
||||
for k in ["x", "y", "za", "f"] {
|
||||
s.cmdline(&format!("ucs {k}")).unwrap();
|
||||
assert!(logged(&s, "not available yet"), "{k}");
|
||||
assert!(s.running.is_some(), "{k}: still at the prompt");
|
||||
s.cancel();
|
||||
assert!(s.execute("ucs", &json!({"option": k})).unwrap_err().to_string().contains("not available yet"), "{k}");
|
||||
}
|
||||
}
|
||||
|
||||
/// UCS View on a twisted view: X runs along the screen's horizontal, not the world's.
|
||||
#[test]
|
||||
fn ucs_view_follows_the_view_twist() {
|
||||
let mut s = session();
|
||||
typed(&mut s, &["ucs 100,50 "]);
|
||||
// The drawing appears turned 90° counterclockwise, so the screen's X is the world's -Y.
|
||||
s.execute("dview", &json!({"twist": 90.0})).unwrap();
|
||||
typed(&mut s, &["ucs v"]);
|
||||
let u = s.ucs();
|
||||
assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)), "origin kept: {u:?}");
|
||||
assert!(near3(u.x, Vec3::new(0.0, -1.0, 0.0)) && near3(u.y, Vec3::new(1.0, 0.0, 0.0)), "{u:?}");
|
||||
// The JSON form gives the same frame; with no twist, the World axes.
|
||||
s.execute("dview", &json!({"twist": 30.0})).unwrap();
|
||||
s.execute("ucs", &json!({"option": "view"})).unwrap();
|
||||
let a = -30f64.to_radians();
|
||||
assert!(near3(s.ucs().x, Vec3::new(a.cos(), a.sin(), 0.0)), "{:?}", s.ucs());
|
||||
s.execute("dview", &json!({"twist": 0.0})).unwrap();
|
||||
s.execute("ucs", &json!({"option": "view"})).unwrap();
|
||||
assert!(near3(s.ucs().x, Vec3::new(1.0, 0.0, 0.0)) && near3(s.ucs().origin, Vec3::new(100.0, 50.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ucs_change_is_undone_like_an_edit() {
|
||||
let mut s = session();
|
||||
typed(&mut s, &["ucs 100,50 "]);
|
||||
typed(&mut s, &["ucs z 45"]);
|
||||
s.undo().unwrap();
|
||||
let u = s.ucs();
|
||||
assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)) && near3(u.x, Vec3::new(1.0, 0.0, 0.0)), "{u:?}");
|
||||
s.undo().unwrap();
|
||||
assert!(s.ucs().is_world());
|
||||
s.redo().unwrap();
|
||||
assert!(near3(s.ucs().origin, Vec3::new(100.0, 50.0, 0.0)));
|
||||
}
|
||||
|
||||
/// Undo restores UCS Previous's history with the UCS: undoing UCS Previous gives back the entry
|
||||
/// it used, and undoing a UCS change takes away the entry it added.
|
||||
#[test]
|
||||
fn undo_restores_the_ucs_previous_history() {
|
||||
let previous = |s: &mut Session| s.execute("ucs", &json!({"option": "previous"})).is_ok();
|
||||
let mut s = session();
|
||||
typed(&mut s, &["ucs z 30"]);
|
||||
assert!(previous(&mut s) && s.ucs().is_world());
|
||||
s.undo().unwrap();
|
||||
assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()), "undo of UCS Previous");
|
||||
// Redo (before any new command clears the redo stack) does UCS Previous again.
|
||||
assert!(s.redo().unwrap().is_some(), "UCS Previous is on the redo stack");
|
||||
assert!(s.ucs().is_world(), "redo of UCS Previous");
|
||||
s.undo().unwrap();
|
||||
assert!(previous(&mut s) && s.ucs().is_world(), "its history entry came back too");
|
||||
let mut s = session();
|
||||
typed(&mut s, &["ucs z 30", "ucs z 30"]);
|
||||
assert!(ang_eq(s.ucs().rotation(), 60f64.to_radians()));
|
||||
s.undo().unwrap();
|
||||
assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()));
|
||||
// The 30° the undone step remembered is gone: Previous goes straight to the World UCS.
|
||||
assert!(previous(&mut s) && s.ucs().is_world());
|
||||
assert!(!previous(&mut s), "nothing before the World UCS");
|
||||
}
|
||||
|
||||
/// A layout's UCS Previous history goes with the layout: it follows a rename, and a layout
|
||||
/// deleted and made again under the same name starts without one.
|
||||
#[test]
|
||||
fn a_layouts_ucs_history_follows_it_and_goes_with_it() {
|
||||
let previous = |s: &mut Session| s.execute("ucs", &json!({"option": "previous"})).is_ok();
|
||||
let set = |s: &mut Session, name: &str| s.execute("layout.set", &json!({"name": name})).unwrap();
|
||||
let mut s = session();
|
||||
s.execute("layout", &json!({"option": "new", "name": "A"})).unwrap();
|
||||
set(&mut s, "A");
|
||||
typed(&mut s, &["ucs z 30"]);
|
||||
set(&mut s, "Model");
|
||||
s.execute("layout", &json!({"option": "rename", "name": "A", "to": "B"})).unwrap();
|
||||
set(&mut s, "B");
|
||||
assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()));
|
||||
assert!(previous(&mut s) && s.ucs().is_world(), "the history followed the rename");
|
||||
typed(&mut s, &["ucs z 45"]);
|
||||
set(&mut s, "Model");
|
||||
s.execute("layout", &json!({"option": "delete", "name": "B"})).unwrap();
|
||||
s.execute("layout", &json!({"option": "new", "name": "B"})).unwrap();
|
||||
set(&mut s, "B");
|
||||
assert!(s.ucs().is_world() && !previous(&mut s), "a new layout B has none of the old B's history");
|
||||
// Model space's history is its own throughout.
|
||||
set(&mut s, "Model");
|
||||
assert!(!previous(&mut s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paper_space_has_its_own_ucs() {
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
let layout = s.doc().unwrap().layouts[0].name.clone();
|
||||
s.execute("layout.set", &json!({"name": layout})).unwrap();
|
||||
assert!(s.ucs().is_world(), "a layout starts in the World UCS");
|
||||
typed(&mut s, &["ucs z 30"]);
|
||||
assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()));
|
||||
assert!(s.doc().unwrap().layouts[0].ucs.is_some());
|
||||
// UCS Previous stays in its space.
|
||||
typed(&mut s, &["ucs p"]);
|
||||
assert!(s.ucs().is_world());
|
||||
typed(&mut s, &["ucs p"]);
|
||||
assert!(logged(&s, "There is no previous UCS."), "model space's history isn't paper space's");
|
||||
s.execute("layout.set", &json!({"name": "Model"})).unwrap();
|
||||
assert!(near3(s.ucs().x, Vec3::new(0.0, 1.0, 0.0)), "model space kept its own");
|
||||
let (m, _) = cadcraft_engine::ucs::current(s.doc().unwrap(), &Space::Model);
|
||||
assert!(near3(m.origin, Vec3::new(100.0, 50.0, 0.0)));
|
||||
}
|
||||
|
||||
// ---------------- typed input in the UCS ----------------
|
||||
|
||||
#[test]
|
||||
fn typed_points_are_read_in_the_ucs() {
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
// Absolute: from the UCS origin along its axes.
|
||||
typed(&mut s, &["line 10,0 20,0 "]);
|
||||
let (a, b) = last_line(&s);
|
||||
assert!(near(a, 100.0, 60.0) && near(b, 100.0, 70.0), "{a:?} {b:?}");
|
||||
// Relative Cartesian along the UCS axes; polar angles from the UCS X axis.
|
||||
typed(&mut s, &["line 0,0 @5,0 @0,5 @10<90 "]);
|
||||
let ls = lines(&s);
|
||||
let n = ls.len();
|
||||
assert!(near(ls[n - 3].1, 100.0, 55.0) && near(ls[n - 2].1, 95.0, 55.0) && near(ls[n - 1].1, 85.0, 55.0), "{ls:?}");
|
||||
// Absolute polar: from the UCS origin.
|
||||
typed(&mut s, &["line 0,0 10<0 "]);
|
||||
assert!(near(last_line(&s).1, 100.0, 60.0), "{:?}", last_line(&s));
|
||||
// `#` is absolute in the UCS; `*` and `@*` are world coordinates.
|
||||
typed(&mut s, &["line #1,2 *1,2 @*3,0 @*5<0 "]);
|
||||
let ls = lines(&s);
|
||||
let n = ls.len();
|
||||
assert!(near(ls[n - 3].0, 98.0, 51.0) && near(ls[n - 3].1, 1.0, 2.0) && near(ls[n - 2].1, 4.0, 2.0) && near(ls[n - 1].1, 9.0, 2.0), "{ls:?}");
|
||||
// A 3D point keeps working (Z is ignored as before).
|
||||
typed(&mut s, &["line 1,1,5 2,1,5 "]);
|
||||
let (a, _) = last_line(&s);
|
||||
assert!(near(a, 99.0, 51.0), "{a:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_world_ucs_reads_points_as_before() {
|
||||
let script = ["line 1,2 @3,4 @5<30 #7,8 *9,10 @*1,1 "];
|
||||
let mut a = session();
|
||||
typed(&mut a, &script);
|
||||
let mut b = session();
|
||||
typed(&mut b, &["ucs 100,50 ", "ucs z 33", "ucs w"]);
|
||||
typed(&mut b, &script);
|
||||
let (la, lb) = (lines(&a), lines(&b));
|
||||
assert_eq!(la.len(), lb.len());
|
||||
for (x, y) in la.iter().zip(&lb) {
|
||||
assert!(x.0.dist(y.0) < 1e-12 && x.1.dist(y.1) < 1e-12, "{x:?} vs {y:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directions_are_measured_from_the_ucs_x_axis() {
|
||||
let mut s = session();
|
||||
typed(&mut s, &["ucs z 30"]);
|
||||
// TEXT's rotation 0 lies along the UCS X axis.
|
||||
typed(&mut s, &["text 0,0 2 0 Hello", ""]);
|
||||
let rot = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.rotation) } else { None }).unwrap();
|
||||
assert!(ang_eq(rot, 30f64.to_radians()), "{rot}");
|
||||
// ANGBASE is measured from the UCS X axis too.
|
||||
cadcraft_engine::sysvars::set(&mut s, "ANGBASE", &json!(90)).unwrap();
|
||||
typed(&mut s, &["line 0,0 @10<0 "]);
|
||||
let (a, b) = last_line(&s);
|
||||
assert!(ang_eq((b - a).angle(), 120f64.to_radians()), "{:?}", (b - a).angle().to_degrees());
|
||||
// `<<` overrides ANGBASE but stays in the UCS.
|
||||
typed(&mut s, &["line 0,0 @10<<0 "]);
|
||||
let (a, b) = last_line(&s);
|
||||
assert!(ang_eq((b - a).angle(), 30f64.to_radians()));
|
||||
cadcraft_engine::sysvars::set(&mut s, "ANGBASE", &json!(0)).unwrap();
|
||||
// A rotation by an angle is a size, the same in any UCS.
|
||||
let h = s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap()["handles"][0].as_str().unwrap().to_string();
|
||||
typed(&mut s, &["rotate l 0,0 90"]);
|
||||
let l = s.doc().unwrap().model.iter().find(|e| e.handle.hex() == h).map(|e| e.kind.clone()).unwrap();
|
||||
let EntityKind::Line(l) = l else { panic!() };
|
||||
assert!(near(l.b.xy(), 0.0, 10.0), "{:?}", l.b);
|
||||
// JSON parameters stay in world coordinates.
|
||||
s.execute("line", &json!({"points": [[0, 0], [3, 0]]})).unwrap();
|
||||
assert!(near(last_line(&s).1, 3.0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coordinates_are_shown_in_the_ucs() {
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
// ID: the message in the UCS; the JSON result keeps world values beside it.
|
||||
let r = s.execute("id", &json!({"at": [100, 60]})).unwrap();
|
||||
assert!(r["message"].as_str().unwrap().starts_with("X = 10.0000 Y = 0.0000"), "{r}");
|
||||
assert_eq!((r["x"].as_f64(), r["y"].as_f64()), (Some(100.0), Some(60.0)));
|
||||
assert!((r["ucs"][0].as_f64().unwrap() - 10.0).abs() < 1e-9);
|
||||
typed(&mut s, &["id 3,4"]);
|
||||
assert!(logged(&s, "X = 3.0000 Y = 4.0000"), "{:?}", s.log.last());
|
||||
// DIST: the deltas and the angle in the UCS.
|
||||
let r = s.execute("dist", &json!({"p1": [100, 50], "p2": [100, 60]})).unwrap();
|
||||
let m = r["message"].as_str().unwrap();
|
||||
assert!(m.contains("Angle in XY Plane = 0") && m.contains("Delta X = 10.0000") && m.contains("Delta Y = 0.0000"), "{m}");
|
||||
// The helpers the status bar and dynamic input use.
|
||||
assert!(near(s.ucs_point(Vec2::new(100.0, 60.0)), 10.0, 0.0));
|
||||
assert!(ang_eq(s.ucs_angle(std::f64::consts::FRAC_PI_2), 0.0));
|
||||
}
|
||||
|
||||
// ---------------- variables, UCSICON, tilted UCSs ----------------
|
||||
|
||||
#[test]
|
||||
fn ucs_variables_are_read_only() {
|
||||
let mut s = session();
|
||||
for v in ["UCSNAME", "UCSORG", "UCSXDIR", "UCSYDIR", "WORLDUCS"] {
|
||||
assert!(cadcraft_engine::sysvars::set(&mut s, v, &json!(1)).is_err(), "{v}");
|
||||
}
|
||||
typed(&mut s, &["ucs 5,6 ", "ucs na s A"]);
|
||||
assert_eq!(var(&s, "UCSNAME"), json!("A"));
|
||||
assert!(near3(vec3(&var(&s, "UCSORG")), Vec3::new(5.0, 6.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ucsicon_options() {
|
||||
let mut s = session();
|
||||
assert_eq!(s.ucsicon_bits(), 3, "shown, at the origin");
|
||||
typed(&mut s, &["ucsicon off"]);
|
||||
assert_eq!(s.ucsicon_bits(), 2);
|
||||
typed(&mut s, &["ucsicon on", "ucsicon n"]);
|
||||
assert_eq!(s.ucsicon_bits(), 1);
|
||||
typed(&mut s, &["ucsicon or"]);
|
||||
assert_eq!(s.ucsicon_bits(), 3);
|
||||
s.cmdline("ucsicon s").unwrap();
|
||||
assert!(logged(&s, "not available yet"));
|
||||
s.cancel();
|
||||
let r = s.execute("ucsicon", &json!({"on": false, "origin": false})).unwrap();
|
||||
assert_eq!(r, json!({"on": false, "origin": false}));
|
||||
assert_eq!(var(&s, "UCSICON"), json!(0));
|
||||
assert!(s.execute("ucsicon", &json!({"on": "yes"})).is_err());
|
||||
assert!(cadcraft_engine::sysvars::set(&mut s, "UCSICON", &json!(9)).is_err());
|
||||
}
|
||||
|
||||
/// Asking UCSICON (or setting what is already set) leaves the drawing unmodified.
|
||||
#[test]
|
||||
fn ucsicon_query_does_not_modify_the_drawing() {
|
||||
let mut s = session();
|
||||
assert!(!s.state().unwrap().is_dirty());
|
||||
assert_eq!(s.execute("ucsicon", &json!({})).unwrap(), json!({"on": true, "origin": true}));
|
||||
s.execute("ucsicon", &json!({"on": true})).unwrap();
|
||||
assert!(!s.state().unwrap().is_dirty(), "nothing changed");
|
||||
s.execute("ucsicon", &json!({"on": false})).unwrap();
|
||||
assert!(s.state().unwrap().is_dirty(), "a real change is unsaved");
|
||||
}
|
||||
|
||||
/// UCS Previous with no earlier UCS changes nothing, so the drawing stays unmodified.
|
||||
#[test]
|
||||
fn ucs_previous_without_history_does_not_modify_the_drawing() {
|
||||
let mut s = session();
|
||||
assert!(s.execute("ucs", &json!({"option": "previous"})).is_err());
|
||||
typed(&mut s, &["ucs p"]);
|
||||
assert!(logged(&s, "There is no previous UCS."));
|
||||
assert!(!s.state().unwrap().is_dirty());
|
||||
}
|
||||
|
||||
/// UCSICON is its own undo step: undoing it brings the icon back, and an undo never undoes the
|
||||
/// edit before it while leaving the icon setting behind (or the other way round).
|
||||
#[test]
|
||||
fn ucsicon_is_undone_on_its_own() {
|
||||
let mut s = session();
|
||||
let lines = |s: &Session| s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
typed(&mut s, &["ucsicon off"]);
|
||||
assert_eq!(s.ucsicon_bits() & 1, 0);
|
||||
s.undo().unwrap();
|
||||
assert_eq!(s.ucsicon_bits() & 1, 1, "undo takes back UCSICON OFF");
|
||||
assert_eq!(lines(&s), 1, "and leaves the line drawn before it");
|
||||
s.undo().unwrap();
|
||||
assert_eq!(lines(&s), 0);
|
||||
assert_eq!(s.ucsicon_bits() & 1, 1);
|
||||
s.redo().unwrap();
|
||||
s.redo().unwrap();
|
||||
assert_eq!((lines(&s), s.ucsicon_bits() & 1), (1, 0), "redo brings both back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tilted_ucs_from_a_file_is_kept_and_input_stays_in_the_world_ucs() {
|
||||
let mut s = session();
|
||||
{
|
||||
let h = &mut s.doc_mut().unwrap().header;
|
||||
h.set("UCSORG", HVal::Point(Vec3::new(10.0, 0.0, 0.0)));
|
||||
h.set("UCSXDIR", HVal::Point(Vec3::new(1.0, 0.0, 0.0)));
|
||||
h.set("UCSYDIR", HVal::Point(Vec3::new(0.0, 0.0, 1.0)));
|
||||
}
|
||||
assert!(!s.ucs().is_planar());
|
||||
assert_eq!(s.input_ucs(), UcsFrame::WORLD);
|
||||
typed(&mut s, &["line 1,1 2,2 "]);
|
||||
assert!(near(last_line(&s).0, 1.0, 1.0), "read in the World UCS");
|
||||
assert!(logged(&s, "tilted out of the XY plane"));
|
||||
let n = s.log.iter().filter(|l| l.contains("tilted out of the XY plane")).count();
|
||||
typed(&mut s, &["line 3,3 4,4 "]);
|
||||
assert_eq!(s.log.iter().filter(|l| l.contains("tilted out of the XY plane")).count(), n, "told once");
|
||||
// The UCS itself is untouched until the user sets another.
|
||||
assert!(near3(vec3(&var(&s, "UCSYDIR")), Vec3::new(0.0, 0.0, 1.0)));
|
||||
// A tilted named UCS isn't restored.
|
||||
s.doc_mut().unwrap().ucss.push(cadcraft_engine::doc::Ucs {
|
||||
name: "FRONT".into(),
|
||||
origin: Vec3::ZERO,
|
||||
x_axis: Vec3::new(1.0, 0.0, 0.0),
|
||||
y_axis: Vec3::new(0.0, 0.0, 1.0),
|
||||
});
|
||||
s.execute("ucs", &json!({"option": "world"})).unwrap();
|
||||
assert!(s.execute("ucs", &json!({"option": "named", "action": "restore", "name": "FRONT"})).unwrap_err().to_string().contains("tilted"));
|
||||
assert!(s.ucs().is_world());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_ucs_input_never_panics() {
|
||||
let mut s = session();
|
||||
let bad: Vec<Value> = vec![
|
||||
json!({"option": "origin", "origin": [f64::MAX, -f64::MAX, f64::MAX]}),
|
||||
json!({"option": "origin", "origin": ["a", 1]}),
|
||||
json!({"option": "origin", "origin": [1]}),
|
||||
json!({"option": "origin", "origin": [0, 0], "xPoint": [1e308, 1e308], "xyPoint": [-1e308, 1e308]}),
|
||||
json!({"option": "origin", "origin": [0, 0], "xyPoint": [0, 1]}),
|
||||
json!({"option": "z", "angle": 1e308}),
|
||||
json!({"option": "z", "angle": "ninety"}),
|
||||
json!({"option": "object"}),
|
||||
json!({"option": "object", "handle": "ZZZZ"}),
|
||||
json!({"option": "object", "handle": "FFFFFF"}),
|
||||
json!({"option": "named", "action": "explode", "name": "A"}),
|
||||
json!({"option": "named", "action": "delete", "name": "*,?,[,]"}),
|
||||
json!({"option": "warp"}),
|
||||
json!({"option": 7}),
|
||||
json!(null),
|
||||
json!([1, 2, 3]),
|
||||
];
|
||||
for p in &bad {
|
||||
let _ = s.execute("ucs", p);
|
||||
let u = s.ucs();
|
||||
assert!(u.origin.is_finite() && u.x.is_finite() && u.y.is_finite(), "{p}: {u:?}");
|
||||
}
|
||||
for t in ["ucs 1e400,0", "ucs nan,nan", "ucs 0,0 0,0", "ucs z 1e999", "ucs na s \u{0}", "ucs na r ", "ucs ob", "ucs na ? [", "ucsicon blah"] {
|
||||
let _ = s.cmdline(t);
|
||||
s.cancel();
|
||||
}
|
||||
// Broken header values read as the World UCS.
|
||||
for v in [HVal::Point(Vec3::new(f64::NAN, 0.0, 0.0)), HVal::Point(Vec3::ZERO), HVal::Str("x".into()), HVal::Int(3)] {
|
||||
s.doc_mut().unwrap().header.set("UCSXDIR", v);
|
||||
let u = s.ucs();
|
||||
assert!(u.origin.is_finite() && u.x.is_finite());
|
||||
typed(&mut s, &["line 0,0 1,0 "]);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- review fixes ----------------
|
||||
|
||||
/// A deferred TAN first point followed by a typed `@d<a`: the angle is read in the UCS (and with
|
||||
/// ANGBASE), like every other typed direction.
|
||||
#[test]
|
||||
fn deferred_line_polar_follows_the_ucs() {
|
||||
use cadcraft_engine::Input;
|
||||
use cadcraft_engine::snap::{Deferred, SnapCurve, mode};
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
s.start("line").unwrap();
|
||||
let d = Deferred { mode: mode::TAN, curve: SnapCurve::Circle { center: Vec2::new(500.0, 500.0), radius: 5.0 }, at: Vec2::new(505.0, 500.0) };
|
||||
s.input(Input::Deferred(d)).unwrap();
|
||||
// UCS angle 0 is world +Y: the tangent to the circle in that direction, then 10 along it.
|
||||
s.cmdline("@10<0").unwrap();
|
||||
s.cancel();
|
||||
let (a, b) = last_line(&s);
|
||||
assert!((b - a).len() > 9.999 && (b.x - a.x).abs() < 1e-9 && (b.y - a.y - 10.0).abs() < 1e-9, "{a:?} {b:?}");
|
||||
}
|
||||
|
||||
/// Deleting a named UCS clears its name wherever it is the current UCS: model space and every
|
||||
/// layout, not only the space deleted from.
|
||||
#[test]
|
||||
fn deleting_a_named_ucs_clears_it_in_every_space() {
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
s.execute("ucs", &json!({"option": "named", "action": "save", "name": "SITE"})).unwrap();
|
||||
let layout = s.doc().unwrap().layouts[0].name.clone();
|
||||
s.execute("layout.set", &json!({"name": layout})).unwrap();
|
||||
s.execute("ucs", &json!({"option": "named", "action": "restore", "name": "SITE"})).unwrap();
|
||||
assert_eq!(s.ucs_named().1, "SITE");
|
||||
// Delete from paper space: model space is still named SITE.
|
||||
s.execute("ucs", &json!({"option": "named", "action": "delete", "name": "SITE"})).unwrap();
|
||||
assert_eq!(s.ucs_named().1, "", "the current space");
|
||||
assert_eq!(s.doc().unwrap().header.str("UCSNAME", ""), "", "model space");
|
||||
assert!(s.doc().unwrap().layouts.iter().all(|l| l.ucs.as_ref().is_none_or(|u| u.name.is_empty())), "every layout");
|
||||
// The axes stay.
|
||||
s.execute("layout.set", &json!({"name": "Model"})).unwrap();
|
||||
assert!(near3(s.ucs().x, Vec3::new(0.0, 1.0, 0.0)));
|
||||
}
|
||||
|
||||
/// The origin prompt offers the origin in the UCS's own terms (0,0,0), so Enter, or the default
|
||||
/// typed back, keeps the origin.
|
||||
#[test]
|
||||
fn pressing_enter_at_the_origin_prompt_keeps_the_origin() {
|
||||
let mut s = session();
|
||||
s.execute("ucs", &json!({"option": "origin", "origin": [100, 50]})).unwrap();
|
||||
s.execute("ucs", &json!({"option": "z", "angle": 30})).unwrap();
|
||||
let before = s.ucs();
|
||||
s.start("ucs.origin").unwrap();
|
||||
let shown = s.current_prompt().and_then(|p| p.default).unwrap_or_default();
|
||||
s.cmdline(&shown).unwrap();
|
||||
assert!(near3(s.ucs().origin, before.origin), "typing the default {shown:?} back: {:?}", s.ucs().origin);
|
||||
s.start("ucs.origin").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(near3(s.ucs().origin, before.origin));
|
||||
}
|
||||
|
||||
/// DIST's JSON keeps world values at the top level, as ID does, and has the numbers its message
|
||||
/// shows (angle and deltas in the current UCS) under `ucs`.
|
||||
#[test]
|
||||
fn dist_json_keeps_world_values_and_adds_ucs() {
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
// Points are given in the world: UCS (0,0) and (10,0).
|
||||
let r = s.execute("dist", &json!({"p1": [100, 50], "p2": [100, 60]})).unwrap();
|
||||
let f = |v: &Value, k: &str| v[k].as_f64().unwrap();
|
||||
assert!(f(&r, "dx").abs() < 1e-9 && (f(&r, "dy") - 10.0).abs() < 1e-9 && (f(&r, "angle") - 90.0).abs() < 1e-9, "{r}");
|
||||
let u = &r["ucs"];
|
||||
assert!((f(u, "dx") - 10.0).abs() < 1e-9 && f(u, "dy").abs() < 1e-9 && f(u, "angle").abs() < 1e-9, "{r}");
|
||||
assert!(r["message"].as_str().unwrap().contains("Delta X = 10"), "{r}");
|
||||
assert!(r.get("world").is_none(), "{r}");
|
||||
}
|
||||
|
||||
/// Deleting the current named UCS leaves no trace of its name: UCS Previous goes back to the axes
|
||||
/// before it, unnamed, and does not bring the deleted name back.
|
||||
#[test]
|
||||
fn ucs_previous_after_deleting_the_current_named_ucs() {
|
||||
let mut s = session();
|
||||
typed(&mut s, &["ucs na s SITE"]);
|
||||
turned(&mut s);
|
||||
typed(&mut s, &["ucs na r SITE"]);
|
||||
typed(&mut s, &["ucs na d SITE"]);
|
||||
assert_eq!(s.ucs_named().1, "");
|
||||
assert!(s.doc().unwrap().ucs_previous.iter().all(|u| u.name.is_empty()), "{:?}", s.doc().unwrap().ucs_previous);
|
||||
typed(&mut s, &["ucs p"]);
|
||||
assert_eq!(s.ucs_named().1, "", "the deleted name does not come back");
|
||||
assert!(near3(s.ucs().x, Vec3::new(0.0, 1.0, 0.0)), "back to the axes before SITE: {:?}", s.ucs());
|
||||
assert_eq!(s.doc().unwrap().header.str("UCSNAME", ""), "");
|
||||
}
|
||||
|
||||
/// Enter at the 3 Point origin prompt keeps the origin and asks for the X axis point.
|
||||
#[test]
|
||||
fn three_point_ucs_enter_keeps_the_origin() {
|
||||
let mut s = session();
|
||||
turned(&mut s);
|
||||
let before = s.ucs();
|
||||
s.start("ucs.3point").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.current_prompt().is_some_and(|p| p.message.contains("X-axis")), "{:?}", s.current_prompt().map(|p| p.message));
|
||||
// A point 10 along the UCS X axis, then Enter for the XY point: the origin is kept.
|
||||
s.cmdline("10,0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(near3(s.ucs().origin, before.origin) && near3(s.ucs().x, before.x), "{:?}", s.ucs());
|
||||
}
|
||||
|
||||
/// With the current UCS tilted, points are read in the World UCS: the origin prompt shows the
|
||||
/// origin there, so Enter, or the default typed back, keeps it.
|
||||
#[test]
|
||||
fn tilted_ucs_origin_default_keeps_the_origin() {
|
||||
let mut s = session();
|
||||
{
|
||||
let h = &mut s.doc_mut().unwrap().header;
|
||||
h.set("UCSORG", HVal::Point(Vec3::new(50.0, 20.0, 7.0)));
|
||||
h.set("UCSXDIR", HVal::Point(Vec3::new(1.0, 0.0, 0.0)));
|
||||
h.set("UCSYDIR", HVal::Point(Vec3::new(0.0, 0.0, 1.0)));
|
||||
}
|
||||
let before = s.ucs().origin;
|
||||
s.start("ucs.origin").unwrap();
|
||||
let shown = s.current_prompt().and_then(|p| p.default).unwrap_or_default();
|
||||
assert_eq!(shown, "50,20,7");
|
||||
s.cmdline(&shown).unwrap();
|
||||
assert!(near3(s.ucs().origin, before), "typed {shown:?}: {:?}", s.ucs().origin);
|
||||
s.start("ucs.origin").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(near3(s.ucs().origin, before));
|
||||
}
|
||||
|
||||
/// The origin prompt's default is a clean number: no negative zero, no 16-digit noise.
|
||||
#[test]
|
||||
fn origin_default_prints_no_negative_zero() {
|
||||
let mut s = session();
|
||||
s.execute("ucs", &json!({"option": "origin", "origin": [100, 50]})).unwrap();
|
||||
s.execute("ucs", &json!({"option": "z", "angle": 200})).unwrap();
|
||||
s.start("ucs.origin").unwrap();
|
||||
let shown = s.current_prompt().and_then(|p| p.default).unwrap_or_default();
|
||||
assert_eq!(shown, "0,0,0");
|
||||
}
|
||||
|
||||
/// Deleting the named World UCS of a layout leaves the layout with no UCS, as setting the World
|
||||
/// UCS does.
|
||||
#[test]
|
||||
fn deleting_a_named_world_ucs_in_a_layout_leaves_no_ucs() {
|
||||
let mut s = session();
|
||||
let layout = s.doc().unwrap().layouts[0].name.clone();
|
||||
s.execute("layout.set", &json!({"name": layout})).unwrap();
|
||||
s.execute("ucs", &json!({"option": "named", "action": "save", "name": "HOME"})).unwrap();
|
||||
s.execute("ucs", &json!({"option": "named", "action": "restore", "name": "HOME"})).unwrap();
|
||||
assert_eq!(s.ucs_named().1, "HOME");
|
||||
s.execute("ucs", &json!({"option": "named", "action": "delete", "name": "HOME"})).unwrap();
|
||||
assert!(s.doc().unwrap().layouts.iter().all(|l| l.ucs.is_none()), "{:?}", s.doc().unwrap().layouts.iter().map(|l| &l.ucs).collect::<Vec<_>>());
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
//! The drafting aids follow the current UCS (#1106): ortho and direct distance entry along its
|
||||
//! axes, grid snap in its XY plane (SNAPBASE from its origin, SNAPANG from its X axis), polar and
|
||||
//! object snap tracking measured from its X axis, isometric axes turned with it, and DIMLINEAR's
|
||||
//! horizontal and vertical along its axes. In the World UCS everything is as before.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{DimKind, EntityKind};
|
||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||
use cadcraft_engine::snap::tracking::{CursorQuery, TrackConfig};
|
||||
use cadcraft_engine::snap::{self, iso};
|
||||
use serde_json::json;
|
||||
|
||||
const DEG: f64 = std::f64::consts::PI / 180.0;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_drawing(false);
|
||||
// Nothing running that would snap the cursor elsewhere.
|
||||
s.settings.osmode = 0;
|
||||
s.settings.otrack = false;
|
||||
s.settings.polarmode = false;
|
||||
s.settings.orthomode = false;
|
||||
s.settings.snapmode = false;
|
||||
s
|
||||
}
|
||||
|
||||
/// The UCS at (5, 5) turned `deg` degrees.
|
||||
fn turned(s: &mut Session, deg: f64) {
|
||||
s.execute("ucs", &json!({"option": "origin", "origin": [5, 5]})).unwrap();
|
||||
s.execute("ucs", &json!({"option": "z", "angle": deg})).unwrap();
|
||||
}
|
||||
|
||||
fn query(base: Option<Vec2>) -> CursorQuery {
|
||||
CursorQuery { base, deferred: false, corner: false, aperture: 0.01, tol: 1.0, now: 0.0, shift: false }
|
||||
}
|
||||
|
||||
fn near(a: Vec2, x: f64, y: f64) -> bool {
|
||||
a.dist(Vec2::new(x, y)) < 1e-9
|
||||
}
|
||||
|
||||
fn ang_eq(a: f64, b: f64) -> bool {
|
||||
let d = (a - b).rem_euclid(std::f64::consts::TAU);
|
||||
d < 1e-9 || std::f64::consts::TAU - d < 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ortho_follows_the_ucs_axes() {
|
||||
let mut s = session();
|
||||
s.settings.orthomode = true;
|
||||
// World UCS: horizontal.
|
||||
let p = s.snap_cursor(Vec2::new(10.0, 4.0), &query(Some(Vec2::ZERO))).point;
|
||||
assert!(near(p, 10.0, 0.0), "{p:?}");
|
||||
// Turned 30°: along the UCS X axis, as far as the cursor reaches along it.
|
||||
turned(&mut s, 30.0);
|
||||
let p = s.snap_cursor(Vec2::new(10.0, 4.0), &query(Some(Vec2::ZERO))).point;
|
||||
let along = 10.0 * (30.0 * DEG).cos() + 4.0 * (30.0 * DEG).sin();
|
||||
assert!(near(p, along * (30.0 * DEG).cos(), along * (30.0 * DEG).sin()), "{p:?}");
|
||||
// And along its Y axis when the cursor is nearer that.
|
||||
let p = s.snap_cursor(Vec2::new(-4.0, 9.0), &query(Some(Vec2::ZERO))).point;
|
||||
let d = p - Vec2::ZERO;
|
||||
assert!(ang_eq(d.angle(), 120.0 * DEG) || ang_eq(d.angle(), 300.0 * DEG), "{:?}", d.angle() / DEG);
|
||||
}
|
||||
|
||||
/// Holding Shift turns ortho on (or off) while it is held, along the current UCS's axes too.
|
||||
#[test]
|
||||
fn shift_ortho_follows_the_ucs_axes() {
|
||||
let mut s = session();
|
||||
s.settings.orthomode = false;
|
||||
turned(&mut s, 30.0);
|
||||
let shifted = CursorQuery { shift: true, ..query(Some(Vec2::ZERO)) };
|
||||
let p = s.snap_cursor(Vec2::new(10.0, 4.0), &shifted).point;
|
||||
let along = 10.0 * (30.0 * DEG).cos() + 4.0 * (30.0 * DEG).sin();
|
||||
assert!(near(p, along * (30.0 * DEG).cos(), along * (30.0 * DEG).sin()), "Shift: ortho on, along the UCS X axis: {p:?}");
|
||||
// Without Shift the cursor goes where it is; with ORTHOMODE on, Shift turns it off.
|
||||
assert!(near(s.snap_cursor(Vec2::new(10.0, 4.0), &query(Some(Vec2::ZERO))).point, 10.0, 4.0));
|
||||
s.settings.orthomode = true;
|
||||
assert!(near(s.snap_cursor(Vec2::new(10.0, 4.0), &shifted).point, 10.0, 4.0), "Shift: ortho off");
|
||||
assert!(s.settings.orthomode, "ORTHOMODE itself is unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_distance_with_ortho_goes_along_the_ucs_axis() {
|
||||
let mut s = session();
|
||||
turned(&mut s, 30.0);
|
||||
s.settings.orthomode = true;
|
||||
s.cmdline("line 0,0").unwrap();
|
||||
// The cursor a little off the UCS X axis: 10 along it.
|
||||
s.cursor = s.input_ucs().to_wcs(Vec2::new(8.0, 1.0));
|
||||
s.cmdline("10").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
let l = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).unwrap();
|
||||
let u = s.input_ucs();
|
||||
assert!(l.a.xy().dist(u.to_wcs(Vec2::ZERO)) < 1e-9 && l.b.xy().dist(u.to_wcs(Vec2::new(10.0, 0.0))) < 1e-9, "{l:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_snap_lies_in_the_ucs() {
|
||||
let mut s = session();
|
||||
cadcraft_engine::sysvars::set(&mut s, "SNAPUNIT", &json!([1, 1])).unwrap();
|
||||
s.settings.snapmode = true;
|
||||
let p = s.snap_cursor(Vec2::new(5.3, 6.8), &query(None)).point;
|
||||
assert!(near(p, 5.0, 7.0), "World: {p:?}");
|
||||
// Turned 90° at (5, 5): the lattice through (5, 5) along the turned axes; with SNAPBASE and
|
||||
// SNAPANG measured in the UCS.
|
||||
turned(&mut s, 90.0);
|
||||
let p = s.snap_cursor(Vec2::new(5.3, 6.8), &query(None)).point;
|
||||
assert!(near(p, 5.0, 7.0), "{p:?}");
|
||||
s.execute("ucs", &json!({"option": "z", "angle": -45})).unwrap();
|
||||
let u = s.input_ucs();
|
||||
let p = s.snap_cursor(u.to_wcs(Vec2::new(2.2, -0.9)), &query(None)).point;
|
||||
assert!(u.to_ucs(p).dist(Vec2::new(2.0, -1.0)) < 1e-9, "UCS {:?}", u.to_ucs(p));
|
||||
let d = s.doc().unwrap();
|
||||
let (o, a) = snap::grid_frame_in(d, &s.space());
|
||||
assert!(near(o, 5.0, 5.0) && ang_eq(a, 45.0 * DEG), "{o:?} {}", a / DEG);
|
||||
// SNAPBASE is a UCS point, SNAPANG an angle from its X axis.
|
||||
cadcraft_engine::sysvars::set(&mut s, "SNAPBASE", &json!([1, 0])).unwrap_or(());
|
||||
s.doc_mut().unwrap().header.set("SNAPBASE", cadcraft_engine::doc::HVal::Point(Vec3::new(1.0, 0.0, 0.0)));
|
||||
s.doc_mut().unwrap().header.set_f64("SNAPANG", 10.0);
|
||||
let (o, a) = snap::grid_frame_in(s.doc().unwrap(), &s.space());
|
||||
assert!(o.dist(u.to_wcs(Vec2::new(1.0, 0.0))) < 1e-9 && ang_eq(a, 55.0 * DEG), "{o:?} {}", a / DEG);
|
||||
// The stored values are unchanged (they are UCS values).
|
||||
assert_eq!(snap::grid_frame(s.doc().unwrap()), (Vec2::new(1.0, 0.0), 10.0 * DEG));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polar_tracking_is_measured_from_the_ucs_x_axis() {
|
||||
let mut s = session();
|
||||
s.settings.polarmode = true;
|
||||
s.settings.polarang = 90.0 * DEG;
|
||||
let base = Vec2::ZERO;
|
||||
let at32 = Vec2::from_angle(32.0 * DEG) * 10.0;
|
||||
// World UCS, 90° steps: 32° is on no path.
|
||||
assert!(s.snap_cursor(at32, &query(Some(base))).track.is_none());
|
||||
// Turned 30°: the path at 30° catches it.
|
||||
turned(&mut s, 30.0);
|
||||
let snapped = s.snap_cursor(at32, &query(Some(base)));
|
||||
let t = snapped.track.expect("on the 30° path");
|
||||
let d = t.point - base;
|
||||
assert!(ang_eq(d.angle(), 30.0 * DEG), "{}", d.angle() / DEG);
|
||||
// The configuration itself: polar angles and the orthogonal tracking paths turn with the UCS.
|
||||
let st = s.drafting_settings();
|
||||
let cfg = TrackConfig::new(&st, 0.0);
|
||||
for want in [30.0, 120.0, 210.0, 300.0] {
|
||||
assert!(
|
||||
cfg.polar_angles.iter().any(|a| ang_eq(*a, want * DEG)),
|
||||
"{want}: {:?}",
|
||||
cfg.polar_angles.iter().map(|a| a / DEG).collect::<Vec<_>>()
|
||||
);
|
||||
assert!(cfg.track_angles.iter().any(|a| ang_eq(*a, want * DEG)), "{want}");
|
||||
}
|
||||
// ANGBASE adds to it.
|
||||
let cfg = TrackConfig::new(&st, 15.0 * DEG);
|
||||
assert!(cfg.polar_angles.iter().any(|a| ang_eq(*a, 45.0 * DEG)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_world_ucs_drafts_as_before() {
|
||||
let s = session();
|
||||
let st = s.drafting_settings();
|
||||
assert_eq!(st.ucs_angle, 0.0);
|
||||
for (b, p) in [(Vec2::ZERO, Vec2::new(10.0, 4.0)), (Vec2::new(3.0, 3.0), Vec2::new(1.0, 20.0)), (Vec2::ZERO, Vec2::new(-5.0, 5.0))] {
|
||||
assert_eq!(snap::ortho_at(b, p, 0.0), snap::ortho(b, p));
|
||||
assert_eq!(iso::constrain(&st, b, p), snap::ortho(b, p));
|
||||
}
|
||||
let cfg = TrackConfig::new(&st, 0.0);
|
||||
for want in [0.0, 90.0, 180.0, 270.0] {
|
||||
assert!(cfg.track_angles.iter().any(|a| ang_eq(*a, want * DEG)));
|
||||
}
|
||||
assert_eq!(snap::grid_frame_in(s.doc().unwrap(), &s.space()), snap::grid_frame(s.doc().unwrap()));
|
||||
// Hostile angles fall back to the world axes.
|
||||
assert_eq!(snap::ortho_at(Vec2::ZERO, Vec2::new(3.0, 1.0), f64::NAN), Vec2::new(3.0, 0.0));
|
||||
assert_eq!(snap::ortho_at(Vec2::ZERO, Vec2::new(3.0, 1.0), f64::INFINITY), Vec2::new(3.0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isometric_axes_turn_with_the_ucs() {
|
||||
let mut s = session();
|
||||
s.settings.isodraft = true;
|
||||
let st0 = s.drafting_settings();
|
||||
turned(&mut s, 40.0);
|
||||
let st = s.drafting_settings();
|
||||
for v in [Vec2::new(10.0, 3.0), Vec2::new(-2.0, 9.0), Vec2::new(4.0, -7.0)] {
|
||||
let base = Vec2::new(1.0, 2.0);
|
||||
let r = iso::constrain(&st, base, base + v.rotate(40.0 * DEG)) - base;
|
||||
let want = iso::constrain(&st0, Vec2::ZERO, v).rotate(40.0 * DEG);
|
||||
assert!(r.dist(want) < 1e-9, "{v:?}: {r:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn last_dim_rotation(s: &Session) -> f64 {
|
||||
let d = s.doc().unwrap();
|
||||
let r = d.model.iter().filter_map(|e| if let EntityKind::Dimension(dm) = &e.kind { Some(dm.kind) } else { None }).last();
|
||||
match r {
|
||||
Some(DimKind::Linear { rotation }) => rotation,
|
||||
other => panic!("not a linear dimension: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimlinear_horizontal_and_vertical_follow_the_ucs() {
|
||||
let mut s = session();
|
||||
turned(&mut s, 30.0);
|
||||
// Placed above the points (in the UCS): horizontal along the UCS X axis.
|
||||
s.cmdline("dimlinear 0,0 10,0 5,5").unwrap();
|
||||
assert!(ang_eq(last_dim_rotation(&s), 30.0 * DEG), "{}", last_dim_rotation(&s) / DEG);
|
||||
// Beside them: vertical along its Y axis.
|
||||
s.cmdline("dimlinear 0,0 0,10 5,5").unwrap();
|
||||
assert!(ang_eq(last_dim_rotation(&s), 120.0 * DEG), "{}", last_dim_rotation(&s) / DEG);
|
||||
// The keywords.
|
||||
s.cmdline("dimlinear 0,0 10,10 h 5,20").unwrap();
|
||||
assert!(ang_eq(last_dim_rotation(&s), 30.0 * DEG));
|
||||
s.cmdline("dimlinear 0,0 10,10 v 20,5").unwrap();
|
||||
assert!(ang_eq(last_dim_rotation(&s), 120.0 * DEG));
|
||||
// JSON stays in world coordinates: horizontal is world horizontal.
|
||||
s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 5]})).unwrap();
|
||||
assert!(ang_eq(last_dim_rotation(&s), 0.0));
|
||||
// World UCS: as before.
|
||||
s.execute("ucs", &json!({"option": "world"})).unwrap();
|
||||
s.cmdline("dimlinear 0,0 10,0 5,5").unwrap();
|
||||
assert!(ang_eq(last_dim_rotation(&s), 0.0));
|
||||
s.cmdline("dimlinear 0,0 0,10 5,5").unwrap();
|
||||
assert!(ang_eq(last_dim_rotation(&s), 90.0 * DEG));
|
||||
}
|
||||
|
||||
/// A point filter takes its coordinates in the UCS: `.X` of one point and `YZ` of another make
|
||||
/// the point with the first's UCS X and the second's UCS Y.
|
||||
#[test]
|
||||
fn point_filters_and_ortho_follow_the_ucs() {
|
||||
let mut s = session();
|
||||
turned(&mut s, 90.0);
|
||||
s.cmdline("line 0,0").unwrap();
|
||||
s.cmdline(".x").unwrap();
|
||||
s.cmdline("3,4").unwrap();
|
||||
s.cmdline("7,9").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
let l = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).unwrap();
|
||||
// UCS (3, 9): the UCS at (5, 5) turned 90° puts it at world (5 - 9, 5 + 3).
|
||||
assert!(near(l.b.xy(), -4.0, 8.0), "{l:?}");
|
||||
}
|
||||
@@ -35,6 +35,40 @@ pub(crate) const PLOT_STYLE_NAMES_KEY: &str = "ACAD_PLOTSTYLENAME";
|
||||
pub(crate) const HANDSEED_KEY: &str = "CADCRAFT_HANDSEED";
|
||||
/// Named-object-dictionary key of the XRECORD holding the current multileader style.
|
||||
pub(crate) const MLEADER_STYLE_KEY: &str = "CADCRAFT_MLEADERSTYLE";
|
||||
/// Named-object-dictionary key of the XRECORD holding model space's current UCS name ($UCSNAME,
|
||||
/// which the DWG bridge drops).
|
||||
pub(crate) const UCS_NAME_KEY: &str = "CADCRAFT_UCSNAME";
|
||||
|
||||
/// Whether the UCS at `origin` with axes `x`, `y` is exactly the named UCS `u` (to rounding):
|
||||
/// only then is the current UCS still that named one, read or written. The origin may differ by
|
||||
/// printing round-off only: we write the shortest exact form and other programs 15–16
|
||||
/// significant digits (half a unit in the 15th is 5e-16 of the value), so 1e-14 of the value,
|
||||
/// plus 1e-9 near the World origin, covers it while even 1e12 away a 0.5 move is a different UCS.
|
||||
pub(crate) fn is_named_frame(u: &cadcraft_doc::Ucs, origin: cadcraft_geom::Vec3, x: cadcraft_geom::Vec3, y: cadcraft_geom::Vec3) -> bool {
|
||||
(origin - u.origin).len() <= 1e-9 + 1e-14 * origin.len() && (x - u.x_axis).len() <= 1e-9 && (y - u.y_axis).len() <= 1e-9
|
||||
}
|
||||
|
||||
/// The UCS table record named `name` whose frame the UCS at `origin`, `x`, `y` still is: the only
|
||||
/// case in which a current UCS (model space's or a layout's, read or written) keeps that name.
|
||||
pub(crate) fn named_ucs<'a>(
|
||||
ucss: &'a [cadcraft_doc::Ucs],
|
||||
name: &str,
|
||||
origin: cadcraft_geom::Vec3,
|
||||
x: cadcraft_geom::Vec3,
|
||||
y: cadcraft_geom::Vec3,
|
||||
) -> Option<&'a cadcraft_doc::Ucs> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
ucss.iter().find(|u| u.name.eq_ignore_ascii_case(name) && is_named_frame(u, origin, x, y))
|
||||
}
|
||||
|
||||
/// Whether `x` and `y` can be a UCS's axes: finite, not zero and not along each other (relative
|
||||
/// to their lengths, so short but square axes are fine). Read and written by the same rule.
|
||||
pub(crate) fn usable_axes(x: cadcraft_geom::Vec3, y: cadcraft_geom::Vec3) -> bool {
|
||||
x.is_finite() && y.is_finite() && x.len() > 1e-12 && y.len() > 1e-12 && x.cross(y).len() > 1e-9 * x.len() * y.len()
|
||||
}
|
||||
/// Most plot style tables and plot style names read from a file.
|
||||
pub(crate) const MAX_PLOT_STYLE_TABLES: usize = 1000;
|
||||
pub(crate) const MAX_PLOT_STYLE_NAMES: usize = 100_000;
|
||||
|
||||
@@ -62,6 +62,8 @@ struct Rx {
|
||||
block_arrays: HashMap<String, cadcraft_doc::ArrayParams>,
|
||||
/// LAYER record handle (upper case) → layer name (VIEWPORT group 331/341 frozen layers).
|
||||
layers: HashMap<String, String>,
|
||||
/// UCS record handle (upper case) → UCS name (a layout's named UCS, group 345).
|
||||
ucss: HashMap<String, String>,
|
||||
/// Owner handle, paper flag and enclosing block (upper case) of each generated sheet viewport
|
||||
/// (PAPERVIEW) the reader dropped.
|
||||
paper_views_dropped: Vec<(Option<String>, bool, Option<String>)>,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::common::T;
|
||||
use super::dimassoc::dimassoc;
|
||||
use super::document::sortents_table;
|
||||
use super::{Drawing, EntityKind, Group, Handle, HashMap, MLeaderStyle, PageSetup, Rx, Tag, Vec2};
|
||||
use super::{Drawing, EntityKind, Group, Handle, HashMap, MLeaderStyle, PageSetup, Rx, Tag, Ucs, Vec2, Vec3};
|
||||
|
||||
/// Non-graphical objects applied once every entity is placed.
|
||||
#[derive(Default)]
|
||||
@@ -22,6 +22,8 @@ pub(super) struct Objects {
|
||||
groups: Vec<(String, Vec<Tag>)>,
|
||||
/// Saved paper-space views of layouts: (layout name, view).
|
||||
layout_views: Vec<(String, (Vec2, f64))>,
|
||||
/// Layouts' current UCSs: (layout name, origin, X axis, Y axis, named UCS record handle).
|
||||
layout_ucss: Vec<(String, Vec3, Vec3, Vec3, Option<String>)>,
|
||||
/// SORTENTSTABLE objects: (owning block record handle, entity handle → sort handle).
|
||||
pub(super) sortents: Vec<(String, HashMap<Handle, u64>)>,
|
||||
/// WIPEOUTVARIABLES: the drawing's WIPEOUTFRAME (0 = frames hidden, 1 = shown).
|
||||
@@ -70,11 +72,18 @@ impl Objects {
|
||||
self.sortents.push(t);
|
||||
}
|
||||
}
|
||||
"LAYOUT" if self.layout_views.len() < MAX_OBJECTS => {
|
||||
"LAYOUT" if self.layout_views.len() < MAX_OBJECTS && self.layout_ucss.len() < MAX_OBJECTS => {
|
||||
let start = tags.iter().position(|x| x.code == 100 && x.str() == "AcDbLayout").unwrap_or(0);
|
||||
if let (Some(name), Some(view)) = (T(tags.get(start..).unwrap_or(&[])).s(1), layout_view(tags)) {
|
||||
let own = T(tags.get(start..).unwrap_or(&[]));
|
||||
if let (Some(name), Some(view)) = (own.s(1), layout_view(tags)) {
|
||||
self.layout_views.push((name, view));
|
||||
}
|
||||
// Its current UCS (groups 13, 16, 17; 345 when it is a named UCS).
|
||||
if let Some(name) = own.s(1)
|
||||
&& [13, 16, 17].iter().all(|c| own.f(*c).is_some())
|
||||
{
|
||||
self.layout_ucss.push((name, own.p(13), own.p(16), own.p(17), own.s(345)));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -94,6 +103,49 @@ impl Objects {
|
||||
Some(text)
|
||||
}
|
||||
|
||||
/// Model space's UCS name ($UCSNAME, or CADCraft's copy when the file lost it, as through
|
||||
/// DWG): kept only while the current UCS is still exactly that named UCS, else unnamed.
|
||||
fn apply_ucs_name(&self, d: &mut Drawing) {
|
||||
let header_name = d.header.str("UCSNAME", "").trim().to_string();
|
||||
let name = if header_name.is_empty() {
|
||||
self.xrecord_text(crate::dxf_ext::UCS_NAME_KEY).map(|n| n.trim().to_string()).unwrap_or_default()
|
||||
} else {
|
||||
header_name.clone()
|
||||
};
|
||||
let frame = (d.header.point("UCSORG"), d.header.point("UCSXDIR"), d.header.point("UCSYDIR"));
|
||||
let named = match frame {
|
||||
(Some(o), Some(x), Some(y)) => crate::dxf_ext::named_ucs(&d.ucss, &name, o, x, y).map(|u| u.name.clone()),
|
||||
_ => None,
|
||||
};
|
||||
match named {
|
||||
Some(n) => d.header.set_str("UCSNAME", &n),
|
||||
None if !header_name.is_empty() => d.header.set_str("UCSNAME", ""),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Layouts' UCSs: the World UCS, unusable axes or no such layout leave it unset.
|
||||
fn apply_layout_ucss(&self, d: &mut Drawing, rx: &Rx) {
|
||||
for (name, origin, x, y, named) in &self.layout_ucss {
|
||||
let usable = origin.is_finite() && crate::dxf_ext::usable_axes(*x, *y);
|
||||
// The named UCS group 345 points at, only while the layout's frame is still that
|
||||
// record's: a valid frame with a stale reference is kept, unnamed.
|
||||
let ucs_name = named
|
||||
.as_ref()
|
||||
.and_then(|h| rx.ucss.get(&h.trim().to_ascii_uppercase()))
|
||||
.and_then(|n| crate::dxf_ext::named_ucs(&d.ucss, n, *origin, *x, *y))
|
||||
.map(|u| u.name.clone())
|
||||
.unwrap_or_default();
|
||||
let world = origin.len() <= 1e-12 && (*x - Vec3::new(1.0, 0.0, 0.0)).len() <= 1e-12 && (*y - Vec3::new(0.0, 1.0, 0.0)).len() <= 1e-12;
|
||||
if !usable || (world && ucs_name.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == *name) {
|
||||
l.ucs = Some(Ucs { name: ucs_name, origin: *origin, x_axis: *x, y_axis: *y });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_table_styles(&self, d: &mut Drawing) {
|
||||
// Table styles (named by their ACAD_TABLESTYLE dictionary entries).
|
||||
for (h, tags) in &self.table_styles {
|
||||
@@ -191,6 +243,7 @@ impl Objects {
|
||||
if let Some(style) = self.xrecord_text(crate::dxf_ext::MLEADER_STYLE_KEY).filter(|s| !s.trim().is_empty()) {
|
||||
d.header.set_str("CMLEADERSTYLE", &style);
|
||||
}
|
||||
self.apply_ucs_name(d);
|
||||
self.apply_table_styles(d);
|
||||
self.apply_table_style_fixes(d, rx);
|
||||
// Parametric constraints and parameters.
|
||||
@@ -223,6 +276,7 @@ impl Objects {
|
||||
l.view = Some(*view);
|
||||
}
|
||||
}
|
||||
self.apply_layout_ucss(d, rx);
|
||||
self.apply_groups(d);
|
||||
// Standard associativity, for dimensions without CADCraft's exact links.
|
||||
for tags in &self.dimassocs {
|
||||
|
||||
@@ -214,6 +214,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
{
|
||||
d.header.set("SNAPBASE", HVal::Point(Vec3::new(x, y, 0.0)));
|
||||
}
|
||||
ucsicon(d, &t);
|
||||
if let Some(a) = t.f(50).filter(|a| a.is_finite()) {
|
||||
d.header.set_f64("SNAPANG", a);
|
||||
}
|
||||
@@ -314,11 +315,21 @@ fn index_table_handles(recs: &[(String, Vec<Tag>)], rx: &mut Rx) {
|
||||
"LAYER" => {
|
||||
rx.layers.insert(handle.trim().to_ascii_uppercase(), name);
|
||||
}
|
||||
"UCS" => {
|
||||
rx.ucss.insert(handle.trim().to_ascii_uppercase(), name);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `*ACTIVE` VPORT's UCSICON setting (group 74: bit 1 the icon shown, bit 2 at the UCS origin).
|
||||
fn ucsicon(d: &mut Drawing, t: &T) {
|
||||
if let Some(v) = t.i(74) {
|
||||
d.header.set_i64("UCSICON", v.clamp(0, 3));
|
||||
}
|
||||
}
|
||||
|
||||
/// Most tiles a viewport configuration keeps.
|
||||
const MAX_VPORT_TILES: usize = 64;
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ use cadcraft_color::Color;
|
||||
use cadcraft_doc::{
|
||||
AssocSnap, Attrib, Block, Common, DimAssoc, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, EntityStore, Gradient, Group, HAlign,
|
||||
HVal, Handle, Hatch, Insert, Layout, Leader, Line, Lineweight, LwPolyline, MLeader, MLeaderStyle, MText, PageSetup, Point, Solid, Space, Table,
|
||||
TableStyle, Text, Transparency, VAlign, VportConfig, VportTile,
|
||||
TableStyle, Text, Transparency, Ucs, VAlign, VportConfig, VportTile,
|
||||
};
|
||||
use cadcraft_geom::{Bounds2, Vec2, Vec3};
|
||||
use craft_dxf::{Tag, Version};
|
||||
@@ -43,6 +43,11 @@ struct W {
|
||||
pstyles: HashMap<String, String>,
|
||||
/// Upper-case layer name → its LAYER table record handle (group 331/341 of viewports).
|
||||
layers: HashMap<String, String>,
|
||||
/// Upper-case UCS name → its UCS table record handle (group 345 of layouts and viewports).
|
||||
ucss: HashMap<String, String>,
|
||||
/// Active VPORT group-345 tags (their index in `t`) waiting for the handle of the named UCS
|
||||
/// (upper case) they refer to, filled in after the UCS table is written.
|
||||
vport_ucs: Vec<(usize, String)>,
|
||||
/// Persistent reactors of source geometry: the associative hatches and DIMASSOC objects
|
||||
/// that follow it (groups `{ACAD_REACTORS 330 …}`).
|
||||
reactors: HashMap<Handle, Vec<String>>,
|
||||
@@ -155,6 +160,8 @@ pub fn entity_groups(d: &Drawing, e: &Entity) -> (String, Vec<Tag>) {
|
||||
next: d.handseed.max(0x100).saturating_add(0x1000),
|
||||
pstyles: HashMap::new(),
|
||||
layers: HashMap::new(),
|
||||
ucss: HashMap::new(),
|
||||
vport_ucs: Vec::new(),
|
||||
reactors: HashMap::new(),
|
||||
};
|
||||
let cx = Ctx { target: Version::R2018, legacy_columns: true, ..Ctx::default() };
|
||||
|
||||
@@ -16,7 +16,15 @@ 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,
|
||||
pstyles: HashMap::new(),
|
||||
layers: HashMap::new(),
|
||||
ucss: HashMap::new(),
|
||||
vport_ucs: Vec::new(),
|
||||
reactors: HashMap::new(),
|
||||
};
|
||||
let mut sah = false;
|
||||
for (k, v) in &dm.overrides {
|
||||
let Some(field) = DimStyle::field_name(k) else { continue };
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{DimVal, Drawing, HVal, K, Version, W, dxf_ext};
|
||||
use super::{DimVal, Drawing, HVal, K, Ucs, Vec3, Version, W, dxf_ext};
|
||||
|
||||
/// Header variables we write, with their group codes (DXF Reference, HEADER section).
|
||||
/// `P2`/`P3` = 2D/3D point.
|
||||
@@ -37,6 +37,11 @@ const HEADER_VARS: &[(&str, i32)] = &[
|
||||
("CHAMFERB", 40),
|
||||
("ANGBASE", 50),
|
||||
("ANGDIR", 70),
|
||||
// Model space's current UCS (each layout's is in its LAYOUT object).
|
||||
("UCSNAME", 2),
|
||||
("UCSORG", -3),
|
||||
("UCSXDIR", -3),
|
||||
("UCSYDIR", -3),
|
||||
("PDMODE", 70),
|
||||
("PDSIZE", 40),
|
||||
("PLINEWID", 40),
|
||||
@@ -52,6 +57,25 @@ const HEADER_VARS: &[(&str, i32)] = &[
|
||||
("VIEWSIZE", 40),
|
||||
];
|
||||
|
||||
/// Model space's current UCS from the header (UCSORG, UCSXDIR, UCSYDIR, UCSNAME): unusable
|
||||
/// values are the World UCS's, so a broken one read from a file isn't written back.
|
||||
pub(super) fn model_ucs(d: &Drawing) -> Ucs {
|
||||
let h = &d.header;
|
||||
let p = |name: &str| h.point(name).filter(|v| v.is_finite());
|
||||
let axis = |name: &str| p(name).filter(|v| v.len() > 1e-12);
|
||||
let (x, y, usable) = match (axis("UCSXDIR"), axis("UCSYDIR")) {
|
||||
(Some(x), Some(y)) if x.cross(y).len() > 1e-9 * x.len() * y.len() => (x, y, true),
|
||||
_ => (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), false),
|
||||
};
|
||||
// The name only of a UCS table record whose frame the current UCS still is: a name read from
|
||||
// a file without its record, beside axes replaced by the World UCS's, or beside an origin or
|
||||
// axes of its own (restoring the name would move the UCS) is dropped.
|
||||
let origin = p("UCSORG").unwrap_or(Vec3::ZERO);
|
||||
let raw = h.str("UCSNAME", "");
|
||||
let name = crate::dxf_ext::named_ucs(&d.ucss, &raw, origin, x, y).filter(|_| usable).map(|u| u.name.clone()).unwrap_or_default();
|
||||
Ucs { name, origin, x_axis: x, y_axis: y }
|
||||
}
|
||||
|
||||
/// The current dimension style's variables as header variables (`$DIMTXT`, `$DIMDEC`…), after
|
||||
/// `$DIMSTYLE`: AutoCAD draws new and updated dimensions with the header's DIM* values, which
|
||||
/// otherwise stay its defaults (0.18 text, 4 decimals) whatever the current style says (#1051).
|
||||
@@ -104,6 +128,9 @@ pub(super) fn header_vars(w: &mut W, d: &Drawing) {
|
||||
let p = match *name {
|
||||
"SNAPUNIT" => d.header.snap_unit().to3(0.0),
|
||||
"GRIDUNIT" => d.header.grid_unit().to3(0.0),
|
||||
"UCSORG" => model_ucs(d).origin,
|
||||
"UCSXDIR" => model_ucs(d).x_axis,
|
||||
"UCSYDIR" => model_ucs(d).y_axis,
|
||||
_ => *p,
|
||||
};
|
||||
w.s(9, format!("${name}"));
|
||||
@@ -128,6 +155,11 @@ pub(super) fn header_vars(w: &mut W, d: &Drawing) {
|
||||
w.i(c, i);
|
||||
}
|
||||
}
|
||||
// Only the name of a UCS the drawing has, with the axes written above.
|
||||
(c, _) if *name == "UCSNAME" => {
|
||||
w.s(9, "$UCSNAME");
|
||||
w.s(c, model_ucs(d).name);
|
||||
}
|
||||
(c, v) => {
|
||||
if let Some(t) = v.as_str() {
|
||||
w.s(9, format!("${name}"));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::ctx::Ctx;
|
||||
use super::header::model_ucs;
|
||||
use super::{Bounds2, Drawing, Entity, EntityKind, Handle, HashMap, Layout, Vec2, Vec3, VportConfig, VportTile, W, dxf_ext};
|
||||
|
||||
/// Layouts with viewports but without the paper-space viewport (id 1, the sheet itself), keyed
|
||||
@@ -138,6 +139,27 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) {
|
||||
w.f(42, 50.0);
|
||||
w.f(50, d.header.f64("SNAPANG", 0.0));
|
||||
w.f(51, twist.to_degrees());
|
||||
// UCSICON: bit 1 shows the icon, bit 2 puts it at the UCS origin. A setting of the shown
|
||||
// configuration (there is no header variable for it).
|
||||
if name == VportConfig::ACTIVE {
|
||||
w.i(74, d.header.i64("UCSICON", 3).clamp(0, 3));
|
||||
}
|
||||
// The shown configuration's tiles keep model space's current UCS (UCSVP 1).
|
||||
if name == VportConfig::ACTIVE {
|
||||
let ucs = model_ucs(d);
|
||||
w.i(65, 1);
|
||||
w.p(110, ucs.origin);
|
||||
w.p(111, ucs.x_axis);
|
||||
w.p(112, ucs.y_axis);
|
||||
w.i(79, 0);
|
||||
// The named UCS it is (none: unnamed). The UCS table comes after VPORT, so the
|
||||
// handle is filled in once that table has given it one ([`W::vport_ucs`]).
|
||||
if !ucs.name.is_empty() {
|
||||
w.s(345, "0");
|
||||
w.vport_ucs.push((w.t.len() - 1, ucs.name.to_ascii_uppercase()));
|
||||
}
|
||||
w.f(146, 0.0);
|
||||
}
|
||||
}
|
||||
w.s(0, "ENDTAB");
|
||||
}
|
||||
|
||||
@@ -3,12 +3,12 @@ use super::blocks::{arrow_block_entities, dim_block_entities, dim_block_plan, re
|
||||
use super::common::annotative_xdata;
|
||||
use super::ctx::{AssocObj, Ctx};
|
||||
use super::entity::{entity, hatch_reactors};
|
||||
use super::header::{code_page, header_vars};
|
||||
use super::header::{code_page, header_vars, model_ucs};
|
||||
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,
|
||||
TableStyle, Tag, Ucs, Vec2, Vec3, Version, W, dxf_ext,
|
||||
};
|
||||
|
||||
struct TableWritePlan<'a> {
|
||||
@@ -163,7 +163,8 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
|
||||
// UCS: named user coordinate systems (DXF Reference, UCS).
|
||||
let th = table_head(w, "UCS", d.ucss.len());
|
||||
for u in &d.ucss {
|
||||
record_head(w, "UCS", &th, "AcDbUCSTableRecord");
|
||||
let h = record_head(w, "UCS", &th, "AcDbUCSTableRecord");
|
||||
w.ucss.insert(u.name.to_ascii_uppercase(), h);
|
||||
w.s(2, &u.name);
|
||||
w.i(70, 0);
|
||||
w.p(10, u.origin);
|
||||
@@ -173,6 +174,13 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
|
||||
w.f(146, 0.0);
|
||||
}
|
||||
w.s(0, "ENDTAB");
|
||||
// The active VPORT's named UCS (written before this table had handles).
|
||||
for (i, name) in std::mem::take(&mut w.vport_ucs) {
|
||||
let h = w.ucss.get(&name).cloned();
|
||||
if let (Some(h), Some(t)) = (h, w.t.get_mut(i)) {
|
||||
*t = Tag::s(345, h);
|
||||
}
|
||||
}
|
||||
let apps = ["ACAD", dxf_ext::APP, "AcadAnnotative", dxf_ext::LAYER_TRANSPARENCY_APP, dxf_ext::LAYER_DESCRIPTION_APP];
|
||||
let th = table_head(w, "APPID", apps.len());
|
||||
for app in apps {
|
||||
@@ -245,7 +253,15 @@ 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,
|
||||
pstyles: HashMap::new(),
|
||||
layers: HashMap::new(),
|
||||
ucss: HashMap::new(),
|
||||
vport_ucs: Vec::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 "<>"
|
||||
@@ -385,6 +401,8 @@ struct LayoutWriteData<'a> {
|
||||
flags: i64,
|
||||
page: &'a PageSetup,
|
||||
view: Option<(Vec2, f64)>,
|
||||
/// The layout's current UCS (none for model space, whose UCS is in the header).
|
||||
ucs: Option<&'a Ucs>,
|
||||
/// The layout's limits as read (`None`: the default 0,0 to 12,9).
|
||||
limits: Option<(Vec2, Vec2)>,
|
||||
}
|
||||
@@ -467,12 +485,21 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
|
||||
w.p(12, Vec3::ZERO);
|
||||
w.p(14, Vec3::ZERO);
|
||||
w.p(15, Vec3::ZERO);
|
||||
// The layout's current UCS: origin, X and Y axes, orthographic type, then (after the
|
||||
// block record) the named UCS it is.
|
||||
// Usable by the rule the reader applies, so what is written reads back.
|
||||
let u = data.ucs.filter(|u| u.origin.is_finite() && dxf_ext::usable_axes(u.x_axis, u.y_axis));
|
||||
w.f(146, 0.0);
|
||||
w.p(13, Vec3::ZERO);
|
||||
w.p(16, Vec3::new(1.0, 0.0, 0.0));
|
||||
w.p(17, Vec3::new(0.0, 1.0, 0.0));
|
||||
w.p(13, u.map_or(Vec3::ZERO, |u| u.origin));
|
||||
w.p(16, u.map_or(Vec3::new(1.0, 0.0, 0.0), |u| u.x_axis));
|
||||
w.p(17, u.map_or(Vec3::new(0.0, 1.0, 0.0), |u| u.y_axis));
|
||||
w.i(76, 0);
|
||||
w.s(330, brh);
|
||||
// The named UCS it is, only while its frame is still that record's (as for model space).
|
||||
let named = u.and_then(|u| dxf_ext::named_ucs(&d.ucss, &u.name, u.origin, u.x_axis, u.y_axis));
|
||||
if let Some(h) = named.and_then(|u| w.ucss.get(&u.name.to_ascii_uppercase())).cloned() {
|
||||
w.s(345, h);
|
||||
}
|
||||
// The saved paper-space view (centre, height) as CADCraft xdata.
|
||||
if let Some((c, height)) = view.filter(|(c, v)| c.x.is_finite() && c.y.is_finite() && v.is_finite()) {
|
||||
w.s(1001, dxf_ext::APP);
|
||||
@@ -532,7 +559,17 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
|
||||
layout_obj(
|
||||
w,
|
||||
LayoutWriteContext { drawing: d, dictionary: layout_dict },
|
||||
LayoutWriteData { handle: model_layout, name: "Model", tab: 0, block_record: ms_br, flags: 1, page: &model_page, view: None, limits: None },
|
||||
LayoutWriteData {
|
||||
handle: model_layout,
|
||||
name: "Model",
|
||||
tab: 0,
|
||||
block_record: ms_br,
|
||||
flags: 1,
|
||||
page: &model_page,
|
||||
view: None,
|
||||
ucs: None,
|
||||
limits: None,
|
||||
},
|
||||
);
|
||||
for (i, (_, brh, l)) in ps_brs.iter().enumerate() {
|
||||
let h = layout_handles.get(i).cloned().unwrap_or_default();
|
||||
@@ -547,6 +584,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
|
||||
flags: 1,
|
||||
page: &l.page,
|
||||
view: l.view,
|
||||
ucs: l.ucs.as_ref(),
|
||||
limits: l.limits,
|
||||
},
|
||||
);
|
||||
@@ -919,6 +957,8 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
|
||||
next: d.handseed.max(0x100).saturating_add(0x1000),
|
||||
pstyles: HashMap::new(),
|
||||
layers: HashMap::new(),
|
||||
ucss: HashMap::new(),
|
||||
vport_ucs: Vec::new(),
|
||||
reactors: hatch_reactors(d),
|
||||
};
|
||||
// Pre-allocate handles for block records.
|
||||
@@ -976,6 +1016,10 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
|
||||
if let Some(name) = d.header.get("CMLEADERSTYLE").and_then(HVal::as_str) {
|
||||
xrecords.push((dxf_ext::MLEADER_STYLE_KEY, w.h(), vec![name.to_string()]));
|
||||
}
|
||||
let ucs_name = model_ucs(d).name;
|
||||
if !ucs_name.is_empty() {
|
||||
xrecords.push((dxf_ext::UCS_NAME_KEY, w.h(), vec![ucs_name]));
|
||||
}
|
||||
if let Some(chunks) = dxf_ext::constraint_chunks(&d.constraints, &d.parametric) {
|
||||
xrecords.push((dxf_ext::CONSTRAINTS_KEY, w.h(), chunks));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,472 @@
|
||||
//! The current UCS survives saving and reopening (#1106): model space's in the header
|
||||
//! ($UCSORG, $UCSXDIR, $UCSYDIR, $UCSNAME) and the shown VPORT, each layout's in its LAYOUT
|
||||
//! object (groups 13, 16, 17 and 345 for a named UCS), through DXF and DWG.
|
||||
|
||||
use cadcraft_doc::*;
|
||||
use cadcraft_geom::Vec3;
|
||||
|
||||
fn near3(a: Vec3, b: Vec3) -> bool {
|
||||
(a - b).len() < 1e-9
|
||||
}
|
||||
|
||||
/// The (code, value) pairs of every `kind` record in DXF text.
|
||||
fn records(text: &str, kind: &str) -> Vec<Vec<(String, String)>> {
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let mut out: Vec<Vec<(String, String)>> = Vec::new();
|
||||
let mut inside = false;
|
||||
for pair in lines.chunks(2) {
|
||||
let [code, value] = pair else { break };
|
||||
if *code == "0" {
|
||||
inside = *value == kind;
|
||||
if inside {
|
||||
out.push(Vec::new());
|
||||
}
|
||||
} else if inside && let Some(rec) = out.last_mut() {
|
||||
rec.push((code.to_string(), value.to_string()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn group<'a>(rec: &'a [(String, String)], code: &str) -> Option<&'a str> {
|
||||
rec.iter().find(|(c, _)| c == code).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// The LAYOUT object of layout `name` (its group 1 after `100 AcDbLayout`; the first group 1 is
|
||||
/// the page setup's).
|
||||
fn layout_record(text: &str, name: &str) -> Vec<(String, String)> {
|
||||
records(text, "LAYOUT")
|
||||
.into_iter()
|
||||
.find(|r| r.iter().skip_while(|(c, v)| !(c == "100" && v == "AcDbLayout")).any(|(c, v)| c == "1" && v == name))
|
||||
.unwrap_or_else(|| panic!("no LAYOUT {name}"))
|
||||
}
|
||||
|
||||
fn num(rec: &[(String, String)], code: &str) -> f64 {
|
||||
group(rec, code).and_then(|v| v.trim().parse().ok()).unwrap_or(f64::NAN)
|
||||
}
|
||||
|
||||
/// The header variable `$name`'s groups in DXF text.
|
||||
fn header_var(text: &str, name: &str) -> Vec<(String, String)> {
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let mut out = Vec::new();
|
||||
let mut on = false;
|
||||
for pair in lines.chunks(2) {
|
||||
let [code, value] = pair else { break };
|
||||
if *code == "9" {
|
||||
on = *value == format!("${name}");
|
||||
continue;
|
||||
}
|
||||
if *code == "0" {
|
||||
on = false;
|
||||
}
|
||||
if on {
|
||||
out.push((code.to_string(), value.to_string()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
const C30: f64 = 0.866_025_403_784_438_6;
|
||||
|
||||
/// A drawing whose model space is in a named UCS turned 30° at (100, 50, 0), and whose first
|
||||
/// layout is in an unnamed one at (5, 5) turned 90°.
|
||||
fn drawing() -> Drawing {
|
||||
let mut d = Drawing::default();
|
||||
let site = Ucs { name: "SITE".into(), origin: Vec3::new(100.0, 50.0, 0.0), x_axis: Vec3::new(C30, 0.5, 0.0), y_axis: Vec3::new(-0.5, C30, 0.0) };
|
||||
d.ucss.push(site.clone());
|
||||
d.header.set("UCSORG", HVal::Point(site.origin));
|
||||
d.header.set("UCSXDIR", HVal::Point(site.x_axis));
|
||||
d.header.set("UCSYDIR", HVal::Point(site.y_axis));
|
||||
d.header.set_str("UCSNAME", "SITE");
|
||||
d.layouts[0].ucs =
|
||||
Some(Ucs { name: String::new(), origin: Vec3::new(5.0, 5.0, 0.0), x_axis: Vec3::new(0.0, 1.0, 0.0), y_axis: Vec3::new(-1.0, 0.0, 0.0) });
|
||||
d
|
||||
}
|
||||
|
||||
fn check(back: &Drawing) {
|
||||
let h = &back.header;
|
||||
assert!(near3(h.point("UCSORG").unwrap(), Vec3::new(100.0, 50.0, 0.0)));
|
||||
assert!(near3(h.point("UCSXDIR").unwrap(), Vec3::new(C30, 0.5, 0.0)));
|
||||
assert!(near3(h.point("UCSYDIR").unwrap(), Vec3::new(-0.5, C30, 0.0)));
|
||||
assert_eq!(h.str("UCSNAME", ""), "SITE");
|
||||
let l = back.layouts[0].ucs.clone().expect("the layout keeps its UCS");
|
||||
assert!(near3(l.origin, Vec3::new(5.0, 5.0, 0.0)) && near3(l.x_axis, Vec3::new(0.0, 1.0, 0.0)) && l.name.is_empty(), "{l:?}");
|
||||
assert!(back.layouts.iter().skip(1).all(|l| l.ucs.is_none()), "the other layouts stay in the World UCS");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_and_layout_ucs_survive_a_dxf_save() {
|
||||
let d = drawing();
|
||||
let text = cadcraft_io::write_dxf(&d);
|
||||
// The header and the shown viewport both carry model space's UCS.
|
||||
let org = header_var(&text, "UCSORG");
|
||||
assert_eq!((num(&org, "10"), num(&org, "20"), num(&org, "30")), (100.0, 50.0, 0.0));
|
||||
assert_eq!(group(&header_var(&text, "UCSNAME"), "2"), Some("SITE"));
|
||||
let active = records(&text, "VPORT").into_iter().find(|r| group(r, "2").is_some_and(|n| n.eq_ignore_ascii_case("*ACTIVE"))).unwrap();
|
||||
assert_eq!((num(&active, "110"), num(&active, "120")), (100.0, 50.0));
|
||||
assert!((num(&active, "111") - C30).abs() < 1e-12 && group(&active, "65") == Some("1"));
|
||||
// The layout object carries the layout's.
|
||||
let lay = layout_record(&text, &d.layouts[0].name);
|
||||
assert_eq!((num(&lay, "13"), num(&lay, "23"), num(&lay, "16"), num(&lay, "26")), (5.0, 5.0, 0.0, 1.0));
|
||||
assert!(group(&lay, "345").is_none(), "unnamed: no UCS record");
|
||||
check(&cadcraft_io::read_dxf(text.as_bytes()).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layouts_named_ucs_points_at_its_record() {
|
||||
let mut d = drawing();
|
||||
// The layout's UCS is SITE (its frame, by name).
|
||||
let site_rec = d.ucss[0].clone();
|
||||
d.layouts[0].ucs = Some(site_rec.clone());
|
||||
let text = cadcraft_io::write_dxf(&d);
|
||||
let site = records(&text, "UCS").into_iter().find(|r| group(r, "2") == Some("SITE")).and_then(|r| group(&r, "5").map(str::to_string)).unwrap();
|
||||
let lay = layout_record(&text, &d.layouts[0].name);
|
||||
assert_eq!(group(&lay, "345"), Some(site.as_str()));
|
||||
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
assert_eq!(back.layouts[0].ucs.as_ref().unwrap().name, "SITE");
|
||||
// Named SITE but moved since: not pointed at SITE (reopened, the name would bring SITE's frame
|
||||
// with the moved one); the layout keeps its own frame unnamed.
|
||||
let mut moved = d.clone();
|
||||
moved.layouts[0].ucs = Some(Ucs { origin: site_rec.origin + Vec3::new(1.0, 0.0, 0.0), ..site_rec.clone() });
|
||||
let text = cadcraft_io::write_dxf(&moved);
|
||||
assert!(group(&layout_record(&text, &d.layouts[0].name), "345").is_none());
|
||||
let u = cadcraft_io::read_dxf(text.as_bytes()).unwrap().layouts[0].ucs.clone().unwrap();
|
||||
assert!(u.name.is_empty() && near3(u.origin, site_rec.origin + Vec3::new(1.0, 0.0, 0.0)), "{u:?}");
|
||||
// A deleted named UCS isn't pointed at, and the layout keeps the axes unnamed.
|
||||
let mut gone = back.clone();
|
||||
gone.ucss.clear();
|
||||
let text = cadcraft_io::write_dxf(&gone);
|
||||
let lay = layout_record(&text, &d.layouts[0].name);
|
||||
assert!(group(&lay, "345").is_none());
|
||||
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
let u = back.layouts[0].ucs.clone().unwrap();
|
||||
assert!(u.name.is_empty() && near3(u.x_axis, site_rec.x_axis));
|
||||
}
|
||||
|
||||
/// Short but square layout axes are a usable UCS when read, so they are written as they are and
|
||||
/// not replaced by the World UCS's (the writer and the reader share one rule).
|
||||
#[test]
|
||||
fn short_layout_axes_survive_a_save() {
|
||||
let mut d = drawing();
|
||||
let tiny = Ucs { name: String::new(), origin: Vec3::new(2.0, 3.0, 0.0), x_axis: Vec3::new(1e-7, 0.0, 0.0), y_axis: Vec3::new(0.0, 1e-7, 0.0) };
|
||||
d.layouts[0].ucs = Some(tiny.clone());
|
||||
let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap();
|
||||
let u = back.layouts[0].ucs.clone().expect("kept");
|
||||
assert!(near3(u.x_axis, tiny.x_axis) && near3(u.y_axis, tiny.y_axis) && near3(u.origin, tiny.origin), "{u:?}");
|
||||
}
|
||||
|
||||
/// Far from the World origin a named UCS's origin is still compared to round-off only: a move of
|
||||
/// 0.05 at 100,000,000 is a different UCS, an exact save keeps the name.
|
||||
#[test]
|
||||
fn a_far_named_ucs_keeps_its_name_only_where_it_is() {
|
||||
let far = Ucs { name: "FAR".into(), origin: Vec3::new(1e8, 0.0, 0.0), x_axis: Vec3::new(1.0, 0.0, 0.0), y_axis: Vec3::new(0.0, 1.0, 0.0) };
|
||||
let mut d = Drawing::default();
|
||||
d.ucss.push(far.clone());
|
||||
d.header.set("UCSORG", HVal::Point(far.origin));
|
||||
d.header.set("UCSXDIR", HVal::Point(far.x_axis));
|
||||
d.header.set("UCSYDIR", HVal::Point(far.y_axis));
|
||||
d.header.set_str("UCSNAME", "FAR");
|
||||
let read = |d: &Drawing| cadcraft_io::read_dxf(cadcraft_io::write_dxf(d).as_bytes()).unwrap().header.str("UCSNAME", "");
|
||||
assert_eq!(read(&d), "FAR");
|
||||
d.header.set("UCSORG", HVal::Point(Vec3::new(1e8 + 0.05, 0.0, 0.0)));
|
||||
assert_eq!(read(&d), "", "moved 0.05: no longer FAR");
|
||||
// Further out still: at 1e12 an exact save keeps the name and a 0.5 move drops it.
|
||||
let mut d = d.clone();
|
||||
let far = Ucs { origin: Vec3::new(1e12, 0.0, 0.0), ..far };
|
||||
d.ucss = vec![far.clone()];
|
||||
d.header.set("UCSORG", HVal::Point(far.origin));
|
||||
assert_eq!(read(&d), "FAR");
|
||||
d.header.set("UCSORG", HVal::Point(Vec3::new(1e12 + 0.5, 0.0, 0.0)));
|
||||
assert_eq!(read(&d), "", "moved 0.5 at 1e12: no longer FAR");
|
||||
}
|
||||
|
||||
/// DXF text with the value of group `code` in the first record `kind` holding `marker` (code,
|
||||
/// value) replaced by `value`.
|
||||
fn replace_group(text: &str, after: (&str, &str), code: &str, value: &str) -> String {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let mut out = Vec::with_capacity(lines.len());
|
||||
let mut armed = false;
|
||||
let mut done = false;
|
||||
for pair in lines.chunks(2) {
|
||||
let [c, v] = pair else { break };
|
||||
let (ct, vt) = (c.trim(), v.trim());
|
||||
if !done && ct == after.0 && vt == after.1 {
|
||||
armed = true;
|
||||
}
|
||||
let v = if armed && !done && ct == code {
|
||||
done = true;
|
||||
value.to_string()
|
||||
} else {
|
||||
v.to_string()
|
||||
};
|
||||
out.push(format!("{c}\n{v}"));
|
||||
}
|
||||
out.join("\n") + "\n"
|
||||
}
|
||||
|
||||
/// Read from a file, a UCS name is kept only while its frame is that record's: a $UCSNAME, or a
|
||||
/// layout's group 345, naming a UCS whose origin differs leaves the frame as it is, unnamed.
|
||||
#[test]
|
||||
fn a_stale_ucs_name_in_a_file_is_dropped_on_read() {
|
||||
// Model space: $UCSNAME SITE, but $UCSORG moved away from SITE's origin.
|
||||
let text = cadcraft_io::write_dxf(&drawing());
|
||||
let moved = replace_group(&text, ("9", "$UCSORG"), "10", "101.0");
|
||||
let back = cadcraft_io::read_dxf(moved.as_bytes()).unwrap();
|
||||
assert_eq!(back.header.str("UCSNAME", ""), "", "SITE no longer");
|
||||
assert!(near3(back.header.point("UCSORG").unwrap(), Vec3::new(101.0, 50.0, 0.0)), "the frame is kept");
|
||||
assert_eq!(cadcraft_io::read_dxf(text.as_bytes()).unwrap().header.str("UCSNAME", ""), "SITE", "unmoved, still SITE");
|
||||
// A layout: its UCS is SITE (345 written), then its origin (group 13) moved in the file.
|
||||
let mut d = drawing();
|
||||
d.layouts[0].ucs = Some(d.ucss[0].clone());
|
||||
let name = d.layouts[0].name.clone();
|
||||
let text = cadcraft_io::write_dxf(&d);
|
||||
assert!(group(&layout_record(&text, &name), "345").is_some());
|
||||
let moved = replace_group(&text, ("1", &name), "13", "7.0");
|
||||
let u = cadcraft_io::read_dxf(moved.as_bytes()).unwrap().layout(&name).unwrap().ucs.clone().unwrap();
|
||||
assert!(u.name.is_empty() && (u.origin.x - 7.0).abs() < 1e-9, "{u:?}");
|
||||
assert_eq!(cadcraft_io::read_dxf(text.as_bytes()).unwrap().layout(&name).unwrap().ucs.as_ref().unwrap().name, "SITE");
|
||||
}
|
||||
|
||||
/// The active VPORT names model space's UCS too: group 345 is the UCS record's handle while the
|
||||
/// UCS is that named one, and absent while it is unnamed.
|
||||
#[test]
|
||||
fn the_active_vport_points_at_the_named_ucs() {
|
||||
let active = |text: &str| records(text, "VPORT").into_iter().find(|r| group(r, "2") == Some("*Active")).unwrap();
|
||||
let text = cadcraft_io::write_dxf(&drawing());
|
||||
let site = records(&text, "UCS").into_iter().find(|r| group(r, "2") == Some("SITE")).and_then(|r| group(&r, "5").map(str::to_string)).unwrap();
|
||||
assert_eq!(group(&active(&text), "345"), Some(site.as_str()));
|
||||
let mut unnamed = drawing();
|
||||
unnamed.header.set_str("UCSNAME", "");
|
||||
assert!(group(&active(&cadcraft_io::write_dxf(&unnamed)), "345").is_none());
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn model_and_layout_ucs_survive_a_dwg_save() {
|
||||
let d = drawing();
|
||||
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
|
||||
let back = cadcraft_io::read(&dwg, "x.dwg").unwrap();
|
||||
check(&back);
|
||||
// And a second trip.
|
||||
let again = cadcraft_io::read(&cadcraft_io::write(&back, "x.dwg").unwrap(), "x.dwg").unwrap();
|
||||
check(&again);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drawing_in_the_world_ucs_is_written_as_before() {
|
||||
let d = Drawing::default();
|
||||
let text = cadcraft_io::write_dxf(&d);
|
||||
assert!(header_var(&text, "UCSORG").is_empty(), "nothing set, nothing written");
|
||||
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
assert!(back.layouts.iter().all(|l| l.ucs.is_none()));
|
||||
assert!(back.header.point("UCSXDIR").is_none_or(|x| near3(x, Vec3::new(1.0, 0.0, 0.0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tilted_ucs_is_kept_as_it_is() {
|
||||
let mut d = Drawing::default();
|
||||
d.header.set("UCSORG", HVal::Point(Vec3::new(0.0, 0.0, 10.0)));
|
||||
d.header.set("UCSXDIR", HVal::Point(Vec3::new(1.0, 0.0, 0.0)));
|
||||
d.header.set("UCSYDIR", HVal::Point(Vec3::new(0.0, 0.0, 1.0)));
|
||||
d.ucss.push(Ucs { name: "FRONT".into(), origin: Vec3::ZERO, x_axis: Vec3::new(1.0, 0.0, 0.0), y_axis: Vec3::new(0.0, 0.0, 1.0) });
|
||||
let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap();
|
||||
assert!(near3(back.header.point("UCSYDIR").unwrap(), Vec3::new(0.0, 0.0, 1.0)));
|
||||
assert!(near3(back.header.point("UCSORG").unwrap(), Vec3::new(0.0, 0.0, 10.0)));
|
||||
assert!(near3(back.ucss[0].y_axis, Vec3::new(0.0, 0.0, 1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_ucs_values_are_not_written_back() {
|
||||
let mut d = Drawing::default();
|
||||
d.header.set("UCSORG", HVal::Point(Vec3::new(f64::NAN, 1.0, 0.0)));
|
||||
d.header.set("UCSXDIR", HVal::Point(Vec3::ZERO));
|
||||
d.header.set("UCSYDIR", HVal::Point(Vec3::new(f64::INFINITY, 0.0, 0.0)));
|
||||
d.layouts[0].ucs = Some(Ucs { name: "X".into(), origin: Vec3::new(f64::NAN, 0.0, 0.0), x_axis: Vec3::ZERO, y_axis: Vec3::ZERO });
|
||||
let text = cadcraft_io::write_dxf(&d);
|
||||
assert!(!text.to_ascii_lowercase().contains("nan") && !text.to_ascii_lowercase().contains("inf"), "no non-finite numbers written");
|
||||
let x = header_var(&text, "UCSXDIR");
|
||||
assert_eq!((num(&x, "10"), num(&x, "20")), (1.0, 0.0), "the World UCS's axes instead");
|
||||
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
assert!(back.layouts[0].ucs.is_none());
|
||||
}
|
||||
|
||||
/// Model space's UCS name is written only for a UCS the drawing has, with the axes it came with:
|
||||
/// a name without its record, or beside axes replaced by the World UCS's, is left out of both
|
||||
/// $UCSNAME and CADCraft's copy of it.
|
||||
#[test]
|
||||
fn a_ucs_name_without_its_ucs_is_not_written() {
|
||||
let name_written = |d: &Drawing| {
|
||||
let text = cadcraft_io::write_dxf(d);
|
||||
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
(
|
||||
group(&header_var(&text, "UCSNAME"), "2").unwrap_or_default().trim().to_string(),
|
||||
text.contains("CADCRAFT_UCSNAME"),
|
||||
back.header.str("UCSNAME", ""),
|
||||
)
|
||||
};
|
||||
// Kept: SITE is in the UCS table and its axes are current.
|
||||
assert_eq!(name_written(&drawing()), ("SITE".to_string(), true, "SITE".to_string()));
|
||||
// No such record (as a file can say).
|
||||
let mut ghost = drawing();
|
||||
ghost.header.set_str("UCSNAME", "GHOST");
|
||||
assert_eq!(name_written(&ghost), (String::new(), false, String::new()));
|
||||
// The record is there, but the axes beside the name are unusable: written as the World UCS.
|
||||
let mut broken = drawing();
|
||||
broken.header.set("UCSXDIR", HVal::Point(Vec3::ZERO));
|
||||
assert_eq!(name_written(&broken), (String::new(), false, String::new()));
|
||||
// Usable but not SITE's frame (moved, or turned): restoring SITE would move the UCS, so the
|
||||
// current one is unnamed.
|
||||
let mut moved = drawing();
|
||||
moved.header.set("UCSORG", HVal::Point(Vec3::new(101.0, 50.0, 0.0)));
|
||||
assert_eq!(name_written(&moved), (String::new(), false, String::new()));
|
||||
let mut turned = drawing();
|
||||
turned.header.set("UCSXDIR", HVal::Point(Vec3::new(1.0, 0.0, 0.0)));
|
||||
turned.header.set("UCSYDIR", HVal::Point(Vec3::new(0.0, 1.0, 0.0)));
|
||||
assert_eq!(name_written(&turned), (String::new(), false, String::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_layout_ucs_groups_are_ignored() {
|
||||
let d = Drawing::default();
|
||||
let text = cadcraft_io::write_dxf(&d);
|
||||
let name = d.layouts[0].name.clone();
|
||||
// Rewrite the layout's UCS axes (X: groups 16/26, Y: 17/27) as nonsense, each with a dangling
|
||||
// 345 handle: no length, Y along X, not a number.
|
||||
let usable = |l: &cadcraft_doc::Layout| l.ucs.as_ref().is_none_or(|u| u.name.is_empty() && u.x_axis.cross(u.y_axis).len() > 1e-9);
|
||||
for (case, [x16, x26, y17, y27], h) in [
|
||||
("no length", ["0.0", "0.0", "0.0", "0.0"], "FFFF"),
|
||||
("Y along X", ["1.0", "0.0", "2.0", "0.0"], "0"),
|
||||
("not a number", ["nan", "0.0", "0.0", "1.0"], "ZZ"),
|
||||
] {
|
||||
let mut out = String::new();
|
||||
let mut in_layout = false;
|
||||
let mut lines = text.lines();
|
||||
while let (Some(c), Some(v)) = (lines.next(), lines.next()) {
|
||||
let (ct, vt) = (c.trim(), v.trim());
|
||||
if ct == "0" {
|
||||
in_layout = vt == "LAYOUT";
|
||||
}
|
||||
let v = match (in_layout, ct) {
|
||||
(true, "16") => x16.to_string(),
|
||||
(true, "26") => x26.to_string(),
|
||||
(true, "17") => y17.to_string(),
|
||||
(true, "27") => y27.to_string(),
|
||||
_ => v.to_string(),
|
||||
};
|
||||
out.push_str(&format!("{c}\n{v}\n"));
|
||||
if in_layout && ct == "76" {
|
||||
out.push_str(&format!("345\n{h}\n"));
|
||||
}
|
||||
}
|
||||
// Refusing the file is fine; reading it must leave no unusable UCS, saved and reopened too.
|
||||
// Parallel axes are plain numbers: that file must read, so the rejection below runs.
|
||||
let back = match cadcraft_io::read_dxf(out.as_bytes()) {
|
||||
Ok(back) => back,
|
||||
Err(e) if case == "Y along X" => panic!("{case}: {e}"),
|
||||
Err(_) => continue,
|
||||
};
|
||||
let l = back.layout(&name).unwrap();
|
||||
assert!(usable(l), "{case}: {:?}", l.ucs);
|
||||
if case == "Y along X" {
|
||||
assert!(l.ucs.is_none(), "parallel axes are rejected: {:?}", l.ucs);
|
||||
}
|
||||
let again = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&back).as_bytes()).unwrap();
|
||||
assert!(usable(again.layout(&name).unwrap()), "{case} after save and reopen");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_ucs_name_copy_is_not_brought_back() {
|
||||
let text = cadcraft_io::write_dxf(&drawing());
|
||||
// As another program would save it after changing the UCS: $UCSNAME cleared, the axes moved,
|
||||
// CADCraft's copy of the old name still there.
|
||||
let mut out = String::new();
|
||||
let mut lines = text.lines().peekable();
|
||||
let mut var = String::new();
|
||||
while let (Some(c), Some(v)) = (lines.next(), lines.next()) {
|
||||
if c.trim() == "9" {
|
||||
var = v.trim().to_string();
|
||||
}
|
||||
let v = match (var.as_str(), c.trim()) {
|
||||
("$UCSNAME", "2") => String::new(),
|
||||
("$UCSXDIR", "10") => "0.0".into(),
|
||||
("$UCSXDIR", "20") => "1.0".into(),
|
||||
("$UCSYDIR", "10") => "-1.0".into(),
|
||||
("$UCSYDIR", "20") => "0.0".into(),
|
||||
_ => v.to_string(),
|
||||
};
|
||||
out.push_str(&format!("{c}\n{v}\n"));
|
||||
}
|
||||
let back = cadcraft_io::read_dxf(out.as_bytes()).unwrap();
|
||||
assert_eq!(back.header.str("UCSNAME", ""), "", "the UCS is no longer SITE");
|
||||
assert!(near3(back.header.point("UCSXDIR").unwrap(), Vec3::new(0.0, 1.0, 0.0)));
|
||||
// While it still matches, the copy names it (what a DWG round trip relies on).
|
||||
let mut same = String::new();
|
||||
let mut lines = text.lines();
|
||||
let mut var = String::new();
|
||||
while let (Some(c), Some(v)) = (lines.next(), lines.next()) {
|
||||
if c.trim() == "9" {
|
||||
var = v.trim().to_string();
|
||||
}
|
||||
let v = if var == "$UCSNAME" && c.trim() == "2" { String::new() } else { v.to_string() };
|
||||
same.push_str(&format!("{c}\n{v}\n"));
|
||||
}
|
||||
assert_eq!(cadcraft_io::read_dxf(same.as_bytes()).unwrap().header.str("UCSNAME", ""), "SITE");
|
||||
}
|
||||
|
||||
/// A layout's UCS far from the World origin keeps its name (and group 345) on an exact save, and
|
||||
/// loses both when the layout moves by 0.5 at 1e12, in the writer and in the reader.
|
||||
#[test]
|
||||
fn a_far_layout_ucs_keeps_its_name_only_where_it_is() {
|
||||
let far = Ucs { name: "FAR".into(), origin: Vec3::new(1e12, 0.0, 0.0), x_axis: Vec3::new(1.0, 0.0, 0.0), y_axis: Vec3::new(0.0, 1.0, 0.0) };
|
||||
let mut d = Drawing::default();
|
||||
d.ucss.push(far.clone());
|
||||
d.layouts[0].ucs = Some(far.clone());
|
||||
let name = d.layouts[0].name.clone();
|
||||
let text = cadcraft_io::write_dxf(&d);
|
||||
assert!(group(&layout_record(&text, &name), "345").is_some(), "exact save: pointed at FAR");
|
||||
assert_eq!(cadcraft_io::read_dxf(text.as_bytes()).unwrap().layouts[0].ucs.as_ref().unwrap().name, "FAR");
|
||||
// Writer: the layout moved 0.5 since it was named FAR.
|
||||
d.layouts[0].ucs = Some(Ucs { origin: Vec3::new(1e12 + 0.5, 0.0, 0.0), ..far.clone() });
|
||||
let moved = cadcraft_io::write_dxf(&d);
|
||||
assert!(group(&layout_record(&moved, &name), "345").is_none(), "moved 0.5 at 1e12: not FAR");
|
||||
assert!(cadcraft_io::read_dxf(moved.as_bytes()).unwrap().layouts[0].ucs.as_ref().unwrap().name.is_empty());
|
||||
// Reader: a file whose layout origin (group 13) moved but whose 345 still names FAR.
|
||||
let stale = replace_group(&text, ("1", &name), "13", "1000000000000.5");
|
||||
let u = cadcraft_io::read_dxf(stale.as_bytes()).unwrap().layouts[0].ucs.clone().unwrap();
|
||||
assert!(u.name.is_empty(), "{u:?}");
|
||||
}
|
||||
|
||||
/// The `*ACTIVE` VPORT record's group 74 (UCSICON setting) in DXF text.
|
||||
fn active_ucsicon(text: &str) -> Option<String> {
|
||||
let active = records(text, "VPORT").into_iter().find(|r| group(r, "2").is_some_and(|n| n.eq_ignore_ascii_case("*ACTIVE")))?;
|
||||
group(&active, "74").map(str::to_string)
|
||||
}
|
||||
|
||||
/// UCSICON is a setting of the drawing, kept in the active VPORT's group 74 (bit 1 the icon,
|
||||
/// bit 2 at the origin): icon off comes back off after a DXF save, and it is no header variable.
|
||||
#[test]
|
||||
fn ucsicon_survives_a_dxf_round_trip() {
|
||||
let mut d = Drawing::default();
|
||||
d.header.set_i64("UCSICON", 0);
|
||||
let text = cadcraft_io::write_dxf(&d);
|
||||
assert_eq!(active_ucsicon(&text).as_deref(), Some("0"), "written to the active VPORT");
|
||||
assert!(header_var(&text, "UCSICON").is_empty(), "not a header variable");
|
||||
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
assert_eq!(back.header.i64("UCSICON", 3), 0);
|
||||
// And a value with the origin bit only.
|
||||
d.header.set_i64("UCSICON", 2);
|
||||
let text = cadcraft_io::write_dxf(&d);
|
||||
assert_eq!(active_ucsicon(&text).as_deref(), Some("2"));
|
||||
assert_eq!(cadcraft_io::read_dxf(text.as_bytes()).unwrap().header.i64("UCSICON", 3), 2);
|
||||
}
|
||||
|
||||
/// A file whose `*ACTIVE` VPORT says 74 = 0 opens with the icon off.
|
||||
#[test]
|
||||
fn ucsicon_reads_from_the_active_vport_group_74() {
|
||||
let dxf = "0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n70\n1\n0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n1.0\n21\n1.0\n12\n6.0\n22\n4.5\n40\n9.0\n41\n1.6\n74\n0\n0\nENDTAB\n0\nENDSEC\n0\nEOF\n";
|
||||
let d = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap();
|
||||
assert_eq!(d.header.i64("UCSICON", 3), 0);
|
||||
let on = dxf.replace("74\n0\n", "74\n3\n");
|
||||
assert_eq!(cadcraft_io::read_dxf(on.as_bytes()).unwrap().header.i64("UCSICON", 3), 3);
|
||||
}
|
||||
@@ -534,16 +534,21 @@ fn paint_pointer_overlay(
|
||||
let view = frame.view;
|
||||
// Acquired tracking points and the polar / tracking paths under the cursor.
|
||||
if app.canvas.cursor.is_some() {
|
||||
draw_tracking(painter, &xf, &app.session.tracking.acquired, app.canvas.track.as_ref(), view.height * 4.0);
|
||||
draw_tracking(painter, &xf, &app.session.tracking.acquired, app.canvas.track.as_ref(), view.height * 4.0, app.session.input_ucs().rotation());
|
||||
}
|
||||
if let (Some(hit), Some(_)) = (app.canvas.snap, app.canvas.cursor) {
|
||||
draw_snap_marker(painter, xf.to_screen(hit.point), &hit);
|
||||
}
|
||||
draw_tiles(app, ui, tiles);
|
||||
// UCS icon, ViewCube and viewport label.
|
||||
if app.ui.show_ucs_icon {
|
||||
draw_ucs_icon(painter, rect);
|
||||
crate::viewcube::ucs_icon(app, ui, rect);
|
||||
if app.session.ucsicon_bits() & 1 != 0 {
|
||||
let place = crate::viewcube::IconPlace::of(app, rect, xf.twist, |p| xf.to_screen(p));
|
||||
draw_ucs_icon(painter, &place);
|
||||
// Clickable only at the Command prompt: while a command runs, a pick or a snap at the UCS
|
||||
// origin (where the icon may sit) reaches the drawing.
|
||||
if app.session.running.is_none() && app.session.pending_window.is_none() {
|
||||
crate::viewcube::ucs_icon(app, ui, rect, &place);
|
||||
}
|
||||
}
|
||||
if app.ui.show_viewcube && sheet.is_none() {
|
||||
draw_viewcube(app, ui, rect);
|
||||
|
||||
@@ -63,9 +63,23 @@ pub(super) fn draw_snap_marker(p: &egui::Painter, at: Pos2, hit: &SnapHit) {
|
||||
p.galley(r.min + vec2(3.0, 1.0), galley, Color32::BLACK);
|
||||
}
|
||||
|
||||
/// The whole degrees (0–359) a tracking tooltip shows for the path `from` → `to`, measured from
|
||||
/// the current UCS's X axis at `ucs` radians.
|
||||
pub(super) fn tooltip_angle(from: Vec2, to: Vec2, ucs: f64) -> i64 {
|
||||
((from.angle_to(to) - ucs).to_degrees().round() as i64).rem_euclid(360)
|
||||
}
|
||||
|
||||
/// Acquired tracking points (small `+`, `//` for a Parallel line), the dotted paths the cursor
|
||||
/// is on and the tooltip naming them ("Endpoint: 5.0000 < 90°").
|
||||
pub(super) fn draw_tracking(p: &egui::Painter, xf: &Xf, acquired: &[snap::tracking::Acquired], track: Option<&snap::tracking::Track>, far: f64) {
|
||||
/// `ucs`: the current UCS's X axis (radians), which the tooltips measure angles from.
|
||||
pub(super) fn draw_tracking(
|
||||
p: &egui::Painter,
|
||||
xf: &Xf,
|
||||
acquired: &[snap::tracking::Acquired],
|
||||
track: Option<&snap::tracking::Track>,
|
||||
far: f64,
|
||||
ucs: f64,
|
||||
) {
|
||||
use snap::tracking::{Acquired, PathShape};
|
||||
let t = Tokens::get();
|
||||
let st = Stroke::new(1.0, t.snap);
|
||||
@@ -100,10 +114,7 @@ pub(super) fn draw_tracking(p: &egui::Painter, xf: &Xf, acquired: &[snap::tracki
|
||||
}
|
||||
};
|
||||
p.extend(Shape::dotted_line(&pts, t.snap, 6.0, 1.0));
|
||||
let (distance, angle) = (
|
||||
cadcraft_engine::units::format_distance(path.from.dist(tr.point), 2, 4),
|
||||
(path.from.angle_to(tr.point).to_degrees().round() as i64).rem_euclid(360),
|
||||
);
|
||||
let (distance, angle) = (cadcraft_engine::units::format_distance(path.from.dist(tr.point), 2, 4), tooltip_angle(path.from, tr.point, ucs));
|
||||
tips.push(if path.name == "Polar" {
|
||||
crate::tf!("Polar: {distance} < {angle}°", distance = distance, angle = angle)
|
||||
} else {
|
||||
|
||||
@@ -11,7 +11,7 @@ fn prim_color32(prim: &cadcraft_render::DPrim, bg: Rgb) -> Color32 {
|
||||
Color32::from_rgba_unmultiplied(c.0, c.1, c.2, prim.alpha())
|
||||
}
|
||||
|
||||
fn clip_infinite(xf: &Xf, base: Vec2, dir: Vec2, ray: bool) -> Option<[Pos2; 2]> {
|
||||
pub(super) fn clip_infinite(xf: &Xf, base: Vec2, dir: Vec2, ray: bool) -> Option<[Pos2; 2]> {
|
||||
let wb = xf.world_bounds();
|
||||
let far = (wb.width() + wb.height()) * 2.0 + base.dist(wb.center());
|
||||
let a = if ray { base } else { base - dir * far };
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::draw::clip_infinite;
|
||||
use super::{Bounds2, CadApp, Shape, Stroke, Tokens, Vec2, Xf};
|
||||
|
||||
/// Grid spacing adapted to the zoom: multiply the unit until lines are at least `min_px` apart.
|
||||
@@ -34,14 +35,20 @@ pub(super) fn draw_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) {
|
||||
let unit = if s.gridunit.x == 0.0 { s.snapunit.x } else { s.gridunit.x };
|
||||
let minor = adaptive(unit, xf.scale, 8.0);
|
||||
let major = minor * major_n;
|
||||
// Keep the visible grid's checked ranges in the snap frame, then map its lines through
|
||||
// the UCS and the view (including its twist); the painter clips them to the viewport.
|
||||
let space = app.session.space();
|
||||
let (origin, angle) = app.session.doc().map(|d| cadcraft_engine::snap::grid_frame_in(d, &space)).unwrap_or((Vec2::ZERO, 0.0));
|
||||
let gb = Bounds2::from_points(wb.corners().map(|p| (p - origin).rotate(-angle)));
|
||||
let world = |p: Vec2| origin + p.rotate(angle);
|
||||
let mut lines = Vec::new();
|
||||
if let Some(((x0, x1), (y0, y1))) = grid_index_ranges(&wb, minor) {
|
||||
// World-aligned lines across the visible box (the painter clips them to the rect).
|
||||
if let Some(((x0, x1), (y0, y1))) = grid_index_ranges(&gb, minor) {
|
||||
// Snap-frame lines across the visible box.
|
||||
for i in x0..=x1 {
|
||||
let x = i as f64 * minor;
|
||||
let is_major = (x / major).round() * major - x == 0.0 || ((x / major) - (x / major).round()).abs() < 1e-6;
|
||||
lines.push(Shape::line_segment(
|
||||
[xf.to_screen(Vec2::new(x, wb.min.y)), xf.to_screen(Vec2::new(x, wb.max.y))],
|
||||
[xf.to_screen(world(Vec2::new(x, gb.min.y))), xf.to_screen(world(Vec2::new(x, gb.max.y)))],
|
||||
Stroke::new(1.0, if is_major { t.grid_major } else { t.grid_minor }),
|
||||
));
|
||||
}
|
||||
@@ -49,19 +56,20 @@ pub(super) fn draw_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) {
|
||||
let y = j as f64 * minor;
|
||||
let is_major = ((y / major) - (y / major).round()).abs() < 1e-6;
|
||||
lines.push(Shape::line_segment(
|
||||
[xf.to_screen(Vec2::new(wb.min.x, y)), xf.to_screen(Vec2::new(wb.max.x, y))],
|
||||
[xf.to_screen(world(Vec2::new(gb.min.x, y))), xf.to_screen(world(Vec2::new(gb.max.x, y)))],
|
||||
Stroke::new(1.0, if is_major { t.grid_major } else { t.grid_minor }),
|
||||
));
|
||||
}
|
||||
}
|
||||
p.extend(lines);
|
||||
}
|
||||
// Axes through the origin.
|
||||
if (wb.min.y..=wb.max.y).contains(&0.0) {
|
||||
p.line_segment([xf.to_screen(Vec2::new(wb.min.x, 0.0)), xf.to_screen(Vec2::new(wb.max.x, 0.0))], Stroke::new(1.0, t.axis_x));
|
||||
}
|
||||
if (wb.min.x..=wb.max.x).contains(&0.0) {
|
||||
p.line_segment([xf.to_screen(Vec2::new(0.0, wb.min.y)), xf.to_screen(Vec2::new(0.0, wb.max.y))], Stroke::new(1.0, t.axis_y));
|
||||
// The current UCS's X and Y axes through its origin.
|
||||
let u = app.session.input_ucs();
|
||||
let o = u.origin.xy();
|
||||
for (dir, color) in [(u.x.xy(), t.axis_x), (u.y.xy(), t.axis_y)] {
|
||||
if let Some(seg) = clip_infinite(xf, o, dir, false) {
|
||||
p.line_segment(seg, Stroke::new(1.0, color));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,7 +86,9 @@ fn draw_iso_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) {
|
||||
}
|
||||
d *= 5.0;
|
||||
}
|
||||
let (origin, angle) = app.session.doc().map(cadcraft_engine::snap::grid_frame).unwrap_or((Vec2::ZERO, 0.0));
|
||||
// In the current UCS (SNAPBASE from its origin, SNAPANG from its X axis).
|
||||
let space = app.session.space();
|
||||
let (origin, angle) = app.session.doc().map(|d| cadcraft_engine::snap::grid_frame_in(d, &space)).unwrap_or((Vec2::ZERO, 0.0));
|
||||
let lines = iso::grid_lines(xf.world_bounds(), d, origin, angle, s.gridmajor);
|
||||
p.extend(
|
||||
lines.into_iter().map(|l| {
|
||||
|
||||
@@ -1,6 +1,23 @@
|
||||
use super::cursor::tooltip_angle;
|
||||
use super::*;
|
||||
use cadcraft_render::DPrim;
|
||||
|
||||
/// Tracking tooltips give angles in the current UCS: a path along a UCS turned 30° reads 0°,
|
||||
/// one along World X reads 330°, and the World UCS reads world angles.
|
||||
#[test]
|
||||
fn tooltip_angles_are_measured_from_the_ucs_x_axis() {
|
||||
let o = Vec2::new(2.0, 1.0);
|
||||
let at = |deg: f64| o + Vec2::from_angle(deg.to_radians()) * 5.0;
|
||||
assert_eq!(tooltip_angle(o, at(90.0), 0.0), 90);
|
||||
assert_eq!(tooltip_angle(o, at(-45.0), 0.0), 315);
|
||||
let ucs = 30f64.to_radians();
|
||||
assert_eq!(tooltip_angle(o, at(30.0), ucs), 0);
|
||||
assert_eq!(tooltip_angle(o, at(0.0), ucs), 330);
|
||||
assert_eq!(tooltip_angle(o, at(120.0), ucs), 90);
|
||||
// A non-finite angle shows a number, not a panic.
|
||||
assert!((0..360).contains(&tooltip_angle(o, o, f64::NAN)));
|
||||
}
|
||||
|
||||
fn list(handles: &[u64]) -> DisplayList {
|
||||
let prim =
|
||||
|h| DPrim { handle: Handle(h), color: Rgb(255, 255, 255), aci7: true, lw: 0.0, transparency: 0, kind: Kind::Polyline, start: 0, len: 0 };
|
||||
|
||||
@@ -48,16 +48,23 @@ pub(super) fn draw_lock(p: &egui::Painter, c: Pos2, color: Color32) {
|
||||
));
|
||||
}
|
||||
|
||||
pub(super) fn draw_ucs_icon(p: &egui::Painter, rect: Rect) {
|
||||
/// The UCS icon: its X and Y arms along the current UCS's axes, with a square at the corner for
|
||||
/// the World UCS.
|
||||
pub(super) fn draw_ucs_icon(p: &egui::Painter, at: &crate::viewcube::IconPlace) {
|
||||
let t = Tokens::get();
|
||||
let o = pos2(rect.left() + 36.0, rect.bottom() - 34.0);
|
||||
let (o, x, y) = (at.origin, at.x, at.y);
|
||||
let arm = crate::viewcube::ARM;
|
||||
let st = Stroke::new(1.0, t.canvas_ink);
|
||||
p.line_segment([o, o + vec2(60.0, 0.0)], st);
|
||||
p.line_segment([o, o + vec2(0.0, -60.0)], st);
|
||||
p.rect_stroke(Rect::from_center_size(o, vec2(9.0, 9.0)), 0.0, st, egui::StrokeKind::Middle);
|
||||
p.line_segment([o, o + x * arm], st);
|
||||
p.line_segment([o, o + y * arm], st);
|
||||
if at.world {
|
||||
let h = 4.5;
|
||||
let square = vec![o + (x + y) * h, o + (x - y) * h, o - (x + y) * h, o - (x - y) * h];
|
||||
p.add(Shape::closed_line(square, st));
|
||||
}
|
||||
let f = egui::FontId::proportional(13.0);
|
||||
p.text(o + vec2(70.0, 0.0), egui::Align2::LEFT_CENTER, crate::tl!("X"), f.clone(), t.canvas_ink);
|
||||
p.text(o + vec2(0.0, -70.0), egui::Align2::CENTER_BOTTOM, crate::tl!("Y"), f, t.canvas_ink);
|
||||
p.text(o + x * (arm + 10.0), egui::Align2::CENTER_CENTER, crate::tl!("X"), f.clone(), t.canvas_ink);
|
||||
p.text(o + y * (arm + 10.0), egui::Align2::CENTER_CENTER, crate::tl!("Y"), f, t.canvas_ink);
|
||||
}
|
||||
|
||||
pub(super) fn viewport_label(p: &egui::Painter, rect: Rect) {
|
||||
@@ -68,15 +75,14 @@ pub(super) fn viewport_label(p: &egui::Painter, rect: Rect) {
|
||||
|
||||
pub(super) fn draw_viewcube(app: &mut CadApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let l = crate::viewcube::Layout::new(rect);
|
||||
let (c, ring) = (l.center, l.ring);
|
||||
let p = ui.painter_at(rect);
|
||||
crate::viewcube::show(app, ui, &l);
|
||||
// WCS pill: the label and a down chevron, drawn as lines rather than a "⌄" glyph that a UI
|
||||
// font may lack (it showed as a box, #1541).
|
||||
let pill = Rect::from_center_size(c + vec2(0.0, ring + 26.0), vec2(56.0, 16.0));
|
||||
// UCS pill: the current UCS's name and a down chevron, drawn as lines rather than a "⌄"
|
||||
// glyph that a UI font may lack (it showed as a box, #1541).
|
||||
let pill = l.pill;
|
||||
p.rect_filled(pill, 8.0, Color32::from_rgb(0x48, 0x50, 0x5c));
|
||||
let ink = Tokens::DARK.canvas_ink;
|
||||
let label = p.layout_no_wrap(crate::tl!("WCS").to_string(), crate::theme::small(), ink);
|
||||
let label = p.layout_no_wrap(ucs_pill_text(app), crate::theme::small(), ink);
|
||||
let (gap, chevron) = (4.0, 6.0);
|
||||
let left = pill.center().x - (label.size().x + gap + chevron) / 2.0;
|
||||
let mid = pill.center().y;
|
||||
@@ -84,3 +90,14 @@ pub(super) fn draw_viewcube(app: &mut CadApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let x = left + label.size().x + gap;
|
||||
p.line(vec![pos2(x, mid - 1.5), pos2(x + chevron / 2.0, mid + 1.5), pos2(x + chevron, mid - 1.5)], Stroke::new(1.2, ink));
|
||||
}
|
||||
|
||||
/// The ViewCube pill's label: WCS, or the current UCS's name (cut short); the menu arrow is drawn
|
||||
/// beside it as lines (#1541).
|
||||
fn ucs_pill_text(app: &CadApp) -> String {
|
||||
let (u, name) = app.session.ucs_named();
|
||||
if u.is_world() && name.is_empty() {
|
||||
return crate::tl!("WCS").to_string();
|
||||
}
|
||||
let n = if name.is_empty() { crate::tl!("Unnamed").to_string() } else { name };
|
||||
if n.chars().count() > 8 { n.chars().take(7).chain(std::iter::once('…')).collect() } else { n }
|
||||
}
|
||||
|
||||
@@ -381,8 +381,9 @@ pub fn status_bar(app: &mut CadApp, ui: &mut egui::Ui) {
|
||||
];
|
||||
let size = 20.0;
|
||||
let rx = r.right() - 8.0 - toggles.len() as f32 * (size + 4.0);
|
||||
// Coordinates.
|
||||
// Coordinates, in the current UCS.
|
||||
let coord = app.canvas.cursor.map(|c| {
|
||||
let c = app.session.ucs_point(c);
|
||||
let (lu, lp) = app.session.doc().map(|d| (d.header.i64("LUNITS", 2), d.header.i64("LUPREC", 4))).unwrap_or((2, 4));
|
||||
format!(
|
||||
"{}, {}, {}",
|
||||
|
||||
@@ -57,7 +57,8 @@ pub fn dyn_frame(app: &CadApp) -> Option<crate::dyninput::Frame> {
|
||||
return None;
|
||||
}
|
||||
let p = app.session.current_prompt().filter(cadcraft_engine::pointmod::accepts)?;
|
||||
Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute })
|
||||
let ucs = app.session.input_ucs();
|
||||
Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute, ucs })
|
||||
}
|
||||
|
||||
/// Take Tab away from egui before it moves keyboard focus to the next widget (which would leave
|
||||
|
||||
@@ -48,6 +48,8 @@ pub struct Frame {
|
||||
pub cartesian: bool,
|
||||
/// DYNPICOORDS = 1: second and next points are absolute instead of relative.
|
||||
pub absolute: bool,
|
||||
/// The UCS the boxes read and show values in (the engine reads the sent text in it too).
|
||||
pub ucs: cadcraft_engine::ucs::UcsFrame,
|
||||
}
|
||||
|
||||
impl Frame {
|
||||
@@ -55,10 +57,11 @@ impl Frame {
|
||||
pub fn default_format(&self) -> Format {
|
||||
if self.base.is_some() && !self.cartesian { Format::Polar } else { Format::Cartesian }
|
||||
}
|
||||
/// Where the typed values are measured from.
|
||||
/// Where the typed values are measured from, in UCS coordinates: the last point, or the UCS
|
||||
/// origin.
|
||||
pub fn origin(&self) -> Vec2 {
|
||||
match self.base {
|
||||
Some(b) if !self.absolute => b,
|
||||
Some(b) if !self.absolute => self.ucs.to_ucs(b),
|
||||
_ => Vec2::ZERO,
|
||||
}
|
||||
}
|
||||
@@ -67,9 +70,9 @@ impl Frame {
|
||||
self.base.is_some() && !self.absolute
|
||||
}
|
||||
|
||||
/// The live (X, Y) or (distance, angle in radians) of `cursor`.
|
||||
/// The live (X, Y) or (distance, angle in radians) of `cursor` (a world point), in the UCS.
|
||||
pub fn live(&self, format: Format, cursor: Vec2) -> (f64, f64) {
|
||||
let d = cursor - self.origin();
|
||||
let d = self.ucs.to_ucs(cursor) - self.origin();
|
||||
match format {
|
||||
Format::Cartesian => (d.x, d.y),
|
||||
Format::Polar => (d.len(), d.y.atan2(d.x)),
|
||||
@@ -145,32 +148,35 @@ pub fn can_lock_second(text: &str, frame: &Frame) -> bool {
|
||||
/// when Tab has locked the second one too (`second_locked`), which pins the cursor to the point.
|
||||
pub fn constrain(entry: &Entry<'_>, frame: &Frame, p: Vec2, second_locked: bool) -> Vec2 {
|
||||
let Some(v) = entry.first_locked() else { return p };
|
||||
let o = frame.origin();
|
||||
// In UCS coordinates; `p` and the result are world points.
|
||||
let (o, u) = (frame.origin(), frame.ucs.to_ucs(p));
|
||||
if second_locked && let Some(w) = entry.second_value() {
|
||||
let q = match entry.format {
|
||||
Format::Cartesian => o + Vec2::new(v, w),
|
||||
Format::Polar => o + Vec2::from_angle(w) * v,
|
||||
};
|
||||
if q.is_finite() {
|
||||
return q;
|
||||
return frame.ucs.to_wcs(q);
|
||||
}
|
||||
}
|
||||
match entry.format {
|
||||
Format::Cartesian => Vec2::new(o.x + v, p.y),
|
||||
let q = match entry.format {
|
||||
Format::Cartesian => Vec2::new(o.x + v, u.y),
|
||||
Format::Polar => {
|
||||
let d = p - o;
|
||||
let d = u - o;
|
||||
let l = d.len();
|
||||
let dir = if l > 1e-12 { d * (1.0 / l) } else { Vec2::X };
|
||||
o + dir * v
|
||||
}
|
||||
}
|
||||
};
|
||||
frame.ucs.to_wcs(q)
|
||||
}
|
||||
|
||||
/// The command-line text to send for a finished entry, or `None` to send the text as typed
|
||||
/// (nothing split yet: a plain number stays direct distance entry). Empty boxes take the cursor's
|
||||
/// value. Entries measured from the last point are sent with `@` when the prompt's base is the
|
||||
/// session's last point (`last`, what `@` resolves against); otherwise, and for absolute entries,
|
||||
/// the finished point is sent as `#x,y`, so what was previewed is exactly what is placed.
|
||||
/// the finished point is sent as `#x,y` (UCS coordinates), so what was previewed is exactly what
|
||||
/// is placed.
|
||||
pub fn complete(entry: &Entry<'_>, frame: &Frame, cursor: Vec2, last: Vec2) -> Option<String> {
|
||||
if !entry.split {
|
||||
return None;
|
||||
@@ -181,7 +187,8 @@ pub fn complete(entry: &Entry<'_>, frame: &Frame, cursor: Vec2, last: Vec2) -> O
|
||||
if frame.relative() && frame.base == Some(last) {
|
||||
return Some(match entry.format {
|
||||
Format::Cartesian => format!("@{first},{second}"),
|
||||
// `<<`: degrees from +X counterclockwise, as previewed, whatever ANGBASE/ANGDIR say.
|
||||
// `<<`: degrees from the UCS X axis counterclockwise, as previewed, whatever
|
||||
// ANGBASE/ANGDIR say.
|
||||
Format::Polar => format!("@{first}<<{}", second.to_degrees()),
|
||||
});
|
||||
}
|
||||
@@ -230,7 +237,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn second_point(base: Vec2) -> Frame {
|
||||
Frame { base: Some(base), cartesian: false, absolute: false }
|
||||
Frame { base: Some(base), cartesian: false, absolute: false, ..Frame::default() }
|
||||
}
|
||||
|
||||
fn sent(text: &str, frame: &Frame, cursor: Vec2, last: Vec2) -> Option<Vec2> {
|
||||
@@ -268,6 +275,44 @@ mod tests {
|
||||
assert_eq!(tab_separator("rec", &polar), None);
|
||||
}
|
||||
|
||||
/// `sent` with the engine reading the text in the frame's UCS, as the command line does.
|
||||
fn sent_in(text: &str, frame: &Frame, cursor: Vec2, last: Vec2) -> Option<Vec2> {
|
||||
let e = parse(text, frame)?;
|
||||
let t = complete(&e, frame, cursor, last)?;
|
||||
let angles = cadcraft_engine::units::AngleSettings { ucs: frame.ucs.rotation(), ..Default::default() };
|
||||
cadcraft_engine::prompt::parse_point_in(&t, last, &angles, &frame.ucs)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_boxes_read_and_show_values_in_the_ucs() {
|
||||
// The UCS at (100, 50) turned 90°: UCS X is world +Y.
|
||||
let ucs =
|
||||
cadcraft_engine::ucs::UcsFrame::WORLD.with_origin(cadcraft_geom::Vec3::new(100.0, 50.0, 0.0)).rotated_z(std::f64::consts::FRAC_PI_2);
|
||||
let first = Frame { ucs, ..Frame::default() };
|
||||
assert!(close(sent_in("10,0", &first, Vec2::ZERO, Vec2::ZERO), Vec2::new(100.0, 60.0)), "absolute: from the UCS origin");
|
||||
let base = Vec2::new(100.0, 60.0);
|
||||
let f = Frame { base: Some(base), ucs, ..Frame::default() };
|
||||
assert!(close(sent_in("5,0", &f, Vec2::ZERO, base), Vec2::new(100.0, 65.0)), "relative along the UCS axes");
|
||||
assert!(close(sent_in("10<0", &f, Vec2::ZERO, base), Vec2::new(100.0, 70.0)), "angles from the UCS X axis");
|
||||
assert!(close(sent_in("10<90", &f, Vec2::ZERO, base), Vec2::new(90.0, 60.0)));
|
||||
// Not relative to the last point: sent as `#x,y` in the UCS, placed where it was previewed.
|
||||
assert!(close(sent_in("5,0", &f, Vec2::ZERO, Vec2::new(-1.0, -1.0)), Vec2::new(100.0, 65.0)));
|
||||
let abs = Frame { absolute: true, cartesian: true, ..f };
|
||||
assert!(close(sent_in("10,5", &abs, Vec2::ZERO, base), Vec2::new(95.0, 60.0)));
|
||||
// The live values are the cursor's, measured in the UCS.
|
||||
let (x, y) = f.live(Format::Cartesian, Vec2::new(97.0, 70.0));
|
||||
assert!((x - 10.0).abs() < 1e-9 && (y - 3.0).abs() < 1e-9, "{x} {y}");
|
||||
let (d, a) = f.live(Format::Polar, Vec2::new(100.0, 70.0));
|
||||
assert!((d - 10.0).abs() < 1e-9 && a.abs() < 1e-9, "{d} {a}");
|
||||
// A locked value holds the cursor along the UCS axes, and Enter sends that point.
|
||||
let e = parse("3,", &f).unwrap();
|
||||
let held = constrain(&e, &f, Vec2::new(80.0, 99.0), false);
|
||||
assert!(close(Some(held), Vec2::new(80.0, 63.0)), "{held:?}");
|
||||
assert!(close(sent_in("3,", &f, Vec2::new(80.0, 99.0), base), Vec2::new(80.0, 63.0)));
|
||||
let e = parse("4<", &f).unwrap();
|
||||
assert!(close(Some(constrain(&e, &f, Vec2::new(100.0, 90.0), false)), Vec2::new(100.0, 64.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_point_is_absolute() {
|
||||
let f = Frame::default();
|
||||
@@ -276,7 +321,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn absolute_setting_measures_from_the_origin() {
|
||||
let f = Frame { base: Some(Vec2::new(5.0, 5.0)), cartesian: true, absolute: true };
|
||||
let f = Frame { base: Some(Vec2::new(5.0, 5.0)), cartesian: true, absolute: true, ..Frame::default() };
|
||||
assert!(close(sent("40,100", &f, Vec2::ZERO, Vec2::new(5.0, 5.0)), Vec2::new(40.0, 100.0)));
|
||||
}
|
||||
|
||||
|
||||
@@ -309,8 +309,8 @@ mod tests {
|
||||
for cartesian in [true, false] {
|
||||
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
|
||||
app.session.settings.dynpi_cartesian = cartesian;
|
||||
// The UCS icon paints "X" and "Y" too.
|
||||
app.ui.show_ucs_icon = false;
|
||||
// The UCS icon paints "X" and "Y" too: off (UCSICON, which the drawing keeps).
|
||||
app.run("ucsicon", serde_json::json!({"on": false})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
crate::canvas::tests::painted_text(&mut app, &ctx, pos2(700.0, 450.0));
|
||||
let at = app.canvas.xf.unwrap().to_screen(Vec2::ZERO) + vec2(130.0, -70.0);
|
||||
|
||||
@@ -1356,6 +1356,14 @@
|
||||
Justify За шириною
|
||||
Text color Колір тексту
|
||||
Click the ruler to add a tab stop, right-click to remove one Натисніть на лінійку, щоб додати табуляцію; права кнопка видаляє її
|
||||
3 Point 3 точки
|
||||
New UCS Нова СКК
|
||||
Origin Початок координат
|
||||
UCS СКК
|
||||
UCS Icon at Origin Піктограма СКК на початку координат
|
||||
World Світова
|
||||
Z Z
|
||||
Unnamed Без назви
|
||||
Select using two clicks only Вибирати лише двома клацаннями
|
||||
Define each corner of the selection window with a separate click. Задайте кожен кут рамки вибору окремим клацанням.
|
||||
Type an alias name. Введіть назву псевдоніма.
|
||||
|
||||
|
@@ -1503,6 +1503,13 @@ menu Dimension 标注
|
||||
menu Draw 绘图
|
||||
menu Modify 修改
|
||||
menu View 视图
|
||||
3 Point 三点
|
||||
New UCS 新建 UCS
|
||||
Origin 原点
|
||||
UCS UCS
|
||||
UCS Icon at Origin 原点处的 UCS 图标
|
||||
World 世界
|
||||
Z Z
|
||||
Clip Xref 剪裁外部参照
|
||||
Xref 外部参照
|
||||
Xref Clip Frame 外部参照剪裁边框
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1472 and column 24.
|
@@ -103,7 +103,6 @@ pub struct UiState {
|
||||
pub show_status_bar: bool,
|
||||
pub show_command_line: bool,
|
||||
pub show_viewcube: bool,
|
||||
pub show_ucs_icon: bool,
|
||||
pub show_layer_list: bool,
|
||||
/// Keep the system cursor visible over the drawing area (a small crosshair at the centre of the
|
||||
/// drawn one) instead of hiding it. Screen magnifiers (Windows Magnifier "follow the mouse
|
||||
@@ -201,7 +200,6 @@ impl Default for UiState {
|
||||
show_status_bar: true,
|
||||
show_command_line: true,
|
||||
show_viewcube: true,
|
||||
show_ucs_icon: true,
|
||||
show_layer_list: false,
|
||||
system_cursor: false,
|
||||
toolset_tab: "Drafting".into(),
|
||||
|
||||
@@ -102,6 +102,7 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
|
||||
("ui.toggle.cmdline", "Command Line", &["Window", "Command Line"], Some("Cmd+9")),
|
||||
("ui.toggle.viewcube", "ViewCube", &["View", "ViewCube", "On"], None),
|
||||
("ui.toggle.ucsicon", "UCS Icon", &["View", "UCS Icon", "On"], None),
|
||||
("ui.toggle.ucsicon.origin", "UCS Icon at Origin", &["View", "UCS Icon", "Origin"], None),
|
||||
("ui.theme.system", "Use System Setting", &["View", "Interface Theme", "Use System Setting"], None),
|
||||
("ui.theme.light", "Light", &["View", "Interface Theme", "Light"], None),
|
||||
("ui.theme.dark", "Dark", &["View", "Interface Theme", "Dark"], None),
|
||||
@@ -307,9 +308,16 @@ fn run_ui_toggle_command(app: &mut CadApp, id: &str, params: &Value) -> Option<R
|
||||
toggle(&mut app.ui.show_viewcube, params);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"ui.toggle.ucsicon" => {
|
||||
toggle(&mut app.ui.show_ucs_icon, params);
|
||||
Ok(Value::Null)
|
||||
// UCSICON's bits, through its command: 1 shown, 2 at the UCS origin.
|
||||
"ui.toggle.ucsicon" | "ui.toggle.ucsicon.origin" => {
|
||||
// The icon is a setting of the drawing: with none open there is nothing to toggle.
|
||||
if app.session.doc().is_err() {
|
||||
return Some(Err("No drawing open.".into()));
|
||||
}
|
||||
let (key, bit) = if id == "ui.toggle.ucsicon" { ("on", 1) } else { ("origin", 2) };
|
||||
let mut on = app.session.ucsicon_bits() & bit != 0;
|
||||
toggle(&mut on, params);
|
||||
app.run("ucsicon", json!({ key: on }))
|
||||
}
|
||||
"ui.toggle.menubar" => {
|
||||
toggle(&mut app.ui.in_window_menu, params);
|
||||
@@ -692,7 +700,9 @@ pub fn tree(app: &CadApp) -> Vec<(String, Vec<Entry>)> {
|
||||
}
|
||||
for (id, label, menu, sc) in UI_COMMANDS {
|
||||
if !menu.is_empty() {
|
||||
add(menu, label, id, *sc, true);
|
||||
// The UCS icon is a setting of the drawing: off the menu's reach when none is open.
|
||||
let enabled = !id.starts_with("ui.toggle.ucsicon") || app.session.doc().is_ok();
|
||||
add(menu, label, id, *sc, enabled);
|
||||
}
|
||||
}
|
||||
if let Some((_, file)) = out.iter_mut().find(|(m, _)| m == "File") {
|
||||
|
||||
+241
-28
@@ -1,14 +1,14 @@
|
||||
//! The navigation overlays on the drawing area: the ViewCube (Top face, Home, compass ring and
|
||||
//! the WCS menu) and the UCS icon.
|
||||
//! the UCS menu) and the UCS icon.
|
||||
//!
|
||||
//! Every overlay registers a widget that senses clicks *and* drags, so egui hands the pointer to
|
||||
//! the overlay instead of the canvas underneath (a click on the ViewCube must never also pick or
|
||||
//! start a selection window in the drawing). What the overlays do goes through commands:
|
||||
//! `zoom.extents` (Top face, Home), `ui.toggle.viewcube`, `ui.toggle.ucsicon`.
|
||||
//! `zoom.extents` (Top face, Home), `ui.toggle.viewcube`, `ui.toggle.ucsicon`, `ucs`.
|
||||
//!
|
||||
//! CADCraft's model view is a 2D plan view of the World Coordinate System: there is no view
|
||||
//! twist, no 3D view direction and no user coordinate system yet, so the compass ring explains
|
||||
//! that instead of rotating, and the WCS menu lists the only coordinate system there is.
|
||||
//! CADCraft's model view is a 2D plan view: there is no view twist and no 3D view direction yet,
|
||||
//! so the compass ring explains that instead of rotating. The UCS menu lists World and the
|
||||
//! drawing's named UCSs.
|
||||
|
||||
use egui::{Color32, CursorIcon, Pos2, Rect, Sense, Stroke, pos2, vec2};
|
||||
use serde_json::json;
|
||||
@@ -42,7 +42,7 @@ impl Layout {
|
||||
ring,
|
||||
face: Rect::from_center_size(center, vec2(44.0, 44.0)),
|
||||
home: Rect::from_center_size(center + vec2(-ring + 2.0, -ring + 2.0), vec2(20.0, 20.0)),
|
||||
pill: Rect::from_center_size(center + vec2(0.0, ring + 26.0), vec2(56.0, 16.0)),
|
||||
pill: Rect::from_center_size(center + vec2(0.0, ring + 26.0), vec2(84.0, 16.0)),
|
||||
bounds: Rect::from_center_size(center, vec2(2.0 * (ring + 10.0), 2.0 * (ring + 10.0))),
|
||||
}
|
||||
}
|
||||
@@ -131,7 +131,8 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, l: &Layout) {
|
||||
if let Some((id, params)) = action {
|
||||
let _ = app.run(id, params);
|
||||
}
|
||||
// The WCS pill (painted by the canvas) opens the coordinate-system menu.
|
||||
// The UCS pill (painted by the canvas, wide enough for a cut-short UCS name) opens the
|
||||
// coordinate-system menu.
|
||||
let pill = ui.interact(l.pill, ui.scope_id().with("viewcube_wcs"), Sense::click_and_drag()).on_hover_cursor(CursorIcon::PointingHand);
|
||||
let pill = pill.on_hover_text("Coordinate system");
|
||||
ucs_menu(app, egui::Popup::menu(&pill));
|
||||
@@ -153,48 +154,164 @@ fn paint_home(p: &egui::Painter, r: Rect, hot: bool) {
|
||||
p.line_segment([c + vec2(-1.2, 2.5), c + vec2(1.2, 2.5)], st);
|
||||
}
|
||||
|
||||
/// The UCS icon's arms (as drawn by the canvas at the lower-left corner): the X arm and the Y arm.
|
||||
pub fn ucs_arms(canvas: Rect) -> [Rect; 2] {
|
||||
let o = pos2(canvas.left() + 36.0, canvas.bottom() - 34.0);
|
||||
[Rect::from_min_max(o + vec2(-8.0, -8.0), o + vec2(80.0, 8.0)), Rect::from_min_max(o + vec2(-8.0, -82.0), o + vec2(8.0, 8.0))]
|
||||
/// How long the UCS icon's arms are, in points.
|
||||
pub const ARM: f32 = 60.0;
|
||||
/// How far past an arm's end its X or Y label reaches, in points.
|
||||
const LABEL: f32 = 16.0;
|
||||
/// How close to an arm a pointer counts as on the icon, in points.
|
||||
const HIT: f32 = 8.0;
|
||||
|
||||
/// Where the UCS icon is drawn: the point its arms start from, the screen directions of its X
|
||||
/// and Y arms (unit vectors: the current UCS's axes seen in the plan view) and whether the UCS is
|
||||
/// the World UCS (the icon then has a square at its corner).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct IconPlace {
|
||||
pub origin: Pos2,
|
||||
pub x: egui::Vec2,
|
||||
pub y: egui::Vec2,
|
||||
pub world: bool,
|
||||
}
|
||||
|
||||
impl IconPlace {
|
||||
/// The World UCS's icon at the lower-left corner of the drawing area.
|
||||
pub fn corner(canvas: Rect) -> IconPlace {
|
||||
IconPlace { origin: pos2(canvas.left() + 36.0, canvas.bottom() - 34.0), x: vec2(1.0, 0.0), y: vec2(0.0, -1.0), world: true }
|
||||
}
|
||||
|
||||
/// The icon for the current UCS: at its origin when UCSICON asks for that (ORigin) and the
|
||||
/// whole icon fits there, else at the corner. `to_screen` maps a point of the space shown, and
|
||||
/// `twist` is the view's twist (radians counterclockwise, `Xf::twist`).
|
||||
pub fn of(app: &CadApp, canvas: Rect, twist: f64, to_screen: impl Fn(cadcraft_geom::Vec2) -> Pos2) -> IconPlace {
|
||||
let u = app.session.input_ucs();
|
||||
// An axis as the screen shows it: a twisted view (DVIEW TWist) turns the arms too.
|
||||
let dir = |v: cadcraft_geom::Vec3, or: egui::Vec2| {
|
||||
let t = if twist.is_finite() && twist != 0.0 { v.xy().rotate(twist) } else { v.xy() };
|
||||
let d = vec2(t.x as f32, -(t.y as f32));
|
||||
let l = d.length();
|
||||
if l.is_finite() && l > 1e-6 { d / l } else { or }
|
||||
};
|
||||
let mut place = IconPlace::corner_turned(canvas, dir(u.x, vec2(1.0, 0.0)), dir(u.y, vec2(0.0, -1.0)), u.is_world());
|
||||
// At the origin only where the screen shows the space the UCS belongs to (not from paper
|
||||
// space into an active viewport).
|
||||
let same_space = app.session.space() == app.session.layout_space();
|
||||
if app.session.ucsicon_bits() & 2 != 0 && same_space {
|
||||
let at = to_screen(u.origin.xy());
|
||||
let reach = ARM + LABEL;
|
||||
let inner = canvas.shrink(12.0);
|
||||
if [at, at + place.x * reach, at + place.y * reach].iter().all(|p| p.x.is_finite() && p.y.is_finite() && inner.contains(*p)) {
|
||||
place.origin = at;
|
||||
}
|
||||
}
|
||||
place
|
||||
}
|
||||
|
||||
/// The icon with arms along `x` and `y` at the lower-left corner: placed so the arms and their
|
||||
/// labels take the corner the World UCS's icon does, whichever way they point.
|
||||
pub fn corner_turned(canvas: Rect, x: egui::Vec2, y: egui::Vec2, world: bool) -> IconPlace {
|
||||
let home = IconPlace::corner(canvas).origin;
|
||||
let reach = ARM + LABEL;
|
||||
let (ends_x, ends_y) = ([0.0, x.x * reach, y.x * reach], [0.0, x.y * reach, y.y * reach]);
|
||||
// The World icon's arms run right and up from `home`: shift so the turned arms' left and
|
||||
// bottom edges sit where those do.
|
||||
let left = ends_x.iter().copied().fold(0.0f32, f32::min);
|
||||
let bottom = ends_y.iter().copied().fold(0.0f32, f32::max);
|
||||
let origin = pos2(home.x - left, home.y - bottom);
|
||||
IconPlace { origin: if origin.x.is_finite() && origin.y.is_finite() { origin } else { home }, x, y, world }
|
||||
}
|
||||
|
||||
/// The icon's arms out to their labels: the X arm and the Y arm, as screen segments.
|
||||
pub fn arms(&self) -> [[Pos2; 2]; 2] {
|
||||
let o = self.origin;
|
||||
[[o, o + self.x * (ARM + 20.0)], [o, o + self.y * (ARM + 22.0)]]
|
||||
}
|
||||
|
||||
/// Whether `p` is on the icon: within [`HIT`] of an arm (labels included), not merely in the
|
||||
/// box around a turned arm.
|
||||
pub fn hit(&self, p: Pos2) -> bool {
|
||||
self.arms().iter().any(|[a, b]| {
|
||||
let ab = *b - *a;
|
||||
let t = if ab.length_sq() > 0.0 { ((p - *a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(*a + ab * t - p).length() <= HIT
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// How the current UCS is named on screen.
|
||||
fn ucs_label(app: &CadApp) -> String {
|
||||
let (u, name) = app.session.ucs_named();
|
||||
if u.is_world() && name.is_empty() {
|
||||
"World Coordinate System".into()
|
||||
} else if name.is_empty() {
|
||||
"Unnamed UCS".into()
|
||||
} else {
|
||||
name
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the UCS icon clickable: hovering highlights it, a click (either button) opens the
|
||||
/// coordinate-system menu.
|
||||
pub fn ucs_icon(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) {
|
||||
pub fn ucs_icon(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect, place: &IconPlace) {
|
||||
let t = Tokens::get();
|
||||
let [x, y] = ucs_arms(canvas);
|
||||
let rx = ui.interact(x, ui.scope_id().with("ucs_x"), Sense::click_and_drag());
|
||||
let ry = ui.interact(y, ui.scope_id().with("ucs_y"), Sense::click_and_drag());
|
||||
let resp = (rx | ry).on_hover_cursor(CursorIcon::PointingHand).on_hover_text("UCS icon: World Coordinate System");
|
||||
if resp.hovered() {
|
||||
let o = pos2(x.left() + 8.0, x.center().y);
|
||||
// The arms' boxes, but only a pointer near an arm takes clicks (a turned arm's box is mostly
|
||||
// drawing). The widget stays every frame so its menu, once open, keeps its anchor.
|
||||
let near = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| place.hit(p));
|
||||
let sense = if near { Sense::click_and_drag() } else { Sense::hover() };
|
||||
let [x, y] = place.arms().map(|[a, b]| Rect::from_two_pos(a, b).expand(HIT));
|
||||
let rx = ui.interact(x, ui.scope_id().with("ucs_x"), sense);
|
||||
let ry = ui.interact(y, ui.scope_id().with("ucs_y"), sense);
|
||||
let mut resp = rx | ry;
|
||||
if near {
|
||||
resp = resp.on_hover_cursor(CursorIcon::PointingHand).on_hover_text(format!("UCS icon: {}", ucs_label(app)));
|
||||
}
|
||||
if near && resp.hovered() {
|
||||
let o = place.origin;
|
||||
let st = Stroke::new(2.0, t.hover);
|
||||
let p = ui.painter_at(canvas);
|
||||
p.line_segment([o, o + vec2(60.0, 0.0)], st);
|
||||
p.line_segment([o, o + vec2(0.0, -60.0)], st);
|
||||
p.line_segment([o, o + place.x * ARM], st);
|
||||
p.line_segment([o, o + place.y * ARM], st);
|
||||
}
|
||||
// Opened with `Bool(true)`: a pointer-anchored popup records its position only then.
|
||||
let open = (resp.clicked() || resp.secondary_clicked()).then_some(egui::SetOpenCommand::Bool(true));
|
||||
ucs_menu(app, egui::Popup::menu(&resp).open_memory(open).at_pointer_fixed());
|
||||
}
|
||||
|
||||
/// The coordinate-system menu: the WCS (the only coordinate system so far) and the icon switch.
|
||||
/// The coordinate-system menu: World, the drawing's named UCSs (picking one makes it current,
|
||||
/// through the UCS command) and the icon switch.
|
||||
fn ucs_menu(app: &mut CadApp, popup: egui::Popup<'_>) {
|
||||
let mut hide = false;
|
||||
let (u, current) = app.session.ucs_named();
|
||||
let names: Vec<String> = app.session.doc().map(|d| d.ucss.iter().map(|u| u.name.clone()).collect()).unwrap_or_default();
|
||||
let mut action: Option<(&str, serde_json::Value)> = None;
|
||||
popup.show(|ui| {
|
||||
ui.radio(true, "World (WCS)").on_hover_text("CADCraft draws in the World Coordinate System; user coordinate systems aren't available yet.");
|
||||
if ui.radio(u.is_world() && current.is_empty(), "World (WCS)").clicked() {
|
||||
action = Some(("ucs.world", json!({})));
|
||||
ui.close();
|
||||
}
|
||||
for n in &names {
|
||||
if ui.radio(current.eq_ignore_ascii_case(n), n.as_str()).clicked() {
|
||||
action = Some(("ucs", json!({"option": "named", "action": "restore", "name": n})));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
if !u.is_world() && current.is_empty() {
|
||||
let _ = ui.radio(true, "Unnamed");
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("Hide UCS Icon").clicked() {
|
||||
hide = true;
|
||||
action = Some(("ui.toggle.ucsicon", json!({"on": false})));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
if hide {
|
||||
let _ = app.run("ui.toggle.ucsicon", json!({"on": false}));
|
||||
if let Some((id, params)) = action {
|
||||
menu_action(app, id, params);
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a coordinate-system menu pick. A failure is already in the command history:
|
||||
/// [`CadApp::run`] echoes it (and the icon switch runs UCSICON through it).
|
||||
fn menu_action(app: &mut CadApp, id: &str, params: serde_json::Value) {
|
||||
let _ = app.run(id, params);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -238,6 +355,22 @@ mod tests {
|
||||
app.canvas.rect.unwrap_or(Rect::NOTHING)
|
||||
}
|
||||
|
||||
/// A menu pick that fails (a tilted named UCS) tells the user once, not twice.
|
||||
#[test]
|
||||
fn a_failed_menu_pick_is_reported_once() {
|
||||
let (mut app, _ctx) = app_and_ctx();
|
||||
let tilted = cadcraft_engine::doc::Ucs {
|
||||
name: "T".into(),
|
||||
origin: cadcraft_engine::geom::Vec3::ZERO,
|
||||
x_axis: cadcraft_engine::geom::Vec3::new(1.0, 0.0, 0.0),
|
||||
y_axis: cadcraft_engine::geom::Vec3::new(0.0, 0.0, 1.0),
|
||||
};
|
||||
app.session.doc_mut().unwrap().ucss.push(tilted);
|
||||
menu_action(&mut app, "ucs", json!({"option": "named", "action": "restore", "name": "T"}));
|
||||
let told = app.session.log.iter().filter(|l| l.contains("tilted out of the XY plane")).count();
|
||||
assert_eq!(told, 1, "{:?}", app.session.log);
|
||||
}
|
||||
|
||||
fn view(app: &CadApp) -> (f64, f64, f64) {
|
||||
let v = app.session.state().map(|s| s.view()).unwrap_or_default();
|
||||
(v.center.x, v.center.y, v.height)
|
||||
@@ -281,11 +414,91 @@ mod tests {
|
||||
assert!(app.session.pending_window.is_some(), "an empty-space click starts a selection window");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ucs_icon_follows_the_ucs() {
|
||||
let (mut app, _ctx) = app_and_ctx();
|
||||
let c = canvas(&app);
|
||||
// A plain mapping: the canvas centre is world (0, 0), one point per unit.
|
||||
let to_screen = |p: cadcraft_geom::Vec2| pos2(c.center().x + p.x as f32, c.center().y - p.y as f32);
|
||||
let world = IconPlace::of(&app, c, 0.0, to_screen);
|
||||
assert!(world.world && (world.x - vec2(1.0, 0.0)).length() < 1e-6 && (world.y - vec2(0.0, -1.0)).length() < 1e-6);
|
||||
// At the World origin (on screen, with ORigin on by default).
|
||||
assert!((world.origin - c.center()).length() < 1e-3, "{:?} vs {:?}", world.origin, c.center());
|
||||
// A view twisted 90° (DVIEW TWist) turns the arms with the drawing: world X points up.
|
||||
let twisted = IconPlace::of(&app, c, std::f64::consts::FRAC_PI_2, to_screen);
|
||||
assert!((twisted.x - vec2(0.0, -1.0)).length() < 1e-6 && (twisted.y - vec2(-1.0, 0.0)).length() < 1e-6, "{twisted:?}");
|
||||
// A UCS turned 90° at (20, 10): the X arm points up the screen, the Y arm left.
|
||||
app.run("ucs", json!({"option": "origin", "origin": [20, 10]})).unwrap();
|
||||
app.run("ucs", json!({"option": "z", "angle": 90})).unwrap();
|
||||
let p = IconPlace::of(&app, c, 0.0, to_screen);
|
||||
assert!(!p.world);
|
||||
assert!((p.x - vec2(0.0, -1.0)).length() < 1e-6 && (p.y - vec2(-1.0, 0.0)).length() < 1e-6, "{p:?}");
|
||||
assert!((p.origin - pos2(c.center().x + 20.0, c.center().y - 10.0)).length() < 1e-3);
|
||||
// Its click areas lie along the turned arms.
|
||||
assert!(p.hit(p.origin + p.x * 40.0) && p.hit(p.origin + p.y * 40.0));
|
||||
// Noorigin, or an origin off screen: the corner, the turned icon in the World icon's place.
|
||||
let corner = IconPlace::corner_turned(c, p.x, p.y, false).origin;
|
||||
app.run("ucsicon", json!({"origin": false})).unwrap();
|
||||
assert_eq!(IconPlace::of(&app, c, 0.0, to_screen).origin, corner);
|
||||
app.run("ucsicon", json!({"origin": true})).unwrap();
|
||||
app.run("ucs", json!({"option": "origin", "origin": [1e6, 0]})).unwrap();
|
||||
assert_eq!(IconPlace::of(&app, c, 0.0, to_screen).origin, corner);
|
||||
app.run("ucs", json!({"option": "world"})).unwrap();
|
||||
app.run("ucs", json!({"option": "origin", "origin": [1e6, 0]})).unwrap();
|
||||
assert_eq!(IconPlace::of(&app, c, 0.0, to_screen).origin, IconPlace::corner(c).origin, "unturned: where it always was");
|
||||
// The menu switch turns UCSICON off through its command.
|
||||
app.run("ui.toggle.ucsicon", json!({"on": false})).unwrap();
|
||||
assert_eq!(app.session.ucsicon_bits() & 1, 0);
|
||||
app.run("ui.toggle.ucsicon", json!({})).unwrap();
|
||||
assert_eq!(app.session.ucsicon_bits() & 1, 1, "a toggle without `on` flips it");
|
||||
app.run("ui.toggle.ucsicon.origin", json!({"on": false})).unwrap();
|
||||
assert_eq!(app.session.ucsicon_bits(), 1);
|
||||
}
|
||||
|
||||
/// At the corner, a turned icon's arms and labels stay on the canvas at every angle, inside
|
||||
/// the World icon's corner box.
|
||||
#[test]
|
||||
fn a_turned_corner_icon_stays_on_the_canvas() {
|
||||
let c = Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0));
|
||||
let home = IconPlace::corner(c).origin;
|
||||
let reach = ARM + LABEL;
|
||||
let (box_left, box_bottom) = (home.x, home.y);
|
||||
for deg in (0..360).step_by(15) {
|
||||
let a = (deg as f32).to_radians();
|
||||
// Screen y runs down: the Y arm is the X arm turned a quarter counterclockwise on screen.
|
||||
let (x, y) = (vec2(a.cos(), -a.sin()), vec2(-a.sin(), -a.cos()));
|
||||
let p = IconPlace::corner_turned(c, x, y, false);
|
||||
for end in [p.origin, p.origin + x * reach, p.origin + y * reach] {
|
||||
assert!(c.contains(end), "{deg}°: {end:?} off {c:?}");
|
||||
assert!(end.x >= box_left - 1e-3 && end.y <= box_bottom + 1e-3, "{deg}°: {end:?}");
|
||||
}
|
||||
}
|
||||
// Unturned, exactly where the World icon always was.
|
||||
assert_eq!(IconPlace::corner_turned(c, vec2(1.0, 0.0), vec2(0.0, -1.0), true).origin, home);
|
||||
}
|
||||
|
||||
/// Only a pointer near an arm is on the icon: on a 45° UCS the corner of the arm's box, well
|
||||
/// away from the arm, is drawing.
|
||||
#[test]
|
||||
fn ucs_icon_hits_follow_the_arms_not_their_boxes() {
|
||||
let s = std::f32::consts::FRAC_1_SQRT_2;
|
||||
let p = IconPlace { origin: pos2(200.0, 200.0), x: vec2(s, -s), y: vec2(-s, -s), world: false };
|
||||
assert!(p.hit(p.origin) && p.hit(p.origin + p.x * 50.0) && p.hit(p.origin + p.y * (ARM + 20.0)));
|
||||
assert!(p.hit(p.origin + p.x * 30.0 + p.y * 7.0), "within reach of the X arm");
|
||||
// The X arm's box spans 200..257 across; its far corner is 40 points from the arm.
|
||||
let box_corner = pos2(200.0 + (ARM + 20.0) * s, 200.0);
|
||||
assert!(!p.hit(box_corner), "{box_corner:?}");
|
||||
assert!(!p.hit(p.origin + p.x * (ARM + 40.0)), "past the label");
|
||||
assert!(!p.hit(pos2(f32::NAN, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ucs_icon_and_wcs_pill_open_the_coordinate_system_menu() {
|
||||
let (mut app, ctx) = app_and_ctx();
|
||||
let [x, _] = ucs_arms(canvas(&app));
|
||||
click(&mut app, &ctx, x.center(), egui::PointerButton::Primary);
|
||||
// Where the canvas drew it: at the World origin when that is on screen (UCSICON 3).
|
||||
let xf = app.canvas.xf.expect("laid out");
|
||||
let place = IconPlace::of(&app, canvas(&app), xf.twist, |p| xf.to_screen(p));
|
||||
click(&mut app, &ctx, place.origin + place.x * 40.0, egui::PointerButton::Primary);
|
||||
assert!(menu_shown(&ctx), "UCS icon menu");
|
||||
assert!(app.session.pending_window.is_none(), "the click stayed on the icon");
|
||||
let l = Layout::new(canvas(&app));
|
||||
|
||||
@@ -27,10 +27,10 @@ impl Canvas {
|
||||
session.execute("view.set", &json!({"center": [100, 100], "height": 400})).unwrap();
|
||||
session.settings.gridmode = false;
|
||||
session.settings.dynmode = false;
|
||||
session.execute("ucsicon", &json!({"on": false})).unwrap();
|
||||
let mut app = CadApp::new(session, Services::default());
|
||||
app.canvas.zoom_pending = false;
|
||||
app.ui.show_command_line = false;
|
||||
app.ui.show_ucs_icon = false;
|
||||
app.ui.show_viewcube = false;
|
||||
app.run("options", json!({"theme": "dark", "systemCursor": false, "PICKBOX": 4, "SELECTIONPREVIEW": 1})).unwrap();
|
||||
let mut canvas = Self { app, ctx: Context::default(), previous_theme };
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
+1
-1
@@ -69,7 +69,7 @@ reached", malformed source is a reader error, and every built-in checks its argu
|
||||
`vl-string-search vl-string-subst vl-string-trim vl-string-left-trim vl-string-right-trim
|
||||
vl-string-translate vl-string->list vl-list->string vl-prin1-to-string vl-princ-to-string
|
||||
vl-symbol-name vl-symbol-value vl-filename-base vl-filename-extension vl-filename-directory`
|
||||
- **Geometry:** `polar distance angle inters trans` (`trans` returns the point: no UCS yet)
|
||||
- **Geometry:** `polar distance angle inters trans` (`trans` between the WCS (0), the current UCS (1), display coordinates (2, 3: the WCS in a plan view) and an object's OCS (an entity name or an extrusion direction); `getpoint` and friends answer in the current UCS and `command` takes UCS points, while entity lists stay in world coordinates)
|
||||
- **Output and files:** `princ prin1 print prompt terpri alert open close read-line write-line
|
||||
findfile`
|
||||
- **Errors:** `*error*`, `vl-catch-all-apply vl-catch-all-error-p vl-catch-all-error-message`
|
||||
|
||||
Reference in New Issue
Block a user