mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-03 03:08:22 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8698649da1 | ||
|
|
4610454c58 | ||
|
|
a6add77c5a | ||
|
|
e90f00dcf3 | ||
|
|
7afe6b3b78 | ||
|
|
17e0c81967 | ||
|
|
adca169651 | ||
|
|
d049a1cf7f | ||
|
|
4ecd4aed42 | ||
|
|
636dd26f07 | ||
|
|
0d70d25f07 | ||
|
|
15c8926c97 | ||
|
|
300a64f711 | ||
|
|
27a9b91f3c | ||
|
|
e48f8805a5 | ||
|
|
9bbe7b69a3 | ||
|
|
8cde239e64 | ||
|
|
15c3c9564a | ||
|
|
f288082ff3 | ||
|
|
0fd046c4c1 | ||
|
|
7bd33b7ff1 | ||
|
|
9ce7cde286 | ||
|
|
0cf540495f | ||
|
|
6050f3c396 | ||
|
|
3371028cdf | ||
|
|
206d40bc0d | ||
|
|
f796d5c8fc | ||
|
|
03bf451124 | ||
|
|
2659b44569 | ||
|
|
e5f62c9546 | ||
|
|
f5a70b0e98 | ||
|
|
13aa3a5cc6 | ||
|
|
3fe6d7e954 | ||
|
|
5950cbce24 | ||
|
|
88a3069ea2 | ||
|
|
20e2efebf7 | ||
|
|
a193f64e04 | ||
|
|
494dbd965b | ||
|
|
bea1843497 | ||
|
|
f9284510ea | ||
|
|
723997489a | ||
|
|
0bc5f721fb | ||
|
|
7aaee29277 | ||
|
|
334bcc3dc0 | ||
|
|
3944964adf | ||
|
|
e9ac879b83 | ||
|
|
ffde4b3bbe | ||
|
|
0db2d73e02 | ||
|
|
fcb2188143 | ||
|
|
ab183249f9 | ||
|
|
cd4912b003 | ||
|
|
61d1f267cf | ||
|
|
b9c9162b14 | ||
|
|
bbf613e944 | ||
|
|
91acccc36a | ||
|
|
dec54a9ded | ||
|
|
38a239b1e9 | ||
|
|
60ac79d4b5 | ||
|
|
a65a9b36b5 | ||
|
|
808ae34499 | ||
|
|
f8769d9650 | ||
|
|
0b2cfae274 | ||
|
|
c647cb4eb9 | ||
|
|
0314c8bf2a | ||
|
|
71f4879f9c | ||
|
|
472d3661ce | ||
|
|
ca90388ff3 | ||
|
|
ded4122de0 | ||
|
|
fe3b20a37a | ||
|
|
9746b6999a | ||
|
|
0ca0af9026 | ||
|
|
6971715295 | ||
|
|
5bfba91aa8 | ||
|
|
080c96aa06 | ||
|
|
a2f732118f | ||
|
|
c2af11dfa7 | ||
|
|
b1dcb46e08 | ||
|
|
c00bc59949 | ||
|
|
1b577e9eed | ||
|
|
29bf02b6ce | ||
|
|
1998da2643 | ||
|
|
28ed9c58a7 | ||
|
|
a3560a1442 | ||
|
|
c40ff9603e | ||
|
|
595ccf2b06 | ||
|
|
8acdceeb61 | ||
|
|
4ce72c668a | ||
|
|
ebeee968b5 | ||
|
|
2eaf90df4b | ||
|
|
d8cf5fbb62 | ||
|
|
bf3e607bd6 | ||
|
|
6042310fc7 | ||
|
|
1ec5d20c84 | ||
|
|
723810f768 | ||
|
|
60e22f38c4 | ||
|
|
ba63055fd3 | ||
|
|
cec2e0c04a | ||
|
|
8fb5e95f15 | ||
|
|
5f4a17cb7c | ||
|
|
1c02f239c3 | ||
|
|
ea0d0e9595 | ||
|
|
5c24bc3dcf | ||
|
|
5689203791 | ||
|
|
b99ea8905e | ||
|
|
c1c97ed00e | ||
|
|
a551f206e8 | ||
|
|
b70c8609c9 | ||
|
|
55ec024e31 | ||
|
|
64cb95d8ec | ||
|
|
4a0063f5f6 | ||
|
|
f4f0702d08 | ||
|
|
98401d6de2 | ||
|
|
97fbaf7da4 | ||
|
|
90a239b410 |
@@ -45,6 +45,31 @@ pub struct ForeignExtra {
|
|||||||
/// Unmodelled groups of the record's own last subclass, written just before its xdata. Filled
|
/// Unmodelled groups of the record's own last subclass, written just before its xdata. Filled
|
||||||
/// on save from the entity itself ([`crate::Viewport::extra`]), so that copies keep them.
|
/// on save from the entity itself ([`crate::Viewport::extra`]), so that copies keep them.
|
||||||
pub tail: Vec<RawTag>,
|
pub tail: Vec<RawTag>,
|
||||||
|
/// A lightweight polyline's vertex identifiers (group 91, DXF 2010 and later) as read: one per
|
||||||
|
/// vertex in the polyline's order; empty when the file gave none. Geometric constraints name the
|
||||||
|
/// polyline's segments by them, so they are written back while the polyline's vertices are
|
||||||
|
/// where they were read ([`vertex_ids_for`]).
|
||||||
|
pub vertex_ids: Vec<VertexId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A vertex of a lightweight polyline as it was read: its identifier and its point as the
|
||||||
|
/// polyline has it once read (a polyline whose normal points down is read mirrored in x).
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||||
|
pub struct VertexId {
|
||||||
|
/// The identifier (group 91); 0 for a vertex without one.
|
||||||
|
pub id: i32,
|
||||||
|
pub x: f64,
|
||||||
|
pub y: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The identifiers `kept` gives the vertices at `points`, in their order, while every vertex is
|
||||||
|
/// where it was read. `None` once a vertex was added, removed, moved or the order changed: the
|
||||||
|
/// identifiers no longer say which vertex is which.
|
||||||
|
pub fn vertex_ids_for(kept: &[VertexId], points: impl ExactSizeIterator<Item = (f64, f64)> + Clone) -> Option<Vec<i32>> {
|
||||||
|
if kept.is_empty() || kept.len() != points.len() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
kept.iter().zip(points).all(|(k, (x, y))| k.x == x && k.y == y).then(|| kept.iter().map(|k| k.id).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ForeignExtra {
|
impl ForeignExtra {
|
||||||
@@ -55,6 +80,7 @@ impl ForeignExtra {
|
|||||||
&& self.color_book.is_none()
|
&& self.color_book.is_none()
|
||||||
&& self.props.is_empty()
|
&& self.props.is_empty()
|
||||||
&& self.tail.is_empty()
|
&& self.tail.is_empty()
|
||||||
|
&& self.vertex_ids.is_empty()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -154,6 +154,8 @@ impl Header {
|
|||||||
// Annotation scale of model space; annotative objects of other scales show (1) or not.
|
// Annotation scale of model space; annotative objects of other scales show (1) or not.
|
||||||
h.set_str("CANNOSCALE", "1:1");
|
h.set_str("CANNOSCALE", "1:1");
|
||||||
h.set_i64("ANNOALLVISIBLE", 1);
|
h.set_i64("ANNOALLVISIBLE", 1);
|
||||||
|
// Written to DXF as $REGENMODE; a header variable the drawing lacks is not written.
|
||||||
|
h.set_i64("REGENMODE", 1);
|
||||||
h
|
h
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -343,6 +343,11 @@ fn eq_variants(o: &TanObj) -> Vec<Eq3> {
|
|||||||
|
|
||||||
/// Circle tangent to three objects, nearest the pick points (Newton on all sign combinations).
|
/// Circle tangent to three objects, nearest the pick points (Newton on all sign combinations).
|
||||||
pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
|
pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
|
||||||
|
ttt_where(objs, |_| true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`ttt`] among the circles `ok` accepts.
|
||||||
|
pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Option<Circle> {
|
||||||
let [(o1, p1), (o2, p2), (o3, p3)] = objs;
|
let [(o1, p1), (o2, p2), (o3, p3)] = objs;
|
||||||
let mut starts: Vec<[f64; 3]> = Vec::new();
|
let mut starts: Vec<[f64; 3]> = Vec::new();
|
||||||
let cen = (p1 + p2 + p3) / 3.0;
|
let cen = (p1 + p2 + p3) / 3.0;
|
||||||
@@ -350,6 +355,20 @@ pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
|
|||||||
starts.push([cen.x, cen.y, rad.max(1e-3)]);
|
starts.push([cen.x, cen.y, rad.max(1e-3)]);
|
||||||
if let Some(c) = Circle::from_3_points(p1, p2, p3) {
|
if let Some(c) = Circle::from_3_points(p1, p2, p3) {
|
||||||
starts.push([c.center.x, c.center.y, c.radius]);
|
starts.push([c.center.x, c.center.y, c.radius]);
|
||||||
|
} else {
|
||||||
|
// The picks lie in one line. When the circles picked are centred on it too, every Newton
|
||||||
|
// step from a start on that line stays on it: start off it as well, on both sides, from
|
||||||
|
// the circle through the two picks farthest apart and a point beside them.
|
||||||
|
let (a, b) = [(p1, p2), (p1, p3), (p2, p3)].into_iter().max_by(|x, y| x.0.dist(x.1).total_cmp(&y.0.dist(y.1))).unwrap_or((p1, p3));
|
||||||
|
let span = a.dist(b);
|
||||||
|
let n = (b - a).normalized().perp();
|
||||||
|
if span.is_finite() && span > 0.0 && n.is_finite() {
|
||||||
|
for side in [1.0, -1.0] {
|
||||||
|
if let Some(c) = Circle::from_3_points(a, b, (a + b) / 2.0 + n * (span * side)) {
|
||||||
|
starts.push([c.center.x, c.center.y, c.radius]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let mut best: Option<(f64, Circle)> = None;
|
let mut best: Option<(f64, Circle)> = None;
|
||||||
let scale = rad.max(p1.dist(p2)).max(1e-6);
|
let scale = rad.max(p1.dist(p2)).max(1e-6);
|
||||||
@@ -379,6 +398,9 @@ pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let c = Circle::new(Vec2::new(x[0], x[1]), x[2]);
|
let c = Circle::new(Vec2::new(x[0], x[1]), x[2]);
|
||||||
|
if !ok(&c) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let sc = score(&c, &objs);
|
let sc = score(&c, &objs);
|
||||||
if best.is_none_or(|(b, _)| sc < b - 1e-12) {
|
if best.is_none_or(|(b, _)| sc < b - 1e-12) {
|
||||||
best = Some((sc, c));
|
best = Some((sc, c));
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use super::{
|
|||||||
Accept, Arc, Circle, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, added, arc, bad, circle, f64_req, line, number,
|
Accept, Arc, Circle, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, added, arc, bad, circle, f64_req, line, number,
|
||||||
point_param, size_param,
|
point_param, size_param,
|
||||||
};
|
};
|
||||||
|
use crate::snap;
|
||||||
|
|
||||||
pub(super) fn run_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
pub(super) fn run_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||||
let c = if let Some(center) = point_param(p, "center") {
|
let c = if let Some(center) = point_param(p, "center") {
|
||||||
@@ -51,6 +52,8 @@ pub(super) fn run_arc(s: &mut Session, p: &Value) -> Result<Value> {
|
|||||||
pub(super) struct CircleM {
|
pub(super) struct CircleM {
|
||||||
mode: u8, // 0 center-radius, 1 = 3P, 2 = 2P, 3 = TTR
|
mode: u8, // 0 center-radius, 1 = 3P, 2 = 2P, 3 = TTR
|
||||||
pts: Vec<Vec2>,
|
pts: Vec<Vec2>,
|
||||||
|
/// 3P: the circle or arc each point was picked on with a tangent snap, by point.
|
||||||
|
tans: Vec<Option<snap::SnapCurve>>,
|
||||||
diameter: bool,
|
diameter: bool,
|
||||||
/// The `Ttr` option hands over to the tangent-circle machine.
|
/// The `Ttr` option hands over to the tangent-circle machine.
|
||||||
delegate: Option<Box<dyn Interactive>>,
|
delegate: Option<Box<dyn Interactive>>,
|
||||||
@@ -69,18 +72,22 @@ impl Interactive for CircleM {
|
|||||||
match (self.mode, n) {
|
match (self.mode, n) {
|
||||||
(0, 0) => Prompt::new("Specify center point for circle", Accept::POINT).kw(&["3P", "2P", "Ttr (tan tan radius)"]),
|
(0, 0) => Prompt::new("Specify center point for circle", Accept::POINT).kw(&["3P", "2P", "Ttr (tan tan radius)"]),
|
||||||
(0, _) if self.diameter => {
|
(0, _) if self.diameter => {
|
||||||
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance()
|
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance().deferred()
|
||||||
}
|
}
|
||||||
(0, _) => {
|
(0, _) => {
|
||||||
let p =
|
let p = Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER)
|
||||||
Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER).kw(&["Diameter"]).base_opt(self.pts.first().copied()).distance();
|
.kw(&["Diameter"])
|
||||||
|
.base_opt(self.pts.first().copied())
|
||||||
|
.distance()
|
||||||
|
.deferred();
|
||||||
if last_r > 0.0 { p.default(format!("{last_r:.4}")) } else { p }
|
if last_r > 0.0 { p.default(format!("{last_r:.4}")) } else { p }
|
||||||
}
|
}
|
||||||
(1, k) => Prompt::new(
|
(1, k) => Prompt::new(
|
||||||
["Specify first point on circle", "Specify second point on circle", "Specify third point on circle"].get(k).copied().unwrap_or(""),
|
["Specify first point on circle", "Specify second point on circle", "Specify third point on circle"].get(k).copied().unwrap_or(""),
|
||||||
Accept::POINT,
|
Accept::POINT,
|
||||||
)
|
)
|
||||||
.base_opt(self.pts.last().copied()),
|
.base_opt(self.pts.last().copied())
|
||||||
|
.deferred(),
|
||||||
(2, k) => Prompt::new(
|
(2, k) => Prompt::new(
|
||||||
if k == 0 { "Specify first end point of circle's diameter" } else { "Specify second end point of circle's diameter" },
|
if k == 0 { "Specify first end point of circle's diameter" } else { "Specify second end point of circle's diameter" },
|
||||||
Accept::POINT,
|
Accept::POINT,
|
||||||
@@ -120,7 +127,14 @@ impl Interactive for CircleM {
|
|||||||
let r = if self.diameter { c.dist(*e) / 2.0 } else { c.dist(*e) };
|
let r = if self.diameter { c.dist(*e) / 2.0 } else { c.dist(*e) };
|
||||||
Some(Circle::new(*c, r))
|
Some(Circle::new(*c, r))
|
||||||
}
|
}
|
||||||
1 if self.pts.len() == 3 => Circle::from_3_points(self.pts[0], self.pts[1], self.pts[2]),
|
1 if self.pts.len() == 3 => match self.three_points() {
|
||||||
|
Some(c) => Some(c),
|
||||||
|
None => {
|
||||||
|
self.pts.pop();
|
||||||
|
self.tans.truncate(self.pts.len());
|
||||||
|
return Err(crate::EngineError::Other("Circle does not exist.".into()));
|
||||||
|
}
|
||||||
|
},
|
||||||
2 if self.pts.len() == 2 => Some(Circle::from_2_points(self.pts[0], self.pts[1])),
|
2 if self.pts.len() == 2 => Some(Circle::from_2_points(self.pts[0], self.pts[1])),
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
@@ -130,6 +144,29 @@ impl Interactive for CircleM {
|
|||||||
}
|
}
|
||||||
Ok(Step::Continue)
|
Ok(Step::Continue)
|
||||||
}
|
}
|
||||||
|
// 3P: a point picked with a tangent snap makes the circle tangent to that curve (#1512).
|
||||||
|
Input::Deferred(d) if self.mode == 1 => {
|
||||||
|
let tan = (d.mode == snap::mode::TAN && !matches!(d.curve, snap::SnapCurve::Line { .. })).then_some(d.curve);
|
||||||
|
self.tans.resize(self.pts.len(), None);
|
||||||
|
self.tans.push(tan);
|
||||||
|
self.input(s, Input::Point(d.at))
|
||||||
|
}
|
||||||
|
// A tangent picked for the radius: the circle around the center that touches the
|
||||||
|
// curve, on the side it was picked (#1512).
|
||||||
|
Input::Deferred(d) if self.mode == 0 && self.pts.len() == 1 => {
|
||||||
|
let Some(&c) = self.pts.first() else { return Ok(Step::Continue) };
|
||||||
|
// Around the picked curve's own center the circle would lie on it, not touch it.
|
||||||
|
let concentric =
|
||||||
|
matches!(d.curve, snap::SnapCurve::Circle { center, .. } | snap::SnapCurve::Arc { center, .. } if center.near(c, 1e-9));
|
||||||
|
let touch = d.curve.perpendiculars(c, d.at).into_iter().filter(|_| !concentric).min_by(|a, b| a.dist(d.at).total_cmp(&b.dist(d.at)));
|
||||||
|
match touch.map(|t| c.dist(t)).filter(|r| *r > 1e-12 && r.is_finite()) {
|
||||||
|
Some(r) => {
|
||||||
|
finish_circle(s, Circle::new(c, r))?;
|
||||||
|
Ok(Step::Done)
|
||||||
|
}
|
||||||
|
None => Err(crate::EngineError::Other("No circle around the center is tangent there.".into())),
|
||||||
|
}
|
||||||
|
}
|
||||||
Input::Text(t) if self.mode == 0 && self.pts.len() == 1 => {
|
Input::Text(t) if self.mode == 0 && self.pts.len() == 1 => {
|
||||||
let v = number(&t).ok_or_else(|| crate::EngineError::Other("Requires numeric distance or second point.".into()))?;
|
let v = number(&t).ok_or_else(|| crate::EngineError::Other("Requires numeric distance or second point.".into()))?;
|
||||||
let r = if self.diameter { v / 2.0 } else { v };
|
let r = if self.diameter { v / 2.0 } else { v };
|
||||||
@@ -174,6 +211,38 @@ impl Interactive for CircleM {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl CircleM {
|
||||||
|
/// The 3P circle: through the three points, or tangent to the curves picked with TAN.
|
||||||
|
fn three_points(&self) -> Option<Circle> {
|
||||||
|
let [a, b, c] = <[Vec2; 3]>::try_from(self.pts.as_slice()).ok()?;
|
||||||
|
if self.tans.iter().all(Option::is_none) {
|
||||||
|
return Circle::from_3_points(a, b, c);
|
||||||
|
}
|
||||||
|
let tan = |i: usize| self.tans.get(i).copied().flatten();
|
||||||
|
// A plain point is a circle of radius zero to pass through; an arc is solved as its circle.
|
||||||
|
let target = |i: usize, p: Vec2| {
|
||||||
|
let circle = match tan(i) {
|
||||||
|
Some(snap::SnapCurve::Circle { center, radius } | snap::SnapCurve::Arc { center, radius, .. }) => Circle::new(center, radius),
|
||||||
|
_ => Circle::new(p, 0.0),
|
||||||
|
};
|
||||||
|
crate::cmd::curves::TanObj::Circle(circle)
|
||||||
|
};
|
||||||
|
let pts = [a, b, c];
|
||||||
|
// The circle must touch an arc within its sweep, not elsewhere on the arc's circle, and
|
||||||
|
// not be the picked circle itself (which lies on it rather than touching it).
|
||||||
|
let touches = |found: &Circle| {
|
||||||
|
pts.iter().enumerate().all(|(i, p)| {
|
||||||
|
tan(i).is_none_or(|t| {
|
||||||
|
let same = matches!(target(i, *p), crate::cmd::curves::TanObj::Circle(o)
|
||||||
|
if o.center.dist(found.center) + (o.radius - found.radius).abs() <= 1e-9 * o.radius);
|
||||||
|
!same && t.contains(target(i, *p).touch(found))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
};
|
||||||
|
crate::cmd::curves::ttt_where([(target(0, a), a), (target(1, b), b), (target(2, c), c)], touches)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn finish_circle(s: &mut Session, c: Circle) -> Result<()> {
|
fn finish_circle(s: &mut Session, c: Circle) -> Result<()> {
|
||||||
s.add_entity(circle(c.center, c.radius))?;
|
s.add_entity(circle(c.center, c.radius))?;
|
||||||
s.doc_mut()?.header.set_f64("CIRCLERAD", c.radius);
|
s.doc_mut()?.header.set_f64("CIRCLERAD", c.radius);
|
||||||
|
|||||||
@@ -603,6 +603,64 @@ fn plot_path_extension_picks_the_format_like_export() {
|
|||||||
std::fs::remove_dir_all(&dir).ok();
|
std::fs::remove_dir_all(&dir).ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn osnap_in_mspace_skips_vplayer_frozen_layers() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("layer.new", &json!({"name": "Hidden"})).unwrap();
|
||||||
|
s.execute("line", &json!({"points": [[60, -25], [70, -25]]})).unwrap();
|
||||||
|
let line_h = s.doc().unwrap().model.iter().last().unwrap().handle;
|
||||||
|
s.execute("properties.set", &json!({"handles": [line_h], "layer": "Hidden"})).unwrap();
|
||||||
|
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
|
||||||
|
s.execute("mview", &json!({"p1": [20, 20], "p2": [220, 120]})).unwrap();
|
||||||
|
let vp_h = viewports(&s, "Layout1").last().unwrap().0;
|
||||||
|
s.execute("vplayer", &json!({"handles": [vp_h], "freeze": ["Hidden"]})).unwrap();
|
||||||
|
s.execute("mspace", &json!({"handle": vp_h})).unwrap();
|
||||||
|
|
||||||
|
let ap = s.pixel_size() * s.settings.aperture.max(1.0);
|
||||||
|
let d = ap * 0.5;
|
||||||
|
let model_before = s.doc().unwrap().model.len();
|
||||||
|
for (ovr, pt, name) in [
|
||||||
|
("end", format!("{},-25", 60.0 + d), "Endpoint"),
|
||||||
|
("mid", format!("{},-25", 65.0 + d), "Midpoint"),
|
||||||
|
("nea", format!("63,{}", -25.0 + d), "Nearest"),
|
||||||
|
] {
|
||||||
|
s.cmdline("line").unwrap();
|
||||||
|
s.cmdline(ovr).unwrap();
|
||||||
|
s.cmdline(&pt).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
s.log.last().map(String::as_str),
|
||||||
|
Some(format!("No {name} found for specified point.").as_str()),
|
||||||
|
"{ovr} should not snap to a line on a VPLAYER-frozen layer; log: {:?}",
|
||||||
|
s.log
|
||||||
|
);
|
||||||
|
s.cmdline("").unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(s.doc().unwrap().model.len(), model_before, "no new line should be created");
|
||||||
|
|
||||||
|
// Running osnaps through snap_cursor must also ignore the VPLAYER-frozen layer.
|
||||||
|
s.settings.osmode = crate::snap::mode::END | crate::snap::mode::MID | crate::snap::mode::NEA;
|
||||||
|
let cs = s.snap_cursor(
|
||||||
|
cadcraft_geom::Vec2::new(60.0 + d, -25.0),
|
||||||
|
&crate::snap::tracking::CursorQuery { base: None, deferred: false, corner: false, aperture: ap, tol: ap, now: 0.0, shift: false },
|
||||||
|
);
|
||||||
|
assert!(cs.snap.is_none(), "running osnap should not snap to a VPLAYER-frozen line: {:?}", cs.snap);
|
||||||
|
|
||||||
|
// A block reference on layer "0" containing an entity on "Hidden" must also not snap.
|
||||||
|
s.execute("block", &json!({"name": "B", "base": [60, -25], "handles": [line_h]})).unwrap();
|
||||||
|
let model_with_block = s.doc().unwrap().model.len();
|
||||||
|
s.cmdline("line").unwrap();
|
||||||
|
s.cmdline("end").unwrap();
|
||||||
|
s.cmdline(&format!("{},-25", 60.0 + d)).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
s.log.last().map(String::as_str),
|
||||||
|
Some("No Endpoint found for specified point."),
|
||||||
|
"end should not snap to a block entity on a VPLAYER-frozen layer; log: {:?}",
|
||||||
|
s.log
|
||||||
|
);
|
||||||
|
s.cmdline("").unwrap();
|
||||||
|
assert_eq!(s.doc().unwrap().model.len(), model_with_block);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn layout_set_frames_extents_away_from_origin() {
|
fn layout_set_frames_extents_away_from_origin() {
|
||||||
let mut s = Session::new();
|
let mut s = Session::new();
|
||||||
|
|||||||
@@ -237,7 +237,7 @@ impl Interactive for SetvarM {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &Value::String(t)) {
|
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &crate::sysvars::typed_value(&n, t)) {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
s.touch();
|
s.touch();
|
||||||
Ok(Step::Done)
|
Ok(Step::Done)
|
||||||
|
|||||||
@@ -126,14 +126,36 @@ pub fn snap_name(m: u32) -> &'static str {
|
|||||||
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
|
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the
|
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
|
||||||
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest
|
/// first, then every other snap of the modes in `osmode` under the aperture (each endpoint of
|
||||||
/// first, then deferred snaps, then Nearest), without repeats.
|
/// each object, each intersection …; [`crate::snap::osnap_all`]), best first, without repeats.
|
||||||
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||||
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
|
snap_candidates_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`snap_candidates`] skipping entities (and block leaves) on `frozen` layers in `space`.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn snap_candidates_with_frozen(
|
||||||
|
d: &Drawing,
|
||||||
|
space: &Space,
|
||||||
|
cursor: Vec2,
|
||||||
|
aperture: f64,
|
||||||
|
osmode: u32,
|
||||||
|
base: Option<Vec2>,
|
||||||
|
deferred: bool,
|
||||||
|
frozen: &[String],
|
||||||
|
) -> Vec<SnapHit> {
|
||||||
|
// A base that is not a number would give meaningless perpendiculars and tangents.
|
||||||
|
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 || base.is_some_and(|b| !b.is_finite()) {
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
}
|
}
|
||||||
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
|
let mut out: Vec<SnapHit> = crate::snap::osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen).into_iter().collect();
|
||||||
|
for h in crate::snap::osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen) {
|
||||||
|
if !out.iter().any(|o| o.same(&h, aperture)) {
|
||||||
|
out.push(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
|
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
|
||||||
@@ -356,12 +378,15 @@ impl Session {
|
|||||||
Frame::Snap { mode } => {
|
Frame::Snap { mode } => {
|
||||||
// Snap the point with this mode alone, within the aperture.
|
// Snap the point with this mode alone, within the aperture.
|
||||||
let prompt = self.current_prompt();
|
let prompt = self.current_prompt();
|
||||||
let space = self.space();
|
let (doc, space, frozen) = {
|
||||||
|
let st = self.state()?;
|
||||||
|
(st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec())
|
||||||
|
};
|
||||||
let aperture = self.pixel_size() * self.settings.aperture.max(1.0);
|
let aperture = self.pixel_size() * self.settings.aperture.max(1.0);
|
||||||
let hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 };
|
let hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 };
|
||||||
let base = prompt.as_ref().and_then(|q| q.base);
|
let base = prompt.as_ref().and_then(|q| q.base);
|
||||||
let deferred = prompt.as_ref().is_some_and(|q| q.deferred);
|
let deferred = prompt.as_ref().is_some_and(|q| q.deferred);
|
||||||
let hit = crate::snap::osnap(self.doc()?, &space, p, aperture, mode | hatch, base, deferred);
|
let hit = crate::snap::osnap_with_frozen(&doc, &space, p, aperture, mode | hatch, base, deferred, &frozen);
|
||||||
match hit {
|
match hit {
|
||||||
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
|
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
|
||||||
Some(h) => {
|
Some(h) => {
|
||||||
|
|||||||
@@ -76,8 +76,9 @@ pub struct Prompt {
|
|||||||
/// Rubber-band origin (for direct distance entry, ortho and polar).
|
/// Rubber-band origin (for direct distance entry, ortho and polar).
|
||||||
pub base: Option<Vec2>,
|
pub base: Option<Vec2>,
|
||||||
/// The command resolves deferred tangent/perpendicular snaps ([`Input::Deferred`]) at this
|
/// The command resolves deferred tangent/perpendicular snaps ([`Input::Deferred`]) at this
|
||||||
/// prompt (a point with no base yet, e.g. the first point of a line). Elsewhere a deferred
|
/// prompt (a point with no base yet, e.g. the first point of a line; with a base, only
|
||||||
/// pick arrives as the plain point it was picked at.
|
/// tangents, e.g. a circle's radius). Elsewhere a deferred pick arrives as the plain point it
|
||||||
|
/// was picked at.
|
||||||
pub deferred: bool,
|
pub deferred: bool,
|
||||||
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
|
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
|
||||||
/// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
|
/// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
|
||||||
|
|||||||
@@ -149,6 +149,9 @@ pub struct Settings {
|
|||||||
/// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes
|
/// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes
|
||||||
/// dialog; on by default, as in AutoCAD (Initial value 1).
|
/// dialog; on by default, as in AutoCAD (Initial value 1).
|
||||||
pub attdia: bool,
|
pub attdia: bool,
|
||||||
|
/// TEXTEVAL: 1 lets a routine's input be read as LISP where it would be text (default: 0).
|
||||||
|
/// Kept for routines that switch it around their prompts; no prompt reads it yet.
|
||||||
|
pub texteval: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Settings {
|
impl Default for Settings {
|
||||||
@@ -220,6 +223,7 @@ impl Default for Settings {
|
|||||||
auditctl: false,
|
auditctl: false,
|
||||||
attreq: true,
|
attreq: true,
|
||||||
attdia: true,
|
attdia: true,
|
||||||
|
texteval: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+581
-217
@@ -90,6 +90,24 @@ pub struct BlockLeaf {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl SnapHit {
|
impl SnapHit {
|
||||||
|
fn plain(mode: u32, point: Vec2) -> SnapHit {
|
||||||
|
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None, source: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same snap as `o`, for a Tab list without repeats: the same mode at the same point
|
||||||
|
/// (within a millionth of `aperture`), deferred or not alike (and if deferred, on the same
|
||||||
|
/// curve), and from the same source (this space, or one viewport). Overlapping viewports can
|
||||||
|
/// show different model points at one paper point; each stays a candidate, since DIST
|
||||||
|
/// measures in the model units of the viewport picked.
|
||||||
|
pub(crate) fn same(&self, o: &SnapHit, aperture: f64) -> bool {
|
||||||
|
self.mode == o.mode
|
||||||
|
// Deferred snaps on different curves at one provisional point stay apart: the line
|
||||||
|
// drawn from each depends on its curve.
|
||||||
|
&& self.deferred.map(|d| d.curve) == o.deferred.map(|d| d.curve)
|
||||||
|
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
|
||||||
|
&& self.point.near(o.point, aperture * 1e-6)
|
||||||
|
}
|
||||||
|
|
||||||
/// The command input a pick at this snap gives: a deferred snap or a plain point.
|
/// The command input a pick at this snap gives: a deferred snap or a plain point.
|
||||||
pub fn input(&self) -> crate::Input {
|
pub fn input(&self) -> crate::Input {
|
||||||
match self.deferred {
|
match self.deferred {
|
||||||
@@ -97,33 +115,6 @@ impl SnapHit {
|
|||||||
None => crate::Input::Point(self.point),
|
None => crate::Input::Point(self.point),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn plain(mode: u32, point: Vec2) -> SnapHit {
|
|
||||||
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None, source: None }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where this hit sorts among the candidates near a cursor: specific snaps by distance
|
|
||||||
/// (Endpoint and Intersection favoured a little), then deferred snaps, then Nearest.
|
|
||||||
fn rank(&self, cursor: Vec2, aperture: f64) -> (u8, f64) {
|
|
||||||
let class = if self.deferred.is_some() {
|
|
||||||
1
|
|
||||||
} else if self.mode == mode::NEA {
|
|
||||||
2
|
|
||||||
} else {
|
|
||||||
0
|
|
||||||
};
|
|
||||||
(class, snap_score(self.mode, self.point, cursor, aperture))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The same snap as `o`: mode and point, from the same source (paper space, or one
|
|
||||||
/// viewport). Overlapping viewports can show different model points at one paper point;
|
|
||||||
/// each stays a candidate, since DIST measures in the model units of the viewport picked.
|
|
||||||
fn same(&self, o: &SnapHit) -> bool {
|
|
||||||
self.mode == o.mode
|
|
||||||
&& self.deferred.is_some() == o.deferred.is_some()
|
|
||||||
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
|
|
||||||
&& self.point.near(o.point, 1e-9 * (1.0 + self.point.len()))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The curve a deferred snap refers to.
|
/// The curve a deferred snap refers to.
|
||||||
@@ -162,12 +153,16 @@ impl SnapCurve {
|
|||||||
}
|
}
|
||||||
/// Points on the curve whose perpendicular passes through `p`; `picked` is where the curve
|
/// Points on the curve whose perpendicular passes through `p`; `picked` is where the curve
|
||||||
/// was picked, kept when `p` is the center of a circle or arc (every radius is perpendicular).
|
/// was picked, kept when `p` is the center of a circle or arc (every radius is perpendicular).
|
||||||
fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
|
pub(crate) fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
|
||||||
match self {
|
match self {
|
||||||
SnapCurve::Circle { center, radius } | SnapCurve::Arc { center, radius, .. } => {
|
SnapCurve::Circle { center, radius } | SnapCurve::Arc { center, radius, .. } => {
|
||||||
let u = (p - *center).normalized();
|
let u = (p - *center).normalized();
|
||||||
if u == Vec2::ZERO {
|
if u == Vec2::ZERO {
|
||||||
vec![Circle::new(*center, *radius).closest(picked)]
|
// On an arc, the point within its sweep.
|
||||||
|
vec![match *self {
|
||||||
|
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(picked),
|
||||||
|
_ => Circle::new(*center, *radius).closest(picked),
|
||||||
|
}]
|
||||||
} else {
|
} else {
|
||||||
[*center + u * *radius, *center - u * *radius].into_iter().filter(|q| self.contains(*q)).collect()
|
[*center + u * *radius, *center - u * *radius].into_iter().filter(|q| self.contains(*q)).collect()
|
||||||
}
|
}
|
||||||
@@ -254,23 +249,34 @@ fn prim_segments(p: &Prim) -> Vec<Segment> {
|
|||||||
/// Tangent and perpendicular snaps need the base point (the other end of the line). With no
|
/// Tangent and perpendicular snaps need the base point (the other end of the line). With no
|
||||||
/// base and `deferred` set (the prompt says it can resolve them, `Prompt.deferred`),
|
/// base and `deferred` set (the prompt says it can resolve them, `Prompt.deferred`),
|
||||||
/// they snap as *deferred*: the hit carries the curve and is resolved once the other end is
|
/// they snap as *deferred*: the hit carries the curve and is resolved once the other end is
|
||||||
/// known. Deferred hits only win where no other snap does (they are as unspecific as Nearest).
|
/// known. With a base and `deferred` set, tangents to circles and circular arcs are deferred too
|
||||||
|
/// (CIRCLE's radius: the circle around the base that touches the curve, #1512); an elliptical arc
|
||||||
|
/// or a spline keeps its ordinary tangent from the base. Deferred hits only win
|
||||||
|
/// where no other snap does (they are as unspecific as Nearest).
|
||||||
pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Option<SnapHit> {
|
pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Option<SnapHit> {
|
||||||
|
osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`osnap`] skipping entities (and block leaves) on `frozen` layers in `space`.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn osnap_with_frozen(
|
||||||
|
d: &Drawing,
|
||||||
|
space: &Space,
|
||||||
|
cursor: Vec2,
|
||||||
|
aperture: f64,
|
||||||
|
osmode: u32,
|
||||||
|
base: Option<Vec2>,
|
||||||
|
deferred: bool,
|
||||||
|
frozen: &[String],
|
||||||
|
) -> Option<SnapHit> {
|
||||||
if osmode == 0 || osmode & mode::OFF != 0 {
|
if osmode == 0 || osmode & mode::OFF != 0 {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let ix = crate::spatial::index(d, space);
|
let ix = crate::spatial::index(d, space);
|
||||||
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred)
|
osnap_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred, frozen).0
|
||||||
}
|
|
||||||
|
|
||||||
/// Every object snap within `aperture` of `cursor`, the one [`osnap`] picks first and the rest
|
|
||||||
/// in the order Tab cycles them: specific snaps nearest first, then deferred snaps, then Nearest.
|
|
||||||
/// Snaps seen through layout viewports are included.
|
|
||||||
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
|
||||||
let ix = crate::spatial::index(d, space);
|
|
||||||
osnap_all_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred).0
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
pub(crate) fn osnap_with(
|
pub(crate) fn osnap_with(
|
||||||
d: &Drawing,
|
d: &Drawing,
|
||||||
@@ -282,7 +288,7 @@ pub(crate) fn osnap_with(
|
|||||||
base: Option<Vec2>,
|
base: Option<Vec2>,
|
||||||
deferred: bool,
|
deferred: bool,
|
||||||
) -> Option<SnapHit> {
|
) -> Option<SnapHit> {
|
||||||
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred).0
|
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred, &[]).0
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Find the best object snap and retain the local-space primitives gathered for that query.
|
/// Find the best object snap and retain the local-space primitives gathered for that query.
|
||||||
@@ -296,40 +302,21 @@ pub(crate) fn osnap_with_neighborhood(
|
|||||||
osmode: u32,
|
osmode: u32,
|
||||||
base: Option<Vec2>,
|
base: Option<Vec2>,
|
||||||
deferred: bool,
|
deferred: bool,
|
||||||
|
frozen: &[String],
|
||||||
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
|
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
|
||||||
let (all, prims) = osnap_all_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred);
|
|
||||||
(all.into_iter().next(), prims)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every object snap near the cursor ([`osnap_all`]) and the local-space primitives gathered.
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
fn osnap_all_with_neighborhood(
|
|
||||||
d: &Drawing,
|
|
||||||
space: &Space,
|
|
||||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
|
||||||
cursor: Vec2,
|
|
||||||
aperture: f64,
|
|
||||||
osmode: u32,
|
|
||||||
base: Option<Vec2>,
|
|
||||||
deferred: bool,
|
|
||||||
) -> (Vec<SnapHit>, Option<Vec<Prim>>) {
|
|
||||||
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
|
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
|
||||||
return (Vec::new(), None);
|
return (None, None);
|
||||||
}
|
}
|
||||||
let (mut all, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
|
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, None) {
|
||||||
Some((hits, prims)) => (hits, Some(prims)),
|
Some((hit, prims)) => (hit, Some(prims)),
|
||||||
None => (Vec::new(), None),
|
None => (None, None),
|
||||||
};
|
};
|
||||||
let views = viewport::near(d, space, cursor, aperture);
|
let views = viewport::near(d, space, cursor, aperture);
|
||||||
if views.is_empty() {
|
if views.is_empty() {
|
||||||
return (all, near_prims);
|
return (best.map(|(h, _)| h), near_prims);
|
||||||
}
|
}
|
||||||
let model = Space::Model;
|
let model = Space::Model;
|
||||||
let model_ix = crate::spatial::index(d, &model);
|
let model_ix = crate::spatial::index(d, &model);
|
||||||
// What a click picks across spaces stays as it was: each space's best snap, and a viewport's
|
|
||||||
// replaces the best so far only when it scores closer. A paper-space Nearest can therefore
|
|
||||||
// beat an Endpoint seen through a viewport, which `ranked` alone would put first.
|
|
||||||
let mut pick = all.first().copied();
|
|
||||||
for view in views {
|
for view in views {
|
||||||
let model_cursor = view.to_model(cursor);
|
let model_cursor = view.to_model(cursor);
|
||||||
let model_aperture = aperture / view.scale;
|
let model_aperture = aperture / view.scale;
|
||||||
@@ -337,66 +324,50 @@ fn osnap_all_with_neighborhood(
|
|||||||
if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) {
|
if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let hits = osnap_in(
|
let Some((cands, prims, src)) = collect_in(d, &model, &model_ix, model_cursor, model_aperture, osmode, &view.viewport.frozen_layers) else {
|
||||||
d,
|
continue;
|
||||||
&model,
|
};
|
||||||
&model_ix,
|
let clip = Some(view.model_clip);
|
||||||
model_cursor,
|
// The rank was found in model units: paper units are model units times the scale.
|
||||||
model_aperture,
|
let project = |(h, r): (SnapHit, Rank)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }));
|
||||||
osmode,
|
let first = finish(cands.clone(), &prims, &src, model_cursor, model_aperture, osmode, model_base, deferred, clip);
|
||||||
model_base,
|
// The model clip is the box round the viewport as the model sees it, larger than the
|
||||||
deferred,
|
// viewport when it is twisted: a snap inside it can still fall off the viewport. Then the
|
||||||
&view.viewport.frozen_layers,
|
// best of the others that is on it, as Tab ranks them.
|
||||||
Some(view.model_clip),
|
let hit = first.and_then(|f| {
|
||||||
);
|
project(f).or_else(|| {
|
||||||
if let Some(hit) = hits.first().and_then(|h| view.hit(*h))
|
finish_all(cands, &prims, &src, model_cursor, model_aperture, osmode, model_base, deferred, clip).into_iter().find_map(project)
|
||||||
&& pick.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
|
})
|
||||||
|
});
|
||||||
|
if let Some((hit, rank)) = hit
|
||||||
|
&& best.as_ref().is_none_or(|(_, b)| rank.beats(b))
|
||||||
{
|
{
|
||||||
pick = Some(hit);
|
best = Some((hit, rank));
|
||||||
}
|
|
||||||
all.extend(hits.into_iter().filter_map(|h| view.hit(h)));
|
|
||||||
}
|
|
||||||
let mut out = ranked(all, cursor, aperture);
|
|
||||||
if let Some(pick) = pick {
|
|
||||||
out.retain(|h| !h.same(&pick));
|
|
||||||
out.insert(0, pick);
|
|
||||||
}
|
|
||||||
(out, near_prims)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `hits` best first ([`SnapHit::rank`]), without repeats.
|
|
||||||
fn ranked(mut hits: Vec<SnapHit>, cursor: Vec2, aperture: f64) -> Vec<SnapHit> {
|
|
||||||
hits.sort_by(|a, b| {
|
|
||||||
let (ca, sa) = a.rank(cursor, aperture);
|
|
||||||
let (cb, sb) = b.rank(cursor, aperture);
|
|
||||||
ca.cmp(&cb).then(sa.total_cmp(&sb))
|
|
||||||
});
|
|
||||||
let mut out: Vec<SnapHit> = Vec::with_capacity(hits.len());
|
|
||||||
for h in hits {
|
|
||||||
if !out.iter().any(|o| o.same(&h)) {
|
|
||||||
out.push(h);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
out
|
(best.map(|(h, _)| h), near_prims)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
/// How a hit ranks against the hits of another space (paper space, another viewport) and, for
|
||||||
fn osnap_in(
|
/// Tab, against the other candidates: first the order [`finish`] tries them in (snap points, then
|
||||||
d: &Drawing,
|
/// a perpendicular or tangent on the object under the cursor or a center found from its curve,
|
||||||
space: &Space,
|
/// then deferred snaps, then Nearest), then its score within that tier, in the units of the cursor.
|
||||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
#[derive(Clone, Copy, Debug)]
|
||||||
cursor: Vec2,
|
struct Rank {
|
||||||
aperture: f64,
|
tier: u8,
|
||||||
osmode: u32,
|
score: f64,
|
||||||
base: Option<Vec2>,
|
}
|
||||||
deferred: bool,
|
|
||||||
frozen: &[String],
|
impl Rank {
|
||||||
clip: Option<Bounds2>,
|
fn cmp(&self, other: &Rank) -> std::cmp::Ordering {
|
||||||
) -> Vec<SnapHit> {
|
self.tier.cmp(&other.tier).then(self.score.total_cmp(&other.score))
|
||||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default()
|
}
|
||||||
|
|
||||||
|
fn beats(&self, other: &Rank) -> bool {
|
||||||
|
self.cmp(other).is_lt()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The snaps near the cursor in one space, best first, and the primitives gathered there.
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
fn osnap_in_with_prims(
|
fn osnap_in_with_prims(
|
||||||
d: &Drawing,
|
d: &Drawing,
|
||||||
@@ -409,7 +380,92 @@ fn osnap_in_with_prims(
|
|||||||
deferred: bool,
|
deferred: bool,
|
||||||
frozen: &[String],
|
frozen: &[String],
|
||||||
clip: Option<Bounds2>,
|
clip: Option<Bounds2>,
|
||||||
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
|
) -> Option<(Option<(SnapHit, Rank)>, Vec<Prim>)> {
|
||||||
|
let (cands, near_prims, src) = collect_in(d, space, ix, cursor, aperture, osmode, frozen)?;
|
||||||
|
let hit = finish(cands, &near_prims, &src, cursor, aperture, osmode, base, deferred, clip);
|
||||||
|
Some((hit, near_prims))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every snap of `osmode` under the aperture round `cursor`, best first: Tab cycles through
|
||||||
|
/// these. Each mode's points of every object nearby, the intersections, perpendicular and
|
||||||
|
/// tangent points from `base`, the centers found from their curves, the deferred snaps and the
|
||||||
|
/// nearest point of each object, ranked as [`osnap`] ranks them, without repeats and at most
|
||||||
|
/// [`MAX_CYCLE`]; in viewports too, as [`osnap`] snaps.
|
||||||
|
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||||
|
osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`osnap_all`] skipping entities (and block leaves) on `frozen` layers in `space`.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn osnap_all_with_frozen(
|
||||||
|
d: &Drawing,
|
||||||
|
space: &Space,
|
||||||
|
cursor: Vec2,
|
||||||
|
aperture: f64,
|
||||||
|
osmode: u32,
|
||||||
|
base: Option<Vec2>,
|
||||||
|
deferred: bool,
|
||||||
|
frozen: &[String],
|
||||||
|
) -> Vec<SnapHit> {
|
||||||
|
if osmode == 0
|
||||||
|
|| osmode & mode::OFF != 0
|
||||||
|
|| !cursor.is_finite()
|
||||||
|
|| !(aperture.is_finite() && aperture > 0.0)
|
||||||
|
|| base.is_some_and(|b| !b.is_finite())
|
||||||
|
{
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
let ix = crate::spatial::index(d, space);
|
||||||
|
let mut out: Vec<(SnapHit, Rank)> = Vec::new();
|
||||||
|
if let Some((cands, prims, src)) = collect_in(d, space, &ix, cursor, aperture, osmode, frozen) {
|
||||||
|
out = finish_all(cands, &prims, &src, cursor, aperture, osmode, base, deferred, None);
|
||||||
|
}
|
||||||
|
let model = Space::Model;
|
||||||
|
let views = viewport::near(d, space, cursor, aperture);
|
||||||
|
if !views.is_empty() {
|
||||||
|
let model_ix = crate::spatial::index(d, &model);
|
||||||
|
for view in views {
|
||||||
|
let (mc, ma, mb) = (view.to_model(cursor), aperture / view.scale, base.map(|p| view.to_model(p)));
|
||||||
|
if !mc.is_finite() || !(ma.is_finite() && ma > 0.0) || mb.is_some_and(|p| !p.is_finite()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some((cands, prims, src)) = collect_in(d, &model, &model_ix, mc, ma, osmode, &view.viewport.frozen_layers) else { continue };
|
||||||
|
// The rank was found in model units: paper units are model units times the scale.
|
||||||
|
out.extend(
|
||||||
|
finish_all(cands, &prims, &src, mc, ma, osmode, mb, deferred, Some(view.model_clip))
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(h, r)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }))),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.sort_by(|a, b| a.1.cmp(&b.1));
|
||||||
|
let mut unique: Vec<SnapHit> = Vec::with_capacity(out.len().min(MAX_CYCLE));
|
||||||
|
for (h, _) in out {
|
||||||
|
if unique.len() >= MAX_CYCLE {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if !unique.iter().any(|u| u.same(&h, aperture)) {
|
||||||
|
unique.push(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unique
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Most snaps [`osnap_all`] offers.
|
||||||
|
const MAX_CYCLE: usize = 256;
|
||||||
|
|
||||||
|
/// The candidate snap points near `cursor` (each with its mode) and the primitives near it:
|
||||||
|
/// [`gather_in`]'s, plus the intersections between those primitives, and what each lies on.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn collect_in(
|
||||||
|
d: &Drawing,
|
||||||
|
space: &Space,
|
||||||
|
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||||
|
cursor: Vec2,
|
||||||
|
aperture: f64,
|
||||||
|
osmode: u32,
|
||||||
|
frozen: &[String],
|
||||||
|
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>, Sources)> {
|
||||||
let (mut cands, near_prims, mut src) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
|
let (mut cands, near_prims, mut src) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
|
||||||
// Intersections between nearby primitives; Apparent Intersection also where their extensions
|
// Intersections between nearby primitives; Apparent Intersection also where their extensions
|
||||||
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
|
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
|
||||||
@@ -449,8 +505,7 @@ fn osnap_in_with_prims(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let hits = finish(cands, &near_prims, src, cursor, aperture, osmode, base, deferred, clip);
|
Some((cands, near_prims, src))
|
||||||
Some((hits, near_prims))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
|
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
|
||||||
@@ -492,26 +547,26 @@ pub(crate) fn extendable(p: &Prim) -> bool {
|
|||||||
matches!(p, Prim::Seg(_) | Prim::Circle(_) | Prim::Infinite { .. })
|
matches!(p, Prim::Seg(_) | Prim::Circle(_) | Prim::Infinite { .. })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The snap candidates of `osmode` and the primitives within `aperture` of `cursor`; `None`
|
|
||||||
/// when the drawing can't be searched.
|
|
||||||
pub(crate) fn gather(
|
|
||||||
d: &Drawing,
|
|
||||||
space: &Space,
|
|
||||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
|
||||||
cursor: Vec2,
|
|
||||||
aperture: f64,
|
|
||||||
osmode: u32,
|
|
||||||
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
|
|
||||||
gather_in(d, space, ix, cursor, aperture, osmode, &[], None).map(|(cands, prims, _)| (cands, prims))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The entity each gathered candidate and nearby primitive comes from (parallel to them).
|
/// The entity each gathered candidate and nearby primitive comes from (parallel to them).
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct Sources {
|
pub(crate) struct Sources {
|
||||||
cands: Vec<Option<SnapSource>>,
|
cands: Vec<Option<SnapSource>>,
|
||||||
prims: Vec<Option<SnapSource>>,
|
prims: Vec<Option<SnapSource>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What the nearby primitive `i` lies on.
|
||||||
|
fn prim_source(src: &Sources, i: usize) -> Option<SnapSource> {
|
||||||
|
src.prims.get(i).copied().flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What each candidate lies on: the `n` gathered candidates' sources, then the object of each
|
||||||
|
/// point found from the base point.
|
||||||
|
fn candidate_sources(n: usize, src: &Sources, from_base: &[FromBase]) -> Vec<Option<SnapSource>> {
|
||||||
|
let mut out: Vec<Option<SnapSource>> = (0..n).map(|i| src.cands.get(i).copied().flatten()).collect();
|
||||||
|
out.extend(from_base.iter().map(|f| prim_source(src, f.prim)));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
|
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
|
||||||
/// `skip` (and on the objects inside block references), with the object's direction there (a unit
|
/// `skip` (and on the objects inside block references), with the object's direction there (a unit
|
||||||
/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic
|
/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic
|
||||||
@@ -562,8 +617,10 @@ pub(crate) fn nearest_with_direction(
|
|||||||
best.map(|(_, at, dir)| (at, dir))
|
best.map(|(_, at, dir)| (at, dir))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The snap candidates of `osmode` and the primitives within `aperture` of `cursor`; `None`
|
||||||
|
/// when the drawing can't be searched.
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
fn gather_in(
|
pub(crate) fn gather_in(
|
||||||
d: &Drawing,
|
d: &Drawing,
|
||||||
space: &Space,
|
space: &Space,
|
||||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||||
@@ -673,89 +730,225 @@ fn leaf_with_source(be: &Entity, m: &Mat3, z: Option<(f64, f64)>, handle: Handle
|
|||||||
src.prims.resize(sink.near.len(), from);
|
src.prims.resize(sink.near.len(), from);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent
|
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps, with
|
||||||
/// snaps, the deferred snaps and Nearest.
|
/// its [`Rank`].
|
||||||
|
///
|
||||||
|
/// In order of preference (the rank's tier):
|
||||||
|
/// 0. the snap point within `aperture` of the cursor that scores best (see [`snap_score`]),
|
||||||
|
/// perpendicular and tangent points from the base point included;
|
||||||
|
/// 1. with a base point, a perpendicular or tangent on an object that passes within `aperture`,
|
||||||
|
/// wherever its point lies (see [`from_base_on_objects`]), or the center of a circle, arc or
|
||||||
|
/// ellipse under the cursor (see [`curve_centers`]): the object nearest the cursor;
|
||||||
|
/// 2. a deferred perpendicular or tangent (no base point yet);
|
||||||
|
/// 3. Nearest.
|
||||||
|
///
|
||||||
|
/// [`finish_all`] keeps every candidate in this order, for Tab.
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
fn finish(
|
fn finish(
|
||||||
mut cands: Vec<(u32, Vec2)>,
|
mut cands: Vec<(u32, Vec2)>,
|
||||||
near_prims: &[Prim],
|
near_prims: &[Prim],
|
||||||
mut src: Sources,
|
src: &Sources,
|
||||||
cursor: Vec2,
|
cursor: Vec2,
|
||||||
aperture: f64,
|
aperture: f64,
|
||||||
osmode: u32,
|
osmode: u32,
|
||||||
base: Option<Vec2>,
|
base: Option<Vec2>,
|
||||||
deferred: bool,
|
deferred: bool,
|
||||||
clip: Option<Bounds2>,
|
clip: Option<Bounds2>,
|
||||||
) -> Vec<SnapHit> {
|
) -> Option<(SnapHit, Rank)> {
|
||||||
// Perpendicular / tangent from the base point.
|
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
|
||||||
if let Some(bp) = base {
|
let sources = candidate_sources(cands.len(), src, &from_base);
|
||||||
for (p, from) in near_prims.iter().zip(&src.prims) {
|
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
|
||||||
if osmode & mode::PER != 0 {
|
|
||||||
match p {
|
|
||||||
Prim::Seg(Segment::Line(l)) => cands.push((mode::PER, l.project(bp))),
|
|
||||||
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
|
|
||||||
// not offered, and the far side is still found.
|
|
||||||
Prim::Seg(Segment::Arc { arc, .. }) => {
|
|
||||||
let curve = SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end };
|
|
||||||
cands.extend(curve.perpendiculars(bp, bp).into_iter().map(|q| (mode::PER, q)));
|
|
||||||
}
|
|
||||||
Prim::Circle(c) => cands.push((mode::PER, c.closest(bp))),
|
|
||||||
Prim::Infinite { base: b0, dir, .. } => cands.push((mode::PER, *b0 + *dir * (bp - *b0).dot(*dir))),
|
|
||||||
Prim::Ellipse(e) => cands.extend(curves::ellipse_perpendiculars(e, bp).into_iter().map(|q| (mode::PER, q))),
|
|
||||||
Prim::Spline(s) => cands.extend(curves::spline_perpendiculars(s, bp).into_iter().map(|q| (mode::PER, q))),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if osmode & mode::TAN != 0 {
|
|
||||||
let pts = match p {
|
|
||||||
// Only the tangent points that lie on the arc itself (not its circle).
|
|
||||||
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
|
|
||||||
.tangent_points(bp)
|
|
||||||
.into_iter()
|
|
||||||
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
|
|
||||||
.collect(),
|
|
||||||
Prim::Circle(c) => c.tangent_points(bp),
|
|
||||||
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
|
|
||||||
Prim::Spline(s) => curves::spline_tangents(s, bp),
|
|
||||||
_ => Vec::new(),
|
|
||||||
};
|
|
||||||
cands.extend(pts.into_iter().map(|t| (mode::TAN, t)));
|
|
||||||
}
|
|
||||||
src.cands.resize(cands.len(), *from);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
||||||
let mut hits: Vec<SnapHit> = cands
|
// Prefer more specific modes when nearly equidistant.
|
||||||
.into_iter()
|
let best = cands
|
||||||
.zip(src.cands.iter().copied().chain(std::iter::repeat(None)))
|
.iter()
|
||||||
|
.zip(&sources)
|
||||||
.filter(|((_, p), _)| visible(*p) && p.dist(cursor) <= aperture)
|
.filter(|((_, p), _)| visible(*p) && p.dist(cursor) <= aperture)
|
||||||
.map(|((m, p), from)| SnapHit { source: from, ..SnapHit::plain(m, p) })
|
.map(|((m, p), from)| (snap_score(*m, *p, cursor, aperture), *m, *p, *from))
|
||||||
.collect();
|
.min_by(|a, b| a.0.total_cmp(&b.0));
|
||||||
if base.is_none() && deferred {
|
if let Some((score, m, p, from)) = best {
|
||||||
hits.extend(deferred_hits(near_prims, &src.prims, cursor, aperture, osmode, clip));
|
return Some((SnapHit { source: from, ..SnapHit::plain(m, p) }, Rank { tier: 0, score }));
|
||||||
|
}
|
||||||
|
// A perpendicular or tangent on the object under the cursor, or the center found from its
|
||||||
|
// curve, only when no snap point is in the aperture: the Midpoint or Quadrant under the cursor
|
||||||
|
// wins over the center of the same curve, as in AutoCAD. Of the two, the object nearer the
|
||||||
|
// cursor; on a tie (the same curve), the perpendicular or tangent.
|
||||||
|
let on_object = from_base_on_objects(&from_base, near_prims, &src.prims, cursor, aperture, visible)
|
||||||
|
.into_iter()
|
||||||
|
.min_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)))
|
||||||
|
.map(|(h, r, _)| (h, r));
|
||||||
|
let center = curve_centers(near_prims, cursor, aperture, osmode)
|
||||||
|
.into_iter()
|
||||||
|
.filter(|(_, c, _)| visible(*c))
|
||||||
|
.min_by(|a, b| a.0.total_cmp(&b.0))
|
||||||
|
.map(|(score, c, i)| (SnapHit { source: prim_source(src, i), ..SnapHit::plain(mode::CEN, c) }, Rank { tier: 1, score }));
|
||||||
|
match (on_object, center) {
|
||||||
|
(Some(o), Some(c)) => return Some(if c.1.beats(&o.1) { c } else { o }),
|
||||||
|
(Some(h), None) | (None, Some(h)) => return Some(h),
|
||||||
|
(None, None) => {}
|
||||||
|
}
|
||||||
|
// With a base, perpendiculars are resolved from it above; only tangents are left to defer.
|
||||||
|
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
|
||||||
|
if deferred && let Some(h) = deferred_hit(near_prims, &src.prims, cursor, aperture, deferrable, clip) {
|
||||||
|
let score = h.point.dist(cursor);
|
||||||
|
return Some((h, Rank { tier: 2, score }));
|
||||||
}
|
}
|
||||||
if osmode & mode::NEA != 0 {
|
if osmode & mode::NEA != 0 {
|
||||||
// The closest point of all nearby objects, whatever their drawing order.
|
// The closest point of all nearby objects, whatever their drawing order.
|
||||||
let mut nb: Option<(f64, Vec2, Option<SnapSource>)> = None;
|
let nb = near_prims
|
||||||
let mut consider = |c: Vec2, from: Option<SnapSource>| {
|
.iter()
|
||||||
let dd = c.dist(cursor);
|
.enumerate()
|
||||||
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, ..)| dd < bd) {
|
.filter_map(|(i, p)| nearest_point(p, cursor, aperture, &visible).map(|(score, q)| (score, q, i)))
|
||||||
nb = Some((dd, c, from));
|
.min_by(|a, b| a.0.total_cmp(&b.0));
|
||||||
}
|
if let Some((score, p, i)) = nb {
|
||||||
};
|
return Some((SnapHit { source: prim_source(src, i), ..SnapHit::plain(mode::NEA, p) }, Rank { tier: 3, score }));
|
||||||
for (p, from) in near_prims.iter().zip(&src.prims) {
|
|
||||||
for s in prim_segments(p) {
|
|
||||||
consider(fix_circle(&s).closest(cursor), *from);
|
|
||||||
}
|
|
||||||
if let Prim::Circle(c) = p {
|
|
||||||
consider(c.closest(cursor), *from);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some((_, p, source)) = nb {
|
|
||||||
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None, source });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ranked(hits, cursor, aperture)
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`finish`], keeping every candidate with its [`Rank`], in the order [`finish`] prefers them:
|
||||||
|
/// the snap points best first, then the perpendiculars and tangents on the objects under the
|
||||||
|
/// cursor and the centers found from their curves, then the deferred snaps, then the nearest point
|
||||||
|
/// of each object nearby.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn finish_all(
|
||||||
|
mut cands: Vec<(u32, Vec2)>,
|
||||||
|
near_prims: &[Prim],
|
||||||
|
src: &Sources,
|
||||||
|
cursor: Vec2,
|
||||||
|
aperture: f64,
|
||||||
|
osmode: u32,
|
||||||
|
base: Option<Vec2>,
|
||||||
|
deferred: bool,
|
||||||
|
clip: Option<Bounds2>,
|
||||||
|
) -> Vec<(SnapHit, Rank)> {
|
||||||
|
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
|
||||||
|
let sources = candidate_sources(cands.len(), src, &from_base);
|
||||||
|
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
|
||||||
|
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
||||||
|
let mut out: Vec<(SnapHit, Rank)> = cands
|
||||||
|
.iter()
|
||||||
|
.zip(&sources)
|
||||||
|
.filter(|((_, p), _)| visible(*p) && p.dist(cursor) <= aperture)
|
||||||
|
.map(|((m, p), from)| (SnapHit { source: *from, ..SnapHit::plain(*m, *p) }, Rank { tier: 0, score: snap_score(*m, *p, cursor, aperture) }))
|
||||||
|
.collect();
|
||||||
|
// Of several points on one object (a circle's two tangents), the one nearer the cursor first,
|
||||||
|
// as `finish` picks it; the sort below is stable.
|
||||||
|
let mut on_object = from_base_on_objects(&from_base, near_prims, &src.prims, cursor, aperture, visible);
|
||||||
|
on_object.sort_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)));
|
||||||
|
out.extend(on_object.into_iter().map(|(h, r, _)| (h, r)));
|
||||||
|
out.extend(
|
||||||
|
curve_centers(near_prims, cursor, aperture, osmode)
|
||||||
|
.into_iter()
|
||||||
|
.filter(|(_, c, _)| visible(*c))
|
||||||
|
.map(|(score, c, i)| (SnapHit { source: prim_source(src, i), ..SnapHit::plain(mode::CEN, c) }, Rank { tier: 1, score })),
|
||||||
|
);
|
||||||
|
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
|
||||||
|
if deferred {
|
||||||
|
let hits = deferred_hits(near_prims, &src.prims, cursor, aperture, deferrable, clip);
|
||||||
|
out.extend(hits.into_iter().map(|h| (h, Rank { tier: 2, score: h.point.dist(cursor) })));
|
||||||
|
}
|
||||||
|
if osmode & mode::NEA != 0 {
|
||||||
|
let near = near_prims.iter().enumerate().filter_map(|(i, p)| nearest_point(p, cursor, aperture, &visible).map(|(score, q)| (score, q, i)));
|
||||||
|
out.extend(near.map(|(score, p, i)| (SnapHit { source: prim_source(src, i), ..SnapHit::plain(mode::NEA, p) }, Rank { tier: 3, score })));
|
||||||
|
}
|
||||||
|
out.sort_by(|a, b| a.1.cmp(&b.1));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The point of `p` closest to `cursor` among its visible points within `aperture`, with its
|
||||||
|
/// distance: each segment's closest point is checked before the closest is chosen, so a curve
|
||||||
|
/// whose closest point is clipped away (outside a viewport) still offers the visible one.
|
||||||
|
fn nearest_point(p: &Prim, cursor: Vec2, aperture: f64, visible: &impl Fn(Vec2) -> bool) -> Option<(f64, Vec2)> {
|
||||||
|
let mut nb: Option<(f64, Vec2)> = None;
|
||||||
|
let mut consider = |c: Vec2| {
|
||||||
|
let dd = c.dist(cursor);
|
||||||
|
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, _)| dd < bd) {
|
||||||
|
nb = Some((dd, c));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for s in prim_segments(p) {
|
||||||
|
consider(fix_circle(&s).closest(cursor));
|
||||||
|
}
|
||||||
|
if let Prim::Circle(c) = p {
|
||||||
|
consider(c.closest(cursor));
|
||||||
|
}
|
||||||
|
nb
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The perpendicular and tangent points from the base point `base` (none without one), each
|
||||||
|
/// with the index in `near_prims` of the object it lies on. At a `deferred` prompt the tangents to
|
||||||
|
/// circles and arcs are left out: the prompt resolves them itself (CIRCLE's radius, #1512).
|
||||||
|
fn base_snaps(near_prims: &[Prim], osmode: u32, base: Option<Vec2>, cursor: Vec2, deferred: bool) -> Vec<FromBase> {
|
||||||
|
let mut from_base: Vec<FromBase> = Vec::new();
|
||||||
|
let Some(bp) = base else { return from_base };
|
||||||
|
for (prim, p) in near_prims.iter().enumerate() {
|
||||||
|
let mut found = |mode: u32, points: Vec<Vec2>| from_base.extend(points.into_iter().map(|point| FromBase { mode, point, prim }));
|
||||||
|
if osmode & mode::PER != 0 {
|
||||||
|
let pts = match p {
|
||||||
|
Prim::Seg(Segment::Line(l)) => vec![l.project(bp)],
|
||||||
|
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
|
||||||
|
// not offered, and the far side is still found. From the centre, the point of
|
||||||
|
// the arc under the cursor.
|
||||||
|
Prim::Seg(Segment::Arc { arc, .. }) => {
|
||||||
|
SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end }.perpendiculars(bp, cursor)
|
||||||
|
}
|
||||||
|
// Both antipodes too, so a pick on the far side of the circle snaps there
|
||||||
|
// rather than across it. From the centre every point is perpendicular: the
|
||||||
|
// one under the cursor.
|
||||||
|
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius }.perpendiculars(bp, cursor),
|
||||||
|
Prim::Infinite { base: b0, dir, .. } => vec![*b0 + *dir * (bp - *b0).dot(*dir)],
|
||||||
|
Prim::Ellipse(e) => curves::ellipse_perpendiculars(e, bp),
|
||||||
|
Prim::Spline(s) => curves::spline_perpendiculars(s, bp),
|
||||||
|
_ => Vec::new(),
|
||||||
|
};
|
||||||
|
found(mode::PER, pts);
|
||||||
|
}
|
||||||
|
if osmode & mode::TAN != 0 {
|
||||||
|
let pts = match p {
|
||||||
|
// A deferred prompt resolves tangents to circles and arcs itself.
|
||||||
|
Prim::Seg(Segment::Arc { .. }) | Prim::Circle(_) if deferred => Vec::new(),
|
||||||
|
// Only the tangent points that lie on the arc itself (not its circle).
|
||||||
|
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
|
||||||
|
.tangent_points(bp)
|
||||||
|
.into_iter()
|
||||||
|
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
|
||||||
|
.collect(),
|
||||||
|
Prim::Circle(c) => c.tangent_points(bp),
|
||||||
|
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
|
||||||
|
Prim::Spline(s) => curves::spline_tangents(s, bp),
|
||||||
|
_ => Vec::new(),
|
||||||
|
};
|
||||||
|
found(mode::TAN, pts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
from_base
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Center, as in AutoCAD: with the cursor over a circle, an arc (also a polyline's) or an
|
||||||
|
/// ellipse, the running Center snap finds its center however far away it is. Each center comes
|
||||||
|
/// with how far the curve is from `cursor` (its score); [`finish`] tries them only when no snap
|
||||||
|
/// point is in the aperture. Empty unless Center is among `osmode`.
|
||||||
|
fn curve_centers(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32) -> Vec<(f64, Vec2, usize)> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
if osmode & mode::CEN == 0 {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// The work limit counts the curves only, so straight segments before them can't hide them.
|
||||||
|
let curves = prims.iter().enumerate().filter_map(|(i, p)| match p {
|
||||||
|
Prim::Circle(c) => Some((c.center, c.closest(cursor), i)),
|
||||||
|
Prim::Seg(s @ Segment::Arc { arc, .. }) => Some((arc.center, fix_circle(s).closest(cursor), i)),
|
||||||
|
Prim::Ellipse(e) => Some((e.center, e.closest(cursor), i)),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
for (center, on, i) in curves.take(2000) {
|
||||||
|
let d = on.dist(cursor);
|
||||||
|
if center.is_finite() && d.is_finite() && d <= aperture {
|
||||||
|
out.push((d, center, i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Prefer more specific modes when nearly equidistant.
|
/// Prefer more specific modes when nearly equidistant.
|
||||||
@@ -763,6 +956,63 @@ fn snap_score(mode: u32, point: Vec2, cursor: Vec2, aperture: f64) -> f64 {
|
|||||||
point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 }
|
point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A perpendicular ([`mode::PER`]) or tangent ([`mode::TAN`]) point found from the base point,
|
||||||
|
/// with the index in `near_prims` of the object it lies on.
|
||||||
|
struct FromBase {
|
||||||
|
mode: u32,
|
||||||
|
point: Vec2,
|
||||||
|
prim: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The perpendiculars and tangents from the base point on the objects that pass within
|
||||||
|
/// `aperture` of the cursor, wherever the foot or tangent point lies (#2800), each with its
|
||||||
|
/// [`Rank`] (tier 1, scored by the cursor's distance to the object) and its distance to the cursor.
|
||||||
|
///
|
||||||
|
/// These snaps name an object, not a spot on it: you can't know in advance where the foot of a
|
||||||
|
/// perpendicular will be, so, as in AutoCAD, hovering anywhere over the object finds it and the
|
||||||
|
/// point jumps there. [`finish`] asks for this only when no snap point lies within the aperture,
|
||||||
|
/// so an endpoint, midpoint or intersection under the cursor still wins.
|
||||||
|
///
|
||||||
|
/// [`finish`] takes the object nearest the cursor; of several points on it (an arc's two
|
||||||
|
/// antipodes, a circle's two tangents), the one nearest the cursor.
|
||||||
|
fn from_base_on_objects(
|
||||||
|
found: &[FromBase],
|
||||||
|
near_prims: &[Prim],
|
||||||
|
sources: &[Option<SnapSource>],
|
||||||
|
cursor: Vec2,
|
||||||
|
aperture: f64,
|
||||||
|
visible: impl Fn(Vec2) -> bool,
|
||||||
|
) -> Vec<(SnapHit, Rank, f64)> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
if found.is_empty() {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// `near_prims` holds every object whose box comes near the cursor, so the true distance is
|
||||||
|
// checked here. It is measured once per object, and only for objects with a point to offer:
|
||||||
|
// an ellipse or a spline is measured on its tessellation.
|
||||||
|
let mut reach: Vec<Option<f64>> = vec![None; near_prims.len()];
|
||||||
|
for f in found.iter().filter(|f| visible(f.point)) {
|
||||||
|
let Some(slot) = reach.get_mut(f.prim) else { continue };
|
||||||
|
let to_object = *slot.get_or_insert_with(|| near_prims.get(f.prim).map_or(f64::INFINITY, |p| distance_to_prim(p, cursor)));
|
||||||
|
// A NaN distance (from a degenerate object) never qualifies.
|
||||||
|
if to_object.is_nan() || to_object > aperture {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let source = sources.get(f.prim).copied().flatten();
|
||||||
|
out.push((SnapHit { source, ..SnapHit::plain(f.mode, f.point) }, Rank { tier: 1, score: to_object }, f.point.dist(cursor)));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The distance from `cursor` to the nearest point of `p`, measured as Nearest measures it.
|
||||||
|
fn distance_to_prim(p: &Prim, cursor: Vec2) -> f64 {
|
||||||
|
// A ray runs one way from its start (an xline both ways, as its segment does).
|
||||||
|
if let Prim::Infinite { base, dir, ray: true } = p {
|
||||||
|
return (*base + *dir * (cursor - *base).dot(*dir).max(0.0)).dist(cursor);
|
||||||
|
}
|
||||||
|
prim_segments(p).iter().map(|s| fix_circle(s).closest(cursor).dist(cursor)).fold(f64::INFINITY, f64::min)
|
||||||
|
}
|
||||||
|
|
||||||
/// Upper bound on the block-reference objects one snap query looks at (hostile files).
|
/// Upper bound on the block-reference objects one snap query looks at (hostile files).
|
||||||
const MAX_BLOCK_LEAVES: usize = 20_000;
|
const MAX_BLOCK_LEAVES: usize = 20_000;
|
||||||
|
|
||||||
@@ -1140,11 +1390,15 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and
|
/// Every deferred tangent and perpendicular within `aperture` of `cursor`, for Tab: one per curve
|
||||||
/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the
|
/// and mode, in drawing order (the caller ranks them), so Tab can go from the tangent to the
|
||||||
/// perpendicular on the same circle. `sources` is parallel to `prims`.
|
/// perpendicular on the same circle, and to the deferred snap of each curve nearby. A click takes
|
||||||
|
/// the nearest one ([`deferred_hit`]).
|
||||||
fn deferred_hits(prims: &[Prim], sources: &[Option<SnapSource>], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
|
fn deferred_hits(prims: &[Prim], sources: &[Option<SnapSource>], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
|
||||||
let mut hits = Vec::new();
|
let mut hits = Vec::new();
|
||||||
|
if osmode & (mode::TAN | mode::PER) == 0 {
|
||||||
|
return hits;
|
||||||
|
}
|
||||||
for (i, p) in prims.iter().enumerate() {
|
for (i, p) in prims.iter().enumerate() {
|
||||||
let curve = match p {
|
let curve = match p {
|
||||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
|
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
|
||||||
@@ -1178,6 +1432,46 @@ fn deferred_hits(prims: &[Prim], sources: &[Option<SnapSource>], cursor: Vec2, a
|
|||||||
hits
|
hits
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The nearest deferred tangent/perpendicular within `aperture` of `cursor`.
|
||||||
|
fn deferred_hit(prims: &[Prim], sources: &[Option<SnapSource>], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Option<SnapHit> {
|
||||||
|
let mut best: Option<(f64, SnapHit)> = None;
|
||||||
|
for (i, p) in prims.iter().enumerate() {
|
||||||
|
let curve = match p {
|
||||||
|
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
|
||||||
|
Prim::Seg(Segment::Arc { arc, .. }) => SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end },
|
||||||
|
Prim::Seg(Segment::Line(l)) => SnapCurve::Line { a: l.a, b: l.b },
|
||||||
|
Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir },
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
let (m, name, at) = match curve {
|
||||||
|
SnapCurve::Circle { center, radius } if osmode & mode::TAN != 0 => {
|
||||||
|
(mode::TAN, "Deferred Tangent", Circle::new(center, radius).closest(cursor))
|
||||||
|
}
|
||||||
|
SnapCurve::Circle { center, radius } if osmode & mode::PER != 0 => {
|
||||||
|
(mode::PER, "Deferred Perpendicular", Circle::new(center, radius).closest(cursor))
|
||||||
|
}
|
||||||
|
SnapCurve::Arc { center, radius, start, end } if osmode & mode::TAN != 0 => {
|
||||||
|
(mode::TAN, "Deferred Tangent", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||||
|
}
|
||||||
|
SnapCurve::Arc { center, radius, start, end } if osmode & mode::PER != 0 => {
|
||||||
|
(mode::PER, "Deferred Perpendicular", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||||
|
}
|
||||||
|
SnapCurve::Line { a, b } if osmode & mode::PER != 0 => {
|
||||||
|
// Pick on the drawn extent: a segment's own span, an xline/ray anywhere.
|
||||||
|
let l = cadcraft_geom::Line::new(a, b);
|
||||||
|
(mode::PER, "Deferred Perpendicular", if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) })
|
||||||
|
}
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
let dd = at.dist(cursor);
|
||||||
|
if at.is_finite() && clip.is_none_or(|c| c.contains(at)) && dd <= aperture && best.is_none_or(|(bd, _)| dd < bd) {
|
||||||
|
let source = sources.get(i).copied().flatten();
|
||||||
|
best = Some((dd, SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }), source }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
best.map(|(_, h)| h)
|
||||||
|
}
|
||||||
|
|
||||||
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
|
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
|
||||||
/// endpoints (in the order given), or `None` when there is no such line (a point inside the
|
/// endpoints (in the order given), or `None` when there is no such line (a point inside the
|
||||||
/// circle it should be tangent to, concentric circles, non-parallel lines both perpendicular to
|
/// circle it should be tangent to, concentric circles, non-parallel lines both perpendicular to
|
||||||
@@ -1449,7 +1743,7 @@ mod tests {
|
|||||||
let frozen = ["vp".to_string()];
|
let frozen = ["vp".to_string()];
|
||||||
let end = |x: f64, y: f64| {
|
let end = |x: f64, y: f64| {
|
||||||
let at = Vec2::new(x, y);
|
let at = Vec2::new(x, y);
|
||||||
osnap_in(&d, &Space::Model, &None, at + Vec2::new(0.02, -0.01), 0.5, mode::END, None, false, &frozen, None)
|
osnap_all_with_frozen(&d, &Space::Model, at + Vec2::new(0.02, -0.01), 0.5, mode::END, None, false, &frozen)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.any(|h| h.point.dist(at) < 1e-9)
|
.any(|h| h.point.dist(at) < 1e-9)
|
||||||
};
|
};
|
||||||
@@ -1632,21 +1926,22 @@ mod tests {
|
|||||||
assert_eq!(h.name, "Intersection");
|
assert_eq!(h.name, "Intersection");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tab cycling sees every snap within the aperture: specific snaps nearest first (Intersection
|
/// Tab cycling sees every snap within the aperture: snap points nearest first (Intersection
|
||||||
/// favoured), then deferred snaps, then Nearest, and no snap twice; the first is what `osnap`
|
/// favoured), then Nearest on each object, and no snap twice; the first is what `osnap` picks.
|
||||||
/// picks.
|
/// On a circle with no base point, its quadrant, then the deferred tangent and the deferred
|
||||||
|
/// perpendicular at the same spot.
|
||||||
#[test]
|
#[test]
|
||||||
fn osnap_all_ranks_every_candidate() {
|
fn osnap_all_ranks_every_candidate() {
|
||||||
let d = drawing();
|
let d = drawing();
|
||||||
let modes = mode::END | mode::MID | mode::INT | mode::NEA;
|
let (cursor, modes) = (Vec2::new(5.2, 0.2), mode::END | mode::MID | mode::INT | mode::NEA);
|
||||||
let all = osnap_all(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false);
|
let all = osnap_all(&d, &Space::Model, cursor, 0.5, modes, None, false);
|
||||||
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA], "{all:?}");
|
// Both lines' midpoints are the intersection point: one Midpoint. Each line has its Nearest.
|
||||||
assert_eq!(all[0].point, osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false).unwrap().point);
|
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA, mode::NEA], "{all:?}");
|
||||||
// On the circle: its quadrant, then the deferred tangent and perpendicular at the same spot.
|
assert_eq!(all.first().map(|h| h.point), osnap(&d, &Space::Model, cursor, 0.5, modes, None, false).map(|h| h.point));
|
||||||
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
|
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
|
||||||
let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect();
|
let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect();
|
||||||
assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}");
|
assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}");
|
||||||
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, modes, None, false).is_empty());
|
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, mode::QUA | mode::TAN | mode::PER, None, true).is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -1665,6 +1960,70 @@ mod tests {
|
|||||||
assert!(h.point.near(Vec2::new(3.0, 0.0), 1e-9));
|
assert!(h.point.near(Vec2::new(3.0, 0.0), 1e-9));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// #2800: hovering anywhere over the line finds the perpendicular, though its foot (2,0) is
|
||||||
|
/// six units from the cursor; it used to snap only within the aperture of the foot.
|
||||||
|
#[test]
|
||||||
|
fn perpendicular_from_base_anywhere_on_the_line() {
|
||||||
|
let d = drawing();
|
||||||
|
let h = osnap(&d, &Space::Model, Vec2::new(8.0, 0.1), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
|
||||||
|
assert!(h.point.near(Vec2::new(2.0, 0.0), 1e-9), "{h:?}");
|
||||||
|
assert_eq!(h.mode, mode::PER);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// #2800: the tangent point is found from anywhere on the circle; of its two tangent points
|
||||||
|
/// from the base, the one nearer the cursor.
|
||||||
|
#[test]
|
||||||
|
fn tangent_from_base_anywhere_on_the_circle() {
|
||||||
|
let d = drawing();
|
||||||
|
// From (30,0), 10 from the centre (20,0) of the radius-2 circle: the tangent points are
|
||||||
|
// at cos = 2/10 from the line to the base, (20.4, ±1.9596).
|
||||||
|
let upper = Vec2::new(20.4, 2.0 * (1.0f64 - 0.04).sqrt());
|
||||||
|
let on_circle = Vec2::new(20.0 - 2.0 * std::f64::consts::FRAC_1_SQRT_2, 2.0 * std::f64::consts::FRAC_1_SQRT_2);
|
||||||
|
let h = osnap(&d, &Space::Model, on_circle, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
|
||||||
|
assert!(h.point.near(upper, 1e-9), "{h:?}");
|
||||||
|
let mirrored = Vec2::new(on_circle.x, -on_circle.y);
|
||||||
|
let h = osnap(&d, &Space::Model, mirrored, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
|
||||||
|
assert!(h.point.near(Vec2::new(upper.x, -upper.y), 1e-9), "{h:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A circle offers both perpendicular points from the base, so a pick on its far side snaps
|
||||||
|
/// there, not to the near side across the circle (CodeRabbit on #2825).
|
||||||
|
#[test]
|
||||||
|
fn perpendicular_from_base_on_a_circle_takes_the_side_under_the_cursor() {
|
||||||
|
let d = drawing();
|
||||||
|
// The circle at (20,0), radius 2, seen from (30,0): perpendicular at (22,0) and (18,0).
|
||||||
|
let base = Some(Vec2::new(30.0, 0.0));
|
||||||
|
let far = osnap(&d, &Space::Model, Vec2::new(18.1, 0.1), 0.5, mode::PER, base, false).unwrap();
|
||||||
|
assert!(far.point.near(Vec2::new(18.0, 0.0), 1e-9), "{far:?}");
|
||||||
|
// Away from both points, at (19, √3) on the circle: 2 from (18,0) and √12 from (22,0).
|
||||||
|
let top = osnap(&d, &Space::Model, Vec2::new(19.0, 3.0f64.sqrt()), 0.5, mode::PER, base, false).unwrap();
|
||||||
|
assert!(top.point.near(Vec2::new(18.0, 0.0), 1e-9), "{top:?}");
|
||||||
|
let near = osnap(&d, &Space::Model, Vec2::new(21.9, 0.1), 0.5, mode::PER, base, false).unwrap();
|
||||||
|
assert!(near.point.near(Vec2::new(22.0, 0.0), 1e-9), "{near:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// With several objects under the aperture, the one nearest the cursor gives the
|
||||||
|
/// perpendicular, even when another object's foot is nearer.
|
||||||
|
#[test]
|
||||||
|
fn perpendicular_from_base_takes_the_object_nearest_the_cursor() {
|
||||||
|
let d = drawing();
|
||||||
|
// 0.4 above the horizontal line and 0.2 right of the vertical one: the vertical line wins,
|
||||||
|
// with its foot (5,4) farther from the cursor than the horizontal line's (2,0).
|
||||||
|
let h = osnap(&d, &Space::Model, Vec2::new(5.2, 0.4), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
|
||||||
|
assert!(h.point.near(Vec2::new(5.0, 4.0), 1e-9), "{h:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A snap point under the cursor still beats a perpendicular whose foot is away from it, and
|
||||||
|
/// an object outside the aperture gives none, though its box is near.
|
||||||
|
#[test]
|
||||||
|
fn perpendicular_from_base_yields_to_points_under_the_cursor() {
|
||||||
|
let d = drawing();
|
||||||
|
let base = Some(Vec2::new(2.0, 4.0));
|
||||||
|
let h = osnap(&d, &Space::Model, Vec2::new(9.9, 0.05), 0.5, mode::END | mode::PER, base, false).unwrap();
|
||||||
|
assert_eq!((h.point, h.mode), (Vec2::new(10.0, 0.0), mode::END));
|
||||||
|
assert!(osnap(&d, &Space::Model, Vec2::new(8.0, 0.7), 0.5, mode::PER, base, false).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn ortho_and_polar() {
|
fn ortho_and_polar() {
|
||||||
assert_eq!(ortho(Vec2::ZERO, Vec2::new(5.0, 1.0)), Vec2::new(5.0, 0.0));
|
assert_eq!(ortho(Vec2::ZERO, Vec2::new(5.0, 1.0)), Vec2::new(5.0, 0.0));
|
||||||
@@ -1707,9 +2066,14 @@ mod tests {
|
|||||||
let df = h.deferred.unwrap();
|
let df = h.deferred.unwrap();
|
||||||
assert_eq!(df.curve, SnapCurve::Circle { center: Vec2::new(20.0, 0.0), radius: 2.0 });
|
assert_eq!(df.curve, SnapCurve::Circle { center: Vec2::new(20.0, 0.0), radius: 2.0 });
|
||||||
assert_eq!(h.input(), crate::Input::Deferred(df));
|
assert_eq!(h.input(), crate::Input::Deferred(df));
|
||||||
// With a base it is an ordinary tangent.
|
// With a base it is an ordinary tangent, unless the prompt resolves it (CIRCLE's radius).
|
||||||
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
|
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), false).unwrap();
|
||||||
assert!(t.deferred.is_none() && t.name == "Tangent");
|
assert!(t.deferred.is_none() && t.name == "Tangent");
|
||||||
|
let t = osnap(&d, &Space::Model, at, 0.5, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
|
||||||
|
assert_eq!(t.name, "Deferred Tangent");
|
||||||
|
// A perpendicular from the base is still resolved from it.
|
||||||
|
let p = osnap(&d, &Space::Model, Vec2::new(2.0, 0.2), 0.5, mode::PER, Some(Vec2::new(2.0, 5.0)), true).unwrap();
|
||||||
|
assert!(p.deferred.is_none() && p.point.near(Vec2::new(2.0, 0.0), 1e-9));
|
||||||
// A specific snap still wins over a deferred one.
|
// A specific snap still wins over a deferred one.
|
||||||
let q = osnap(&d, &Space::Model, at, 0.5, mode::TAN | mode::QUA, None, true).unwrap();
|
let q = osnap(&d, &Space::Model, at, 0.5, mode::TAN | mode::QUA, None, true).unwrap();
|
||||||
assert_eq!(q.mode, mode::QUA);
|
assert_eq!(q.mode, mode::QUA);
|
||||||
|
|||||||
@@ -482,13 +482,38 @@ impl Tracker {
|
|||||||
cfg: &TrackConfig,
|
cfg: &TrackConfig,
|
||||||
base: Option<Vec2>,
|
base: Option<Vec2>,
|
||||||
) -> Option<Track> {
|
) -> Option<Track> {
|
||||||
let t = self.find(d, space, cursor, aperture, tol, cfg, base);
|
self.track_with_frozen(d, space, cursor, aperture, tol, cfg, base, &[])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub(crate) fn track_with_frozen(
|
||||||
|
&mut self,
|
||||||
|
d: &Drawing,
|
||||||
|
space: &Space,
|
||||||
|
cursor: Vec2,
|
||||||
|
aperture: f64,
|
||||||
|
tol: f64,
|
||||||
|
cfg: &TrackConfig,
|
||||||
|
base: Option<Vec2>,
|
||||||
|
frozen: &[String],
|
||||||
|
) -> Option<Track> {
|
||||||
|
let t = self.find(d, space, cursor, aperture, tol, cfg, base, frozen);
|
||||||
self.last = t.clone();
|
self.last = t.clone();
|
||||||
t
|
t
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
fn find(&self, d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, tol: f64, cfg: &TrackConfig, base: Option<Vec2>) -> Option<Track> {
|
fn find(
|
||||||
|
&self,
|
||||||
|
d: &Drawing,
|
||||||
|
space: &Space,
|
||||||
|
cursor: Vec2,
|
||||||
|
aperture: f64,
|
||||||
|
tol: f64,
|
||||||
|
cfg: &TrackConfig,
|
||||||
|
base: Option<Vec2>,
|
||||||
|
frozen: &[String],
|
||||||
|
) -> Option<Track> {
|
||||||
if !(cursor.is_finite() && aperture.is_finite() && tol.is_finite() && aperture > 0.0 && tol > 0.0) {
|
if !(cursor.is_finite() && aperture.is_finite() && tol.is_finite() && aperture > 0.0 && tol > 0.0) {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -538,7 +563,7 @@ impl Tracker {
|
|||||||
// 2. A path crossing an object.
|
// 2. A path crossing an object.
|
||||||
if cfg.running(mode::INT | mode::APP) {
|
if cfg.running(mode::INT | mode::APP) {
|
||||||
let ix = crate::spatial::index(d, space);
|
let ix = crate::spatial::index(d, space);
|
||||||
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
|
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p, _)| p).unwrap_or_default();
|
||||||
for prim in prims.iter().take(200) {
|
for prim in prims.iter().take(200) {
|
||||||
let extend = cfg.running(mode::APP) && super::extendable(prim);
|
let extend = cfg.running(mode::APP) && super::extendable(prim);
|
||||||
for seg in super::prim_segments(prim) {
|
for seg in super::prim_segments(prim) {
|
||||||
@@ -588,12 +613,26 @@ pub fn candidate(
|
|||||||
aperture: f64,
|
aperture: f64,
|
||||||
cfg: &TrackConfig,
|
cfg: &TrackConfig,
|
||||||
base: Option<Vec2>,
|
base: Option<Vec2>,
|
||||||
|
) -> Option<Acquired> {
|
||||||
|
candidate_with_frozen(d, space, cursor, hit, aperture, cfg, base, &[])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub(crate) fn candidate_with_frozen(
|
||||||
|
d: &Drawing,
|
||||||
|
space: &Space,
|
||||||
|
cursor: Vec2,
|
||||||
|
hit: Option<&SnapHit>,
|
||||||
|
aperture: f64,
|
||||||
|
cfg: &TrackConfig,
|
||||||
|
base: Option<Vec2>,
|
||||||
|
frozen: &[String],
|
||||||
) -> Option<Acquired> {
|
) -> Option<Acquired> {
|
||||||
if !can_acquire(cursor, aperture, cfg) {
|
if !can_acquire(cursor, aperture, cfg) {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let ix = crate::spatial::index(d, space);
|
let ix = crate::spatial::index(d, space);
|
||||||
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
|
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p, _)| p).unwrap_or_default();
|
||||||
candidate_from_prims(cursor, hit, aperture, cfg, base, &prims)
|
candidate_from_prims(cursor, hit, aperture, cfg, base, &prims)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -789,7 +828,7 @@ impl crate::Session {
|
|||||||
s.orthomode ^= q.shift;
|
s.orthomode ^= q.shift;
|
||||||
let angbase = self.angle_settings().angbase;
|
let angbase = self.angle_settings().angbase;
|
||||||
let Ok(st) = self.state() else { return CursorSnap { point: raw, ..Default::default() } };
|
let Ok(st) = self.state() else { return CursorSnap { point: raw, ..Default::default() } };
|
||||||
let (doc, space) = (st.doc.clone(), st.edit_space());
|
let (doc, space, frozen) = (st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec());
|
||||||
if !raw.is_finite() {
|
if !raw.is_finite() {
|
||||||
return CursorSnap { point: raw, ..Default::default() };
|
return CursorSnap { point: raw, ..Default::default() };
|
||||||
}
|
}
|
||||||
@@ -798,10 +837,10 @@ impl crate::Session {
|
|||||||
let cfg = TrackConfig::relative_to(&s, angbase, last);
|
let cfg = TrackConfig::relative_to(&s, angbase, last);
|
||||||
let osmode = s.osmode | if s.osnaphatch { mode::HATCH } else { 0 };
|
let osmode = s.osmode | if s.osnaphatch { mode::HATCH } else { 0 };
|
||||||
let ix = crate::spatial::index(&doc, &space);
|
let ix = crate::spatial::index(&doc, &space);
|
||||||
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred);
|
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred, &frozen);
|
||||||
let cand = match (osmode & mode::HATCH, near_prims.as_deref()) {
|
let cand = match (osmode & mode::HATCH, near_prims.as_deref()) {
|
||||||
(0, Some(prims)) => candidate_with_prims(raw, hit.as_ref(), q.aperture, &cfg, q.base, prims),
|
(0, Some(prims)) => candidate_with_prims(raw, hit.as_ref(), q.aperture, &cfg, q.base, prims),
|
||||||
_ => candidate(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base),
|
_ => candidate_with_frozen(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base, &frozen),
|
||||||
};
|
};
|
||||||
let wait = self.tracking.hover(cand, q.now, cfg.shift_acquire, q.shift);
|
let wait = self.tracking.hover(cand, q.now, cfg.shift_acquire, q.shift);
|
||||||
if let Some(h) = hit {
|
if let Some(h) = hit {
|
||||||
@@ -816,7 +855,7 @@ impl crate::Session {
|
|||||||
let (origin, angle) = super::grid_frame_in(&doc, &space);
|
let (origin, angle) = super::grid_frame_in(&doc, &space);
|
||||||
p = super::grid_snap(p, doc.header.snap_unit(), origin, angle);
|
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) {
|
if let Some(mut t) = self.tracking.track_with_frozen(&doc, &space, p, q.aperture, q.tol, &cfg, q.base, &frozen) {
|
||||||
// PolarSnap (SNAPTYPE 1): steps of POLARDIST, or of the snap X spacing when it is 0.
|
// PolarSnap (SNAPTYPE 1): steps of POLARDIST, or of the snap X spacing when it is 0.
|
||||||
let step = if s.polardist > 0.0 { s.polardist } else { s.snapunit.x };
|
let step = if s.polardist > 0.0 { s.polardist } else { s.snapunit.x };
|
||||||
if s.snapmode
|
if s.snapmode
|
||||||
|
|||||||
@@ -7,7 +7,14 @@ use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_
|
|||||||
|
|
||||||
mod table;
|
mod table;
|
||||||
|
|
||||||
|
/// ACADVER: the program's release, as a text AutoCAD documents it and `atof` reads back as a
|
||||||
|
/// number. A drawing's `$ACADVER` header is its file version, which is what a save writes, so the
|
||||||
|
/// two are separate values: `get` gives this text, `list` too, and the header stays as read.
|
||||||
|
pub const ACADVER_TEXT: &str = "24.3s (CADCraft)";
|
||||||
|
|
||||||
const SESSION_VARS: &[&str] = &[
|
const SESSION_VARS: &[&str] = &[
|
||||||
|
// The release text, with or without a drawing (the header's `$ACADVER` is the file version).
|
||||||
|
"ACADVER",
|
||||||
"AUDITCTL",
|
"AUDITCTL",
|
||||||
"ATTREQ",
|
"ATTREQ",
|
||||||
"OSMODE",
|
"OSMODE",
|
||||||
@@ -81,10 +88,54 @@ const SESSION_VARS: &[&str] = &[
|
|||||||
"SAVETIME",
|
"SAVETIME",
|
||||||
"SAVEFILEPATH",
|
"SAVEFILEPATH",
|
||||||
"ISAVEBAK",
|
"ISAVEBAK",
|
||||||
|
"DIMASO",
|
||||||
|
"TEXTEVAL",
|
||||||
|
"POPUPS",
|
||||||
];
|
];
|
||||||
|
|
||||||
pub fn get(s: &Session, name: &str) -> Option<Value> {
|
/// The DIMASSOC mode DIMASO turned off, kept in the drawing's header so undo restores it.
|
||||||
|
/// `CADCRAFT_` names are not listed by SYSVARS and no file writes this one.
|
||||||
|
const DIMASO_MODE: &str = "CADCRAFT_DIMASO_MODE";
|
||||||
|
|
||||||
|
/// The header key above, under any number of `$`: no variable of that name exists.
|
||||||
|
fn is_internal(n: &str) -> bool {
|
||||||
|
n.trim_start_matches('$') == DIMASO_MODE
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The names this session also answers with DXF's `$` in front: the header writes them that way
|
||||||
|
/// (`$DIMASO`, `$TEXTEVAL`, `$REGENMODE`, `$POPUPS`), so a routine may type either form.
|
||||||
|
const DOLLAR_VARS: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"];
|
||||||
|
|
||||||
|
/// [`set`] takes only a number for these: a program's or a routine's text is refused. A value
|
||||||
|
/// typed at the command line arrives as text and goes through [`typed_value`] first.
|
||||||
|
const NUMBER_ONLY: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE"];
|
||||||
|
|
||||||
|
/// The value of `text` typed at a SETVAR prompt for `name`: typed digits are a number for the
|
||||||
|
/// [`NUMBER_ONLY`] variables. Anything else stays text.
|
||||||
|
pub(crate) fn typed_value(name: &str, text: String) -> Value {
|
||||||
|
if NUMBER_ONLY.contains(&bare_name(name).as_str())
|
||||||
|
&& let Ok(number) = text.trim().parse::<i64>()
|
||||||
|
{
|
||||||
|
return json!(number);
|
||||||
|
}
|
||||||
|
Value::String(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `name` trimmed and upper case, without the `$` those names take. Every other name keeps the
|
||||||
|
/// `$` it was typed with: `$ANGBASE` stays a name of its own (LISP converts radians only for the
|
||||||
|
/// plain name) and `$OSMODE` is not the session's OSMODE.
|
||||||
|
fn bare_name(name: &str) -> String {
|
||||||
let n = name.trim().to_ascii_uppercase();
|
let n = name.trim().to_ascii_uppercase();
|
||||||
|
// Every leading `$`, as the header drops them all when it stores a value.
|
||||||
|
let rest = n.trim_start_matches('$');
|
||||||
|
if rest.len() < n.len() && DOLLAR_VARS.contains(&rest) { rest.to_string() } else { n }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||||
|
let n = bare_name(name);
|
||||||
|
if is_internal(&n) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
let st = &s.settings;
|
let st = &s.settings;
|
||||||
let v = match n.as_str() {
|
let v = match n.as_str() {
|
||||||
"OSMODE" => json!(st.osmode),
|
"OSMODE" => json!(st.osmode),
|
||||||
@@ -177,6 +228,12 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
|
|||||||
"SAVETIME" => json!(crate::autosave::savetime()),
|
"SAVETIME" => json!(crate::autosave::savetime()),
|
||||||
"SAVEFILEPATH" => json!(crate::autosave::savefilepath()),
|
"SAVEFILEPATH" => json!(crate::autosave::savefilepath()),
|
||||||
"ISAVEBAK" => json!(i32::from(crate::autosave::isavebak())),
|
"ISAVEBAK" => json!(i32::from(crate::autosave::isavebak())),
|
||||||
|
// DIMASO is obsolete in AutoCAD and has no value of its own: it reports DIMASSOC.
|
||||||
|
"DIMASO" => json!(i32::from(matches!(dimassoc(s)?, 1 | 2))),
|
||||||
|
// Whether a prompt reads typed text as LISP (routines switch it around their prompts).
|
||||||
|
"TEXTEVAL" => json!(i32::from(st.texteval)),
|
||||||
|
// Dialogs are available (read-only; a batch session is still told 1, as AutoCAD does).
|
||||||
|
"POPUPS" => json!(1),
|
||||||
"CMDNAMES" => json!(s.running.as_ref().map(|r| r.id.to_ascii_uppercase()).unwrap_or_default()),
|
"CMDNAMES" => json!(s.running.as_ref().map(|r| r.id.to_ascii_uppercase()).unwrap_or_default()),
|
||||||
"DWGNAME" => json!(s.state().map(|d| d.title.clone()).unwrap_or_default()),
|
"DWGNAME" => json!(s.state().map(|d| d.title.clone()).unwrap_or_default()),
|
||||||
"DBMOD" => json!(s.state().map(|d| i32::from(d.is_dirty())).unwrap_or(0)),
|
"DBMOD" => json!(s.state().map(|d| i32::from(d.is_dirty())).unwrap_or(0)),
|
||||||
@@ -189,6 +246,9 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
|
|||||||
"DWGTITLED" => json!(s.state().map(|d| i32::from(d.path.is_some())).unwrap_or(0)),
|
"DWGTITLED" => json!(s.state().map(|d| i32::from(d.path.is_some())).unwrap_or(0)),
|
||||||
"CMDACTIVE" => json!(i32::from(s.running.is_some())),
|
"CMDACTIVE" => json!(i32::from(s.running.is_some())),
|
||||||
"TILEMODE" => json!(i32::from(s.state().is_ok_and(|d| d.space.layout().is_none()))),
|
"TILEMODE" => json!(i32::from(s.state().is_ok_and(|d| d.space.layout().is_none()))),
|
||||||
|
// The release number as AutoCAD reports it, so `(atof (getvar "ACADVER"))` is 24.3; the
|
||||||
|
// drawing's own `$ACADVER` (its file version) is left alone for the save version.
|
||||||
|
"ACADVER" => json!(ACADVER_TEXT),
|
||||||
"PLATFORM" => json!(std::env::consts::OS),
|
"PLATFORM" => json!(std::env::consts::OS),
|
||||||
"BLOCKEDITOR" => json!(i32::from(s.state().is_ok_and(|d| d.block_edit.is_some()))),
|
"BLOCKEDITOR" => json!(i32::from(s.state().is_ok_and(|d| d.block_edit.is_some()))),
|
||||||
// The template NEW/QNEW start from (a profile setting, like FONTALT; "" = none).
|
// The template NEW/QNEW start from (a profile setting, like FONTALT; "" = none).
|
||||||
@@ -257,6 +317,11 @@ fn dwg_prefix(path: &str) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// DIMASSOC's value (0 off, 1 or 2 associative), read where DIMASO reports it from.
|
||||||
|
fn dimassoc(s: &Session) -> Option<i64> {
|
||||||
|
table::get(s, "DIMASSOC")?.as_i64()
|
||||||
|
}
|
||||||
|
|
||||||
fn as_bool(v: &Value) -> Option<bool> {
|
fn as_bool(v: &Value) -> Option<bool> {
|
||||||
v.as_bool().or_else(|| v.as_i64().map(|i| i != 0)).or_else(|| v.as_str().and_then(|s| s.trim().parse::<i64>().ok()).map(|i| i != 0))
|
v.as_bool().or_else(|| v.as_i64().map(|i| i != 0)).or_else(|| v.as_str().and_then(|s| s.trim().parse::<i64>().ok()).map(|i| i != 0))
|
||||||
}
|
}
|
||||||
@@ -277,6 +342,7 @@ fn as_pt(v: &Value) -> Option<cadcraft_geom::Vec2> {
|
|||||||
|
|
||||||
/// Variables `get` reports from session or drawing state that `set` can't change.
|
/// Variables `get` reports from session or drawing state that `set` can't change.
|
||||||
const READ_ONLY: &[&str] = &[
|
const READ_ONLY: &[&str] = &[
|
||||||
|
"ACADVER",
|
||||||
"CMDNAMES",
|
"CMDNAMES",
|
||||||
"DWGNAME",
|
"DWGNAME",
|
||||||
"DWGPREFIX",
|
"DWGPREFIX",
|
||||||
@@ -304,10 +370,15 @@ const READ_ONLY: &[&str] = &[
|
|||||||
"UCSXDIR",
|
"UCSXDIR",
|
||||||
"UCSYDIR",
|
"UCSYDIR",
|
||||||
"WORLDUCS",
|
"WORLDUCS",
|
||||||
|
// Dialogs: a session always has them, so the variable is fixed (not saved).
|
||||||
|
"POPUPS",
|
||||||
];
|
];
|
||||||
|
|
||||||
pub fn is_read_only(name: &str) -> bool {
|
pub fn is_read_only(name: &str) -> bool {
|
||||||
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(name.trim())) || table::is_read_only(&name.trim().to_ascii_uppercase())
|
// A header name's `$` is ignored: the header drops it when it stores a value, so `$ACADVER`
|
||||||
|
// would otherwise change ACADVER, and with it the version a save writes.
|
||||||
|
let n = name.trim().trim_start_matches('$').trim();
|
||||||
|
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(n)) || table::is_read_only(&n.to_ascii_uppercase())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POLARADDANG as typed: up to ten angles in degrees separated by `;` (radians out); `None` when
|
/// POLARADDANG as typed: up to ten angles in degrees separated by `;` (radians out); `None` when
|
||||||
@@ -325,11 +396,17 @@ pub fn format_angle_list(angles: &[f64]) -> String {
|
|||||||
|
|
||||||
/// Set a system variable, refusing values out of its range and folders the automation roots can't hold.
|
/// Set a system variable, refusing values out of its range and folders the automation roots can't hold.
|
||||||
pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
|
pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
|
||||||
let n = name.trim().to_ascii_uppercase();
|
let n = bare_name(name);
|
||||||
|
if is_internal(&n) {
|
||||||
|
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("unknown variable `{n}`") });
|
||||||
|
}
|
||||||
if is_read_only(&n) {
|
if is_read_only(&n) {
|
||||||
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("{n} is read-only") });
|
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("{n} is read-only") });
|
||||||
}
|
}
|
||||||
let bad = || EngineError::BadParams { cmd: "setvar".into(), msg: format!("invalid value for {n}") };
|
let bad = || EngineError::BadParams { cmd: "setvar".into(), msg: format!("invalid value for {n}") };
|
||||||
|
if NUMBER_ONLY.contains(&n.as_str()) && !v.is_number() {
|
||||||
|
return Err(bad());
|
||||||
|
}
|
||||||
let st = &mut s.settings;
|
let st = &mut s.settings;
|
||||||
match n.as_str() {
|
match n.as_str() {
|
||||||
"OSMODE" => {
|
"OSMODE" => {
|
||||||
@@ -436,6 +513,35 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
|
|||||||
}
|
}
|
||||||
"SAVEFILEPATH" => crate::autosave::set_savefilepath(v.as_str().ok_or_else(bad)?),
|
"SAVEFILEPATH" => crate::autosave::set_savefilepath(v.as_str().ok_or_else(bad)?),
|
||||||
"ISAVEBAK" => crate::autosave::set_isavebak(as_bool(v).ok_or_else(bad)?),
|
"ISAVEBAK" => crate::autosave::set_isavebak(as_bool(v).ok_or_else(bad)?),
|
||||||
|
// DIMASO has no value of its own: 0 turns DIMASSOC off (remembering the mode it had),
|
||||||
|
// 1 restores that mode (2 when none was seen), and 1 while it is on changes nothing. The
|
||||||
|
// mode it remembers is in the drawing's header ([`DIMASO_MODE`]), so each open drawing
|
||||||
|
// keeps its own and undo restores it with DIMASSOC; no file writes it.
|
||||||
|
"DIMASO" => {
|
||||||
|
let on = as_i(v).filter(|i| matches!(i, 0 | 1)).ok_or_else(bad)? == 1;
|
||||||
|
let mode = dimassoc(s).ok_or_else(bad)?;
|
||||||
|
// The drawing is touched only when DIMASSOC changes, so it is not marked modified
|
||||||
|
// and no undo step is left for a value it already has.
|
||||||
|
match (on, mode) {
|
||||||
|
(true, 1 | 2) | (false, 0) => {}
|
||||||
|
// Turned back on, from off or from a file's unknown mode: the mode it had.
|
||||||
|
(true, _) => {
|
||||||
|
let h = &mut s.doc_mut()?.header;
|
||||||
|
// Only a mode DIMASSOC takes: a file's value of anything else restores 2.
|
||||||
|
let restore = h.i64(DIMASO_MODE, 2);
|
||||||
|
h.set_i64("DIMASSOC", if matches!(restore, 1 | 2) { restore } else { 2 });
|
||||||
|
}
|
||||||
|
(false, _) => {
|
||||||
|
let h = &mut s.doc_mut()?.header;
|
||||||
|
if matches!(mode, 1 | 2) {
|
||||||
|
h.set_i64(DIMASO_MODE, mode);
|
||||||
|
}
|
||||||
|
h.set_i64("DIMASSOC", 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Stored for routines that switch it around their prompts; no prompt reads it yet.
|
||||||
|
"TEXTEVAL" => st.texteval = small(v, 1).ok_or_else(bad)? == 1,
|
||||||
// A number is in degrees; text is an angle typed in AUNITS (SETVAR at the command line).
|
// A number is in degrees; text is an angle typed in AUNITS (SETVAR at the command line).
|
||||||
"ANGBASE" => {
|
"ANGBASE" => {
|
||||||
let a = match v {
|
let a = match v {
|
||||||
|
|||||||
@@ -73,6 +73,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
|
|||||||
("PLINEWID", Kind::Real { min: 0.0, strict: false }, Def::Real(0.0)),
|
("PLINEWID", Kind::Real { min: 0.0, strict: false }, Def::Real(0.0)),
|
||||||
("POLYSIDES", Kind::Int(3, 1024), Def::Int(4)),
|
("POLYSIDES", Kind::Int(3, 1024), Def::Int(4)),
|
||||||
("PROJMODE", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
|
("PROJMODE", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
|
||||||
|
// 1 regenerates the drawing after a command that changes it (stored, nothing reads it yet).
|
||||||
|
("REGENMODE", Kind::Choice(&[0, 1]), Def::Int(1)),
|
||||||
("REVCLOUDARCLEN", Kind::Real { min: 0.0, strict: true }, Def::Units(0.5, 15.0)),
|
("REVCLOUDARCLEN", Kind::Real { min: 0.0, strict: true }, Def::Units(0.5, 15.0)),
|
||||||
("SPLINESEGS", Kind::Int(-32768, 32767), Def::Int(8)),
|
("SPLINESEGS", Kind::Int(-32768, 32767), Def::Int(8)),
|
||||||
("SPLKNOTS", Kind::Choice(&[0, 1, 2]), Def::Int(0)),
|
("SPLKNOTS", Kind::Choice(&[0, 1, 2]), Def::Int(0)),
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
//! ACADVER is the program's release as text, as AutoCAD documents it, so `(atof (getvar
|
||||||
|
//! "ACADVER"))` reads a number from it. It is read-only, and the drawing's `$ACADVER` stays the
|
||||||
|
//! file version a save writes, so a drawing read from a 2000 DXF saves as one.
|
||||||
|
|
||||||
|
use cadcraft_engine::Session;
|
||||||
|
use cadcraft_engine::lisp::value::Value;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
/// The release text `getvar` and `(getvar "ACADVER")` report.
|
||||||
|
const RELEASE: &str = "24.3s (CADCraft)";
|
||||||
|
|
||||||
|
/// A 2000 DXF (`$ACADVER` `AC1015`) holding one line.
|
||||||
|
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n\
|
||||||
|
0\nSECTION\n2\nENTITIES\n\
|
||||||
|
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n10.0\n21\n0.0\n31\n0.0\n\
|
||||||
|
0\nENDSEC\n0\nEOF\n";
|
||||||
|
|
||||||
|
/// A LISP expression's value, or its error message.
|
||||||
|
fn lisp(s: &mut Session, code: &str) -> Result<Value, String> {
|
||||||
|
match s.lisp_eval(code, false, true, Vec::new()) {
|
||||||
|
Ok(Some(Ok(v))) => Ok(v),
|
||||||
|
Ok(Some(Err(e))) => Err(e),
|
||||||
|
Ok(None) => Err("did not finish".into()),
|
||||||
|
Err(e) => Err(e.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// GETVAR's value.
|
||||||
|
fn getvar(s: &mut Session, name: &str) -> serde_json::Value {
|
||||||
|
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `$ACADVER` a DXF text declares.
|
||||||
|
fn file_version(text: &str) -> Option<String> {
|
||||||
|
let l: Vec<&str> = text.lines().map(str::trim).collect();
|
||||||
|
let at = l.windows(2).position(|w| w == ["9", "$ACADVER"])?;
|
||||||
|
l.get(at + 2).filter(|c| **c == "1").and_then(|_| l.get(at + 3)).map(|v| (*v).to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn getvar_gives_the_release_text_and_atof_reads_the_number() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
|
||||||
|
assert_eq!(getvar(&mut s, "acadver"), json!(RELEASE), "lower-case names work");
|
||||||
|
assert!(matches!(lisp(&mut s, "(getvar \"ACADVER\")"), Ok(Value::Str(t)) if &*t == RELEASE), "a LISP string");
|
||||||
|
assert!(matches!(lisp(&mut s, "(atof (getvar \"ACADVER\"))"), Ok(Value::Real(r)) if (r - 24.3).abs() < 1e-9), "(atof) reads the release number");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn setvar_refuses_acadver_and_changes_nothing() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
let before = s.state().unwrap().doc.header.str("ACADVER", "");
|
||||||
|
let e = s.execute("setvar", &json!({ "name": "ACADVER", "value": "AC1027" })).unwrap_err().to_string();
|
||||||
|
assert!(e.contains("read-only"), "{e}");
|
||||||
|
assert!(lisp(&mut s, "(setvar \"ACADVER\" \"AC1027\")").is_err(), "AutoLISP's setvar too");
|
||||||
|
// Typed at the command line, SETVAR reports the variable as read-only at its name prompt.
|
||||||
|
s.cmdline("setvar acadver").unwrap();
|
||||||
|
assert!(s.log.iter().any(|l| l == &format!("ACADVER = {RELEASE} (read only)")), "{:?}", s.log);
|
||||||
|
// Neither the release text nor the drawing's file version moved.
|
||||||
|
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
|
||||||
|
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), before);
|
||||||
|
assert_eq!(before, "AC1032");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_2000_drawing_saves_as_2000() {
|
||||||
|
crate::refedit_xref::hooks();
|
||||||
|
let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("acadver-{}", std::process::id()));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let path = dir.join("r2000.dxf");
|
||||||
|
let name = path.to_string_lossy().into_owned();
|
||||||
|
let mut s = Session::empty();
|
||||||
|
s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "r2000.dxf", Some(name.clone()));
|
||||||
|
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015", "read as 2000");
|
||||||
|
assert_eq!(cadcraft_io::save_version(&s.state().unwrap().doc), cadcraft_io::Version::R2000);
|
||||||
|
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE), "still the release text");
|
||||||
|
|
||||||
|
s.execute("qsave", &json!({})).unwrap();
|
||||||
|
let saved = std::fs::read_to_string(&path).unwrap();
|
||||||
|
assert_eq!(file_version(&saved).as_deref(), Some("AC1015"), "the file keeps its 2000 version");
|
||||||
|
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015");
|
||||||
|
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
|
||||||
|
assert_eq!(cadcraft_io::read_dxf(saved.as_bytes()).unwrap().header.str("ACADVER", ""), "AC1015", "and reopens as 2000");
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_dollar_name_cannot_change_the_file_version() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
let e = s.execute("setvar", &json!({ "name": "$ACADVER", "value": "AC1027" })).unwrap_err().to_string();
|
||||||
|
assert!(e.contains("read-only"), "{e}");
|
||||||
|
assert!(lisp(&mut s, "(setvar \"$ACADVER\" \"AC1015\")").is_err(), "AutoLISP's setvar too");
|
||||||
|
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1032", "the save version did not move");
|
||||||
|
assert!(cadcraft_engine::sysvars::is_read_only("$acadver"), "SETVAR's prompt sees it as read-only too");
|
||||||
|
// Other `$` names still reach the header as before, in LISP's units.
|
||||||
|
assert!(lisp(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
|
||||||
|
assert!(matches!(lisp(&mut s, "(getvar \"$ANGBASE\")"), Ok(Value::Real(r)) if (r - std::f64::consts::FRAC_PI_2).abs() < 1e-9));
|
||||||
|
let r = s.execute("setvar", &json!({ "name": "$OSMODE", "value": 9 })).unwrap();
|
||||||
|
assert_eq!(r["value"], json!(9), "{r}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn listings_show_the_release_text_without_a_drawing() {
|
||||||
|
let mut s = Session::empty();
|
||||||
|
let all = s.execute("sysvars", &json!({})).unwrap();
|
||||||
|
let text = all.to_string();
|
||||||
|
assert!(text.contains(RELEASE), "{text}");
|
||||||
|
let mut s = Session::new();
|
||||||
|
let all = s.execute("sysvars", &json!({})).unwrap().to_string();
|
||||||
|
assert!(all.contains(RELEASE) && !all.contains("\"AC1032\""), "{all}");
|
||||||
|
}
|
||||||
@@ -0,0 +1,386 @@
|
|||||||
|
//! Legacy system variables a LISP routine saves and restores around its work: DIMASO (obsolete in
|
||||||
|
//! AutoCAD, which reports and sets DIMASSOC through it), TEXTEVAL, REGENMODE (kept in the drawing
|
||||||
|
//! and its DXF header) and POPUPS (read-only). Before them `(getvar "DIMASO")` read nil, so
|
||||||
|
//! `(setq o (getvar "DIMASO")) … (setvar "DIMASO" o)` failed and the routine left the drawing's
|
||||||
|
//! associativity changed.
|
||||||
|
|
||||||
|
use cadcraft_engine::Session;
|
||||||
|
use cadcraft_engine::lisp::value::{Value as LispValue, to_text};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
fn getvar(s: &mut Session, name: &str) -> Value {
|
||||||
|
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setvar(s: &mut Session, name: &str, value: Value) -> bool {
|
||||||
|
s.execute("setvar", &json!({ "name": name, "value": value })).is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value of a LISP expression, or the error it left.
|
||||||
|
fn eval(s: &mut Session, src: &str) -> Result<LispValue, String> {
|
||||||
|
match s.lisp_eval(src, false, true, Vec::new()) {
|
||||||
|
Ok(Some(v)) => v,
|
||||||
|
Ok(None) => Err("no value".into()),
|
||||||
|
Err(e) => Err(e.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `(getvar name)` as the integer a routine receives.
|
||||||
|
fn lisp_getvar(s: &mut Session, name: &str) -> i64 {
|
||||||
|
let v = eval(s, &format!("(getvar \"{name}\")")).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||||
|
let n = v.as_number().unwrap_or_else(|| panic!("{name} is not a number"));
|
||||||
|
assert_eq!(n.fract(), 0.0, "{name} is a whole number");
|
||||||
|
n as i64
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `(setvar name value)` from LISP: whether it was accepted.
|
||||||
|
fn lisp_setvar(s: &mut Session, name: &str, value: &str) -> bool {
|
||||||
|
eval(s, &format!("(setvar \"{name}\" {value})")).is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The DXF pairs `(group code, value)` of a file, both trimmed.
|
||||||
|
fn pairs(text: &str) -> Vec<(i32, String)> {
|
||||||
|
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for chunk in lines.chunks(2) {
|
||||||
|
let [code, value] = chunk else { break };
|
||||||
|
let Ok(c) = code.parse::<i32>() else { continue };
|
||||||
|
out.push((c, (*value).to_string()));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The HEADER variable names a DXF text writes (the value after each group code 9).
|
||||||
|
fn header_names(text: &str) -> Vec<String> {
|
||||||
|
pairs(text).iter().filter(|(c, _)| *c == 9).map(|(_, v)| v.trim_start_matches('$').to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The integer a header variable is written with, as `(group code, value)` after its name.
|
||||||
|
fn header_int(text: &str, name: &str) -> Option<(i32, String)> {
|
||||||
|
let ps = pairs(text);
|
||||||
|
let i = ps.iter().position(|(c, v)| *c == 9 && v.trim_start_matches('$') == name)?;
|
||||||
|
ps.get(i + 1).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fresh_values_are_integers_a_routine_reads() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
for (name, want) in [("DIMASO", 1), ("TEXTEVAL", 0), ("REGENMODE", 1), ("POPUPS", 1)] {
|
||||||
|
assert_eq!(getvar(&mut s, name), json!(want), "{name}");
|
||||||
|
assert_eq!(lisp_getvar(&mut s, name), want, "{name} through getvar");
|
||||||
|
let kind = eval(&mut s, &format!("(type (getvar \"{name}\"))")).unwrap();
|
||||||
|
assert_eq!(to_text(&kind, true), "INT", "{name} is an integer to LISP");
|
||||||
|
}
|
||||||
|
// The list a routine sees (`SETVAR ?`) carries them too.
|
||||||
|
let all = cadcraft_engine::sysvars::list(&s);
|
||||||
|
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
|
||||||
|
assert_eq!(all.get(name), Some(&getvar(&mut s, name)), "{name} listed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_routine_saving_and_restoring_each_one_leaves_it_as_it_was() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
for (name, changed) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
|
||||||
|
let before = lisp_getvar(&mut s, name);
|
||||||
|
// (setq o (getvar X)) … (setvar X o) must give back exactly what it read.
|
||||||
|
assert!(eval(&mut s, &format!("(setq o (getvar \"{name}\"))")).is_ok(), "{name} readable");
|
||||||
|
assert!(lisp_setvar(&mut s, name, changed), "{name} takes {changed}");
|
||||||
|
assert_ne!(lisp_getvar(&mut s, name), before, "{name} changed by {changed}");
|
||||||
|
assert!(eval(&mut s, &format!("(setvar \"{name}\" o)")).is_ok(), "{name} restored");
|
||||||
|
assert_eq!(lisp_getvar(&mut s, name), before, "{name} back to {before}");
|
||||||
|
}
|
||||||
|
// REGENMODE is the drawing's, kept in its header; TEXTEVAL only the session's.
|
||||||
|
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dimaso_restores_the_dimassoc_mode_it_turned_off() {
|
||||||
|
// The routine's save/restore through DIMASO, for each associative mode.
|
||||||
|
for mode in [1, 2] {
|
||||||
|
let mut s = Session::new();
|
||||||
|
assert!(setvar(&mut s, "DIMASSOC", json!(mode)));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASO"), json!(1), "DIMASO follows DIMASSOC {mode}");
|
||||||
|
let o = eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number().unwrap();
|
||||||
|
assert!(lisp_setvar(&mut s, "DIMASO", "0"));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "DIMASO 0 turns associativity off");
|
||||||
|
assert!(lisp_setvar(&mut s, "DIMASO", "1"));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||||
|
assert_eq!(eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number(), Some(o), "DIMASO 1 puts back the DIMASSOC {mode} the routine read");
|
||||||
|
}
|
||||||
|
// Set directly, without ever switching it off first, DIMASO 1 leaves the mode alone.
|
||||||
|
let mut s = Session::new();
|
||||||
|
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||||
|
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
|
||||||
|
// No non-zero mode was seen: turning associativity back on gives AutoCAD's 2.
|
||||||
|
let mut s = Session::new();
|
||||||
|
assert!(setvar(&mut s, "DIMASSOC", json!(0)));
|
||||||
|
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||||
|
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "none was seen: the default 2");
|
||||||
|
// A drawing whose saved DIMASSOC is no mode DIMASO can restore (a hostile file) gives 2.
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
|
||||||
|
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||||
|
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
|
||||||
|
// Such a mode is not associative, and DIMASO 1 turns associativity on from it too.
|
||||||
|
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
|
||||||
|
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn typed_setvar_still_takes_digits() {
|
||||||
|
for (name, digits) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
|
||||||
|
let want = json!(digits.parse::<i64>().unwrap());
|
||||||
|
let dollar = format!("${name}");
|
||||||
|
// SETVAR with the name, the bare name, and the `$` form, as typed at the command line.
|
||||||
|
for lines in [vec!["setvar", name, digits], vec![name, digits], vec!["setvar", dollar.as_str(), digits]] {
|
||||||
|
let mut s = Session::new();
|
||||||
|
for line in &lines {
|
||||||
|
s.cmdline(line).unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(getvar(&mut s, name), want, "typed {lines:?}");
|
||||||
|
}
|
||||||
|
// A routine that types the command passes its answers the same way.
|
||||||
|
let mut s = Session::new();
|
||||||
|
eval(&mut s, &format!("(command \"SETVAR\" \"{name}\" \"{digits}\")")).unwrap();
|
||||||
|
assert_eq!(getvar(&mut s, name), want, "(command \"SETVAR\" {name})");
|
||||||
|
// Typed words are still refused.
|
||||||
|
let mut s = Session::new();
|
||||||
|
let before = getvar(&mut s, name);
|
||||||
|
for line in ["setvar", name, "two"] {
|
||||||
|
s.cmdline(line).unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(getvar(&mut s, name), before, "typed word refused for {name}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_new_drawing_writes_regenmode() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
// The first drawing, then a new metric and a new imperial one.
|
||||||
|
for metric in [None, Some(true), Some(false)] {
|
||||||
|
if let Some(metric) = metric {
|
||||||
|
s.new_drawing(metric);
|
||||||
|
}
|
||||||
|
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||||
|
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "1".to_string())), "new drawing, metric {metric:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_values_are_refused_and_change_nothing() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
for (name, v) in [
|
||||||
|
("REGENMODE", json!(2)),
|
||||||
|
("REGENMODE", json!(-1)),
|
||||||
|
("REGENMODE", json!(1.5)),
|
||||||
|
("REGENMODE", json!("two")),
|
||||||
|
("REGENMODE", Value::Null),
|
||||||
|
("TEXTEVAL", json!(-1)),
|
||||||
|
("TEXTEVAL", json!(2)),
|
||||||
|
("TEXTEVAL", json!("two")),
|
||||||
|
("TEXTEVAL", Value::Null),
|
||||||
|
("DIMASO", json!(3)),
|
||||||
|
("DIMASO", json!(-1)),
|
||||||
|
("DIMASO", json!(0.5)),
|
||||||
|
("DIMASO", json!("two")),
|
||||||
|
("DIMASO", Value::Null),
|
||||||
|
// Text a program or a routine passes is refused even when it spells a number.
|
||||||
|
("REGENMODE", json!("0")),
|
||||||
|
("TEXTEVAL", json!("1")),
|
||||||
|
("DIMASO", json!("0")),
|
||||||
|
("TEXTEVAL", json!(true)),
|
||||||
|
] {
|
||||||
|
let before = getvar(&mut s, name);
|
||||||
|
assert!(!setvar(&mut s, name, v.clone()), "{name} = {v} refused");
|
||||||
|
assert_eq!(getvar(&mut s, name), before, "{name} unchanged by {v}");
|
||||||
|
}
|
||||||
|
// The drawing's associativity is untouched by a refused DIMASO.
|
||||||
|
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||||
|
assert!(!setvar(&mut s, "DIMASO", json!(3)));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
|
||||||
|
// The same through LISP, where nil and a NaN real arrive as values a variable can't take.
|
||||||
|
assert!(!lisp_setvar(&mut s, "REGENMODE", "nil"), "nil refused");
|
||||||
|
assert!(!lisp_setvar(&mut s, "DIMASO", "3"), "DIMASO 3 refused");
|
||||||
|
assert!(!lisp_setvar(&mut s, "DIMASO", "\"two\""), "DIMASO text refused");
|
||||||
|
for (name, v) in [("DIMASO", "\"0\""), ("TEXTEVAL", "\"1\""), ("REGENMODE", "\"0\"")] {
|
||||||
|
assert!(!lisp_setvar(&mut s, name, v), "{name} text {v} refused");
|
||||||
|
}
|
||||||
|
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "-1"), "TEXTEVAL -1 refused");
|
||||||
|
// (- (exp 1000) (exp 1000)) is NaN: not a number JSON can hold, so it is refused as one.
|
||||||
|
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "(- (exp 1000) (exp 1000))"), "NaN refused");
|
||||||
|
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn popups_is_read_only() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
assert!(cadcraft_engine::sysvars::is_read_only("popups"));
|
||||||
|
for v in [json!(1), json!(0), json!("1")] {
|
||||||
|
let e = s.execute("setvar", &json!({ "name": "POPUPS", "value": v })).unwrap_err().to_string();
|
||||||
|
assert!(e.contains("read-only"), "{v}: {e}");
|
||||||
|
}
|
||||||
|
assert!(!lisp_setvar(&mut s, "POPUPS", "0"));
|
||||||
|
assert_eq!(getvar(&mut s, "POPUPS"), json!(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn regenmode_is_saved_in_the_dxf_header_and_read_back() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
assert!(setvar(&mut s, "REGENMODE", json!(0)));
|
||||||
|
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||||
|
assert!(header_names(&text).contains(&"REGENMODE".to_string()), "$REGENMODE is in the header (has {:?})", header_names(&text));
|
||||||
|
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "0".to_string())), "$REGENMODE is group 70, 0");
|
||||||
|
// A reopened drawing has the value it was saved with, and saves it back.
|
||||||
|
let mut back = Session::new();
|
||||||
|
back.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "regenmode.dxf", None);
|
||||||
|
assert_eq!(getvar(&mut back, "REGENMODE"), json!(0));
|
||||||
|
let again = cadcraft_io::write_dxf(back.doc().unwrap());
|
||||||
|
assert_eq!(header_int(&again, "REGENMODE"), Some((70, "0".to_string())));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn texteval_dimaso_and_popups_are_not_saved() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
assert!(setvar(&mut s, "TEXTEVAL", json!(1)));
|
||||||
|
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||||
|
let names = header_names(&text);
|
||||||
|
for name in ["TEXTEVAL", "DIMASO", "POPUPS"] {
|
||||||
|
assert!(!names.contains(&name.to_string()), "{name} is not a header variable (has {names:?})");
|
||||||
|
}
|
||||||
|
// TEXTEVAL is the session's: a drawing opened in this session does not bring its own value.
|
||||||
|
s.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "no_legacy_vars.dxf", None);
|
||||||
|
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "opening a drawing leaves the session's value");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dimaso_remembers_the_mode_of_each_open_drawing() {
|
||||||
|
// The mode DIMASO turns off is the drawing's, not the session's: two open drawings switched
|
||||||
|
// between each put back the DIMASSOC mode they had.
|
||||||
|
let mut s = Session::new();
|
||||||
|
let first = s.active;
|
||||||
|
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||||
|
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||||
|
let second = s.new_drawing(true);
|
||||||
|
assert_eq!(second, first + 1);
|
||||||
|
assert!(setvar(&mut s, "DIMASSOC", json!(2)));
|
||||||
|
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||||
|
s.execute("document.switch", &json!({ "index": first })).unwrap();
|
||||||
|
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the first drawing restores its own mode");
|
||||||
|
s.execute("document.switch", &json!({ "index": second })).unwrap();
|
||||||
|
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "the second drawing restores its own mode");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_dollar_forms_are_the_same_variables() {
|
||||||
|
// The DXF header writes these names with a `$` ($DIMASO, $TEXTEVAL, $REGENMODE, $POPUPS), so
|
||||||
|
// the command line takes them that way too, in any case and with spaces around them.
|
||||||
|
let mut s = Session::new();
|
||||||
|
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
|
||||||
|
let plain = getvar(&mut s, name);
|
||||||
|
let dollar = format!("${name}");
|
||||||
|
assert_eq!(getvar(&mut s, &dollar), plain, "{dollar} reads like {name}");
|
||||||
|
let typed = format!(" ${} ", name.to_ascii_lowercase());
|
||||||
|
assert_eq!(getvar(&mut s, &typed), plain, "{typed:?} reads like {name}");
|
||||||
|
assert_eq!(cadcraft_engine::sysvars::is_read_only(&dollar), cadcraft_engine::sysvars::is_read_only(name), "{dollar} read-only as {name}");
|
||||||
|
}
|
||||||
|
// DIMASO through its DXF name still turns DIMASSOC off and puts its mode back.
|
||||||
|
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||||
|
assert!(setvar(&mut s, "$DIMASO", json!(0)));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "$DIMASO 0 turns associativity off");
|
||||||
|
assert!(setvar(&mut s, " $dimaso ", json!(1)));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "$DIMASO 1 puts the mode back");
|
||||||
|
// TEXTEVAL: set under one name, read under the other.
|
||||||
|
assert!(setvar(&mut s, "$TEXTEVAL", json!(1)));
|
||||||
|
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "$TEXTEVAL set TEXTEVAL");
|
||||||
|
assert!(setvar(&mut s, "TEXTEVAL", json!(0)));
|
||||||
|
assert_eq!(getvar(&mut s, "$TEXTEVAL"), json!(0));
|
||||||
|
// REGENMODE takes only the values its plain name takes, and stores the ones it takes.
|
||||||
|
assert!(!setvar(&mut s, "$REGENMODE", json!(2)), "$REGENMODE 2 is out of range");
|
||||||
|
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $REGENMODE changed nothing");
|
||||||
|
assert!(!setvar(&mut s, "$REGENMODE", json!(-1)), "$REGENMODE -1 is out of range");
|
||||||
|
assert!(setvar(&mut s, "$REGENMODE", json!(0)));
|
||||||
|
assert_eq!(getvar(&mut s, "$REGENMODE"), json!(0));
|
||||||
|
assert_eq!(getvar(&mut s, "REGENMODE"), json!(0));
|
||||||
|
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 0, "$REGENMODE stored the drawing's value");
|
||||||
|
// POPUPS is read-only under its DXF name too.
|
||||||
|
for v in [json!(0), json!("1")] {
|
||||||
|
let e = s.execute("setvar", &json!({ "name": "$POPUPS", "value": v })).unwrap_err().to_string();
|
||||||
|
assert!(e.contains("read-only"), "$POPUPS {v}: {e}");
|
||||||
|
}
|
||||||
|
assert!(!lisp_setvar(&mut s, "$POPUPS", "0"));
|
||||||
|
assert_eq!(getvar(&mut s, "$POPUPS"), json!(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn other_dollar_names_keep_their_own_handling() {
|
||||||
|
// Only those four take a `$`: LISP's angle variables convert radians for the plain name, and
|
||||||
|
// `$OSMODE` stays a name of its own rather than becoming the session's OSMODE.
|
||||||
|
let mut s = Session::new();
|
||||||
|
assert!(eval(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
|
||||||
|
let base = eval(&mut s, "(getvar \"$ANGBASE\")").unwrap().as_number().unwrap_or(f64::NAN);
|
||||||
|
assert!((base - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "(getvar \"$ANGBASE\") gives pi/2, not {base}");
|
||||||
|
let osmode = eval(&mut s, "(setvar \"$OSMODE\" 9)").unwrap();
|
||||||
|
assert_eq!(to_text(&osmode, true), "9", "(setvar \"$OSMODE\" 9) returns 9");
|
||||||
|
assert_eq!(getvar(&mut s, "OSMODE"), json!(4133), "$OSMODE is not the session's OSMODE");
|
||||||
|
assert_eq!(getvar(&mut s, "$OSMODE"), json!(9), "$OSMODE still reads back what it was set to");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn undo_puts_back_the_mode_dimaso_remembers() {
|
||||||
|
// The mode DIMASO remembers goes back with DIMASSOC when the changes are undone.
|
||||||
|
let mut s = Session::new();
|
||||||
|
for (name, v) in [("DIMASSOC", 1), ("DIMASO", 0), ("DIMASSOC", 2), ("DIMASO", 0)] {
|
||||||
|
assert!(setvar(&mut s, name, json!(v)), "{name} {v}");
|
||||||
|
}
|
||||||
|
s.cmdline("u").unwrap();
|
||||||
|
s.cmdline("u").unwrap();
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "back to after the first DIMASO 0");
|
||||||
|
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||||
|
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the mode remembered then, not the later 2");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repeated_dollars_are_the_same_variables() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
assert!(!lisp_setvar(&mut s, "$$REGENMODE", "2"), "out of range under any number of $");
|
||||||
|
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $$REGENMODE changed nothing");
|
||||||
|
assert!(!setvar(&mut s, "$$$POPUPS", json!(0)), "read-only under any number of $");
|
||||||
|
assert!(cadcraft_engine::sysvars::is_read_only("$$POPUPS"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dimaso_on_while_already_on_leaves_the_drawing_unmodified() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "a fresh drawing");
|
||||||
|
assert!(setvar(&mut s, "DIMASO", json!(1)), "already on");
|
||||||
|
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "nothing changed, so not modified");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_remembered_mode_is_not_a_variable_and_is_not_reported_lost() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||||
|
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||||
|
for name in ["CADCRAFT_DIMASO_MODE", "$CADCRAFT_DIMASO_MODE", "cadcraft_dimaso_mode"] {
|
||||||
|
assert!(s.execute("getvar", &json!({ "name": name })).is_err(), "{name} is not a variable");
|
||||||
|
assert!(!setvar(&mut s, name, json!(2)), "{name} cannot be set");
|
||||||
|
}
|
||||||
|
assert!(eval(&mut s, "(getvar \"CADCRAFT_DIMASO_MODE\")").map_or(true, |v| to_text(&v, false) == "nil"));
|
||||||
|
// Saved and read back, the drawing has lost nothing a save keeps.
|
||||||
|
let before = s.doc().unwrap().clone();
|
||||||
|
let after = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&before).as_bytes()).unwrap();
|
||||||
|
let cmp = cadcraft_io::roundtrip::compare(&before, &after, &cadcraft_io::roundtrip::Options::default());
|
||||||
|
assert!(!cmp.differences.iter().any(|d| d.place.contains("DIMASO")), "{:?}", cmp.differences.iter().map(|d| &d.place).collect::<Vec<_>>());
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
#[path = "../support/temp_dir.rs"]
|
#[path = "../support/temp_dir.rs"]
|
||||||
mod temp_dir;
|
mod temp_dir;
|
||||||
|
|
||||||
|
mod acadver;
|
||||||
mod angle_prompts;
|
mod angle_prompts;
|
||||||
mod angle_settings;
|
mod angle_settings;
|
||||||
mod annotate_options;
|
mod annotate_options;
|
||||||
@@ -104,6 +105,7 @@ mod layout_prompts;
|
|||||||
mod leader_command;
|
mod leader_command;
|
||||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
mod leader_text_scale;
|
mod leader_text_scale;
|
||||||
|
mod legacy_sysvars;
|
||||||
mod lisp_answer_by_frames;
|
mod lisp_answer_by_frames;
|
||||||
mod lisp_corpus;
|
mod lisp_corpus;
|
||||||
mod lisp_findfile;
|
mod lisp_findfile;
|
||||||
@@ -135,6 +137,7 @@ mod offset_ellipse_side;
|
|||||||
mod offset_move;
|
mod offset_move;
|
||||||
mod oops_command;
|
mod oops_command;
|
||||||
mod options_profile;
|
mod options_profile;
|
||||||
|
mod osnap_opened_drawings;
|
||||||
mod overkill;
|
mod overkill;
|
||||||
mod parallel_display_list;
|
mod parallel_display_list;
|
||||||
mod pedit_heights;
|
mod pedit_heights;
|
||||||
@@ -185,10 +188,12 @@ mod setvar_coverage;
|
|||||||
mod shapes;
|
mod shapes;
|
||||||
mod snap_annotations;
|
mod snap_annotations;
|
||||||
mod snap_blocks;
|
mod snap_blocks;
|
||||||
|
mod snap_center_on_curve;
|
||||||
mod snap_curves;
|
mod snap_curves;
|
||||||
mod snap_intersections_aperture;
|
mod snap_intersections_aperture;
|
||||||
mod snap_nearest;
|
mod snap_nearest;
|
||||||
mod snap_overrides;
|
mod snap_overrides;
|
||||||
|
mod snap_tab_cycling;
|
||||||
mod snap_tracking;
|
mod snap_tracking;
|
||||||
mod snap_z;
|
mod snap_z;
|
||||||
mod snaps_more;
|
mod snaps_more;
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
//! DIST snaps to the model geometry displayed in paper-space viewports (#516).
|
//! DIST snaps to the model geometry displayed in paper-space viewports (#516).
|
||||||
|
|
||||||
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
|
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Ellipse, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
|
||||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||||
|
use cadcraft_engine::pointmod::snap_candidates;
|
||||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
|
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
|
||||||
use cadcraft_engine::{Input, Session};
|
use cadcraft_engine::{Input, Session};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
@@ -307,22 +308,22 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
|
|||||||
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
|
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Across spaces a click keeps the snap it had before Tab cycling: a viewport's best snap
|
/// Across spaces a click takes the viewport's Endpoint over a paper-space Nearest that scores
|
||||||
/// replaces paper space's only when it scores closer. Tab still reaches the other one.
|
/// closer, as within one space a snap point beats Nearest. Tab starts at the click's snap and
|
||||||
|
/// still reaches the paper-space Nearest.
|
||||||
#[test]
|
#[test]
|
||||||
fn a_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() {
|
fn a_viewport_endpoint_beats_a_closer_paper_space_nearest() {
|
||||||
let (mut d, paper) = drawing();
|
let (mut d, paper) = drawing();
|
||||||
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
|
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
|
||||||
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
|
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
|
||||||
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
|
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
|
||||||
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
|
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
|
||||||
assert_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}");
|
assert!(hit.mode == mode::END && hit.viewport.is_some() && hit.point.near(Vec2::new(95.0, 50.0), 1e-9), "{hit:?}");
|
||||||
assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}");
|
let all = snap_candidates(&d, &paper, cursor, 0.5, modes, None, false);
|
||||||
let all = osnap_all(&d, &paper, cursor, 0.5, modes, None, false);
|
|
||||||
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
|
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
|
||||||
assert!(
|
assert!(
|
||||||
all.iter().any(|h| h.mode == mode::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)),
|
all.iter().any(|h| h.mode == mode::NEA && h.viewport.is_none() && h.point.near(Vec2::new(94.7, 50.0), 1e-9)),
|
||||||
"Tab reaches the viewport's endpoint: {all:?}"
|
"Tab reaches the paper-space Nearest: {all:?}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -458,3 +459,50 @@ fn malformed_and_paper_space_viewports_are_not_snap_sources() {
|
|||||||
assert!(osnap(&d, &paper, Vec2::new(95.1, 50.1), 0.5, mode::END, None, false).is_none());
|
assert!(osnap(&d, &paper, Vec2::new(95.1, 50.1), 0.5, mode::END, None, false).is_none());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Nearest on a curve that leaves the viewport: the curve's closest point to the cursor is outside
|
||||||
|
/// the viewport, another point of it within the aperture is inside, and Nearest snaps there.
|
||||||
|
#[test]
|
||||||
|
fn nearest_takes_the_visible_part_of_a_curve_crossing_the_viewport_edge() {
|
||||||
|
let (mut d, paper) = drawing();
|
||||||
|
// The viewport shows model y up to 20. A tall ellipse peaks at (15, 20.1), just outside.
|
||||||
|
let ellipse = Ellipse { center: Vec3::new(15.0, 0.0, 0.0), major: Vec3::new(0.0, 20.1, 0.0), ratio: 0.1, start: 0.0, end: std::f64::consts::TAU };
|
||||||
|
d.add(&Space::Model, Common::default(), EntityKind::Ellipse(ellipse)).unwrap();
|
||||||
|
// The viewport's border is on a layer that is off, so it offers no Nearest of its own.
|
||||||
|
d.layers.push(cadcraft_engine::doc::Layer { name: "Border".into(), on: false, ..Default::default() });
|
||||||
|
let vp = viewport(&d, &paper);
|
||||||
|
d.modify_entity(vp, |e| e.common.layer = "Border".into()).unwrap();
|
||||||
|
// Model (15, 19.99): 0.11 from the peak, about 0.2 from where the ellipse comes back inside.
|
||||||
|
let cursor = Vec2::new(102.5, 59.995);
|
||||||
|
let hit = osnap(&d, &paper, cursor, 0.5, mode::NEA, None, false).expect("a visible nearest point");
|
||||||
|
let model = hit.viewport.expect("seen through the viewport").point;
|
||||||
|
assert!(model.y <= 20.0 + 1e-9 && model.dist(Vec2::new(15.0, 19.99)) <= 1.0, "{hit:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_twisted_viewport_offers_the_visible_perpendicular_when_a_nearer_one_is_off_the_sheet() {
|
||||||
|
// A viewport twisted 45°, 20 square at 0,0 on the sheet, scale 1. Through it, a line along
|
||||||
|
// y = 0 under the cursor and one along x = 9.3 (sheet coordinates). From the base 12,3 the
|
||||||
|
// foot on the first, 12,0, is inside the turned model box but off the viewport; the foot on
|
||||||
|
// the second, 9.3,3, is on it.
|
||||||
|
let mut d = Drawing::new_imperial();
|
||||||
|
let paper = Space::Paper("Layout1".into());
|
||||||
|
let vp = Viewport {
|
||||||
|
center: Vec3::ZERO,
|
||||||
|
width: 20.0,
|
||||||
|
height: 20.0,
|
||||||
|
view_center: Vec2::ZERO,
|
||||||
|
view_height: 20.0,
|
||||||
|
id: 2,
|
||||||
|
twist: std::f64::consts::FRAC_PI_4,
|
||||||
|
..Viewport::default()
|
||||||
|
};
|
||||||
|
for (a, b) in [(Vec2::new(-9.0, 0.0), Vec2::new(30.0, 0.0)), (Vec2::new(9.3, -9.0), Vec2::new(9.3, 9.0))] {
|
||||||
|
let (a, b) = (vp.paper_to_model(a), vp.paper_to_model(b));
|
||||||
|
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })).unwrap();
|
||||||
|
}
|
||||||
|
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
|
||||||
|
let hit = osnap(&d, &paper, Vec2::new(9.0, 0.0), 0.5, mode::PER, Some(Vec2::new(12.0, 3.0)), false).expect("the visible foot");
|
||||||
|
assert_eq!(hit.mode, mode::PER);
|
||||||
|
assert!(hit.point.near(Vec2::new(9.3, 3.0), 1e-9), "{hit:?}");
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
//! Running object snaps in a fresh drawing and in drawings opened from DXF and DWG files, with
|
||||||
|
//! AutoCAD's default modes (OSMODE 4133: Endpoint, Center, Intersection, Extension).
|
||||||
|
//!
|
||||||
|
//! Moving onto a circle, an arc or a polyline arc finds its Center. OSMODE is a profile setting,
|
||||||
|
//! as in AutoCAD (saved in the registry there, not the drawing): a file's `$OSMODE` header
|
||||||
|
//! variable, 0 included, never changes the running snaps.
|
||||||
|
|
||||||
|
use cadcraft_engine::Session;
|
||||||
|
use cadcraft_engine::doc::Drawing;
|
||||||
|
use cadcraft_engine::geom::Vec2;
|
||||||
|
use cadcraft_engine::snap::{mode, tracking::CursorQuery};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
/// AutoCAD's default running snaps.
|
||||||
|
const DEFAULT: u32 = 4133;
|
||||||
|
|
||||||
|
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
|
||||||
|
let a = deg.to_radians();
|
||||||
|
c + Vec2::new(r * a.cos(), r * a.sin())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A line crossed by another, a circle, an arc and a polyline with a straight and an arc segment.
|
||||||
|
fn draw(s: &mut Session) {
|
||||||
|
s.execute("line", &json!({ "points": [[0, 0], [20, 0]] })).unwrap();
|
||||||
|
s.execute("line", &json!({ "points": [[5, -5], [5, 5]] })).unwrap();
|
||||||
|
s.execute("circle", &json!({ "center": [50, 0], "radius": 5 })).unwrap();
|
||||||
|
s.execute("arc", &json!({ "center": [80, 0], "radius": 5, "start": 0, "end": 180 })).unwrap();
|
||||||
|
// 100,0 to 110,0 straight, then a half circle (bulge 1) to 130,0 round 120,0, below the axis.
|
||||||
|
s.execute("pline", &json!({ "vertices": [[100, 0], {"p": [110, 0], "bulge": 1.0}, [130, 0]] })).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drawing() -> Drawing {
|
||||||
|
let mut s = Session::new();
|
||||||
|
draw(&mut s);
|
||||||
|
s.doc().unwrap().clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a click at `cursor` lands while LINE asks for its first point (the drawing area's path).
|
||||||
|
fn snap(s: &mut Session, cursor: Vec2) -> Option<(Vec2, u32)> {
|
||||||
|
if s.running.is_none() {
|
||||||
|
s.start("line").unwrap();
|
||||||
|
}
|
||||||
|
let q = CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
|
||||||
|
let r = s.snap_cursor(cursor, &q);
|
||||||
|
r.snap.map(|h| (r.point, h.mode))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_snaps(s: &mut Session, what: &str) {
|
||||||
|
assert_eq!(s.settings.osmode, DEFAULT, "{what}: the running snaps are the profile's");
|
||||||
|
let cases = [
|
||||||
|
("the line's end", Vec2::new(20.2, 0.1), Vec2::new(20.0, 0.0), &[mode::END][..]),
|
||||||
|
("the lines' crossing", Vec2::new(5.2, 0.15), Vec2::new(5.0, 0.0), &[mode::INT][..]),
|
||||||
|
("the circle", polar(Vec2::new(50.0, 0.0), 5.3, 45.0), Vec2::new(50.0, 0.0), &[mode::CEN][..]),
|
||||||
|
("the arc", polar(Vec2::new(80.0, 0.0), 5.2, 90.0), Vec2::new(80.0, 0.0), &[mode::CEN][..]),
|
||||||
|
("the arc's end", Vec2::new(85.2, 0.1), Vec2::new(85.0, 0.0), &[mode::END][..]),
|
||||||
|
("the polyline's vertex", Vec2::new(110.2, 0.1), Vec2::new(110.0, 0.0), &[mode::END][..]),
|
||||||
|
("the polyline's arc", polar(Vec2::new(120.0, 0.0), 10.2, 270.0), Vec2::new(120.0, 0.0), &[mode::CEN][..]),
|
||||||
|
];
|
||||||
|
for (name, cursor, want, modes) in cases {
|
||||||
|
let (p, m) = snap(s, cursor).unwrap_or_else(|| panic!("{what}: no snap on {name}"));
|
||||||
|
assert!(modes.contains(&m), "{what}, {name}: mode {m}");
|
||||||
|
assert!(p.near(want, 1e-6), "{what}, {name}: {p:?}");
|
||||||
|
}
|
||||||
|
// Away from everything: nothing.
|
||||||
|
assert_eq!(snap(s, Vec2::new(35.0, 20.0)), None, "{what}");
|
||||||
|
// F3 off: nothing; on again: back.
|
||||||
|
s.execute("osnap", &json!({})).unwrap();
|
||||||
|
assert_eq!(snap(s, Vec2::new(20.2, 0.1)), None, "{what}: F3 off");
|
||||||
|
s.execute("osnap", &json!({})).unwrap();
|
||||||
|
assert_eq!(snap(s, Vec2::new(20.2, 0.1)).map(|h| h.1), Some(mode::END), "{what}: F3 on");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn default_snaps_work_in_a_fresh_drawing() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
draw(&mut s);
|
||||||
|
assert_snaps(&mut s, "fresh drawing");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `text` with `$OSMODE` set to `value` at the top of its header.
|
||||||
|
fn with_osmode(text: &str, value: u32) -> String {
|
||||||
|
let at = text.find("HEADER").expect("a header section") + "HEADER".len();
|
||||||
|
let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
|
||||||
|
let (head, tail) = text.split_at(at);
|
||||||
|
format!("{head}{eol} 9{eol}$OSMODE{eol} 70{eol}{value}{tail}")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_dxf_with_osmode_0_keeps_the_running_snaps() {
|
||||||
|
let clean = String::from_utf8(cadcraft_io::write(&drawing(), "snaps.dxf").unwrap()).unwrap();
|
||||||
|
let text = with_osmode(&clean, 0);
|
||||||
|
let d = cadcraft_io::read(text.as_bytes(), "snaps.dxf").unwrap();
|
||||||
|
let mut s = Session::new();
|
||||||
|
// OSMODE is the profile's: the user's own choice survives opening the file.
|
||||||
|
s.execute("setvar", &json!({ "name": "OSMODE", "value": DEFAULT })).unwrap();
|
||||||
|
s.open_drawing(d, "snaps.dxf", None);
|
||||||
|
assert_snaps(&mut s, "DXF with $OSMODE 0");
|
||||||
|
// Nor does a file change a profile without Center.
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("setvar", &json!({ "name": "OSMODE", "value": mode::END })).unwrap();
|
||||||
|
let text = with_osmode(&clean, DEFAULT);
|
||||||
|
assert_eq!(text.matches("$OSMODE").count(), 1, "one $OSMODE in the file");
|
||||||
|
s.open_drawing(cadcraft_io::read(text.as_bytes(), "x.dxf").unwrap(), "x.dxf", None);
|
||||||
|
assert_eq!(s.settings.osmode, mode::END);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn default_snaps_work_in_a_drawing_opened_from_dwg() {
|
||||||
|
// The drawing is the test's own, so it is converted in this process.
|
||||||
|
cadcraft_io::dwg_worker::allow_in_process();
|
||||||
|
let bytes = cadcraft_io::write(&drawing(), "snaps.dwg").unwrap();
|
||||||
|
let d = cadcraft_io::read(&bytes, "snaps.dwg").unwrap();
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.open_drawing(d, "snaps.dwg", None);
|
||||||
|
assert_snaps(&mut s, "DWG");
|
||||||
|
}
|
||||||
@@ -11,7 +11,9 @@ use cadcraft_engine::doc::{Block, Circle, Drawing, Entity, EntityKind, Handle, I
|
|||||||
use cadcraft_engine::{Input, Session};
|
use cadcraft_engine::{Input, Session};
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
fn hooks() {
|
/// The real file formats, for every test in this binary that opens or saves files (the hooks are
|
||||||
|
/// process-wide and the first ones set stay).
|
||||||
|
pub(crate) fn hooks() {
|
||||||
set_io(IoHooks {
|
set_io(IoHooks {
|
||||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||||
|
|||||||
@@ -0,0 +1,203 @@
|
|||||||
|
//! Center snaps from the curve, as in AutoCAD: with the cursor over a circle, an arc, an
|
||||||
|
//! ellipse or a polyline arc (also inside a block reference) the running Center snap finds its
|
||||||
|
//! center, however far away it is. Before, the center was only found with the cursor on the
|
||||||
|
//! center itself, so moving onto a circle with the default running snaps (END, CEN, INT, EXT)
|
||||||
|
//! showed nothing.
|
||||||
|
|
||||||
|
use cadcraft_engine::Session;
|
||||||
|
use cadcraft_engine::doc::{Common, EntityKind, Insert, Space};
|
||||||
|
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||||
|
use cadcraft_engine::pointmod::snap_candidates;
|
||||||
|
use cadcraft_engine::snap::{self, mode};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
/// AutoCAD's default running snaps (OSMODE 4133).
|
||||||
|
const DEFAULT: u32 = 4133;
|
||||||
|
|
||||||
|
fn snap_at(s: &Session, cursor: Vec2, aperture: f64, osmode: u32) -> Option<(Vec2, u32)> {
|
||||||
|
snap::osnap(s.doc().unwrap(), &Space::Model, cursor, aperture, osmode, None, false).map(|h| (h.point, h.mode))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
|
||||||
|
let a = deg.to_radians();
|
||||||
|
c + Vec2::new(r * a.cos(), r * a.sin())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cursor_on_a_circle_snaps_to_its_center() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("circle", &json!({ "center": [100, 50], "radius": 20 })).unwrap();
|
||||||
|
let c = Vec2::new(100.0, 50.0);
|
||||||
|
for deg in [10.0, 45.0, 130.0, 250.0, 300.0] {
|
||||||
|
// A hair off the circle, well inside the aperture; the center is 20 units away.
|
||||||
|
let cursor = polar(c, 20.3, deg);
|
||||||
|
let (p, m) = snap_at(&s, cursor, 1.0, DEFAULT).unwrap_or_else(|| panic!("no snap on the circle at {deg}°"));
|
||||||
|
assert_eq!(m, mode::CEN, "at {deg}°");
|
||||||
|
assert!(p.near(c, 1e-9), "at {deg}°: {p:?}");
|
||||||
|
}
|
||||||
|
// Away from the circle (outside the aperture) there is nothing.
|
||||||
|
assert_eq!(snap_at(&s, polar(c, 23.0, 45.0), 1.0, DEFAULT), None);
|
||||||
|
// Center off: no center.
|
||||||
|
assert_eq!(snap_at(&s, polar(c, 20.3, 45.0), 1.0, mode::END), None);
|
||||||
|
// On the center itself, as before.
|
||||||
|
assert_eq!(snap_at(&s, c + Vec2::new(0.2, 0.1), 1.0, DEFAULT).map(|h| h.1), Some(mode::CEN));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn arcs_ellipses_and_polyline_arcs_snap_to_their_centers() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 90 })).unwrap();
|
||||||
|
s.execute("ellipse", &json!({ "center": [50, 0], "major": [8, 0], "ratio": 0.5 })).unwrap();
|
||||||
|
// A polyline with a half-circle bulge from (100,0) to (120,0): center (110,0), radius 10.
|
||||||
|
s.execute("pline", &json!({ "vertices": [{"p": [100, 0], "bulge": 1.0}, [120, 0]] })).unwrap();
|
||||||
|
let arc = snap_at(&s, polar(Vec2::ZERO, 10.2, 45.0), 1.0, DEFAULT).unwrap();
|
||||||
|
assert_eq!(arc.1, mode::CEN);
|
||||||
|
assert!(arc.0.near(Vec2::ZERO, 1e-9));
|
||||||
|
// The arc runs 0°-90°: on its circle at 200° (not on the arc) there is no center.
|
||||||
|
assert_eq!(snap_at(&s, polar(Vec2::ZERO, 10.2, 200.0), 1.0, DEFAULT), None);
|
||||||
|
let el = snap_at(&s, Vec2::new(50.0, 4.2), 1.0, DEFAULT).unwrap();
|
||||||
|
assert_eq!(el.1, mode::CEN);
|
||||||
|
assert!(el.0.near(Vec2::new(50.0, 0.0), 1e-9));
|
||||||
|
let pl = snap_at(&s, polar(Vec2::new(110.0, 0.0), 10.2, 270.0), 1.0, DEFAULT).unwrap();
|
||||||
|
assert_eq!(pl.1, mode::CEN, "the bulge's arc");
|
||||||
|
assert!(pl.0.near(Vec2::new(110.0, 0.0), 1e-9), "{:?}", pl.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_nearer_endpoint_or_intersection_still_wins() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
|
||||||
|
s.execute("line", &json!({ "points": [[10, 0], [30, 0]] })).unwrap();
|
||||||
|
// At the line's end on the circle: Endpoint/Intersection, not the far center.
|
||||||
|
let (p, m) = snap_at(&s, Vec2::new(10.2, 0.1), 1.0, DEFAULT).unwrap();
|
||||||
|
assert!(m == mode::END || m == mode::INT, "{m}");
|
||||||
|
assert!(p.near(Vec2::new(10.0, 0.0), 1e-9));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn circles_inside_block_references_snap_to_their_centers() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
let c = s.execute("circle", &json!({ "center": [5, 0], "radius": 2 })).unwrap()["handle"].as_str().unwrap().to_string();
|
||||||
|
s.execute("block", &json!({ "name": "H", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap();
|
||||||
|
let kind = EntityKind::Insert(Insert {
|
||||||
|
block: "H".into(),
|
||||||
|
insert: Vec3::new(100.0, 100.0, 0.0),
|
||||||
|
scale: Vec3::new(3.0, 3.0, 1.0),
|
||||||
|
rotation: 0.0,
|
||||||
|
attribs: Vec::new(),
|
||||||
|
cols: 1,
|
||||||
|
rows: 1,
|
||||||
|
col_spacing: 0.0,
|
||||||
|
row_spacing: 0.0,
|
||||||
|
clip: None,
|
||||||
|
});
|
||||||
|
s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap();
|
||||||
|
// The circle lands at (115,100) with radius 6.
|
||||||
|
let (p, m) = snap_at(&s, polar(Vec2::new(115.0, 100.0), 6.2, 60.0), 1.0, DEFAULT).unwrap();
|
||||||
|
assert_eq!(m, mode::CEN);
|
||||||
|
assert!(p.near(Vec2::new(115.0, 100.0), 1e-9), "{p:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tab_cycling_offers_the_center_from_the_curve() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
|
||||||
|
let all = snap_candidates(s.doc().unwrap(), &Space::Model, polar(Vec2::ZERO, 10.2, 30.0), 1.0, DEFAULT, None, false);
|
||||||
|
assert_eq!(all.iter().filter(|h| h.mode == mode::CEN && h.point.near(Vec2::ZERO, 1e-9)).count(), 1, "{all:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_cursor_query_snaps_to_the_center_from_the_curve() {
|
||||||
|
// The path the drawing area uses (Session::snap_cursor): the point a click would take.
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("circle", &json!({ "center": [0, 0], "radius": 50 })).unwrap();
|
||||||
|
s.start("line").unwrap();
|
||||||
|
let q = snap::tracking::CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
|
||||||
|
let r = s.snap_cursor(polar(Vec2::ZERO, 50.4, 33.0), &q);
|
||||||
|
assert_eq!(r.snap.map(|h| h.mode), Some(mode::CEN));
|
||||||
|
assert!(r.point.near(Vec2::ZERO, 1e-9), "{:?}", r.point);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The arc of the review of #2347 (and #1114's test): center (100,50), radius 80, 30°-150°.
|
||||||
|
fn review_arc() -> Session {
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("arc", &json!({ "center": [100, 50], "radius": 80, "start": 30, "end": 150 })).unwrap();
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_midpoint_under_the_cursor_beats_the_center_from_the_curve() {
|
||||||
|
let s = review_arc();
|
||||||
|
// On the arc's midpoint (100,130) with Center and Midpoint running: Midpoint, as in AutoCAD.
|
||||||
|
for cursor in [Vec2::new(100.05, 130.0), Vec2::new(100.2, 130.1)] {
|
||||||
|
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
|
||||||
|
assert_eq!(snap_at(&s, cursor, 0.5, mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
|
||||||
|
}
|
||||||
|
// Elsewhere on the arc, with no snap point in the aperture, the center from the curve.
|
||||||
|
let (p, m) = snap_at(&s, polar(Vec2::new(100.0, 50.0), 80.1, 70.0), 0.5, mode::CEN | mode::MID).unwrap();
|
||||||
|
assert_eq!(m, mode::CEN);
|
||||||
|
assert!(p.near(Vec2::new(100.0, 50.0), 1e-9), "{p:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_quadrant_under_the_cursor_beats_the_center_from_the_curve() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("circle", &json!({ "center": [20, 0], "radius": 2 })).unwrap();
|
||||||
|
let cursor = Vec2::new(20.1, 2.0);
|
||||||
|
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
|
||||||
|
assert_eq!(snap_at(&s, cursor, 0.5, mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
|
||||||
|
// Away from the quadrants the center from the curve.
|
||||||
|
let (p, m) = snap_at(&s, polar(Vec2::new(20.0, 0.0), 2.1, 45.0), 0.5, mode::CEN | mode::QUA).unwrap();
|
||||||
|
assert_eq!(m, mode::CEN);
|
||||||
|
assert!(p.near(Vec2::new(20.0, 0.0), 1e-9), "{p:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn many_straight_segments_do_not_hide_a_circle_from_center() {
|
||||||
|
// A polyline of 2,500 straight segments zigzagging over the cursor, then a circle: the
|
||||||
|
// work limit counts circles and arcs only, so the circle's center is still found.
|
||||||
|
let mut s = Session::new();
|
||||||
|
let vertices: Vec<[f64; 2]> = (0..=2500).map(|i| [i as f64 * 0.04, if i % 2 == 0 { 0.0 } else { 100.0 }]).collect();
|
||||||
|
s.execute("pline", &json!({ "vertices": vertices })).unwrap();
|
||||||
|
s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap();
|
||||||
|
let (p, m) = snap_at(&s, polar(Vec2::new(50.0, 50.0), 20.2, 100.0), 0.5, mode::CEN).unwrap();
|
||||||
|
assert_eq!(m, mode::CEN);
|
||||||
|
assert!(p.near(Vec2::new(50.0, 50.0), 1e-9), "{p:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_viewport_center_keeps_its_curve_distance_against_paper_space() {
|
||||||
|
use cadcraft_engine::doc::{Circle, Drawing, Viewport};
|
||||||
|
let mut d = Drawing::new_imperial();
|
||||||
|
let paper = Space::Paper("Layout1".into());
|
||||||
|
// Model circle (10,0) r16 seen through a viewport at half scale: paper center (100,50), radius 8.
|
||||||
|
d.add(&Space::Model, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(10.0, 0.0, 0.0), radius: 16.0 })).unwrap();
|
||||||
|
let vp = Viewport {
|
||||||
|
center: Vec3::new(100.0, 50.0, 0.0),
|
||||||
|
width: 20.0,
|
||||||
|
height: 20.0,
|
||||||
|
view_center: Vec2::new(10.0, 0.0),
|
||||||
|
view_height: 40.0,
|
||||||
|
id: 2,
|
||||||
|
locked: false,
|
||||||
|
frozen_layers: Vec::new(),
|
||||||
|
layer_colors: Vec::new(),
|
||||||
|
clip: None,
|
||||||
|
on: true,
|
||||||
|
twist: 0.0,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
|
||||||
|
// A small paper-space circle whose curve passes 0.3 from the cursor and whose center is
|
||||||
|
// nearer the cursor (3.3) than the model circle's (8).
|
||||||
|
d.add(&paper, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(108.0, 53.3, 0.0), radius: 3.0 })).unwrap();
|
||||||
|
// The cursor is on the model circle (0.1 off in paper units): its center wins.
|
||||||
|
let h = snap::osnap(&d, &paper, Vec2::new(108.1, 50.0), 0.5, mode::CEN, None, false).unwrap();
|
||||||
|
assert_eq!(h.mode, mode::CEN);
|
||||||
|
assert!(h.point.near(Vec2::new(100.0, 50.0), 1e-9), "{h:?}");
|
||||||
|
assert!(h.viewport.is_some());
|
||||||
|
// On the paper circle, away from the model one: its center.
|
||||||
|
let h = snap::osnap(&d, &paper, Vec2::new(108.0, 56.35), 0.5, mode::CEN, None, false).unwrap();
|
||||||
|
assert!(h.point.near(Vec2::new(108.0, 53.3), 1e-9), "{h:?}");
|
||||||
|
assert!(h.viewport.is_none());
|
||||||
|
}
|
||||||
@@ -70,6 +70,9 @@ fn elliptical_arc_perpendicular_and_tangent_from_a_base_point() {
|
|||||||
let (q, m) = along_quarter(&s, mode::TAN, Some(base)).expect("a tangent point on the arc");
|
let (q, m) = along_quarter(&s, mode::TAN, Some(base)).expect("a tangent point on the arc");
|
||||||
assert_eq!(m, mode::TAN);
|
assert_eq!(m, mode::TAN);
|
||||||
assert!(on_quarter(q) && Vec2::new(q.x / 16.0, q.y / 4.0).dot(q - base).abs() < 1e-9, "{q:?}");
|
assert!(on_quarter(q) && Vec2::new(q.x / 16.0, q.y / 4.0).dot(q - base).abs() < 1e-9, "{q:?}");
|
||||||
|
// The same tangent at a prompt that resolves deferred snaps (CIRCLE's 3P points, #1512).
|
||||||
|
let h = snap::osnap(s.doc().unwrap(), &Space::Model, q, 0.3, mode::TAN, Some(base), true).expect("tangent at a deferred prompt");
|
||||||
|
assert!(h.mode == mode::TAN && h.deferred.is_none() && h.point.near(q, 1e-9), "{h:?}");
|
||||||
// Perpendicular from (10,10): the line from the base runs along the normal.
|
// Perpendicular from (10,10): the line from the base runs along the normal.
|
||||||
let base = Vec2::new(10.0, 10.0);
|
let base = Vec2::new(10.0, 10.0);
|
||||||
let (q, m) = along_quarter(&s, mode::PER, Some(base)).expect("a perpendicular foot on the arc");
|
let (q, m) = along_quarter(&s, mode::PER, Some(base)).expect("a perpendicular foot on the arc");
|
||||||
@@ -119,3 +122,28 @@ fn spline_midpoint_perpendicular_and_tangent() {
|
|||||||
let d = (sp.eval(i + 1e-6) - sp.eval(i - 1e-6)).normalized();
|
let d = (sp.eval(i + 1e-6) - sp.eval(i - 1e-6)).normalized();
|
||||||
assert!(d.cross((q - base).normalized()).abs() < 1e-3, "the line from the base runs along the curve at {q:?}");
|
assert!(d.cross((q - base).normalized()).abs() < 1e-3, "the line from the base runs along the curve at {q:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn perpendicular_from_an_arcs_center_stays_on_the_arc() {
|
||||||
|
// From the center of an arc every point is perpendicular: the one under the cursor, never a
|
||||||
|
// point of its circle outside the sweep.
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("arc", &serde_json::json!({"center": [0, 0], "radius": 10, "start": 90, "end": 180})).unwrap();
|
||||||
|
let hit = snap::osnap(s.doc().unwrap(), &Space::Model, Vec2::new(-6.0, 8.0), 0.3, mode::PER, Some(Vec2::ZERO), false);
|
||||||
|
let (p, m) = hit.map(|h| (h.point, h.mode)).expect("a perpendicular on the arc");
|
||||||
|
assert_eq!(m, mode::PER);
|
||||||
|
assert!(p.near(Vec2::new(-6.0, 8.0), 1e-9), "{p:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn perpendicular_to_a_ray_needs_the_cursor_on_the_ray() {
|
||||||
|
// A ray along +X from the origin: behind its start the cursor is over nothing.
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("ray", &serde_json::json!({"base": [0, 0], "through": [10, 0]})).unwrap();
|
||||||
|
let d = s.doc().unwrap();
|
||||||
|
let base = Some(Vec2::new(5.0, 3.0));
|
||||||
|
assert_eq!(snap::osnap(d, &Space::Model, Vec2::new(-2.0, 0.0), 0.5, mode::PER, base, false), None);
|
||||||
|
// Over the ray, the foot is found.
|
||||||
|
let hit = snap::osnap(d, &Space::Model, Vec2::new(2.0, 0.0), 0.5, mode::PER, base, false).expect("the foot on the ray");
|
||||||
|
assert!(hit.point.near(Vec2::new(5.0, 0.0), 1e-9), "{hit:?}");
|
||||||
|
}
|
||||||
|
|||||||
@@ -21,6 +21,17 @@ fn last_line(s: &Session) -> (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 }).last().unwrap()
|
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).last().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The last circle drawn as (center, radius).
|
||||||
|
fn last_circle(s: &Session) -> (Vec2, f64) {
|
||||||
|
s.doc()
|
||||||
|
.unwrap()
|
||||||
|
.model
|
||||||
|
.iter()
|
||||||
|
.filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some((c.center.xy(), c.radius)) } else { None })
|
||||||
|
.last()
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
fn near(p: Vec2, x: f64, y: f64) -> bool {
|
fn near(p: Vec2, x: f64, y: f64) -> bool {
|
||||||
p.near(Vec2::new(x, y), 1e-9)
|
p.near(Vec2::new(x, y), 1e-9)
|
||||||
}
|
}
|
||||||
@@ -80,6 +91,23 @@ fn nothing_to_snap_to_rejects_the_point() {
|
|||||||
assert!(near(s.last_point, 10.0, 10.0));
|
assert!(near(s.last_point, 10.0, 10.0));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// #2800: a typed PER or TAN finds its point from a pick anywhere on the object, as in AutoCAD.
|
||||||
|
/// The pick used to have to land within the aperture (0.125 here) of the foot or tangent point,
|
||||||
|
/// which you can't know in advance; elsewhere it said "No Perpendicular found".
|
||||||
|
#[test]
|
||||||
|
fn typed_per_and_tan_snap_from_anywhere_on_the_object() {
|
||||||
|
let mut s = drawing();
|
||||||
|
// From (5,5), PER picked at (3,0) on the line 0,0–10,0: two units from the foot (5,0).
|
||||||
|
s.script("LINE 5,5 PER 3,0\n\n").unwrap();
|
||||||
|
let (a, b) = last_line(&s);
|
||||||
|
assert!(near(a, 5.0, 5.0) && near(b, 5.0, 0.0), "{a:?} {b:?}");
|
||||||
|
// From (30,20), TAN picked at the top of the circle (centre 20,20, radius 3): the tangent
|
||||||
|
// points are at cos = 3/10 from the line to the base, and the upper one is nearer the pick.
|
||||||
|
s.script("LINE 30,20 TAN 20,23\n\n").unwrap();
|
||||||
|
let (a, b) = last_line(&s);
|
||||||
|
assert!(near(a, 30.0, 20.0) && near(b, 20.9, 20.0 + 3.0 * 0.91f64.sqrt()), "{a:?} {b:?}");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn from_nests_with_a_snap_override() {
|
fn from_nests_with_a_snap_override() {
|
||||||
let mut s = drawing();
|
let mut s = drawing();
|
||||||
@@ -116,3 +144,97 @@ fn a_command_keyword_wins_over_a_snap_word() {
|
|||||||
s.cmdline("arc _cen").unwrap();
|
s.cmdline("arc _cen").unwrap();
|
||||||
assert!(s.prompt_text().ends_with("Center of:"), "{}", s.prompt_text());
|
assert!(s.prompt_text().ends_with("Center of:"), "{}", s.prompt_text());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tan_for_a_circle_radius_touches_the_picked_circle() {
|
||||||
|
// #1512: the circle around the center that touches the circle at 20,20 radius 3, on the side
|
||||||
|
// it was picked: the near side (radius 7), the far side (13), and through Diameter.
|
||||||
|
for (script, center, r) in [
|
||||||
|
("CIRCLE 30,20 TAN 23.02,20.03\n", (30.0, 20.0), 7.0),
|
||||||
|
("CIRCLE 30,20 TAN 16.98,19.97\n", (30.0, 20.0), 13.0),
|
||||||
|
("CIRCLE 20,10 D TAN 20.03,17.02\n", (20.0, 10.0), 7.0),
|
||||||
|
] {
|
||||||
|
let mut s = drawing();
|
||||||
|
s.script(script).unwrap();
|
||||||
|
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||||
|
let (c, got) = last_circle(&s);
|
||||||
|
assert!(near(c, center.0, center.1) && (got - r).abs() < 1e-9, "{script}: {c:?} r={got}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tan_for_a_3p_circle_touches_the_picked_circles() {
|
||||||
|
// #1512: through two points and tangent to the circle at 20,20 radius 3, the tangent pick
|
||||||
|
// first or last.
|
||||||
|
for script in ["CIRCLE 3P 26,20 26,26 TAN 23.02,20.03\n", "CIRCLE 3P TAN 23.02,20.03 26,20 26,26\n"] {
|
||||||
|
let mut s = drawing();
|
||||||
|
s.script(script).unwrap();
|
||||||
|
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||||
|
let (c, r) = last_circle(&s);
|
||||||
|
assert!((c.dist(Vec2::new(26.0, 20.0)) - r).abs() < 1e-9 && (c.dist(Vec2::new(26.0, 26.0)) - r).abs() < 1e-9, "{script}");
|
||||||
|
assert!((c.dist(Vec2::new(20.0, 20.0)) - (3.0 + r)).abs() < 1e-9, "{script}: {c:?} r={r}");
|
||||||
|
}
|
||||||
|
// Tan, Tan, Tan: the circle between three circles of radius 1, picked on their inner sides.
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.script("CIRCLE 0,0 1\nCIRCLE 6,0 1\nCIRCLE 3,5 1\nCIRCLE 3P TAN 0.98,0.2 TAN 5.02,0.2 TAN 3.01,3.98\n").unwrap();
|
||||||
|
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||||
|
let (c, r) = last_circle(&s);
|
||||||
|
for k in [(0.0, 0.0), (6.0, 0.0), (3.0, 5.0)] {
|
||||||
|
assert!((c.dist(Vec2::new(k.0, k.1)) - (1.0 + r)).abs() < 1e-9, "{c:?} r={r}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tan_for_a_3p_circle_touches_an_arc_within_its_sweep() {
|
||||||
|
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
|
||||||
|
// on the right or the far left, both off an arc swept from 90° to 100°: no circle.
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 90, "end": 100})).unwrap();
|
||||||
|
s.script("CIRCLE 3P 26,20 26,26 TAN 19.74,22.99\n").unwrap();
|
||||||
|
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
|
||||||
|
assert!(!s.doc().unwrap().model.iter().any(|e| matches!(e.kind, EntityKind::Circle(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tan_for_a_3p_circle_takes_the_solution_that_touches_the_arc() {
|
||||||
|
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
|
||||||
|
// at about 29.6° and -103.3°. Picked at 20° on an arc swept from 200° to 25°, the 29.6°
|
||||||
|
// circle is nearer the pick but off the arc: the -103.3° one (radius 6.0826) is drawn.
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 200, "end": 25})).unwrap();
|
||||||
|
s.script("CIRCLE 3P 26,20 26,26 TAN 22.82,21.03\n").unwrap();
|
||||||
|
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||||
|
let (c, r) = last_circle(&s);
|
||||||
|
assert!((c.dist(Vec2::new(20.0, 20.0)) - (r - 3.0)).abs() < 1e-9 && (r - 6.082575694955838).abs() < 1e-9, "{c:?} r={r}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tan_for_a_circle_radius_refuses_the_picked_circles_own_center() {
|
||||||
|
// #1512: a circle around 20,20 would lie on the circle there, not touch it.
|
||||||
|
let mut s = drawing();
|
||||||
|
s.script("CIRCLE 20,20 TAN 23.02,20.03\n").unwrap();
|
||||||
|
assert!(s.prompt_text().contains("radius of circle"), "{}", s.prompt_text());
|
||||||
|
assert!(s.log.iter().any(|l| l.contains("No circle around the center is tangent there.")), "{:?}", s.log);
|
||||||
|
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tan_for_a_3p_circle_refuses_the_picked_circle_itself() {
|
||||||
|
// #1512: tangent twice to the circle and through a point on it is only the circle itself.
|
||||||
|
let mut s = drawing();
|
||||||
|
s.script("CIRCLE 3P TAN 23.02,20.03 TAN 16.98,20.03 20,23\n").unwrap();
|
||||||
|
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
|
||||||
|
assert!(s.log.iter().any(|l| l.contains("Circle does not exist.")), "{:?}", s.log);
|
||||||
|
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tan_for_a_3p_circle_through_points_in_line_with_the_picked_circles_center() {
|
||||||
|
// Through 3,0 and 5,0 and tangent to the unit circle at the origin: the two points and that
|
||||||
|
// circle's center lie on one line, the circle that touches it does not (center 4,±√48, radius 7).
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.script("CIRCLE 0,0 1\nCIRCLE 3P 3,0 5,0 TAN 1,0\n").unwrap();
|
||||||
|
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||||
|
let (c, r) = last_circle(&s);
|
||||||
|
assert!(near(Vec2::new(c.x, c.y.abs()), 4.0, 48f64.sqrt()) && (r - 7.0).abs() < 1e-9, "{c:?} r={r}");
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
//! Tab cycling through object snaps: a crowd of candidates is capped, hostile cursors and
|
||||||
|
//! apertures give no candidates, and the list never repeats a snap.
|
||||||
|
|
||||||
|
use cadcraft_engine::Session;
|
||||||
|
use cadcraft_engine::doc::Space;
|
||||||
|
use cadcraft_engine::geom::Vec2;
|
||||||
|
use cadcraft_engine::pointmod::snap_candidates;
|
||||||
|
use cadcraft_engine::snap::mode;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_crowd_of_snaps_is_capped_and_never_repeats() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
// 600 short lines fanning out from points packed round the origin: 1,200 endpoints.
|
||||||
|
for i in 0..600 {
|
||||||
|
let a = f64::from(i) * 0.01;
|
||||||
|
let p = [1e-3 * a.cos(), 1e-3 * a.sin()];
|
||||||
|
s.execute("line", &json!({ "points": [p, [a.cos(), a.sin()]] })).unwrap();
|
||||||
|
}
|
||||||
|
let d = s.doc().unwrap();
|
||||||
|
let cands = snap_candidates(d, &Space::Model, Vec2::ZERO, 0.5, mode::END | mode::INT | mode::NEA, None, false);
|
||||||
|
assert!(!cands.is_empty());
|
||||||
|
assert!(cands.len() <= 257, "{} candidates", cands.len());
|
||||||
|
for (i, a) in cands.iter().enumerate() {
|
||||||
|
assert!(a.point.is_finite());
|
||||||
|
assert!(!cands.iter().skip(i + 1).any(|b| b.mode == a.mode && b.point == a.point), "{a:?} repeats");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_cursor_and_aperture_give_no_candidates() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||||
|
let d = s.doc().unwrap();
|
||||||
|
let space = Space::Model;
|
||||||
|
let all = mode::END | mode::MID | mode::INT | mode::NEA | mode::PER;
|
||||||
|
for (c, ap) in [
|
||||||
|
(Vec2::new(f64::NAN, 0.0), 0.5),
|
||||||
|
(Vec2::new(0.0, f64::INFINITY), 0.5),
|
||||||
|
(Vec2::ZERO, f64::NAN),
|
||||||
|
(Vec2::ZERO, 0.0),
|
||||||
|
(Vec2::ZERO, -1.0),
|
||||||
|
(Vec2::ZERO, f64::INFINITY),
|
||||||
|
] {
|
||||||
|
assert!(snap_candidates(d, &space, c, ap, all, None, false).is_empty(), "{c:?} {ap}");
|
||||||
|
assert!(snap_candidates(d, &space, c, ap, all, Some(Vec2::new(f64::NAN, 1.0)), true).is_empty(), "{c:?} {ap}");
|
||||||
|
}
|
||||||
|
// A huge but finite aperture still answers, from the objects there are.
|
||||||
|
let far = snap_candidates(d, &space, Vec2::ZERO, 1e300, mode::END, None, false);
|
||||||
|
assert!(far.iter().all(|h| h.point.is_finite()));
|
||||||
|
// Object snaps off (or only the OFF bit) offer nothing.
|
||||||
|
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, 0, None, false).is_empty());
|
||||||
|
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, mode::END | mode::OFF, None, false).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_endpoint_under_the_aperture_is_offered_not_one_per_mode() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
// Three line ends close together, all within the aperture of the cursor between them.
|
||||||
|
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
|
||||||
|
s.execute("line", &json!({ "points": [a, b] })).unwrap();
|
||||||
|
}
|
||||||
|
let d = s.doc().unwrap();
|
||||||
|
let cands = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false);
|
||||||
|
let ends: Vec<Vec2> = cands.iter().filter(|h| h.mode == mode::END).map(|h| h.point).collect();
|
||||||
|
assert_eq!(ends.len(), 3, "{cands:?}");
|
||||||
|
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
|
||||||
|
assert!(ends.iter().any(|p| p.near(want, 1e-12)), "{want:?} in {ends:?}");
|
||||||
|
}
|
||||||
|
// The first is the snap a click would take.
|
||||||
|
let first = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).first().map(|h| h.point);
|
||||||
|
assert_eq!(first, cadcraft_engine::snap::osnap(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).map(|h| h.point));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A base point that is not a number gives no candidates, though the cursor is on an endpoint: the
|
||||||
|
/// perpendicular and tangent points from it would be meaningless, as a viewport already treats it.
|
||||||
|
#[test]
|
||||||
|
fn a_non_finite_base_gives_no_candidates() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||||
|
let d = s.doc().unwrap();
|
||||||
|
let all = mode::END | mode::PER | mode::TAN | mode::NEA;
|
||||||
|
for base in [Vec2::new(f64::NAN, 1.0), Vec2::new(1.0, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NAN)] {
|
||||||
|
assert!(snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), false).is_empty(), "{base:?}");
|
||||||
|
assert!(cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), true).is_empty(), "{base:?}");
|
||||||
|
}
|
||||||
|
// A finite base still offers them.
|
||||||
|
assert!(!snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(Vec2::new(5.0, 5.0)), false).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn deferred_snaps_of_two_curves_at_one_point_are_both_offered() {
|
||||||
|
// Two circles touching at the origin: each offers its own deferred tangent there, and the
|
||||||
|
// line drawn from it depends on which circle it is.
|
||||||
|
let mut s = Session::new();
|
||||||
|
s.script("CIRCLE 0,1 1\nCIRCLE 0,-2 2\n").unwrap();
|
||||||
|
let d = s.doc().unwrap();
|
||||||
|
let all = cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(0.0, 0.1), 0.5, mode::TAN, None, true);
|
||||||
|
let curves: Vec<_> = all.iter().filter_map(|h| h.deferred.map(|f| f.curve)).collect();
|
||||||
|
assert_eq!(curves.len(), 2, "{all:?}");
|
||||||
|
assert_ne!(curves.first(), curves.get(1), "{all:?}");
|
||||||
|
}
|
||||||
@@ -16,7 +16,9 @@ use std::borrow::Cow;
|
|||||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number, proxy_has_string_stream};
|
use cadcraft_doc::foreign::{
|
||||||
|
Foreign, ForeignExtra, ForeignKey, ForeignObject, VertexId, class_group, class_index, class_number, proxy_has_string_stream,
|
||||||
|
};
|
||||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
|
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
|
||||||
use craft_dxf::{SectionRef, Tag, Version};
|
use craft_dxf::{SectionRef, Tag, Version};
|
||||||
|
|
||||||
@@ -83,6 +85,8 @@ fn leader_acad_rest(chunk: &[Tag]) -> Vec<Tag> {
|
|||||||
|
|
||||||
/// Most objects kept from one file.
|
/// Most objects kept from one file.
|
||||||
const MAX_OBJECTS: usize = 1_000_000;
|
const MAX_OBJECTS: usize = 1_000_000;
|
||||||
|
/// Most vertices of one polyline whose identifiers are kept.
|
||||||
|
const MAX_VERTEX_IDS: usize = 1_000_000;
|
||||||
/// Most xdata groups kept per record (AutoCAD allows 16 KB of xdata per object).
|
/// Most xdata groups kept per record (AutoCAD allows 16 KB of xdata per object).
|
||||||
const MAX_XDATA_GROUPS: usize = cadcraft_doc::MAX_XDATA_GROUPS;
|
const MAX_XDATA_GROUPS: usize = cadcraft_doc::MAX_XDATA_GROUPS;
|
||||||
/// Longest ownership chain followed.
|
/// Longest ownership chain followed.
|
||||||
@@ -345,9 +349,57 @@ fn extra(kind: &str, tags: &[Tag], entity: bool, unknown: bool, kept: &HashSet<S
|
|||||||
}
|
}
|
||||||
x.props = props.iter().filter(|t| matches!(t.code, 347 | 284)).map(raw).collect();
|
x.props = props.iter().filter(|t| matches!(t.code, 347 | 284)).map(raw).collect();
|
||||||
}
|
}
|
||||||
|
if entity && !unknown && kind == "LWPOLYLINE" {
|
||||||
|
x.vertex_ids = vertex_ids(tags);
|
||||||
|
}
|
||||||
x
|
x
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A LWPOLYLINE record's vertices with their identifiers (group 91 after a vertex's point): one
|
||||||
|
/// per vertex, identifier 0 for a vertex without one; empty when no vertex has one
|
||||||
|
/// ([`ForeignExtra::vertex_ids`]). The points are as the reader gives them: mirrored in x when
|
||||||
|
/// the normal points down. Groups inside an application's `102 {` … `102 }` are not the
|
||||||
|
/// polyline's.
|
||||||
|
fn vertex_ids(tags: &[Tag]) -> Vec<VertexId> {
|
||||||
|
let mut in_app = false;
|
||||||
|
let own_tags: Vec<&Tag> = tags
|
||||||
|
.iter()
|
||||||
|
.take_while(|t| t.code < 1000)
|
||||||
|
.filter(|t| {
|
||||||
|
if t.code == 102 {
|
||||||
|
in_app = t.str().trim_start().starts_with('{');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
!in_app
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let own = || own_tags.iter().copied();
|
||||||
|
let down = own().any(|t| t.code == 230 && t.f64() < 0.0);
|
||||||
|
if !own().any(|t| t.code == 91 && t.i64() != 0) {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
let mut ids: Vec<VertexId> = Vec::new();
|
||||||
|
for t in own() {
|
||||||
|
match t.code {
|
||||||
|
// A polyline past the cap keeps none: identifiers for some of its vertices would be wrong.
|
||||||
|
10 if ids.len() >= MAX_VERTEX_IDS => return Vec::new(),
|
||||||
|
10 => ids.push(VertexId { id: 0, x: if down { -t.f64() } else { t.f64() }, y: 0.0 }),
|
||||||
|
20 => {
|
||||||
|
if let Some(last) = ids.last_mut() {
|
||||||
|
last.y = t.f64();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
91 => {
|
||||||
|
if let Some(last) = ids.last_mut() {
|
||||||
|
last.id = i32::try_from(t.i64()).unwrap_or(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ids
|
||||||
|
}
|
||||||
|
|
||||||
/// Every entity of the drawing (model space, layouts, blocks).
|
/// Every entity of the drawing (model space, layouts, blocks).
|
||||||
fn all_entities(d: &Drawing) -> impl Iterator<Item = &Entity> {
|
fn all_entities(d: &Drawing) -> impl Iterator<Item = &Entity> {
|
||||||
std::iter::once(&d.model)
|
std::iter::once(&d.model)
|
||||||
|
|||||||
@@ -169,7 +169,11 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
|||||||
w.f(38, elevation);
|
w.f(38, elevation);
|
||||||
}
|
}
|
||||||
thickness(w, e);
|
thickness(w, e);
|
||||||
for v in &p.vertices {
|
// The vertex identifiers the file gave the polyline (DXF 2010 and later), while its
|
||||||
|
// vertices are where they were read: geometric constraints name its segments by them.
|
||||||
|
let kept = d.foreign.entities.get(&e.handle).map(|x| x.vertex_ids.as_slice()).filter(|_| cx.target >= Version::R2010);
|
||||||
|
let ids = kept.and_then(|kept| cadcraft_doc::foreign::vertex_ids_for(kept, p.vertices.iter().map(|v| (v.p.x, v.p.y))));
|
||||||
|
for (i, v) in p.vertices.iter().enumerate() {
|
||||||
w.p2(10, v.p);
|
w.p2(10, v.p);
|
||||||
if v.start_width != 0.0 || v.end_width != 0.0 {
|
if v.start_width != 0.0 || v.end_width != 0.0 {
|
||||||
w.f(40, v.start_width);
|
w.f(40, v.start_width);
|
||||||
@@ -178,6 +182,9 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
|||||||
if v.bulge != 0.0 {
|
if v.bulge != 0.0 {
|
||||||
w.f(42, v.bulge);
|
w.f(42, v.bulge);
|
||||||
}
|
}
|
||||||
|
if let Some(id) = ids.as_ref().and_then(|ids| ids.get(i)).filter(|id| **id != 0) {
|
||||||
|
w.i(91, i64::from(*id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
EntityKind::MLine(m) => {
|
EntityKind::MLine(m) => {
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ const HEADER_VARS: &[(&str, i32)] = &[
|
|||||||
("PSTYLEMODE", 290),
|
("PSTYLEMODE", 290),
|
||||||
("INSUNITS", 70),
|
("INSUNITS", 70),
|
||||||
("MEASUREMENT", 70),
|
("MEASUREMENT", 70),
|
||||||
|
("REGENMODE", 70),
|
||||||
("PSLTSCALE", 70),
|
("PSLTSCALE", 70),
|
||||||
// The model view the drawing is saved at, as DXF keeps it in HEADER (the `*ACTIVE` VPORT
|
// The model view the drawing is saved at, as DXF keeps it in HEADER (the `*ACTIVE` VPORT
|
||||||
// record below repeats it). Written so a drawing opened on its saved view saves it back.
|
// record below repeats it). Written so a drawing opened on its saved view saves it back.
|
||||||
|
|||||||
@@ -287,8 +287,19 @@ impl<'o> Out<'o> {
|
|||||||
|
|
||||||
/// Header variables that change on every save (time stamps, the handle seed, GUIDs): not
|
/// Header variables that change on every save (time stamps, the handle seed, GUIDs): not
|
||||||
/// compared.
|
/// compared.
|
||||||
pub const VOLATILE_HEADER: &[&str] =
|
/// `CADCRAFT_DIMASO_MODE` is the engine's memory of the mode DIMASO turned off; no file keeps it.
|
||||||
&["HANDSEED", "TDCREATE", "TDUCREATE", "TDUPDATE", "TDUUPDATE", "TDINDWG", "TDUSRTIMER", "VERSIONGUID", "FINGERPRINTGUID"];
|
pub const VOLATILE_HEADER: &[&str] = &[
|
||||||
|
"HANDSEED",
|
||||||
|
"TDCREATE",
|
||||||
|
"TDUCREATE",
|
||||||
|
"TDUPDATE",
|
||||||
|
"TDUUPDATE",
|
||||||
|
"TDINDWG",
|
||||||
|
"TDUSRTIMER",
|
||||||
|
"VERSIONGUID",
|
||||||
|
"FINGERPRINTGUID",
|
||||||
|
"CADCRAFT_DIMASO_MODE",
|
||||||
|
];
|
||||||
|
|
||||||
/// Compare `before` (the drawing as first opened) with `after` (the same drawing saved and
|
/// Compare `before` (the drawing as first opened) with `after` (the same drawing saved and
|
||||||
/// reopened). Differences are reported as what `after` lost, gained or changed.
|
/// reopened). Differences are reported as what `after` lost, gained or changed.
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
//! A lightweight polyline keeps its vertex identifiers (LWPOLYLINE group 91 after a vertex, DXF
|
||||||
|
//! 2010 and later) through a save while its vertices are where they were read.
|
||||||
|
//! Geometric constraints name a polyline's segments by these identifiers. CADCraft's polyline has
|
||||||
|
//! none, so every save wrote the polyline without them, and what the constraints name was gone.
|
||||||
|
//!
|
||||||
|
//! The DWG is written here with acadrust, the identifiers out of order and the first vertex not
|
||||||
|
//! the smallest, as on a polyline that was edited in another program. The harness builds this
|
||||||
|
//! module only where acadrust builds (see `main.rs`).
|
||||||
|
use std::io::Cursor;
|
||||||
|
|
||||||
|
use acadrust::entities::{EntityType, LwPolyline, LwVertex};
|
||||||
|
use acadrust::{CadDocument, DxfVersion, Vector2};
|
||||||
|
use cadcraft_io::{SaveOptions, Version, read, write_with};
|
||||||
|
|
||||||
|
const VERTEX_IDS: [i32; 4] = [2, 5, 7, 1];
|
||||||
|
|
||||||
|
fn polyline_dwg() -> Vec<u8> {
|
||||||
|
polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], 1.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A DWG with one closed polyline at `points`, its normal along `normal_z` Z.
|
||||||
|
fn polyline_dwg_with(points: [(f64, f64); 4], normal_z: f64) -> Vec<u8> {
|
||||||
|
let mut doc = CadDocument::with_version(DxfVersion::AC1032);
|
||||||
|
let mut polyline = LwPolyline::new();
|
||||||
|
polyline.is_closed = true;
|
||||||
|
polyline.normal = acadrust::Vector3::new(0.0, 0.0, normal_z);
|
||||||
|
for (id, (x, y)) in VERTEX_IDS.iter().zip(points) {
|
||||||
|
polyline.vertices.push(LwVertex { vertex_id: *id, ..LwVertex::new(Vector2::new(x, y)) });
|
||||||
|
}
|
||||||
|
doc.add_entity(EntityType::LwPolyline(polyline)).expect("add the polyline");
|
||||||
|
acadrust::DwgWriter::write_to_vec(&doc).expect("write the DWG")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The vertex identifiers of the one lightweight polyline in DWG bytes.
|
||||||
|
fn vertex_ids_of(dwg: &[u8]) -> Vec<i32> {
|
||||||
|
let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg.to_vec())).read().unwrap();
|
||||||
|
doc.entities()
|
||||||
|
.find_map(|e| match e {
|
||||||
|
EntityType::LwPolyline(p) => Some(p.vertices.iter().map(|v| v.vertex_id).collect()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.expect("the polyline is in the DWG")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The vertex identifiers (groups 91) of the one LWPOLYLINE record in a DXF text.
|
||||||
|
fn dxf_vertex_ids(dxf: &[u8]) -> Vec<String> {
|
||||||
|
let text = String::from_utf8_lossy(dxf);
|
||||||
|
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||||
|
let mut pairs = lines.chunks(2).filter_map(|pair| Some((*pair.first()?, *pair.get(1)?)));
|
||||||
|
let record = pairs.by_ref().skip_while(|pair| *pair != ("0", "LWPOLYLINE")).skip(1);
|
||||||
|
record.take_while(|(code, _)| *code != "0").filter(|(code, _)| *code == "91").map(|(_, value)| value.to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(d: &cadcraft_doc::Drawing, name: &str, version: Version) -> Vec<u8> {
|
||||||
|
write_with(d, name, &SaveOptions { version: Some(version), binary: false }).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_polyline_keeps_its_vertex_identifiers_through_a_save() {
|
||||||
|
cadcraft_io::dwg_worker::allow_in_process();
|
||||||
|
let dwg = polyline_dwg();
|
||||||
|
assert_eq!(vertex_ids_of(&dwg), VERTEX_IDS, "the fixture as acadrust reads it");
|
||||||
|
let d = read(&dwg, "polyline.dwg").unwrap();
|
||||||
|
for version in [Version::R2010, Version::R2018] {
|
||||||
|
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", version)), VERTEX_IDS, "DWG {version:?}");
|
||||||
|
}
|
||||||
|
assert_eq!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2018)), ["2", "5", "7", "1"]);
|
||||||
|
// A DXF before 2010 has no such group.
|
||||||
|
assert!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2000)).is_empty());
|
||||||
|
let back = read(&save(&d, "saved.dxf", Version::R2018), "saved.dxf").unwrap();
|
||||||
|
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"], "read back from a DXF");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Once a vertex is elsewhere, the order is another or a vertex is gone, the identifiers no longer
|
||||||
|
/// say which vertex is which: none are written.
|
||||||
|
#[test]
|
||||||
|
fn an_edited_polyline_drops_its_vertex_identifiers() {
|
||||||
|
cadcraft_io::dwg_worker::allow_in_process();
|
||||||
|
let mut d = read(&polyline_dwg(), "polyline.dwg").unwrap();
|
||||||
|
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
|
||||||
|
let mut after = |edit: fn(&mut cadcraft_doc::LwPolyline)| {
|
||||||
|
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
|
||||||
|
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
|
||||||
|
edit(p);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
vertex_ids_of(&save(&d, "edited.dwg", Version::R2018))
|
||||||
|
};
|
||||||
|
assert_eq!(after(|p| p.vertices.reverse()), [0; 4], "reversed");
|
||||||
|
assert_eq!(after(|p| p.vertices.reverse()), VERTEX_IDS, "reversed back: every vertex is where it was read");
|
||||||
|
assert_eq!(after(|p| p.vertices[1].p.x += 1.0), [0; 4], "a vertex moved");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A polyline whose normal points down is read mirrored in x; untouched, it keeps its identifiers.
|
||||||
|
#[test]
|
||||||
|
fn a_polyline_facing_down_keeps_its_vertex_identifiers() {
|
||||||
|
cadcraft_io::dwg_worker::allow_in_process();
|
||||||
|
let d = read(&polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], -1.0), "down.dwg").unwrap();
|
||||||
|
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), VERTEX_IDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reversed, a polyline symmetric about x = 0 has its mirror image's points: the identifiers still
|
||||||
|
/// no longer say which vertex is which.
|
||||||
|
#[test]
|
||||||
|
fn a_reversed_symmetric_polyline_drops_its_vertex_identifiers() {
|
||||||
|
cadcraft_io::dwg_worker::allow_in_process();
|
||||||
|
let mut d = read(&polyline_dwg_with([(-20.0, 0.0), (-20.0, 25.0), (20.0, 25.0), (20.0, 0.0)], 1.0), "sym.dwg").unwrap();
|
||||||
|
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
|
||||||
|
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
|
||||||
|
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
|
||||||
|
p.vertices.reverse();
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), [0; 4]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A group 91 inside an application's `102 {` group of the record is not a vertex identifier.
|
||||||
|
#[test]
|
||||||
|
fn a_91_inside_an_application_group_is_not_an_identifier() {
|
||||||
|
cadcraft_io::dwg_worker::allow_in_process();
|
||||||
|
let d = read(&polyline_dwg(), "polyline.dwg").unwrap();
|
||||||
|
let dxf = String::from_utf8(save(&d, "saved.dxf", Version::R2018)).unwrap();
|
||||||
|
let mut lines: Vec<&str> = dxf.lines().collect();
|
||||||
|
let start = lines.windows(2).position(|pair| pair[0].trim() == "0" && pair[1].trim() == "LWPOLYLINE").unwrap();
|
||||||
|
// After the first vertex's identifier.
|
||||||
|
let at = (start..lines.len()).step_by(2).find(|i| lines[*i].trim() == "91").unwrap() + 2;
|
||||||
|
lines.splice(at..at, ["102", "{SOMEAPP", " 91", "9", "102", "}"]);
|
||||||
|
let back = read(lines.join("\n").as_bytes(), "app.dxf").unwrap();
|
||||||
|
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"]);
|
||||||
|
}
|
||||||
@@ -62,6 +62,8 @@ mod low_handseed;
|
|||||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||||
mod ltype_dwg_dash_count;
|
mod ltype_dwg_dash_count;
|
||||||
mod ltype_element_cap;
|
mod ltype_element_cap;
|
||||||
|
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||||
|
mod lwpolyline_vertex_ids;
|
||||||
mod minsert_marker;
|
mod minsert_marker;
|
||||||
mod mleader_content;
|
mod mleader_content;
|
||||||
mod mleader_roundtrip;
|
mod mleader_roundtrip;
|
||||||
|
|||||||
@@ -200,12 +200,14 @@ pub(super) fn override_cursor(app: &mut CadApp, raw: Vec2, xf: &Xf) {
|
|||||||
let s = &app.session.settings;
|
let s = &app.session.settings;
|
||||||
let osmode = over.unwrap_or(s.osmode) | if s.osnaphatch { snap::mode::HATCH } else { 0 };
|
let osmode = over.unwrap_or(s.osmode) | if s.osnaphatch { snap::mode::HATCH } else { 0 };
|
||||||
let Ok(st) = app.session.state() else { return };
|
let Ok(st) = app.session.state() else { return };
|
||||||
|
let space = st.edit_space();
|
||||||
|
let frozen = st.viewport_frozen();
|
||||||
let hit = match cycle {
|
let hit = match cycle {
|
||||||
Some(i) => {
|
Some(i) => {
|
||||||
let cands = cadcraft_engine::pointmod::snap_candidates(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred);
|
let cands = cadcraft_engine::pointmod::snap_candidates_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen);
|
||||||
cands.get(i % cands.len().max(1)).copied()
|
cands.get(i % cands.len().max(1)).copied()
|
||||||
}
|
}
|
||||||
None => snap::osnap(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred),
|
None => snap::osnap_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen),
|
||||||
};
|
};
|
||||||
let p = match (hit, app.canvas.snap) {
|
let p = match (hit, app.canvas.snap) {
|
||||||
(Some(h), _) => {
|
(Some(h), _) => {
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ mod shared_controls;
|
|||||||
mod shortcut_menus;
|
mod shortcut_menus;
|
||||||
mod shortcuts_checked;
|
mod shortcuts_checked;
|
||||||
mod slow_clicks;
|
mod slow_clicks;
|
||||||
|
mod snap_tab_cycling;
|
||||||
mod space_at_options;
|
mod space_at_options;
|
||||||
mod status_bar_toggles;
|
mod status_bar_toggles;
|
||||||
mod style_dialogs;
|
mod style_dialogs;
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
//! Tab at a point prompt steps through every object snap under the aperture (each endpoint of
|
||||||
|
//! each object nearby), not just the closest snap of each running mode, and comes back round.
|
||||||
|
|
||||||
|
use cadcraft_engine::Session;
|
||||||
|
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Line, Space};
|
||||||
|
use cadcraft_engine::snap::mode;
|
||||||
|
use cadcraft_geom::Vec2;
|
||||||
|
use cadcraft_ui_egui::{CadApp, Services};
|
||||||
|
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
|
||||||
|
use egui_kittest::Harness;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tab_cycles_through_every_endpoint_under_the_aperture() {
|
||||||
|
let mut s = Session::new();
|
||||||
|
// Three line ends close together (within the aperture of the cursor between them).
|
||||||
|
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
|
||||||
|
s.execute("line", &json!({ "points": [a, b] })).unwrap();
|
||||||
|
}
|
||||||
|
s.execute("setvar", &json!({ "name": "OSMODE", "value": 1 })).unwrap();
|
||||||
|
s.execute("view.set", &json!({ "center": [0, 0], "height": 20 })).unwrap();
|
||||||
|
let mut app = CadApp::new(s, Services::default());
|
||||||
|
app.canvas.zoom_pending = false;
|
||||||
|
let mut h = Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|
||||||
|
|ui, app: &mut CadApp| {
|
||||||
|
app.logic(ui.ctx());
|
||||||
|
app.ui(ui);
|
||||||
|
},
|
||||||
|
app,
|
||||||
|
);
|
||||||
|
h.run_steps(3);
|
||||||
|
h.state_mut().session.start("line").unwrap();
|
||||||
|
h.run_steps(2);
|
||||||
|
let xf = h.state().canvas.xf.unwrap();
|
||||||
|
let at = xf.to_screen(Vec2::new(0.03, 0.0));
|
||||||
|
h.event(Event::PointerMoved(at));
|
||||||
|
h.run_steps(2);
|
||||||
|
let mut seen: Vec<Vec2> = Vec::new();
|
||||||
|
for i in 0..4 {
|
||||||
|
let p = h.state().canvas.snap.map(|s| s.point).unwrap();
|
||||||
|
if i < 3 {
|
||||||
|
assert!(!seen.iter().any(|q| q.near(p, 1e-9)), "Tab {i} repeats {p:?} ({seen:?})");
|
||||||
|
} else {
|
||||||
|
assert!(seen.first().is_some_and(|q| q.near(p, 1e-9)), "the fourth Tab comes back round");
|
||||||
|
}
|
||||||
|
seen.push(p);
|
||||||
|
h.key_press(egui::Key::Tab);
|
||||||
|
h.run_steps(2);
|
||||||
|
}
|
||||||
|
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
|
||||||
|
assert!(seen.iter().any(|q| q.near(want, 1e-9)), "{want:?} in {seen:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Three endpoints near 10,0: 10,0 (the nearest to the cursor), 10.03,0 and 9.95,0. Endpoint is
|
||||||
|
/// the only running snap, so every candidate is an endpoint.
|
||||||
|
fn three_ends() -> Harness<'static, CadApp> {
|
||||||
|
let mut d = Drawing::new_imperial();
|
||||||
|
for (a, b) in [((0.0, 0.0), (10.0, 0.0)), ((10.03, 0.0), (20.0, 0.0)), ((9.95, 0.0), (9.95, -5.0))] {
|
||||||
|
let line = Line { a: Vec2::new(a.0, a.1).to3(0.0), b: Vec2::new(b.0, b.1).to3(0.0) };
|
||||||
|
d.add(&Space::Model, Common::default(), EntityKind::Line(line)).unwrap();
|
||||||
|
}
|
||||||
|
let mut session = Session::empty();
|
||||||
|
session.open_drawing(d, "Tab snap cycling", None);
|
||||||
|
session.execute("view.set", &json!({"center":[10,0],"height":8})).unwrap();
|
||||||
|
session.settings.osmode = mode::END;
|
||||||
|
session.settings.snapmode = false;
|
||||||
|
session.settings.orthomode = false;
|
||||||
|
let mut app = CadApp::new(session, Services::default());
|
||||||
|
app.canvas.zoom_pending = false;
|
||||||
|
let mut h = Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|
||||||
|
|ui, app: &mut CadApp| {
|
||||||
|
app.logic(ui.ctx());
|
||||||
|
app.ui(ui);
|
||||||
|
},
|
||||||
|
app,
|
||||||
|
);
|
||||||
|
h.run_steps(5);
|
||||||
|
h.state_mut().start("line");
|
||||||
|
h.run_steps(2);
|
||||||
|
assert_eq!(h.state().session.running.as_ref().unwrap().id, "line");
|
||||||
|
let ap = h.state().session.settings.aperture / h.state().canvas.xf.unwrap().scale;
|
||||||
|
assert!(ap > 0.07, "all three endpoints lie in the aperture ({ap})");
|
||||||
|
h
|
||||||
|
}
|
||||||
|
|
||||||
|
const CURSOR: Vec2 = Vec2::new(10.01, 0.0);
|
||||||
|
|
||||||
|
fn hover(h: &mut Harness<'_, CadApp>, p: Vec2) -> Pos2 {
|
||||||
|
let pos = h.state().canvas.xf.unwrap().to_screen(p);
|
||||||
|
h.event(Event::PointerMoved(pos));
|
||||||
|
h.run_steps(3);
|
||||||
|
pos
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tab, as the command line receives it (`cmdline::capture_tab`).
|
||||||
|
fn tab(h: &mut Harness<'_, CadApp>) {
|
||||||
|
h.key_press(egui::Key::Tab);
|
||||||
|
h.run_steps(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn snapped(h: &Harness<'_, CadApp>) -> Vec2 {
|
||||||
|
let hit = h.state().canvas.snap.expect("a snap marker");
|
||||||
|
assert_eq!(hit.mode, mode::END);
|
||||||
|
hit.point
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_at(got: Vec2, x: f64) {
|
||||||
|
assert!(got.near(Vec2::new(x, 0.0), 1e-9), "{got:?}, expected {x},0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn moving_the_cursor_away_starts_the_cycle_over() {
|
||||||
|
let mut h = three_ends();
|
||||||
|
hover(&mut h, CURSOR);
|
||||||
|
tab(&mut h);
|
||||||
|
assert_at(snapped(&h), 10.03);
|
||||||
|
hover(&mut h, Vec2::new(10.0, 2.0));
|
||||||
|
assert!(h.state().canvas.snap.is_none());
|
||||||
|
hover(&mut h, CURSOR);
|
||||||
|
assert_at(snapped(&h), 10.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_click_places_the_candidate_tab_chose() {
|
||||||
|
let mut h = three_ends();
|
||||||
|
let pos = hover(&mut h, CURSOR);
|
||||||
|
tab(&mut h);
|
||||||
|
assert_at(snapped(&h), 10.03);
|
||||||
|
for pressed in [true, false] {
|
||||||
|
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||||
|
h.run_steps(2);
|
||||||
|
}
|
||||||
|
let base = h.state().session.current_prompt().and_then(|p| p.base).expect("LINE asks for the next point");
|
||||||
|
assert_at(base, 10.03);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user