Compare commits

...
Author SHA1 Message Date
Tanish Manku fe3b20a37a Merge main 2026-11-20 18:28:48 -07:00
Tanish Manku 9746b6999a Snap: rustfmt 2026-11-20 17:58:24 -07:00
Marco Arnulfo 0ca0af9026 Tab snap tests from #1408: moving away restarts the cycle, a click takes Tab's choice
Carried from #1408's crates/ui-egui/tests/tab_snap_cycling.rs onto the #2350
Tab list: moving_the_cursor_away_starts_the_cycle_over and
a_click_places_the_candidate_tab_chose, with their three-endpoint fixture.
2026-11-20 17:57:59 -07:00
Tanish Manku 6971715295 Tab: a base point that is not a number gives no candidates
With a finite cursor and aperture, a NaN or infinite base passed the Tab
list's guards and it still offered snaps, though the perpendicular and tangent
points from such a base mean nothing (a viewport already skips it).
osnap_all and snap_candidates now return none for it.
2026-11-20 17:51:37 -07:00
Tanish Manku 8d3236c5a3 Merge pull request #3350 from storytold/stack/r2
Land #2763, #2905, #2918, #3233, #2804: tilted 2D polylines, mirrored heights on save, kept APPIDs, plot layout flags, Generate Boundary
2026-11-20 17:48:52 -07:00
Tanish Manku 5bfba91aa8 Tab: every deferred tangent and perpendicular under the aperture
The Tab list took the one deferred snap a click would, so with a circle under
the cursor and no base point the deferred perpendicular could not be reached
after the deferred tangent, nor a second curve's deferred snap. The list now
has one deferred snap per curve and mode (ported from #1673), ranked after
the snap points; the click still takes the nearest. Makes
osnap_all_ranks_every_candidate (from #1673) pass.
2026-11-20 17:47:22 -07:00
Tanish Manku 080c96aa06 Tab: snaps seen through different viewports stay apart in the list
The Tab list dropped a snap as a repeat when another had the same mode and
paper point, so where two viewports overlap only one of their model points
could be picked, and DIST measures in the model units of the viewport picked.
A repeat now also has to come from the same viewport (and be deferred or not
alike), in osnap_all and in snap_candidates. Makes
overlapping_viewports_each_offer_their_model_point (from #1673) pass.
2026-11-20 17:45:11 -07:00
Oliver Hagmann a2f732118f Snap tests from #1673: Tab keeps each viewport's snap and every deferred snap
Carried from #1673 onto the #2350 Tab list: overlapping viewports each offer
their model point, the deferred tangent and perpendicular on one circle are
both offered, and a click across spaces. That last test is inverted from
#1673: with #2347's ranking a viewport Endpoint beats a paper-space Nearest
that scores closer, as a snap point beats Nearest within one space; Tab
starts at the click's snap and still reaches the Nearest.
2026-11-20 17:43:12 -07:00
Tanish Manku c2af11dfa7 Nearest: a curve crossing a viewport edge offers its visible point
The Nearest from #2350 took each object's closest point first and only then
dropped it when the viewport clipped it, so an ellipse or spline whose closest
point lay just outside the viewport offered nothing, though another of its
points was in the aperture and in view. Each segment's point is now checked
before the closest is chosen, as before #2350, in one helper the click snap
and the Tab list share.
2026-11-20 17:39:55 -07:00
Tanish Manku f4d4a6e4e1 DXF read: a thick polyline drawn as seen from above keeps the side of Z it extruded toward 2026-11-20 17:37:24 -07:00
Tanish Manku b1dcb46e08 Snap test: convert the test's own DWG in process, as main's DWG reader now asks 2026-11-20 17:37:04 -07:00
Tanish Manku c00bc59949 Snap tests: fill in the Insert clip and Viewport twist fields that main added after #2347 2026-11-20 17:28:59 -07:00
Tanish Manku 1b577e9eed Merge #3164: Snap: object snaps skip layers frozen in the active layout viewport
# Conflicts:
#	crates/engine/src/doc_state.rs
#	crates/engine/src/pointmod.rs
2026-11-20 17:27:48 -07:00
Tanish Manku 29bf02b6ce Merge #2103: CIRCLE: tangent snaps for the radius and for 3P points
# Conflicts:
#	crates/engine/src/snap.rs
2026-11-20 17:27:21 -07:00
Tanish Manku 1998da2643 Merge #2350: Tab cycles through every object snap under the aperture, not one per mode
# Conflicts:
#	crates/engine/src/snap.rs
#	crates/ui-egui/tests/it/main.rs
#	docs/gaps.md
#	docs/ui-parity.md
2026-11-20 17:26:58 -07:00
Tanish Manku 28ed9c58a7 Merge #2347: Object snap: Center found by moving onto a circle, arc, ellipse or polyline arc
# Conflicts:
#	crates/engine/src/snap.rs
#	docs/ui-parity.md
2026-11-20 17:23:44 -07:00
Tanish Manku a3560a1442 Merge #2825: PER and TAN snap from anywhere on the object 2026-11-20 17:23:11 -07:00
Tanish Manku 80e9a97164 Merge main 2026-11-20 17:20:59 -07:00
Tanish Manku b39170aded HATCHGENERATEBOUNDARY: a mirrored hatch's boundary goes to its world height; the command is classified as using no files 2026-11-20 16:45:17 -07:00
Tanish Manku 318d8d9de1 Plot layout flag tests that save DWG opt in to the in-process bridge 2026-11-20 16:40:30 -07:00
Tanish Manku 4076a71dee Registered applications alone note no file version; the APPID tests that save DWG opt in to the in-process bridge 2026-11-20 16:40:26 -07:00
Tanish Manku e5a7d38a67 Merge #2804: Generate Boundary in a hatch's right-click menu (#2801) 2026-11-20 16:37:35 -07:00
Tanish Manku 46053d43c1 Merge #3233: save the plot layout flags as read (#3227) 2026-11-20 16:37:17 -07:00
Tanish Manku 6aa64fb5ae Merge #2918: a file's registered applications are kept when no xdata names them 2026-11-20 16:34:22 -07:00
Tanish Manku 543285778b Merge #2905: mirrored objects keep their world height and extrusion side 2026-11-20 16:34:00 -07:00
Tanish Manku fed8b0f4e4 Merge #2763: draw a tilted 2D POLYLINE as seen from above, like LWPOLYLINE 2026-11-20 16:33:50 -07:00
Ray dab89a38ed Layouts: keep an unchanged standard plot scale (#3227)
A layout read with a standard scale other than 1:1 (flags 176, group 75 = 25,
scale 0.02 for 1:50) lost plot layout flag 16 and its standard-scale choice on
save, because only scaled to fit and 1:1 counted as standard. The page now
keeps the file's group 75 with the scale it was read with; while the scale is
unchanged, saving writes that choice and keeps flag 16.
2026-11-17 12:33:43 -07:00
Ray 3ee12a8c62 Layouts: save the plot layout flags as read (#3227)
The DXF writer, which also feeds the DWG bridge, built the layout's plot
flags (AcDbPlotSettings group 70) from the bits CADCraft models and always
set 512 (plot paper space last) and 32 (plot with plot styles), plus 16
for a standard scale. A layout read with flags 0 came back as 560.

The page setup now keeps the flags as read; saving sets or clears only
the bits the page models (2, 4, 128, and 16 when the scale decides it).
Page setups made in CADCraft keep the old defaults.
2026-11-16 21:18:35 -07:00
jayzed80 c40ff9603e Snap: skip VPLAYER-frozen layers in MSPACE (#3158) 2026-11-14 14:54:49 +00:00
Walter Haslbeck 5869cf91f9 Merge remote-tracking branch 'origin/main' into fix/tilted-2d-polyline 2026-11-12 07:35:17 +01:00
2ez4gcxandClaude Opus 5.5 8e2aa822f7 Merge main into fix/dxf-mirrored-heights
Brings the branch up to main 6d744887, which has #2954's fix for
mtext::tests::strips_formatting, so the gate runs on a main that passes.
No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 13:21:46 +07:00
ZachAR3 595ccf2b06 Merge remote-tracking branch 'origin/main' into circle-tan-radius
# Conflicts:
#	crates/engine/src/cmd/draw.rs
#	docs/ui-parity.md
2026-11-09 17:07:40 +01:00
Walter Haslbeck a34cf69439 Merge remote-tracking branch 'origin/main' into fix/tilted-2d-polyline 2026-11-09 07:21:14 +01:00
2ez4gcxandClaude Opus 5.5 6ec0f2400a DXF test: the same objects facing up keep their height and thickness
The mirrored-objects test only had objects whose normal is 0,0,-1, so a
writer that flips the elevation and thickness of every object passed it.
It now reads the same nine objects with no normal and with 0,0,1 as
well: those keep +5 and +2 through a save, and their LINEs keep 39 = 2.0
with no 230.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 09:28:55 +07:00
mkzungandClaude Opus 5.5 18effe68b4 DXF/DWG: the registered applications test counts the records
The test only checked that an `Other_App` record was there, so a second record for the same
application would have passed. It now asks for exactly one, and a second test has a line's xdata
name the application as `OTHER_APP` beside the registered `Other_App`: DXF and DWG, twice, keep
the xdata and one APPID record. With `add_appids` keyed by the name as written instead of
case-insensitively, that test fails (2 records).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01H43qQA41CJLauqXnPgBQ7r
2026-11-08 14:17:58 +00:00
mkzungandClaude Opus 5.5 b325046f76 DXF/DWG: a file's registered applications are kept when no xdata names them
The writer rebuilt the APPID table only from the applications whose xdata
the drawing still had, so every other registered application of the file
was dropped at each save. The reader now keeps the names of all of the
file's APPID records, and the writer adds them to the table with the ones
in use.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01H43qQA41CJLauqXnPgBQ7r
2026-11-07 23:47:26 +00:00
2ez4gcxandClaude Opus 5.5 48bcb817ed DXF writer: say the mirrored flips are exact for 0,0,-1 only
The elevation and thickness flips are exact for a normal of 0,0,-1; a
tilted normal pointing partly down is flipped the same way, an
approximation. The comments now say so (CodeRabbit's note on #2905).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 22:04:50 +07:00
2ez4gcxandClaude Opus 5.5 275f989aa5 DXF: mirrored objects keep their world height and extrusion side
The reader keeps a mirrored object's normal (0,0,-1) but brings its points
into world coordinates; a polyline's or hatch's elevation stays along the
normal. The writer writes these objects with no normal, along +Z, so a
mirrored polyline or hatch at elevation 5 (world Z -5) came back at Z +5,
and a mirrored circle, arc, point, solid or text extruded up instead of
down. Their elevation and thickness are now written along +Z too: negated
when the normal points down Z. LINE writes its normal and keeps its
thickness as read.

Measured in AutoCAD 2024 (AutoCAD's objects, converted by CADCraft,
reopened in AutoCAD): every world point and thickness top now matches the
original.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:30:03 +07:00
austin62jakeandClaude Opus 5.5 8acdceeb61 fix(snap): a circle offers both perpendicular points from the base (CodeRabbit on #2825)
PER on a circle offered only the point nearest the base point, so with the
new object fallback a pick on the circle's far side jumped across it. Like
an arc, a circle now offers both antipodes, and the one nearer the cursor
wins. From the circle's centre, where every point is perpendicular, the
point under the cursor is taken.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 08:05:36 -06:00
austin62jakeandClaude Opus 5.5 4ce72c668a fix(snap): PER and TAN snap from anywhere on the object (#2800)
With a base point, a perpendicular or tangent snap was kept only when its
foot or tangent point lay within the aperture, so hovering elsewhere on the
line or circle found nothing, and a typed `per` said "No Perpendicular found
for specified point". As in AutoCAD, these snaps name an object, not a spot
on it: from anywhere over the object, the point jumps to the foot or the
tangent point.

They now also qualify when their object passes within the aperture, as a
fallback after every snap point within the aperture, so an endpoint,
midpoint or intersection under the cursor still wins. Of several objects,
the one nearest the cursor gives the snap; of several points on one (an
arc's antipodes, a circle's two tangents), the one nearest the cursor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 07:39:52 -06:00
okereke-devandClaude Opus 5.5 ad6d3d12ca HATCHGENERATEBOUNDARY: compare the loop count with the room left, so it can't overflow (CodeRabbit on #2804)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 21:53:26 -05:00
okereke-devandClaude Opus 5.5 6412e9c99a HATCHGENERATEBOUNDARY: a hatch named twice gets one boundary (CodeRabbit on #2804)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 21:36:46 -05:00
okereke-devandClaude Opus 5.5 f7c4c148a3 HATCHGENERATEBOUNDARY: keep the hatch elevation, refuse other spaces and over-limit calls (CodeRabbit on #2804)
Each polyline takes its hatch's elevation; a hatch outside the current space
is refused with a clear message; every selected hatch counts toward the
10,000-polyline limit, refused before anything is added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 21:25:18 -05:00
okereke-devandClaude Opus 5.5 0bd4d54f4a HATCHGENERATEBOUNDARY: Generate Boundary in the right-click menu of a hatch (#2801)
A closed polyline around every boundary loop (outer and islands) of the
selected hatches, which stay as they are: an associative hatch keeps its own
boundary objects and is not linked to the new polylines. Runs at once on a
pickfirst selection, otherwise asks for objects; one undo step.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 21:02:24 -05:00
Walter Haslbeck 11ee9f1f64 Merge remote-tracking branch 'origin/main' into fix/tilted-2d-polyline 2026-11-04 08:56:37 +01:00
Walter Haslbeck e928316c4d docs: leave file-format-parity.md to the maintainers (AGENTS.md); the rows are named in the PR description 2026-11-04 08:55:57 +01:00
Walter Haslbeck 1a3d2f6015 Merge branch 'pr2584' into fix/tilted-2d-polyline 2026-11-04 07:24:26 +01:00
Walter Haslbeck 41f9e394b9 fix(io): draw a tilted 2D POLYLINE as seen from above, like LWPOLYLINE (follow-up to #2584) 2026-11-03 15:42:49 +01:00
Francesco BVandClaude Opus 5.5 55ec024e31 Object snap: the center from the curve ranks behind snap points
A center found from its curve was scored by the cursor's distance to the
curve, so it beat the Midpoint or Quadrant of the same curve under the
cursor (those lie on the curve), and they could only be picked with Tab.
Now finish() tries the curve centers only when no snap point is in the
aperture, as in AutoCAD: Endpoint, Midpoint, Quadrant and Intersection
under the cursor win, the center shows elsewhere on the curve.

Hits from layout viewports are compared with paper-space ones by the same
rank (tier, then the score scaled into paper units), so a center keeps
its curve distance there instead of being rescored by the distance to the
center point. The 2,000-item work limit counts circles, arcs and ellipses
only, so straight segments gathered before them can't hide them.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-29 08:52:22 +01:00
Francesco BVandClaude Opus 5.5 64cb95d8ec Tab cycles through every object snap under the aperture, not one per mode (gaps U4)
Tab at a point prompt offered only the closest snap of each running mode,
so of several line ends under the aperture only one was reachable. The
candidate gathering is split out of osnap_in_with_prims (collect_in) and
the new snap::osnap_all keeps every candidate: each mode's points of every
object nearby, the intersections, perpendicular and tangent points from
the base, the deferred snap and the nearest point of each object, in
layout viewports too, ranked with the click snap's score (Nearest and
deferred last), without repeats and capped at 256. finish and finish_all
share base_snaps and nearest_points. pointmod::snap_candidates puts the
click snap first, then osnap_all's list.

Tests: every endpoint under the aperture is offered; 1,200 endpoints and
their crossings give at most 257 finite, unrepeated candidates; NaN or
infinite cursors, base points and apertures, zero or negative apertures,
OSMODE 0 and the F3 bit give none; with the real pointer Tab visits three
line ends and comes back round.

gaps: U4 removed. ui-parity: Tab row.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-27 19:52:55 +01:00
Francesco BVandClaude Opus 5.5 4a0063f5f6 Object snap: Center found by moving onto a circle, arc, ellipse or polyline arc
With the default running snaps (OSMODE 4133: END, CEN, INT, EXT) moving the
cursor onto a circle, an arc or the middle of a polyline arc found nothing:
Center only snapped with the cursor on the center itself. As in AutoCAD,
the cursor on a circle, arc, ellipse or polyline arc (also inside block
references) now finds its center (snap::curve_centers), scored by how near
the curve is so a nearer endpoint or intersection still wins; Tab cycling
offers it too.

Regression tests open DXF (with $OSMODE 0, which never changes the
profile's running snaps) and DWG files and snap on lines, intersections,
circles, arcs and polylines.

ui-parity: Center row.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-27 19:52:26 +01:00
ZachAR3 f4f0702d08 CIRCLE: a tangent circle never lies on the picked circle (#1512)
A radius picked with TAN around the picked circle's own center, or a 3P
circle tangent twice to one circle through a point on it, would only
reproduce that circle; both now report that no such circle exists.
2026-10-25 03:08:29 +01:00
ZachAR3 98401d6de2 CIRCLE: a 3P circle takes the tangent solution that touches the arc (#1512)
The arc check ran on the solver's best circle only, so when that one
touched the arc's circle off the sweep, a valid circle that touches the
arc was reported as nonexistent. The Tan, Tan, Tan solver now takes a
filter (ttt_where), and 3P skips off-arc candidates before choosing.
2026-10-25 02:47:57 +01:00
ZachAR3 97fbaf7da4 CIRCLE: keep ellipse and spline tangents, and touch an arc within its sweep (#1512)
At CIRCLE's deferred prompts only tangents to circles and arcs are
deferred; ellipses and splines keep the ordinary tangent from the base,
as before. A 3P circle solved for an arc's circle must touch the arc
itself: a circle that touches the arc's circle off the sweep is
refused with "Circle does not exist."
2026-10-25 02:14:02 +01:00
ZachAR3 90a239b410 CIRCLE: tangent snaps for the radius and for 3P points (fixes #1512)
At CIRCLE's radius and diameter prompts a TAN pick on a circle or arc
used the tangent point as seen from the center, which gives the wrong
radius, and the 3P points took a tangent as a plain point. These prompts
now take the tangent as deferred and CIRCLE resolves it:

- Radius or diameter: the circle around the center that touches the
  curve, on the side it was picked.
- 3P: the circle through the plain points that touches every curve
  picked with TAN, solved by the Tan, Tan, Tan solver (a plain point is
  a circle of radius zero). Three tangent picks give Tan, Tan, Tan.
  Points with no such circle report "Circle does not exist." and ask
  for the last point again.

A perpendicular from the base is still resolved from it, so PER keeps
giving a circle tangent to a line. Only prompts that ask for deferred
snaps change: LINE's have no base.
2026-10-25 00:22:55 +02:00
37 changed files with 2184 additions and 157 deletions
+4
View File
@@ -85,6 +85,9 @@ pub struct Foreign {
/// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a
/// later save must not take it for this one (#2471).
pub version: Option<String>,
/// The file's registered applications (APPID names as read, in file order). Saving writes
/// them all back, whether or not any xdata still names them.
pub appids: Vec<String>,
}
impl Foreign {
@@ -103,6 +106,7 @@ impl Foreign {
&& self.targets.is_empty()
&& self.class_order.is_empty()
&& self.data_store.is_empty()
&& self.appids.is_empty()
}
/// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity
+14
View File
@@ -821,6 +821,18 @@ pub struct PageSetup {
/// save keeps where the sheet sits; `None` for a page CADCraft made, written as 0,0 (#2109).
#[serde(skip_serializing_if = "Option::is_none")]
pub image_origin: Option<Vec2>,
/// The plot layout flags (DXF group 70 of AcDbPlotSettings) as the file had them. Saving keeps
/// the bits CADCraft doesn't model (plot paper space last, plot with plot styles, standard
/// scale and the rest) as read instead of forcing its defaults (#3227); `None` for page setups
/// made in CADCraft.
#[serde(skip)]
pub file_plot_flags: Option<i64>,
/// The standard scale the file chose (DXF group 75, such as 25 for 1:50) and the plot scale it
/// was read with. While the scale is unchanged, saving keeps that choice and the standard scale
/// flag instead of writing the scale as a custom one; `None` for a custom scale, scaled to
/// fit, or a page setup made in CADCraft.
#[serde(skip)]
pub file_standard_scale: Option<(i64, f64)>,
}
impl Default for PageSetup {
@@ -844,6 +856,8 @@ impl Default for PageSetup {
paper_mm: None,
file_paper: None,
image_origin: None,
file_plot_flags: None,
file_standard_scale: None,
}
}
}
+8
View File
@@ -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).
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 mut starts: Vec<[f64; 3]> = Vec::new();
let cen = (p1 + p2 + p3) / 3.0;
@@ -379,6 +384,9 @@ pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
continue;
}
let c = Circle::new(Vec2::new(x[0], x[1]), x[2]);
if !ok(&c) {
continue;
}
let sc = score(&c, &objs);
if best.is_none_or(|(b, _)| sc < b - 1e-12) {
best = Some((sc, c));
+74 -5
View File
@@ -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,
point_param, size_param,
};
use crate::snap;
pub(super) fn run_circle(s: &mut Session, p: &Value) -> Result<Value> {
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 {
mode: u8, // 0 center-radius, 1 = 3P, 2 = 2P, 3 = TTR
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,
/// The `Ttr` option hands over to the tangent-circle machine.
delegate: Option<Box<dyn Interactive>>,
@@ -69,18 +72,22 @@ impl Interactive for CircleM {
match (self.mode, n) {
(0, 0) => Prompt::new("Specify center point for circle", Accept::POINT).kw(&["3P", "2P", "Ttr (tan tan radius)"]),
(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, _) => {
let p =
Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER).kw(&["Diameter"]).base_opt(self.pts.first().copied()).distance();
let p = Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER)
.kw(&["Diameter"])
.base_opt(self.pts.first().copied())
.distance()
.deferred();
if last_r > 0.0 { p.default(format!("{last_r:.4}")) } else { p }
}
(1, k) => Prompt::new(
["Specify first point on circle", "Specify second point on circle", "Specify third point on circle"].get(k).copied().unwrap_or(""),
Accept::POINT,
)
.base_opt(self.pts.last().copied()),
.base_opt(self.pts.last().copied())
.deferred(),
(2, k) => Prompt::new(
if k == 0 { "Specify first end point of circle's diameter" } else { "Specify second end point of circle's diameter" },
Accept::POINT,
@@ -120,7 +127,14 @@ impl Interactive for CircleM {
let r = if self.diameter { c.dist(*e) / 2.0 } else { c.dist(*e) };
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])),
_ => None,
};
@@ -130,6 +144,29 @@ impl Interactive for CircleM {
}
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 => {
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 };
@@ -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<()> {
s.add_entity(circle(c.center, c.radius))?;
s.doc_mut()?.header.set_f64("CIRCLERAD", c.radius);
+4
View File
@@ -1,4 +1,5 @@
//! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects.
//! HATCHGENERATEBOUNDARY: polylines around existing hatches.
mod patfile;
pub(super) use edit::{set_pattern, takes_pattern};
@@ -36,6 +37,9 @@ pub fn specs() -> Vec<CommandSpec> {
// Typed with nothing selected it asks for objects, as in AutoCAD, rather than converting none.
.interactive(|_| Ok(Box::new(SelectRun::new("region", "REGION")))),
CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], addPoints?: [[x,y]], addBoundary?: [hex], removeLoops?: [zero-based index] (geometry edits require one hatch), style?, origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))),
CommandSpec::new("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary)
.params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles")
.interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))),
CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick)
.params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing")
.enabled(has_doc)
+53
View File
@@ -29,6 +29,59 @@ fn hatches(s: &Session, p: &Value) -> Result<Vec<Handle>> {
Ok(out)
}
/// Most polylines one HATCHGENERATEBOUNDARY call creates.
const MAX_GENERATED: usize = 10_000;
/// HATCHGENERATEBOUNDARY: a closed polyline around every boundary loop (outer and islands) of
/// the selected hatches, at each hatch's height. The hatches are not changed: an associative
/// hatch stays linked to its own boundary objects and is not linked to the new polylines.
pub(super) fn run_hatchgenerateboundary(s: &mut Session, p: &Value) -> Result<Value> {
let selected = targets(s, p)?;
// The polylines go to the current space, so every hatch must be there too.
let space = s.space();
let mut loops = Vec::new();
let mut found = false;
// A hatch named twice gets its boundary once.
let mut seen = std::collections::HashSet::new();
{
let d = s.doc()?;
for h in selected {
let Some(e) = d.entity(h) else { continue };
let EntityKind::Hatch(x) = &e.kind else { continue };
if !seen.insert(h) {
continue;
}
found = true;
if d.space_of(h).as_ref() != Some(&space) {
return Err(bad("hatchgenerateboundary", format!("hatch {} is not in the current space; switch to its layout first", h.hex())));
}
// Every selected hatch counts: none is left out of a call that succeeds. Compared
// against the room left, so a hostile loop count can't overflow the sum.
if x.loops.len() > MAX_GENERATED.saturating_sub(loops.len()) {
return Err(bad("hatchgenerateboundary", format!("more than {MAX_GENERATED} boundary polylines in one call; select fewer hatches")));
}
// The elevation runs along the hatch's normal: one facing down Z (mirrored) lies at its
// negative, where the polyline, facing up, goes.
let z = if e.common.extrusion.z < 0.0 { -x.elevation } else { x.elevation };
loops.extend(x.loops.iter().map(|l| (l.vertices.clone(), z)));
}
}
if !found {
return Err(bad("hatchgenerateboundary", "select one or more hatches"));
}
// Everything is checked before anything is added, so a refused call leaves nothing behind.
let mut created = Vec::new();
for (vs, elevation) in loops {
let mut kind = lwpoly(vs, true);
if let EntityKind::LwPolyline(pl) = &mut kind {
pl.elevation = elevation;
}
created.push(s.add_entity(kind)?.hex());
}
let n = created.len();
Ok(json!({ "handles": created, "message": format!("{n} boundary polyline(s) created.") }))
}
fn outline(l: &HatchLoop) -> Vec<Vec2> {
Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(1e-3)
}
+58
View File
@@ -466,3 +466,61 @@ fn plot_path_extension_picks_the_format_like_export() {
assert!(!dir.join("w.png").exists(), "nothing written when `output` and the path disagree");
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);
}
@@ -235,6 +235,7 @@ pub const NO_FILES: &[&str] = &[
"boundary",
"region",
"hatchedit",
"hatchgenerateboundary",
"hatchpick",
"overkill",
"block",
+27 -11
View File
@@ -127,18 +127,31 @@ pub fn snap_name(m: u32) -> &'static str {
}
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
/// first, then the closest snap of each other mode in `osmode`, nearest first, without repeats.
/// first, then every other snap of the modes in `osmode` under the aperture (each endpoint of
/// 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> {
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();
}
let osnap = |m: u32| crate::snap::osnap(d, space, cursor, aperture, m, base, deferred);
let extra = osmode & mode::HATCH;
let mut per_mode: Vec<SnapHit> = mode::ALL.iter().filter(|(b, _)| osmode & b != 0).filter_map(|(b, _)| osnap(*b | extra)).collect();
per_mode.sort_by(|a, b| a.point.dist(cursor).total_cmp(&b.point.dist(cursor)));
let mut out: Vec<SnapHit> = osnap(osmode).into_iter().collect();
for h in per_mode {
if !out.iter().any(|o| o.mode == h.mode && o.point.near(h.point, aperture * 1e-6)) {
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);
}
}
@@ -352,12 +365,15 @@ impl Session {
Frame::Snap { mode } => {
// Snap the point with this mode alone, within the aperture.
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 hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 };
let base = prompt.as_ref().and_then(|q| q.base);
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 {
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
Some(h) => p = h.point,
+3 -2
View File
@@ -75,8 +75,9 @@ pub struct Prompt {
/// Rubber-band origin (for direct distance entry, ortho and polar).
pub base: Option<Vec2>,
/// 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
/// pick arrives as the plain point it was picked at.
/// prompt (a point with no base yet, e.g. the first point of a line; with a base, only
/// tangents, e.g. a circle's radius). Elsewhere a deferred pick arrives as the plain point it
/// was picked at.
pub deferred: bool,
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
/// cell): ortho does not bend the opposite corner, so the rectangle keeps its area.
+520 -97
View File
@@ -65,6 +65,21 @@ pub struct SnapHit {
}
impl SnapHit {
fn plain(mode: u32, point: Vec2) -> SnapHit {
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: 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 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
&& 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, aperture * 1e-6)
}
/// The command input a pick at this snap gives: a deferred snap or a plain point.
pub fn input(&self) -> crate::Input {
match self.deferred {
@@ -110,7 +125,7 @@ impl SnapCurve {
}
/// 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).
fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
pub(crate) fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
match self {
SnapCurve::Circle { center, radius } | SnapCurve::Arc { center, radius, .. } => {
let u = (p - *center).normalized();
@@ -202,15 +217,34 @@ fn prim_segments(p: &Prim) -> Vec<Segment> {
/// 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`),
/// 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> {
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 {
return None;
}
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
}
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn osnap_with(
d: &Drawing,
@@ -222,7 +256,7 @@ pub(crate) fn osnap_with(
base: Option<Vec2>,
deferred: bool,
) -> 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.
@@ -236,17 +270,18 @@ pub(crate) fn osnap_with_neighborhood(
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
return (None, None);
}
let (mut best, 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((hit, prims)) => (hit, Some(prims)),
None => (None, None),
};
let views = viewport::near(d, space, cursor, aperture);
if views.is_empty() {
return (best, near_prims);
return (best.map(|(h, _)| h), near_prims);
}
let model = Space::Model;
let model_ix = crate::spatial::index(d, &model);
@@ -269,14 +304,35 @@ pub(crate) fn osnap_with_neighborhood(
&view.viewport.frozen_layers,
Some(view.model_clip),
)
.and_then(|h| view.hit(h));
if let Some(hit) = hit
&& best.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
// The rank was found in model units: paper units are model units times the scale.
.and_then(|(h, r)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r })));
if let Some((hit, rank)) = hit
&& best.as_ref().is_none_or(|(_, b)| rank.beats(b))
{
best = Some(hit);
best = Some((hit, rank));
}
}
(best, near_prims)
(best.map(|(h, _)| h), near_prims)
}
/// How a hit ranks against the hits of another space (paper space, another viewport) and, for
/// Tab, against the other candidates: first the order [`finish`] tries them in (snap points, then
/// a perpendicular or tangent on the object under the cursor or a center found from its curve,
/// then deferred snaps, then Nearest), then its score within that tier, in the units of the cursor.
#[derive(Clone, Copy, Debug)]
struct Rank {
tier: u8,
score: f64,
}
impl Rank {
fn cmp(&self, other: &Rank) -> std::cmp::Ordering {
self.tier.cmp(&other.tier).then(self.score.total_cmp(&other.score))
}
fn beats(&self, other: &Rank) -> bool {
self.cmp(other).is_lt()
}
}
#[allow(clippy::too_many_arguments)]
@@ -291,7 +347,7 @@ fn osnap_in(
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<SnapHit> {
) -> Option<(SnapHit, Rank)> {
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).and_then(|(hit, _)| hit)
}
@@ -307,7 +363,92 @@ fn osnap_in_with_prims(
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(Option<SnapHit>, Vec<Prim>)> {
) -> Option<(Option<(SnapHit, Rank)>, Vec<Prim>)> {
let (cands, near_prims) = collect_in(d, space, ix, cursor, aperture, osmode, frozen)?;
let hit = finish(cands, &near_prims, 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)) = collect_in(d, space, &ix, cursor, aperture, osmode, frozen) {
out = finish_all(cands, &prims, 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)) = 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, 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.
#[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>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
// Intersections between nearby primitives; Apparent Intersection also where their extensions
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
@@ -345,8 +486,7 @@ fn osnap_in_with_prims(
}
}
}
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
Some((hit, near_prims))
Some((cands, near_prims))
}
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
@@ -390,18 +530,7 @@ pub(crate) fn extendable(p: &Prim) -> bool {
/// 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, &[])
}
fn gather_in(
pub(crate) fn gather_in(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
@@ -458,7 +587,19 @@ fn gather_in(
Some((cands, near_prims))
}
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps.
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps, with
/// 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)]
fn finish(
mut cands: Vec<(u32, Vec2)>,
@@ -469,87 +610,248 @@ fn finish(
base: Option<Vec2>,
deferred: bool,
clip: Option<Bounds2>,
) -> Option<SnapHit> {
// Perpendicular / tangent from the base point.
if let Some(bp) = base {
for p in near_prims {
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)));
}
}
}
) -> Option<(SnapHit, Rank)> {
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
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 best = cands.iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).min_by(|a, b| {
// Prefer more specific modes when nearly equidistant.
let da = snap_score(a.0, a.1, cursor, aperture);
let db = snap_score(b.0, b.1, cursor, aperture);
da.total_cmp(&db)
});
if let Some((m, p)) = best {
return Some(SnapHit { point: *p, mode: *m, name: name_of(*m), viewport: None, deferred: None });
// Prefer more specific modes when nearly equidistant.
let best = cands
.iter()
.filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture)
.map(|(m, p)| (snap_score(*m, *p, cursor, aperture), *m, *p))
.min_by(|a, b| a.0.total_cmp(&b.0));
if let Some((score, m, p)) = best {
return Some((SnapHit::plain(m, p), Rank { tier: 0, score }));
}
if base.is_none()
&& deferred
&& let Some(h) = deferred_hit(near_prims, cursor, aperture, osmode, clip)
{
return Some(h);
// 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, 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)| (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, cursor, aperture, deferrable, clip) {
let score = h.point.dist(cursor);
return Some((h, Rank { tier: 2, score }));
}
if osmode & mode::NEA != 0 {
// The closest point of all nearby objects, whatever their drawing order.
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 p in near_prims {
for s in prim_segments(p) {
consider(fix_circle(&s).closest(cursor));
}
if let Prim::Circle(c) = p {
consider(c.closest(cursor));
}
}
if let Some((_, p)) = nb {
return Some(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
let nb = near_prims.iter().filter_map(|p| nearest_point(p, cursor, aperture, &visible)).min_by(|a, b| a.0.total_cmp(&b.0));
if let Some((score, p)) = nb {
return Some((SnapHit::plain(mode::NEA, p), Rank { tier: 3, score }));
}
}
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],
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);
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()
.filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture)
.map(|(m, p)| (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, 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)| (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, 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().filter_map(|p| nearest_point(p, cursor, aperture, &visible));
out.extend(near.map(|(score, p)| (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.
Prim::Seg(Segment::Arc { arc, .. }) => {
SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end }.perpendiculars(bp, bp)
}
// 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)> {
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().filter_map(|p| match p {
Prim::Circle(c) => Some((c.center, c.closest(cursor))),
Prim::Seg(s @ Segment::Arc { arc, .. }) => Some((arc.center, fix_circle(s).closest(cursor))),
Prim::Ellipse(e) => Some((e.center, e.closest(cursor))),
_ => None,
});
for (center, on) in curves.take(2000) {
let d = on.dist(cursor);
if center.is_finite() && d.is_finite() && d <= aperture {
out.push((d, center));
}
}
out
}
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 }
}
/// 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],
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;
}
out.push((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 {
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).
const MAX_BLOCK_LEAVES: usize = 20_000;
@@ -848,6 +1150,47 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
}
}
/// Every deferred tangent and perpendicular within `aperture` of `cursor`, for Tab: one per curve
/// and mode, in drawing order (the caller ranks them), so Tab can go from the tangent to the
/// 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], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
let mut hits = Vec::new();
if osmode & (mode::TAN | mode::PER) == 0 {
return hits;
}
for p in prims {
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,
};
// Where the curve was picked: a circle's, an arc's or a segment's own span, an xline/ray
// anywhere.
let at = match curve {
SnapCurve::Circle { center, radius } => Circle::new(center, radius).closest(cursor),
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor),
SnapCurve::Line { a, b } => {
let l = cadcraft_geom::Line::new(a, b);
if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) }
}
};
if !(at.is_finite() && clip.is_none_or(|c| c.contains(at)) && at.dist(cursor) <= aperture) {
continue;
}
let modes: &[(u32, &'static str)] = match curve {
SnapCurve::Circle { .. } | SnapCurve::Arc { .. } => &[(mode::TAN, "Deferred Tangent"), (mode::PER, "Deferred Perpendicular")],
SnapCurve::Line { .. } => &[(mode::PER, "Deferred Perpendicular")],
};
for &(m, name) in modes.iter().filter(|(m, _)| osmode & m != 0) {
hits.push(SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) });
}
}
hits
}
/// The nearest deferred tangent/perpendicular within `aperture` of `cursor`.
fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Option<SnapHit> {
let mut best: Option<(f64, SnapHit)> = None;
@@ -1121,6 +1464,17 @@ mod tests {
assert_eq!(h.name, "Intersection");
}
/// Tab cycling sees every deferred snap within the aperture: on a circle with no base point,
/// its quadrant, then the deferred tangent and the deferred perpendicular at the same spot.
#[test]
fn osnap_all_ranks_every_candidate() {
let d = drawing();
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();
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, mode::QUA | mode::TAN | mode::PER, None, true).is_empty());
}
#[test]
fn center_quadrant_tangent() {
let d = drawing();
@@ -1137,6 +1491,70 @@ mod tests {
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]
fn ortho_and_polar() {
assert_eq!(ortho(Vec2::ZERO, Vec2::new(5.0, 1.0)), Vec2::new(5.0, 0.0));
@@ -1179,9 +1597,14 @@ mod tests {
let df = h.deferred.unwrap();
assert_eq!(df.curve, SnapCurve::Circle { center: Vec2::new(20.0, 0.0), radius: 2.0 });
assert_eq!(h.input(), crate::Input::Deferred(df));
// With a base it is an ordinary tangent.
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();
// 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)), false).unwrap();
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.
let q = osnap(&d, &Space::Model, at, 0.5, mode::TAN | mode::QUA, None, true).unwrap();
assert_eq!(q.mode, mode::QUA);
+47 -8
View File
@@ -482,13 +482,38 @@ impl Tracker {
cfg: &TrackConfig,
base: Option<Vec2>,
) -> 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();
t
}
#[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) {
return None;
}
@@ -538,7 +563,7 @@ impl Tracker {
// 2. A path crossing an object.
if cfg.running(mode::INT | mode::APP) {
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).map(|(_, p)| p).unwrap_or_default();
for prim in prims.iter().take(200) {
let extend = cfg.running(mode::APP) && super::extendable(prim);
for seg in super::prim_segments(prim) {
@@ -588,12 +613,26 @@ pub fn candidate(
aperture: f64,
cfg: &TrackConfig,
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> {
if !can_acquire(cursor, aperture, cfg) {
return None;
}
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).map(|(_, p)| p).unwrap_or_default();
candidate_from_prims(cursor, hit, aperture, cfg, base, &prims)
}
@@ -789,7 +828,7 @@ impl crate::Session {
s.orthomode ^= q.shift;
let angbase = self.angle_settings().angbase;
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() {
return CursorSnap { point: raw, ..Default::default() };
}
@@ -798,10 +837,10 @@ impl crate::Session {
let cfg = TrackConfig::relative_to(&s, angbase, last);
let osmode = s.osmode | if s.osnaphatch { mode::HATCH } else { 0 };
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()) {
(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);
if let Some(h) = hit {
@@ -816,7 +855,7 @@ impl crate::Session {
let (origin, angle) = super::grid_frame_in(&doc, &space);
p = super::grid_snap(p, doc.header.snap_unit(), origin, angle);
}
if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) {
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.
let step = if s.polardist > 0.0 { s.polardist } else { s.snapunit.x };
if s.snapmode
@@ -0,0 +1,205 @@
//! HATCHGENERATEBOUNDARY (#2801): closed polylines around existing hatches, which stay as they are.
use cadcraft_engine::doc::{EntityKind, Handle, Hatch, LwPolyline};
use cadcraft_engine::{Input, Session};
use serde_json::{Value, json};
fn hatch(s: &Session, h: &str) -> Hatch {
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
EntityKind::Hatch(x) => x.clone(),
k => panic!("not a hatch: {k:?}"),
}
}
fn poly(s: &Session, h: &str) -> LwPolyline {
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
EntityKind::LwPolyline(p) => p.clone(),
k => panic!("not a polyline: {k:?}"),
}
}
fn handle(v: &Value) -> String {
v["handle"].as_str().unwrap().to_string()
}
fn handles(v: &Value) -> Vec<String> {
v["handles"].as_array().unwrap().iter().map(|h| h.as_str().unwrap().to_string()).collect()
}
fn rect(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> String {
handle(&s.execute("rectang", &json!({ "p1": a, "p2": b })).unwrap())
}
fn count(s: &Session) -> usize {
s.doc().unwrap().model.iter().count()
}
#[test]
fn generates_a_closed_polyline_around_a_hatch_without_its_outline() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()] })).unwrap());
s.execute("erase", &json!({ "handles": [r] })).unwrap();
let before = hatch(&s, &h);
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
let new = handles(&v);
assert_eq!(new.len(), 1);
let p = poly(&s, &new[0]);
assert!(p.closed);
assert_eq!(p.vertices, before.loops[0].vertices);
assert_eq!(hatch(&s, &h), before, "the hatch is not changed");
s.execute("undo", &json!({})).unwrap();
assert_eq!(count(&s), 1, "one undo step removes what was generated");
}
#[test]
fn islands_get_their_own_polylines() {
let mut s = Session::new();
rect(&mut s, [0.0, 0.0], [20.0, 20.0]);
rect(&mut s, [5.0, 5.0], [10.0, 10.0]);
let h = handle(&s.execute("hatch", &json!({ "points": [[2, 2]] })).unwrap());
assert_eq!(hatch(&s, &h).loops.len(), 2);
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
assert_eq!(handles(&v).len(), 2);
}
#[test]
fn every_selected_hatch_gets_its_boundary() {
let mut s = Session::new();
let a = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let b = rect(&mut s, [10.0, 0.0], [14.0, 2.0]);
let ha = handle(&s.execute("hatch", &json!({ "handles": [a] })).unwrap());
let hb = handle(&s.execute("hatch", &json!({ "handles": [b] })).unwrap());
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [ha, hb] })).unwrap();
assert_eq!(handles(&v).len(), 2);
}
#[test]
fn a_hatch_named_twice_gets_one_boundary() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone(), h] })).unwrap();
assert_eq!(handles(&v).len(), 1);
}
#[test]
fn an_associative_hatch_stays_linked_to_its_own_boundary() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()], "associative": true })).unwrap());
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
let p = handles(&v)[0].clone();
// Moving the generated polyline leaves the hatch where it is.
s.execute("move", &json!({ "handles": [p], "delta": [0, 10] })).unwrap();
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.y, 0.0);
// Moving the original rectangle still moves the hatch.
s.execute("move", &json!({ "handles": [r], "delta": [10, 0] })).unwrap();
assert!(hatch(&s, &h).associative);
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.x, 10.0);
}
#[test]
fn boundaries_keep_the_hatch_elevation() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.doc_mut()
.unwrap()
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
if let EntityKind::Hatch(x) = &mut e.kind {
x.elevation = 300.0;
}
})
.unwrap();
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
assert_eq!(poly(&s, &handles(&v)[0]).elevation, 300.0);
}
/// A mirrored hatch (normal 0,0,-1, as exploding a mirrored block makes) at elevation 300 lies at
/// world Z -300; its boundary, facing up, goes there too, not to +300.
#[test]
fn a_mirrored_hatchs_boundary_keeps_its_world_height() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.doc_mut()
.unwrap()
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
e.common.extrusion = cadcraft_engine::geom::Vec3::new(0.0, 0.0, -1.0);
if let EntityKind::Hatch(x) = &mut e.kind {
x.elevation = 300.0;
}
})
.unwrap();
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
let new = Handle::parse_hex(&handles(&v)[0]).unwrap();
let e = s.doc().unwrap().entity(new).unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline") };
assert_eq!(e.common.extrusion.z.signum() * p.elevation, -300.0);
}
#[test]
fn refuses_a_hatch_in_another_space_and_adds_nothing() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
let before = s.doc().unwrap().entity_count();
let e = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap_err();
assert!(e.to_string().contains("not in the current space"), "{e}");
assert_eq!(s.doc().unwrap().entity_count(), before);
}
#[test]
fn refuses_more_boundaries_than_the_limit_and_adds_nothing() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
// One hatch with more loops than one call may turn into polylines.
s.doc_mut()
.unwrap()
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
if let EntityKind::Hatch(x) = &mut e.kind {
let l = x.loops[0].clone();
x.loops = vec![l; 10_001];
}
})
.unwrap();
let before = count(&s);
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).is_err());
assert_eq!(count(&s), before);
}
#[test]
fn needs_a_hatch() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [r] })).is_err());
assert_eq!(count(&s), 1, "nothing is added");
}
#[test]
fn runs_at_once_on_selected_hatches() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.set_selection(vec![Handle::parse_hex(&h).unwrap()]);
s.start("hatchgenerateboundary").unwrap();
assert!(s.current_prompt().is_none(), "a pickfirst selection needs no prompt");
assert_eq!(count(&s), 3);
}
#[test]
fn asks_for_hatches_without_a_selection() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.set_selection(Vec::new());
s.start("hatchgenerateboundary").unwrap();
assert!(s.current_prompt().is_some());
s.input(Input::Pick(vec![Handle::parse_hex(&h).unwrap()])).unwrap();
s.input(Input::Enter).unwrap();
assert!(s.current_prompt().is_none());
assert_eq!(count(&s), 3);
}
+4
View File
@@ -68,6 +68,7 @@ mod group_selection;
mod groups;
mod hatch_assoc;
mod hatch_dialog_helpers;
mod hatch_generate_boundary;
mod hatch_numeric_validation;
mod hatch_options;
mod helix;
@@ -114,6 +115,7 @@ mod offset_ellipse_side;
mod offset_move;
mod oops_command;
mod options_profile;
mod osnap_opened_drawings;
mod overkill;
mod parallel_display_list;
mod pedit_multiple;
@@ -156,10 +158,12 @@ mod setvar_coverage;
mod shapes;
mod snap_annotations;
mod snap_blocks;
mod snap_center_on_curve;
mod snap_curves;
mod snap_intersections_aperture;
mod snap_nearest;
mod snap_overrides;
mod snap_tab_cycling;
mod snap_tracking;
mod snaps_more;
mod solid_command;
@@ -1,8 +1,9 @@
//! 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::snap::{SnapCurve, SnapHit, mode, osnap};
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
use cadcraft_engine::{Input, Session};
use serde_json::json;
@@ -278,6 +279,46 @@ 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());
}
/// Across spaces a click takes the viewport's Endpoint over a paper-space Nearest that scores
/// 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]
fn a_viewport_endpoint_beats_a_closer_paper_space_nearest() {
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).
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 hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
assert!(hit.mode == mode::END && hit.viewport.is_some() && hit.point.near(Vec2::new(95.0, 50.0), 1e-9), "{hit:?}");
let all = snap_candidates(&d, &paper, cursor, 0.5, modes, None, false);
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
assert!(
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 paper-space Nearest: {all:?}"
);
}
/// Overlapping viewports can show different model points at one paper point; Tab offers each,
/// since DIST measures in the model units of the viewport picked.
#[test]
fn overlapping_viewports_each_offer_their_model_point() {
let (mut d, paper) = drawing();
// This viewport shows the model endpoint (20, 0) at paper (100, 50), a second one over it (0, 0).
edit_viewport(&mut d, &paper, |vp| vp.view_center = Vec2::new(20.0, 0.0));
let mut vp = match &d.entity(viewport(&d, &paper)).unwrap().kind {
EntityKind::Viewport(vp) => vp.clone(),
_ => panic!("viewport fixture"),
};
vp.view_center = Vec2::new(0.0, 0.0);
vp.id = 3;
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
let all = osnap_all(&d, &paper, Vec2::new(100.05, 50.04), 0.5, mode::END, None, false);
let mut models: Vec<Vec2> =
all.iter().filter(|h| h.point.near(Vec2::new(100.0, 50.0), 1e-9)).filter_map(|h| h.viewport).map(|v| v.point).collect();
models.sort_by(|a, b| a.x.total_cmp(&b.x));
assert_eq!(models, [Vec2::new(0.0, 0.0), Vec2::new(20.0, 0.0)], "{all:?}");
}
#[test]
fn viewport_frozen_layers_do_not_hide_paper_space_geometry() {
let (mut d, paper) = drawing();
@@ -389,3 +430,22 @@ 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());
}
}
/// 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:?}");
}
@@ -0,0 +1,114 @@
//! 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 text = String::from_utf8(cadcraft_io::write(&drawing(), "snaps.dxf").unwrap()).unwrap();
let text = with_osmode(&text, 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();
s.open_drawing(cadcraft_io::read(with_osmode(&text, DEFAULT).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");
}
@@ -0,0 +1,202 @@
//! 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,
};
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());
}
+3
View File
@@ -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");
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:?}");
// 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.
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");
+111
View File
@@ -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()
}
/// 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 {
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));
}
/// #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]
fn from_nests_with_a_snap_override() {
let mut s = drawing();
@@ -116,3 +144,86 @@ fn a_command_keyword_wins_over_a_snap_word() {
s.cmdline("arc _cen").unwrap();
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);
}
@@ -0,0 +1,89 @@
//! 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());
}
+12 -4
View File
@@ -457,6 +457,10 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
if !f.is_empty() {
f.version = file_version(secs);
}
// Added after the version: registered applications alone are no kept objects whose groups
// the DWG writer must read as the file's version, and nearly every file has some (ACAD).
let appids = tables.iter().filter(|(k, _, _)| k == "APPID").filter_map(|(_, _, t)| val(t, 2)).map(|n| n.trim().to_string());
f.appids = appids.take(MAX_OBJECTS).collect();
// The file's handles of the objects CADCraft writes itself (AutoLISP's `handent`).
f.handles = ids.iter().filter(|(h, _)| !ents.contains_key(*h)).filter_map(|(h, k)| Some((handle(h)?, k.clone()))).take(MAX_OBJECTS).collect();
if !f.is_empty() || !f.handles.is_empty() {
@@ -1267,7 +1271,7 @@ pub(crate) fn finish(
join_entries(&map, b, kept, &mut out);
}
}
add_appids(&mut out);
add_appids(&mut out, &f.appids);
let top = max_handle(&out).saturating_add(1);
if let Some(t) = seed_index(&out).and_then(|i| out.get_mut(i))
&& Handle::parse_hex(&t.str()).is_none_or(|h| h.0 < top)
@@ -1593,9 +1597,13 @@ fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>)
}
}
/// APPID records for every application with xdata in the file, added to the APPID table.
fn add_appids(out: &mut Vec<Tag>) {
let used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
/// APPID records for every application with xdata in the file and every one the file read had
/// (`kept`), added to the APPID table.
fn add_appids(out: &mut Vec<Tag>, kept: &[String]) {
let mut used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
for name in kept.iter().filter(|n| !n.is_empty()) {
used.entry(up(name)).or_insert_with(|| name.clone());
}
let recs = written_records(out);
let Some(table) = recs.iter().position(|r| {
r.sec == "TABLES" && r.kind == "TABLE" && val(out.get(r.start + 1..r.end).unwrap_or(&[]), 2).is_some_and(|n| up(&n) == "APPID")
+28 -6
View File
@@ -88,6 +88,7 @@ fn lwpolyline(tags: &[Tag], c: &mut Common, t: &T) -> Option<EntityKind> {
// In a tilted plane: drawn as seen from above, at the vertices' mean height, its
// vertices now plan coordinates.
(verts, elevation) = plan_of_tilted(c.extrusion, elevation, &verts, flags & 1 != 0);
thickness_along_z(c);
c.extrusion = Vec3::Z;
} else if c.extrusion.z < 0.0 {
for v in &mut verts {
@@ -577,7 +578,7 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
break;
}
}
let c = common(t);
let mut c = common(t);
let mut extra: Vec<EntityKind> = Vec::new();
let k = if flags & 64 != 0 {
// Face records that name a missing vertex (or fewer than three) are dropped: they draw
@@ -599,13 +600,26 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
} else if flags & 8 != 0 {
EntityKind::Polyline3d(Polyline3d { points: pts.iter().map(|p| p.0).collect(), closed: flags & 1 != 0 })
} else {
// A 2D polyline's vertices are in its OCS: mirrored like LWPOLYLINE.
let m = if c.extrusion.z < 0.0 { -1.0 } else { 1.0 };
// A 2D polyline's vertices are in its OCS, at the elevation of the POLYLINE's own point:
// in a tilted plane drawn as seen from above like LWPOLYLINE, else mirrored like it.
let closed = flags & 1 != 0;
let mut vertices: Vec<PolyVertex> = pts.iter().map(|p| PolyVertex { p: p.0.xy(), bulge: p.1, start_width: p.2, end_width: p.3 }).collect();
let mut elevation = t.p(10).z;
if tilted(c.extrusion, run_points(&vertices, elevation, closed)) {
(vertices, elevation) = plan_of_tilted(c.extrusion, elevation, &vertices, closed);
thickness_along_z(&mut c);
c.extrusion = Vec3::Z;
} else if c.extrusion.z < 0.0 {
for v in &mut vertices {
v.p.x = -v.p.x;
v.bulge = -v.bulge;
}
}
EntityKind::LwPolyline(LwPolyline {
vertices: pts.iter().map(|p| PolyVertex { p: Vec2::new(m * p.0.x, p.0.y), bulge: m * p.1, start_width: p.2, end_width: p.3 }).collect(),
closed: flags & 1 != 0,
vertices,
closed,
const_width: t.fd(40, 0.0).min(t.fd(41, 0.0)).max(0.0),
elevation: t.p(10).z,
elevation,
plinegen: flags & 128 != 0,
})
};
@@ -714,3 +728,11 @@ fn helix(tags: &[Tag]) -> Helix {
}
.sanitized()
}
/// A polyline drawn as seen from above gets the normal +Z: its thickness keeps the side of Z it
/// extruded toward, which the normal it is losing said.
fn thickness_along_z(c: &mut Common) {
if c.extrusion.z < 0.0 {
c.thickness = -c.thickness;
}
}
+9
View File
@@ -421,6 +421,8 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
// Plot layout flags: 2 display plot styles, 4 centred, 16 standard scale (75 = 0: scaled
// to fit), 128 lineweights.
if let Some(flags) = t.i(70) {
// Kept to be written back (a 16-bit group: only those bits).
p.file_plot_flags = Some(flags & 0xFFFF);
p.show_plot_styles = flags & 2 != 0;
p.center = flags & 4 != 0;
p.lineweights = flags & 128 != 0;
@@ -432,6 +434,13 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
if let Some(s) = pos(ratio).or_else(|| pos(t.f(147))) {
p.scale = s;
}
// A standard scale (flag 16, group 75 above 0: 0 is scaled to fit, the DXF Reference lists
// 1 to 32), kept with the scale it stands for so a save can tell it was not changed.
if t.i(70).is_some_and(|f| f & 16 != 0)
&& let Some(code) = t.i(75).filter(|c| (1..=32).contains(c))
{
p.file_standard_scale = Some((code, p.scale));
}
p.plot_area = match t.i(74) {
Some(0) => "display",
Some(1) => "extents",
+22 -7
View File
@@ -108,7 +108,10 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
EntityKind::Line(l) => {
w.s(0, "LINE");
common(w, e, owner, paper, "AcDbLine");
thickness(w, e);
// Along the normal written with it (210 below), as read.
if e.common.thickness != 0.0 {
w.f(39, e.common.thickness);
}
w.p(10, l.a);
w.p(11, l.b);
extrusion(w, e);
@@ -156,8 +159,13 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
if p.const_width > 0.0 {
w.f(43, p.const_width);
}
if p.elevation != 0.0 {
w.f(38, p.elevation);
// The elevation runs along the polyline's normal, which isn't written: one facing down
// Z is at the elevation's negative. That is exact for a normal of 0,0,-1 only; a tilted
// one pointing partly down is flipped the same way (the reader brings tilted polylines
// into plan with normal Z, so only other sources make one).
let elevation = if e.common.extrusion.z < 0.0 { -p.elevation } else { p.elevation };
if elevation != 0.0 {
w.f(38, elevation);
}
thickness(w, e);
for v in &p.vertices {
@@ -609,7 +617,10 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
if let EntityKind::Hatch(h) = &e.kind {
w.s(0, "HATCH");
common(w, e, owner, paper, "AcDbHatch");
w.p(10, Vec3::new(0.0, 0.0, h.elevation));
// Its elevation runs along its normal, written as Z: one facing down is at the negative.
// Exact for a normal of 0,0,-1; the reader brings a tilted hatch into plan with normal Z.
let elevation = if e.common.extrusion.z < 0.0 { -h.elevation } else { h.elevation };
w.p(10, Vec3::new(0.0, 0.0, elevation));
w.p(210, Vec3::Z);
w.s(2, &h.pattern);
w.i(70, i64::from(h.solid));
@@ -829,10 +840,14 @@ fn gradient(w: &mut W, g: &Gradient) {
w.s(1000, g.color2.name());
}
/// Group 39 (thickness) of the entities whose DXF Reference record has one; only when set.
/// Group 39 (thickness) of the entities whose DXF Reference record has one; only when set. They
/// are written with no normal, so they extrude along Z: one whose normal points down Z extrudes
/// the other way, and its thickness changes sign. That is exact for a normal of 0,0,-1; a tilted
/// one pointing partly down only gets the closer of the two directions.
fn thickness(w: &mut W, e: &Entity) {
if e.common.thickness != 0.0 {
w.f(39, e.common.thickness);
let t = if e.common.extrusion.z < 0.0 { -e.common.thickness } else { e.common.thickness };
if t != 0.0 {
w.f(39, t);
}
}
+22 -8
View File
@@ -413,6 +413,23 @@ struct LayoutWriteData<'a> {
limits: Option<(Vec2, Vec2)>,
}
/// The plot layout flags (AcDbPlotSettings group 70) for `page`. The bits CADCraft models come
/// from the page: 2 display plot styles, 4 centred, 128 lineweights, and 16 standard scale where
/// the scale decides it (scaled to fit: set; a custom scale: clear). The rest are kept as the file
/// had them (#3227); a page CADCraft made gets 512 (plot paper space last) and 32 (plot with plot
/// styles), and 16 when its scale is standard.
fn plot_layout_flags(page: &PageSetup, standard: bool) -> i64 {
const MODELED: i64 = 2 | 4 | 128;
const STANDARD_SCALE: i64 = 16;
let kept = match page.file_plot_flags {
Some(f) if page.scale_to_fit => (f & !MODELED) | STANDARD_SCALE,
Some(f) if !standard => f & !MODELED & !STANDARD_SCALE,
Some(f) => f & !MODELED,
None => 512 | 32 | if standard { STANDARD_SCALE } else { 0 },
};
kept | if page.lineweights { 128 } else { 0 } | if page.center { 4 } else { 0 } | if page.show_plot_styles { 2 } else { 0 }
}
fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<'_>) {
let d = context.drawing;
let layout_dict = context.dictionary;
@@ -426,13 +443,10 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
// Plot scale: a standard scale when fitting or 1:1, otherwise custom (142 paper units
// per 143 drawing units).
let scale = if page.scale.is_finite() && page.scale > 0.0 { page.scale } else { 1.0 };
let standard = page.scale_to_fit || scale == 1.0;
let plot_flags = 512
| 32
| if standard { 16 } else { 0 }
| if page.lineweights { 128 } else { 0 }
| if page.center { 4 } else { 0 }
| if page.show_plot_styles { 2 } else { 0 };
// The file's standard scale (such as 1:50) while the scale is still the one read with it.
let file_standard = page.file_standard_scale.filter(|&(_, s)| !page.scale_to_fit && s == scale).map(|(code, _)| code);
let standard = page.scale_to_fit || scale == 1.0 || file_standard.is_some();
let plot_flags = plot_layout_flags(page, standard);
let plot_type = match page.plot_area.as_str() {
"display" => 0,
"extents" => 1,
@@ -474,7 +488,7 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
w.i(73, rotation);
w.i(74, plot_type);
w.s(7, &page.plot_style_table);
w.i(75, if page.scale_to_fit { 0 } else { 16 });
w.i(75, if page.scale_to_fit { 0 } else { file_standard.unwrap_or(16) });
w.f(147, scale);
// The paper image origin the file had (#2109), else 0,0.
let origin = page.image_origin.filter(|o| o.is_finite()).unwrap_or(Vec2::ZERO);
+143
View File
@@ -2683,6 +2683,84 @@ fn mirrored_2d_polyline_extrusion_flips_x_and_bulge() {
assert_eq!(got, vec![(-1.0, 0.0, -1.0), (-3.0, 0.0, 0.0)]);
}
/// Objects whose normal is 0,0,-1, at OCS height 5 and most of them 2 thick, keep their world height
/// and the side they extrude to through a save. They are written with no normal (along Z), so an
/// elevation or a thickness written as read put a polyline or a hatch at Z +5 instead of -5, and
/// extruded a circle, point, solid or text up instead of down (AutoCAD 2024 opening the saved file,
/// measured). A line writes its normal, and keeps its thickness as read. The same objects facing up
/// (no normal, and 0,0,1) keep +5 and +2: only a normal pointing down Z changes the sign.
#[test]
fn mirrored_objects_keep_their_world_height_and_thickness_side() {
let records = |normal: &str| {
format!(
"0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n38\n5\n39\n2\n{normal}10\n0\n20\n0\n42\n0.5\n10\n-10\n20\n0\n\
0\nPOLYLINE\n8\n0\n66\n1\n70\n0\n10\n0\n20\n0\n30\n5\n{normal}0\nVERTEX\n8\n0\n10\n0\n20\n10\n0\nVERTEX\n8\n0\n10\n-10\n20\n10\n0\nSEQEND\n\
0\nCIRCLE\n8\n0\n10\n-10\n20\n5\n30\n5\n40\n5\n39\n2\n{normal}\
0\nARC\n8\n0\n10\n-30\n20\n5\n30\n5\n40\n5\n50\n180\n51\n270\n{normal}\
0\nPOINT\n8\n0\n10\n-40\n20\n0\n30\n5\n39\n2\n{normal}\
0\nSOLID\n8\n0\n10\n50\n20\n0\n30\n5\n11\n60\n21\n0\n31\n5\n12\n50\n22\n5\n32\n5\n13\n60\n23\n5\n33\n5\n39\n2\n{normal}\
0\nHATCH\n8\n0\n10\n0\n20\n0\n30\n5\n{normal}2\nSOLID\n70\n1\n71\n0\n91\n1\n92\n2\n72\n0\n73\n1\n93\n4\n\
10\n70\n20\n0\n10\n80\n20\n0\n10\n80\n20\n5\n10\n70\n20\n5\n97\n0\n75\n0\n76\n1\n98\n0\n\
0\nTEXT\n8\n0\n10\n-90\n20\n0\n30\n5\n40\n2\n1\nA\n39\n2\n{normal}\
0\nLINE\n8\n0\n39\n2\n10\n0\n20\n20\n30\n3\n11\n10\n21\n20\n31\n3\n{normal}"
)
};
let (down, up) = ("210\n0\n220\n0\n230\n-1\n", "210\n0\n220\n0\n230\n1\n");
let text = format!("0\nSECTION\n2\nENTITIES\n{}{}{}0\nENDSEC\n0\nEOF\n", records(down), records(""), records(up));
// Each object's kind, world height and thickness along world Z.
let place = |d: &Drawing| -> Vec<(&'static str, f64, f64)> {
d.model
.iter()
.map(|e| {
let n = e.common.extrusion.z.signum();
let (kind, z) = match &e.kind {
EntityKind::LwPolyline(p) => ("polyline", n * p.elevation),
EntityKind::Circle(c) => ("circle", c.center.z),
EntityKind::Arc(a) => ("arc", a.center.z),
EntityKind::Point(p) => ("point", p.p.z),
EntityKind::Solid(s) => ("solid", s.corners[0].z),
EntityKind::Hatch(h) => ("hatch", n * h.elevation),
EntityKind::Text(t) => ("text", t.insert.z),
EntityKind::Line(l) => ("line", l.a.z),
_ => ("other", f64::NAN),
};
(kind, z, n * e.common.thickness)
})
.collect()
};
let d = read(text.as_bytes(), "m.dxf").unwrap();
let mut want = vec![
("polyline", -5.0, -2.0),
("polyline", -5.0, 0.0),
("circle", -5.0, -2.0),
("arc", -5.0, 0.0),
("point", 5.0, -2.0),
("solid", -5.0, -2.0),
("hatch", -5.0, 0.0),
("text", -5.0, -2.0),
("line", 3.0, -2.0),
];
let facing_up = [
("polyline", 5.0, 2.0),
("polyline", 5.0, 0.0),
("circle", 5.0, 2.0),
("arc", 5.0, 0.0),
("point", 5.0, 2.0),
("solid", 5.0, 2.0),
("hatch", 5.0, 0.0),
("text", 5.0, 2.0),
("line", 3.0, 2.0),
];
want.extend(facing_up);
want.extend(facing_up);
assert_eq!(place(&d), want, "as read");
let out = write(&d, "m.dxf").unwrap();
assert_eq!(place(&read(&out, "m.dxf").unwrap()), want, "after a save");
let pairs = dxf_pairs(std::str::from_utf8(&out).unwrap());
let lines: Vec<_> = dxf_records(&pairs, "LINE").into_iter().map(|l| (group(l, "39"), group(l, "230"))).collect();
assert_eq!(lines, [(Some("2.0"), Some("-1.0")), (Some("2.0"), None), (Some("2.0"), None)]);
}
#[test]
fn mirrored_hatch_extrusion_flips_boundary() {
// HATCH boundaries are OCS: the square (1,0)..(3,2) under extrusion (0,0,-1) lies at (-3,0)..(-1,2).
@@ -2727,6 +2805,20 @@ fn tilted_hatch_turns_its_gradient() {
assert!((g.angle - std::f64::consts::PI).abs() < 1e-9, "gradient angle {}", g.angle);
}
/// A tilted polyline with a thickness, its normal pointing partly down Z, still extrudes toward -Z
/// once it is drawn as seen from above and saved with no normal.
#[test]
fn tilted_thick_polyline_keeps_its_extrusion_side() {
let text = "0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n39\n5\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\
10\n1\n20\n0\n10\n3\n20\n2\n0\nENDSEC\n0\nEOF\n";
let d = read(text.as_bytes(), "p.dxf").unwrap();
let e = d.model.iter().next().unwrap();
assert_eq!((e.common.thickness, e.common.extrusion), (-5.0, Vec3::Z));
let back = roundtrip(&d);
let e = back.model.iter().next().unwrap();
assert_eq!((e.common.thickness, e.common.extrusion), (-5.0, Vec3::Z), "saved with no normal, it still extrudes toward -Z");
}
/// A straight tilted LWPOLYLINE keeps its vertex widths (groups 40/41) on the projected vertices.
#[test]
fn tilted_straight_lwpolyline_keeps_its_widths() {
@@ -2841,6 +2933,57 @@ fn tilted_lwpolyline_is_drawn_as_seen_from_above() {
assert_eq!(p.vertices.iter().map(|v| v.bulge).collect::<Vec<_>>(), vec![1.0, 1.0]);
}
/// A 2D POLYLINE (heavy polyline) in a tilted plane is drawn as seen from above, like a
/// LWPOLYLINE: before, its OCS points were taken for world coordinates. With extrusion
/// (0, 0.5, -√3/2) the OCS axes are x = (-1,0,0) and y = (0, √3/2, 1/2), and the elevation of 2
/// moves the plane by twice the normal, (0, 1, -√3): the square (1,0)..(3,2) lies over
/// (-3,1)..(-1,1+√3), its corners at a mean height of 1/2 - √3.
#[test]
fn tilted_2d_polyline_is_drawn_as_seen_from_above() {
let square = |n: &str| {
format!(
"0\nSECTION\n2\nENTITIES\n0\nPOLYLINE\n8\n0\n66\n1\n10\n0\n20\n0\n30\n2\n70\n1\n{n}\
0\nVERTEX\n8\n0\n10\n1\n20\n0\n0\nVERTEX\n8\n0\n10\n3\n20\n0\n0\nVERTEX\n8\n0\n10\n3\n20\n2\n\
0\nVERTEX\n8\n0\n10\n1\n20\n2\n0\nSEQEND\n0\nENDSEC\n0\nEOF\n"
)
};
let d = read(square("210\n0\n220\n0.5\n230\n-0.8660254037844386\n").as_bytes(), "p.dxf").unwrap();
let b = d.extents(&Space::Model);
let r3 = 3f64.sqrt();
for (got, want) in [(b.min.x, -3.0), (b.min.y, 1.0), (b.max.x, -1.0), (b.max.y, 1.0 + r3)] {
assert!((got - want).abs() < 1e-9, "extents {b:?}");
}
let e = d.model.iter().next().unwrap();
assert_eq!(e.common.extrusion, Vec3::Z, "its points are plan coordinates now");
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline") };
assert!((p.elevation - (0.5 - r3)).abs() < 1e-9, "the mean height of its corners: {}", p.elevation);
// In plan and in the mirrored plane the polyline stays as it was: mirrored only in x.
let plain = read(square("").as_bytes(), "p.dxf").unwrap();
let b = plain.extents(&Space::Model);
assert!((b.min.x - 1.0).abs() < 1e-9 && (b.max.y - 2.0).abs() < 1e-9, "extents {b:?}");
let mirrored = read(square("210\n0\n220\n0\n230\n-1\n").as_bytes(), "p.dxf").unwrap();
let b = mirrored.extents(&Space::Model);
assert!((b.min.x + 3.0).abs() < 1e-9 && (b.max.x + 1.0).abs() < 1e-9, "extents {b:?}");
assert_eq!(mirrored.model.iter().next().unwrap().common.extrusion, Vec3::new(0.0, 0.0, -1.0));
}
/// A tilted 2D POLYLINE with an arc keeps its shape as seen from above: the half circle from
/// (0,0) to (2,0) is flattened into its half ellipse, in plan x from -2 to 0 and reaching √3/2.
#[test]
fn tilted_2d_polyline_arc_is_flattened() {
let text = "0\nSECTION\n2\nENTITIES\n0\nPOLYLINE\n8\n0\n66\n1\n10\n0\n20\n0\n30\n0\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\
0\nVERTEX\n8\n0\n10\n0\n20\n0\n42\n1\n0\nVERTEX\n8\n0\n10\n2\n20\n0\n0\nSEQEND\n0\nENDSEC\n0\nEOF\n";
let d = read(text.as_bytes(), "p.dxf").unwrap();
let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None });
assert!(p.vertices.len() > 8 && p.vertices.iter().all(|v| v.bulge == 0.0), "{} vertices", p.vertices.len());
let b = d.extents(&Space::Model);
// Bulge 1 turns counter-clockwise from (0,0) to (2,0), so the arc runs below its chord, down
// to OCS y -1: plan y -√3/2.
for (got, want) in [(b.min.x, -2.0), (b.max.x, 0.0), (b.min.y, -(3f64.sqrt()) / 2.0), (b.max.y, 0.0)] {
assert!((got - want).abs() < 5e-3, "extents {b:?}");
}
}
/// The model extents of a one-loop solid HATCH whose edge boundary is `edges` (group 72 onwards).
fn hatch_edge_extents(edges: &str) -> Bounds2 {
let n = edges.matches("72\n").count();
+74
View File
@@ -0,0 +1,74 @@
//! #3227: saving kept the layout's plot flags only for the bits CADCraft models and forced 512
//! (plot paper space last), 32 (plot with plot styles) and 16 (standard scale) on, so a layout
//! with flags 0 came back as 560, in DXF and in DWG.
use cadcraft_doc::{Drawing, Layout, PageSetup};
use cadcraft_io::{read, write};
/// A drawing with layout SHEET read with plot layout `flags` (lineweights, centring and display
/// plot styles follow them, as the reader sets them).
fn drawing(flags: i64) -> Drawing {
let mut d = Drawing::new_imperial();
let mut l = Layout::new("SHEET", 1);
l.page = PageSetup {
lineweights: flags & 128 != 0,
center: flags & 4 != 0,
show_plot_styles: flags & 2 != 0,
file_plot_flags: Some(flags),
..PageSetup::default()
};
d.layouts.push(l);
d
}
/// The plot layout flags of SHEET after saving `d` as `name` and reading it back.
fn flags_after_save(d: &Drawing, name: &str) -> Option<i64> {
let bytes = write(d, name).unwrap();
let back = read(&bytes, name).unwrap();
back.layouts.iter().find(|l| l.name == "SHEET")?.page.file_plot_flags
}
#[test]
fn plot_layout_flags_are_saved_as_read() {
cadcraft_io::dwg_worker::allow_in_process();
for name in ["sheet.dxf", "sheet.dwg"] {
for flags in [0, 176, 560, 688] {
assert_eq!(flags_after_save(&drawing(flags), name), Some(flags), "{name}: flags {flags}");
}
}
}
#[test]
fn an_unchanged_standard_scale_keeps_its_flag_and_choice() {
cadcraft_io::dwg_worker::allow_in_process();
// Flags 176 with standard scale 25 (1:50): the scale is 0.02, not 1:1, and still standard.
let mut d = drawing(176);
let page = &mut d.layouts.last_mut().unwrap().page;
page.scale = 0.02;
page.file_standard_scale = Some((25, 0.02));
for name in ["sheet.dxf", "sheet.dwg"] {
let back = read(&write(&d, name).unwrap(), name).unwrap();
let page = &back.layouts.iter().find(|l| l.name == "SHEET").unwrap().page;
assert_eq!(page.file_plot_flags, Some(176), "{name}");
assert_eq!(page.file_standard_scale, Some((25, 0.02)), "{name}");
}
// A scale changed after reading is a custom one: 16 is cleared and the choice dropped.
d.layouts.last_mut().unwrap().page.scale = 0.05;
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(160));
}
#[test]
fn the_page_still_decides_the_bits_cadcraft_models() {
// Lineweights turned on and a custom scale chosen after reading flags 16: 128 is set and the
// standard scale bit cleared, the rest kept.
let mut d = drawing(16 | 512);
let page = &mut d.layouts.last_mut().unwrap().page;
page.lineweights = true;
page.scale = 0.02;
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128));
// A page made in CADCraft keeps the defaults (plot paper space last, plot with plot styles,
// standard scale, lineweights).
let mut d = drawing(0);
d.layouts.last_mut().unwrap().page = PageSetup::default();
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128 | 32 | 16));
}
+1
View File
@@ -36,6 +36,7 @@ mod helix_roundtrip;
mod layer_states_acad;
mod layout_limits_roundtrip;
mod layout_paper_units;
mod layout_plot_flags;
mod layout_plot_window;
mod leader_vertex_elevation;
#[cfg(not(target_arch = "wasm32"))]
+2 -1
View File
@@ -257,7 +257,8 @@ pub(super) fn assert_layouts(a: &Drawing, b: &Drawing, context: &str) {
let back = b.layouts.iter().find(|l| l.name == layout.name).expect("layout must survive");
assert_eq!(back.tab_order, layout.tab_order, "{context}.{}.tab_order", layout.name);
// The groups 44, 45 and 73 the file stored are provenance, not a setting.
let setting = |p: &cadcraft_doc::PageSetup| cadcraft_doc::PageSetup { file_paper: None, ..p.clone() };
let setting =
|p: &cadcraft_doc::PageSetup| cadcraft_doc::PageSetup { file_paper: None, file_plot_flags: None, file_standard_scale: None, ..p.clone() };
assert_eq!(setting(&back.page), setting(&layout.page), "{context}.{}.page", layout.name);
assert_eq!(back.view, layout.view, "{context}.{}.view", layout.name);
compare::entities(a, b, &layout.entities, &back.entities, &format!("{context}.layout[{}]", layout.name));
@@ -112,7 +112,7 @@ fn layout_page_setup_and_paper_view_round_trip() {
for (a, b) in d.layouts.iter().zip(&r.layouts) {
assert_eq!(a.name, b.name);
// The groups 44, 45 and 73 the file stored are provenance, not a setting.
let read = cadcraft_doc::PageSetup { file_paper: None, ..b.page.clone() };
let read = cadcraft_doc::PageSetup { file_paper: None, file_plot_flags: None, file_standard_scale: None, ..b.page.clone() };
assert_eq!(a.page, read, "{}", a.name);
assert_eq!(a.view, b.view, "{}", a.name);
}
@@ -0,0 +1,121 @@
//! The registered applications (APPID) of a file are saved back, in DXF and in DWG, save after
//! save, also those no xdata names.
use cadcraft_doc::Drawing;
use cadcraft_io::{read, read_dxf, write, write_dxf};
/// The records of a DXF: each `(code, value)` from its `0` group on.
fn records(text: &str) -> Vec<Vec<(i32, String)>> {
let lines: Vec<&str> = text.lines().collect();
let mut out: Vec<Vec<(i32, String)>> = Vec::new();
for chunk in lines.chunks(2) {
let [code, value] = chunk else { break };
let Ok(c) = code.trim().parse::<i32>() else { continue };
let pair = (c, value.trim().to_string());
if c == 0 {
out.push(vec![pair]);
} else if let Some(r) = out.last_mut() {
r.push(pair);
}
}
out
}
/// The value of the record's first group `code`.
fn value(r: &[(i32, String)], code: i32) -> Option<&str> {
r.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str())
}
/// A file whose APPID table has `Other_App` (handle 7A00), which no xdata names; with `xdata`,
/// a line's xdata names it as `OTHER_APP`.
fn source(xdata: bool) -> String {
let mut out = String::new();
let mut put = |c: i32, v: &str| out.push_str(&format!("{c:>3}\n{v}\n"));
for r in records(&write_dxf(&Drawing::new_metric())) {
for (c, v) in &r {
put(*c, v);
}
if xdata && r[0].1 == "SECTION" && value(&r, 2) == Some("ENTITIES") {
for (c, v) in [
(0, "LINE"),
(5, "7A01"),
(100, "AcDbEntity"),
(8, "0"),
(100, "AcDbLine"),
(10, "0"),
(20, "0"),
(30, "0"),
(11, "10"),
(21, "0"),
(31, "0"),
(1001, "OTHER_APP"),
(1000, "x"),
] {
put(c, v);
}
}
if r[0].1 == "TABLE" && value(&r, 2) == Some("APPID") {
let table = value(&r, 5).unwrap_or("0").to_string();
for (c, v) in [
(0, "APPID"),
(5, "7A00"),
(330, table.as_str()),
(100, "AcDbSymbolTableRecord"),
(100, "AcDbRegAppTableRecord"),
(2, "Other_App"),
(70, "0"),
] {
put(c, v);
}
}
}
out
}
/// How many APPID records of the DXF are named `Other_App`, in any case.
fn appids(text: &str) -> usize {
records(text).into_iter().filter(|r| r[0].1 == "APPID" && value(r, 2).is_some_and(|n| n.eq_ignore_ascii_case("Other_App"))).count()
}
#[test]
fn registered_applications_no_xdata_names_are_kept() {
cadcraft_io::dwg_worker::allow_in_process();
let mut d = read_dxf(source(false).as_bytes()).expect("read");
for generation in 1..=2 {
let text = write_dxf(&d);
assert_eq!(appids(&text), 1, "DXF {generation}");
d = read_dxf(text.as_bytes()).expect("reread");
}
for generation in 1..=2 {
let dwg = write(&d, "kept.dwg").expect("DWG");
d = read(&dwg, "kept.dwg").expect("DWG read");
assert_eq!(appids(&write_dxf(&d)), 1, "DWG {generation}");
}
}
/// An application both registered and named by xdata, in another case, gets one record.
#[test]
fn a_registered_application_xdata_names_gets_one_record() {
cadcraft_io::dwg_worker::allow_in_process();
let mut d = read_dxf(source(true).as_bytes()).expect("read");
for generation in 1..=2 {
let text = write_dxf(&d);
assert!(text.contains("OTHER_APP"), "DXF {generation}: the line's xdata is kept");
assert_eq!(appids(&text), 1, "DXF {generation}");
d = read_dxf(text.as_bytes()).expect("reread");
}
for generation in 1..=2 {
let dwg = write(&d, "kept.dwg").expect("DWG");
d = read(&dwg, "kept.dwg").expect("DWG read");
assert_eq!(appids(&write_dxf(&d)), 1, "DWG {generation}");
}
}
/// Registered applications alone are not kept objects: a file with nothing else to keep notes no
/// version, so the DWG writer reads its R2000 text as before rather than as the file's version.
#[test]
fn registered_applications_alone_note_no_version() {
let d = read_dxf(source(false).as_bytes()).expect("read");
assert!(d.foreign.appids.iter().any(|n| n == "Other_App"), "{:?}", d.foreign.appids);
assert_eq!(d.foreign.version, None);
}
+4 -2
View File
@@ -200,12 +200,14 @@ pub(super) fn override_cursor(app: &mut CadApp, raw: Vec2, xf: &Xf) {
let s = &app.session.settings;
let osmode = over.unwrap_or(s.osmode) | if s.osnaphatch { snap::mode::HATCH } else { 0 };
let Ok(st) = app.session.state() else { return };
let space = st.edit_space();
let frozen = st.viewport_frozen();
let hit = match cycle {
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()
}
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) {
(Some(h), _) => {
+3 -3
View File
@@ -133,8 +133,8 @@ pub fn entries(app: &CadApp) -> Vec<Vec<Entry>> {
}
/// The edit commands of the selected objects' type (when they are all of one type), with their
/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit,
/// Polyline Edit, Spline Edit…
/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit
/// and Generate Boundary for hatches, Polyline Edit, Spline Edit…
fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> {
let Ok(d) = app.session.doc() else { return Vec::new() };
let sel = app.session.selection();
@@ -153,7 +153,7 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> {
}
v
}
EntityKind::Hatch(_) => vec![("hatchedit", None)],
EntityKind::Hatch(_) => vec![("hatchedit", None), ("hatchgenerateboundary", None)],
EntityKind::LwPolyline(_) | EntityKind::Polyline3d(_) => vec![("pedit", Some("Polyline Edit"))],
EntityKind::Spline(_) => vec![("splinedit", Some("Spline Edit"))],
EntityKind::Dimension(_) => vec![("dimtedit", None)],
+1
View File
@@ -374,6 +374,7 @@
From Desde
From Template... Desde plantilla...
General General
Generate Boundary Generar contorno
Geometric Center Centro geométrico
Geometric Constraint Restricción geométrica
Geometric Constraints Restricciones geométricas
1 # CADCraft Spanish interface catalog — original translations.
374
375
376
377
378
379
380
+1
View File
@@ -296,6 +296,7 @@
Freeze/Thaw in the current viewport 在当前视口中冻结/解冻
From 自
General 常规
Generate Boundary 生成边界
Geometric Center 几何中心
Geometric Constraint 几何约束
Geometric Constraints 几何约束
1 # CADCraft Simplified Chinese interface catalog — original translations.
296
297
298
299
300
301
302
+1
View File
@@ -42,6 +42,7 @@ mod shared_controls;
mod shortcut_menus;
mod shortcuts_checked;
mod slow_clicks;
mod snap_tab_cycling;
mod space_at_options;
mod status_bar_toggles;
mod style_dialogs;
+136
View File
@@ -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_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.event(Event::Text("\t".into()));
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_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.event(Event::Text("\t".into()));
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);
}