Compare commits

..
34 Commits
Author SHA1 Message Date
Tanish Manku f8769d9650 Snap: rustfmt 2026-11-23 12:33:39 -07:00
Tanish Manku 0b2cfae274 Snap: Perpendicular to a ray needs the cursor on the ray
The 'cursor is over this object' distance measured a ray as a line both
ways, so a cursor behind the ray's start snapped to the foot on it. Measure
to the ray's own half; an xline stays two-sided.
2026-11-23 12:33:14 -07:00
Tanish Manku c647cb4eb9 Snap: a perpendicular from an arc's centre stays on the arc
From the centre every point of an arc is perpendicular. The snap passed the
base as the pick, so it fell back to a point of the arc's circle (10,0 for a
90-180 degree arc) outside the sweep. Take the point of the arc nearest the
cursor.
2026-11-23 12:31:37 -07:00
Tanish Manku 0314c8bf2a Snap: a twisted viewport offers its next snap when the best is off it
In a twisted viewport the model clip is the box round the turned viewport.
A perpendicular foot inside that box but off the viewport could win, and
view.hit then rejected it, so the click got no snap from the viewport while
Tab still offered a valid one. When the winner falls off the viewport, take
the best of the ranked others that is on it; the extra ranking runs only then.
2026-11-23 12:29:20 -07:00
Tanish Manku 71f4879f9c Tab: keep deferred snaps of different curves at one point
Two circles touching at the cursor each offer a deferred tangent at the same
provisional point. SnapHit::same took them for one snap and dropped the
second, so Tab could not pick the other circle. Compare the deferred curve.
2026-11-23 12:27:03 -07:00
Tanish Manku 472d3661ce CIRCLE 3P TAN: solve picks in line with the picked circle's centre
CIRCLE 3P 3,0 5,0 TAN on a unit circle at the origin found no circle: the
picks were collinear, so the only Newton start lay on y = 0 with every target
centre, and each step stayed on that line until the matrix went singular.
With collinear picks, also start from circles on both sides of their line.
2026-11-23 12:25:05 -07:00
Tanish Manku ca90388ff3 OSMODE test: build each DXF variant from the clean export
The second check added $OSMODE = 4133 to text that already had $OSMODE = 0,
so the file carried both. Build it from the clean export and assert one.
2026-11-23 12:23:04 -07:00
Tanish Manku ded4122de0 Merge main
#1673 (Tab cycles every candidate) is already carried by this stack: its
deferred_hits and tests were ported, and Tab's list comes from finish_all
ranked by Rank. Keep the stack's snap.rs, pointmod.rs and
measure_distance_snapping.rs; restore the first half of #1673's
osnap_all_ranks_every_candidate (snap points, then Nearest on each object).
2026-11-23 12:19:18 -07:00
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 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 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
jayzed80 c40ff9603e Snap: skip VPLAYER-frozen layers in MSPACE (#3158) 2026-11-14 14:54:49 +00: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
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
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
104 changed files with 1691 additions and 3295 deletions
+1 -1
View File
@@ -38,7 +38,7 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
dry-run: ${{ github.event_name == 'schedule' }}
nightly: ${{ github.event_name == 'schedule' }}
app-name: cadcraft
app-title: CADCraft
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
+1 -3
View File
@@ -19,9 +19,7 @@ Generated-in-code assets are original and have no file to list:
- the standard linetype and hatch-pattern libraries (`crates/doc/src/library.rs`; industry-common
names, our own dash/spacing values);
- the colour index palette, generated from its structure (`crates/color/src/lib.rs`);
- the sample drawings (`crates/engine/src/sample.rs`);
- the synthetic two-hexagon hatch logo (`crates/io/tests/it/hatch_loop_flags.rs`, `logo`):
original contributor geometry, generated in code from invented points, under MIT OR Apache-2.0.
- the sample drawings (`crates/engine/src/sample.rs`).
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
Generated
-12
View File
@@ -661,7 +661,6 @@ dependencies = [
"craft-window",
"eframe",
"egui",
"fmv-macos-events",
"hidapi",
"log",
"muda",
@@ -2057,17 +2056,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8"
[[package]]
name = "fmv-macos-events"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55"
dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
]
[[package]]
name = "foldhash"
version = "0.1.5"
+1 -21
View File
@@ -58,7 +58,6 @@ fn install_io() {
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
}
/// `path` as text, for the engine and io calls that take a file name as a string.
@@ -96,7 +95,7 @@ where
Ok(cli) => cli,
Err(e) => {
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
return match write!(to, "{}", e.render()).and_then(|()| to.flush()) {
return match write!(to, "{}", e.render()) {
Err(w) if w.kind() != std::io::ErrorKind::BrokenPipe => {
let _ = writeln!(err, "error: can't write the output: {w}");
1
@@ -166,25 +165,6 @@ mod tests {
assert_eq!(run(["--help"], &mut FailingWriter(std::io::ErrorKind::BrokenPipe), &mut Vec::new()), 0);
}
struct FailingFlush(std::io::ErrorKind);
impl Write for FailingFlush {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Err(self.0.into())
}
}
#[test]
fn a_failed_flush_of_help_exits_1_unless_the_pipe_is_closed() {
let mut err = Vec::new();
assert_eq!(run(["--help"], &mut FailingFlush(std::io::ErrorKind::StorageFull), &mut err), 1);
assert!(String::from_utf8_lossy(&err).starts_with("error: "));
assert_eq!(run(["--help"], &mut FailingFlush(std::io::ErrorKind::BrokenPipe), &mut Vec::new()), 0);
}
#[test]
fn write_atomic_replaces_file_and_leaves_no_staging_files() {
let dir = scratch_dir("replace");
+1 -1
View File
@@ -58,7 +58,7 @@ pub(crate) fn roundtrip(a: &RoundtripArgs, io: &mut Streams) -> Result {
if a.keep_saved {
opts.keep_saved = Some(out.join("saved"));
}
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| io.errln(format_args!("[{}/{n}] {rel}", i + 1)));
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| eprintln!("[{}/{n}] {rel}", i + 1));
for f in &report.files {
let routes: Vec<String> = f
.routes
+2 -10
View File
@@ -1,7 +1,7 @@
use super::args::{CmdStep, Drawing, RunArgs, Step};
use super::error::Result;
use super::open;
use super::output::{Streams, export, export_framed, export_window, model_views, undrawn_message};
use super::output::{Streams, export, export_framed, export_window, model_views};
use cadcraft_engine::Session;
use cadcraft_engine::doc::Handle;
use serde_json::Value;
@@ -216,15 +216,7 @@ pub(crate) fn run_cmds(a: &RunArgs, io: &mut Streams) -> Result {
export(&s, p, io)?;
}
if let Some(p) = export_to {
let window = if cadcraft_io::is_image(p) {
let window = export_window(&s, framing, Some(&before))?;
if let Some(message) = undrawn_message(s.doc()?, &p.to_string_lossy()) {
io.errln(format_args!("{message}"));
}
window
} else {
None
};
let window = if cadcraft_io::is_image(p) { export_window(&s, framing, Some(&before))? } else { None };
export_framed(&s, p, window, io)?;
}
Ok(())
+2 -24
View File
@@ -1,5 +1,5 @@
//! Image exports report how many model-space entities they can't draw, by type. The exit code
//! stays 0 (#1208).
//! `convert` to an image says how many model-space entities it can't draw, by type, instead of
//! leaving them out silently (#1208). The exit code stays 0.
use std::process::{Command, Output};
@@ -70,28 +70,6 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() {
assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr));
}
#[test]
fn run_image_export_warns_about_undrawn_entities() {
let scratch = Scratch::new("run-undrawn");
let input = scratch.0.join("proxies.dxf");
std::fs::write(&input, PROXIES).unwrap();
let image = scratch.0.join("out.svg");
let out = cli(&["run", input.to_str().unwrap(), "--export", image.to_str().unwrap()]);
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{:?}: {err}", out.status);
assert!(image.is_file());
assert!(out.stdout.is_empty(), "the warning belongs on stderr");
let warnings: Vec<&str> = err.lines().filter(|l| l.contains("not drawn")).collect();
assert_eq!(warnings, [format!("{}: 3 entities not drawn (PDFUNDERLAY: 1, REGION: 2)", image.display())], "{err}");
let copy = scratch.0.join("copy.dxf");
let out = cli(&["run", input.to_str().unwrap(), "--export", copy.to_str().unwrap()]);
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{:?}: {err}", out.status);
assert!(copy.is_file());
assert!(!err.contains("not drawn"), "{err}");
}
/// An OLE2FRAME's frame outline is drawn, so an image export doesn't call it an undrawn entity (#2422); it
/// says once that the OLE content inside the frame is not drawn (review on #2587).
#[test]
-8
View File
@@ -949,11 +949,3 @@ fn json_output_is_pretty_unless_compact() {
assert_eq!(r.stdout.lines().count(), 2, "one line per --cmd result: {}", r.stdout);
assert_eq!(invoke(&["run", "--sample", "--compact"]).code, 2, "run takes no --compact");
}
#[test]
fn roundtrip_progress_uses_the_requested_stderr() {
run_cases(
"roundtrip-progress",
&[case("roundtrip progress", &["roundtrip", "{b}", "--same-format", "--no-census"], 0, Starts("b.dxf: opened;"), Line("[1/1] b.dxf"))],
);
}
-1
View File
@@ -132,7 +132,6 @@ mod web {
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
let Some(canvas) = app_canvas() else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
-5
View File
@@ -62,11 +62,6 @@ winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
# in Cargo.lock through eframe.
pollster = "1"
# Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C
# handler behind a safe API, without relaxing the workspace's unsafe-code lint.
# Pinned exactly: review the implementation before bumping.
fmv-macos-events = "=0.1.0"
# Rust HID backends: no proprietary SDK or C HID library.
[target.'cfg(target_os = "windows")'.dependencies]
-211
View File
@@ -1,211 +0,0 @@
//! macOS open-documents and quit Apple events (#158).
//!
//! A Finder double-click, Open With, a drop on the Dock icon and `open -a CADCraft plan.dxf` don't
//! put the path in argv: LaunchServices sends the running (or just-launched) app a
//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
//! `NSApplicationDelegate`, so AppKit answered "CADCraft cannot open files in the Drawing Exchange
//! Format format". Handling it ourselves needs Objective-C class declarations, i.e. `unsafe`, which
//! this workspace forbids. The pinned `fmv-macos-events` crate wraps exactly that, an
//! `NSAppleEventManager` handler registered before Finder's
//! launch event that leaves winit's delegate alone, behind a safe main-thread API.
use std::path::PathBuf;
use cadcraft_ui_egui::CadApp;
#[cfg(target_os = "macos")]
use fmv_macos_events::{Event, Inbox, Registration};
/// The shape of `fmv_macos_events::Event`, so [`dispatch`] and its tests also build and run where
/// that crate is not compiled (PR CI runs on Linux). On macOS the crate's own type is used.
#[cfg(not(target_os = "macos"))]
enum Event {
Open(Vec<PathBuf>),
Quit,
}
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
#[cfg(target_os = "macos")]
pub struct AppleEvents {
_registration: Registration,
inbox: Inbox,
}
#[cfg(target_os = "macos")]
impl AppleEvents {
/// Register the handlers. Call on the main thread before the event loop starts, so the event
/// that launched the app (a Finder double-click) is caught too.
pub fn install() -> Self {
let (registration, inbox) = Registration::install();
Self { _registration: registration, inbox }
}
/// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
pub fn connect(&self, ctx: &egui::Context) -> Inbox {
let ctx = ctx.clone();
self.inbox.set_wake(move || ctx.request_repaint());
self.inbox.clone()
}
}
/// The paths to hand to OPEN: UTF-8 and non-empty, each once, in the order they arrived. A second
/// copy of the same path (Finder sends one per selected item, and a drop can repeat) would open
/// the drawing twice.
fn openable(paths: impl IntoIterator<Item = PathBuf>) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for p in paths {
if let Some(s) = p.to_str().filter(|s| !s.is_empty())
&& !out.iter().any(|o| o == s)
{
out.push(s.to_string());
}
}
out
}
/// Dispatch a batch through the regular opening and unsaved-changes paths. Returns whether the
/// window may close now; a queued quit must not bypass the Save / Don't Save / Cancel prompt.
fn dispatch(events: impl IntoIterator<Item = Event>, app: &mut CadApp) -> bool {
let mut quit = false;
for e in events {
match e {
Event::Open(paths) => {
for p in openable(paths) {
app.open_path(std::path::Path::new(&p));
}
}
Event::Quit => quit = true,
}
}
quit && !app.request_quit()
}
/// Drain the inbox each frame; a quit closes the window like Cmd+Q, prompting for unsaved drawings.
#[cfg(target_os = "macos")]
pub fn poll(inbox: &Inbox, app: &mut CadApp, ctx: &egui::Context) {
if dispatch(inbox.drain(), app) {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
}
#[cfg(test)]
mod tests {
use super::{Event, dispatch, openable};
use cadcraft_engine::Session;
use cadcraft_ui_egui::closing::Choice;
use cadcraft_ui_egui::{CadApp, Services};
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
struct TestDir(PathBuf);
impl TestDir {
fn new() -> Self {
let dir = std::env::temp_dir().join(format!("cadcraft-apple-events-{}-{}", std::process::id(), NEXT_DIR.fetch_add(1, Ordering::Relaxed)));
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
}
impl Drop for TestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn app() -> CadApp {
crate::install_io();
// The DWG written and read here is the test's own synthetic file; the app starts its DWG
// worker in `main`, which a test does not run.
cadcraft_io::dwg_worker::allow_in_process();
CadApp::new(Session::new(), Services::default())
}
fn settle(app: &mut CadApp) {
let deadline = Instant::now() + Duration::from_secs(10);
while app.opening.busy() && Instant::now() < deadline {
app.finish_opening();
std::thread::sleep(Duration::from_millis(5));
}
app.finish_opening();
assert!(!app.opening.busy(), "background opening completed");
}
#[test]
fn keeps_order_and_drops_duplicates_and_empty_paths() {
let paths = ["/a/plan.dxf", "", "/b/site.dwg", "/a/plan.dxf"].map(PathBuf::from);
assert_eq!(openable(paths), ["/a/plan.dxf", "/b/site.dwg"]);
assert!(openable(Vec::new()).is_empty());
}
#[cfg(unix)]
#[test]
fn skips_paths_that_are_not_utf8() {
use std::os::unix::ffi::OsStringExt;
let bad = PathBuf::from(std::ffi::OsString::from_vec(vec![b'/', 0xff, b'.', b'd', b'x', b'f']));
assert_eq!(openable([bad, PathBuf::from("/ok.dxf")]), ["/ok.dxf"]);
}
#[test]
fn opens_dwg_and_dxf_without_replacing_an_unsaved_drawing() {
// Writing and opening the DWG here needs the converter in this process: each test is its own.
cadcraft_io::dwg_worker::allow_in_process();
let dir = TestDir::new();
let dxf = dir.0.join("planta com espaços.dxf");
let dwg = dir.0.join("Documentac\u{327}a\u{303}o.dwg");
let bytes = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n10\n21\n10\n0\nENDSEC\n0\nEOF\n";
let drawing = cadcraft_io::read(bytes, "synthetic.dxf").unwrap();
std::fs::write(&dxf, bytes).unwrap();
std::fs::write(&dwg, cadcraft_io::write(&drawing, "synthetic.dwg").unwrap()).unwrap();
let mut app = app();
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
let original = app.session.docs[0].uid;
assert!(app.session.docs[0].is_dirty());
assert!(!dispatch([Event::Open(vec![dxf.clone(), dwg.clone(), dxf.clone(), PathBuf::new()])], &mut app));
settle(&mut app);
assert_eq!(app.session.docs.len(), 3, "each file is opened once alongside the unsaved drawing");
assert_eq!(app.session.docs[0].uid, original);
assert!(app.session.docs[0].is_dirty());
for path in [&dxf, &dwg] {
assert!(app.session.docs.iter().any(|d| d.path.as_deref() == path.to_str()));
}
}
#[test]
fn a_failed_open_reports_the_path_and_keeps_existing_drawings() {
let dir = TestDir::new();
let missing = dir.0.join("missing drawing.dwg");
let mut app = app();
let original = app.session.docs[0].uid;
assert!(!dispatch([Event::Open(vec![missing.clone()])], &mut app));
settle(&mut app);
assert_eq!(app.session.docs.len(), 1);
assert_eq!(app.session.docs[0].uid, original);
assert!(app.session.log.iter().any(|line| line.contains(missing.to_str().unwrap())));
}
#[test]
fn a_quit_event_asks_before_closing_unsaved_work_and_can_be_cancelled() {
let mut app = app();
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
assert!(!dispatch([Event::Quit], &mut app), "must not issue a window close before the answer");
assert!(app.close_prompt().is_some());
assert!(!app.quit_confirmed);
assert!(!app.quit_requested);
app.answer_close(Choice::Cancel);
assert!(app.close_prompt().is_none());
assert!(app.session.docs[0].is_dirty());
assert!(!app.quit_requested);
}
#[test]
fn a_quit_event_can_close_a_clean_session() {
let mut app = app();
assert!(dispatch([Event::Quit], &mut app));
assert!(app.close_prompt().is_none());
}
}
-25
View File
@@ -14,8 +14,6 @@
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(any(target_os = "macos", test))]
mod apple_events;
mod control_server;
mod desktop_theme;
mod env;
@@ -56,9 +54,6 @@ struct App {
/// The `movable` flag last set on the main window.
#[cfg(target_os = "macos")]
movable: Option<bool>,
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
}
impl App {
@@ -107,9 +102,6 @@ impl eframe::App for App {
}
}
}
// Drawings and quit requests from Finder, the Dock and `open -a` (macOS).
#[cfg(target_os = "macos")]
apple_events::poll(&self.apple_events, &mut self.cad, ctx);
// Consume control/open/screenshot queues and time-based autosave, including hidden ticks.
self.cad.guarded_logic(ctx);
// Host frame work runs here, once per frame, and so also on a hidden logic-only tick (which
@@ -184,7 +176,6 @@ pub fn install_io() {
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
}
fn services() -> Services {
@@ -446,12 +437,6 @@ fn main() -> eframe::Result {
b.with_close_requested_on_terminate(true);
}));
}
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
#[cfg(target_os = "macos")]
let apple_events = apple_events::AppleEvents::install();
#[cfg(target_os = "macos")]
let apple_events = &apple_events;
eframe::run_native(
"CADCraft",
options,
@@ -515,14 +500,6 @@ fn main() -> eframe::Result {
for f in &files {
app.open_path(f);
}
// Start reading any launch-time documents before the first frame. Later events use
// this same inbox, including the normal unsaved-changes handling for quit requests.
#[cfg(target_os = "macos")]
let apple_events = {
let inbox = apple_events.connect(&cc.egui_ctx);
apple_events::poll(&inbox, &mut app, &cc.egui_ctx);
inbox
};
if app.session.docs.is_empty() {
// In the units the profile asks for (MEASUREINIT, restored above).
let metric = app.session.settings.measureinit;
@@ -550,8 +527,6 @@ fn main() -> eframe::Result {
menus_in_window: vars.no_native_menu == Switch::On,
#[cfg(target_os = "macos")]
movable: None,
#[cfg(target_os = "macos")]
apple_events,
}))
}),
)
-4
View File
@@ -144,10 +144,6 @@ impl NativeMenu {
self.last_refresh = now;
let typing = menus::text_field_window(ctx).is_some();
for (cmd, _, item) in self.items.values() {
// Open Recent rebuilds this item with the correct enabled state.
if cmd == menus::RECENT_CLEAR {
continue;
}
let en = (typing && menus::edits_text(cmd)) || cadcraft_engine::find_command(cmd).is_none_or(|c| (c.enabled)(&app.session).is_ok());
item.set_enabled(en);
}
-5
View File
@@ -123,11 +123,6 @@ sync_github_name = true
[people.helenkwok]
real_name = "Helen Kwok"
[people.whaslbeck]
real_name = "Walter Haslbeck"
display_name = "Walter Haslbeck"
sync_github_name = false
[people.V1dalTheAbidal]
sync_github_name = true
+1 -9
View File
@@ -43,7 +43,6 @@ mod curves;
mod dim;
mod fill;
mod layout;
mod proxy;
mod text;
mod wipeout;
@@ -53,18 +52,12 @@ pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, Polyface
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
pub use fill::{Gradient, Hatch, HatchLoop};
pub use layout::{Image, Table, TableCell, Viewport};
pub use proxy::{ProxyTables, proxy_entities};
pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign};
pub use wipeout::Wipeout;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Unknown {
pub dxf_type: String,
pub tags: Vec<RawTag>,
/// What an ACAD_PROXY_ENTITY draws: its proxy graphics as read-only entities, made when the
/// drawing is read (the graphics refer to table rows by their place in the file). Drawn and
/// measured like block contents; saving writes `tags` unchanged.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub graphics: Vec<Entity>,
}
impl Unknown {
@@ -271,8 +264,7 @@ impl EntityKind {
EntityKind::Image(i) => vec![Prim::Point(i.insert.xy())],
EntityKind::Table(t) => vec![Prim::Point(t.insert.xy())],
EntityKind::Tolerance(t) => vec![Prim::Point(t.insert.xy())],
// What its proxy graphics draw, so a proxy can be picked and snapped to.
EntityKind::Unknown(u) => u.graphics.iter().flat_map(|g| g.kind.prims()).collect(),
EntityKind::Unknown(_) => Vec::new(),
}
}
-5
View File
@@ -7,11 +7,6 @@ pub struct HatchLoop {
pub vertices: Vec<PolyVertex>,
#[serde(default)]
pub outer: bool,
/// Original DXF group 92 bits. Writing keeps only Derived (4), Textbox (8) and
/// Outermost (16), derives External (1) from `outer`, and sets Polyline (2).
/// None uses the flags of a locally created loop.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub boundary_flags: Option<i64>,
/// The objects the loop was made from (DXF group 97 count, 330 handles): an associative
/// hatch re-fills the loop from them when they change.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
-717
View File
@@ -1,717 +0,0 @@
//! The proxy graphics an ACAD_PROXY_ENTITY carries (DXF groups 92/160 and 310): the picture
//! the owning application left for programs that don't have it, drawn as AutoCAD draws it with
//! PROXYSHOW 1. The layout follows the Open Design Alliance's public DWG specification
//! ("Proxy Entity Graphics"): a header (total size, chunk count), then chunks of (size, type,
//! data), sizes in bytes including the 8-byte chunk header, all little-endian.
//!
//! The picture becomes ordinary, read-only entities: drawn and measured like the contents of a
//! block, with layer 0, ByBlock colour, linetype and lineweight standing for the proxy's own
//! until a chunk sets them. Chunks CADCraft doesn't decode (meshes, shells, lightweight
//! polylines, materials) are skipped.
use super::{Arc, Circle, Common, Entity, EntityKind, Handle, Hatch, HatchLoop, Line, Lineweight, LwPolyline, Text, Unknown};
use cadcraft_color::{Color, Rgb};
use cadcraft_geom::{PolyVertex, Vec2, Vec3};
/// Bytes of proxy graphics read at most from one entity.
const MAX_BYTES: usize = 16 << 20;
/// Entities made at most from one entity's proxy graphics.
const MAX_ENTITIES: usize = 100_000;
/// Vertices read at most from one polyline or polygon chunk.
const MAX_VERTICES: usize = 1_000_000;
/// Matrices pushed at most.
const MAX_MATRICES: usize = 64;
/// The table names proxy graphics refer to by index, in the order of the file's tables.
#[derive(Clone, Debug, Default)]
pub struct ProxyTables {
/// LAYER records in file order.
pub layers: Vec<String>,
/// LTYPE records in file order, without ByBlock and ByLayer (indices count only the others).
pub linetypes: Vec<String>,
/// Text styles (name, font file) in file order: a text chunk names its font, and the first
/// style with that font draws it.
pub styles: Vec<(String, String)>,
}
impl Unknown {
/// The proxy graphics bytes of an ACAD_PROXY_ENTITY: the 310 groups after its size group
/// (92, or 160 in newer files), cut to that size. Empty for other records, for an entity
/// without graphics and for one whose data isn't hex.
pub fn proxy_graphics_bytes(&self) -> Vec<u8> {
if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
return Vec::new();
}
let Some(at) = self.tags.iter().position(|t| t.code == 92 || t.code == 160) else { return Vec::new() };
let size = self.tags.get(at).and_then(|t| t.value.trim().parse::<usize>().ok()).unwrap_or(0).min(MAX_BYTES);
let mut out = Vec::with_capacity(size);
for t in self.tags.iter().skip(at + 1).take_while(|t| t.code == 310) {
// Damaged data draws nothing rather than a picture cut at a guess.
if !push_hex(&mut out, &t.value) {
return Vec::new();
}
if out.len() >= size {
break;
}
}
out.truncate(size);
out
}
}
/// Append the bytes of hex string `s`. False on a character that isn't a hex digit.
fn push_hex(out: &mut Vec<u8>, s: &str) -> bool {
let digits: Vec<u8> = s.trim().bytes().collect();
for pair in digits.chunks(2) {
let (Some(&hi), Some(&lo)) = (pair.first(), pair.get(1)) else { return false };
let (Some(hi), Some(lo)) = ((hi as char).to_digit(16), (lo as char).to_digit(16)) else { return false };
out.push((hi * 16 + lo) as u8);
}
true
}
/// The entities the proxy graphics `bytes` draw, all with `handle` (the proxy's): selecting one
/// selects the proxy.
pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec<Entity> {
let mut r = Decoder {
tables,
handle,
pen: Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..Common::default() },
fill: false,
matrices: Vec::new(),
out: Vec::new(),
};
let mut at = 8;
while let (Some(size), Some(kind)) = (u32_at(bytes, at), u32_at(bytes, at + 4)) {
let size = size as usize;
if size < 8 || r.out.len() >= MAX_ENTITIES {
break;
}
let Some(data) = bytes.get(at + 8..at.saturating_add(size)) else { break };
r.chunk(kind, data);
at += size;
}
r.out
}
struct Decoder<'a> {
tables: &'a ProxyTables,
handle: Handle,
/// Layer, colour, linetype and lineweight for the entities that follow.
pen: Common,
fill: bool,
/// Model transforms pushed by PUSH_MATRIX, innermost last (row-major 3x4 of the 4x4).
matrices: Vec<[f64; 12]>,
out: Vec<Entity>,
}
impl Decoder<'_> {
/// Decode one chunk of type `kind`: draw it, or change the pen for what follows.
fn chunk(&mut self, kind: u32, data: &[u8]) {
let mut b = Bytes { data, at: 0 };
match kind {
// CIRCLE: centre, radius, normal.
2 => {
if let (Some(c), Some(r)) = (b.point(), b.f64()) {
self.circle(c, r);
}
}
// CIRCLE_3P: three points on it.
3 => {
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point())
&& let Some((c, r)) = circle_through(self.xy(p1), self.xy(p2), self.xy(p3))
{
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
}
}
// CIRCULAR_ARC: centre, radius, normal, start vector, sweep angle (around the normal).
4 => {
if let (Some(c), Some(r), Some(n), Some(v), Some(sweep)) = (b.point(), b.f64(), b.point(), b.point(), b.f64()) {
self.arc(c, r, n, v, sweep);
}
}
// CIRCULAR_ARC_3P: start, a point on the arc, end.
5 => {
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point()) {
self.arc_3p(self.xy(p1), self.xy(p2), self.xy(p3));
}
}
// POLYLINE and POLYGON: a count, then the points.
6 | 7 => {
let Some(n) = b.u32() else { return };
let n = (n as usize).min(MAX_VERTICES);
let pts: Vec<Vec2> = (0..n).map_while(|_| b.point()).map(|p| self.xy(p)).collect();
self.polyline(pts, kind == 7);
}
// TEXT: position, normal, direction, height, width factor, oblique, string.
10 => {
if let (Some(p), Some(_), Some(dir), Some(h), Some(w), Some(o)) = (b.point(), b.point(), b.point(), b.f64(), b.f64(), b.f64()) {
let s = b.string();
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font: String::new() });
}
}
// TEXT2: position, normal, direction, string, length (the characters drawn), raw
// flag, height, width factor, oblique, tracking, five style flags, font, big font.
11 => {
if let (Some(p), Some(_), Some(dir)) = (b.point(), b.point(), b.point()) {
let s = b.string();
let s = first_chars(s, b.u32());
b.skip(4);
if let (Some(h), Some(w), Some(o)) = (b.f64(), b.f64(), b.f64()) {
b.skip(8 + 20);
let font = b.string();
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font });
}
}
}
// UNICODE_TEXT: as TEXT with a UTF-16 string.
36 => {
if let (Some(p), Some(_), Some(dir), Some(h), Some(w), Some(o)) = (b.point(), b.point(), b.point(), b.f64(), b.f64(), b.f64()) {
let s = b.unicode();
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font: String::new() });
}
}
// UNICODE_TEXT2: as TEXT2 with UTF-16 strings, and bold, italic, charset, pitch and
// the typeface before the font file.
38 => {
if let (Some(p), Some(_), Some(dir)) = (b.point(), b.point(), b.point()) {
let s = b.unicode();
let s = first_chars(s, b.u32());
b.skip(4);
if let (Some(h), Some(w), Some(o)) = (b.f64(), b.f64(), b.f64()) {
b.skip(8 + 20 + 16);
let _typeface = b.unicode();
let font = b.unicode();
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font });
}
}
}
// ATTRIBUTE_COLOR: ACI, 0 ByBlock, 256 ByLayer.
14 => {
if let Some(c) = b.u32() {
self.pen.color = Color::from_aci(i16::try_from(c).unwrap_or(256));
}
}
// ATTRIBUTE_LAYER: index into the layer table; an index past it leaves the layer.
16 => {
if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)) {
self.pen.layer = name.clone();
}
}
// ATTRIBUTE_LINETYPE: index into the linetypes other than ByBlock and ByLayer;
// 32766 is ByBlock, 32767 and anything past the table ByLayer.
18 => {
if let Some(i) = b.u32() {
self.pen.linetype = match i {
32766 => "ByBlock".into(),
_ => self.tables.linetypes.get(i as usize).cloned().unwrap_or_else(|| "ByLayer".into()),
};
}
}
// ATTRIBUTE_FILL: the next polygon is filled.
20 => self.fill = b.u32().is_some_and(|f| f != 0),
// ATTRIBUTE_TRUE_COLOR: a colour with its method in the top byte.
22 => {
if let Some(v) = b.u32() {
self.pen.color = match v >> 24 {
0xC0 => Color::ByLayer,
0xC1 => Color::ByBlock,
0xC2 => Color::True(Rgb::from_u32(v & 0x00FF_FFFF)),
0xC3 => Color::from_aci((v & 0xFF) as i16),
_ => self.pen.color,
};
}
}
// ATTRIBUTE_LINEWEIGHT: hundredths of a millimetre, or -1 ByLayer, -2 ByBlock,
// -3 the default.
23 => {
if let Some(v) = b.u32() {
self.pen.lineweight = Lineweight::from_dxf(i16::try_from(v as i32).unwrap_or(-1));
}
}
// ATTRIBUTE_LTSCALE.
24 => {
if let Some(s) = b.f64().filter(|s| s.is_finite() && *s > 0.0) {
self.pen.ltscale = s;
}
}
// PUSH_MATRIX, PUSH_MATRIX2: a 4x4 model transform for what follows; POP_MATRIX.
29 | 30 => {
let m: Vec<f64> = (0..16).map_while(|_| b.f64()).collect();
if let Some(m) = m.get(..12).and_then(|m| <[f64; 12]>::try_from(m).ok())
&& m.iter().all(|x| x.is_finite())
&& self.matrices.len() < MAX_MATRICES
{
self.matrices.push(m);
}
}
31 => {
self.matrices.pop();
}
_ => {}
}
}
/// Add an entity drawn with the current pen (up to [`MAX_ENTITIES`]).
fn push(&mut self, kind: EntityKind) {
if self.out.len() < MAX_ENTITIES {
self.out.push(Entity { handle: self.handle, common: self.pen.clone(), kind });
}
}
/// `p` through the pushed matrices, innermost first, in the XY plane.
fn xy(&self, p: Vec3) -> Vec2 {
let mut p = p;
for m in self.matrices.iter().rev() {
p = Vec3::new(
m[0] * p.x + m[1] * p.y + m[2] * p.z + m[3],
m[4] * p.x + m[5] * p.y + m[6] * p.z + m[7],
m[8] * p.x + m[9] * p.y + m[10] * p.z + m[11],
);
}
p.xy()
}
/// How much the pushed matrices scale lengths (1 without any).
fn scale(&self) -> f64 {
self.matrices.iter().map(|m| (m[0] * m[5] - m[1] * m[4]).abs().sqrt()).product()
}
/// A full circle around `c`, through the pushed matrices.
fn circle(&mut self, c: Vec3, r: f64) {
let r = r * self.scale();
let c = self.xy(c);
if r.is_finite() && r > 0.0 && c.is_finite() {
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
}
}
/// An arc around `c` from the direction `start`, turned by `sweep` around `normal`.
fn arc(&mut self, c: Vec3, r: f64, normal: Vec3, start: Vec3, sweep: f64) {
if !(r.is_finite() && r > 0.0 && sweep.is_finite() && sweep != 0.0) || start.xy().len() < 1e-12 {
return;
}
// The start point and the end point (the start vector turned by the sweep around the
// normal: clockwise in plan for a normal pointing down), through the matrices.
let dir = if normal.z < 0.0 { -1.0 } else { 1.0 };
let a0 = start.y.atan2(start.x);
let a1 = a0 + dir * sweep;
let on = |a: f64| c + Vec3::new(r * a.cos(), r * a.sin(), 0.0);
let mid = on((a0 + a1) / 2.0);
if sweep.abs() >= std::f64::consts::TAU - 1e-9 {
return self.circle(c, r);
}
self.arc_3p(self.xy(on(a0)), self.xy(mid), self.xy(on(a1)));
}
/// The arc from `p1` through `p2` to `p3`.
fn arc_3p(&mut self, p1: Vec2, p2: Vec2, p3: Vec2) {
let Some((c, r)) = circle_through(p1, p2, p3) else {
return self.polyline(vec![p1, p3], false);
};
let ang = |p: Vec2| (p.y - c.y).atan2(p.x - c.x);
let (a1, a2, a3) = (ang(p1), ang(p2), ang(p3));
let ccw = |from: f64, to: f64| (to - from).rem_euclid(std::f64::consts::TAU);
// Counter-clockwise from p1 to p3 when p2 lies on that way, else from p3 to p1.
let (start, end) = if ccw(a1, a2) <= ccw(a1, a3) { (a1, a3) } else { (a3, a1) };
self.push(EntityKind::Arc(Arc { center: c.to3(0.0), radius: r, start, end }));
}
/// A polyline, or a closed polygon: filled (a solid hatch) when ATTRIBUTE_FILL asked for it,
/// which applies to this one polygon only.
fn polyline(&mut self, pts: Vec<Vec2>, polygon: bool) {
let fill = std::mem::take(&mut self.fill);
if pts.iter().any(|p| !p.is_finite()) || pts.is_empty() {
return;
}
if polygon && fill && pts.len() >= 3 {
let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect();
return self.push(EntityKind::Hatch(Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
style: 0,
elevation: 0.0,
gradient: None,
origin: Vec2::ZERO,
background: None,
pattern_lines: Vec::new(),
}));
}
match pts.as_slice() {
[a, b] if !polygon => self.push(EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })),
_ => {
let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect();
self.push(EntityKind::LwPolyline(LwPolyline { vertices, closed: polygon, const_width: 0.0, elevation: 0.0, plinegen: false }));
}
}
}
/// A single-line text, its style the first one whose font file the chunk names.
fn text(&mut self, t: TextChunk) {
let TextChunk { p, dir, height, width, oblique, value, font } = t;
let font = font.as_str();
let height = height * self.scale();
if !(height.is_finite() && height > 0.0) || value.is_empty() {
return;
}
let at = self.xy(p);
if !at.is_finite() {
return;
}
let towards = self.xy(p + dir) - at;
let rotation = if towards.len() > 1e-12 { towards.y.atan2(towards.x) } else { 0.0 };
let stem = |f: &str| f.trim().rsplit(['/', '\\']).next().unwrap_or_default().split('.').next().unwrap_or_default().to_ascii_lowercase();
let style = self
.tables
.styles
.iter()
.find(|(_, f)| !font.is_empty() && stem(f) == stem(font))
.map(|(n, _)| n.clone())
.unwrap_or_else(|| "Standard".into());
self.push(EntityKind::Text(Text {
insert: at.to3(0.0),
align_pt: None,
height,
value,
rotation,
width_factor: if width.is_finite() && width > 0.0 { width } else { 1.0 },
oblique: if oblique.is_finite() { oblique } else { 0.0 },
style,
halign: Default::default(),
valign: Default::default(),
}));
}
}
/// The first `length` characters of `s`: a text chunk may carry more text than it draws (the
/// rest of a note, drawn by the chunks after it). No length, or one past the end, keeps it all.
fn first_chars(s: String, length: Option<u32>) -> String {
match length.map(|n| n as usize) {
Some(n) if n > 0 && n < s.chars().count() => s.chars().take(n).collect(),
_ => s,
}
}
/// A text chunk: position, direction, height, width factor, oblique, string and font file.
struct TextChunk {
p: Vec3,
dir: Vec3,
height: f64,
width: f64,
oblique: f64,
value: String,
font: String,
}
/// The circle through three points (centre, radius), if they aren't on one line.
fn circle_through(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> {
let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));
if !d.is_finite() || d.abs() < 1e-12 {
return None;
}
let (a2, b2, c2) = (a.x * a.x + a.y * a.y, b.x * b.x + b.y * b.y, c.x * c.x + c.y * c.y);
let center =
Vec2::new((a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d, (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d);
let r = (a - center).len();
(center.is_finite() && r.is_finite() && r > 0.0).then_some((center, r))
}
/// The little-endian u32 at `at`, if `bytes` holds one there.
fn u32_at(bytes: &[u8], at: usize) -> Option<u32> {
bytes.get(at..at.checked_add(4)?).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)
}
/// A reader over one chunk's data. Strings are padded to four bytes.
struct Bytes<'a> {
data: &'a [u8],
at: usize,
}
impl Bytes<'_> {
/// The next `n` bytes, if there are that many.
fn take(&mut self, n: usize) -> Option<&[u8]> {
let s = self.data.get(self.at..self.at.checked_add(n)?)?;
self.at += n;
Some(s)
}
/// Pass over `n` bytes (reads after the end then find nothing).
fn skip(&mut self, n: usize) {
self.at = self.at.saturating_add(n);
}
/// A little-endian u32.
fn u32(&mut self) -> Option<u32> {
self.take(4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)
}
/// A little-endian double.
fn f64(&mut self) -> Option<f64> {
self.take(8).and_then(|b| b.try_into().ok()).map(f64::from_le_bytes)
}
/// Three doubles, if all are finite.
fn point(&mut self) -> Option<Vec3> {
let p = Vec3::new(self.f64()?, self.f64()?, self.f64()?);
(p.x.is_finite() && p.y.is_finite() && p.z.is_finite()).then_some(p)
}
/// Move on to the next multiple of four bytes, where padded strings end.
fn align(&mut self) {
self.at = self.at.saturating_add((4 - self.at % 4) % 4);
}
/// A zero-terminated string in the drawing's code page; bytes above 0x7F as Latin-1.
fn string(&mut self) -> String {
let rest = self.data.get(self.at..).unwrap_or_default();
let end = rest.iter().position(|&c| c == 0).unwrap_or(rest.len());
let s: String = rest.iter().take(end).map(|&c| c as char).collect();
self.at += end + 1;
self.align();
s
}
/// A UTF-16 string ended by a zero code unit.
fn unicode(&mut self) -> String {
let rest = self.data.get(self.at..).unwrap_or_default();
let (pairs, _) = rest.as_chunks::<2>();
let units: Vec<u16> = pairs.iter().map(|&p| u16::from_le_bytes(p)).take_while(|&u| u != 0).collect();
self.at += units.len() * 2 + 2;
self.align();
String::from_utf16_lossy(&units)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::RawTag;
/// A chunk of type `kind`, its data padded to four bytes.
fn chunk(kind: u32, data: &[u8]) -> Vec<u8> {
let mut d = data.to_vec();
d.resize(d.len().div_ceil(4) * 4, 0);
let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec();
out.extend(kind.to_le_bytes());
out.extend(d);
out
}
/// Proxy graphics: the header (total size, chunk count), then the chunks.
fn graphics(chunks: &[Vec<u8>]) -> Vec<u8> {
let body: Vec<u8> = chunks.concat();
let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec();
out.extend((chunks.len() as u32).to_le_bytes());
out.extend(body);
out
}
/// A point in the XY plane as three doubles.
fn pt(x: f64, y: f64) -> Vec<u8> {
[x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect()
}
/// Two layers, two linetypes and two text styles.
fn tables() -> ProxyTables {
ProxyTables {
layers: vec!["0".into(), "BALLOONS".into()],
linetypes: vec!["Continuous".into(), "DASHED".into()],
styles: vec![("Standard".into(), "txt".into()), ("ISO".into(), "isocp.shx".into())],
}
}
/// A balloon as AutoCAD Mechanical stores one: layer, colour, a circle, the leader and the
/// number as TEXT2.
#[test]
fn a_balloon_becomes_circle_line_and_text() {
let mut text2 = pt(173.0, 112.0);
text2.extend(pt(0.0, 0.0).iter().take(16).chain(1.0f64.to_le_bytes().iter()));
text2.extend(pt(1.0, 0.0));
text2.extend(b"12\0\0");
text2.extend(2i32.to_le_bytes());
text2.extend(0i32.to_le_bytes());
for v in [6.0f64, 1.0, 0.0, 0.0] {
text2.extend(v.to_le_bytes());
}
text2.extend([0u8; 20]);
text2.extend(b"ISOCP.SHX\0\0\0\0\0");
let mut circle = pt(175.0, 115.0);
circle.extend(6.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0).iter().take(16).chain(1.0f64.to_le_bytes().iter()));
let mut leader = 2u32.to_le_bytes().to_vec();
leader.extend(pt(170.0, 111.0));
leader.extend(pt(150.0, 90.0));
let g = graphics(&[chunk(16, &1u32.to_le_bytes()), chunk(14, &1u32.to_le_bytes()), chunk(2, &circle), chunk(6, &leader), chunk(11, &text2)]);
let es = proxy_entities(&g, &tables(), Handle(0x35));
assert_eq!(es.len(), 3);
assert!(es.iter().all(|e| e.handle == Handle(0x35) && e.common.layer == "BALLOONS" && e.common.color == Color::Index(1)));
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center == Vec3::new(175.0, 115.0, 0.0) && c.radius == 6.0));
assert!(matches!(&es[1].kind, EntityKind::Line(l) if l.b == Vec3::new(150.0, 90.0, 0.0)));
assert!(matches!(&es[2].kind, EntityKind::Text(t) if t.value == "12" && t.height == 6.0 && t.style == "ISO" && t.rotation == 0.0));
}
/// A TEXT2 chunk draws only as many characters as its length says.
#[test]
fn text2_draws_its_length() {
let text2 = |value: &[u8], length: i32| {
let mut t = pt(0.0, 0.0);
t.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
t.extend(pt(1.0, 0.0));
t.extend(value);
t.extend(vec![0u8; 4 - value.len() % 4]);
t.extend(length.to_le_bytes());
t.extend(1i32.to_le_bytes());
for v in [2.5f64, 1.0, 0.0, 0.0] {
t.extend(v.to_le_bytes());
}
t.extend([0u8; 20]);
t.extend(b"txt\0");
let es = proxy_entities(&graphics(&[chunk(11, &t)]), &tables(), Handle(1));
match es.first().map(|e| &e.kind) {
Some(EntityKind::Text(t)) => t.value.clone(),
other => panic!("{other:?}"),
}
};
assert_eq!(text2(b"two lines\\Pof text", 9), "two lines");
assert_eq!(text2(b"whole", 0), "whole");
assert_eq!(text2(b"whole", 99), "whole");
}
/// Without layer and colour chunks the picture takes the proxy's own (layer 0, ByBlock).
#[test]
fn unset_traits_are_the_proxys() {
let mut leader = 3u32.to_le_bytes().to_vec();
for (x, y) in [(0.0, 0.0), (10.0, 0.0), (10.0, 5.0)] {
leader.extend(pt(x, y));
}
let es = proxy_entities(
&graphics(&[chunk(6, &leader), chunk(16, &u32::MAX.to_le_bytes()), chunk(18, &32766u32.to_le_bytes())]),
&tables(),
Handle(1),
);
let e = es.first().expect("polyline");
assert_eq!(
(e.common.layer.as_str(), e.common.color, e.common.linetype.as_str(), e.common.lineweight),
("0", Color::ByBlock, "ByBlock", Lineweight::ByBlock)
);
assert!(matches!(&e.kind, EntityKind::LwPolyline(p) if p.vertices.len() == 3 && !p.closed));
}
#[test]
fn a_filled_polygon_is_a_solid_hatch_and_fill_applies_once() {
let mut tri = 3u32.to_le_bytes().to_vec();
for (x, y) in [(0.0, 0.0), (4.0, 0.0), (2.0, 3.0)] {
tri.extend(pt(x, y));
}
let es = proxy_entities(&graphics(&[chunk(20, &1u32.to_le_bytes()), chunk(7, &tri), chunk(7, &tri)]), &tables(), Handle(1));
assert!(matches!(&es[0].kind, EntityKind::Hatch(h) if h.solid && h.loops[0].vertices.len() == 3));
assert!(matches!(&es[1].kind, EntityKind::LwPolyline(p) if p.closed));
}
/// A quarter arc counter-clockwise from 0°, and the same sweep around a downward normal,
/// which runs clockwise in plan (from 0° to -90°).
#[test]
fn arcs_follow_their_normal() {
let arc = |nz: f64| {
let mut a = pt(0.0, 0.0);
a.extend(2.0f64.to_le_bytes());
a.extend([0.0f64, 0.0, nz].iter().flat_map(|v| v.to_le_bytes()));
a.extend(pt(1.0, 0.0));
a.extend(std::f64::consts::FRAC_PI_2.to_le_bytes());
a.extend(0u32.to_le_bytes());
match proxy_entities(&graphics(&[chunk(4, &a)]), &tables(), Handle(1)).first().map(|e| e.kind.clone()) {
Some(EntityKind::Arc(a)) => (a.start, a.end, a.radius),
other => panic!("{other:?}"),
}
};
let (s, e, r) = arc(1.0);
assert!(s.abs() < 1e-9 && (e - std::f64::consts::FRAC_PI_2).abs() < 1e-9 && (r - 2.0).abs() < 1e-9);
let (s, e, _) = arc(-1.0);
assert!((s + std::f64::consts::FRAC_PI_2).abs() < 1e-9 && e.abs() < 1e-9, "{s} {e}");
}
#[test]
fn a_pushed_matrix_moves_what_follows_until_popped() {
let mut m = [0.0f64; 16];
(m[0], m[5], m[10], m[15], m[3], m[7]) = (2.0, 2.0, 1.0, 1.0, 100.0, 50.0);
let mut circle = pt(1.0, 1.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
let push: Vec<u8> = m.iter().flat_map(|v| v.to_le_bytes()).collect();
let es = proxy_entities(&graphics(&[chunk(29, &push), chunk(2, &circle), chunk(31, &[]), chunk(2, &circle)]), &tables(), Handle(1));
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center == Vec3::new(102.0, 52.0, 0.0) && c.radius == 2.0));
assert!(matches!(&es[1].kind, EntityKind::Circle(c) if c.center == Vec3::new(1.0, 1.0, 0.0) && c.radius == 1.0));
}
/// A finite matrix can still move a point past the largest float: a circle or a text that
/// would land there is left out, as a polyline is, so no infinity reaches the extents.
#[test]
fn what_a_matrix_moves_out_of_range_is_left_out() {
let mut m = [0.0f64; 16];
(m[0], m[5], m[10], m[15], m[3]) = (1.0, 1.0, 1.0, 1.0, 1.7e308);
let push: Vec<u8> = m.iter().flat_map(|v| v.to_le_bytes()).collect();
let mut circle = pt(1e308, 0.0);
circle.extend(1.0f64.to_le_bytes());
circle.extend(pt(0.0, 0.0));
let mut text = pt(1e308, 0.0);
text.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
text.extend(pt(1.0, 0.0));
text.extend(b"far\0");
text.extend(0i32.to_le_bytes());
text.extend(1i32.to_le_bytes());
for v in [2.5f64, 1.0, 0.0, 0.0] {
text.extend(v.to_le_bytes());
}
text.extend([0u8; 20]);
text.extend(b"txt\0");
let es = proxy_entities(&graphics(&[chunk(29, &push), chunk(2, &circle), chunk(11, &text)]), &tables(), Handle(1));
assert!(es.is_empty(), "{es:?}");
// The same text without the matrix is drawn: the chunk itself is sound.
assert_eq!(proxy_entities(&graphics(&[chunk(11, &text)]), &tables(), Handle(1)).len(), 1);
}
#[test]
fn the_bytes_come_from_the_310_groups_after_the_size() {
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let u = Unknown {
dxf_type: "ACAD_PROXY_ENTITY".into(),
tags: vec![tag(90, "498"), tag(92, "5"), tag(310, "0102"), tag(310, "030405FF"), tag(93, "0")],
graphics: Vec::new(),
};
assert_eq!(u.proxy_graphics_bytes(), [1, 2, 3, 4, 5]);
let other = Unknown { dxf_type: "ACAD_PROXY_OBJECT".into(), ..u.clone() };
assert!(other.proxy_graphics_bytes().is_empty());
let bad = Unknown { tags: vec![tag(92, "4"), tag(310, "01zz")], ..u };
assert!(bad.proxy_graphics_bytes().is_empty());
}
/// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and
/// never panic.
#[test]
fn hostile_graphics_do_not_panic() {
let mut huge = u32::MAX.to_le_bytes().to_vec();
huge.extend(pt(1.0, 1.0));
let mut nan = pt(f64::NAN, 0.0);
nan.extend(1.0f64.to_le_bytes());
let cases: Vec<Vec<u8>> = vec![
Vec::new(),
vec![0; 7],
graphics(&[chunk(6, &huge)]),
graphics(&[chunk(2, &nan)]),
graphics(&[chunk(11, &[0xFF; 30])]),
graphics(&[chunk(38, &[0x41; 77])]),
graphics(&[chunk(29, &[1; 40])]),
graphics(&[chunk(31, &[]), chunk(31, &[])]),
[graphics(&[chunk(2, &pt(0.0, 0.0))]), vec![0xFF; 9]].concat(),
{
let mut g = graphics(&[]);
g.extend(4u32.to_le_bytes());
g.extend(2u32.to_le_bytes());
g
},
{
let mut g = graphics(&[]);
g.extend(1_000u32.to_le_bytes());
g.extend(2u32.to_le_bytes());
g
},
];
for g in cases {
let _ = proxy_entities(&g, &tables(), Handle(1));
}
}
}
+2 -2
View File
@@ -37,7 +37,7 @@ pub struct RegionProps {
impl Region {
/// A region bounded by one closed loop.
pub fn from_loop(vertices: Vec<PolyVertex>) -> Region {
Region { loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }] }
Region { loops: vec![HatchLoop { vertices, outer: true, sources: Vec::new() }] }
}
pub fn polylines(&self) -> Vec<Polyline> {
@@ -170,7 +170,7 @@ mod tests {
let mut vertices: Vec<PolyVertex> =
(0..n).map(|k| PolyVertex::new(Vec2::new(c - half + 2.0 * half * k as f64 / n as f64, c - half))).collect();
vertices.extend([Vec2::new(c + half, c - half), Vec2::new(c + half, c + half), Vec2::new(c - half, c + half)].map(PolyVertex::new));
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
HatchLoop { vertices, outer, sources: Vec::new() }
}
#[test]
+4 -30
View File
@@ -371,28 +371,6 @@ fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blo
bounds_in(d, e, depth, blocks, off_counts)
}
/// The bounds of a record kept as read that draws something: a proxy as its proxy graphics draw
/// (layer 0 in them is the proxy's layer), each at the next depth as a block's contents are, and an
/// OLE2FRAME as its frame.
fn unknown_bounds<'a>(
d: &'a Drawing,
u: &crate::Unknown,
depth: usize,
blocks: &mut HashMap<(&'a str, usize), Bounds2>,
off_counts: bool,
) -> Bounds2 {
if u.graphics.is_empty() {
return ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points);
}
if depth >= MAX_BLOCK_DEPTH {
return Bounds2::EMPTY;
}
u.graphics
.iter()
.filter(|g| in_block_visible(d, g, off_counts))
.fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, off_counts)))
}
/// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed,
/// by block name and depth: every further reference to a block at that depth reuses them instead of
/// expanding the block again, so nested or self-referencing blocks cost at most one pass over each
@@ -538,9 +516,8 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
Bounds2::from_points([o, o + u, o + v, o + u + v])
}
EntityKind::LwPolyline(p) => lwpolyline_bounds(p),
// A proxy measures as its proxy graphics draw. An OLE object's content is not drawn, but its
// frame is, so the frame counts (#2422).
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, off_counts),
// An OLE object's content is not drawn, but its frame is, so the frame counts (#2422).
EntityKind::Unknown(u) if u.is_ole_frame() => ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points),
kind => {
let mut b = Bounds2::EMPTY;
for p in kind.prims() {
@@ -741,15 +718,12 @@ mod tests {
#[test]
fn ole_frame_counts_in_extents() {
let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() };
let frame = |tags: Vec<crate::RawTag>| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
let frame = |tags: Vec<crate::RawTag>| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags });
let b = bounds(frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")]));
assert_eq!((b.min, b.max), (Vec2::new(30.0, -22.0), Vec2::new(35.0, -19.0)));
assert!(bounds(frame(vec![tag(10, "1"), tag(20, "2")])).is_empty(), "one corner is not a frame");
assert!(bounds(frame(vec![tag(10, "NaN"), tag(20, "0"), tag(11, "1"), tag(21, "inf")])).is_empty());
assert!(
bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")], graphics: Vec::new() }))
.is_empty()
);
assert!(bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")] })).is_empty());
}
/// Groups 10/20 inside an application-defined `102 {...}` group belong to the application, not
-4
View File
@@ -53,10 +53,6 @@ impl ForeignExtra {
/// Everything of a file CADCraft keeps without modelling it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Foreign {
/// Original two-point text and style, by entity handle and attribute position.
/// Kept with imported metadata so new entities never inherit another entity's fitting.
pub text_fits: BTreeMap<Handle, Vec<(crate::Text, crate::TextStyle)>>,
/// CLASS records (groups after `0 CLASS`) of the kept objects' and entities' types.
pub classes: Vec<Vec<RawTag>>,
/// Classes retain every source position, including duplicate names.
-5
View File
@@ -57,10 +57,6 @@ impl EntityStore {
pub fn iter(&self) -> impl Iterator<Item = &Arc<Entity>> + '_ {
self.chunks.iter().flat_map(|c| c.items.iter())
}
/// Iterate from the top of the draw order down.
pub fn iter_rev(&self) -> impl Iterator<Item = &Arc<Entity>> + '_ {
self.chunks.iter().rev().flat_map(|c| c.items.iter().rev())
}
pub fn handles(&self) -> Vec<Handle> {
self.iter().map(|e| e.handle).collect()
}
@@ -350,7 +346,6 @@ mod tests {
}
assert!(s.move_next_to(Handle(1), Handle(3), true));
assert_eq!(order(&s), [2, 3, 1, 4, 5]);
assert_eq!(s.iter_rev().map(|e| e.handle.0).collect::<Vec<_>>(), [5, 4, 1, 3, 2], "top down");
assert!(s.move_next_to(Handle(5), Handle(2), false));
assert_eq!(order(&s), [5, 2, 3, 1, 4]);
assert!(!s.move_next_to(Handle(5), Handle(5), true));
+22
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;
@@ -350,6 +355,20 @@ pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
starts.push([cen.x, cen.y, rad.max(1e-3)]);
if let Some(c) = Circle::from_3_points(p1, p2, p3) {
starts.push([c.center.x, c.center.y, c.radius]);
} else {
// The picks lie in one line. When the circles picked are centred on it too, every Newton
// step from a start on that line stays on it: start off it as well, on both sides, from
// the circle through the two picks farthest apart and a point beside them.
let (a, b) = [(p1, p2), (p1, p3), (p2, p3)].into_iter().max_by(|x, y| x.0.dist(x.1).total_cmp(&y.0.dist(y.1))).unwrap_or((p1, p3));
let span = a.dist(b);
let n = (b - a).normalized().perp();
if span.is_finite() && span > 0.0 && n.is_finite() {
for side in [1.0, -1.0] {
if let Some(c) = Circle::from_3_points(a, b, (a + b) / 2.0 + n * (span * side)) {
starts.push([c.center.x, c.center.y, c.radius]);
}
}
}
}
let mut best: Option<(f64, Circle)> = None;
let scale = rad.max(p1.dist(p2)).max(1e-6);
@@ -379,6 +398,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);
-11
View File
@@ -39,10 +39,6 @@ fn vertex_value(v: &Value) -> Option<PolyVertex> {
Some(PolyVertex { p, bulge: f64_or(v, "bulge", 0.0), start_width: f64_or(v, "startWidth", 0.0), end_width: f64_or(v, "endWidth", 0.0) })
}
fn current_elevation(s: &Session) -> Result<f64> {
Ok(s.doc()?.header.f64("ELEVATION", 0.0))
}
pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
let raw = p.get("vertices").or_else(|| p.get("points")).and_then(Value::as_array);
for v in raw.into_iter().flatten() {
@@ -57,7 +53,6 @@ pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
let mut k = lwpoly(vs, bool_or(p, "closed", false));
if let EntityKind::LwPolyline(pl) = &mut k {
pl.const_width = width;
pl.elevation = current_elevation(s)?;
}
added(s.add_entity(k)?)
}
@@ -179,7 +174,6 @@ impl Interactive for LineM {
#[derive(Default)]
pub(super) struct PlineM {
verts: Vec<PolyVertex>,
elevation: f64,
arc_mode: bool,
/// Total width at the start and end of the next segment (Width / Halfwidth answers).
start_w: f64,
@@ -197,7 +191,6 @@ impl PlineM {
fn entity(&self, closed: bool) -> EntityKind {
let mut k = lwpoly(self.verts.clone(), closed);
if let EntityKind::LwPolyline(pl) = &mut k {
pl.elevation = self.elevation;
// Every segment the same uniform width: store it as the constant width, as before.
let segs = if closed { pl.vertices.len() } else { pl.vertices.len().saturating_sub(1) };
let w = pl.vertices.first().map_or(0.0, |v| v.start_width);
@@ -266,10 +259,6 @@ impl Interactive for PlineM {
fn name(&self) -> &'static str {
"PLINE"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.elevation = current_elevation(s)?;
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
if self.asking_width > 0 {
let unit = if self.half { "half-width" } else { "width" };
+1 -1
View File
@@ -232,7 +232,7 @@ impl Interactive for MTextM {
None => Prompt::new("Specify first corner", Accept::POINT),
Some(a) if !self.boxed() => Prompt::new("Specify opposite corner", Accept::POINT)
.kw(&["Height", "Justify", "Line spacing", "Rotation", "Style", "Width", "Columns"])
.corner(a),
.base(a),
_ if self.lines.is_empty() => Prompt::new("Enter text (use \\P for new paragraphs)", Accept::TEXT),
_ => Prompt::new("Enter next line of text (empty line to finish)", Accept::TEXT),
}
+1 -3
View File
@@ -593,9 +593,7 @@ fn run_select(s: &mut Session, p: &Value) -> Result<Value> {
} else if let Some(f) = points_param(p, "fence") {
crate::select::select_fence_in(s.doc()?, &space, s.viewport_frozen(), &f)
} else if ["handles", "handle"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
// Handles named outright, less the proxies: no selection takes one in.
let d = s.doc()?;
targets(s, p)?.into_iter().filter(|h| !d.entity(*h).is_some_and(|e| crate::select::kept_as_read(&e.kind))).collect()
targets(s, p)?
} else {
// Nothing to select with: the selection stays, also what the active viewport does not draw.
s.stored_selection()
-15
View File
@@ -95,15 +95,6 @@ pub fn set_proxies_lost(f: ProxiesLost) {
let _ = PROXIES_LOST.set(f);
}
/// Version-specific DWG compatibility omissions, counted by the host's actual writer.
pub type DwgCompatLost = fn(&Drawing, Version) -> std::collections::BTreeMap<String, usize>;
static DWG_COMPAT_LOST: OnceLock<DwgCompatLost> = OnceLock::new();
pub fn set_dwg_compat_lost(f: DwgCompatLost) {
let _ = DWG_COMPAT_LOST.set(f);
}
/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from
/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file).
fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
@@ -932,12 +923,6 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap
*n = n.saturating_add(1);
}
}
if let Some(compatibility) = DWG_COMPAT_LOST.get() {
for (kind, count) in compatibility(d, version) {
let total = out.entry(kind).or_default();
*total = total.saturating_add(count);
}
}
out
}
+4 -9
View File
@@ -232,7 +232,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
let outer = found.outer;
let ob = Bounds2::from_points(outer.iter().copied());
let sources = handles_of(&owners, &found.outer_sources);
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, boundary_flags: None, sources }];
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, sources }];
// Islands: closed objects entirely inside the outer loop that don't contain the pick point.
if let Some(store) = d.space(&space) {
for e in store.iter() {
@@ -248,7 +248,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
let inside = pts.iter().all(|q| point_in_polygon(&outer, *q) || outer.iter().any(|o| o.near(*q, tol * 10.0)));
let same_as_outer = (cadcraft_geom::shoelace(&pts).abs() - cadcraft_geom::shoelace(&outer).abs()).abs() < tol.max(1e-6) * 1000.0;
if inside && !same_as_outer && !point_in_polygon(&pts, p) {
loops.push(HatchLoop { vertices: vs, outer: false, boundary_flags: None, sources: vec![e.handle] });
loops.push(HatchLoop { vertices: vs, outer: false, sources: vec![e.handle] });
}
}
}
@@ -260,12 +260,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
&& island.sources.iter().all(|&i| owners.get(i).and_then(|h| d.entity(*h)).is_some_and(|e| island_curve(d, e)));
if open_curves {
let sources = handles_of(&owners, &island.sources);
loops.push(HatchLoop {
vertices: island.outline.into_iter().map(PolyVertex::new).collect(),
outer: false,
boundary_flags: None,
sources,
});
loops.push(HatchLoop { vertices: island.outline.into_iter().map(PolyVertex::new).collect(), outer: false, sources });
}
}
Ok(loops)
@@ -276,7 +271,7 @@ pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result<Vec<Hatch
let mut loops = Vec::new();
for h in hs {
if let Some(vs) = d.entity(*h).and_then(|e| closed_loop(d, e)) {
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), boundary_flags: None, sources: vec![*h] });
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), sources: vec![*h] });
}
}
if loops.is_empty() {
+1 -1
View File
@@ -197,7 +197,7 @@ fn follow(before: &Drawing, after: &Drawing, handle: Handle, h: &Hatch, checked:
match refill(from, after, l) {
Refill::Loop(vertices) => {
let sources = l.sources.iter().copied().filter(|s| exists(after, *s)).take(MAX_SOURCES).collect();
loops.push(HatchLoop { vertices, outer: l.outer, boundary_flags: l.boundary_flags, sources });
loops.push(HatchLoop { vertices, outer: l.outer, sources });
}
// An erased island: the hatch fills its area.
Refill::Erased if !l.outer => {}
+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);
}
+2 -6
View File
@@ -219,18 +219,14 @@ fn type_matches(e: &Entity, ty: Option<&str>) -> bool {
}
}
/// The candidate objects: the whole edit space (without proxies, which no selection takes in), or
/// the current selection.
/// The candidate objects: the whole edit space, or the current selection.
fn candidates(s: &Session, p: &Value) -> Result<Vec<Handle>> {
let apply = str_param(p, "applyTo").unwrap_or("drawing").to_ascii_lowercase();
if apply.starts_with("sel") || apply == "current" {
return Ok(s.selection());
}
let space = s.space();
Ok(s.doc()?
.space(&space)
.map(|st| st.iter().take(MAX_SCAN).filter(|e| !crate::select::kept_as_read(&e.kind)).map(|e| e.handle).collect())
.unwrap_or_default())
Ok(s.doc()?.space(&space).map(|st| st.iter().take(MAX_SCAN).map(|e| e.handle).collect()).unwrap_or_default())
}
fn run_qselect(s: &mut Session, p: &Value) -> Result<Value> {
-13
View File
@@ -454,19 +454,6 @@ fn printing_many_lines_is_linear() {
assert_eq!(s.log.last().map(String::as_str), Some("a"));
}
#[test]
fn lisp_pline_keeps_current_elevation() {
let mut s = session();
ok(&mut s, r#"(setvar "ELEVATION" 800.0)"#);
ok(&mut s, r#"(command "_PLINE" '(0 0) '(1000 0) '(1000 100) "")"#);
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "800.0");
ok(&mut s, r#"(setvar "ELEVATION" -2.5)"#);
s.execute("pline", &serde_json::json!({"vertices": [[0, 0], [10, 0]], "width": 2})).unwrap();
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "-2.5");
assert_eq!(ok(&mut s, "(cdr (assoc 43 (entget (entlast))))"), "2.0");
}
#[test]
fn command_draws_and_one_routine_is_one_undo_step() {
let mut s = session();
+32 -7
View File
@@ -126,14 +126,36 @@ pub fn snap_name(m: u32) -> &'static str {
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
}
/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest
/// first, then deferred snaps, then Nearest), without repeats.
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
/// 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();
}
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
let mut out: Vec<SnapHit> = crate::snap::osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen).into_iter().collect();
for h in crate::snap::osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen) {
if !out.iter().any(|o| o.same(&h, aperture)) {
out.push(h);
}
}
out
}
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
@@ -343,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,
+4 -3
View File
@@ -75,11 +75,12 @@ 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, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
/// cell): ortho does not bend the opposite corner, so the rectangle keeps its area.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub corner: bool,
/// The grip this prompt stretches (one hot grip at the STRETCH prompt), as (object, grip
+1 -1
View File
@@ -139,7 +139,7 @@ pub fn bracket() -> Drawing {
EntityKind::Hatch(Hatch {
pattern: "ANSI31".into(),
solid: false,
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, boundary_flags: None, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
+10 -18
View File
@@ -161,25 +161,19 @@ pub(crate) fn on_frozen_layer(frozen: &[String], e: &Entity) -> bool {
/// The last object of `store`, in draw order, that is not on one of the layers in `frozen`, the
/// layers frozen in the layout viewport the selection is made through: what the Last option
/// takes there. With no such layers it is the last object, whether the drawing shows it or not.
/// A proxy is passed over: no selection takes one in ([`kept_as_read`]).
pub(crate) fn last_in(store: &cadcraft_doc::EntityStore, frozen: &[String]) -> Option<Handle> {
store.iter_rev().find(|e| !kept_as_read(&e.kind) && !on_frozen_layer(frozen, e)).map(|e| e.handle)
if frozen.is_empty() {
return store.last().map(|e| e.handle);
}
store.iter().filter(|e| !on_frozen_layer(frozen, e)).last().map(|e| e.handle)
}
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]), it is not
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]) and it is not
/// on one of the layers in `frozen`, the layers frozen in the layout viewport the selection is
/// made through ([`crate::DocState::viewport_frozen`]; empty anywhere else), and commands can
/// edit it. A viewport shows model space, so `frozen` goes with a selection in model space only.
/// A proxy (or another record CADCraft keeps as it was read) is drawn and snapped to, but never
/// selected: commands can't edit it, and saving writes its record as it was read.
/// made through ([`crate::DocState::viewport_frozen`]; empty anywhere else). A viewport shows
/// model space, so `frozen` goes with a selection in model space only.
pub(crate) fn selectable(d: &Drawing, e: &Entity, frozen: &[String]) -> bool {
d.is_visible(e) && !on_frozen_layer(frozen, e) && !kept_as_read(&e.kind)
}
/// Whether `k` is a record CADCraft keeps as it was read and commands can't edit: every
/// [`EntityKind::Unknown`] but an OLE2FRAME, which moves and scales with its frame.
pub(crate) fn kept_as_read(k: &EntityKind) -> bool {
matches!(k, EntityKind::Unknown(u) if !u.is_ole_frame())
d.is_visible(e) && !on_frozen_layer(frozen, e)
}
/// Entities to test, in the order to test them, each with its bounds when already known.
@@ -605,8 +599,7 @@ mod tests {
#[test]
fn clicking_an_ole_frame_edge_selects_it() {
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
let frame =
|tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
let frame = |tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags });
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap();
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "80"), tag(20, "80")])).unwrap();
@@ -729,7 +722,7 @@ mod hatch_pattern_pick_tests {
fn square(lo: f64, hi: f64, outer: bool) -> HatchLoop {
let vertices = [(lo, lo), (hi, lo), (hi, hi), (lo, hi)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
HatchLoop { vertices, outer, sources: Vec::new() }
}
fn ansi31_hatch(loops: Vec<HatchLoop>) -> Drawing {
@@ -795,7 +788,6 @@ mod hatch_pattern_pick_tests {
let tri = HatchLoop {
vertices: [(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(),
outer: true,
boundary_flags: None,
sources: Vec::new(),
};
let d = solid_hatch(vec![tri], 0);
-1
View File
@@ -192,7 +192,6 @@ impl Session {
}
fn script_lines(&mut self, text: &str) -> Result<()> {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
for line in text.lines() {
// Trailing spaces are inputs (Enter); other trailing whitespace (`\r`) is not.
let line = line.trim_end_matches(|c: char| c.is_whitespace() && c != ' ');
+551 -208
View File
@@ -65,6 +65,24 @@ 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 if deferred, on the same
/// curve), and from the same source (this space, or one viewport). Overlapping viewports can
/// show different model points at one paper point; each stays a candidate, since DIST
/// measures in the model units of the viewport picked.
pub(crate) fn same(&self, o: &SnapHit, aperture: f64) -> bool {
self.mode == o.mode
// Deferred snaps on different curves at one provisional point stay apart: the line
// drawn from each depends on its curve.
&& self.deferred.map(|d| d.curve) == o.deferred.map(|d| d.curve)
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
&& self.point.near(o.point, aperture * 1e-6)
}
/// The command input a pick at this snap gives: a deferred snap or a plain point.
pub fn input(&self) -> crate::Input {
match self.deferred {
@@ -72,33 +90,6 @@ impl SnapHit {
None => crate::Input::Point(self.point),
}
}
fn plain(mode: u32, point: Vec2) -> SnapHit {
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None }
}
/// Where this hit sorts among the candidates near a cursor: specific snaps by distance
/// (Endpoint and Intersection favoured a little), then deferred snaps, then Nearest.
fn rank(&self, cursor: Vec2, aperture: f64) -> (u8, f64) {
let class = if self.deferred.is_some() {
1
} else if self.mode == mode::NEA {
2
} else {
0
};
(class, snap_score(self.mode, self.point, cursor, aperture))
}
/// The same snap as `o`: mode and point, from the same source (paper space, or one
/// viewport). Overlapping viewports can show different model points at one paper point;
/// each stays a candidate, since DIST measures in the model units of the viewport picked.
fn same(&self, o: &SnapHit) -> bool {
self.mode == o.mode
&& self.deferred.is_some() == o.deferred.is_some()
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
&& self.point.near(o.point, 1e-9 * (1.0 + self.point.len()))
}
}
/// The curve a deferred snap refers to.
@@ -137,12 +128,16 @@ 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();
if u == Vec2::ZERO {
vec![Circle::new(*center, *radius).closest(picked)]
// On an arc, the point within its sweep.
vec![match *self {
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(picked),
_ => Circle::new(*center, *radius).closest(picked),
}]
} else {
[*center + u * *radius, *center - u * *radius].into_iter().filter(|q| self.contains(*q)).collect()
}
@@ -229,23 +224,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)
}
/// Every object snap within `aperture` of `cursor`, the one [`osnap`] picks first and the rest
/// in the order Tab cycles them: specific snaps nearest first, then deferred snaps, then Nearest.
/// Snaps seen through layout viewports are included.
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
let ix = crate::spatial::index(d, space);
osnap_all_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred).0
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,
@@ -257,7 +263,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.
@@ -271,40 +277,21 @@ pub(crate) fn osnap_with_neighborhood(
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
let (all, prims) = osnap_all_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred);
(all.into_iter().next(), prims)
}
/// Every object snap near the cursor ([`osnap_all`]) and the local-space primitives gathered.
#[allow(clippy::too_many_arguments)]
fn osnap_all_with_neighborhood(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
) -> (Vec<SnapHit>, Option<Vec<Prim>>) {
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
return (Vec::new(), None);
return (None, None);
}
let (mut all, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
Some((hits, prims)) => (hits, Some(prims)),
None => (Vec::new(), 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 (all, near_prims);
return (best.map(|(h, _)| h), near_prims);
}
let model = Space::Model;
let model_ix = crate::spatial::index(d, &model);
// What a click picks across spaces stays as it was: each space's best snap, and a viewport's
// replaces the best so far only when it scores closer. A paper-space Nearest can therefore
// beat an Endpoint seen through a viewport, which `ranked` alone would put first.
let mut pick = all.first().copied();
for view in views {
let model_cursor = view.to_model(cursor);
let model_aperture = aperture / view.scale;
@@ -312,66 +299,49 @@ fn osnap_all_with_neighborhood(
if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) {
continue;
}
let hits = osnap_in(
d,
&model,
&model_ix,
model_cursor,
model_aperture,
osmode,
model_base,
deferred,
&view.viewport.frozen_layers,
Some(view.model_clip),
);
if let Some(hit) = hits.first().and_then(|h| view.hit(*h))
&& pick.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
let Some((cands, prims)) = collect_in(d, &model, &model_ix, model_cursor, model_aperture, osmode, &view.viewport.frozen_layers) else {
continue;
};
let clip = Some(view.model_clip);
// The rank was found in model units: paper units are model units times the scale.
let project = |(h, r): (SnapHit, Rank)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }));
let first = finish(cands.clone(), &prims, model_cursor, model_aperture, osmode, model_base, deferred, clip);
// The model clip is the box round the viewport as the model sees it, larger than the
// viewport when it is twisted: a snap inside it can still fall off the viewport. Then the
// best of the others that is on it, as Tab ranks them.
let hit = first.and_then(|f| {
project(f)
.or_else(|| finish_all(cands, &prims, model_cursor, model_aperture, osmode, model_base, deferred, clip).into_iter().find_map(project))
});
if let Some((hit, rank)) = hit
&& best.as_ref().is_none_or(|(_, b)| rank.beats(b))
{
pick = Some(hit);
}
all.extend(hits.into_iter().filter_map(|h| view.hit(h)));
}
let mut out = ranked(all, cursor, aperture);
if let Some(pick) = pick {
out.retain(|h| !h.same(&pick));
out.insert(0, pick);
}
(out, near_prims)
}
/// `hits` best first ([`SnapHit::rank`]), without repeats.
fn ranked(mut hits: Vec<SnapHit>, cursor: Vec2, aperture: f64) -> Vec<SnapHit> {
hits.sort_by(|a, b| {
let (ca, sa) = a.rank(cursor, aperture);
let (cb, sb) = b.rank(cursor, aperture);
ca.cmp(&cb).then(sa.total_cmp(&sb))
});
let mut out: Vec<SnapHit> = Vec::with_capacity(hits.len());
for h in hits {
if !out.iter().any(|o| o.same(&h)) {
out.push(h);
best = Some((hit, rank));
}
}
out
(best.map(|(h, _)| h), near_prims)
}
#[allow(clippy::too_many_arguments)]
fn osnap_in(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Vec<SnapHit> {
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default()
/// 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()
}
}
/// The snaps near the cursor in one space, best first, and the primitives gathered there.
#[allow(clippy::too_many_arguments)]
fn osnap_in_with_prims(
d: &Drawing,
@@ -384,7 +354,92 @@ fn osnap_in_with_prims(
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(Vec<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
@@ -422,8 +477,7 @@ fn osnap_in_with_prims(
}
}
}
let hits = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
Some((hits, near_prims))
Some((cands, near_prims))
}
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
@@ -467,18 +521,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>>,
@@ -535,8 +578,19 @@ fn gather_in(
Some((cands, near_prims))
}
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent
/// snaps, the deferred snaps and Nearest.
/// 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)>,
@@ -547,71 +601,192 @@ fn finish(
base: Option<Vec2>,
deferred: bool,
clip: Option<Bounds2>,
) -> Vec<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 mut hits: Vec<SnapHit> =
cands.into_iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).map(|(m, p)| SnapHit::plain(m, p)).collect();
if base.is_none() && deferred {
hits.extend(deferred_hits(near_prims, cursor, aperture, osmode, clip));
// 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 }));
}
// 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 {
hits.push(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 }));
}
}
ranked(hits, cursor, aperture)
None
}
/// [`finish`], keeping every candidate with its [`Rank`], in the order [`finish`] prefers them:
/// the snap points best first, then the perpendiculars and tangents on the objects under the
/// cursor and the centers found from their curves, then the deferred snaps, then the nearest point
/// of each object nearby.
#[allow(clippy::too_many_arguments)]
fn finish_all(
mut cands: Vec<(u32, Vec2)>,
near_prims: &[Prim],
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. From the centre, the point of
// the arc under the cursor.
Prim::Seg(Segment::Arc { arc, .. }) => {
SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end }.perpendiculars(bp, cursor)
}
// Both antipodes too, so a pick on the far side of the circle snaps there
// rather than across it. From the centre every point is perpendicular: the
// one under the cursor.
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius }.perpendiculars(bp, cursor),
Prim::Infinite { base: b0, dir, .. } => vec![*b0 + *dir * (bp - *b0).dot(*dir)],
Prim::Ellipse(e) => curves::ellipse_perpendiculars(e, bp),
Prim::Spline(s) => curves::spline_perpendiculars(s, bp),
_ => Vec::new(),
};
found(mode::PER, pts);
}
if osmode & mode::TAN != 0 {
let pts = match p {
// A deferred prompt resolves tangents to circles and arcs itself.
Prim::Seg(Segment::Arc { .. }) | Prim::Circle(_) if deferred => Vec::new(),
// Only the tangent points that lie on the arc itself (not its circle).
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
.tangent_points(bp)
.into_iter()
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
.collect(),
Prim::Circle(c) => c.tangent_points(bp),
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
Prim::Spline(s) => curves::spline_tangents(s, bp),
_ => Vec::new(),
};
found(mode::TAN, pts);
}
}
from_base
}
/// Center, as in AutoCAD: with the cursor over a circle, an arc (also a polyline's) or an
/// ellipse, the running Center snap finds its center however far away it is. Each center comes
/// with how far the curve is from `cursor` (its score); [`finish`] tries them only when no snap
/// point is in the aperture. Empty unless Center is among `osmode`.
fn curve_centers(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32) -> Vec<(f64, Vec2)> {
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
}
/// Prefer more specific modes when nearly equidistant.
@@ -619,6 +794,61 @@ 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 {
// A ray runs one way from its start (an xline both ways, as its segment does).
if let Prim::Infinite { base, dir, ray: true } = p {
return (*base + *dir * (cursor - *base).dot(*dir).max(0.0)).dist(cursor);
}
prim_segments(p).iter().map(|s| fix_circle(s).closest(cursor).dist(cursor)).fold(f64::INFINITY, f64::min)
}
/// Upper bound on the block-reference objects one snap query looks at (hostile files).
const MAX_BLOCK_LEAVES: usize = 20_000;
@@ -917,11 +1147,15 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
}
}
/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and
/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the
/// perpendicular on the same circle.
/// 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 },
@@ -954,6 +1188,45 @@ fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip:
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;
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,
};
let (m, name, at) = match curve {
SnapCurve::Circle { center, radius } if osmode & mode::TAN != 0 => {
(mode::TAN, "Deferred Tangent", Circle::new(center, radius).closest(cursor))
}
SnapCurve::Circle { center, radius } if osmode & mode::PER != 0 => {
(mode::PER, "Deferred Perpendicular", Circle::new(center, radius).closest(cursor))
}
SnapCurve::Arc { center, radius, start, end } if osmode & mode::TAN != 0 => {
(mode::TAN, "Deferred Tangent", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
}
SnapCurve::Arc { center, radius, start, end } if osmode & mode::PER != 0 => {
(mode::PER, "Deferred Perpendicular", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
}
SnapCurve::Line { a, b } if osmode & mode::PER != 0 => {
// Pick on the drawn extent: a segment's own span, an xline/ray anywhere.
let l = cadcraft_geom::Line::new(a, b);
(mode::PER, "Deferred Perpendicular", if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) })
}
_ => continue,
};
let dd = at.dist(cursor);
if at.is_finite() && clip.is_none_or(|c| c.contains(at)) && dd <= aperture && best.is_none_or(|(bd, _)| dd < bd) {
best = Some((dd, SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) }));
}
}
best.map(|(_, h)| h)
}
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
/// endpoints (in the order given), or `None` when there is no such line (a point inside the
/// circle it should be tangent to, concentric circles, non-parallel lines both perpendicular to
@@ -1188,21 +1461,22 @@ mod tests {
assert_eq!(h.name, "Intersection");
}
/// Tab cycling sees every snap within the aperture: specific snaps nearest first (Intersection
/// favoured), then deferred snaps, then Nearest, and no snap twice; the first is what `osnap`
/// picks.
/// Tab cycling sees every snap within the aperture: snap points nearest first (Intersection
/// favoured), then Nearest on each object, and no snap twice; the first is what `osnap` picks.
/// 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 modes = mode::END | mode::MID | mode::INT | mode::NEA;
let all = osnap_all(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false);
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA], "{all:?}");
assert_eq!(all[0].point, osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false).unwrap().point);
// On the circle: its quadrant, then the deferred tangent and perpendicular at the same spot.
let (cursor, modes) = (Vec2::new(5.2, 0.2), mode::END | mode::MID | mode::INT | mode::NEA);
let all = osnap_all(&d, &Space::Model, cursor, 0.5, modes, None, false);
// Both lines' midpoints are the intersection point: one Midpoint. Each line has its Nearest.
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA, mode::NEA], "{all:?}");
assert_eq!(all.first().map(|h| h.point), osnap(&d, &Space::Model, cursor, 0.5, modes, None, false).map(|h| h.point));
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
let 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, modes, None, false).is_empty());
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, mode::QUA | mode::TAN | mode::PER, None, true).is_empty());
}
#[test]
@@ -1221,6 +1495,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));
@@ -1263,9 +1601,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
-53
View File
@@ -746,15 +746,6 @@ fn script_runs_commands() {
assert!(matches!(&t.kind, EntityKind::Text(t) if t.value == "Hello world"));
}
#[test]
fn scripts_allow_one_leading_utf8_bom() {
for text in ["\u{feff}LINE 0,0 10,10\n\n", "\u{feff}; first comment\r\nLINE 0,0 10,10\r\n\r\n"] {
let mut s = Session::new();
s.script(text).unwrap();
assert_eq!(kinds(&s), vec!["Line"]);
}
}
#[test]
fn script_splits_line_at_keyword_prompt() {
let mut s = Session::new();
@@ -1561,50 +1552,6 @@ fn setvar_rejects_non_finite_text_for_real_variables() {
}
}
#[test]
fn a_proxy_is_drawn_but_no_selection_takes_it_in() {
// A proxy's graphics are drawn and measured, but saving writes its record unchanged: an edit
// could not hold. So a window round a line and a proxy, ALL, SELECTALL and a pick on the
// proxy's graphics leave the proxy out, and MOVE moves the line alone.
use cadcraft_doc::{Common, Entity, Handle, Line, Space, Unknown, entity_bounds};
use cadcraft_geom::Vec3;
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let line = s.doc().unwrap().model.last().unwrap().handle;
let drawn = Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(0.0, 5.0, 0.0), b: Vec3::new(10.0, 5.0, 0.0) }));
let unknown = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: vec![drawn] };
let proxy = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Unknown(unknown)).unwrap();
let bounds = |s: &Session| entity_bounds(s.doc().unwrap(), s.doc().unwrap().entity(proxy).unwrap(), 0);
let before = bounds(&s);
assert!(!before.is_empty(), "the proxy measures as its graphics");
s.idle_click(Vec2::new(5.0, 5.0), false).unwrap();
assert_eq!(s.selection(), Vec::<Handle>::new(), "a pick on the proxy's graphics");
s.idle_click(Vec2::new(-1.0, -1.0), false).unwrap();
s.idle_click(Vec2::new(11.0, 6.0), false).unwrap();
assert_eq!(s.selection(), vec![line], "a window round both");
s.execute("selectall", &json!({})).unwrap();
assert_eq!(s.selection(), vec![line], "SELECTALL");
s.execute("move", &json!({"delta": [0, 20]})).unwrap();
let d = s.doc().unwrap();
assert!(matches!(&d.entity(line).unwrap().kind, EntityKind::Line(l) if l.a.y == 20.0), "the line moved");
assert_eq!(bounds(&s), before, "the proxy stayed where its record puts it");
// Handles named outright leave the proxy out too.
s.execute("select", &json!({"handles": [proxy.hex(), line.hex()]})).unwrap();
assert_eq!(s.selection(), vec![line], "SELECT by handles");
// Last passes over the proxy drawn last: it takes the line.
s.set_selection(Vec::new());
s.start("erase").unwrap();
s.input(Input::Text("L".into())).unwrap();
s.input(Input::Enter).unwrap();
let d = s.doc().unwrap();
assert!(d.entity(line).is_none(), "Last took the line");
assert!(d.entity(proxy).is_some(), "the proxy is kept");
}
#[test]
fn additional_tools_keeps_compatible_command_ids() {
assert_eq!(crate::cmd::resolve_alias("-blockreplace"), "blockreplace");
+1 -24
View File
@@ -144,26 +144,6 @@ fn moving_or_copying_the_hatch_alone_ends_the_link() {
assert!(!hatch(&s, &h).associative);
}
#[test]
fn imported_boundary_flags_survive_refill_and_copy() {
let mut session = Session::new();
let boundary = handle(&session.execute("rectang", &json!({ "p1": [0, 0], "p2": [4, 2] })).unwrap());
let hatch_handle = handle(&session.execute("hatch", &json!({ "handles": [boundary.clone()] })).unwrap());
session.doc_mut().unwrap().model.modify(Handle::parse_hex(&hatch_handle).unwrap(), |entity| {
if let EntityKind::Hatch(hatch) = &mut entity.kind {
hatch.loops[0].boundary_flags = Some(7);
}
});
let expected = hatch(&session, &hatch_handle).loops[0].boundary_flags;
session.execute("move", &json!({ "handles": [boundary], "delta": [10, 0] })).unwrap();
assert_eq!(hatch(&session, &hatch_handle).loops[0].boundary_flags, expected);
let count = session.doc().unwrap().model.len();
session.execute("copy", &json!({ "handles": [hatch_handle], "delta": [30, 0] })).unwrap();
let copy = session.doc().unwrap().model.iter().skip(count).find(|entity| matches!(entity.kind, EntityKind::Hatch(_))).unwrap();
let EntityKind::Hatch(copied) = &copy.kind else { panic!("not a hatch") };
assert_eq!(copied.loops[0].boundary_flags, expected);
}
#[test]
fn non_associative_hatch_keeps_no_sources() {
let mut s = Session::new();
@@ -186,10 +166,7 @@ fn hostile_sources_never_panic() {
let k = EntityKind::Hatch(Hatch {
pattern: "ANSI31".into(),
solid: false,
loops: vec![
HatchLoop { vertices: sq, outer: true, boundary_flags: None, sources: sources.clone() },
HatchLoop { vertices: nan, outer: false, boundary_flags: None, sources },
],
loops: vec![HatchLoop { vertices: sq, outer: true, sources: sources.clone() }, HatchLoop { vertices: nan, outer: false, sources }],
scale: 1.0,
angle: 0.0,
associative: true,
+3 -1
View File
@@ -106,7 +106,6 @@ mod mocoro;
mod modify_curves;
mod mtext_columns;
mod mtext_options;
mod mtext_ortho;
mod multiline_attributes;
mod named_viewports;
mod named_views;
@@ -116,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;
@@ -158,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,7 +1,8 @@
//! 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::pointmod::snap_candidates;
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
use cadcraft_engine::{Input, Session};
use serde_json::json;
@@ -278,22 +279,22 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
}
/// Across spaces a click keeps the snap it had before Tab cycling: a viewport's best snap
/// replaces paper space's only when it scores closer. Tab still reaches the other one.
/// 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_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() {
fn a_viewport_endpoint_beats_a_closer_paper_space_nearest() {
let (mut d, paper) = drawing();
// 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_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}");
assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}");
let all = osnap_all(&d, &paper, cursor, 0.5, modes, None, false);
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::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)),
"Tab reaches the viewport's endpoint: {all:?}"
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:?}"
);
}
@@ -429,3 +430,50 @@ fn malformed_and_paper_space_viewports_are_not_snap_sources() {
assert!(osnap(&d, &paper, Vec2::new(95.1, 50.1), 0.5, mode::END, None, false).is_none());
}
}
/// Nearest on a curve that leaves the viewport: the curve's closest point to the cursor is outside
/// the viewport, another point of it within the aperture is inside, and Nearest snaps there.
#[test]
fn nearest_takes_the_visible_part_of_a_curve_crossing_the_viewport_edge() {
let (mut d, paper) = drawing();
// The viewport shows model y up to 20. A tall ellipse peaks at (15, 20.1), just outside.
let ellipse = Ellipse { center: Vec3::new(15.0, 0.0, 0.0), major: Vec3::new(0.0, 20.1, 0.0), ratio: 0.1, start: 0.0, end: std::f64::consts::TAU };
d.add(&Space::Model, Common::default(), EntityKind::Ellipse(ellipse)).unwrap();
// The viewport's border is on a layer that is off, so it offers no Nearest of its own.
d.layers.push(cadcraft_engine::doc::Layer { name: "Border".into(), on: false, ..Default::default() });
let vp = viewport(&d, &paper);
d.modify_entity(vp, |e| e.common.layer = "Border".into()).unwrap();
// Model (15, 19.99): 0.11 from the peak, about 0.2 from where the ellipse comes back inside.
let cursor = Vec2::new(102.5, 59.995);
let hit = osnap(&d, &paper, cursor, 0.5, mode::NEA, None, false).expect("a visible nearest point");
let model = hit.viewport.expect("seen through the viewport").point;
assert!(model.y <= 20.0 + 1e-9 && model.dist(Vec2::new(15.0, 19.99)) <= 1.0, "{hit:?}");
}
#[test]
fn a_twisted_viewport_offers_the_visible_perpendicular_when_a_nearer_one_is_off_the_sheet() {
// A viewport twisted 45°, 20 square at 0,0 on the sheet, scale 1. Through it, a line along
// y = 0 under the cursor and one along x = 9.3 (sheet coordinates). From the base 12,3 the
// foot on the first, 12,0, is inside the turned model box but off the viewport; the foot on
// the second, 9.3,3, is on it.
let mut d = Drawing::new_imperial();
let paper = Space::Paper("Layout1".into());
let vp = Viewport {
center: Vec3::ZERO,
width: 20.0,
height: 20.0,
view_center: Vec2::ZERO,
view_height: 20.0,
id: 2,
twist: std::f64::consts::FRAC_PI_4,
..Viewport::default()
};
for (a, b) in [(Vec2::new(-9.0, 0.0), Vec2::new(30.0, 0.0)), (Vec2::new(9.3, -9.0), Vec2::new(9.3, 9.0))] {
let (a, b) = (vp.paper_to_model(a), vp.paper_to_model(b));
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })).unwrap();
}
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
let hit = osnap(&d, &paper, Vec2::new(9.0, 0.0), 0.5, mode::PER, Some(Vec2::new(12.0, 3.0)), false).expect("the visible foot");
assert_eq!(hit.mode, mode::PER);
assert!(hit.point.near(Vec2::new(9.3, 3.0), 1e-9), "{hit:?}");
}
-157
View File
@@ -1,157 +0,0 @@
//! MTEXT's opposite corner ignores ortho: the text box keeps its width and proportion (#3388).
use cadcraft_doc::{EntityKind, MText};
use cadcraft_engine::snap::tracking::CursorQuery;
use cadcraft_engine::{Input, Session};
use cadcraft_geom::{Bounds2, Vec2};
use serde_json::json;
/// Move the cursor to `raw` at the current prompt, as the canvas does.
fn hover(s: &mut Session, raw: Vec2) -> Vec2 {
let p = s.current_prompt().unwrap();
let q = CursorQuery { base: p.base, deferred: p.deferred, corner: p.corner, aperture: 1e-6, tol: 1e-6, now: 0.0, shift: false };
let c = s.snap_cursor(raw, &q).point;
s.cursor = c;
c
}
fn session(ortho: bool) -> Session {
let mut s = Session::new();
s.execute("setvar", &json!({ "name": "OSMODE", "value": 0 })).unwrap();
s.execute("setvar", &json!({ "name": "ORTHOMODE", "value": i32::from(ortho) })).unwrap();
s
}
fn last_mtext(s: &Session) -> MText {
match s.doc().unwrap().model.last().map(|e| e.kind.clone()) {
Some(EntityKind::MText(t)) => t,
k => panic!("no mtext: {k:?}"),
}
}
/// Place an MTEXT from `first` to a cursor click at `second`, returning the preview bounds,
/// in-place editor box `(insert, width)` and created entity `(insert, width)`.
fn click_mtext(ortho: bool, first: Vec2, second: Vec2) -> ((Vec2, Vec2), (Vec2, f64), (Vec2, f64)) {
let mut s = session(ortho);
s.cmdline(&format!("mtext {},{}", first.x, first.y)).unwrap();
let p = s.current_prompt().unwrap();
assert_eq!(p.message, "Specify opposite corner");
assert!(p.corner, "MTEXT opposite corner ignores ortho");
let c = hover(&mut s, second);
assert!(c.near(second, 1e-9), "opposite corner stays under the cursor: {c:?}");
let mut pv = Bounds2::EMPTY;
for e in s.preview(c) {
pv = pv.union(&cadcraft_doc::entity_bounds(s.doc().unwrap(), &e, 0));
}
s.input(Input::Point(c)).unwrap();
let ed = s.editing_mtext().unwrap();
s.input(Input::Text("Hello".to_string())).unwrap();
s.input(Input::Enter).unwrap();
assert!(s.current_prompt().is_none(), "MTEXT is done, still at {:?}", s.current_prompt().map(|p| p.message));
let t = last_mtext(&s);
assert_eq!(t.contents, "Hello");
((pv.min, pv.max), (ed.insert.xy(), ed.width), (t.insert.xy(), t.width))
}
#[test]
fn mtext_opposite_corner_ignores_ortho() {
let cases = [
// Wide box (dx > dy)
(Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::new(0.0, 3.0), 10.0),
// Tall box (dy > dx)
(Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::new(0.0, 10.0), 3.0),
// Opposite quadrant (negative dx and dy)
(Vec2::new(10.0, 10.0), Vec2::new(2.0, 4.0), Vec2::new(2.0, 4.0), Vec2::new(10.0, 10.0), Vec2::new(2.0, 10.0), 8.0),
];
for (first, second, min, max, insert, width) in cases {
let on = click_mtext(true, first, second);
assert!(on.0.0.near(min, 1e-9) && on.0.1.near(max, 1e-9), "preview bounds with ortho on: {:?}", on.0);
assert!(on.1.0.near(insert, 1e-9) && (on.1.1 - width).abs() < 1e-9, "editor box with ortho on: {:?}", on.1);
assert!(on.2.0.near(insert, 1e-9) && (on.2.1 - width).abs() < 1e-9, "entity box with ortho on: {:?}", on.2);
let off = click_mtext(false, first, second);
assert_eq!(off, on, "ortho changes nothing");
}
}
#[test]
fn mtext_coordinate_and_direct_distance_input_with_ortho() {
let mut s = session(true);
// Absolute coordinate input for the opposite corner.
s.cmdline("mtext 0,0").unwrap();
s.cmdline("10,3").unwrap();
let ed = s.editing_mtext().unwrap();
assert!(ed.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9));
assert!((ed.width - 10.0).abs() < 1e-9);
s.input(Input::Text("Abs".to_string())).unwrap();
s.input(Input::Enter).unwrap();
let t = last_mtext(&s);
assert!(t.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9));
assert!((t.width - 10.0).abs() < 1e-9);
// Relative coordinate input for the opposite corner.
s.cmdline("mtext 2,3").unwrap();
s.cmdline("@4,9").unwrap();
let ed = s.editing_mtext().unwrap();
assert!(ed.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9));
assert!((ed.width - 4.0).abs() < 1e-9);
s.input(Input::Text("Rel".to_string())).unwrap();
s.input(Input::Enter).unwrap();
let t = last_mtext(&s);
assert!(t.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9));
assert!((t.width - 4.0).abs() < 1e-9);
// Direct distance entry goes toward the cursor rather than along an axis.
s.cmdline("mtext 0,0").unwrap();
let c = hover(&mut s, Vec2::new(3.0, 4.0));
assert!(c.near(Vec2::new(3.0, 4.0), 1e-9));
s.cmdline("5").unwrap();
let ed = s.editing_mtext().unwrap();
assert!(ed.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9));
assert!((ed.width - 3.0).abs() < 1e-9);
s.input(Input::Text("Dir".to_string())).unwrap();
s.input(Input::Enter).unwrap();
let t = last_mtext(&s);
assert!(t.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9));
assert!((t.width - 3.0).abs() < 1e-9);
}
#[test]
fn mtext_escape_cancels_cleanly_with_ortho() {
let mut s = session(true);
// Cancel at the opposite-corner prompt.
s.cmdline("mtext 0,0").unwrap();
let c = hover(&mut s, Vec2::new(10.0, 3.0));
assert!(c.near(Vec2::new(10.0, 3.0), 1e-9));
s.cancel();
assert!(s.current_prompt().is_none());
assert!(s.editing_mtext().is_none());
assert!(s.doc().unwrap().model.is_empty());
// Cancel after picking the opposite corner (at the text prompt).
s.cmdline("mtext 0,0").unwrap();
let c = hover(&mut s, Vec2::new(10.0, 3.0));
s.input(Input::Point(c)).unwrap();
assert!(s.editing_mtext().is_some());
s.cancel();
assert!(s.current_prompt().is_none());
assert!(s.editing_mtext().is_none());
assert!(s.doc().unwrap().model.is_empty());
}
#[test]
fn line_and_pline_still_obey_ortho() {
let mut s = session(true);
s.cmdline("line 0,0").unwrap();
let p = s.current_prompt().unwrap();
assert!(!p.corner, "LINE next point is constrained by ortho");
let c = hover(&mut s, Vec2::new(10.0, 3.0));
assert!(c.near(Vec2::new(10.0, 0.0), 1e-9), "ortho keeps LINE horizontal: {c:?}");
s.cancel();
s.cmdline("pline 0,0").unwrap();
let p = s.current_prompt().unwrap();
assert!(!p.corner, "PLINE next point is constrained by ortho");
let c = hover(&mut s, Vec2::new(3.0, 10.0));
assert!(c.near(Vec2::new(0.0, 10.0), 1e-9), "ortho keeps PLINE vertical: {c:?}");
s.cancel();
}
@@ -0,0 +1,116 @@
//! Running object snaps in a fresh drawing and in drawings opened from DXF and DWG files, with
//! AutoCAD's default modes (OSMODE 4133: Endpoint, Center, Intersection, Extension).
//!
//! Moving onto a circle, an arc or a polyline arc finds its Center. OSMODE is a profile setting,
//! as in AutoCAD (saved in the registry there, not the drawing): a file's `$OSMODE` header
//! variable, 0 included, never changes the running snaps.
use cadcraft_engine::Session;
use cadcraft_engine::doc::Drawing;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::snap::{mode, tracking::CursorQuery};
use serde_json::json;
/// AutoCAD's default running snaps.
const DEFAULT: u32 = 4133;
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
let a = deg.to_radians();
c + Vec2::new(r * a.cos(), r * a.sin())
}
/// A line crossed by another, a circle, an arc and a polyline with a straight and an arc segment.
fn draw(s: &mut Session) {
s.execute("line", &json!({ "points": [[0, 0], [20, 0]] })).unwrap();
s.execute("line", &json!({ "points": [[5, -5], [5, 5]] })).unwrap();
s.execute("circle", &json!({ "center": [50, 0], "radius": 5 })).unwrap();
s.execute("arc", &json!({ "center": [80, 0], "radius": 5, "start": 0, "end": 180 })).unwrap();
// 100,0 to 110,0 straight, then a half circle (bulge 1) to 130,0 round 120,0, below the axis.
s.execute("pline", &json!({ "vertices": [[100, 0], {"p": [110, 0], "bulge": 1.0}, [130, 0]] })).unwrap();
}
fn drawing() -> Drawing {
let mut s = Session::new();
draw(&mut s);
s.doc().unwrap().clone()
}
/// Where a click at `cursor` lands while LINE asks for its first point (the drawing area's path).
fn snap(s: &mut Session, cursor: Vec2) -> Option<(Vec2, u32)> {
if s.running.is_none() {
s.start("line").unwrap();
}
let q = CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
let r = s.snap_cursor(cursor, &q);
r.snap.map(|h| (r.point, h.mode))
}
fn assert_snaps(s: &mut Session, what: &str) {
assert_eq!(s.settings.osmode, DEFAULT, "{what}: the running snaps are the profile's");
let cases = [
("the line's end", Vec2::new(20.2, 0.1), Vec2::new(20.0, 0.0), &[mode::END][..]),
("the lines' crossing", Vec2::new(5.2, 0.15), Vec2::new(5.0, 0.0), &[mode::INT][..]),
("the circle", polar(Vec2::new(50.0, 0.0), 5.3, 45.0), Vec2::new(50.0, 0.0), &[mode::CEN][..]),
("the arc", polar(Vec2::new(80.0, 0.0), 5.2, 90.0), Vec2::new(80.0, 0.0), &[mode::CEN][..]),
("the arc's end", Vec2::new(85.2, 0.1), Vec2::new(85.0, 0.0), &[mode::END][..]),
("the polyline's vertex", Vec2::new(110.2, 0.1), Vec2::new(110.0, 0.0), &[mode::END][..]),
("the polyline's arc", polar(Vec2::new(120.0, 0.0), 10.2, 270.0), Vec2::new(120.0, 0.0), &[mode::CEN][..]),
];
for (name, cursor, want, modes) in cases {
let (p, m) = snap(s, cursor).unwrap_or_else(|| panic!("{what}: no snap on {name}"));
assert!(modes.contains(&m), "{what}, {name}: mode {m}");
assert!(p.near(want, 1e-6), "{what}, {name}: {p:?}");
}
// Away from everything: nothing.
assert_eq!(snap(s, Vec2::new(35.0, 20.0)), None, "{what}");
// F3 off: nothing; on again: back.
s.execute("osnap", &json!({})).unwrap();
assert_eq!(snap(s, Vec2::new(20.2, 0.1)), None, "{what}: F3 off");
s.execute("osnap", &json!({})).unwrap();
assert_eq!(snap(s, Vec2::new(20.2, 0.1)).map(|h| h.1), Some(mode::END), "{what}: F3 on");
}
#[test]
fn default_snaps_work_in_a_fresh_drawing() {
let mut s = Session::new();
draw(&mut s);
assert_snaps(&mut s, "fresh drawing");
}
/// `text` with `$OSMODE` set to `value` at the top of its header.
fn with_osmode(text: &str, value: u32) -> String {
let at = text.find("HEADER").expect("a header section") + "HEADER".len();
let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
let (head, tail) = text.split_at(at);
format!("{head}{eol} 9{eol}$OSMODE{eol} 70{eol}{value}{tail}")
}
#[test]
fn a_dxf_with_osmode_0_keeps_the_running_snaps() {
let clean = String::from_utf8(cadcraft_io::write(&drawing(), "snaps.dxf").unwrap()).unwrap();
let text = with_osmode(&clean, 0);
let d = cadcraft_io::read(text.as_bytes(), "snaps.dxf").unwrap();
let mut s = Session::new();
// OSMODE is the profile's: the user's own choice survives opening the file.
s.execute("setvar", &json!({ "name": "OSMODE", "value": DEFAULT })).unwrap();
s.open_drawing(d, "snaps.dxf", None);
assert_snaps(&mut s, "DXF with $OSMODE 0");
// Nor does a file change a profile without Center.
let mut s = Session::new();
s.execute("setvar", &json!({ "name": "OSMODE", "value": mode::END })).unwrap();
let text = with_osmode(&clean, DEFAULT);
assert_eq!(text.matches("$OSMODE").count(), 1, "one $OSMODE in the file");
s.open_drawing(cadcraft_io::read(text.as_bytes(), "x.dxf").unwrap(), "x.dxf", None);
assert_eq!(s.settings.osmode, mode::END);
}
#[test]
fn default_snaps_work_in_a_drawing_opened_from_dwg() {
// The drawing is the test's own, so it is converted in this process.
cadcraft_io::dwg_worker::allow_in_process();
let bytes = cadcraft_io::write(&drawing(), "snaps.dwg").unwrap();
let d = cadcraft_io::read(&bytes, "snaps.dwg").unwrap();
let mut s = Session::new();
s.open_drawing(d, "snaps.dwg", None);
assert_snaps(&mut s, "DWG");
}
@@ -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());
}
+28
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");
@@ -119,3 +122,28 @@ fn spline_midpoint_perpendicular_and_tangent() {
let d = (sp.eval(i + 1e-6) - sp.eval(i - 1e-6)).normalized();
assert!(d.cross((q - base).normalized()).abs() < 1e-3, "the line from the base runs along the curve at {q:?}");
}
#[test]
fn perpendicular_from_an_arcs_center_stays_on_the_arc() {
// From the center of an arc every point is perpendicular: the one under the cursor, never a
// point of its circle outside the sweep.
let mut s = Session::new();
s.execute("arc", &serde_json::json!({"center": [0, 0], "radius": 10, "start": 90, "end": 180})).unwrap();
let hit = snap::osnap(s.doc().unwrap(), &Space::Model, Vec2::new(-6.0, 8.0), 0.3, mode::PER, Some(Vec2::ZERO), false);
let (p, m) = hit.map(|h| (h.point, h.mode)).expect("a perpendicular on the arc");
assert_eq!(m, mode::PER);
assert!(p.near(Vec2::new(-6.0, 8.0), 1e-9), "{p:?}");
}
#[test]
fn perpendicular_to_a_ray_needs_the_cursor_on_the_ray() {
// A ray along +X from the origin: behind its start the cursor is over nothing.
let mut s = Session::new();
s.execute("ray", &serde_json::json!({"base": [0, 0], "through": [10, 0]})).unwrap();
let d = s.doc().unwrap();
let base = Some(Vec2::new(5.0, 3.0));
assert_eq!(snap::osnap(d, &Space::Model, Vec2::new(-2.0, 0.0), 0.5, mode::PER, base, false), None);
// Over the ray, the foot is found.
let hit = snap::osnap(d, &Space::Model, Vec2::new(2.0, 0.0), 0.5, mode::PER, base, false).expect("the foot on the ray");
assert!(hit.point.near(Vec2::new(5.0, 0.0), 1e-9), "{hit:?}");
}
+122
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,97 @@ 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);
}
#[test]
fn tan_for_a_3p_circle_through_points_in_line_with_the_picked_circles_center() {
// Through 3,0 and 5,0 and tangent to the unit circle at the origin: the two points and that
// circle's center lie on one line, the circle that touches it does not (center 4,±√48, radius 7).
let mut s = Session::new();
s.script("CIRCLE 0,0 1\nCIRCLE 3P 3,0 5,0 TAN 1,0\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let (c, r) = last_circle(&s);
assert!(near(Vec2::new(c.x, c.y.abs()), 4.0, 48f64.sqrt()) && (r - 7.0).abs() < 1e-9, "{c:?} r={r}");
}
+102
View File
@@ -0,0 +1,102 @@
//! Tab cycling through object snaps: a crowd of candidates is capped, hostile cursors and
//! apertures give no candidates, and the list never repeats a snap.
use cadcraft_engine::Session;
use cadcraft_engine::doc::Space;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::mode;
use serde_json::json;
#[test]
fn a_crowd_of_snaps_is_capped_and_never_repeats() {
let mut s = Session::new();
// 600 short lines fanning out from points packed round the origin: 1,200 endpoints.
for i in 0..600 {
let a = f64::from(i) * 0.01;
let p = [1e-3 * a.cos(), 1e-3 * a.sin()];
s.execute("line", &json!({ "points": [p, [a.cos(), a.sin()]] })).unwrap();
}
let d = s.doc().unwrap();
let cands = snap_candidates(d, &Space::Model, Vec2::ZERO, 0.5, mode::END | mode::INT | mode::NEA, None, false);
assert!(!cands.is_empty());
assert!(cands.len() <= 257, "{} candidates", cands.len());
for (i, a) in cands.iter().enumerate() {
assert!(a.point.is_finite());
assert!(!cands.iter().skip(i + 1).any(|b| b.mode == a.mode && b.point == a.point), "{a:?} repeats");
}
}
#[test]
fn hostile_cursor_and_aperture_give_no_candidates() {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
let d = s.doc().unwrap();
let space = Space::Model;
let all = mode::END | mode::MID | mode::INT | mode::NEA | mode::PER;
for (c, ap) in [
(Vec2::new(f64::NAN, 0.0), 0.5),
(Vec2::new(0.0, f64::INFINITY), 0.5),
(Vec2::ZERO, f64::NAN),
(Vec2::ZERO, 0.0),
(Vec2::ZERO, -1.0),
(Vec2::ZERO, f64::INFINITY),
] {
assert!(snap_candidates(d, &space, c, ap, all, None, false).is_empty(), "{c:?} {ap}");
assert!(snap_candidates(d, &space, c, ap, all, Some(Vec2::new(f64::NAN, 1.0)), true).is_empty(), "{c:?} {ap}");
}
// A huge but finite aperture still answers, from the objects there are.
let far = snap_candidates(d, &space, Vec2::ZERO, 1e300, mode::END, None, false);
assert!(far.iter().all(|h| h.point.is_finite()));
// Object snaps off (or only the OFF bit) offer nothing.
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, 0, None, false).is_empty());
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, mode::END | mode::OFF, None, false).is_empty());
}
#[test]
fn every_endpoint_under_the_aperture_is_offered_not_one_per_mode() {
let mut s = Session::new();
// Three line ends close together, all within the aperture of the cursor between them.
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
s.execute("line", &json!({ "points": [a, b] })).unwrap();
}
let d = s.doc().unwrap();
let cands = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false);
let ends: Vec<Vec2> = cands.iter().filter(|h| h.mode == mode::END).map(|h| h.point).collect();
assert_eq!(ends.len(), 3, "{cands:?}");
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
assert!(ends.iter().any(|p| p.near(want, 1e-12)), "{want:?} in {ends:?}");
}
// The first is the snap a click would take.
let first = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).first().map(|h| h.point);
assert_eq!(first, cadcraft_engine::snap::osnap(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).map(|h| h.point));
}
/// A base point that is not a number gives no candidates, though the cursor is on an endpoint: the
/// perpendicular and tangent points from it would be meaningless, as a viewport already treats it.
#[test]
fn a_non_finite_base_gives_no_candidates() {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
let d = s.doc().unwrap();
let all = mode::END | mode::PER | mode::TAN | mode::NEA;
for base in [Vec2::new(f64::NAN, 1.0), Vec2::new(1.0, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NAN)] {
assert!(snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), false).is_empty(), "{base:?}");
assert!(cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), true).is_empty(), "{base:?}");
}
// A finite base still offers them.
assert!(!snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(Vec2::new(5.0, 5.0)), false).is_empty());
}
#[test]
fn deferred_snaps_of_two_curves_at_one_point_are_both_offered() {
// Two circles touching at the origin: each offers its own deferred tangent there, and the
// line drawn from it depends on which circle it is.
let mut s = Session::new();
s.script("CIRCLE 0,1 1\nCIRCLE 0,-2 2\n").unwrap();
let d = s.doc().unwrap();
let all = cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(0.0, 0.1), 0.5, mode::TAN, None, true);
let curves: Vec<_> = all.iter().filter_map(|h| h.deferred.map(|f| f.curve)).collect();
assert_eq!(curves.len(), 2, "{all:?}");
assert_ne!(curves.first(), curves.get(1), "{all:?}");
}
+5 -12
View File
@@ -9,11 +9,8 @@ use serde_json::json;
fn session() -> (Session, String) {
let tag = |code: i32, v: &str| RawTag { code, value: v.into() };
let mut d = Drawing::new_imperial();
let kind = EntityKind::Unknown(Unknown {
dxf_type: "OLE2FRAME".into(),
tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")],
graphics: Vec::new(),
});
let kind =
EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")] });
let h = d.add(&Space::Model, Common::default(), kind).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "ole.dxf", None);
@@ -78,8 +75,7 @@ fn data_session(chunks: &[usize], hex_override: Option<&str>) -> (Session, Strin
tags.push(tag(310, &hex[at..]));
}
let mut d = Drawing::new_imperial();
let h =
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() })).unwrap();
let h = d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags })).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "ole.dxf", None);
(s, h.hex())
@@ -164,11 +160,8 @@ fn a_locked_ole_frame_does_not_block_an_in_place_rotation() {
let mut d = Drawing::new_imperial();
d.ensure_layer("L");
let common = Common { layer: "L".into(), ..Common::default() };
let kind = EntityKind::Unknown(Unknown {
dxf_type: "OLE2FRAME".into(),
tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")],
graphics: Vec::new(),
});
let kind =
EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")] });
let ole = d.add(&Space::Model, common, kind).unwrap();
if let Some(l) = d.layer_mut("L") {
l.locked = true;
@@ -22,7 +22,6 @@ fn install() {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
}
/// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes.
@@ -88,35 +87,6 @@ fn not_saved(r: &Value) -> Value {
r.get("notSaved").cloned().unwrap_or(Value::Null)
}
#[test]
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
fn legacy_visualstyles_warn_only_for_2007_dwg() {
install();
cadcraft_io::dwg_worker::allow_in_process();
let source = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1021\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n30\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n30\n0\n11\n10\n21\n5\n31\n0\n0\nENDSEC\n\
0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_VISUALSTYLE\n350\n20\n\
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nSynthetic\n350\n21\n\
0\nVISUALSTYLE\n5\n21\n330\n20\n100\nAcDbVisualStyle\n2\nSynthetic\n70\n0\n71\n1\n72\n1\n73\n1\n90\n0\n40\n1.0\n41\n0.5\n63\n7\n\
74\n2\n91\n0\n64\n7\n65\n7\n75\n1\n175\n1\n42\n30.0\n92\n0\n66\n7\n43\n1.0\n76\n1\n77\n0\n78\n0\n67\n7\n79\n1\n\
170\n0\n171\n0\n290\n0\n174\n0\n93\n0\n44\n0.0\n173\n0\n291\n0\n0\nENDSEC\n0\nEOF\n";
let drawing = cadcraft_io::read_dxf(source.as_bytes()).unwrap();
let mut session = Session::empty();
session.open_drawing(drawing, "styles.dxf", None);
assert_eq!(cadcraft_engine::cmd::file::loss_on_save(&session, "styles.dwg").get("VISUALSTYLE"), Some(&1));
for (format, version) in [("dwg", 2007), ("dwg", 2013), ("dxf", 2007)] {
let start = session.log.len();
let result = session.execute("document.bytes", &json!({"format": format, "version": version})).unwrap();
if format == "dwg" && version == 2007 {
assert_eq!(not_saved(&result), json!({"VISUALSTYLE": 1}));
assert!(session.log[start..].iter().any(|message| message.contains("VISUALSTYLE")));
} else {
assert_eq!(not_saved(&result), Value::Null);
assert!(!session.log[start..].iter().any(|message| message.contains("VISUALSTYLE")));
}
}
}
#[test]
fn a_proxy_no_version_writes_is_not_reported() {
install();
@@ -8,7 +8,7 @@ use cadcraft_engine::doc::{Block, Common, Drawing, EntityKind, RawTag, Space, Un
use serde_json::json;
fn unknown(kind: &str) -> EntityKind {
EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }], graphics: Vec::new() })
EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }] })
}
#[test]
@@ -129,7 +129,6 @@ fn proxy_entities_are_reported_only_before_2013() {
RawTag { code: 90, value: "498".into() },
RawTag { code: 91, value: class.to_string() },
],
graphics: Vec::new(),
})
};
let mut d = Drawing::new_imperial();
@@ -191,7 +190,6 @@ fn saving_sat_text_solids_as_dxf_2013_reports_them() {
RawTag { code: 1, value: "400 1 1 0".into() },
RawTag { code: 3, value: "End-of-ACIS-data".into() },
],
graphics: Vec::new(),
});
d.add(&Space::Model, Common::default(), sat).unwrap();
let mut s = Session::empty();
@@ -221,7 +219,7 @@ fn a_dxf_2013_loss_is_known_before_saving() {
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
let sat = |d: &mut Drawing| {
let tags = vec![RawTag { code: 8, value: "0".into() }, RawTag { code: 1, value: "400 1 1 0".into() }];
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags, graphics: Vec::new() })).unwrap();
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags })).unwrap();
};
let mut modern = Drawing::new_imperial();
modern.header.set_str("ACADVER", "AC1032");
@@ -257,7 +255,6 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() {
RawTag { code: 1, value: "400 1 1 0".into() },
RawTag { code: 3, value: "End-of-ACIS-data".into() },
],
graphics: Vec::new(),
});
d.add(&Space::Model, Common::default(), sat).unwrap();
d.blocks.insert("Door".into(), std::sync::Arc::new(Block::new("Door")));
@@ -279,7 +276,7 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() {
fn a_dwg_keeps_sat_text_solids_only_before_2013() {
use cadcraft_engine::cmd::file::{Version, not_saved_as};
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let solid = |tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags, graphics: Vec::new() });
let solid = |tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags });
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "700 0 1 0")])).unwrap();
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(70, "1")])).unwrap();
@@ -355,7 +352,6 @@ fn proxy_entity(strings: &str) -> EntityKind {
EntityKind::Unknown(Unknown {
dxf_type: "ACAD_PROXY_ENTITY".into(),
tags: tags.iter().map(|(code, value)| RawTag { code: *code, value: (*value).into() }).collect(),
graphics: Vec::new(),
})
}
+21 -40
View File
@@ -649,41 +649,31 @@ fn frame(font: &TextFont, s: &str, p: &TextParams) -> (Vec2, Vec2, f64, Vec2) {
(origin, justify_offset(font, &sh, height, p.h, p.v), rot, mirror)
}
/// Resolve Aligned/Fit dimensions with the same shaping direction as [`place`].
/// Missing, coincident or nonfinite points leave the parameters unchanged.
pub fn fit_params(font: &TextFont, s: &str, p: &TextParams) -> TextParams {
let mut fitted = *p;
if !matches!(p.h, Align::Aligned | Align::Fit) {
return fitted;
}
let Some(second) = p.align_pt else { return fitted };
let distance = p.insert.dist(second);
if !distance.is_finite() || distance <= 1e-12 {
return fitted;
}
fitted.rotation = p.insert.angle_to(second);
let height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
let width = shape_line_dir(font, s, height, p.width_factor, p.oblique, TEXT_BASE_RTL).width;
if width.is_finite() && width > 1e-12 {
let scale = distance / width;
if p.h == Align::Aligned {
fitted.height = height * scale;
} else {
fitted.width_factor *= scale;
}
}
fitted
}
/// Place a single-line TEXT in world coordinates with any font. Returns the shaped text and its
/// bounding box.
pub fn place(font: &TextFont, s: &str, p: &TextParams) -> (Shaped, Bounds2) {
let fitted = fit_params(font, s, p);
let p = &fitted;
let height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
let rot = if p.rotation.is_finite() { p.rotation } else { 0.0 };
let mut height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
let mut wf = p.width_factor;
let mut rot = if p.rotation.is_finite() { p.rotation } else { 0.0 };
let insert = p.insert;
let mut sh = shape_line_dir(font, s, height, p.width_factor, p.oblique, TEXT_BASE_RTL);
if matches!(p.h, Align::Aligned | Align::Fit)
&& let Some(p2) = p.align_pt
{
let len = insert.dist(p2);
rot = insert.angle_to(p2);
// Measured as it is placed, left to right: the stroke font's trailing gap follows the
// glyph that ends the line.
let w = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL).width;
if w > 1e-12 && len > 1e-12 {
let k = len / w;
if p.h == Align::Aligned {
height *= k;
} else {
wf *= k;
}
}
}
let mut sh = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL);
let width = sh.width;
// Every justification but baseline-left (and aligned/fit, which span both points) is placed by
// its alignment point (DXF group 11); the insertion point (group 10) is then a computed point.
@@ -750,15 +740,6 @@ mod tests {
assert!((text.width - 10.0).abs() < 1e-9, "{}", text.width);
}
#[test]
fn two_point_middle_vertical_spans_points() {
for h in [Align::Aligned, Align::Fit] {
let p = TextParams { h, v: VAlign::Middle, align_pt: Some(Vec2::new(12.0, 5.0)), ..TextParams::new(Vec2::ZERO, 2.0) };
let (shaped, _) = place(&TextFont::Stroke, "SYNTHETIC", &p);
assert!((shaped.width - p.insert.dist(p.align_pt.unwrap())).abs() < 1e-9);
}
}
#[test]
fn every_ascii_printable_has_a_glyph() {
for c in ' '..='~' {
-4
View File
@@ -102,9 +102,6 @@ pub struct MTextLayout {
/// Geometry by colour run (strokes plus fillable glyph outlines).
pub pieces: Vec<MTextPiece>,
pub bounds: Bounds2,
/// The box of each column, in the order the text flows through them, measured like `bounds`
/// but without the gutters and to each column's own height. One column: `bounds`.
pub column_bounds: Vec<Bounds2>,
/// Plain text of each laid-out line.
pub lines: Vec<String>,
/// Whether the geometry stops short: the layout reached its allowance of retained points
@@ -734,7 +731,6 @@ pub fn layout_mtext_with(contents: &str, p: &MTextParams) -> MTextLayout {
out.bounds = Bounds2::from_points(
[Vec2::new(x0, top), Vec2::new(x0 + block_w, top), Vec2::new(x0 + block_w, top - block_h), Vec2::new(x0, top - block_h)].map(xf),
);
out.column_bounds = vec![out.bounds];
out
}
-8
View File
@@ -700,14 +700,6 @@ pub(super) fn layout(contents: &str, params: &MTextParams, base: &Fmt) -> MTextL
[Vec2::new(box_x0, top), Vec2::new(box_x0 + total_w, top), Vec2::new(box_x0 + total_w, top - block_h), Vec2::new(box_x0, top - block_h)]
.map(xf),
);
out.column_bounds = (0..n_cols)
.map(|column| {
let h = col_bottom.get(column).copied().unwrap_or(0.0).max(col_height(column));
let slot = if reversed { n_cols.saturating_sub(1).saturating_sub(column) } else { column };
let x0 = box_x0 + slot as f64 * (col_w + gutter);
Bounds2::from_points([Vec2::new(x0, top), Vec2::new(x0 + col_w, top), Vec2::new(x0 + col_w, top - h), Vec2::new(x0, top - h)].map(xf))
})
.collect();
out
}
-60
View File
@@ -109,66 +109,6 @@ fn reversed_columns_run_right_to_left() {
assert!(first > 0 && second > 0 && min_x(&l) >= 0.0);
}
/// The geometry points inside `b`.
fn points_in(l: &MTextLayout, b: &cadcraft_geom::Bounds2) -> usize {
l.strokes.iter().flatten().filter(|p| b.contains(**p)).count()
}
#[test]
fn each_column_has_its_own_box_without_the_gutter() {
let two = lay(&"word ".repeat(12), 10.0, Some(MTextColumnSpec { count: 2, gutter: 2.0, height: 6.0, ..Default::default() }));
let [a, b] = two.column_bounds.as_slice() else { panic!("{:?}", two.column_bounds) };
assert!(two.bounds.contains_box(a) && two.bounds.contains_box(b));
assert!(a.max.x < b.min.x, "the gutter lies between the columns: {a:?} {b:?}");
assert!(a.width() + b.width() < two.bounds.width());
let total = two.strokes.iter().map(Vec::len).sum::<usize>();
assert!(points_in(&two, a) > 0 && points_in(&two, b) > 0);
assert_eq!(points_in(&two, a) + points_in(&two, b), total, "every point is in its column's box");
// Three static columns, the text filling two and a half: the half-full column keeps the
// column height; text past the last column lengthens only that one.
let spec = MTextColumnSpec { count: 3, gutter: 2.0, height: 6.0, ..Default::default() };
let three = lay(&"word ".repeat(20), 10.0, Some(spec.clone()));
assert_eq!(three.column_bounds.len(), 3);
assert!(three.column_bounds.windows(2).all(|w| w[0].max.x < w[1].min.x && (w[0].height() - w[1].height()).abs() < 1e-9));
let over = lay(&"word ".repeat(40), 10.0, Some(spec));
let [first, .., last] = over.column_bounds.as_slice() else { panic!("{:?}", over.column_bounds) };
assert!(last.height() > first.height() && (last.height() - over.bounds.height()).abs() < 1e-9);
// Manual heights: each column as tall as its own height.
let manual = lay("one\\Ntwo", 5.0, Some(MTextColumnSpec { dynamic: true, heights: vec![3.0, 5.0], ..Default::default() }));
let [a, b] = manual.column_bounds.as_slice() else { panic!("{:?}", manual.column_bounds) };
assert!(a.height() < b.height());
}
#[test]
fn an_empty_column_keeps_its_place() {
let l = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 3, gutter: 1.0, height: 4.0, ..Default::default() }));
let [a, b, c] = l.column_bounds.as_slice() else { panic!("{:?}", l.column_bounds) };
assert!(a.max.x < b.min.x && b.max.x < c.min.x);
assert!(points_in(&l, a) > 0 && points_in(&l, b) > 0 && points_in(&l, c) == 0);
assert!((c.max.x - l.bounds.max.x).abs() < 1e-9 && (c.height() - a.height()).abs() < 1e-9);
// Reversed: the column the text starts in is the rightmost.
let r = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 2, height: 1.0, reversed: true, ..Default::default() }));
let [a, b] = r.column_bounds.as_slice() else { panic!("{:?}", r.column_bounds) };
assert!(a.min.x > b.max.x - 1e-9);
}
#[test]
fn one_column_is_the_whole_box() {
let rotated = |p: MTextParams| MTextParams { rotation: 0.4, attach: 5, insert: Vec2::new(3.0, -2.0), ..p };
for (s, width, columns) in [
("plain text that wraps a few times", 6.0, None),
("\\pxl1;paragraph text that wraps\\Pagain", 6.0, None),
("no width\\Pat all", 0.0, None),
(&*"word ".repeat(30), 10.0, Some(MTextColumnSpec { count: 1, gutter: 5.0, height: 3.0, ..Default::default() })),
("one\\Ptwo", 10.0, Some(MTextColumnSpec { dynamic: true, gutter: 5.0, height: 30.0, ..Default::default() })),
] {
let l = layout_mtext_with(s, &rotated(MTextParams { width, columns, ..MTextParams::new(Vec2::ZERO, 1.0) }));
assert_eq!(l.column_bounds, vec![l.bounds], "{s}");
}
}
#[test]
fn hostile_paragraph_codes_do_not_panic() {
let huge_tabs = format!("\\pt{};a\tb", (0..100_000).map(|i| i.to_string()).collect::<Vec<_>>().join(","));
-48
View File
@@ -62,9 +62,6 @@ struct Rx {
block_arrays: HashMap<String, cadcraft_doc::ArrayParams>,
/// LAYER record handle (upper case) → layer name (VIEWPORT group 331/341 frozen layers).
layers: HashMap<String, String>,
/// Layer, linetype and text style names in the order of the file's tables, which proxy
/// graphics refer to by index (the drawing's own tables are ordered differently).
proxy_tables: cadcraft_doc::ProxyTables,
/// UCS record handle (upper case) → UCS name (a layout's named UCS, group 345).
ucss: HashMap<String, String>,
/// Owner handle, paper flag and enclosing block (upper case) of each generated sheet viewport
@@ -78,26 +75,6 @@ struct Rx {
image_defs: HashMap<Handle, String>,
}
/// Order `items` as the file's table lists them (`order`, names in any case), after the `pinned`
/// names: records the file doesn't have keep their order after the file's own. A file without
/// that table changes nothing.
fn keep_file_order<T>(items: &mut [T], name: impl Fn(&T) -> &str, order: &[String], pinned: &[&str]) {
if order.is_empty() {
return;
}
let mut place: HashMap<String, usize> = HashMap::new();
for (i, n) in order.iter().enumerate() {
place.entry(n.to_ascii_lowercase()).or_insert(i);
}
items.sort_by_key(|it| {
let n = name(it);
match pinned.iter().position(|p| p.eq_ignore_ascii_case(n)) {
Some(i) => (0, i),
None => place.get(&n.to_ascii_lowercase()).map_or((2, 0), |&i| (1, i)),
}
});
}
/// Read a DXF file into a drawing.
pub fn read(bytes: &[u8]) -> Result<Drawing> {
read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS)
@@ -202,13 +179,6 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
_ => {}
}
}
// Proxy graphics name layers and linetypes by their place in the file's tables, and saving
// writes them unchanged: the tables keep the file's order, with what CADCraft adds after it.
keep_file_order(&mut d.layers, |l| &l.name, &rx.proxy_tables.layers, &[]);
keep_file_order(&mut d.linetypes, |l| &l.name, &rx.proxy_tables.linetypes, &["ByBlock", "ByLayer"]);
// A proxy text takes the first style on its font, so the styles keep the file's order too.
let styles: Vec<String> = rx.proxy_tables.styles.iter().map(|(n, _)| n.clone()).collect();
keep_file_order(&mut d.text_styles, |s| &s.name, &styles, &[]);
// A file CADCraft wrote names its own next handle (#495): its table records and objects
// are numbered above it and rebuilt on save, so following $HANDSEED would drift every save.
let own_seed = objs.xrecord_text(crate::dxf_ext::HANDSEED_KEY).and_then(|t| Handle::parse_hex(t.trim()));
@@ -242,7 +212,6 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
// Every record is placed now, and an object holding a reserved handle keeps it from new
// objects by itself. Kept, the set would be copied with every undo step of the drawing.
d.reserved_handles.clear();
remember_text_fits(&mut d);
Ok(d)
}
@@ -275,23 +244,6 @@ fn number_unknown_viewport_ids(d: &mut Drawing, sheet_dropped: &std::collections
}
}
/// Capture after all tables and entity fixups, including files whose tables follow entities.
fn remember_text_fits(d: &mut Drawing) {
let mut fits = std::collections::BTreeMap::new();
for e in d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter())) {
let texts: Vec<&Text> = match &e.kind {
EntityKind::Text(t) => vec![t],
EntityKind::AttDef(a) => vec![&a.text],
EntityKind::Insert(i) => i.attribs.iter().map(|a| &a.text).collect(),
_ => continue,
};
if texts.iter().any(|t| matches!(t.halign, HAlign::Aligned | HAlign::Fit)) {
fits.insert(e.handle, texts.into_iter().map(|t| (t.clone(), d.text_style(&t.style).cloned().unwrap_or_default())).collect());
}
}
std::sync::Arc::make_mut(&mut d.foreign).text_fits = fits;
}
/// An entity from the groups of a DXF record of type `kind` (without its `0` group), as the
/// reader makes it, with plain strings as [`crate::entity_groups`] gives them (not the file's
/// `^ ` escapes). AutoLISP's `entmake` and `entmod` are built on it.
-5
View File
@@ -329,7 +329,6 @@ pub(super) fn entity_with_table_budget(
other => EntityKind::Unknown(Unknown {
dxf_type: other.to_string(),
tags: tags.iter().map(|tg| RawTag { code: tg.code, value: tg.str() }).collect(),
graphics: Vec::new(),
}),
};
Some((c, k))
@@ -489,10 +488,6 @@ pub(super) fn entity_plot_style(tags: &[Tag], rx: &Rx) -> Option<String> {
/// needs the file's handle maps.
pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityKind, rx: &mut Rx) {
match (kind, k) {
// Its proxy graphics, with the table indices resolved while the file's order is known.
("ACAD_PROXY_ENTITY", EntityKind::Unknown(u)) => {
u.graphics = cadcraft_doc::proxy_entities(&u.proxy_graphics_bytes(), &rx.proxy_tables, h);
}
("DIMENSION", EntityKind::Dimension(dm)) => {
dm.overrides = crate::dxf_ext::read_dstyle(tags, &rx.styles, &rx.brs, &rx.ltypes);
dm.assoc = crate::dxf_ext::read_assoc(tags);
+1 -1
View File
@@ -73,7 +73,7 @@ pub(super) fn hatch(tags: &[Tag], t: &T, curves: &mut CurvePoints) -> Option<Ent
verts.pop();
}
let sources = boundary_sources(tags, &mut i);
loops.push(HatchLoop { vertices: verts, outer, boundary_flags: Some(flags), sources });
loops.push(HatchLoop { vertices: verts, outer, sources });
}
curves.left = curves.left.saturating_sub(start_left.saturating_sub(budget.left));
if budget.cut {
-5
View File
@@ -299,7 +299,6 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
let (Some(handle), Some(name)) = (table.s(5), table.s(2)) else { continue };
match kind.as_str() {
"STYLE" => {
rx.proxy_tables.styles.push((name.clone(), table.s(3).unwrap_or_default()));
rx.styles.insert(handle.trim().to_ascii_uppercase(), name);
}
"BLOCK_RECORD" => {
@@ -311,13 +310,9 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
rx.brs.insert(handle.trim().to_ascii_uppercase(), name);
}
"LTYPE" => {
if !name.eq_ignore_ascii_case("ByBlock") && !name.eq_ignore_ascii_case("ByLayer") {
rx.proxy_tables.linetypes.push(name.clone());
}
rx.ltypes.insert(handle.trim().to_ascii_uppercase(), name);
}
"LAYER" => {
rx.proxy_tables.layers.push(name.clone());
rx.layers.insert(handle.trim().to_ascii_uppercase(), name);
}
"UCS" => {
+2 -3
View File
@@ -70,8 +70,7 @@ pub(crate) fn from_polyline(tags: &[Tag], pl: LwPolyline) -> Option<EntityKind>
let list = xdata_list(x, "REGION");
let fin = |v: &PolyVertex| v.p.is_finite() && v.bulge.is_finite();
let first_outer = list.iter().find(|t| t.code == 1070).is_none_or(|t| t.i64() != 0);
let mut loops =
vec![HatchLoop { vertices: pl.vertices.into_iter().filter(fin).collect(), outer: first_outer, boundary_flags: None, sources: Vec::new() }];
let mut loops = vec![HatchLoop { vertices: pl.vertices.into_iter().filter(fin).collect(), outer: first_outer, sources: Vec::new() }];
let mut total = 0usize;
let mut cur: Option<HatchLoop> = None;
let mut expect_flag = false;
@@ -82,7 +81,7 @@ pub(crate) fn from_polyline(tags: &[Tag], pl: LwPolyline) -> Option<EntityKind>
if loops.len() >= MAX_REGION_LOOPS {
break;
}
cur = Some(HatchLoop { vertices: Vec::new(), outer: false, boundary_flags: None, sources: Vec::new() });
cur = Some(HatchLoop { vertices: Vec::new(), outer: false, sources: Vec::new() });
expect_flag = true;
}
1070 if expect_flag => {
+3 -49
View File
@@ -165,56 +165,10 @@ fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::Hash
/// The R2000 DXF the DWG bridge converts to a `dwg` version DWG: its entity types are the DWG
/// version's (MULTILEADER from 2007).
pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> (String, craft_dwg::Unwritten) {
let (mut tags, kept) = sections::tags_kept_for(d, Version::R2000, dwg, false, true);
let mut unwritten = craft_dwg::Unwritten::new();
if dwg == Version::R2007 {
let omitted = legacy_visualstyles_kept(d, &kept);
if omitted != 0 {
let mut source = d.clone();
std::sync::Arc::make_mut(&mut source.foreign).objects.retain(|object| !legacy_visual_style(object));
tags = tags_for(&source, Version::R2000, dwg, false);
unwritten.insert("VISUALSTYLE".into(), omitted);
}
}
pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> String {
let mut tags = tags_for(d, Version::R2000, dwg, false);
bridge_markers(&mut tags);
(craft_dxf::write_ascii(&tags), unwritten)
}
/// Version-specific DWG compatibility omissions, counted from the actual saved view.
/// Hosts use this before saving and when reporting saves through their byte-only I/O hooks.
pub fn dwg_compat_lost(d: &Drawing, version: Version) -> craft_dwg::Unwritten {
let mut lost = craft_dwg::Unwritten::new();
if version == Version::R2007 && d.foreign.objects.iter().any(legacy_visual_style) {
let (_, kept) = sections::tags_kept_for(d, Version::R2000, version, false, true);
let omitted = legacy_visualstyles_kept(d, &kept);
if omitted != 0 {
lost.insert("VISUALSTYLE".into(), omitted);
}
}
lost
}
fn legacy_visualstyles_kept(d: &Drawing, kept: &HashSet<cadcraft_doc::Handle>) -> usize {
d.foreign.objects.iter().filter(|object| kept.contains(&object.handle) && legacy_visual_style(object)).count()
}
/// The fixed-property VISUALSTYLE layout in the 2007/2010 DXF Reference has no 176/177
/// property pairs. The bridge cannot faithfully save this layout as a 2007 DWG.
fn legacy_visual_style(object: &cadcraft_doc::foreign::ForeignObject) -> bool {
if !object.kind.trim().eq_ignore_ascii_case("VISUALSTYLE") {
return false;
}
let mut properties = object.tags.iter().skip_while(|tag| tag.code != 100 || tag.value.trim() != "AcDbVisualStyle");
properties.next();
let mut fixed = false;
for tag in properties.take_while(|tag| tag.code != 100 && tag.code < 1000) {
if matches!(tag.code, 176 | 177) {
return false;
}
fixed |= matches!(tag.code, 40 | 71);
}
fixed
craft_dxf::write_ascii(&tags)
}
/// Proxy type names and lookup-parameter subclass names must match the bridge reader's spelling.
+1 -62
View File
@@ -254,69 +254,8 @@ fn computed_text_insert(d: &Drawing, t: &Text) -> Vec3 {
if q.is_finite() { Vec3::new(q.x, q.y, t.insert.z) } else { t.insert }
}
fn relative_match(a: f64, b: f64) -> bool {
a.is_finite() && b.is_finite() && (a - b).abs() <= 1e-9 * a.abs().max(b.abs())
}
// A fitted dimension depends on the point distance, independently of position and direction.
fn imported_fit_scale(original: &Text, current: &Text) -> Option<f64> {
let (Some(first), Some(second)) = (original.align_pt, current.align_pt) else {
return None;
};
let before = original.insert.xy().dist(first.xy());
let after = current.insert.xy().dist(second.xy());
if !before.is_finite() || !after.is_finite() || before <= 0.0 || after <= 0.0 {
return None;
}
if relative_match(before, after) {
return Some(1.0);
}
let scale = after / before;
(scale.is_finite() && scale > 0.0).then_some(scale)
}
/// `attdef_prompt` is `Some` for an ATTDEF (its prompt, which may be empty) and `None` for an ATTRIB.
pub(super) fn text_tags(
w: &mut W,
d: &Drawing,
t: &Text,
attrib: Option<(&Attrib, Version)>,
attdef_prompt: Option<&str>,
source: (cadcraft_doc::Handle, usize),
) {
let fitted;
let t = if matches!(t.halign, HAlign::Aligned | HAlign::Fit) {
let mut resolved = t.clone();
// Imported dimensions use the originating font's measurements. A substituted font
// must not replace them while the fitting inputs still match the read-time snapshot.
if let Some((original, style)) = d.foreign.text_fits.get(&source.0).and_then(|texts| texts.get(source.1))
&& original.value == t.value
&& let Some(scale) = imported_fit_scale(original, t)
&& original.style == t.style
&& *style == d.text_style(&t.style).cloned().unwrap_or_default()
&& original.halign == t.halign
&& original.valign == t.valign
&& original.oblique == t.oblique
&& original.width_factor == t.width_factor
&& (t.halign != HAlign::Fit || relative_match(t.height, original.height * scale))
{
if t.halign == HAlign::Aligned && !t.value.is_empty() {
resolved.height = original.height * scale;
}
if let Some(second) = t.align_pt {
let distance = t.insert.xy().dist(second.xy());
if distance.is_finite() && distance > 1e-12 {
resolved.rotation = t.insert.xy().angle_to(second.xy());
}
}
} else {
resolved = cadcraft_render::fitted_text_entity(d, t, &t.value);
}
fitted = resolved;
&fitted
} else {
t
};
pub(super) fn text_tags(w: &mut W, d: &Drawing, t: &Text, attrib: Option<(&Attrib, Version)>, attdef_prompt: Option<&str>) {
let attdef = attdef_prompt.is_some();
// An attribute definition with no default value is drawn as its tag, whatever its prompt: the
// baseline start AutoCAD stored is judged against the tag's width too. A stored point that is
+5 -5
View File
@@ -292,7 +292,7 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo
w.s(0, "TEXT");
common(w, e, owner, paper, "AcDbText");
thickness(w, e);
text_tags(w, d, t, None, None, (e.handle, 0));
text_tags(w, d, t, None, None);
}
// Closed polylines, one per loop (`dxf_region`): REGION's own data is ACIS.
EntityKind::Region(r) => {
@@ -312,7 +312,7 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo
EntityKind::AttDef(a) => {
w.s(0, "ATTDEF");
common(w, e, owner, paper, "AcDbText");
text_tags(w, d, &a.text, Some((a, cx.target)), Some(&a.prompt), (e.handle, 0));
text_tags(w, d, &a.text, Some((a, cx.target)), Some(&a.prompt));
if cx.target >= Version::R2007 {
multiline_tags(w, a, true);
}
@@ -372,7 +372,7 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
w.f(45, i.row_spacing);
}
if !i.attribs.is_empty() {
for (index, a) in i.attribs.iter().enumerate() {
for a in &i.attribs {
let ah = w.h();
w.s(0, "ATTRIB");
w.s(5, ah);
@@ -385,7 +385,7 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
w.i(60, 1);
}
w.s(100, "AcDbText");
text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index));
text_tags(w, d, &a.text, Some((a, cx.target)), None);
if cx.target >= Version::R2007 {
multiline_tags(w, a, false);
}
@@ -627,7 +627,7 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
w.i(71, i64::from(h.associative));
w.i(91, h.loops.len() as i64);
for l in &h.loops {
w.i(92, 2 | i64::from(l.outer) | (l.boundary_flags.unwrap_or(0) & (4 | 8 | 16)));
w.i(92, 2 | if l.outer { 1 } else { 0 });
let has_bulge = l.vertices.iter().any(|v| v.bulge != 0.0);
w.i(72, i64::from(has_bulge));
w.i(73, 1);
+1 -3
View File
@@ -26,7 +26,6 @@ const HEADER_VARS: &[(&str, i32)] = &[
("CELTSCALE", 40),
("DIMSCALE", 40),
("DIMSTYLE", 2),
("DIMASSOC", 280),
("LUNITS", 70),
("LUPREC", 70),
("AUNITS", 70),
@@ -125,7 +124,6 @@ fn dim_header_vars(w: &mut W, d: &Drawing) {
}
}
/// Write modelled HEADER variables with their declared DXF group types, then dimension style variables.
pub(super) fn header_vars(w: &mut W, d: &Drawing) {
for (name, code) in HEADER_VARS {
let Some(v) = d.header.get(name) else { continue };
@@ -155,7 +153,7 @@ pub(super) fn header_vars(w: &mut W, d: &Drawing) {
w.f(c, f);
}
}
(c @ (62 | 70 | 280 | 290 | 370), v) => {
(c @ (62 | 70 | 290 | 370), v) => {
if let Some(i) = v.as_i64() {
w.s(9, format!("${name}"));
w.i(c, i);
+3 -11
View File
@@ -411,28 +411,22 @@ struct LayoutWriteData<'a> {
ucs: Option<&'a Ucs>,
/// The layout's limits as read (`None`: the default 0,0 to 12,9).
limits: Option<(Vec2, Vec2)>,
/// Whether this is the Model layout (block record *Model_Space).
model: bool,
}
/// 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. 1024 ("ModelType", DXF Reference, PLOTSETTINGS
/// group 70) follows the layout: set for the Model layout, cleared for a paper-space layout even
/// when the file had it, since it would mark that layout as model space.
fn plot_layout_flags(page: &PageSetup, standard: bool, model: bool) -> i64 {
/// 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;
const MODEL_TYPE: i64 = 1024;
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 },
};
let kept = if model { kept | MODEL_TYPE } else { kept & !MODEL_TYPE };
kept | if page.lineweights { 128 } else { 0 } | if page.center { 4 } else { 0 } | if page.show_plot_styles { 2 } else { 0 }
}
@@ -452,7 +446,7 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
// 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, data.model);
let plot_flags = plot_layout_flags(page, standard);
let plot_type = match page.plot_area.as_str() {
"display" => 0,
"extents" => 1,
@@ -616,7 +610,6 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
view: None,
ucs: None,
limits: None,
model: true,
},
);
for (i, (_, brh, l)) in ps_brs.iter().enumerate() {
@@ -634,7 +627,6 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
view: l.view,
ucs: l.ucs.as_ref(),
limits: l.limits,
model: false,
},
);
}
+3 -8
View File
@@ -37,7 +37,7 @@ pub use cadcraft_doc::Format;
pub use craft_dxf::Version;
pub use dxf_raw::{ObjectRecord, object_records};
pub use dxf_read::entity_from_groups;
pub use dxf_write::{dwg_compat_lost, entity_groups, proxies_lost};
pub use dxf_write::{entity_groups, proxies_lost};
pub use pdf::{PdfOptions, pdf, plot};
/// How a drawing is saved as DXF or DWG.
@@ -164,13 +164,8 @@ pub fn write_noted(d: &Drawing, name: impl AsRef<Path>, opts: &SaveOptions) -> R
/// file they came from (`Foreign::version`, not `$ACADVER`, which SAVEAS changes), and the bridge
/// reads them as that version.
fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec<u8>, craft_dwg::Unwritten)> {
let (bridge, omitted) = dxf_write::dwg_bridge(d, version);
let (bytes, mut unwritten) = craft_dwg::encode_kept_noted(bridge.as_bytes(), version.code(), d.foreign.version.as_deref()).map_err(dwg_error)?;
for (kind, omitted) in omitted {
let count = unwritten.entry(kind).or_default();
*count = count.saturating_add(omitted);
}
Ok((bytes, unwritten))
let bridge = dxf_write::dwg_bridge(d, version);
craft_dwg::encode_kept_noted(bridge.as_bytes(), version.code(), d.foreign.version.as_deref()).map_err(dwg_error)
}
/// Like [`write`], but image formats (PNG, SVG, PDF) show `window` (a model-space rectangle in
+2 -6
View File
@@ -39,11 +39,7 @@ fn drawing() -> Drawing {
d.add(
&Space::Model,
Common::default(),
EntityKind::Unknown(Unknown {
dxf_type: "ACME_WIDGET".into(),
tags: vec![tag(100, "AcDbEntity"), tag(10, "1.0"), tag(20, "2.0")],
graphics: Vec::new(),
}),
EntityKind::Unknown(Unknown { dxf_type: "ACME_WIDGET".into(), tags: vec![tag(100, "AcDbEntity"), tag(10, "1.0"), tag(20, "2.0")] }),
)
.unwrap();
d.add(&Space::Paper("Layout1".into()), Common::default(), line((1.0, 1.0), (2.0, 2.0))).unwrap();
@@ -525,7 +521,7 @@ fn corpus_round_trip_report() {
fn types_the_dwg_writer_cannot_write_are_reported_lost() {
use corpus::{CorpusReport, FileReport, Format, round_trip};
crate::dwg_worker::allow_in_process();
let unknown = |t: &str, tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: t.into(), tags, graphics: Vec::new() });
let unknown = |t: &str, tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: t.into(), tags });
let mut d = Drawing::new_metric();
let widget = vec![tag(100, "AcDbEntity"), tag(100, "AcmeWidget"), tag(10, "1.0"), tag(20, "2.0"), tag(30, "0.0")];
d.add(&Space::Model, Common::default(), unknown("ACME_WIDGET", widget.clone())).unwrap();
+1 -510
View File
@@ -111,7 +111,6 @@ fn sample() -> Drawing {
loops: vec![HatchLoop {
vertices: vec![PolyVertex::new(Vec2::ZERO), PolyVertex::new(Vec2::new(2.0, 0.0)), PolyVertex::new(Vec2::new(2.0, 2.0))],
outer: true,
boundary_flags: Some(3),
sources: Vec::new(),
}],
scale: 1.0,
@@ -2030,514 +2029,6 @@ fn intl_text(value: &str) -> Text {
}
}
fn two_point_text_sample() -> Drawing {
let mut drawing = Drawing::new_metric();
let mut block = Block::new("Labels");
let mut attribs = Vec::new();
for (index, halign) in [HAlign::Aligned, HAlign::Fit].into_iter().enumerate() {
for multiplier in [1.0, 2.0] {
let text =
Text { insert: Vec3::ZERO, align_pt: Some(Vec3::new(30.0 * multiplier, 4.0 * multiplier, 0.0)), halign, ..intl_text("SYNTHETIC") };
drawing.add(&Space::Model, Common::default(), EntityKind::Text(text.clone())).unwrap();
let attribute = Attrib {
tag: format!("LABEL{index}_{multiplier}"),
text,
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
block.entities.push(Entity::new(Handle(0x500 + attribs.len() as u64), EntityKind::AttDef(attribute.clone())));
attribs.push(attribute);
}
}
drawing.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
drawing
.add(
&Space::Model,
Common::default(),
EntityKind::Insert(Insert {
block: "Labels".into(),
insert: Vec3::ZERO,
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs,
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}),
)
.unwrap();
drawing
}
fn two_point_texts(drawing: &Drawing) -> Vec<&Text> {
let mut texts = Vec::new();
for entity in drawing.model.iter() {
match &entity.kind {
EntityKind::Text(text) => texts.push(text),
EntityKind::Insert(insert) => texts.extend(insert.attribs.iter().map(|attribute| &attribute.text)),
_ => {}
}
}
texts.extend(
drawing
.block("Labels")
.unwrap()
.entities
.iter()
.filter_map(|entity| if let EntityKind::AttDef(attribute) = &entity.kind { Some(&attribute.text) } else { None }),
);
texts
}
fn edit_two_point_texts(d: &mut Drawing, edit: impl Fn(&mut Text)) {
fn store(store: &mut EntityStore, edit: &impl Fn(&mut Text)) {
for handle in store.handles() {
store.modify(handle, |e| match &mut e.kind {
EntityKind::Text(t) => edit(t),
EntityKind::AttDef(a) => edit(&mut a.text),
EntityKind::Insert(i) => i.attribs.iter_mut().for_each(|a| edit(&mut a.text)),
_ => {}
});
}
}
store(&mut d.model, &edit);
for block in d.blocks.values_mut() {
store(&mut std::sync::Arc::make_mut(block).entities, &edit);
}
}
// Original synthetic DXF records with measurements deliberately different from our stroke font.
fn imported_two_point_text_sample() -> Drawing {
let tags = craft_dxf::parse(write_dxf(&two_point_text_sample()).as_bytes()).unwrap();
let mut altered = tags.clone();
// Work on complete records, including their leading group 0.
let starts: Vec<usize> = tags.iter().enumerate().filter_map(|(i, t)| (t.code == 0).then_some(i)).chain([tags.len()]).collect();
for pair in starts.windows(2) {
let record = &tags[pair[0]..pair[1]];
if !matches!(record[0].str().as_ref(), "TEXT" | "ATTDEF" | "ATTRIB") {
continue;
}
let number = |code| record.iter().find(|t| t.code == code).map(|t| t.str().parse::<f64>().unwrap()).unwrap_or(0.0);
let distance = Vec2::new(number(10), number(20)).dist(Vec2::new(number(11), number(21)));
let width = cadcraft_fonts::shape_stroke("SYNTHETIC", 2.5, 1.0, 0.0).width;
let aligned = number(72) == 3.0;
let code = if aligned { 40 } else { 41 };
let dimension = if aligned { 2.5 } else { 1.0 } * distance / width * 1.15;
for tag in &mut altered[pair[0]..pair[1]] {
if tag.code == code {
*tag = craft_dxf::Tag::new(code, craft_dxf::Value::Real(dimension));
}
if tag.code == 50 {
*tag = craft_dxf::Tag::new(50, craft_dxf::Value::Real(0.0));
}
}
}
read_dxf(craft_dxf::write_ascii(&altered).as_bytes()).unwrap()
}
fn check_two_point_save(d: &Drawing, name: &str, recompute: bool, rotation: bool) {
let saved = read(&write(d, name).unwrap(), name).unwrap();
let before = two_point_texts(d);
let after = two_point_texts(&saved);
assert_eq!(after.len(), before.len());
for (original, text) in before.into_iter().zip(&after) {
if rotation {
assert!((text.rotation - text.insert.xy().angle_to(text.align_pt.unwrap().xy())).abs() < 1e-10, "{name}: {text:?}");
}
if recompute {
let width =
cadcraft_fonts::shape_stroke_dir(&original.value, original.height, original.width_factor, original.oblique, Some(false)).width;
let scale = original.insert.xy().dist(original.align_pt.unwrap().xy()) / width;
let (height, factor) = if original.halign == HAlign::Aligned {
(original.height * scale, original.width_factor)
} else {
(original.height, original.width_factor * scale)
};
assert!((text.height / height - 1.0).abs() < 1e-12, "height: {name}");
assert!((text.width_factor / factor - 1.0).abs() < 1e-12, "width factor: {name}");
} else {
assert!((text.height - original.height).abs() < 1e-10, "{name}");
assert!((text.width_factor - original.width_factor).abs() < 1e-10, "{name}");
}
}
let again = read(&write(&saved, name).unwrap(), name).unwrap();
for (first, second) in after.into_iter().zip(two_point_texts(&again)) {
assert!((first.rotation - second.rotation).abs() < 1e-10, "{name}");
assert!((first.height - second.height).abs() < 1e-10, "{name}");
assert!((first.width_factor - second.width_factor).abs() < 1e-10, "{name}");
}
}
fn two_point_formats() -> [&'static str; 2] {
crate::dwg_worker::allow_in_process();
["fit.dxf", "fit.dwg"]
}
#[test]
fn two_point_imported_measurements_survive_save() {
for name in two_point_formats() {
check_two_point_save(&imported_two_point_text_sample(), name, false, false);
}
}
#[test]
fn two_point_imported_rotation_follows_points() {
for name in two_point_formats() {
check_two_point_save(&imported_two_point_text_sample(), name, false, true);
}
}
fn transform_two_point_sample(d: &mut Drawing, matrix: cadcraft_geom::Mat3) {
// Transform the reference itself so attached attributes follow the production path.
for handle in d.model.handles() {
d.model.modify(handle, |entity| entity.kind.transform(&matrix));
}
}
#[test]
fn two_point_imported_measurements_survive_move() {
let mut d = imported_two_point_text_sample();
transform_two_point_sample(&mut d, cadcraft_geom::Mat3::translate(Vec2::new(47.0, -19.0)));
for name in two_point_formats() {
check_two_point_save(&d, name, false, true);
}
}
#[test]
fn two_point_imported_measurements_survive_rotate() {
let mut d = imported_two_point_text_sample();
transform_two_point_sample(&mut d, cadcraft_geom::Mat3::rotate_about(Vec2::new(7.0, -3.0), 0.73));
for name in two_point_formats() {
check_two_point_save(&d, name, false, true);
}
}
#[test]
fn two_point_imported_measurements_follow_uniform_scale() {
let mut d = imported_two_point_text_sample();
let imported = d.clone();
transform_two_point_sample(&mut d, cadcraft_geom::Mat3::scale_about(Vec2::new(7.0, -3.0), 2.0));
for (before, scaled) in two_point_texts(&imported).into_iter().zip(two_point_texts(&d)).take(8) {
assert!((scaled.height - before.height * 2.0).abs() < 1e-10);
assert!((scaled.width_factor - before.width_factor).abs() < 1e-10);
}
for name in two_point_formats() {
check_two_point_save(&d, name, false, true);
}
}
#[test]
fn two_point_changed_fit_height_recomputes_measurements() {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| t.height *= 1.4);
for name in two_point_formats() {
// Aligned height is derived from distance, so editing it alone preserves the import.
let saved = read(&write(&d, name).unwrap(), name).unwrap();
for (before, after) in two_point_texts(&d).into_iter().zip(two_point_texts(&saved)) {
if before.halign == HAlign::Fit {
let expected = cadcraft_render::fitted_text_entity(&d, before, &before.value);
assert!((after.width_factor / expected.width_factor - 1.0).abs() < 1e-12);
}
}
}
}
#[test]
fn two_point_imported_distance_uses_relative_tolerance() {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| {
let point = t.align_pt.as_mut().unwrap();
point.x *= 1.0 + 0.5e-9;
point.y *= 1.0 + 0.5e-9;
});
for name in two_point_formats() {
check_two_point_save(&d, name, false, true);
}
}
#[test]
fn two_point_changed_fitting_inputs_recompute_measurements() {
for input in ["style", "oblique", "width factor"] {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| match input {
"style" => t.style = "Replacement".into(),
"oblique" => t.oblique += 0.2,
_ => t.width_factor *= 1.2,
});
for name in two_point_formats() {
check_two_point_save(&d, name, true, true);
}
}
}
#[test]
fn two_point_changed_string_recomputes_measurements() {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| t.value.push_str(" EDITED"));
for name in two_point_formats() {
check_two_point_save(&d, name, true, false);
}
}
#[test]
fn two_point_changed_distance_scales_aligned_and_recomputes_fit() {
let mut d = imported_two_point_text_sample();
let imported = d.clone();
edit_two_point_texts(&mut d, |t| t.align_pt.as_mut().unwrap().x *= 1.8);
for name in two_point_formats() {
let saved = read(&write(&d, name).unwrap(), name).unwrap();
for ((before, edited), after) in two_point_texts(&imported).into_iter().zip(two_point_texts(&d)).zip(two_point_texts(&saved)) {
if before.halign == HAlign::Aligned {
let ratio = edited.insert.xy().dist(edited.align_pt.unwrap().xy()) / before.insert.xy().dist(before.align_pt.unwrap().xy());
assert!((after.height / (before.height * ratio) - 1.0).abs() < 1e-12, "{name}");
} else {
let expected = cadcraft_render::fitted_text_entity(&d, edited, &edited.value);
assert!((after.width_factor / expected.width_factor - 1.0).abs() < 1e-12, "{name}");
}
}
check_two_point_save(&saved, name, false, true);
}
}
#[test]
fn two_point_authored_text_recomputes_measurements() {
for name in two_point_formats() {
check_two_point_save(&two_point_text_sample(), name, true, false);
}
}
#[test]
fn two_point_text_save_keeps_degenerate_and_unrelated_values() {
for halign in [HAlign::Left, HAlign::Center, HAlign::Right, HAlign::Middle, HAlign::Aligned, HAlign::Fit] {
for valign in [VAlign::Baseline, VAlign::Bottom] {
for align_pt in [None, Some(Vec3::ZERO), Some(Vec3::new(30.0, 4.0, 0.0))] {
if matches!(halign, HAlign::Aligned | HAlign::Fit) && align_pt.is_some_and(|point| point != Vec3::ZERO) {
continue;
}
let text = Text { insert: Vec3::ZERO, align_pt, halign, valign, rotation: 0.7, width_factor: 0.8, ..intl_text("SYNTHETIC") };
let mut drawing = Drawing::new_metric();
drawing.add(&Space::Model, Common::default(), EntityKind::Text(text.clone())).unwrap();
let saved = read(&write(&drawing, "edge.dxf").unwrap(), "edge.dxf").unwrap();
let back = first(&saved, |kind| if let EntityKind::Text(text) = kind { Some(text.clone()) } else { None });
assert!((text.rotation - back.rotation).abs() < 1e-12);
assert!((text.height - back.height).abs() < 1e-10);
assert!((text.width_factor - back.width_factor).abs() < 1e-10);
}
}
}
}
#[test]
fn two_point_imported_degenerate_geometry_keeps_edited_height() {
for missing in [false, true] {
let mut d = imported_two_point_text_sample();
let handle = d.model.handles()[0];
d.model.modify(handle, |entity| {
if let EntityKind::Text(t) = &mut entity.kind {
t.insert = Vec3::ZERO;
t.align_pt = if missing { None } else { Some(Vec3::ZERO) };
t.height = 2.0;
}
});
let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0;
snapshot.insert = Vec3::ZERO;
snapshot.align_pt = if missing { None } else { Some(Vec3::ZERO) };
snapshot.height = 2.0;
let mut d = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap();
let handle = d.model.handles()[0];
let imported = first(&d, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None });
assert_eq!(imported.align_pt, if missing { None } else { Some(Vec3::ZERO) });
d.model.modify(handle, |entity| {
if let EntityKind::Text(t) = &mut entity.kind {
t.height = 4.0;
}
});
let saved = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap();
let text = first(&saved, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None });
assert!((text.height - 4.0).abs() < 1e-10, "missing: {missing}");
}
}
#[test]
fn two_point_imported_nonfinite_geometry_keeps_edited_height() {
let mut d = imported_two_point_text_sample();
let handle = d.model.handles()[0];
d.model.modify(handle, |entity| {
if let EntityKind::Text(t) = &mut entity.kind {
assert_eq!(t.halign, HAlign::Aligned);
t.insert = Vec3::ZERO;
t.align_pt = Some(Vec3::new(f64::INFINITY, 0.0, 0.0));
t.height = 4.0;
}
});
let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0;
snapshot.insert = Vec3::ZERO;
snapshot.align_pt = Some(Vec3::new(f64::INFINITY, 0.0, 0.0));
snapshot.height = 2.0;
let saved = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap();
let text = first(&saved, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None });
assert!((text.height - 4.0).abs() < 1e-10);
}
#[test]
fn two_point_imported_empty_attdef_keeps_dimensions_when_points_move() {
let mut d = imported_two_point_text_sample();
let block = std::sync::Arc::make_mut(d.blocks.get_mut("Labels").unwrap());
let handle = block.entities.handles()[0];
block.entities.modify(handle, |entity| {
if let EntityKind::AttDef(a) = &mut entity.kind {
a.text.value.clear();
a.text.insert = Vec3::ZERO;
a.text.align_pt = Some(Vec3::new(10.0, 0.0, 0.0));
a.text.height = 2.0;
a.text.width_factor = 0.8;
}
});
let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0;
snapshot.value.clear();
snapshot.insert = Vec3::ZERO;
snapshot.align_pt = Some(Vec3::new(10.0, 0.0, 0.0));
snapshot.height = 2.0;
snapshot.width_factor = 0.8;
let mut d = read(&write(&d, "empty.dxf").unwrap(), "empty.dxf").unwrap();
let block = std::sync::Arc::make_mut(d.blocks.get_mut("Labels").unwrap());
let handle = block.entities.handles()[0];
block.entities.modify(handle, |entity| {
if let EntityKind::AttDef(a) = &mut entity.kind {
a.text.align_pt = Some(Vec3::new(0.0, 20.0, 0.0));
}
});
let saved = read(&write(&d, "empty.dxf").unwrap(), "empty.dxf").unwrap();
let entity = saved.block("Labels").unwrap().entities.iter().next().unwrap();
let EntityKind::AttDef(a) = &entity.kind else { panic!("expected ATTDEF") };
assert!((a.text.height - 2.0).abs() < 1e-10);
assert!((a.text.width_factor - 0.8).abs() < 1e-10);
assert!((a.text.rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-10);
}
#[test]
fn two_point_changed_style_definition_recomputes_measurements() {
let mut d = imported_two_point_text_sample();
d.text_styles.iter_mut().find(|style| style.name.eq_ignore_ascii_case("Standard")).unwrap().backwards = true;
for name in two_point_formats() {
let saved = read(&write(&d, name).unwrap(), name).unwrap();
for (before, after) in two_point_texts(&d).into_iter().zip(two_point_texts(&saved)) {
let expected = cadcraft_render::fitted_text_entity(&d, before, &before.value);
assert!((after.height - expected.height).abs() < 1e-9, "{name}");
assert!((after.width_factor - expected.width_factor).abs() < 1e-9, "{name}");
}
}
}
#[test]
fn two_point_changed_justification_recomputes_measurements() {
for horizontal in [true, false] {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| {
if horizontal {
t.halign = if t.halign == HAlign::Fit { HAlign::Aligned } else { HAlign::Fit };
} else {
t.valign = VAlign::Middle;
}
});
for name in two_point_formats() {
check_two_point_save(&d, name, true, true);
}
}
}
#[test]
fn two_point_dwg_source_preserves_imported_measurements() {
let imported = imported_two_point_text_sample();
crate::dwg_worker::allow_in_process();
let dwg = write(&imported, "source.dwg").unwrap();
let reopened = read(&dwg, "source.dwg").unwrap();
assert!(!reopened.foreign.text_fits.is_empty());
for name in two_point_formats() {
check_two_point_save(&reopened, name, false, true);
}
}
#[test]
fn two_point_block_layout_and_empty_default() {
let mut d = Drawing::new_metric();
let mut block = Block::new("Labels");
for (index, halign) in [HAlign::Aligned, HAlign::Fit].into_iter().enumerate() {
let text = Text { halign, valign: VAlign::Middle, align_pt: Some(Vec3::new(30.0, 4.0, 0.0)), ..intl_text("SYNTHETIC") };
block.entities.push(Entity::new(Handle(0x500 + index as u64), EntityKind::Text(text.clone())));
d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Text(text)).unwrap();
let empty = Text { halign, align_pt: Some(Vec3::new(30.0, 4.0, 0.0)), ..intl_text("") };
block.entities.push(Entity::new(
Handle(0x510 + index as u64),
EntityKind::AttDef(Attrib {
tag: "LABEL".into(),
text: empty,
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
}),
));
}
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
for name in two_point_formats() {
let saved = read(&write(&d, name).unwrap(), name).unwrap();
for (before, after) in d.block("Labels").unwrap().entities.iter().zip(saved.block("Labels").unwrap().entities.iter()) {
match (&before.kind, &after.kind) {
(EntityKind::Text(a), EntityKind::Text(b)) => {
let expected = cadcraft_render::fitted_text_entity(&d, a, &a.value);
assert!((b.height - expected.height).abs() < 1e-9);
assert!((b.width_factor - expected.width_factor).abs() < 1e-9);
}
(EntityKind::AttDef(a), EntityKind::AttDef(b)) => {
assert!((a.text.height - b.text.height).abs() < 1e-9);
assert!((a.text.width_factor - b.text.width_factor).abs() < 1e-9);
assert!((b.text.rotation - b.text.insert.xy().angle_to(b.text.align_pt.unwrap().xy())).abs() < 1e-9);
}
_ => panic!("unexpected block entity"),
}
}
let before = &d.layout("Layout1").unwrap().entities;
let after = &saved.layout("Layout1").unwrap().entities;
for (a, b) in before.iter().zip(after.iter()) {
if let (EntityKind::Text(a), EntityKind::Text(b)) = (&a.kind, &b.kind) {
let expected = cadcraft_render::fitted_text_entity(&d, a, &a.value);
assert!((b.height - expected.height).abs() < 1e-9);
assert!((b.width_factor - expected.width_factor).abs() < 1e-9);
}
}
assert_eq!(before.len(), after.len());
}
}
#[test]
fn two_point_nonuniform_insert_keeps_attribute_fit_in_its_stored_coordinates() {
let mut d = two_point_text_sample();
for h in d.model.handles() {
d.model.modify(h, |e| {
if let EntityKind::Insert(i) = &mut e.kind {
i.scale = Vec3::new(2.0, 0.5, 1.0);
}
});
}
for name in two_point_formats() {
let saved = read(&write(&d, name).unwrap(), name).unwrap();
let insert = saved.model.iter().find_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i) } else { None }).unwrap();
let fit = insert.attribs.iter().find(|a| a.text.halign == HAlign::Fit).unwrap();
let width = cadcraft_fonts::shape_stroke_dir(&fit.text.value, fit.text.height, fit.text.width_factor, fit.text.oblique, Some(false)).width;
assert!((width - fit.text.insert.xy().dist(fit.text.align_pt.unwrap().xy())).abs() < 1e-9);
assert!((insert.scale.x - 2.0).abs() < 1e-9 && (insert.scale.y - 0.5).abs() < 1e-9);
}
}
fn intl_sample() -> Drawing {
let mut d = Drawing::new_metric();
let layer = format!("层 {INTL}");
@@ -2952,7 +2443,7 @@ fn gradient_sample() -> (Drawing, Vec<Option<Gradient>>) {
let h = Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices: square.clone(), outer: true, boundary_flags: Some(3), sources: Vec::new() }],
loops: vec![HatchLoop { vertices: square.clone(), outer: true, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
-48
View File
@@ -1,48 +0,0 @@
//! DIMASSOC is a drawing variable, written as HEADER group 280, independently of DIMSTYLE.
use cadcraft_doc::Drawing;
use cadcraft_io::{SaveOptions, Version, read_dxf, write, write_with};
/// Extract every DIMASSOC HEADER entry so duplicate or mistyped values fail the assertions.
fn dimassoc_groups(bytes: &[u8]) -> Vec<(i32, i64)> {
let tags = craft_dxf::parse(bytes).unwrap();
let header = craft_dxf::sections(&tags).into_iter().find(|s| s.name == "HEADER").unwrap();
let mut found = Vec::new();
for pair in header.tags.windows(2) {
if pair[0].code == 9 && pair[0].str() == "$DIMASSOC" {
found.push((pair[1].code, pair[1].i64()));
}
}
found
}
/// All supported modes use group 280 and survive each tested DXF version and encoding.
#[test]
fn new_drawing_modes_use_group_280_in_ascii_and_binary_dxf() {
for mode in [0, 1, 2] {
let mut d = Drawing::new_metric();
d.header.set_i64("DIMASSOC", mode);
for version in [Version::R2000, Version::R2004, Version::R2007, Version::R2018] {
for binary in [false, true] {
let bytes = write_with(&d, "setting.dxf", &SaveOptions { version: Some(version), binary }).unwrap();
assert_eq!(dimassoc_groups(&bytes), [(280, mode)], "{version:?}, binary{binary}");
let back = read_dxf(&bytes).unwrap();
assert_eq!(back.header.i64("DIMASSOC", -1), mode);
}
}
}
}
/// Editing an imported mode replaces its stored value without emitting a second HEADER entry.
#[test]
fn an_imported_mode_can_be_changed_without_a_stale_or_duplicate_header() {
let source = b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$DIMASSOC\n280\n1\n0\nENDSEC\n0\nEOF\n";
let mut d = read_dxf(source).unwrap();
assert_eq!(d.header.i64("DIMASSOC", -1), 1);
for mode in [1, 0, 2] {
d.header.set_i64("DIMASSOC", mode);
let bytes = write(&d, "edited.dxf").unwrap();
assert_eq!(dimassoc_groups(&bytes), [(280, mode)]);
d = read_dxf(&bytes).unwrap();
assert_eq!(d.header.i64("DIMASSOC", -1), mode);
}
}
+1 -1
View File
@@ -370,7 +370,7 @@ fn top_line_kept_objects_and_unknown(handle: Handle) -> Drawing {
RawTag { code: 100, value: "SyntheticWidget".into() },
RawTag { code: 1, value: "widget".into() },
];
let kind = EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags, graphics: Vec::new() });
let kind = EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags });
d.model.push(Entity { handle, common: Common::default(), kind });
d
}
+1 -1
View File
@@ -166,7 +166,7 @@ fn sat_text_is_told_by_its_subclass_and_a_geometry_record() {
use cadcraft_doc::foreign::{Foreign, sat_text_acis};
use cadcraft_doc::{Handle, RawTag, Unknown};
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
let solid = |tags: Vec<RawTag>| Unknown { dxf_type: "3DSOLID".into(), tags, graphics: Vec::new() };
let solid = |tags: Vec<RawTag>| Unknown { dxf_type: "3DSOLID".into(), tags };
let none = std::collections::BTreeSet::new();
let h = Handle(0x2B);
// A stray 1 or 3 outside AcDbModelerGeometry is not SAT text.
+1 -1
View File
@@ -118,7 +118,7 @@ fn hatch(pattern: &str, gradient: Option<Gradient>) -> Hatch {
Hatch {
pattern: pattern.into(),
solid: pattern == "SOLID",
loops: vec![HatchLoop { vertices: square(10.0), outer: true, boundary_flags: None, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: square(10.0), outer: true, sources: Vec::new() }],
scale: 2.0,
angle: 0.25,
associative: false,
+5 -5
View File
@@ -41,8 +41,8 @@ fn source_boundary_objects_roundtrip() {
let outer = poly(&mut d, square(0.0, 20.0));
let island = poly(&mut d, square(5.0, 5.0));
let loops = vec![
HatchLoop { vertices: square(0.0, 20.0), outer: true, boundary_flags: None, sources: vec![outer] },
HatchLoop { vertices: square(5.0, 5.0), outer: false, boundary_flags: None, sources: vec![island] },
HatchLoop { vertices: square(0.0, 20.0), outer: true, sources: vec![outer] },
HatchLoop { vertices: square(5.0, 5.0), outer: false, sources: vec![island] },
];
d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(loops.clone(), true))).expect("add");
// A non-associative hatch writes no sources; a source that is gone isn't written.
@@ -79,7 +79,7 @@ fn join(p: &[(i32, String)]) -> String {
fn sources_after_spline_fit_data_and_hostile_counts() {
let mut d = Drawing::new_imperial();
let outer = poly(&mut d, square(0.0, 20.0));
let loops = vec![HatchLoop { vertices: square(0.0, 20.0), outer: true, boundary_flags: None, sources: vec![outer] }];
let loops = vec![HatchLoop { vertices: square(0.0, 20.0), outer: true, sources: vec![outer] }];
d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(loops, true))).expect("add");
let p = pairs(&write_dxf(&d));
let start = p.iter().position(|(c, v)| *c == 0 && v == "HATCH").expect("HATCH");
@@ -127,11 +127,11 @@ fn a_hatch_in_a_block_keeps_its_boundary_and_the_boundary_its_reactor() {
let fill = d.new_handle();
let k = EntityKind::LwPolyline(LwPolyline { vertices: square(0.0, 10.0), closed: true, const_width: 0.0, elevation: 0.0, plinegen: false });
b.entities.push(Entity::new(outline, k));
let loops = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, boundary_flags: None, sources: vec![outline] }];
let loops = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, sources: vec![outline] }];
b.entities.push(Entity::new(fill, EntityKind::Hatch(hatch(loops, true))));
d.blocks.insert("Tag".into(), std::sync::Arc::new(b));
// A model-space hatch whose source is in the block is not linked to it.
let stray = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, boundary_flags: None, sources: vec![outline] }];
let stray = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, sources: vec![outline] }];
let other = d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(stray, true))).expect("add");
let p = pairs(&write_dxf(&d));
let poly = record(&p, "LWPOLYLINE", outline);
-145
View File
@@ -1,145 +0,0 @@
use cadcraft_doc::{Drawing, EntityKind, HatchLoop, Region};
use cadcraft_io::{read_dxf, write_dxf};
fn boundary(points: &[(f64, f64)], flags: i64) -> String {
let mut text = format!("92\n{flags}\n");
if flags & 2 != 0 {
text.push_str(&format!("72\n0\n73\n1\n93\n{}\n", points.len()));
for (point_x, point_y) in points {
text.push_str(&format!("10\n{point_x}\n20\n{point_y}\n"));
}
} else {
text.push_str(&format!("93\n{}\n", points.len()));
for (start, end) in points.iter().zip(points.iter().cycle().skip(1)) {
text.push_str(&format!("72\n1\n10\n{}\n20\n{}\n11\n{}\n21\n{}\n", start.0, start.1, end.0, end.1));
}
}
text.push_str("97\n0\n");
text
}
fn logo(flags: [i64; 4]) -> String {
let hexagon = [(-10.0, 0.0), (-5.0, -8.0), (5.0, -8.0), (10.0, 0.0), (5.0, 8.0), (-5.0, 8.0)];
let letter = [(-3.0, -4.0), (3.0, -4.0), (3.0, -2.0), (-1.0, -2.0), (-1.0, 4.0), (-3.0, 4.0)];
let right: Vec<_> = hexagon.iter().map(|(point_x, point_y)| (point_x + 28.0, *point_y)).collect();
let hole: Vec<_> = hexagon.iter().map(|(point_x, point_y)| (point_x * 0.6 + 28.0, point_y * 0.6)).collect();
let mut text = String::from("0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n");
for (index, loops) in
[[(&hexagon[..], flags[0]), (&letter[..], flags[1])], [(&right[..], flags[2]), (&hole[..], flags[3])]].into_iter().enumerate()
{
text.push_str(&format!(
"0\nHATCH\n5\n{:X}\n100\nAcDbEntity\n8\n0\n100\nAcDbHatch\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0\n230\n1\n2\nSOLID\n70\n1\n71\n0\n91\n2\n",
0x100 + index
));
for (points, flags) in loops {
text.push_str(&boundary(points, flags));
}
text.push_str("75\n1\n76\n1\n98\n0\n");
}
text.push_str("0\nENDSEC\n0\nEOF\n");
text
}
fn flags_written(drawing: &Drawing) -> Vec<i64> {
let text = write_dxf(drawing);
let lines: Vec<_> = text.lines().collect();
let mut hatch = false;
lines
.as_chunks::<2>()
.0
.iter()
.filter_map(|pair| {
let code: i32 = pair[0].trim().parse().unwrap();
if code == 0 {
hatch = pair[1].trim() == "HATCH";
}
if hatch && code == 92 { Some(pair[1].trim().parse().unwrap()) } else { None }
})
.collect()
}
#[test]
fn boundary_flags_survive_dxf_open_and_save() {
for flags in [[7, 22, 7, 6], [7, 22, 6, 20], [0, 9, 16, 31]] {
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
let expected = flags.map(|flag| flag | 2);
assert_eq!(flags_written(&drawing), expected);
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
assert_eq!(flags_written(&back), expected);
for entity in back.model.iter() {
if let EntityKind::Hatch(hatch) = &entity.kind {
let json = serde_json::to_vec(&hatch.loops).unwrap();
let restored: Vec<HatchLoop> = serde_json::from_slice(&json).unwrap();
assert_eq!(restored, hatch.loops);
}
}
}
}
#[test]
fn reclassified_loops_write_current_external_bit() {
for imported in [7, 23] {
let mut drawing = read_dxf(logo([7, imported, 7, 6]).as_bytes()).unwrap();
let handle = drawing.model.iter().next().unwrap().handle;
drawing.model.modify(handle, |entity| {
let EntityKind::Hatch(hatch) = &mut entity.kind else { panic!("expected hatch") };
assert!(hatch.loops[1].outer);
let mut region = Region { loops: hatch.loops.clone() };
assert!(region.renest());
hatch.loops = region.loops;
assert!(!hatch.loops[1].outer);
assert_eq!(hatch.loops[1].boundary_flags, Some(imported));
});
let written = flags_written(&drawing)[1];
assert_eq!(written & 1, 0);
assert_eq!(written & (4 | 16), imported & (4 | 16));
assert_ne!(written & 2, 0);
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
assert_eq!(flags_written(&back), flags_written(&drawing));
}
}
#[test]
fn undocumented_boundary_bits_are_not_written_back() {
let flags = [i64::MAX, -1, 32 | 7, i64::MIN | 22];
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
let expected = flags.map(|flag| (flag & 31) | 2);
assert_eq!(flags_written(&drawing), expected);
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
assert_eq!(flags_written(&back), expected);
}
#[test]
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
fn boundary_flags_survive_dwg_open_and_both_save_formats() {
cadcraft_io::dwg_worker::allow_in_process();
for flags in [[7, 22, 7, 6], [7, 22, 6, 20]] {
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
let bytes = cadcraft_io::write(&drawing, "logo.dwg").unwrap();
let back = cadcraft_io::read(&bytes, "logo.dwg").unwrap();
let expected = flags.map(|flag| flag | 2);
assert_eq!(flags_written(&back), expected);
let again = cadcraft_io::write(&back, "logo.dwg").unwrap();
assert_eq!(flags_written(&cadcraft_io::read(&again, "logo.dwg").unwrap()), expected);
}
}
#[test]
fn old_serialized_loops_keep_locally_created_flags() {
let mut drawing = read_dxf(logo([7, 22, 6, 20]).as_bytes()).unwrap();
let mut expected = Vec::new();
let handles: Vec<_> = drawing.model.iter().map(|entity| entity.handle).collect();
for handle in handles {
drawing.model.modify(handle, |entity| {
if let EntityKind::Hatch(hatch) = &mut entity.kind {
for boundary in &mut hatch.loops {
let mut json = serde_json::to_value(&*boundary).unwrap();
json.as_object_mut().unwrap().remove("boundary_flags");
*boundary = serde_json::from_value::<HatchLoop>(json).unwrap();
expected.push(2 | i64::from(boundary.outer));
}
}
});
}
assert_eq!(flags_written(&drawing), expected);
}
+1 -1
View File
@@ -8,7 +8,7 @@ use cadcraft_io::{read_dxf, write_dxf};
fn square() -> HatchLoop {
let v = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].into_iter().map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
HatchLoop { vertices: v, outer: true, boundary_flags: None, sources: Vec::new() }
HatchLoop { vertices: v, outer: true, sources: Vec::new() }
}
fn hatch(pattern: &str, scale: f64, angle: f64, origin: Vec2, lines: Vec<PatternLine>) -> Hatch {
-38
View File
@@ -72,41 +72,3 @@ fn the_page_still_decides_the_bits_cadcraft_models() {
d.layouts.last_mut().unwrap().page = PageSetup::default();
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128 | 32 | 16));
}
/// Each LAYOUT object's name and plot layout flags (the AcDbLayout group 1 and the
/// AcDbPlotSettings group 70) in DXF text.
fn layout_plot_flags(text: &str) -> Vec<(String, i64)> {
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let mut out = Vec::new();
let (mut inside, mut subclass, mut name, mut flags) = (false, "", None, None);
for pair in lines.chunks(2) {
let [code, value] = pair else { break };
match *code {
"0" => {
if let (true, Some(n), Some(f)) = (inside, name.take(), flags.take()) {
out.push((n, f));
}
(inside, subclass, name, flags) = (*value == "LAYOUT", "", None, None);
}
"100" if inside => subclass = value,
"70" if inside && subclass == "AcDbPlotSettings" => flags = value.parse().ok(),
"1" if inside && subclass == "AcDbLayout" => name = Some(value.to_string()),
_ => {}
}
}
out
}
#[test]
fn only_the_model_layout_carries_the_model_type_flag() {
// 1024 is "ModelType" (DXF Reference, PLOTSETTINGS group 70): the plot settings of model space.
// The Model layout carries it; a paper layout does not, even when it was read with it.
for read in [688, 688 | 1024] {
let bytes = write(&drawing(read), "sheet.dxf").unwrap();
let layouts = layout_plot_flags(&String::from_utf8_lossy(&bytes));
let flags = |name: &str| layouts.iter().find(|(n, _)| n == name).map(|&(_, f)| f);
let (model, sheet) = (flags("Model").unwrap(), flags("SHEET").unwrap());
assert_ne!(model & 1024, 0, "Model, SHEET read with {read}: {layouts:?}");
assert_eq!(sheet & 1024, 0, "SHEET read with {read}: {layouts:?}");
}
}
-4
View File
@@ -31,7 +31,6 @@ mod exhausted_handseed;
mod followups_626;
mod groups_roundtrip;
mod hatch_assoc_roundtrip;
mod hatch_loop_flags;
mod hatch_pattern_def;
mod helix_roundtrip;
mod layer_states_acad;
@@ -69,7 +68,6 @@ mod plot_model_png_scale;
mod plot_styles;
mod polyface_roundtrip;
mod portable_fonts;
mod proxy_graphics;
mod region_roundtrip;
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod render_settings_version;
@@ -92,7 +90,5 @@ mod user_lin_pat_roundtrip;
mod view_tables_roundtrip;
mod view_target;
mod viewport_clip_roundtrip;
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod visualstyle_dwg;
mod xclip_roundtrip;
mod xref_roundtrip;
-172
View File
@@ -1,172 +0,0 @@
//! ACAD_PROXY_ENTITY draws its proxy graphics (#2646): read from DXF with the table indices of the
//! file, measured in the extents, and written back unchanged.
use cadcraft_doc::color::Color;
use cadcraft_doc::{EntityKind, Space};
use cadcraft_io::{read_dxf, write_dxf};
/// A proxy graphics chunk of type `kind`, its data padded to four bytes.
fn chunk(kind: u32, data: &[u8]) -> Vec<u8> {
let mut d = data.to_vec();
d.resize(d.len().div_ceil(4) * 4, 0);
let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec();
out.extend(kind.to_le_bytes());
out.extend(d);
out
}
/// A point in the XY plane as three doubles.
fn pt(x: f64, y: f64) -> Vec<u8> {
[x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect()
}
/// A balloon: layer 1 of the file's LAYER table, colour 1, a circle, a leader and the number.
fn balloon() -> Vec<u8> {
let mut circle = pt(175.0, 115.0);
circle.extend(6.0f64.to_le_bytes());
circle.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
let mut leader = 2u32.to_le_bytes().to_vec();
leader.extend(pt(170.8, 110.8));
leader.extend(pt(150.0, 90.0));
let mut text = pt(172.9, 112.0);
text.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
text.extend(pt(1.0, 0.0));
text.extend(b"1\0\0\0");
text.extend(1i32.to_le_bytes());
text.extend(0i32.to_le_bytes());
for v in [6.0f64, 1.0, 0.0, 0.0] {
text.extend(v.to_le_bytes());
}
text.extend([0u8; 20]);
text.extend(b"isocp.shx\0\0\0\0\0\0\0");
let chunks = [chunk(16, &1u32.to_le_bytes()), chunk(14, &1u32.to_le_bytes()), chunk(2, &circle), chunk(6, &leader), chunk(11, &text)];
let body = chunks.concat();
let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec();
out.extend((chunks.len() as u32).to_le_bytes());
out.extend(body);
out
}
/// A DXF whose LAYER table holds 0 and BALLOONS only (CADCraft keeps Defpoints at index 1 of
/// its own table), a text style on isocp.shx, a line and one proxy balloon.
fn file() -> String {
let graphics = balloon();
let hex: Vec<String> = graphics.chunks(127).map(|c| c.iter().map(|b| format!("{b:02X}")).collect()).collect();
let mut tags: Vec<(i32, String)> = vec![(0, "SECTION".into()), (2, "CLASSES".into())];
for (c, v) in [(0, "CLASS"), (1, "SYNBALLOON"), (2, "SynBalloon"), (3, "SyntheticProxyApp"), (90, "0"), (280, "0"), (281, "1"), (0, "ENDSEC")] {
tags.push((c, v.into()));
}
for (c, v) in [
(0, "SECTION"),
(2, "TABLES"),
(0, "TABLE"),
(2, "LAYER"),
(0, "LAYER"),
(5, "10"),
(2, "0"),
(62, "7"),
(0, "LAYER"),
(5, "11"),
(2, "BALLOONS"),
(62, "3"),
(0, "ENDTAB"),
(0, "TABLE"),
(2, "STYLE"),
(0, "STYLE"),
(5, "12"),
(2, "ISO"),
(3, "isocp.shx"),
(0, "ENDTAB"),
(0, "ENDSEC"),
(0, "SECTION"),
(2, "ENTITIES"),
(0, "LINE"),
(5, "20"),
(8, "0"),
(10, "50"),
(20, "40"),
(11, "150"),
(21, "90"),
(0, "ACAD_PROXY_ENTITY"),
(5, "21"),
(100, "AcDbEntity"),
(8, "0"),
(100, "AcDbProxyEntity"),
(90, "498"),
(91, "500"),
(95, "0"),
(70, "0"),
] {
tags.push((c, v.into()));
}
tags.push((92, graphics.len().to_string()));
tags.extend(hex.into_iter().map(|h| (310, h)));
for (c, v) in [(93, "0"), (94, "0"), (0, "ENDSEC"), (0, "EOF")] {
tags.push((c, v.into()));
}
tags.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
}
#[test]
fn a_proxy_draws_its_graphics_with_the_files_table_indices() {
let d = read_dxf(file().as_bytes()).expect("read");
let proxy = d.model.iter().find(|e| matches!(e.kind, EntityKind::Unknown(_))).expect("proxy");
let EntityKind::Unknown(u) = &proxy.kind else { unreachable!() };
let kinds: Vec<(&str, &str, Color)> = u.graphics.iter().map(|g| (g.kind.dxf_name(), g.common.layer.as_str(), g.common.color)).collect();
// Layer index 1 is BALLOONS, the file's second layer, not CADCraft's Defpoints.
assert_eq!(kinds, [("CIRCLE", "BALLOONS", Color::Index(1)), ("LINE", "BALLOONS", Color::Index(1)), ("TEXT", "BALLOONS", Color::Index(1))]);
assert!(matches!(&u.graphics[2].kind, EntityKind::Text(t) if t.value == "1" && t.style == "ISO"));
// The extents reach the balloon (the line alone ends at 150, 90).
let b = d.extents(&Space::Model);
assert!(b.max.x >= 181.0 && b.max.y >= 121.0, "{b:?}");
}
#[test]
fn a_proxy_is_written_back_unchanged_and_draws_again() {
let d = read_dxf(file().as_bytes()).expect("read");
let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen");
let graphics = |d: &cadcraft_doc::Drawing| {
d.model.iter().find_map(|e| match &e.kind {
EntityKind::Unknown(u) => Some((u.proxy_graphics_bytes(), u.graphics.len())),
_ => None,
})
};
assert_eq!(graphics(&again), graphics(&d));
assert_eq!(graphics(&d).map(|g| g.1), Some(3));
// The saved LAYER table keeps the file's order, so index 1 is still BALLOONS (CADCraft's
// Defpoints comes after it) and the reopened graphics stay on that layer.
let layers = |d: &cadcraft_doc::Drawing| -> Vec<String> {
d.model
.iter()
.find_map(|e| match &e.kind {
EntityKind::Unknown(u) => Some(u.graphics.iter().map(|g| g.common.layer.clone()).collect()),
_ => None,
})
.unwrap_or_default()
};
assert_eq!(layers(&again), ["BALLOONS"; 3]);
let names: Vec<&str> = again.layers.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, ["0", "BALLOONS", "Defpoints"]);
}
/// A proxy text takes the first style on its font. With ISO and then Standard both on
/// isocp.shx, it is ISO, and stays ISO after a save: CADCraft's own Standard, which the file's
/// replaces, would otherwise come first in the saved STYLE table.
#[test]
fn a_proxy_text_keeps_its_style_after_a_save() {
let iso = "0\nSTYLE\n5\n12\n2\nISO\n3\nisocp.shx\n";
let src = file().replacen(iso, &format!("{iso}0\nSTYLE\n5\n13\n2\nStandard\n3\nisocp.shx\n"), 1);
let style = |d: &cadcraft_doc::Drawing| {
d.model.iter().find_map(|e| match &e.kind {
EntityKind::Unknown(u) => u.graphics.iter().find_map(|g| match &g.kind {
EntityKind::Text(t) => Some(t.style.clone()),
_ => None,
}),
_ => None,
})
};
let d = read_dxf(src.as_bytes()).expect("read");
assert_eq!(style(&d).as_deref(), Some("ISO"));
let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen");
assert_eq!(style(&again).as_deref(), Some("ISO"), "after a save");
}
+1 -2
View File
@@ -19,7 +19,7 @@ fn regions(d: &Drawing) -> Vec<Region> {
fn square(x: f64, y: f64, s: f64, outer: bool) -> HatchLoop {
let v = |a: f64, b: f64| PolyVertex::new(Vec2::new(a, b));
HatchLoop { vertices: vec![v(x, y), v(x + s, y), v(x + s, y + s), v(x, y + s)], outer, boundary_flags: None, sources: Vec::new() }
HatchLoop { vertices: vec![v(x, y), v(x + s, y), v(x + s, y + s), v(x, y + s)], outer, sources: Vec::new() }
}
#[test]
@@ -29,7 +29,6 @@ fn region_with_islands_survives_save_and_reopen() {
let hole = HatchLoop {
vertices: vec![PolyVertex::with_bulge(Vec2::new(3.0, 5.0), 1.0), PolyVertex::with_bulge(Vec2::new(7.0, 5.0), 1.0)],
outer: false,
boundary_flags: None,
sources: Vec::new(),
};
let r = Region { loops: vec![square(0.0, 0.0, 10.0, true), hole, square(4.5, 4.5, 1.0, true), square(20.0, 0.0, 2.0, true)] };
@@ -226,7 +226,7 @@ pub(crate) fn hatches() -> Vec<Case> {
EntityKind::Hatch(Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, boundary_flags: Some(3), sources: Vec::new() }],
loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
-50
View File
@@ -373,53 +373,3 @@ fn angle_tolerance_does_not_hide_real_changes_or_nonfinite_values() {
assert!(std::panic::catch_unwind(|| angle(0.7, actual, "self-test", "angle")).is_err());
}
}
/// Authored two-point text saves the dimensions of its measured span. Expectations come from
/// shaping and geometry, independently of the save fitting helper; all field assertions remain.
pub(super) fn authored_text_dimensions(d: &Drawing) -> Drawing {
fn fit(d: &Drawing, t: &mut Text) {
use cadcraft_doc::HAlign;
if !matches!(t.halign, HAlign::Aligned | HAlign::Fit) {
return;
}
let Some(second) = t.align_pt else { return };
let distance = t.insert.xy().dist(second.xy());
if !distance.is_finite() || distance <= 1e-12 {
return;
}
t.rotation = t.insert.xy().angle_to(second.xy());
let style = d.text_style(&t.style).cloned().unwrap_or_default();
let font = cadcraft_render::style_font(&style);
let width = cadcraft_fonts::shape_line_dir(&font, &t.value, t.height, t.width_factor, t.oblique, Some(false)).width;
if width.is_finite() && width > 1e-12 {
if t.halign == HAlign::Aligned {
t.height *= distance / width;
} else {
t.width_factor *= distance / width;
}
}
}
fn store(d: &Drawing, entities: &mut EntityStore) {
for h in entities.handles() {
// Read-time measurements already have their own preservation contract.
if d.foreign.text_fits.contains_key(&h) {
continue;
}
entities.modify(h, |e| match &mut e.kind {
EntityKind::Text(t) => fit(d, t),
EntityKind::AttDef(a) => fit(d, &mut a.text),
EntityKind::Insert(i) => i.attribs.iter_mut().for_each(|a| fit(d, &mut a.text)),
_ => {}
});
}
}
let mut expected = d.clone();
store(d, &mut expected.model);
for layout in &mut expected.layouts {
store(d, &mut layout.entities);
}
for block in expected.blocks.values_mut() {
store(d, &mut std::sync::Arc::make_mut(block).entities);
}
expected
}
-2
View File
@@ -57,8 +57,6 @@ fn check_version_with(case: &str, original: &Drawing, expected: &Drawing, versio
}
fn check_version_using(case: &str, original: &Drawing, expected: &Drawing, version: Version, verify: impl Fn(&Drawing, &Drawing, &str)) {
let expected_dimensions = compare::authored_text_dimensions(expected);
let expected = &expected_dimensions;
cadcraft_io::dwg_worker::allow_in_process();
let options = SaveOptions { version: Some(version), binary: false };
let mut current = original.clone();
-2
View File
@@ -33,8 +33,6 @@ fn check_version(case: &str, original: &Drawing, expected: &Drawing, version: Ve
}
fn check_version_with(case: &str, original: &Drawing, expected: &Drawing, version: Version, extra: impl Fn(&Drawing, &Drawing, &str)) {
let expected_dimensions = compare::authored_text_dimensions(expected);
let expected = &expected_dimensions;
for binary in [false, true] {
let options = SaveOptions { version: Some(version), binary };
let mut current = original.clone();
+1 -1
View File
@@ -27,7 +27,7 @@ fn drawing() -> Drawing {
RawTag { code: 30, value: "3.75".into() },
RawTag { code: 330, value: target.hex() },
];
d.model.push(Entity::new(handle, EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags, graphics: Vec::new() })));
d.model.push(Entity::new(handle, EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags })));
d.model.push(Entity::new(target, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(5.0, 6.0, 7.0) })));
d
}
+1 -1
View File
@@ -19,7 +19,7 @@ fn user_linetypes_and_patterns_survive_dxf() {
let h = Hatch {
pattern: steps.name.clone(),
solid: false,
loops: vec![HatchLoop { vertices: square, outer: true, boundary_flags: None, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: square, outer: true, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
-95
View File
@@ -1,95 +0,0 @@
//! Original synthetic geometry, style values and xdata, licensed with the repository.
//! The fixed fields follow Autodesk's 2010 DXF Reference, VISUALSTYLE, pp. 208-210:
//! https://images.autodesk.com/adsk/files/acad_dxf1.pdf
use cadcraft_doc::EntityKind;
use cadcraft_io::{SaveOptions, Version};
fn source(version: &str) -> String {
let mut text = format!(
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\n{version}\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nAPPID\n5\n10\n100\nAcDbSymbolTable\n70\n1\n\
0\nAPPID\n5\n11\n330\n10\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n2\nACAD\n70\n0\n0\nENDTAB\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n30\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n30\n0\n11\n10\n21\n5\n31\n0\n0\nENDSEC\n\
0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_VISUALSTYLE\n350\n20\n\
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nSynthetic0\n350\n21\n3\nSynthetic1\n350\n22\n"
);
for index in 0..2 {
text.push_str(&format!(
"0\nVISUALSTYLE\n5\n{:X}\n330\n20\n100\nAcDbVisualStyle\n2\nSynthetic{index}\n\
70\n0\n71\n1\n72\n1\n73\n1\n90\n0\n40\n1.0\n41\n0.5\n63\n7\n\
74\n2\n91\n0\n64\n7\n65\n7\n75\n1\n175\n1\n42\n30.0\n92\n0\n66\n7\n43\n1.0\n\
76\n1\n77\n0\n78\n0\n67\n7\n79\n1\n170\n0\n171\n0\n290\n0\n174\n0\n93\n0\n44\n0.0\n173\n0\n291\n0\n\
1001\nACAD\n1000\nAcRTDxfName\n1000\nVISUALSTYLE\n",
0x21 + index
));
}
text.push_str("0\nENDSEC\n0\nEOF\n");
text
}
#[test]
fn legacy_visualstyles_are_reported_and_left_out_of_2007_dwg_only() {
cadcraft_io::dwg_worker::allow_in_process();
for from in ["AC1021", "AC1024"] {
let drawing = cadcraft_io::read_dxf(source(from).as_bytes()).unwrap();
let styles = || drawing.foreign.objects.iter().filter(|object| object.kind == "VISUALSTYLE").count();
assert_eq!(styles(), 2);
for version in [Version::R2007, Version::R2013] {
let options = SaveOptions { version: Some(version), binary: false };
let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap();
let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap();
assert!(back.model.iter().any(|entity| matches!(entity.kind, EntityKind::Line(_))));
let retained = back
.foreign
.objects
.iter()
.any(|object| object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 2 && tag.value.starts_with("Synthetic")));
if version == Version::R2007 {
assert_eq!(report.get("VISUALSTYLE"), Some(&styles()));
assert!(!retained);
} else {
assert!(!report.contains_key("VISUALSTYLE"));
assert!(retained);
}
let (dxf, report) = cadcraft_io::write_noted(&drawing, "styles.dxf", &options).unwrap();
assert!(report.is_empty());
let back = cadcraft_io::read_dxf(&dxf).unwrap();
assert_eq!(back.foreign.objects.iter().filter(|object| object.kind == "VISUALSTYLE").count(), styles());
}
assert_eq!(styles(), 2);
}
}
#[test]
fn orphaned_legacy_visualstyles_are_not_reported_as_compatibility_omissions() {
cadcraft_io::dwg_worker::allow_in_process();
let mut drawing = cadcraft_io::read_dxf(source("AC1021").as_bytes()).unwrap();
let foreign = std::sync::Arc::make_mut(&mut drawing.foreign);
let orphan = foreign.objects.iter_mut().find(|object| object.kind == "VISUALSTYLE").unwrap();
orphan.tags.iter_mut().find(|tag| tag.code == 330).unwrap().value = "FF".into();
let options = SaveOptions { version: Some(Version::R2007), binary: false };
let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap();
let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap();
assert!(back.model.iter().any(|entity| matches!(entity.kind, EntityKind::Line(_))));
assert_eq!(report.get("VISUALSTYLE"), Some(&1));
}
#[test]
fn newer_visualstyle_properties_are_kept_in_2007_dwg() {
cadcraft_io::dwg_worker::allow_in_process();
let document = acadrust::DxfReader::from_reader(std::io::Cursor::new(source("AC1027").into_bytes())).unwrap().read().unwrap();
let modern = acadrust::DxfWriter::new(&document).write_to_vec().unwrap();
let drawing = cadcraft_io::read_dxf(&modern).unwrap();
assert!(drawing.foreign.objects.iter().any(|object| object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 176)));
let options = SaveOptions { version: Some(Version::R2007), binary: false };
let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap();
assert!(!report.contains_key("VISUALSTYLE"));
let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap();
assert!(
back.foreign
.objects
.iter()
.any(|object| { object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 2 && tag.value.starts_with("Synthetic")) })
);
}
-17
View File
@@ -40,23 +40,6 @@ pub(crate) fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> {
}
}
/// A proxy entity draws its proxy graphics as AutoCAD does with PROXYSHOW 1, like block contents:
/// layer 0 and ByBlock in the picture stand for the proxy's own layer and properties. Other
/// unknown records draw nothing. `own` is the proxy's transparency without its locked-layer fade,
/// as for a block reference.
pub(crate) fn proxy(b: &mut Builder, ctx: &Ctx, e: &Entity, u: &cadcraft_doc::Unknown, own: u8) {
if u.graphics.is_empty() || ctx.depth >= cadcraft_doc::MAX_BLOCK_DEPTH {
return;
}
let sub = Ctx { block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, Mat3::IDENTITY) };
for g in &u.graphics {
if !b.expand() {
break;
}
entity(b, &sub, g);
}
}
/// `own` is the reference's resolved transparency without its locked-layer fade: what ByBlock
/// children inherit (a child fades only for its own layer).
pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert, rgb: Ink, own: u8) {
+7 -13
View File
@@ -1,4 +1,4 @@
use super::blocks::{insert, proxy, sub_ctx};
use super::blocks::{insert, sub_ctx};
use super::dim_draw::{MAX_FILL_SOLIDS, MAX_FILL_TEXTS, block_text_box, dim_text_fill, dimension, dimension_in, solid_covers, starts_text_marks};
use super::display::{Kind, NO_LAYER, VIEWPORT_CONTENT};
use super::props::{resolve, transparency};
@@ -240,7 +240,12 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
b.polyline(ctx, rgb, lw, l);
}
}
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => draw_unknown(b, ctx, e, u, rgb, lw, own),
// An OLE object's content is not drawn; its frame, from its two corner points, is.
EntityKind::Unknown(u) if u.is_ole_frame() => {
if let Some(q) = cadcraft_doc::ole_frame(&u.tags) {
b.polyline(ctx, rgb, lw, &q);
}
}
kind => {
for prim in kind.prims() {
match prim {
@@ -297,17 +302,6 @@ fn draw_mleader(b: &mut Builder, ctx: &Ctx, e: &Entity, m: &cadcraft_doc::MLeade
}
}
/// A record kept as read that draws something: a proxy its proxy graphics, and an OLE object its
/// frame, from its two corner points (its content is not drawn). `own`: the proxy's transparency
/// without its locked-layer fade, for its graphics.
fn draw_unknown(b: &mut Builder, ctx: &Ctx, e: &Entity, u: &cadcraft_doc::Unknown, rgb: Ink, lw: f32, own: u8) {
if !u.graphics.is_empty() {
proxy(b, ctx, e, u, own);
} else if let Some(q) = cadcraft_doc::ole_frame(&u.tags) {
b.polyline(ctx, rgb, lw, &q);
}
}
fn draw_image(b: &mut Builder, ctx: &Ctx, i: &cadcraft_doc::Image, rgb: Ink, lw: f32) {
let o = i.insert.xy();
let u = i.u.xy() * i.size.x;
-1
View File
@@ -684,7 +684,6 @@ mod tests {
PolyVertex::new(Vec2::new(0.0, 10.0)),
],
outer: true,
boundary_flags: None,
sources: vec![],
};
let loop2 = loop1.clone();
+1 -1
View File
@@ -438,7 +438,7 @@ pub use display::{DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER,
pub use pipeline::{Options, build, build_entities, build_plot};
use props::{default_lineweight, resolve_common};
use text_entity::text_style;
pub use text_entity::{fitted_text_entity, layout_mtext_entity, place_text_entity, style_font, text_align};
pub use text_entity::{layout_mtext_entity, place_text_entity, style_font, text_align};
use viewports::{Clip, append_clipped_keep};
pub use viewports::{clip_list, viewport_clip, viewport_content};
+4 -51
View File
@@ -82,7 +82,7 @@ fn hatch_pattern_and_solid() {
let h = Hatch {
pattern: "ANSI31".into(),
solid: false,
loops: vec![HatchLoop { vertices: sq.clone(), outer: true, boundary_flags: None, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: sq.clone(), outer: true, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
@@ -514,7 +514,7 @@ fn pattern_hatch(pattern: &str, scale: f64, (x0, y0, x1, y1): (f64, f64, f64, f6
Hatch {
pattern: pattern.into(),
solid: false,
loops: vec![HatchLoop { vertices: sq.to_vec(), outer: true, boundary_flags: None, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: sq.to_vec(), outer: true, sources: Vec::new() }],
scale,
angle: 0.0,
associative: false,
@@ -1299,8 +1299,7 @@ fn raster_hatch_pattern_matches_one_by_one() {
#[test]
fn ole_frame_draws_its_outline() {
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
let frame =
|tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
let frame = |tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags });
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap();
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "1"), tag(20, "2")])).unwrap();
@@ -1334,51 +1333,6 @@ fn without_linetypes_every_line_is_drawn_whole() {
assert!(drawn.prims.len() > 2 * continuous.prims.len(), "drawn with its linetype: {} primitives", drawn.prims.len());
}
/// A proxy draws its proxy graphics like block contents: layer 0 and ByBlock in the picture are
/// the proxy's own, and the proxy's layer hides all of it.
#[test]
fn proxy_graphics_draw_like_block_contents() {
let mut d = Drawing::new_imperial();
d.layers.push(cadcraft_doc::Layer { name: "Notes".into(), color: Color::Index(3), ..Default::default() });
let byblock = Common { color: Color::ByBlock, ..Default::default() };
let graphics = vec![
block_entity(7, byblock, EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) })),
block_entity(
7,
Common { color: Color::Index(1), ..Default::default() },
EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::new(15.0, 0.0, 0.0), radius: 5.0 }),
),
];
let proxy = EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics });
d.add(&Space::Model, Common { layer: "Notes".into(), ..Default::default() }, proxy).unwrap();
let l = build(&d, &Space::Model, &Options::default());
assert_eq!(l.prims.iter().map(|p| p.color).collect::<Vec<_>>(), [Rgb(0, 255, 0), Rgb(255, 0, 0)]);
let b = d.extents(&Space::Model);
assert!((b.min.x, b.max.x, b.max.y) == (0.0, 20.0, 5.0), "{b:?}");
d.layer_mut("Notes").unwrap().frozen = true;
assert!(build(&d, &Space::Model, &Options::default()).prims.is_empty());
}
/// On a locked layer, a proxy's graphics fade like a block's contents: layer 0 in the picture takes
/// the proxy's fade, a ByBlock part on an unlocked layer only the proxy's own transparency.
#[test]
fn proxy_graphics_on_a_locked_layer_fade_like_block_contents() {
use cadcraft_doc::Transparency::{ByBlock, ByLayer, Percent};
for (own, want) in [(ByLayer, 0), (Percent(20), 20)] {
let mut d = Drawing::new_imperial();
d.layers.push(cadcraft_doc::Layer { name: "Locked".into(), locked: true, ..Default::default() });
d.layers.push(cadcraft_doc::Layer { name: "Open".into(), ..Default::default() });
let line = |x: f64| EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(x, 0.0, 0.0), b: Vec3::new(x + 1.0, 0.0, 0.0) });
let graphics = vec![
block_entity(7, Common::default(), line(0.0)),
block_entity(7, Common { layer: "Open".into(), transparency: ByBlock, ..Default::default() }, line(2.0)),
];
let proxy = EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics });
d.add(&Space::Model, Common { layer: "Locked".into(), transparency: own, ..Default::default() }, proxy).unwrap();
assert_eq!(faded(&build(&d, &Space::Model, &on_screen(with_transparency()))), vec![50.max(want), want], "{own:?}");
}
}
/// A broken table whose parts, with their repeated labels, together hold more cells than a table may
/// lay out is drawn as its outline, though the table's own cells are within the limit.
#[test]
@@ -1417,7 +1371,7 @@ fn rotated_and_reversed_copies_of_a_curved_loop_fill_once() {
}
}
v.rotate_left(rot);
HatchLoop { vertices: v, outer: true, boundary_flags: None, sources: Vec::new() }
HatchLoop { vertices: v, outer: true, sources: Vec::new() }
};
let mut h = pattern_hatch("SOLID", 1.0, (0.0, 0.0, 1.0, 1.0));
h.loops = vec![ring(0, false), ring(2, false), ring(1, true), ring(3, true)];
@@ -1426,7 +1380,6 @@ fn rotated_and_reversed_copies_of_a_curved_loop_fill_once() {
h.loops.push(HatchLoop {
vertices: ring(0, false).vertices.into_iter().map(|q| PolyVertex { bulge: 0.0, ..q }).collect(),
outer: true,
boundary_flags: None,
sources: Vec::new(),
});
assert_eq!(loops_of(&h).len(), 2);
+1 -13
View File
@@ -13,18 +13,6 @@ pub fn style_font(ts: &cadcraft_doc::TextStyle) -> cadcraft_fonts::TextFont {
/// Shape a TEXT / ATTRIB / ATTDEF with its style's font and generation flags.
pub fn place_text_entity(d: &Drawing, t: &cadcraft_doc::Text, value: &str) -> (cadcraft_fonts::Shaped, Bounds2) {
let (font, params) = text_params(d, t);
cadcraft_fonts::place(&font, value, &params)
}
/// The dimensions used to display a two-point TEXT, ATTRIB or ATTDEF, for file writers.
pub fn fitted_text_entity(d: &Drawing, t: &cadcraft_doc::Text, value: &str) -> cadcraft_doc::Text {
let (font, params) = text_params(d, t);
let fitted = cadcraft_fonts::fit_params(&font, value, &params);
cadcraft_doc::Text { height: fitted.height, rotation: fitted.rotation, width_factor: fitted.width_factor, ..t.clone() }
}
fn text_params(d: &Drawing, t: &cadcraft_doc::Text) -> (cadcraft_fonts::TextFont, cadcraft_fonts::TextParams) {
let ts = text_style(d, &t.style);
let font = style_font(&ts);
let (h, v) = align(t.halign, t.valign);
@@ -40,7 +28,7 @@ fn text_params(d: &Drawing, t: &cadcraft_doc::Text) -> (cadcraft_fonts::TextFont
backwards: ts.backwards,
upside_down: ts.upside_down,
};
(font, p)
cadcraft_fonts::place(&font, value, &p)
}
/// Lay out an MTEXT with its style's font.
+1 -1
View File
@@ -9,7 +9,7 @@ use cadcraft_render::{DisplayList, Kind, Options, build};
fn square(lo: f64, hi: f64) -> HatchLoop {
let v = [(lo, lo), (hi, lo), (hi, hi), (lo, hi)].into_iter().map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
HatchLoop { vertices: v, outer: lo == 0.0, boundary_flags: None, sources: Vec::new() }
HatchLoop { vertices: v, outer: lo == 0.0, sources: Vec::new() }
}
fn hatch(pattern: &str, loops: Vec<HatchLoop>) -> Hatch {
+1 -1
View File
@@ -1562,7 +1562,7 @@ mod tests {
let d = Drawing::new_metric();
assert!(too_much(&d, EntityKind::Wipeout(Wipeout { boundary: points.clone() })));
assert!(too_much(&d, EntityKind::MLine(MLine::new(&MLineStyle::default(), &points, false, MLineJust::default(), 1.0))));
let region = Region { loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, boundary_flags: None, sources: Vec::new() }] };
let region = Region { loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, sources: Vec::new() }] };
assert!(too_much(&d, EntityKind::Region(region)));
// An object with nothing in it still takes a visit, for each cell of an array.
let mut empty = Block::new("EMPTY");
+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), _) => {
+9 -14
View File
@@ -2,11 +2,10 @@
//! the spot where it went down, however fast the mouse is moving. Where the pointer goes while the
//! button is held only decides whether the press also becomes a drag:
//!
//! - holding still, or staying within the press tolerance, never makes a drag;
//! - holding still, or staying within [`TOLERANCE`] of the press, never makes a drag;
//! - once the pointer leaves the tolerance a timer starts; a button still down [`DRAG_DELAY`]
//! later is a drag (a selection window the press opened closes where the button comes up);
//! - returning within the selection-window tolerance resets the timer; a button that comes up
//! there or before the delay was a click (the window waits for the next press).
//! - a button that comes up sooner was a click (the window waits for the next press).
//!
//! The timer starts on leaving the tolerance, not on the press: pressing, holding still and then
//! moving and letting go quickly is still a click, as in AutoCAD.
@@ -19,16 +18,15 @@ use egui::{Modifiers, Pos2};
/// How far (points) the pointer may wander from the press before the timer starts.
pub(crate) const TOLERANCE: f32 = 6.0;
/// Extra room to click the first corner of a window without committing it by accident.
const WINDOW_TOLERANCE: f32 = 12.0;
/// How long (seconds) the button must stay down outside the tolerance for the press to be a drag.
/// How long (seconds) the button must stay down after the pointer left [`TOLERANCE`] for the
/// press to be a drag.
pub(crate) const DRAG_DELAY: f64 = 0.25;
/// A primary-button press being held.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Press {
origin: Pos2,
/// When the pointer went outside the press tolerance (seconds).
/// When the pointer first went further than [`TOLERANCE`] from `origin` (seconds).
left_at: Option<f64>,
/// The press opened a selection window (set its first corner).
pub(crate) opened_window: bool,
@@ -62,11 +60,8 @@ impl Press {
/// The pointer is at `pos` at time `now`.
pub(crate) fn moved(&mut self, pos: Pos2, now: f64) {
let tolerance = if self.opened_window { WINDOW_TOLERANCE } else { TOLERANCE };
if pos.distance(self.origin) > tolerance {
self.left_at.get_or_insert(now);
} else if self.opened_window {
self.left_at = None;
if self.left_at.is_none() && pos.distance(self.origin) > TOLERANCE {
self.left_at = Some(now);
}
}
@@ -114,7 +109,7 @@ mod tests {
#[test]
fn letting_go_soon_after_leaving_the_tolerance_is_a_click() {
let mut p = Press::new(pos2(100.0, 100.0), true);
p.moved(pos2(115.0, 100.0), 1.0);
p.moved(pos2(112.0, 100.0), 1.0);
assert!(!p.released_as_drag(pos2(130.0, 100.0), 1.0 + DRAG_DELAY / 2.0));
}
@@ -129,7 +124,7 @@ mod tests {
#[test]
fn a_button_still_down_after_the_delay_is_a_drag() {
let mut p = Press::new(pos2(100.0, 100.0), true);
p.moved(pos2(115.0, 100.0), 1.0);
p.moved(pos2(110.0, 100.0), 1.0);
p.moved(pos2(200.0, 150.0), 1.1);
assert!(p.released_as_drag(pos2(250.0, 160.0), 1.0 + DRAG_DELAY));
}
+2 -19
View File
@@ -73,7 +73,7 @@ pub const OPEN_RECENT: &str = "Open Recent";
/// The last item of File ▸ Open Recent.
pub const CLEAR_RECENT: &str = "Clear Recent Files";
const RECENT_ITEM: &str = "ui.recent.";
pub const RECENT_CLEAR: &str = "ui.recent.clear";
const RECENT_CLEAR: &str = "ui.recent.clear";
/// UI-only commands: (id, label, menu path, shortcut).
pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
@@ -459,13 +459,7 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Re
.unwrap_or(Ok(Value::Null)),
"ui.saveas" | "saveas" if no_path => {
let title = app.session.state().map(|s| s.title.clone()).ok();
// `format` ("dxf" or "dwg") is only this dialog's suggestion. Without it, Save As uses
// the user's default format, and neither call changes that default.
let format = match suggested_save_format(params, app.ui.save_format) {
Ok(format) => format,
Err(e) => return Some(Err(e)),
};
let name = format.suggested_name(title.as_deref());
let name = app.ui.save_format.suggested_name(title.as_deref());
// Bound to this drawing: the answer saves it, not whichever drawing is active then.
app.pick_then(Pick::Save(name), |app, p| {
app.session.execute("saveas", &saveas_params(&app.ui, &app.session, &p)).map_err(|e| e.to_string())
@@ -614,17 +608,6 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Re
Some(r)
}
/// The format a Save dialog suggests: `format` when the call names `dxf` or `dwg`, otherwise the
/// user's default. Naming one does not change the default.
fn suggested_save_format(params: &Value, default: crate::SaveFormat) -> Result<crate::SaveFormat, String> {
let Some(v) = params.get("format").filter(|v| !v.is_null()) else { return Ok(default) };
let Some(name) = v.as_str() else { return Err("save format must be \"dxf\" or \"dwg\"".into()) };
crate::SaveFormat::parse(name).ok_or_else(|| {
let shown: String = name.chars().take(40).collect();
format!("unknown save format \"{shown}\" (dxf or dwg)")
})
}
/// SAVEAS parameters for a path picked in the Save dialog: a drawing that has no file yet is saved
/// in the default save version; one opened from a file keeps that file's version.
fn saveas_params(ui: &crate::UiState, session: &cadcraft_engine::Session, path: &str) -> Value {
+3 -10
View File
@@ -2,10 +2,8 @@
//! another program keeps (`cadcraft_engine::cmd::file::not_saved`), a DXF can't hold every solid
//! or proxy of every version (`cadcraft_engine::cmd::file::loss_on_save`), and QSAVE replaces the file
//! that still has it, so File ▸ Save, its shortcut or typing QSAVE says what would go first:
//! Save Anyway / Save As... / Cancel. Save As from a DWG warning suggests DXF, which keeps the
//! objects; File ▸ Save As suggests the user's default format. Agreeing lasts for that same loss
//! on that same file, so later saves in the session don't ask again; the file no longer holds
//! what was agreed to.
//! Save Anyway / Save As... / Cancel. Agreeing lasts for that same loss on that same file, so
//! later saves in the session don't ask again; the file no longer holds what was agreed to.
//!
//! Programmatic saves (`engine.execute`, the control channel, MCP, scripts) never ask: they keep
//! reporting the loss in the result's `notSaved` and on the command line.
@@ -96,12 +94,7 @@ impl CadApp {
(Choice::Cancel, _) | (_, None) => self.session.echo(crate::tf!("Save cancelled: {path} was not changed.", path = loss.path)),
(Choice::SaveAs, Some(i)) => {
self.activate_doc(i);
// A DWG warning says DXF keeps the objects, so this dialog suggests DXF. A DXF
// warning is about an older version, and File ▸ Save As passes no format, so both
// keep suggesting the user's default.
let dxf = std::path::Path::new(&loss.path).extension().is_some_and(|e| e.eq_ignore_ascii_case("dxf"));
let params = if dxf { Value::Null } else { json!({ "format": "dxf" }) };
let _ = self.run("ui.saveas", params);
let _ = self.run("ui.saveas", Value::Null);
}
(Choice::SaveAnyway, Some(i)) => {
self.activate_doc(i);
+1
View File
@@ -43,6 +43,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;

Some files were not shown because too many files have changed in this diff Show More