Compare commits

..
10 Commits
Author SHA1 Message Date
Dylan M. Taylor 23a599dcd6 Merge pull request #3026 from cdwilson127/fix/3011-mcp-find-text-query
MCP: find_text takes `query` as its filter; stylesmanager set replies with what changed
2026-11-19 19:44:39 -05:00
Dylan M. Taylor a1f5481cf9 Merge pull request #3035 from cdwilson127/fix/2988-getvar-point
LISP: getvar returns a point list for point system variables (LIMMIN, SNAPBASE, INSBASE, ...)
2026-11-19 19:43:25 -05:00
Dylan M. Taylor e072b680d6 Merge pull request #3297 from storytold/feat/share-lin-pat-parser
doc: share .lin and .pat text parsers via craft-dxf
2026-11-19 17:40:27 -05:00
Dylan M. Taylor 7c98bb2617 chore: pin craft-dxf to merged main rev 219c1d0b 2026-11-19 16:27:00 -05:00
Dylan M. Taylor 865ecbd071 doc: delegate .lin and .pat parsing to craft-dxf::lin_pat 2026-11-19 16:25:18 -05:00
cdwilson127 2423f45e49 stylesmanager set: a long style name cut at a space finds its stored style (#3011)
`sanitized` trims a style name, then cuts it to 255 characters. A name cut at a space was looked
up with that trailing space, but the next `sanitized` trims it: the reply left out `style`, and
setting the same name again added a second style that `sanitized` dropped, so the edit was lost.
The cut name is now trimmed at the end too, as it is stored.
2026-11-14 22:48:06 +13:00
cdwilson127 b4c76bb796 stylesmanager set: a long style name finds and replies with the stored style (#3011)
A style name over 255 characters was looked up and reported by its full name, but stored cut to
255. The reply then left out `style`, and setting the same long name again added a second style
that `sanitized` dropped, so the edit was lost. The name is now cut to its stored form first.
2026-11-11 22:13:53 +13:00
cdwilson127 39a2e4da07 stylesmanager set replies with only what changed (#3011)
The reply carried the table summary (kind, style count, inDrawing, builtin) next to the edit.
#3011 asks for only the changed style, so `set` now replies with the table's name and what the
call changed: the edited `style`, the `removedStyle` name and the `description`, each only when
given. The test checks that nothing else is in the reply.
2026-11-11 16:22:20 +10:00
cdwilson127 4750d67331 LISP: getvar returns a point list for point system variables (#2988)
Header point variables came back as their JSON text. They are now 2D lists for LIMMIN, LIMMAX, SNAPBASE and HPORIGIN and 3D for the rest.
2026-11-11 12:22:52 +13:00
cdwilson127 152e3b560c MCP: find_text takes query as its filter; stylesmanager set replies with what changed (#3011)
find_text only knew `contains`; a call with `query` was accepted and the filter silently
dropped, so every text came back. The texts command now reads `query` as `contains` (contains
wins when both are given), and the tool schema and docs list it.

stylesmanager `set` replied with the whole table (255 styles, about 25 kB for a .ctb). It now
replies like `new` and `load` do, with the table summary, plus the edited `style` and the
`removedStyle` name when given.
2026-11-11 08:46:44 +13:00
68 changed files with 381 additions and 4259 deletions
Generated
+4 -3
View File
@@ -717,6 +717,7 @@ version = "0.21.0"
dependencies = [
"cadcraft-color",
"cadcraft-geom",
"craft-dxf",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -1183,7 +1184,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
[[package]]
name = "craft-docpath"
@@ -1202,9 +1203,9 @@ dependencies = [
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
dependencies = [
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9)",
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a)",
"encoding_rs",
"kurbo",
"log",
+1 -1
View File
@@ -14,7 +14,7 @@ repository = "https://github.com/storytold/cadcraft"
# internal
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "9ed120e6b1bd5116a4649c578d1272d60cf932b9" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "2f2d1d84e3a36b3f93e81507aeff3f0da97a7162" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" }
+1
View File
@@ -44,6 +44,7 @@ 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,
+1
View File
@@ -11,6 +11,7 @@ workspace = true
[dependencies]
cadcraft-geom = { workspace = true }
cadcraft-color = { workspace = true }
craft-dxf = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
-5
View File
@@ -130,10 +130,6 @@ 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>,
@@ -205,7 +201,6 @@ 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(),
+46 -314
View File
@@ -1,32 +1,14 @@
//! Readers for the user's own linetype (`.lin`) and hatch pattern (`.pat`) files.
//!
//! Both follow the publicly documented text formats: a header line `*NAME[,description]`, then
//! the definition (`A,dash,gap,…` for a linetype, `angle, x, y, dx, dy[, dash, …]` lines for
//! a pattern), with `;` starting a comment line. CADCraft ships no such file; these read the
//! files users bring. Everything here treats the text as hostile: lines, definitions, dashes,
//! families and warnings are capped, numbers must be finite and reasonable, and nothing panics.
//! Problems become warnings and the definitions that can be read are kept.
//! Grammar and hostile-input capping live in [`craft_dxf::lin_pat`]; this module maps the
//! parsed definitions into CADCraft's [`Linetype`] and [`UserPattern`] document types.
use cadcraft_geom::Vec2;
pub use craft_dxf::lin_pat::{MAX_DEFINITIONS, MAX_LINE_CHARS, MAX_LINETYPE_ELEMENTS, MAX_PATTERN_DASHES, MAX_PATTERN_FAMILIES, MAX_VALUE, Parsed};
use super::PatternLine;
use crate::{DashElement, Linetype};
/// Longest line read; longer lines are skipped with a warning.
pub const MAX_LINE_CHARS: usize = 4096;
/// Most definitions (linetypes or patterns) read from one file.
pub const MAX_DEFINITIONS: usize = 4096;
/// Most elements in one linetype.
pub const MAX_LINETYPE_ELEMENTS: usize = 256;
/// Most line families in one hatch pattern (what the renderer draws, too).
pub const MAX_PATTERN_FAMILIES: usize = 1024;
/// Most dashes in one pattern line family (as for a pattern definition read from DXF).
pub const MAX_PATTERN_DASHES: usize = 256;
/// Largest magnitude accepted for a length, offset or scale.
pub const MAX_VALUE: f64 = 1.0e6;
/// Longest name or description kept.
const MAX_NAME_CHARS: usize = 255;
/// Most warnings collected; the rest are counted in a last line.
const MAX_WARNINGS: usize = 100;
/// A hatch pattern read from a user's `.pat` file.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct UserPattern {
@@ -35,307 +17,57 @@ pub struct UserPattern {
pub lines: Vec<PatternLine>,
}
/// What a file held: the definitions that could be read, and why anything else was skipped.
#[derive(Clone, Debug, PartialEq)]
pub struct Parsed<T> {
pub items: Vec<T>,
pub warnings: Vec<String>,
}
impl<T> Default for Parsed<T> {
fn default() -> Self {
Parsed { items: Vec::new(), warnings: Vec::new() }
}
}
impl<T> Parsed<T> {
fn warn(&mut self, line: usize, msg: impl Into<String>) {
match self.warnings.len() {
n if n < MAX_WARNINGS => self.warnings.push(format!("line {line}: {}", msg.into())),
MAX_WARNINGS => self.warnings.push("more problems not listed".into()),
_ => {}
}
}
}
/// A header line `*NAME[,description]`: the name and description, or why it can't be used.
fn header(rest: &str) -> std::result::Result<(String, String), String> {
let (name, desc) = rest.split_once(',').unwrap_or((rest, ""));
let name = name.trim();
if name.is_empty() {
return Err("a definition without a name".into());
}
if name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) {
return Err("a definition name that is too long or has control characters".into());
}
let desc: String = desc.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect();
Ok((name.to_string(), desc))
}
/// A finite number within ±[`MAX_VALUE`].
fn number(t: &str) -> Option<f64> {
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= MAX_VALUE)
}
/// The file's text lines with 1-based numbers, without a leading byte-order mark.
fn lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
text.trim_start_matches('\u{feff}').lines().enumerate().map(|(i, l)| (i.saturating_add(1), l.trim()))
}
// ---------- LIN ----------
/// Read the linetypes of a `.lin` file. Simple linetypes and complex ones with embedded text
/// (`["TEXT",STYLE,S=…,R=…,A=…,U=…,X=…,Y=…]`) are read; shape elements (`[SHAPE,file.shx,…]`)
/// need SHX shape fonts, so they are left out with a warning and the dashes around them kept.
/// Lengths are in drawing units as written: a user's file is never rescaled.
pub fn parse_lin(text: &str) -> Parsed<Linetype> {
let mut out = Parsed::default();
// The definition being read: name, description, header line.
let mut pending: Option<(String, String, usize)> = None;
for (no, line) in lines(text) {
if line.is_empty() || line.starts_with(';') {
continue;
}
if line.chars().count() > MAX_LINE_CHARS {
out.warn(no, "line too long; skipped");
continue;
}
if let Some(rest) = line.strip_prefix('*') {
if let Some((name, _, at)) = pending.take() {
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
}
match header(rest) {
Ok((name, desc)) => pending = Some((name, desc, no)),
Err(e) => out.warn(no, format!("{e}; skipped")),
}
continue;
}
let Some((name, description, _)) = pending.take() else {
out.warn(no, "pattern line without a *NAME line before it; skipped");
continue;
};
if out.items.len() >= MAX_DEFINITIONS {
out.warn(no, format!("more than {MAX_DEFINITIONS} linetypes; the rest are skipped"));
break;
}
if out.items.iter().any(|l: &Linetype| l.name.eq_ignore_ascii_case(&name)) {
out.warn(no, format!("linetype {name} is defined twice; the first definition is kept"));
continue;
}
match lin_pattern(line, no, &name, &mut out) {
Ok(pattern) => out.items.push(Linetype { name, description, pattern }),
Err(e) => out.warn(no, format!("linetype {name}: {e}; skipped")),
}
let parsed = craft_dxf::lin_pat::parse_lin(text);
Parsed {
items: parsed
.items
.into_iter()
.map(|d| Linetype {
name: d.name,
description: d.description,
pattern: d
.pattern
.into_iter()
.map(|e| DashElement {
length: e.length,
text: e.text,
shape: None,
style: e.style,
scale: e.scale,
rotation: e.rotation,
offset: Vec2::new(e.offset[0], e.offset[1]),
absolute: e.absolute,
})
.collect(),
})
.collect(),
warnings: parsed.warnings,
}
if let Some((name, _, at)) = pending {
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
}
out
}
/// Split a pattern line at commas outside `[…]` and `"…"`.
fn lin_fields(line: &str) -> std::result::Result<Vec<&str>, String> {
let mut out = Vec::new();
let (mut depth, mut quoted, mut start) = (0usize, false, 0usize);
for (i, c) in line.char_indices() {
match c {
'"' => quoted = !quoted,
'[' if !quoted => depth = depth.saturating_add(1),
']' if !quoted => depth = depth.checked_sub(1).ok_or("a ] without its [")?,
',' if !quoted && depth == 0 => {
out.push(line.get(start..i).unwrap_or("").trim());
start = i.saturating_add(1);
}
_ => {}
}
if out.len() > MAX_LINETYPE_ELEMENTS.saturating_mul(2) {
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
}
}
if quoted || depth != 0 {
return Err("an unclosed [ or \"".into());
}
out.push(line.get(start..).unwrap_or("").trim());
Ok(out)
}
/// The elements of a pattern line `A,dash,gap,[…],…`.
fn lin_pattern(line: &str, no: usize, name: &str, out: &mut Parsed<Linetype>) -> std::result::Result<Vec<DashElement>, String> {
let mut fields = lin_fields(line)?;
// The alignment field ("A") comes first; a line of plain numbers is read as well.
if fields.first().is_some_and(|f| f.eq_ignore_ascii_case("a")) {
fields.remove(0);
} else if fields.first().is_some_and(|f| number(f).is_none() && !f.starts_with('[')) {
return Err(format!("unknown alignment `{}` (expected A)", fields.first().copied().unwrap_or("")));
}
let mut pattern: Vec<DashElement> = Vec::new();
for f in fields.into_iter().filter(|f| !f.is_empty()) {
if pattern.len() >= MAX_LINETYPE_ELEMENTS {
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
}
let Some(inner) = f.strip_prefix('[') else {
let len = number(f).ok_or_else(|| format!("`{f}` is not a dash length"))?;
pattern.push(DashElement::dash(len));
continue;
};
let inner = inner.strip_suffix(']').ok_or_else(|| format!("`{f}` is not a complete [ ] element"))?;
match lin_text(inner)? {
Some(text) => {
// The text sits at the end of the element before it (a zero-length one if none).
if pattern.last().is_none_or(|e| e.text.is_some()) {
pattern.push(DashElement::dash(0.0));
}
if let Some(last) = pattern.last_mut() {
*last = DashElement { length: last.length, ..text };
}
}
None => {
let shape = inner.split(',').next().unwrap_or("").trim();
out.warn(no, format!("linetype {name}: shape {shape} needs an SHX shape file, which CADCraft can't read; left out"));
}
}
}
if pattern.is_empty() {
return Err("no dashes".into());
}
if pattern.iter().all(|e| e.length == 0.0) && pattern.iter().all(|e| e.text.is_none()) {
return Err("every element has zero length".into());
}
Ok(pattern)
}
/// A `"TEXT",STYLE,key=value…` element (the inside of `[…]`), or `None` for a shape element.
fn lin_text(inner: &str) -> std::result::Result<Option<DashElement>, String> {
let inner = inner.trim();
let Some(after) = inner.strip_prefix('"') else { return Ok(None) };
let (text, rest) = after.split_once('"').ok_or("unclosed text quote")?;
if text.chars().count() > MAX_NAME_CHARS || text.chars().any(char::is_control) {
return Err("embedded text that is too long or has control characters".into());
}
let mut parts = rest.split(',').map(str::trim);
if !parts.next().unwrap_or("").is_empty() {
return Err("text element: expected a comma after the text".into());
}
let style = parts.next().unwrap_or("").trim();
if style.is_empty() || style.contains('=') {
return Err("text element: the text style is missing".into());
}
let mut e = DashElement { text: Some(text.to_string()), style: Some(style.to_string()), ..DashElement::dash(0.0) };
for kv in parts.filter(|p| !p.is_empty()) {
let (k, v) = kv.split_once('=').ok_or_else(|| format!("text element: `{kv}` is not key=value"))?;
match k.trim().to_ascii_uppercase().as_str() {
"S" => e.scale = number(v).filter(|s| *s > 0.0).ok_or_else(|| format!("text element: bad scale `{v}`"))?,
"X" => e.offset.x = number(v).ok_or_else(|| format!("text element: bad X offset `{v}`"))?,
"Y" => e.offset.y = number(v).ok_or_else(|| format!("text element: bad Y offset `{v}`"))?,
// Upright text keeps a rotation relative to the line, like R.
k @ ("R" | "A" | "U") => {
e.rotation = angle(v).ok_or_else(|| format!("text element: bad rotation `{v}`"))?;
e.absolute = k == "A";
}
other => return Err(format!("text element: unknown option `{other}`")),
}
}
Ok(Some(e))
}
/// An angle in degrees, or with a `d` (degrees), `r` (radians) or `g` (grads) suffix; radians out.
fn angle(t: &str) -> Option<f64> {
let t = t.trim().to_ascii_lowercase();
let (num, unit) = match t.char_indices().last() {
Some((i, c @ ('d' | 'r' | 'g'))) => (t.get(..i)?, c),
_ => (t.as_str(), 'd'),
};
let v = num.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= 1.0e5)?;
Some(match unit {
'r' => v,
'g' => v * std::f64::consts::PI / 200.0,
_ => v.to_radians(),
})
}
// ---------- PAT ----------
/// Read the hatch patterns of a `.pat` file. Values are used as written (an inch file for inch
/// drawings, a millimetre file for metric ones).
pub fn parse_pat(text: &str) -> Parsed<UserPattern> {
let mut out: Parsed<UserPattern> = Parsed::default();
// The pattern being read, its header line, and whether it already failed.
let mut cur: Option<(UserPattern, usize, bool)> = None;
let finish = |cur: Option<(UserPattern, usize, bool)>, out: &mut Parsed<UserPattern>| {
let Some((p, at, failed)) = cur else { return };
if failed {
return;
}
if p.lines.is_empty() {
out.warn(at, format!("pattern {} has no line families; skipped", p.name));
} else if out.items.len() >= MAX_DEFINITIONS {
out.warn(at, format!("more than {MAX_DEFINITIONS} patterns; {} skipped", p.name));
} else if out.items.iter().any(|q| q.name.eq_ignore_ascii_case(&p.name)) {
out.warn(at, format!("pattern {} is defined twice; the first definition is kept", p.name));
} else {
out.items.push(p);
}
};
for (no, line) in lines(text) {
// A comment runs to the end of the line.
let line = line.split(';').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
if line.chars().count() > MAX_LINE_CHARS {
out.warn(no, "line too long; skipped");
continue;
}
if let Some(rest) = line.strip_prefix('*') {
finish(cur.take(), &mut out);
match header(rest) {
Ok((name, description)) => cur = Some((UserPattern { name: name.to_ascii_uppercase(), description, lines: Vec::new() }, no, false)),
Err(e) => out.warn(no, format!("{e}; skipped")),
}
continue;
}
let Some((p, _, failed)) = cur.as_mut() else {
out.warn(no, "line family without a *NAME line before it; skipped");
continue;
};
if *failed {
continue;
}
if p.lines.len() >= MAX_PATTERN_FAMILIES {
out.warn(no, format!("pattern {}: more than {MAX_PATTERN_FAMILIES} line families; skipped", p.name));
*failed = true;
continue;
}
match pat_family(line) {
Ok(l) => p.lines.push(l),
Err(e) => {
out.warn(no, format!("pattern {}: {e}; skipped", p.name));
*failed = true;
}
}
let parsed = craft_dxf::lin_pat::parse_pat(text);
Parsed {
items: parsed
.items
.into_iter()
.map(|p| UserPattern {
name: p.name,
description: p.description,
lines: p
.lines
.into_iter()
.map(|l| PatternLine { angle: l.angle, origin: (l.origin[0], l.origin[1]), delta: (l.delta[0], l.delta[1]), dashes: l.dashes })
.collect(),
})
.collect(),
warnings: parsed.warnings,
}
finish(cur, &mut out);
out
}
/// One line family: `angle, x-origin, y-origin, delta-x, delta-y[, dash-1, dash-2, …]`.
fn pat_family(line: &str) -> std::result::Result<PatternLine, String> {
let mut v = Vec::new();
for f in line.split(',') {
if v.len() >= MAX_PATTERN_DASHES.saturating_add(5) {
return Err(format!("more than {MAX_PATTERN_DASHES} dashes in a line family"));
}
let f = f.trim();
if f.is_empty() && v.len() >= 5 {
continue;
}
v.push(number(f).ok_or_else(|| format!("`{f}` is not a number"))?);
}
let (Some(&angle), Some(&x), Some(&y), Some(&dx), Some(&dy)) = (v.first(), v.get(1), v.get(2), v.get(3), v.get(4)) else {
return Err("a line family needs angle, x, y, delta-x and delta-y".into());
};
if dy.abs() < 1e-9 {
return Err("a line family with zero spacing (delta-y)".into());
}
Ok(PatternLine { angle, origin: (x, y), delta: (dx, dy), dashes: v.get(5..).unwrap_or(&[]).to_vec() })
}
+1 -18
View File
@@ -857,14 +857,6 @@ 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")]
@@ -873,16 +865,7 @@ 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,
ucs: None,
ucs_previous: Vec::new(),
limits: None,
}
Layout { name: name.into(), tab_order, page: PageSetup::default(), entities: EntityStore::new(), view: None, limits: None }
}
}
-2
View File
@@ -51,7 +51,6 @@ mod tolerance;
mod trimextend;
mod txt2mtxt;
pub use txt2mtxt::Txt2MtxtOptions;
mod ucs;
mod utility;
mod view;
@@ -188,7 +187,6 @@ 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());
+2 -9
View File
@@ -35,15 +35,8 @@ fn auto_rotation(p1: Vec2, p2: Vec2, at: Vec2) -> f64 {
if outside_x && !outside_y { std::f64::consts::FRAC_PI_2 } else { 0.0 }
}
/// 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) }
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)) } }
}
/// Add a dimension. With DIMASSOC on, definition points that sit on object endpoints,
+5 -14
View File
@@ -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, 0.0), at, a, b, Vec2::ZERO, str_param(p, "text").unwrap_or(""));
let k = dim(s, linear_kind(a, b, at, rot, false), at, a, b, Vec2::ZERO, str_param(p, "text").unwrap_or(""));
Ok(json!({ "handle": add_dim(s, k)?.hex() }))
}
@@ -216,8 +216,7 @@ 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, s.input_ucs().rotation()), at, a, b, Vec2::ZERO, ""));
let k = self.text.apply(dim(s, linear_kind(a, b, at, self.rotation, self.aligned), 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();
@@ -228,8 +227,8 @@ impl Interactive for LinearM {
}
(_, Input::Keyword(k)) => {
match k.as_str() {
"Horizontal" => self.rotation = Some(s.input_ucs().rotation()),
"Vertical" => self.rotation = Some(s.input_ucs().rotation() + std::f64::consts::FRAC_PI_2),
"Horizontal" => self.rotation = Some(0.0),
"Vertical" => self.rotation = Some(std::f64::consts::FRAC_PI_2),
"Rotated" => self.rotating = true,
other => {
self.text.keyword(other);
@@ -244,15 +243,7 @@ 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, s.input_ucs().rotation()),
c,
*a,
*b,
Vec2::ZERO,
"",
))],
[a, b] => vec![self.text.apply(dim(s, linear_kind(*a, *b, c, self.rotation, self.aligned), c, *a, *b, Vec2::ZERO, ""))],
_ => Vec::new(),
}
}
+15 -29
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("dist", "Distance", run_dist)
.menu(&["Tools", "Inquiry", "Distance"])
.alias(&["di"])
.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}")
.params("{p1, p2}")
.noundo()
.transparent()
.interactive(|_| Ok(Box::new(DistM::default()))),
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("usage", "Analyze Usage", usage::run).params(usage::PARAMS).noundo(),
CommandSpec::new("loops", "Implied Loops", loops::run).params(loops::PARAMS).noundo(),
CommandSpec::new("texts", "Query Texts", run_texts)
.params("{contains?: text (any case), layer?, window?: [[x,y],[x,y]] (by insertion point), limit? (default 200), offset?} → {count (all matches), returned, offset, texts: [{handle, type, layer, text, at, height, rotation (degrees), style, tag? (attributes)}]}: the readable text of TEXT, MTEXT (formatting removed), block attributes and multileaders")
.params("{contains?: text (any case; `query` is the same filter), layer?, window?: [[x,y],[x,y]] (by insertion point), limit? (default 200), offset?} → {count (all matches), returned, offset, texts: [{handle, type, layer, text, at, height, rotation (degrees), style, tag? (attributes)}]}: the readable text of TEXT, MTEXT (formatting removed), block attributes and multileaders")
.noundo(),
CommandSpec::new("countlist", "Count List", count::run_countlist)
.params("{space?: all (default)|current|model|<layout>, nested?: bool} → per-block counts, as COUNT")
@@ -192,18 +192,11 @@ fn angle_from_xy(d: Vec3) -> f64 {
d.z.atan2(d.xy().len())
}
/// 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 {
fn dist_text(s: &Session, a: Vec3, b: Vec3) -> String {
let d = b - a;
format!(
"Distance = {}, Angle in XY Plane = {}, Angle from XY Plane = {}\nDelta X = {}, Delta Y = {}, Delta Z = {}",
fmt_d(s, dist),
fmt_d(s, (b - a).len()),
fmt_a(s, d.xy().angle()),
fmt_a(s, angle_from_xy(d)),
fmt_d(s, d.x),
@@ -229,8 +222,6 @@ 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(),
@@ -238,28 +229,18 @@ fn run_dist(s: &mut Session, p: &Value) -> Result<Value> {
"dx": d.x,
"dy": d.y,
"dz": d.z,
"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),
"message": dist_text(s, a, b),
}))
}
/// ID's report: the point in the current UCS.
fn id_text(s: &Session, a: Vec3) -> String {
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))
format!("X = {} Y = {} Z = {}", fmt_d(s, a.x), fmt_d(s, a.y), fmt_d(s, a.z))
}
fn run_id(s: &mut Session, p: &Value) -> Result<Value> {
let a = point3_req(s, "id", p, "at")?;
s.last_point = a.xy();
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) }))
Ok(json!({ "x": a.x, "y": a.y, "z": a.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
@@ -683,7 +664,12 @@ fn run_texts(s: &mut Session, p: &Value) -> Result<Value> {
v.as_u64().map(|n| usize::try_from(n).unwrap_or(usize::MAX)).ok_or_else(|| bad(CMD, format!("`{k}` must be a whole number, 0 or more")))
})
};
let contains = text("contains")?;
// `query` is what agents tend to call the filter; without this alias it was silently ignored
// and every text came back (#3011).
let contains = match text("contains")? {
Some(c) => Some(c),
None => text("query")?,
};
let layer = text("layer")?;
let window = given("window")
.map(|w| {
@@ -919,7 +905,7 @@ impl Interactive for DistM {
s.last_point = first;
return Err(bad("dist", "the distance is too large"));
}
let t = dist_text(s, (b - a).len(), dist_delta(s, a, b));
let t = dist_text(s, a, b);
for l in t.lines() {
s.echo(l.to_string());
}
+1 -10
View File
@@ -313,16 +313,7 @@ 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,
ucs: src.ucs,
ucs_previous: Vec::new(),
limits: src.limits,
});
d.layouts.push(Layout { name: to.clone(), tab_order: order, page: src.page, entities: store, view: src.view, limits: src.limits });
Ok(json!({ "name": to }))
}
+23 -2
View File
@@ -264,16 +264,23 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, format!("`{name}` has no style `{rm}`")));
}
}
let mut changed: Option<String> = None;
if let Some(v) = p.get("style") {
let sname = v.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty());
let sname = sname.ok_or_else(|| bad(cmd, "`style.name` is required"))?;
// The name as it is stored (at most 255 characters, as `sanitized` cuts it, and
// without a space the cut leaves at the end, which `sanitized` trims), so a long
// name finds the style it was stored as and the reply finds the edited style.
let cut: String = sname.chars().take(255).collect();
let sname = cut.trim_end();
changed = Some(sname.to_string());
let idx = match t.styles.iter().position(|x| x.name.eq_ignore_ascii_case(sname)) {
Some(i) => i,
None if t.kind == PlotStyleKind::Named => {
if t.styles.len() >= cadcraft_doc::MAX_NAMED_STYLES {
return Err(bad(cmd, "the table has too many styles"));
}
t.styles.push(PlotStyle::object(&sname.chars().take(255).collect::<String>()));
t.styles.push(PlotStyle::object(sname));
t.styles.len() - 1
}
None => return Err(bad(cmd, format!("`{name}` has no style `{sname}` (colour-dependent styles are Color_1 to Color_255)"))),
@@ -283,7 +290,21 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let t = t.sanitized();
let out = serde_json::to_value(&t).unwrap_or(Value::Null);
// Only what changed, not the table (a colour-dependent one has 255 styles): the table's
// name, the description if given, the edited style and the removed style's name.
let mut out = json!({ "name": t.name });
if let Some(o) = out.as_object_mut() {
if str_param(p, "description").is_some() {
o.insert("description".into(), json!(t.description));
}
let edited = changed.and_then(|n| t.styles.iter().find(|x| x.name.eq_ignore_ascii_case(&n)));
if let Some(e) = edited.and_then(|x| serde_json::to_value(x).ok()) {
o.insert("style".into(), e);
}
if let Some(r) = str_param(p, "removeStyle") {
o.insert("removedStyle".into(), json!(r.trim()));
}
}
store(s.doc_mut()?, t);
Ok(out)
}
-675
View File
@@ -1,675 +0,0 @@
//! 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.")),
}
}
}
-1
View File
@@ -55,7 +55,6 @@ 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).
-3
View File
@@ -41,8 +41,6 @@ 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
@@ -74,7 +72,6 @@ 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(),
}
-3
View File
@@ -36,7 +36,6 @@ pub mod settings_dir;
pub mod snap;
pub mod spatial;
pub mod sysvars;
pub mod ucs;
pub mod undoctl;
pub mod units;
@@ -240,8 +239,6 @@ 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).
+3 -10
View File
@@ -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(&self.input_ucs())),
Need::Get(req) => Some(req.prompt()),
_ => None,
}
}
@@ -569,15 +569,10 @@ 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) });
// 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);
let Some(b) = req.first.or(req.base).map(|p| cadcraft_geom::Vec2::new(p[0], p[1])) else { return Some(Vec::new()) };
Some(match req.kind {
input::GetKind::Corner => {
// 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)));
let (c1, c2) = (cadcraft_geom::Vec2::new(cursor.x, b.y), cadcraft_geom::Vec2::new(b.x, cursor.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)],
@@ -756,8 +751,6 @@ fn file_key(name: &str) -> String {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod ucs_tests;
#[cfg(test)]
mod block_tests;
+17 -74
View File
@@ -117,14 +117,10 @@ 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() {
// 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));
feed(ctx.s, Input::Point(Vec2::new(p[0], p[1])));
} else if let Value::Ename(h) = arg.car() {
// An `entsel` result: (ename point).
// 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]))));
named(ctx.s, h, arg.cdr().car().as_point().map(|p| Vec2::new(p[0], p[1])));
} else {
return Err(LispError::bad_arg("command argument", arg));
}
@@ -217,10 +213,19 @@ pub fn getvar(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
let name = string(&a[0])?;
Ok(Flow::Value(match crate::sysvars::get(ctx.s, &name) {
Some(serde_json::Value::Number(n)) if in_radians(&name) => Value::Real(n.as_f64().unwrap_or(0.0).to_radians()),
Some(serde_json::Value::Object(o)) if o.contains_key("x") => point_list(&o, &name),
v => v.map(|v| from_json(&v)).unwrap_or_default(),
}))
}
/// Header point variables are stored as `{x, y, z}`; AutoLISP gives a point list. LIMMIN, LIMMAX,
/// SNAPBASE and HPORIGIN are 2D points, so they lose z; the rest (INSBASE, UCSORG, ...) keep all three.
fn point_list(o: &serde_json::Map<String, serde_json::Value>, name: &str) -> Value {
let coord = |k: &str| Value::Real(o.get(k).and_then(serde_json::Value::as_f64).unwrap_or(0.0));
let planar = ["LIMMIN", "LIMMAX", "SNAPBASE", "HPORIGIN"].iter().any(|v| v.eq_ignore_ascii_case(name.trim()));
if planar { Value::list(vec![coord("x"), coord("y")]) } else { Value::list(vec![coord("x"), coord("y"), coord("z")]) }
}
/// Set a system variable after bounded JSON conversion, reporting invalid or oversized values as LISP errors.
pub fn setvar(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 2, 2)?;
@@ -718,13 +723,10 @@ 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(frame.to_wcs(Vec2::new(p[0], p[1])))
Ok(Vec2::new(p[0], p[1]))
};
let s = &mut *ctx.s;
let all = |s: &Session, all_spaces: bool| -> Vec<Handle> {
@@ -752,8 +754,6 @@ 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)) };
@@ -762,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| frame.to_wcs(Vec2::new(q[0], q[1])))).collect()).unwrap_or_default();
pts.first().map(|l| l.iter().filter_map(|p| p.as_point().map(|q| 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() {
@@ -1212,8 +1212,7 @@ 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])?;
// A pure string-to-angle conversion: ANGBASE and ANGDIR apply, the UCS does not.
let mut settings = ctx.s.angle_settings().world();
let mut settings = ctx.s.angle_settings();
// AUNITS 0..=4; any other units argument is an error in AutoCAD, nil here.
match a.get(1) {
None | Some(Value::Nil) => {}
@@ -1223,67 +1222,11 @@ pub fn angtof(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
Ok(Flow::Value(settings.direction(&s).map(Value::Real).unwrap_or_default()))
}
/// 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> {
/// `(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> {
arity(&a, 3, 4)?;
let p = a[0].as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", &a[0]))?;
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])))
Ok(Flow::Value(Value::point(&p)))
}
/// What `(load name)` reads: a file loaded through APPLOAD (the web), or one on disk, with
+7 -20
View File
@@ -49,8 +49,8 @@ pub struct GetRequest {
}
impl GetRequest {
/// The prompt the command line shows (`ucs`: the UCS the routine's points are in).
pub fn prompt(&self, ucs: &crate::ucs::UcsFrame) -> Prompt {
/// The prompt the command line shows.
pub fn prompt(&self) -> 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| ucs.to_wcs(Vec2::new(p[0], p[1])));
let base = self.first.or(self.base).map(|p| 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,21 +106,11 @@ impl GetRequest {
Ok(Value::Nil)
}
Input::Keyword(k) => Ok(Value::str(&k)),
// 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])
}
Input::Point(p) => self.point(s, [p.x, p.y, 0.0]),
// A deferred tangent/perpendicular snap is the point it was picked at here.
Input::Deferred(d) => {
let u = s.ucs_point(d.at);
self.point(s, [u.x, u.y, 0.0])
}
Input::Deferred(d) => self.point(s, [d.at.x, d.at.y, 0.0]),
Input::Pick(hs) => match (self.kind, hs.first()) {
(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])]))
}
(GetKind::EntSel, Some(h)) => Ok(Value::list(vec![Value::Ename(*h), Value::point(&[s.last_point.x, s.last_point.y, 0.0])])),
_ => Err("Invalid point.".into()),
},
Input::Text(t) => self.text(s, &t),
@@ -151,8 +141,7 @@ 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()))?;
// `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) {
match crate::select::pick_in(d, &space, s.viewport_frozen(), 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()),
}
@@ -198,8 +187,6 @@ 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)
}
+11
View File
@@ -649,6 +649,17 @@ fn getvar_drawing_and_session_variables() {
assert_eq!(ok(&mut s, "(getvar \"DWGTITLED\")"), "1");
}
/// LIMMIN, LIMMAX, SNAPBASE and HPORIGIN read as 2D point lists and INSBASE as a 3D one, not as JSON text (#2988).
#[test]
fn getvar_point_variables_are_point_lists() {
let mut s = session();
assert_eq!(ok(&mut s, "(getvar \"LIMMIN\")"), "(0.0 0.0)");
assert_eq!(ok(&mut s, "(getvar \"LIMMAX\")"), "(12.0 9.0)");
assert_eq!(ok(&mut s, "(getvar \"SNAPBASE\")"), "(0.0 0.0)");
assert_eq!(ok(&mut s, "(getvar \"INSBASE\")"), "(0.0 0.0 0.0)");
assert_eq!(ok(&mut s, "(setvar \"HPORIGIN\" '(3.0 4.0)) (getvar \"HPORIGIN\")"), "(3.0 4.0)");
}
/// CECOLOR is a string in AutoCAD, whatever it was set from (#1999).
#[test]
fn getvar_cecolor_is_a_string() {
-284
View File
@@ -1,284 +0,0 @@
//! 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}");
}
}
+5 -12
View File
@@ -61,13 +61,6 @@ 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.
@@ -243,16 +236,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()
&& self.parse_typed_point(t, self.last_point).is_none()
&& crate::prompt::parse_point_with(t, self.last_point, &self.angle_settings()).is_none()
&& let Some(d) = crate::units::parse_distance(t)
{
let dir = (crate::snap::ortho_at(l, self.cursor, self.drafting_settings().ucs_angle) - l).normalized();
let dir = (crate::snap::ortho(l, self.cursor) - 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 self.parse_typed_point(t, self.last_point).is_some() {
if crate::prompt::parse_point_with(t, self.last_point, &self.angle_settings()).is_some() {
self.point_mods.pop();
return None;
}
@@ -335,7 +328,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_at(l, p, self.drafting_settings().ucs_angle));
let q = last.map_or(p, |l| crate::snap::ortho(l, p));
self.point_mods.push(Frame::Track { last: Some(q) });
self.last_point = q;
return Ok(());
@@ -343,7 +336,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_in(&self.input_ucs(), f, p),
Frame::Filter { keep, first: Some(f) } => p = keep.combine(f, p),
Frame::Angle { base, dir } => p = base + dir * (p - base).dot(dir),
Frame::Snap { mode: 0 } => {}
Frame::Snap { mode } => {
+10 -33
View File
@@ -114,10 +114,7 @@ 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()?;
// 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)? };
let angle = angles.amount(a.trim())?;
(dist.is_finite() && angle.is_finite()).then_some((dist, angle))
}
@@ -353,9 +350,10 @@ 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).
/// `*x,y` and `*@dx,dy`/`@*dx,dy` (world coordinates: the same as the plain forms, as there is no
/// UCS yet).
/// Relative forms use `last`. Polar angles read the default angle settings (degrees from +X,
/// counterclockwise); `parse_point_with` reads a drawing's, `parse_point_in` a UCS too.
/// counterclockwise); `parse_point_with` reads a drawing's.
pub fn parse_point(text: &str, last: Vec2) -> Option<Vec2> {
parse_point_with(text, last, &crate::units::AngleSettings::default())
}
@@ -363,31 +361,14 @@ 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 (mut world, t) = match t.strip_prefix('*') {
Some(r) => (true, r.trim_start()),
None => (false, t),
};
let t = t.strip_prefix('*').map_or(t, str::trim_start);
let (rel, body) = if let Some(b) = t.strip_prefix('@') {
let b = b.trim();
match b.strip_prefix('*') {
Some(r) => {
world = true;
(true, r.trim_start())
}
None => (true, b),
}
(true, b.strip_prefix('*').map_or(b, str::trim_start))
} else if let Some(b) = t.strip_prefix('#') {
(false, b.trim())
} else {
@@ -396,15 +377,11 @@ pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettin
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)? };
let v = Vec2::from_angle(ang) * dist;
if rel { last + v } else { frame.origin.xy() + v }
Vec2::from_angle(ang) * dist
} else {
let parts: Vec<&str> = body.split(',').collect();
if parts.len() < 2 || parts.len() > 3 {
@@ -415,10 +392,10 @@ pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettin
if let Some(z) = parts.get(2) {
crate::units::parse_distance(z)?;
}
let v = Vec2::new(x, y);
if rel { last + frame.vec_to_wcs(v) } else { frame.to_wcs(v) }
Vec2::new(x, y)
};
p.is_finite().then_some(p)
let r = if rel { last + p } else { p };
r.is_finite().then_some(r)
}
#[cfg(test)]
+2 -4
View File
@@ -107,8 +107,7 @@ 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() {
// 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])))),
Some(p) => self.input(Input::Point(Vec2::new(p[0], p[1]))),
None => {
self.echo(format!("Invalid input: {}", lisp::value::to_text(&other, true)));
Ok(())
@@ -147,8 +146,7 @@ impl Session {
return self.input(Input::Keyword(k));
}
if prompt.accept.point {
self.note_tilted_ucs();
if let Some(p) = self.parse_typed_point(tt, self.last_point) {
if let Some(p) = prompt::parse_point_with(tt, self.last_point, &self.angle_settings()) {
self.last_polar = prompt::parse_polar_text(tt, &self.angle_settings());
return self.input(Input::Point(p));
}
-5
View File
@@ -125,10 +125,6 @@ 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
@@ -197,7 +193,6 @@ impl Default for Settings {
polaraddang: Vec::new(),
polarsnap: false,
polardist: 0.0,
ucs_angle: 0.0,
auditctl: false,
attreq: true,
}
+1 -26
View File
@@ -1025,17 +1025,6 @@ 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)> {
@@ -1069,26 +1058,12 @@ 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,
/// as stored: in the UCS ([`grid_frame_in`] places them in the world).
/// The snap grid's origin (SNAPBASE) and rotation in radians (SNAPANG, in degrees) of a drawing.
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::*;
+7 -68
View File
@@ -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, space: &cadcraft_doc::Space, mut s: Settings, p: Vec2) -> (Vec2, Settings) {
pub(crate) fn grid_snap(doc: &cadcraft_doc::Drawing, mut s: Settings, p: Vec2) -> (Vec2, Settings) {
if !(s.snapmode && s.isodraft) || s.polarsnap {
return (p, s);
}
let (origin, angle) = super::grid_frame_in(doc, space);
let (origin, angle) = super::grid_frame(doc);
s.snapmode = false;
(lattice_snap(p, s.snapunit.y, origin, angle), s)
}
@@ -144,12 +144,10 @@ 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_at(base, p, s.ucs_angle);
return super::ortho(base, p);
}
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 dir = nearest_axis(s.isoplane, p - base);
let r = base + dir * (p - base).dot(dir);
if r.is_finite() { r } else { p }
}
@@ -216,29 +214,16 @@ 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 degs {
for deg in [30.0f64, 90.0, 150.0] {
let dir = Vec2::from_angle(deg.to_radians() + angle);
let n = dir.perp();
let off = origin.dot(n);
@@ -304,50 +289,4 @@ 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);
}
}
+8 -14
View File
@@ -259,14 +259,12 @@ 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 { &[] };
// 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 absolute = polar_angles(s.polarang, additional, angbase);
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(ucs) };
let track_angles = if s.polar_flags & polarmode::TRACK_POLAR != 0 { absolute } else { orthogonal() };
TrackConfig {
otrack: s.otrack,
osmode: s.osmode,
@@ -281,9 +279,9 @@ impl TrackConfig {
}
}
/// 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()
/// Horizontal and vertical, both ways.
fn orthogonal() -> Vec<f64> {
vec![0.0, PI / 2.0, PI, 1.5 * PI]
}
/// Every multiple of the increment `inc` (POLARANG) around the circle, plus the `additional`
@@ -809,11 +807,10 @@ 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 snapmode = s.snapmode;
let (raw, mut s) = super::iso::grid_snap(&doc, &space, s, raw);
let (raw, s) = super::iso::grid_snap(&doc, s, raw);
let mut p = raw;
if s.snapmode && !s.polarsnap {
let (origin, angle) = super::grid_frame_in(&doc, &space);
let (origin, angle) = super::grid_frame(&doc);
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) {
@@ -832,10 +829,7 @@ impl crate::Session {
&& s.orthomode
&& !q.corner
{
// 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);
p = super::iso::ortho(&self.settings, b, p);
}
CursorSnap { point: p, snap: None, track: None, wait }
}
-18
View File
@@ -188,19 +188,6 @@ 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" => {
@@ -285,11 +272,6 @@ const READ_ONLY: &[&str] = &[
"EXTMAX",
"UNDOCTL",
"UNDOMARKS",
"UCSNAME",
"UCSORG",
"UCSXDIR",
"UCSYDIR",
"WORLDUCS",
];
pub fn is_read_only(name: &str) -> bool {
-3
View File
@@ -73,9 +73,6 @@ 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)),
-404
View File
@@ -1,404 +0,0 @@
//! 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);
}
}
+17 -54
View File
@@ -269,20 +269,11 @@ 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, ucs: 0.0 }
}
/// The same settings with directions measured in the World UCS (`*` coordinates).
pub fn world(&self) -> Self {
AngleSettings { ucs: 0.0, ..*self }
AngleSettings { aunits: h.i64("AUNITS", 0), angbase: h.f64("ANGBASE", 0.0), clockwise: h.i64("ANGDIR", 0) != 0 }
}
/// A typed angle size in radians (included angles, sweeps, angles from an axis): a bare
@@ -304,31 +295,29 @@ 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).and_then(|(a, _)| ucs(a));
return parse_units(r, self.aunits).map(|(a, _)| a);
}
if let Some(r) = t.strip_prefix("<<") {
return parse_units(r, 0).filter(|(_, bearing)| !bearing).and_then(|(a, _)| ucs(a));
return parse_units(r, 0).filter(|(_, bearing)| !bearing).map(|(a, _)| a);
}
let (a, _) = parse_units(t, self.aunits)?;
ucs(self.angbase + if self.clockwise { -a } else { a })
let v = self.angbase + if self.clockwise { -a } else { a };
v.is_finite().then_some(v)
}
/// 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.)
/// 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.)
pub fn shown(&self, dir: f64) -> f64 {
let local = dir - self.ucs;
let a = if self.clockwise { self.angbase - local } else { local - self.angbase };
let a = if self.clockwise { self.angbase - dir } else { dir - self.angbase };
a.rem_euclid(std::f64::consts::TAU)
}
/// The direction (radians counterclockwise from world +X) the drawing shows as `v`
/// (radians): the inverse of [`AngleSettings::shown`].
/// The direction (radians counterclockwise from +X) the drawing shows as `v` (radians): the
/// inverse of [`AngleSettings::shown`].
pub fn unshown(&self, v: f64) -> f64 {
(self.ucs + self.angbase + if self.clockwise { -v } else { v }).rem_euclid(std::f64::consts::TAU)
(self.angbase + if self.clockwise { -v } else { v }).rem_euclid(std::f64::consts::TAU)
}
}
@@ -429,12 +418,9 @@ fn parse_dms(t: &str) -> Option<f64> {
}
impl crate::Session {
/// How typed angles are read in the current drawing (the defaults without one): directions
/// are measured in the current UCS.
/// How typed angles are read in the current drawing (the defaults without one).
pub fn angle_settings(&self) -> AngleSettings {
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 }
self.doc().map(|d| AngleSettings::from_header(&d.header)).unwrap_or_default()
}
}
@@ -478,7 +464,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, ucs: 0.0 };
let north_clockwise = AngleSettings { aunits: 0, angbase: 90f64.to_radians(), clockwise: true };
// 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}");
@@ -488,33 +474,10 @@ 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, ucs: 0.0 };
let based = AngleSettings { aunits: 0, angbase: 30f64.to_radians(), clockwise: false };
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");
@@ -606,7 +569,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, ucs: 0.0 };
let a = AngleSettings { aunits: 4, angbase: PI / 2.0, clockwise: true };
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}");
+2 -2
View File
@@ -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, ucs: 0.0 };
let settings = AngleSettings { aunits: 0, angbase: std::f64::consts::FRAC_PI_2, clockwise: true };
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, ucs: 0.0 };
let a = AngleSettings { aunits: 0, angbase: 0.0, clockwise: false };
assert_eq!(a.direction(""), None);
assert_eq!(a.direction("nan"), None);
assert_eq!(a.direction("1e400"), None);
+69 -1
View File
@@ -62,7 +62,10 @@ fn stylesmanager_creates_edits_saves_and_loads_tables() {
&json!({"action": "set", "name": "office.stb", "style": {"name": "Pen 5", "color": "#00ff00", "screening": 40, "lineweight": 0.35, "linetype": "HIDDEN", "end": "round"}}),
)
.unwrap();
let pen = r["styles"].as_array().unwrap().iter().find(|v| v["name"] == "Pen 5").unwrap().clone();
// `set` replies with the table's name and the edited style, not the table.
assert_eq!(r["name"], "office.stb");
let pen = r["style"].clone();
assert_eq!(pen["name"], "Pen 5");
assert_eq!(
(pen["color"].as_str(), pen["screening"].as_u64(), pen["lineweight"].as_u64(), pen["end"].as_str()),
(Some("#00ff00"), Some(40), Some(35), Some("round"))
@@ -131,3 +134,68 @@ fn plot_style_save_is_atomic_and_keeps_permissions() {
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
let _ = std::fs::remove_dir_all(&dir);
}
/// #3011: `set` on a colour-dependent table (255 styles) replies with what changed, not the table.
#[test]
fn stylesmanager_set_replies_with_the_change_not_the_whole_table() {
let mut s = Session::new();
let set = json!({"action": "set", "name": "monochrome.ctb", "style": {"name": "Color_13", "lineweight": 0.3}});
let r = s.execute("stylesmanager", &set).unwrap();
assert_eq!(r["name"], "monochrome.ctb", "{r}");
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some("Color_13"), Some(30)), "{r}");
// Only the change: no table summary, no other style.
let keys: Vec<&str> = r.as_object().unwrap().keys().map(String::as_str).collect();
assert_eq!(keys, ["name", "style"], "{r}");
assert!(r.to_string().len() < 1000, "the reply is short, not the 255-style table: {} bytes", r.to_string().len());
// The edit is in the drawing.
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "monochrome.ctb"})).unwrap();
let c13 = got["styles"].as_array().unwrap().iter().find(|v| v["name"] == "Color_13").unwrap();
assert_eq!(c13["lineweight"], 30);
// Removing a style of a named table names what went.
s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap();
s.execute("stylesmanager", &json!({"action": "set", "name": "office.stb", "style": {"name": "Pen 5"}})).unwrap();
let r =
s.execute("stylesmanager", &json!({"action": "set", "name": "office.stb", "removeStyle": "Pen 5", "description": "Office pens"})).unwrap();
assert_eq!((r["removedStyle"].as_str(), r["description"].as_str()), (Some("Pen 5"), Some("Office pens")), "{r}");
assert!(r.get("style").is_none() && r.get("styles").is_none(), "{r}");
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap();
assert_eq!(got["styles"].as_array().map(Vec::len), Some(1), "{got}");
}
/// A style name over 255 characters is stored cut to 255: the reply names the stored style, and
/// setting the same long name again edits that style instead of adding one.
#[test]
fn stylesmanager_set_with_a_long_style_name_replies_with_the_stored_style() {
let mut s = Session::new();
s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap();
let long = "P".repeat(300);
let stored = "P".repeat(255);
let set = |lw: f64| json!({"action": "set", "name": "office.stb", "style": {"name": long, "lineweight": lw}});
let r = s.execute("stylesmanager", &set(0.3)).unwrap();
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(30)), "{r}");
let r = s.execute("stylesmanager", &set(0.5)).unwrap();
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(50)), "{r}");
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap();
let styles = got["styles"].as_array().unwrap();
assert_eq!(styles.len(), 2, "Normal and the one long-named style: {got}");
assert_eq!(styles[1]["lineweight"], 50, "{got}");
}
/// A long name whose 255th character is a space is stored without it (`sanitized` trims the cut
/// name), so the reply still has the style and setting the same name again edits it.
#[test]
fn stylesmanager_set_with_a_long_name_cut_at_a_space_edits_one_style() {
let mut s = Session::new();
s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap();
let long = format!("{} tail", "P".repeat(254));
let stored = "P".repeat(254);
let set = |lw: f64| json!({"action": "set", "name": "office.stb", "style": {"name": long, "lineweight": lw}});
let r = s.execute("stylesmanager", &set(0.3)).unwrap();
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(30)), "{r}");
let r = s.execute("stylesmanager", &set(0.5)).unwrap();
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(50)), "{r}");
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap();
let styles = got["styles"].as_array().unwrap();
assert_eq!(styles.len(), 2, "Normal and the one long-named style: {got}");
assert_eq!(styles[1]["lineweight"], 50, "{got}");
}
-765
View File
@@ -1,765 +0,0 @@
//! 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<_>>());
}
-239
View File
@@ -1,239 +0,0 @@
//! 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:?}");
}
-34
View File
@@ -35,40 +35,6 @@ 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;
-2
View File
@@ -62,8 +62,6 @@ 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>)>,
+3 -57
View File
@@ -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, Ucs, Vec2, Vec3};
use super::{Drawing, EntityKind, Group, Handle, HashMap, MLeaderStyle, PageSetup, Rx, Tag, Vec2};
/// Non-graphical objects applied once every entity is placed.
#[derive(Default)]
@@ -22,8 +22,6 @@ 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).
@@ -72,18 +70,11 @@ impl Objects {
self.sortents.push(t);
}
}
"LAYOUT" if self.layout_views.len() < MAX_OBJECTS && self.layout_ucss.len() < MAX_OBJECTS => {
"LAYOUT" if self.layout_views.len() < MAX_OBJECTS => {
let start = tags.iter().position(|x| x.code == 100 && x.str() == "AcDbLayout").unwrap_or(0);
let own = T(tags.get(start..).unwrap_or(&[]));
if let (Some(name), Some(view)) = (own.s(1), layout_view(tags)) {
if let (Some(name), Some(view)) = (T(tags.get(start..).unwrap_or(&[])).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)));
}
}
_ => {}
}
@@ -103,49 +94,6 @@ 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 {
@@ -243,7 +191,6 @@ 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.
@@ -276,7 +223,6 @@ 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 {
-11
View File
@@ -214,7 +214,6 @@ 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);
}
@@ -315,21 +314,11 @@ 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;
+1 -8
View File
@@ -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, Ucs, VAlign, VportConfig, VportTile,
TableStyle, Text, Transparency, VAlign, VportConfig, VportTile,
};
use cadcraft_geom::{Bounds2, Vec2, Vec3};
use craft_dxf::{Tag, Version};
@@ -43,11 +43,6 @@ 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>>,
@@ -160,8 +155,6 @@ 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() };
+1 -9
View File
@@ -16,15 +16,7 @@ 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(),
ucss: HashMap::new(),
vport_ucs: Vec::new(),
reactors: HashMap::new(),
};
let mut ov = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() };
let mut sah = false;
for (k, v) in &dm.overrides {
let Some(field) = DimStyle::field_name(k) else { continue };
+1 -33
View File
@@ -1,4 +1,4 @@
use super::{DimVal, Drawing, HVal, K, Ucs, Vec3, Version, W, dxf_ext};
use super::{DimVal, Drawing, HVal, K, Version, W, dxf_ext};
/// Header variables we write, with their group codes (DXF Reference, HEADER section).
/// `P2`/`P3` = 2D/3D point.
@@ -37,11 +37,6 @@ 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),
@@ -57,25 +52,6 @@ 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).
@@ -128,9 +104,6 @@ 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}"));
@@ -155,11 +128,6 @@ 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}"));
-22
View File
@@ -1,5 +1,4 @@
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
@@ -139,27 +138,6 @@ 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");
}
+8 -52
View File
@@ -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, model_ucs};
use super::header::{code_page, header_vars};
use super::layout::{paper_views, record_head, sheet_first, table_head, vport_table};
use super::objects::{cadcraft_fonts_name, group_obj, mleader_style_obj, scale_list, table_style_obj};
use super::{
Block, Color, DimStyle, DimVal, Drawing, Entity, EntityKind, EntityStore, Group, HVal, Handle, HashMap, Layout, MLeaderStyle, PageSetup, Space,
TableStyle, Tag, Ucs, Vec2, Vec3, Version, W, dxf_ext,
TableStyle, Tag, Vec2, Vec3, Version, W, dxf_ext,
};
struct TableWritePlan<'a> {
@@ -163,8 +163,7 @@ 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 {
let h = record_head(w, "UCS", &th, "AcDbUCSTableRecord");
w.ucss.insert(u.name.to_ascii_uppercase(), h);
record_head(w, "UCS", &th, "AcDbUCSTableRecord");
w.s(2, &u.name);
w.i(70, 0);
w.p(10, u.origin);
@@ -174,13 +173,6 @@ 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 {
@@ -253,15 +245,7 @@ fn write_dimstyles(w: &mut W, d: &Drawing, cx: &mut Ctx, version: Version) {
w.i(70, 0);
let v = serde_json::to_value(s).unwrap_or_default();
let defaults = serde_json::to_value(DimStyle::default()).unwrap_or_default();
let mut newer = W {
t: Vec::new(),
next: 0,
pstyles: HashMap::new(),
layers: HashMap::new(),
ucss: HashMap::new(),
vport_ucs: Vec::new(),
reactors: HashMap::new(),
};
let mut newer = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() };
for (field, code, kind) in dxf_ext::DIM_CODES {
let Some(enc) = v.get(*field).and_then(|x| cx.encode(*kind, x)) else { continue };
// DIMPOST is written even when empty: a reader that defaults a missing one to "<>"
@@ -401,8 +385,6 @@ 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)>,
}
@@ -485,21 +467,12 @@ 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, 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.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.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);
@@ -559,17 +532,7 @@ 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,
ucs: None,
limits: None,
},
LayoutWriteData { handle: model_layout, name: "Model", tab: 0, block_record: ms_br, flags: 1, page: &model_page, view: None, limits: None },
);
for (i, (_, brh, l)) in ps_brs.iter().enumerate() {
let h = layout_handles.get(i).cloned().unwrap_or_default();
@@ -584,7 +547,6 @@ 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,
},
);
@@ -957,8 +919,6 @@ 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.
@@ -1016,10 +976,6 @@ 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));
}
-472
View File
@@ -1,472 +0,0 @@
//! 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);
}
+16
View File
@@ -226,6 +226,22 @@ fn find_text_reads_texts_and_render_shows_one_area() {
assert_eq!((w, h), (1600, 800));
}
/// Guards #3011: `find_text` filters by `query` as it does by `contains`, instead of ignoring it
/// and returning every text.
#[test]
fn find_text_filters_by_query() {
let mut s = Server::new(Box::new(Headless::default()));
call(&mut s, 1, "initialize", json!({"protocolVersion": "2025-06-18"}));
tool(&mut s, "execute", json!({"command": "text", "params": {"at": [1, 1], "height": 0.15, "text": "RECAMARA 1"}}));
tool(&mut s, "execute", json!({"command": "text", "params": {"at": [50, 1], "height": 0.15, "text": "COCINA"}}));
assert_eq!(tool(&mut s, "find_text", json!({}))["count"], 2);
let r = tool(&mut s, "find_text", json!({"query": "cocina"}));
assert_eq!((r["count"].as_u64(), r["texts"][0]["text"].as_str()), (Some(1), Some("COCINA")), "{r}");
assert_eq!(tool(&mut s, "find_text", json!({"query": "nada"}))["count"], 0);
// `contains` still works and wins when both are given.
assert_eq!(tool(&mut s, "find_text", json!({"contains": "recamara", "query": "cocina"}))["texts"][0]["text"], "RECAMARA 1");
}
/// Guards a lazy Remote bridge: it serves tools without the app, reports how to start it
/// (`--control`), and reaches the app once that app starts listening on the port.
#[test]
+2 -2
View File
@@ -28,8 +28,8 @@ pub fn tool_definitions(has_ui: bool) -> Value {
"background": {"type": "string", "description": "\"dark\" (default without plot_style), \"white\" (default with one), \"paper\" or \"#rrggbb\""},
"plot_style": {"type": "string", "description": "a plot style table: monochrome.ctb, grayscale.ctb, default.ctb, default.stb, monochrome.stb, or one the drawing holds; \"none\" or \"\" for the objects' own properties"},
"path": {"type": "string"}}}}),
json!({"name": "find_text", "description": "Read the drawing's texts: TEXT, MTEXT (formatting removed), block attributes and multileaders, each with its text, insertion point `at`, height, rotation, style, layer and handle. Filter by `contains` (any case), `layer` and/or `window` [[x0,y0],[x1,y1]] around the insertion points; page with offset and limit (default 200). Use it to find room names, sheet titles and notes without reading all the geometry.",
"inputSchema": {"type": "object", "properties": {"contains": {"type": "string"}, "layer": {"type": "string"},
json!({"name": "find_text", "description": "Read the drawing's texts: TEXT, MTEXT (formatting removed), block attributes and multileaders, each with its text, insertion point `at`, height, rotation, style, layer and handle. Filter by `contains` (any case; `query` is the same filter), `layer` and/or `window` [[x0,y0],[x1,y1]] around the insertion points; page with offset and limit (default 200). Use it to find room names, sheet titles and notes without reading all the geometry.",
"inputSchema": {"type": "object", "properties": {"contains": {"type": "string"}, "query": {"type": "string"}, "layer": {"type": "string"},
"window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2},
"limit": {"type": "integer", "minimum": 0}, "offset": {"type": "integer", "minimum": 0}}}}),
json!({"name": "new_drawing", "description": "Create a new drawing (imperial by default, or metric).",
+4 -9
View File
@@ -534,21 +534,16 @@ 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, app.session.input_ucs().rotation());
draw_tracking(painter, &xf, &app.session.tracking.acquired, app.canvas.track.as_ref(), view.height * 4.0);
}
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.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_ucs_icon {
draw_ucs_icon(painter, rect);
crate::viewcube::ucs_icon(app, ui, rect);
}
if app.ui.show_viewcube && sheet.is_none() {
draw_viewcube(app, ui, rect);
+5 -16
View File
@@ -63,23 +63,9 @@ 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°").
/// `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,
) {
pub(super) fn draw_tracking(p: &egui::Painter, xf: &Xf, acquired: &[snap::tracking::Acquired], track: Option<&snap::tracking::Track>, far: f64) {
use snap::tracking::{Acquired, PathShape};
let t = Tokens::get();
let st = Stroke::new(1.0, t.snap);
@@ -114,7 +100,10 @@ pub(super) fn draw_tracking(
}
};
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), tooltip_angle(path.from, tr.point, ucs));
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),
);
tips.push(if path.name == "Polar" {
crate::tf!("Polar: {distance} < {angle}°", distance = distance, angle = angle)
} else {
+1 -1
View File
@@ -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())
}
pub(super) fn clip_infinite(xf: &Xf, base: Vec2, dir: Vec2, ray: bool) -> Option<[Pos2; 2]> {
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 };
+11 -21
View File
@@ -1,4 +1,3 @@
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.
@@ -35,20 +34,14 @@ 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(&gb, minor) {
// Snap-frame lines across the visible box.
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).
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(world(Vec2::new(x, gb.min.y))), xf.to_screen(world(Vec2::new(x, gb.max.y)))],
[xf.to_screen(Vec2::new(x, wb.min.y)), xf.to_screen(Vec2::new(x, wb.max.y))],
Stroke::new(1.0, if is_major { t.grid_major } else { t.grid_minor }),
));
}
@@ -56,20 +49,19 @@ 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(world(Vec2::new(gb.min.x, y))), xf.to_screen(world(Vec2::new(gb.max.x, y)))],
[xf.to_screen(Vec2::new(wb.min.x, y)), xf.to_screen(Vec2::new(wb.max.x, y))],
Stroke::new(1.0, if is_major { t.grid_major } else { t.grid_minor }),
));
}
}
p.extend(lines);
}
// 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));
}
// 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));
}
}
@@ -86,9 +78,7 @@ fn draw_iso_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) {
}
d *= 5.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 (origin, angle) = app.session.doc().map(cadcraft_engine::snap::grid_frame).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| {
-17
View File
@@ -1,23 +1,6 @@
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 };
+12 -29
View File
@@ -48,23 +48,16 @@ pub(super) fn draw_lock(p: &egui::Painter, c: Pos2, color: Color32) {
));
}
/// 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) {
pub(super) fn draw_ucs_icon(p: &egui::Painter, rect: Rect) {
let t = Tokens::get();
let (o, x, y) = (at.origin, at.x, at.y);
let arm = crate::viewcube::ARM;
let o = pos2(rect.left() + 36.0, rect.bottom() - 34.0);
let st = Stroke::new(1.0, t.canvas_ink);
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));
}
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);
let f = egui::FontId::proportional(13.0);
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);
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);
}
pub(super) fn viewport_label(p: &egui::Painter, rect: Rect) {
@@ -75,14 +68,15 @@ 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);
// 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;
// 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));
p.rect_filled(pill, 8.0, Color32::from_rgb(0x48, 0x50, 0x5c));
let ink = Tokens::DARK.canvas_ink;
let label = p.layout_no_wrap(ucs_pill_text(app), crate::theme::small(), ink);
let label = p.layout_no_wrap(crate::tl!("WCS").to_string(), 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;
@@ -90,14 +84,3 @@ 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 }
}
+1 -2
View File
@@ -381,9 +381,8 @@ 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, in the current UCS.
// Coordinates.
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!(
"{}, {}, {}",
+1 -2
View File
@@ -57,8 +57,7 @@ pub fn dyn_frame(app: &CadApp) -> Option<crate::dyninput::Frame> {
return None;
}
let p = app.session.current_prompt().filter(cadcraft_engine::pointmod::accepts)?;
let ucs = app.session.input_ucs();
Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute, ucs })
Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute })
}
/// Take Tab away from egui before it moves keyboard focus to the next widget (which would leave
+14 -59
View File
@@ -48,8 +48,6 @@ 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 {
@@ -57,11 +55,10 @@ 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, in UCS coordinates: the last point, or the UCS
/// origin.
/// Where the typed values are measured from.
pub fn origin(&self) -> Vec2 {
match self.base {
Some(b) if !self.absolute => self.ucs.to_ucs(b),
Some(b) if !self.absolute => b,
_ => Vec2::ZERO,
}
}
@@ -70,9 +67,9 @@ impl Frame {
self.base.is_some() && !self.absolute
}
/// The live (X, Y) or (distance, angle in radians) of `cursor` (a world point), in the UCS.
/// The live (X, Y) or (distance, angle in radians) of `cursor`.
pub fn live(&self, format: Format, cursor: Vec2) -> (f64, f64) {
let d = self.ucs.to_ucs(cursor) - self.origin();
let d = cursor - self.origin();
match format {
Format::Cartesian => (d.x, d.y),
Format::Polar => (d.len(), d.y.atan2(d.x)),
@@ -148,35 +145,32 @@ 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 };
// In UCS coordinates; `p` and the result are world points.
let (o, u) = (frame.origin(), frame.ucs.to_ucs(p));
let o = frame.origin();
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 frame.ucs.to_wcs(q);
return q;
}
}
let q = match entry.format {
Format::Cartesian => Vec2::new(o.x + v, u.y),
match entry.format {
Format::Cartesian => Vec2::new(o.x + v, p.y),
Format::Polar => {
let d = u - o;
let d = p - 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` (UCS coordinates), so what was previewed is exactly what
/// is placed.
/// the finished point is sent as `#x,y`, 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;
@@ -187,8 +181,7 @@ 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 the UCS X axis counterclockwise, as previewed, whatever
// ANGBASE/ANGDIR say.
// `<<`: degrees from +X counterclockwise, as previewed, whatever ANGBASE/ANGDIR say.
Format::Polar => format!("@{first}<<{}", second.to_degrees()),
});
}
@@ -237,7 +230,7 @@ mod tests {
use super::*;
fn second_point(base: Vec2) -> Frame {
Frame { base: Some(base), cartesian: false, absolute: false, ..Frame::default() }
Frame { base: Some(base), cartesian: false, absolute: false }
}
fn sent(text: &str, frame: &Frame, cursor: Vec2, last: Vec2) -> Option<Vec2> {
@@ -275,44 +268,6 @@ 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();
@@ -321,7 +276,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, ..Frame::default() };
let f = Frame { base: Some(Vec2::new(5.0, 5.0)), cartesian: true, absolute: true };
assert!(close(sent("40,100", &f, Vec2::ZERO, Vec2::new(5.0, 5.0)), Vec2::new(40.0, 100.0)));
}
+2 -2
View File
@@ -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: off (UCSICON, which the drawing keeps).
app.run("ucsicon", serde_json::json!({"on": false})).unwrap();
// The UCS icon paints "X" and "Y" too.
app.ui.show_ucs_icon = false;
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);
-8
View File
@@ -1356,14 +1356,6 @@
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. Введіть назву псевдоніма.
1 # CADCraft Ukrainian interface catalog — original translations by @dmatviichuk.
1356
1357
1358
1359
1360
1361
-7
View File
@@ -1503,13 +1503,6 @@ 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.
+2
View File
@@ -103,6 +103,7 @@ 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
@@ -200,6 +201,7 @@ 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(),
+4 -14
View File
@@ -102,7 +102,6 @@ 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),
@@ -308,16 +307,9 @@ fn run_ui_toggle_command(app: &mut CadApp, id: &str, params: &Value) -> Option<R
toggle(&mut app.ui.show_viewcube, 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.ucsicon" => {
toggle(&mut app.ui.show_ucs_icon, params);
Ok(Value::Null)
}
"ui.toggle.menubar" => {
toggle(&mut app.ui.in_window_menu, params);
@@ -700,9 +692,7 @@ pub fn tree(app: &CadApp) -> Vec<(String, Vec<Entry>)> {
}
for (id, label, menu, sc) in UI_COMMANDS {
if !menu.is_empty() {
// 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);
add(menu, label, id, *sc, true);
}
}
if let Some((_, file)) = out.iter_mut().find(|(m, _)| m == "File") {
+28 -241
View File
@@ -1,14 +1,14 @@
//! The navigation overlays on the drawing area: the ViewCube (Top face, Home, compass ring and
//! the UCS menu) and the UCS icon.
//! the WCS 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`, `ucs`.
//! `zoom.extents` (Top face, Home), `ui.toggle.viewcube`, `ui.toggle.ucsicon`.
//!
//! 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.
//! 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.
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(84.0, 16.0)),
pill: Rect::from_center_size(center + vec2(0.0, ring + 26.0), vec2(56.0, 16.0)),
bounds: Rect::from_center_size(center, vec2(2.0 * (ring + 10.0), 2.0 * (ring + 10.0))),
}
}
@@ -131,8 +131,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, l: &Layout) {
if let Some((id, params)) = action {
let _ = app.run(id, params);
}
// The UCS pill (painted by the canvas, wide enough for a cut-short UCS name) opens the
// coordinate-system menu.
// The WCS pill (painted by the canvas) 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));
@@ -154,164 +153,48 @@ 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);
}
/// 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
}
/// 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))]
}
/// 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, place: &IconPlace) {
pub fn ucs_icon(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) {
let t = Tokens::get();
// 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 [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);
let st = Stroke::new(2.0, t.hover);
let p = ui.painter_at(canvas);
p.line_segment([o, o + place.x * ARM], st);
p.line_segment([o, o + place.y * ARM], st);
p.line_segment([o, o + vec2(60.0, 0.0)], st);
p.line_segment([o, o + vec2(0.0, -60.0)], 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: World, the drawing's named UCSs (picking one makes it current,
/// through the UCS command) and the icon switch.
/// The coordinate-system menu: the WCS (the only coordinate system so far) and the icon switch.
fn ucs_menu(app: &mut CadApp, popup: egui::Popup<'_>) {
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;
let mut hide = false;
popup.show(|ui| {
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.radio(true, "World (WCS)").on_hover_text("CADCraft draws in the World Coordinate System; user coordinate systems aren't available yet.");
ui.separator();
if ui.button("Hide UCS Icon").clicked() {
action = Some(("ui.toggle.ucsicon", json!({"on": false})));
hide = true;
ui.close();
}
});
if let Some((id, params)) = action {
menu_action(app, id, params);
if hide {
let _ = app.run("ui.toggle.ucsicon", json!({"on": false}));
}
}
/// 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::*;
@@ -355,22 +238,6 @@ 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)
@@ -414,91 +281,11 @@ 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();
// 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);
let [x, _] = ucs_arms(canvas(&app));
click(&mut app, &ctx, x.center(), 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));
+1 -1
View File
@@ -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 };
+1 -1
View File
@@ -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` 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)
- **Geometry:** `polar distance angle inters trans` (`trans` returns the point: no UCS yet)
- **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`
+1 -1
View File
@@ -48,7 +48,7 @@ Example client configuration (Claude Code / Claude Desktop):
| `execute {"command": "loops", "params": {tolerance?, maxPairs?, limit?, offset?}}` | Implied closed loops from loose LINE and ARC chains: each closed loop with its member handles, perimeter, area and winding, exact with arcs; each open chain with the endpoint gap, its location (`at`, `ends`) and length; and branch junctions (three or more ends meeting), reported but not resolved. `tolerance` defaults to 1e-9 × the extents diagonal; the quadratic endpoint pairing stops at `maxPairs` (default 1,000,000) and reports `capped` with `pairTestsNeeded` instead of guessing from a partial pairing. |
| `query_entities {type?, layer?, selected?, window?, crossing?, limit?, offset?}` | Filtered entities with handles and geometry. `selected: true` restricts results to the current selection in the active space; an empty selection returns no entities. Omitted/false queries all entities in that space. Filters combine before paging. `window` `[[x0,y0],[x1,y1]]` finds objects whose geometry is inside it or crosses it (`crossing: false`: entirely inside). `count` is every match, `returned` the page (`offset`, `limit`, default 500). |
| `render {width?, height?, fit?, window?, background?, plot_style?}` | A PNG image of the drawing, or of just the area `window` `[[x0,y0],[x1,y1]]` (one sheet or room of a large drawing; 1600 px wide with the window's shape unless sized). `background`: `"dark"` (the canvas; the default without a plot style), `"white"` (the default with one, as a plot prints on paper), `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. `monochrome.ctb` (every colour black) or `grayscale.ctb`; `"none"` (or `""`) draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown value is refused. The result is an image content block (`content[0].type` is `"image"`), not text. |
| `find_text {contains?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (any case), layer and a window around the insertion points. Read-only (the `texts` command). |
| `find_text {contains?, query?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (`contains`, or `query` as an alias; any case), layer and a window around the insertion points. Read-only (the `texts` command). |
| `new_drawing {metric?}`, `open {path}`, `save {path?}`, `cancel` | Files and Escape. `save` to a `.svg`, `.png` or `.pdf` path exports: the drawing keeps its name and unsaved changes. |
| `screenshot`, `ui_inspect`, `ui_click {x, y}` | Only when connected to the app. |
+2 -1
View File
@@ -81,7 +81,8 @@ prints as `Normal`. A colour-dependent table ignores the property.
style and the named styles.
- `layer.set {name, plotStyle}` sets a layer's plot style.
- `stylesmanager {action, …}` manages the tables: `list`, `get`, `new` (`kind`, `from`), `set`
(`style: {name, …fields}`, `removeStyle`, `description`), `delete`, `load` (`path` or `text`)
(`style: {name, …fields}`, `removeStyle`, `description`; it replies with the table's name and
only what changed), `delete`, `load` (`path` or `text`)
and `save` (`path`, or returns `text`). Typed or chosen from **File ▸ Plot Styles...**, it
opens the Plot Style Manager dialog.