Compare commits

...
207 Commits
Author SHA1 Message Date
FredApps a3ed0682ab Merge pull request #1633 from KnottyDyes/squad/docs-dxf-dwg-write-version
Docs: describe DXF and DWG save-version selection
2026-11-26 15:12:38 +01:00
FredApps b1340f0697 Merge main into docs/save-version (keep main's craft-dwg and acadrust 0.6.6 text; this PR's version-selection rules) 2026-11-26 20:48:14 +07:00
FredApps b3bc4a7618 Merge pull request #997 from aldozar/perf/cjk-text
Faster CJK-heavy drawings: per-thread font caches, offscreen glyphs left out (#666, #662)
2026-11-26 13:43:40 +01:00
FredApps e66cdcec29 Merge main into perf/cjk-text
Conflicts: crates/fonts/src/ttf.rs (main made OutlineMesh's points pub(crate); kept that and this PR's bounds field) and crates/render/src/tests.rs (kept this PR's #666 view test and main's fixture-font section).

Main also added a public font-set GENERATION/generation() for redraws (2c979eb1), which clashed by name with this PR's private lookup-cache counter. Renamed this PR's counter to LOOKUP_GENERATION/lookup_generation(), and set_font_dirs now also calls changed() so the per-thread caches drop fonts from removed folders.

cargo test -p cadcraft-fonts -p cadcraft-render and cargo fmt --check pass locally.
2026-11-26 19:31:45 +07:00
FredApps e59031a441 Merge pull request #2782 from 2ez4gcx/fix/arraypath-closed-spacing
ARRAYPATH: no extra item where a closed path closes, by spacing
2026-11-26 10:39:43 +01:00
FredApps e0d64c676d Merge pull request #2705 from 2ez4gcx/fix/spline-closed-autocad
SPLINE: closed fit-point splines built as AutoCAD 2024 builds them
2026-11-26 10:29:22 +01:00
FredApps a46923c96d Merge remote-tracking branch 'origin/main' into ic45-2782 2026-11-26 16:20:50 +07:00
FredApps 61f4632e60 Merge pull request #2762 from 2ez4gcx/fix/arraypath-item-count
ARRAYPATH: the item count takes a whole number as AutoCAD 2024 does
2026-11-26 10:20:35 +01:00
FredApps 28fd71600c Merge pull request #2778 from 2ez4gcx/fix/splinedit-elevate-order-integer
SPLINEDIT: take a whole number as typed for Elevate order
2026-11-26 10:20:17 +01:00
FredApps 6525de811e Merge pull request #2784 from 2ez4gcx/fix/insert-points-at-scale-prompts
INSERT/MINSERT: take points at the scale, rotation and spacing prompts
2026-11-26 10:20:00 +01:00
FredApps daa6bf9063 Merge main into fix/spline-closed-autocad 2026-11-26 16:09:42 +07:00
FredApps b4ad0f3800 Merge pull request #2703 from 2ez4gcx/fix/spline-file-tangent-length
SPLINE: a file's end tangents count with their length, as in AutoCAD 2024
2026-11-26 10:09:24 +01:00
FredApps 5096e1503f Merge pull request #3500 from 2ez4gcx/feat/vi-catalog-phase1
Vietnamese catalog: approved terminology and the 249 missing strings (craft-i18n#401 phase 1)
2026-11-26 10:09:06 +01:00
FredApps bcfc9a0786 Merge pull request #2780 from 2ez4gcx/fix/divide-count-integer
DIVIDE: take a whole number as typed for the number of segments
2026-11-26 10:04:21 +01:00
FredApps 9df34c448c Merge remote-tracking branch 'origin/main' into ic45-2762 2026-11-26 16:00:43 +07:00
FredApps edbdf0dd8f Merge pull request #2774 from 2ez4gcx/fix/arraypath-json-params
ARRAYPATH: refuse a JSON count or spacing it can't use
2026-11-26 10:00:31 +01:00
FredApps 60ca94cd7a Merge commit 'bb3b0cd5' into ic46-2705 2026-11-26 16:00:25 +07:00
FredApps 02bc55aaaa Merge remote-tracking branch 'origin/main' into ic45-2778
# Conflicts:
#	crates/engine/tests/it/pedit_splinedit.rs
2026-11-26 15:56:21 +07:00
FredApps 66d92125f1 Merge pull request #2772 from 2ez4gcx/fix/splinedit-precision-integer
SPLINEDIT: take a whole number as typed for the polyline precision
2026-11-26 09:54:22 +01:00
FredApps 40c4c7dac1 Merge main into feat/vi-catalog-phase1 2026-11-26 15:52:44 +07:00
FredApps bb3b0cd5cd Merge main into fix/spline-file-tangent-length 2026-11-26 15:52:12 +07:00
FredApps efa617fcd5 Merge remote-tracking branch 'origin/main' into ic45-2784
# Conflicts:
#	crates/engine/tests/it/minsert.rs
2026-11-26 15:51:50 +07:00
FredApps 19290804a1 Merge pull request #2699 from 2ez4gcx/fix/spline-fit-autocad
SPLINE: open fit-point splines built as AutoCAD 2024 builds them
2026-11-26 09:51:49 +01:00
FredApps bb375992f4 Merge pull request #2789 from 2ez4gcx/fix/minsert-json-counts
MINSERT: JSON rows and columns are whole numbers
2026-11-26 09:51:23 +01:00
FredApps f2d1845aee Merge pull request #2205 from 2ez4gcx/fix/pline-undo-plinewid
PLINE: Undo returns to the last segment's mode, and PLINEWID is the width
2026-11-26 09:48:33 +01:00
FredApps 2c4ab18255 Merge pull request #2761 from 2ez4gcx/fix/array-count-integer
ARRAY: counts take a whole number as typed, as AutoCAD 2024 does
2026-11-26 09:48:12 +01:00
FredApps a37797484d Merge pull request #2204 from 2ez4gcx/fix/rectang-autocad-vertices
RECTANG: Area with cut corners, oversized corners and Rotation as AutoCAD takes them
2026-11-26 09:48:01 +01:00
FredApps 900ed557f1 Merge pull request #2726 from 2ez4gcx/feat/copy-autocad
COPY as AutoCAD 2024: COPYMODE, mOde/Multiple, Array with Fit, Undo, and Enter for a displacement
2026-11-26 09:47:40 +01:00
FredApps d7ea0ede4c Merge pull request #2209 from 2ez4gcx/fix/stretch-arcs-bulges-splines
STRETCH: arcs and polyline arc segments keep their height; spline control points move
2026-11-26 09:47:17 +01:00
FredApps 0e3a58418f Merge remote-tracking branch 'origin/main' into ic45-2780 2026-11-26 15:44:23 +07:00
FredApps 6a3199d5a4 Merge pull request #3539 from 2ez4gcx/fix/style-name-lookups
fix(doc, io): look linetypes, text and dimension styles and layouts up by name through an index, so crafted files don't open or draw in quadratic time
2026-11-26 09:42:20 +01:00
FredApps c352afc399 Merge remote-tracking branch 'origin/main' into ic45-2774 2026-11-26 15:40:39 +07:00
FredApps 292b6bc7ce Merge remote-tracking branch 'origin/main' into ic45-2772 2026-11-26 15:38:23 +07:00
FredApps 45b20c6470 Merge remote-tracking branch 'origin/main' into ic45-2789 2026-11-26 09:35:09 +01:00
FredApps fbea6d1ffc Merge pull request #2766 from 2ez4gcx/fix/minsert-count-integer
MINSERT: take a whole number as typed for the rows and columns
2026-11-26 09:34:52 +01:00
FredApps 22ba34c123 Merge main into feat/vi-catalog-phase1 2026-11-26 09:32:53 +01:00
FredApps 331c867476 Merge main into fix/array-count-integer 2026-11-26 09:28:41 +01:00
FredApps bddbf390f7 Merge main into fix/rectang-autocad-vertices 2026-11-26 09:28:12 +01:00
FredApps 5f24b4b667 Merge main into fix/pline-undo-plinewid 2026-11-26 09:28:06 +01:00
FredApps 6b403674ed Merge main into fix/stretch-arcs-bulges-splines 2026-11-26 09:27:59 +01:00
FredApps 2485c2e758 Merge main into feat/copy-autocad 2026-11-26 09:17:23 +01:00
FredApps 2ca9557d2c Merge remote-tracking branch 'origin/main' into ic45-2766 2026-11-26 09:16:22 +01:00
FredApps ea66defc0d Merge main into fix/spline-fit-autocad 2026-11-26 09:12:33 +01:00
FredApps 2e9fe9462c Merge main into fix/style-name-lookups 2026-11-26 09:10:47 +01:00
2ez4gcxandClaude Opus 5.5 4c1ea7d320 Merge main (ba344a89) into feat/copy-autocad
One conflict, in crates/engine/src/cmd/modify/select_then.rs: this branch
adds COPY's copy_prompt, copy_input and copy_done just above join_now, and
main (#2725) rewrote join_now's doc comment. Kept both: the COPY methods,
then main's two-line doc. The struct fields (copy_single, copies,
copy_array, ask_circle), SelectThen::new and the match arms merged without
conflict. No behaviour changed on either side.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:39:48 +07:00
2ez4gcxandClaude Opus 5.5 d290fc886f fix(doc, io): look linetypes, styles and layouts up by name through an index
Drawing::linetype, text_style, dim_style and layout scanned their table,
once per entity while a drawing is drawn, measured or saved, and once
per layout after every command. The DXF reader also scanned the
dimension styles once per DIMSTYLE record and the layouts by exact name
once per paper-space object. So a crafted file of N records and N
entities naming one it lacks, N DIMSTYLE records, or N layouts with N
objects in the last of them cost N^2 name comparisons (#1924, F-04
item 3): at N = 40 000 a PNG export took 23 s, opening 107-151 s or
more than 300 s on main.

- linetypes, text_styles, dim_styles and layouts are NamedLists (from
  #3484) and the four lookups use its index: the first entry of a name
  in list order, ASCII case folded, as the scan returned.
- NamedList::by_name_mut: the first entry of a name to change.
- Scans with the same answer go through the lookup (STYLE, DIMSTYLE,
  RENAME, -DIMSTYLE, .lin loading, COMPARE, COUNT, UCS, plotter, DXF
  header, Layers panel).
- The DXF reader indexes DIMSTYLE records by lower-cased name, and maps
  layout names (exact) to the first layout of that name once per pass.

Cost tests (doc: one per table; io: DIMSTYLE records and layouts) fail
on main at 66-421 s and pass within 3 s; a behaviour test compares
every lookup with a scan.

Part of #1924

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:02:33 +07:00
skylar taylor-barrick 12eef22768 Nightly: stop blocking a refused launch on macOS (#3537)
Nightly launch fix under Skylar's Exec 454: the Launcher's trailing `--` no longer reaches the file list where that applied, and a refused launch no longer blocks on macOS (the reason goes to stderr and the app exits 2).
2026-11-26 00:46:02 -06:00
FredApps 7c8f8ada92 Merge pull request #3536 from 2ez4gcx/fix/dwg-ltype-dash-count
DWG save: keep the first 255 dash elements of a linetype, and say so (part of #1923)
2026-11-26 07:43:27 +01:00
FredApps ba344a894b Merge pull request #2790 from 2ez4gcx/fix/join-other-height
JOIN: ends meet at the same height; objects facing the other way stay out
2026-11-26 06:13:20 +01:00
2ez4gcxandClaude Opus 5.5 b861b6c0a5 DWG save: keep the first 255 dash elements of a linetype, and say so
acadrust 0.6.6 writes and reads a DWG linetype's element count as one
byte, so a linetype of 256 elements came back from a DWG save with none
(continuous) and one of 300 with 44. The DXF read cap of #3482 lets 256
through, so every capped DXF linetype hit the 256 -> 0 case.

The DWG bridge text now writes at most 255 elements per linetype (the
first ones, with group 40 totalling them); DXF output is unchanged.
cadcraft_io::dwg_notes gives one note counting the linetypes cut, counted
by the writer so an xref linetype the file leaves out is not counted. An
engine hook installed by the apps echoes it and returns it in `warnings`
on every DWG write: QSAVE/SAVEAS, document.bytes, EXPORT, WBLOCK,
-WBLOCK, LAYOUT SAVEAS; cadcraft-cli convert prints it.

Part of #1923 (F-05).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 12:07:14 +07:00
FredApps c9260d1b59 Merge pull request #2740 from 2ez4gcx/feat/qleader
QLEADER at the command line, as AutoCAD 2024 runs it
2026-11-26 06:06:19 +01:00
FredApps d2587c694e Merge pull request #2487 from 2ez4gcx/fix/linetype-dash-layout
Linetypes: lay dashes out as AutoCAD does
2026-11-26 06:05:59 +01:00
FredApps a06b236f0c Merge branch 'main' into fix/join-other-height 2026-11-26 05:34:33 +01:00
FredApps 4a4b1e2339 Merge pull request #2906 from 2ez4gcx/fix/pedit-heights
PEDIT: polylines at their objects' height; Join only at the same height
2026-11-26 05:32:57 +01:00
FredApps b5481e3bbf Merge pull request #2725 from 2ez4gcx/feat/join-autocad
JOIN onto the source object as AutoCAD 2024 does: lines, arcs, and a polyline that keeps its handle
2026-11-26 05:32:42 +01:00
FredApps 7244d2bc96 Note QLEADER in the Leaders, tables, fields parity row
The command-line form lands in #2740 / #3532; the Settings dialog is still open.
Percentages and hours are not re-measured.
2026-11-26 05:30:16 +01:00
FredApps d8aa2c60dc Merge main into feat/qleader 2026-11-26 05:30:16 +01:00
FredApps b38215b7cf Merge main into fix/linetype-dash-layout 2026-11-26 05:30:04 +01:00
FredApps d955a3ccfc Clamp gap-first open-run dashes to the start of the run
In the x < 0 branch, a dash that starts slightly before p0 could push a
negative range. Keep the start at p0 (and the existing end cap at p0 + len).
2026-11-26 05:30:04 +01:00
aiongg b55abde2a8 Merge pull request #3449 from aiongg/minimal-port-next
CadCraft: move to craft-libs next (minimal port)
2026-11-25 23:16:50 -05:00
aiongg a3640199b6 Quit CADCraft asks about unsaved drawings again
muda's predefined Quit ends the process through terminate: without asking. The menu item
is craft-quit's Quit, a close request of the main window, so the close path asks first
as the close button does (#2157).
2026-11-26 03:48:00 +00:00
FredApps 91966ccc9d Classify qleader under NO_FILES for automation roots 2026-11-26 10:15:15 +07:00
FredApps 414e544282 Merge pull request #2760 from 2ez4gcx/fix/options-reset-profile
OPTIONS: reset restores every profile variable; a refused change leaves the drawing's snap and grid
2026-11-26 03:58:53 +01:00
FredApps b255d58275 Merge pull request #3491 from 2ez4gcx/fix/attrib-tag-matching
fix(doc,render,io,engine): match attributes to their definitions by tag in one lookup (part of #1923)
2026-11-26 03:54:12 +01:00
FredApps 1fb86ec415 Merge remote-tracking branch 'origin/main' into ic40-2740 2026-11-26 09:50:41 +07:00
FredApps bc5749ec18 fix(doc): order attribute tags instead of hashing them, so crafted tags can't collide on the web build
The web build's RandomState keys come from addresses, not entropy, so a
file could pick tags whose hashes collide and bring back the A x K cost
this change removes. Key the by-tag maps by the tag's ASCII-folded bytes
in a BTreeMap, as the layer and block name index (#3484) does. Matching
is unchanged: TagKey's order is consistent with eq_ignore_ascii_case.

Part of #1923.
2026-11-26 09:42:42 +07:00
FredApps 4cc0e1f19a Merge main into fix/attrib-tag-matching 2026-11-26 09:34:25 +07:00
aiongg f99ae6956c A copy fired in a floating panel keeps the modifiers it was pressed with 2026-11-25 20:11:31 +00:00
aiongg b844248903 Floating windows carry the running channel's app id 2026-11-25 20:09:16 +00:00
aiongg 1cff8cd681 Repin craft-libs to storytold next 8fa4db64a9 and egui to b9770908e 2026-11-25 19:15:09 +00:00
aiongg 09944da2a4 Repin craft-libs to the hidden-window and modal-focus fixes (next + float-fixes) 2026-11-25 18:45:26 +00:00
aiongg 433e51abc4 Reset Panel Layout cancels a panel drag in progress again
As before the move to the craft-ui dock, a tab held while the layout
resets is not dropped into the reset layout. The reset replaces the
workspace, so its generation changes.
2026-11-25 18:29:18 +00:00
aiongg 53d1790348 Close tests: a close that goes ahead is checked without quitting
The tests assert CADCraft's own close decision for a saved drawing and
for a programmatic quit, as they did before the platform's quit joined
the close path, so they pass on macOS, where that quit cancels the window
close. Unsaved drawings still run the whole close frame.
2026-11-25 18:24:58 +00:00
aiongg f4c3018003 An opened panel's floating window comes to the front again
As before the move to the craft-ui dock, opening or activating a panel
with a command raises the floating window that holds it, once. Docked
panels only become the front tab.
2026-11-25 18:24:58 +00:00
aiongg 239f8a32f0 Repin craft-libs to the fix for windows that stay hidden (next + float-menu) 2026-11-25 18:19:04 +00:00
aiongg 9d214d6e88 Drawing focus comment: a click on a palette leaves the drawing focused 2026-11-25 15:50:21 +00:00
aiongg d26d9ca01f Repin craft-libs to storytold next aa401985d 2026-11-25 15:50:21 +00:00
aiongg c9286726ab Copy, Cut and Paste pressed in a floating panel reach the app 2026-11-25 15:15:06 +00:00
aiongg 138f447988 Ctrl+=, Ctrl++, Ctrl+- and Ctrl+0 change the interface scale
The keys (Cmd on macOS) step the Options interface scale by a tenth, within its limits, and Ctrl+0 sets it back to 100 %. They work while a text field or the command line has the keyboard, and a key the user gave to a command runs the command. In the browser they zoom the page.
2026-11-25 14:35:42 +00:00
aiongg e425c71c44 Enter and Space leave the drawing's right-click menus open 2026-11-25 14:20:12 +00:00
aiongg c3f691264a Repin craft-libs to storytold next d1bdf8e5da 2026-11-25 13:44:10 +00:00
aiongg aac7ae1cf2 A running command keeps Tab after a click on the palette or the status bar 2026-11-25 13:24:08 +00:00
aiongg 849e6fd5c4 The drawing takes the keyboard focus and keeps Tab while the command line has work for it
A press in the drawing, and a drawing that opens or becomes active, give the drawing the focus; a text field, a dialog
or a menu keeps it. The focused drawing keeps Tab (KeepKeys::Tab) only while a command runs, text is typed, value boxes
are live or a snap marker is under the cursor. A bare Tab with nothing focused is the framework's: capture_tab is gone.
2026-11-25 13:06:11 +00:00
aiongg 9e5889b782 Tab reaches the palettes from the document tabs
The drawing's host canvas is declared with the id of the drawing's own widget, so egui keeps the focus Tab gives it.
While the drawing is the focused Tab stop, the command line and the shortcuts take the keyboard as with nothing focused.
2026-11-25 12:38:02 +00:00
2ez4gcxandClaude Opus 5.5 3439895ec3 Vietnamese catalog: approved terminology and the 249 missing strings
Phase 1 of storytold/craft-i18n#401 for CADCraft's own vi.tsv.

- 44 existing rows: the 8 terms raised in #401 (14 rows), "nạp" for
  loading into CADCraft (8 rows), Boundary as "Đường bao" (2), the 17
  rows left in English (Find and Replace, Magenta, Working Set, Feet)
  and 3 rows kept consistent with them. "tỉ lệ" stays as spelled.
- 249 new rows, one for each string the translation_gaps report listed
  (Dimension Style Manager and dimension properties, keyboard shortcuts,
  right-click customization, Array dialog, UCS, ALIASEDIT, commands),
  grouped under comments. The report now prints "vi: nothing missing".
- ATTRIBUTION.md: the phase 1 changes were reviewed by a native
  Vietnamese speaker; older rows are not yet proofread in full.

Translations are written from the meaning of the English strings and
their use in the code (clean room).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 17:58:46 +07:00
2ez4gcxandClaude Opus 5.5 a34ebd0bd0 Match attributes to their definitions by tag in one lookup (part of #1923)
One block reference with A attributes of a block with K attribute
definitions cost A x K tag comparisons wherever they are matched: the
extents (constant values a reference carries, the layer of an attribute
without its own), the renderer's constant values (per MINSERT copy), the
DXF writer (ATTRIB properties, MULTILEADER block-content values), BURST,
ATTSYNC/BLOCKREPLACE and the dynamic-grip preview. Crafted 16k x 16k and
32k x 32k files took 2-28 s to open, draw or save in a dev build.

TagKey compares and hashes a tag without ASCII case, as
eq_ignore_ascii_case does; Block::attdefs_by_tag and
Insert::attribs_by_tag keep the first definition or attribute of a tag,
as the scans' find/any did. Each site builds the map once and looks each
tag up once. Outputs of the crafted files are byte-identical.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 15:26:03 +07:00
aiongg c089fdff1a Paste tests that run only the shortcut table don't install the runtime (no drawing keeps the clipboard events in egui) 2026-11-25 07:19:23 +00:00
aiongg ad1446c302 Allow egui::ComboBox: craft-libs next has no craft_ui::ComboBox 2026-11-25 06:47:06 +00:00
aiongg 7eb9401f08 cargo fmt 2026-11-25 06:40:11 +00:00
aiongg 69a040acc6 Merge main into the minimal port
Conflicts: Cargo.toml (kept the next/egui pins for every craft-libs entry, including main's new craft-csv and hayro-interpret/cmap/postscript patches), apps/cadcraft/src/main.rs (port's framework frame decision and apply_frame with main's os_window identity, persistence path and exit hook), crates/ui-egui/src/updates_ui.rs (next's argument-free check calls with main's check_updates_at_start gate). Main's new tests and dialogs switched to install_headless and escape_pressed.
2026-11-25 06:38:00 +00:00
aiongg 2282d11b37 Repin egui to storytold b15ffe9bfc (what craft-libs next pins) 2026-11-25 06:32:55 +00:00
aiongg d659315743 Repin craft-libs to storytold next 16001e7210 and egui to storytold b15ffe9bfc 2026-11-25 06:31:24 +00:00
2ez4gcxandClaude Opus 5.5 5bff714e00 ARRAY counts: withdraw the ARRAYEDIT measurement claim
b781f047 said AutoCAD 2024 was measured at ARRAYEDIT's columns, rows
and items. That measurement was made after the clean-room standard of
20 November (one agent session must not both operate AutoCAD and write
code), so the claim is withdrawn.

The module doc now lists only ARRAYRECT's rows and columns,
ARRAYPOLAR's items and rows, and -ARRAY's rows and items as measured.
The arrayedit_counts doc says ARRAYEDIT's counts go through the same
count() parser in crates/engine/src/cmd/array.rs, so they refuse and
take the same texts; no AutoCAD measurement of ARRAYEDIT is claimed.
Comments only: the test logic and the engine code are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 10:41:49 +07:00
2ez4gcxandClaude Opus 5.5 c4f139ac50 Merge main into fix/spline-closed-autocad
Conflict in crates/engine/tests/it/spline_options.rs, where both sides
appended tests: keep reverse_keeps_a_closed_spline_seam and main's SPLINE
CV method tests (#3456).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 09:02:43 +07:00
aiongg 9ea307ede8 Capture tests: frames run the app's raw input hooks; one geometry for the admission test
The capture rig ran note_raw_geometry alone, so the framework never got
the Options interface scale (FrameInput's Scale, given in before_input)
and egui's zoom stayed 1: the settled-scale test saw 800×600. It now runs
raw_input_hook and before_input, as the desktop app does.

The admission test reseeded the geometry for each request, an identity
change that the next drain rejects queued requests for; it now admits
all four against one geometry, so all four issue and stay undrained.
2026-11-24 19:28:13 +00:00
aiongg c125e9ebb8 Repin craft-libs to 9fd8b0cdaa; frame-only work and captures skip passes that will run again 2026-11-24 19:08:26 +00:00
aiongg ddee4e5bec Tests on next: clipboard rig without the runtime, wheel rig with the frame input, QuickCalc field under its panel, traversal from a focused control, left-edge drop case 2026-11-24 17:40:53 +00:00
aiongg 092ab07e66 Repin craft-libs to next-host-input 3ad64a26ea 2026-11-24 17:06:04 +00:00
aiongg 5195d9e5c8 Screenshots need no egui import on the web; iconic-column test reads the icons right of the drawing 2026-11-24 16:57:16 +00:00
aiongg 4f4a3e94b6 Tests: install the runtime in harnesses that run the app's UI; dock tests on next's model
Harnesses and bare contexts that run CadApp::ui install the runtime headless; rigs that
run the raw hook also run before_input. Dock tests use the workspace accessors, next's
action constructors and the tabs' accessible names; tests of the old renderer's hit rects,
divider ids and drag bar are removed.
2026-11-24 16:47:31 +00:00
aiongg 68de3797cc Host the craft-ui runtime from CADCraft's eframe App on craft-libs next
The runtime is installed in the desktop and web shells, before_input runs in the raw hook,
the close path decides in embed::logic, and the interface scale is the runtime's RootEnv
scale. The dock is next's DockArea over the saved workspace with CADCraft's panel bodies
and the drawing as its canvas group; ui.dock keeps its JSON vocabulary. Update dialogs run
on a DialogHost, the macOS title row is shell::TitleBar, screenshots use the runtime's
screenshot slot, and Escape with nothing focused is read as the window's cancel.
2026-11-24 16:47:31 +00:00
aiongg b6ee77e3ac Cargo.lock for the next pins (rustix 1.1.6) 2026-11-24 16:35:24 +00:00
aiongg 180ff4471d minimal-port rewrite: 99 edits (dock rename 43, combo 40, dock 10, split rename 3, deps 2, split 1) 2026-11-24 16:27:10 +00:00
aiongg 8fe5682b63 minimal-port repin: 35 edits (revs 30, features 5) 2026-11-24 16:26:54 +00:00
2ez4gcxandClaude Opus 5.5 bc976e9bde Merge main into fix/pline-undo-plinewid
Conflict in crates/engine/src/cmd/draw/line_pline.rs PlineM::begin():
keep main's drawing elevation (#3423) and the branch's PLINEWID start
widths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 08:57:36 +07:00
2ez4gcxandClaude Opus 5.5 b781f04784 ARRAY counts: test ARRAYEDIT's counts and the MAXARRAY bounds
ARRAYEDIT's columns, rows and items, measured in AutoCAD 2024's core
console, refuse 5.0, 5., 4.5, 1e1 and 8/2 and take +5, 05 and 5, as the
other count prompts do. A count runs from 1 to the MAXARRAY limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 21:19:36 +07:00
2ez4gcxandClaude Opus 5.5 c40fc740ab Merge main into fix/array-count-integer
Conflict in crates/engine/tests/it/main.rs: keep both array_counts and
main's array_key_point (#2368).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 19:21:22 +07:00
2ez4gcxandClaude Opus 5.5 fb20f102df Merge main into fix/spline-closed-autocad
Conflict in crates/io/src/dxf_read/entities.rs: keep the branch's
keeps_closing_tangent() and main's hatch curve budget parameter (#3306).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 18:06:39 +07:00
2ez4gcxandClaude Opus 5.5 ee13c648df Merge main into fix/linetype-dash-layout
Conflict in crates/render/src/wide.rs dashed(): keep main's point budget
for segments() (#3306) and the branch's closed PLINEGEN anchor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 17:34:35 +07:00
2ez4gcxandClaude Opus 5.5 62a1a23288 Prompt: declare NO_OR as a slice
This PR and #2915 each add a prompt to NO_OR and raise its array length
from 28 to 29, so with both merged the array holds 30 entries under a
length of 29 (E0308), whichever lands first. A slice has no length to
keep in step; both PRs make the same change to this line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 09:06:54 +07:00
2ez4gcxandClaude Opus 5.5 12b7742384 JOIN: set the new polyline's elevation without with_z
#2548 rewrites BREAK and deletes with_z; with both PRs in, this branch's
call to it no longer compiled (E0425), whichever landed first. Set the
elevation on the polyline lwpoly() makes instead: the same value, and
nothing of this branch depends on with_z any more.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 08:59:04 +07:00
2ez4gcxandClaude Opus 5.5 927a417255 Merge branch 'fix/spline-file-tangent-length' into fix/spline-closed-autocad
Brings chord_interpolate's start-condition row ahead of the fit-point
rows, so its system stays banded. chord_closed builds closed chord fits
through it: control points are bit-identical, and a closed fit of 1,000
points took 17.4 -> 3.2 ms (dev profile).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 08:02:36 +07:00
2ez4gcxandClaude Opus 5.5 fc838dce98 SPLINE: assemble the chord fit's start condition before its points
chord_interpolate added the start tangent or zero-curvature row after
all the fit-point rows, so its column-0 entry sat in row n and solve
swept the whole width. With the start row first, the system has a lower
and upper bandwidth of at most two. The control points come out
bit-identical; a fit took 17.5 -> 4.4 ms at 1,000 points and
414 -> 135 ms at 4,000 (natural ends, dev profile).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 07:58:59 +07:00
2ez4gcxandClaude Opus 5.5 a1142566b8 SPLINE: assemble the chord fit's start condition before its points
chord_interpolate added the start tangent or zero-curvature row after
all the fit-point rows, so its column-0 entry sat in row n and solve
swept the whole width. With the start row first, the system has a lower
and upper bandwidth of at most two. The control points come out
bit-identical; a fit took 17.5 -> 4.4 ms at 1,000 points and
414 -> 135 ms at 4,000 (natural ends, dev profile).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 07:28:58 +07:00
2ez4gcxandClaude Opus 5.5 db8f6cc6e4 Merge main into fix/spline-fit-autocad
Main's banded solve came with a dense-solver oracle test whose cases all
use chord-length knots; on this branch those go through
chord_interpolate, so the test no longer reached interpolate. Extend it
with square-root and uniform knots, with and without end tangents, and
a 1000-point square-root fit (the same change as on
fix/spline-file-tangent-length).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 07:08:12 +07:00
2ez4gcxandClaude Opus 5.5 4b76e4a305 Merge branch 'fix/spline-file-tangent-length' into fix/spline-closed-autocad
Brings in main f9c0c96e. Main's clippy-pedantic refactor of
spline_fit.rs conflicted in three places: fit_sanitized takes main's
if-let form and keeps closed_fit's tangent argument, closed_fit keeps
main's #[expect] on its four-parameter signature, and the closed
tolerance test keeps main's bit-exact assert with this branch's comment.

Closed chord-length fits go through chord_closed on this branch, so the
dense-solver oracle's comments say so, and an n=150 closed square-root
fit keeps the large cyclic matrix compared.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 06:24:09 +07:00
2ez4gcxandClaude Opus 5.5 17888ad5c6 Test the dense-solver oracle on interpolate's fits too
With chord-length knots, open fit-point splines are now built by
chord_interpolate, so fits_are_bit_identical_to_the_dense_solver no
longer reached interpolate (a panic there left the test passing). Add
square-root and uniform knots, with and without end tangents, and a
1000-point square-root fit, so interpolate's matrices, its tangent rows
and the closed cyclic interpolation stay compared with the dense solver.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 06:01:28 +07:00
2ez4gcxandClaude Opus 5.5 0edd056e8e Merge main into fix/spline-file-tangent-length
Main's clippy-pedantic refactor of spline_fit.rs restyled the body of
Spline::fit_with; this branch had moved that body into fit_sanitized.
Keep the split and apply main's if-let form inside fit_sanitized.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 05:30:27 +07:00
2ez4gcxandClaude Opus 5.5 74c183415b Merge main into fix/linetype-dash-layout
Brings the branch up to main ca87680f. The one conflict is in
crates/render/src/linetype_text.rs, texts(): main's #2744 adds a point
allowance for the labels of a run, and this branch starts the run a period
before its start. Both are kept: the allowance is charged for each label
placed, and elements before the run's start are skipped before any charge.
Main's new test placed_labels_stop_at_the_point_allowance now passes the
Layout argument this branch added to texts().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 11:54:27 +07:00
2ez4gcxandClaude Opus 5.5 67c78743dd DXF: write the closing fit point after a closed list ending with its first
The reader drops one closing fit point from a closed spline, so the writer
now adds one whenever the reader will drop one: also after a list that
already ends with its first point (a kink where it closes, as a file can
give it). Before, [A, B, C, A, A] came back as [A, B, C, A], and a later
fit-point edit smoothed the seam. Three points ending with the first are
still written as they are, since the reader keeps them so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 13:56:20 +07:00
2ez4gcxandClaude Opus 5.5 45300ee3a2 Merge main into fix/pedit-heights
Brings the branch up to main 6d744887, which has #2954's fix for
mtext::tests::strips_formatting, so the gate runs on a main that passes.
No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 12:52:16 +07:00
2ez4gcxandClaude Opus 5.5 d6dc7131c3 Merge main into fix/spline-closed-autocad
Brings the branch up to main 6d744887, which has #2954's fix for
mtext::tests::strips_formatting. The one conflict is in
crates/geom/src/nurbs.rs, where main makes the derivative allocation-free
(#2434, basis_pair_into) and this branch adds reversed_loop. The merged
file is main's plus exactly this branch's own lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 11:08:03 +07:00
2ez4gcxandClaude Opus 5.5 96e62b4632 PEDIT Join: only objects in one plane with the polyline, as AutoCAD 2024
AutoCAD 2024 joins only objects that lie in one plane with the polyline:
the plane the polyline and every line picked share, if they share one,
else the polyline's own. Measured: a triangle at Z 5 whose last side slopes
to Z 0 leaves that side out; a sloped line followed by a line turning off
their vertical plane joins neither; a sloped line followed by an arc joins
the line only. Before, a sloped line joined wherever its end met the chain
at the same height.

Also, after review: tests for the sloped line drawn either way, a chain
meeting its start at another height, arcs below Z 0 and mirrored above it,
thickness, the joined polyline's normal and bulges, fuzz in plan only, and
an exact pick on the arc; doc comments for the plane rule, the height
tolerance and tilted arcs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 04:04:46 +07:00
2ez4gcxandClaude Opus 5.5 e20f5ed590 PEDIT: polylines at their objects' height; Join only at the same height
PEDIT turned a line or an arc into a polyline at elevation 0, so a line at
Z 5 dropped to Z 0, and its Join took any object meeting the polyline in
plan. As AutoCAD 2024 does (measured):

- Convert puts the polyline at the line's height or the arc's centre
  height and keeps the thickness; a line's polyline faces up whatever the
  line's normal, a mirrored arc's keeps its normal and runs as the arc
  does in its own coordinates.
- PEDIT's Join takes an object only where the ends meet at the same
  height, and none facing the other way (an arc or polyline whose normal
  points down Z where the polyline's points up, or the other way round;
  a line counts as facing up). After a sloped line, the chain continues
  from its far end's height.
- Multiple's Join leaves out objects facing the other way too, but takes
  them at any height.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:19:21 +07:00
2ez4gcxandClaude Opus 5.5 6133dc60bb JOIN: a new polyline stays at the source's height
JOIN made the new polyline from a line or arc source at elevation 0, so
lines at Z 5 moved down to Z 0. It now takes the source's height, as a
polyline source keeps its elevation with a sloped line joined to it
(AutoCAD 2024, measured), negated when the polyline inherits a normal
pointing down Z. The new polyline itself wasn't measured: the core
console's JOIN never makes one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 09:02:04 +07:00
2ez4gcxandClaude Opus 5.5 8b1adcd8d5 MINSERT: test that JSON null counts and distances are taken as missing
A null rows or columns is 1 and a null rowSpacing or columnSpacing is 0,
as when the key is missing. Each count is tested null on its own; the
distances on a 2 x 2 grid, since one row or column drops its distance
anyway.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 23:39:33 +07:00
2ez4gcxandClaude Opus 5.5 19dcf74419 JOIN: ends meet at the same height; objects facing the other way stay out
JOIN compared chain ends in plan only, so an end meeting another only in
plan at another height was joined and collapsed onto the source's
elevation. Each piece now carries its ends' world heights (a line's own
Z, an arc's centre Z, a polyline's elevation, negated when its normal
points down Z), turned round with the piece, and ends must meet at the
same height too.

Onto a polyline source, an object facing the other way stays out: an arc
or a polyline faces its normal, a line always counts as facing up.
AutoCAD 2024 (accoreconsole, measured) joins a line with normal 0,0,-1
to a polyline facing up, no line to a polyline facing down, and an arc
or polyline only when it faces the polyline's way. A line or arc source
keeps the old behaviour: the core console can't measure it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 23:18:18 +07:00
KnottyDyesandClaude Opus 5.5 b573490901 Docs: qualify the README DWG read claims
The format-parity table marks R13 and R14 DWG reading as untested and
2018 as tested only on synthetic files; say the same in the README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:13:35 -07:00
KnottyDyesandClaude Opus 5.5 5f4c2ed819 Docs: SAVEAS version overrides the kept version and is remembered
Say so wherever the docs describe a drawing keeping its own version,
as file-format-parity.md already does: save_as writes an explicit
version into $ACADVER, so later saves use it too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:13:35 -07:00
KnottyDyes 203ed93f51 Docs: describe DXF and DWG save-version selection 2026-11-04 09:13:35 -07:00
2ez4gcxandClaude Opus 5.5 20a9ac7433 MINSERT: JSON rows and columns are whole numbers
The JSON form read rows and columns as numbers with no fraction, so 2.0 and
1e2 were counts. They must now be JSON whole numbers from 1 to 32767, as the
array commands' JSON counts already are; missing or null is still 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 22:08:20 +07:00
2ez4gcxandClaude Opus 5.5 22b2f7a5a9 Merge main into feat/copy-autocad; NO_OR is 29 long
main and this branch each added a row to NO_OR in prompt.rs ("Enter
option" and "Enter a copy mode option") on top of the same 27, and both
declared 28; the merge has 29 rows, so the declared length is now 29.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 20:51:41 +07:00
2ez4gcxandClaude Opus 5.5 ca3ff7997f INSERT/MINSERT: take points at the scale, rotation and spacing prompts
These prompts ignored a point. AutoCAD 2024 (measured on INSERT and
MINSERT) takes one as the first of two at the Scale, X, Y, Z and Rotate
presets and at MINSERT's column spacing, asking "Specify second point:"
(the distance is the scale or spacing, the direction the rotation; Enter
there keeps a preset's default); at XYZ's Z a point gives its distance from
the insertion point; Y scale refuses a point. They now do the same, with
AutoCAD's messages at each prompt ("Value must be nonzero.", "Requires
numeric distance or two points.", "Requires valid numeric angle or two
points.", "Requires numeric distance or second point.", "Requires numeric
value."). Exploded INSERT's scale takes a positive number only ("Value must
be positive and nonzero."). The Rotate preset still reads typed text as an
angle, so <<45 stays 45 degrees.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 20:33:17 +07:00
2ez4gcxandClaude Opus 5.5 a113667951 ARRAYPATH: no extra item where a closed path closes, by spacing
The JSON spacing form made floor(length / spacing) + 1 items on every path,
so on a closed one the last sat on top of the first (or nearer to it than
the spacing). AutoCAD 2024 fills a closed path with floor(length / spacing)
items and an open one with one more, at its end (measured with Fill entire
path on a closed and an open square and a circle). The spacing form now does
the same, letting length / spacing fall 1e-9 short for rounding.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 19:46:34 +07:00
2ez4gcxandClaude Opus 5.5 8af4b8a61b DIVIDE: take a whole number as typed for the number of segments
The count was read as a number with no fraction, so 5.0, 5. and 1e1 were
taken; a point gave its distance from the pick as the count; and Enter ended
DIVIDE. AutoCAD 2024 takes +5, 05 and 2 to 32767, and refuses all of those,
and 4.5, 1, 32768 and x, with "Requires an integer between 2 and 32767, or
option keyword." ("...32767." once Block has been chosen) and asks again
(measured). DIVIDE now does the same. MEASURE, which shares the prompt
machine, is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 19:05:56 +07:00
2ez4gcxandClaude Opus 5.5 223beb2fb8 SPLINEDIT: take a whole number as typed for Elevate order
"Enter new order" took a number with no fraction from 1 to 1000, so 5.0 and
1e1 were taken, and a point went back to the vertex menu without a word.
AutoCAD 2024 takes +5 and 05, keeps the order on 4 (a cubic's), and refuses
5.0, 5., 1e1, 4.5, 3, 27 and a point with "Requires an integer between 4
and 26."; the range starts at the spline's own order (measured at orders 4
and 5). The prompt now does the same, and the JSON form's elevate uses the
same wording. The prompt's logic moves to input_order(), which keeps
SplineditM::input under clippy's complexity limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 19:02:20 +07:00
2ez4gcxandClaude Opus 5.5 20463574de COPY: MAXARRAY doesn't limit Array; refuse a point at the count
AutoCAD 2024 doesn't apply MAXARRAY to COPY's Array: with MaxArray 100000,
four lines and 26000 items made 104000 lines. The count is now 2 to 32767
whatever the selection, as AutoCAD asks it. A point at "Enter number of
items to array:" was ignored; AutoCAD refuses it with "Requires an integer
between 2 and 32767." (measured with a LISP point), and so does COPY now.

So that a large selection can't run out of memory, the copies (items after
the first, times the objects) stay within MAX_ARRAY_ITEMS, ARRAY's own limit
whatever MAXARRAY says, checked before anything is made.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 17:35:30 +07:00
2ez4gcxandClaude Opus 5.5 b44d5c3588 ARRAYPATH: refuse a JSON count or spacing it can't use
The JSON form read `count` with as_u64 and `spacing` with as_f64 and quietly
dropped what didn't fit: a count of 4.5, "8" or -3 made the default 6 items,
0 made 1, and a spacing of 0, -5 or "10" fell back to the count. They are now
refused as the other arrays' JSON forms refuse them: the count goes through
count_or (a whole number of at least 1) and the spacing through size_param (a
positive number). Missing or null keeps the defaults.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 16:50:40 +07:00
2ez4gcxandClaude Opus 5.5 35462869e6 SPLINEDIT: take a whole number as typed for the polyline precision
"Specify a precision <10>:" read a number from 0 to 99 and rounded it, so
5.0, 5. and 4.5 were taken. AutoCAD 2024 refuses those, and 1e1, 8/2, 100,
-1 and a point, with "Requires an integer between 0 and 99." and takes +5
and 05 (measured). A point used to convert with precision 10; it is now
refused too.

The JSON form clamped `precision` to 99 and read any other value as 10. It
now refuses a precision that isn't a whole number from 0 to 99; absent or
null is still 10.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 16:15:17 +07:00
2ez4gcxandClaude Opus 5.5 cf90a60626 MINSERT: take a whole number as typed for the rows and columns
The row and column counts were read as a number with no fraction, so 5.0,
5. and 1e1 were taken. AutoCAD 2024 refuses those with "Requires an integer
between 1 and 32767." and asks again, and takes +3 and 03 (measured at the
rows, and 5.0 and +3 at the columns). A point at these prompts was ignored
without a message; AutoCAD refuses it with the same message (measured with
a LISP point at the rows).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 15:39:35 +07:00
2ez4gcxandClaude Opus 5.5 81f8032255 OPTIONS: a refused change puts the same drawing back
Writing the header entries back went through doc_mut, whose copy on
write gave a clean drawing a new Arc, so a refused OPTIONS call marked
it changed. apply now keeps the drawing's Arc when SNAPUNIT or GRIDUNIT
is among the values and puts that same Arc back on a refusal; a call
that names neither never touches the drawing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 13:43:33 +07:00
2ez4gcxandClaude Opus 5.5 1d16e82a49 ARRAYPATH: the item count takes a whole number as AutoCAD 2024 does
"Enter number of items along path" read the count as a distance and cut
it to an integer, so 4.5 gave 4 items and 1e1, 8/2 and 3' were taken.
AutoCAD 2024 takes a whole number from 1 to 32767 in plain decimals
there (5, +5, 05, 5., 5.0) and refuses 4.5, 1e1, 8/2, 3', 0 and 32768
(measured); the count is now read the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 13:02:19 +07:00
2ez4gcxandClaude Opus 5.5 8ecf3e6cac ARRAY: counts take a whole number as typed, as AutoCAD 2024 does
The ARRAYRECT, ARRAYPOLAR, -ARRAY and ARRAYEDIT count prompts read a
number with no fraction, so they took 5.0, 4. and 1e1. AutoCAD 2024
refuses those, and 8/2, 3' and 4.5, and takes +3 and 03 (measured at
ARRAYRECT's rows and columns, ARRAYPOLAR's items and rows, and -ARRAY's
rows and items). The count is now read as a whole number.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 12:22:19 +07:00
2ez4gcxandClaude Opus 5.5 ab71b353d5 OPTIONS: reset puts every profile variable back; a refused change leaves the drawing's snap and grid
options::reset missed 15 profile variables (the Dynamic Input, selection
preview and area, grip, PICKSTYLE and MEASUREINIT settings), so a reset
left them as they were. It now restores all of them; SNAPUNIT and
GRIDUNIT, which the drawing keeps in its header, are still left alone.

apply is all or nothing, but a refused value left SNAPUNIT and GRIDUNIT
written to the drawing's header. Their raw header entries are now put
back as they were, or removed when the drawing didn't have them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 11:54:04 +07:00
2ez4gcxandClaude Opus 5.5 02dfd37d14 Merge main into fix/linetype-dash-layout
main added SHX shapes to complex linetypes in linetype_text.rs; this
branch lays linetype elements out with Layout and phase. Both are kept:
shapes go where texts and dashes go (centred on an open run), and
main's point budget counts only the elements placed. main's shape test
now expects the centred positions, as the text test does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:35:44 +07:00
2ez4gcxandClaude Opus 5.5 43207db68e QLEADER: refuse a width that overflows; name an unreadable JSON point
A width given by a point far enough away to overflow is refused with the
message typed text gets, and the width is asked again. In the JSON form, a
point that can't be read says so instead of saying `points` is missing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 05:02:43 +07:00
2ez4gcxandClaude Opus 5.5 69b214743d COPY: pin +3 and 03 at the array count, as AutoCAD 2024 takes them
AutoCAD 2024 takes "+3" and "03" at "Enter number of items to array:"
(measured: three items each), which the count's integer parse already
does. Say so in the comment and test it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 04:38:00 +07:00
2ez4gcxandClaude Opus 5.5 3c9b4be339 JOIN: whole objects by their ends, the circle question, the source's space
Measured in AutoCAD 2024's core console:
- Objects join whole, by their end points; a polyline is never split, and
  one met only at an inner vertex stays as it is. The source is the first
  pick JOIN can take (a circle picked first is passed over).
- Where an object meeting the chain at more than one place goes: a
  polyline by its first vertex if it can, before the chain rather than
  after; a line or an arc turned round if it can. A source that already
  ends where it starts still takes more; a join that closes the chain
  stops it; a source of no length takes nothing; a lone polyline whose
  ends meet stays open.
- Arcs that come round make a circle with no tolerance at the source's
  start, and the command line asks "Combined arc segments form a circle.
  Convert to circle? [Yes/No] <Yes>:" first; No leaves the arcs. The JSON
  form takes the default.
- A new polyline keeps another polyline's widths, and what JOIN makes
  goes in the source's space.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 04:36:45 +07:00
2ez4gcxandClaude Opus 5.5 762b64268b QLEADER at the command line, as AutoCAD 2024 runs it with its default settings
Up to three leader points, a text width (not remembered; a point gives its
distance from the leader's end), then lines of multiline text. The text
sits DIMGAP past the end: with the middle of its first line level with it
when the leader runs right (attachment 1), of its last line when it runs
left (attachment 9), whatever DIMTAD. A hook line DIMASZ long is added when
the last segment slopes and text follows. Enter at the first line leaves
the leader alone. Measured in AutoCAD 2024's core console. Alias LE, and a
JSON form.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 03:32:55 +07:00
2ez4gcxandClaude Opus 5.5 c2b2545d0a COPY: the array count takes digits only; mOde Enter keeps the mode shown; reset COPYMODE
AutoCAD 2024 refuses 4.0, 1e1, 8/2, 1' and 3" at "Enter number of items
to array:" (measured), so the count is read as digits, not as a number
with no fraction. Enter at the mOde prompt now runs COPY in the mode the
prompt shows, and OPTIONS reset puts COPYMODE back to 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 02:55:48 +07:00
2ez4gcxandClaude Opus 5.5 c36cc6af34 SPLINE: a closed spline keeps its seam and its tangent where it closes
Review of #2705: REVERSE turned a closed spline's whole fit list round
while the curve still started at the old first fit point. The DXF
writer, which writes a closed spline's fit points from the first one,
then wrote another seam, and the next fit-point edit moved it.

Measured with AutoCAD 2024 (accoreconsole) on SPLINE (0,0) (4,0) (6,3)
(1,4) Close:
- REVERSE keeps the first fit point first and turns the others round
  ([f0, f3, f2, f1]); it turns the tangent where the curve closes
  (12/13) round and reverses the control points and knots;
- SPLINEDIT Fit data Move, Delete (of the first fit point too) and
  Open keep that tangent instead of working it out again from the
  points.

So a closed fit spline with chord-length knots now keeps its tangent
where it closes as both end tangents, as AutoCAD keeps 12/13:
- refits, grips and SPLINEDIT take it;
- `Spline::reversed` keeps the seam first and turns the tangent round;
- the DXF reader keeps it for such a spline, and drops the curve's own
  tangents that the writer gives the others (periodic knots, a fit
  tolerance, a kink);
- SPLINEDIT Close still gives the closed curve its own tangent.
A new closed spline still ignores the tangents given with it.

Also:
- a closed kinked fit stores its fit points from the kink where the
  curve starts;
- the closing tangent is divided by its length, not normalised, so a
  short one is not a zero tangent;
- AutoCAD's 44 = 1e-10 (no fit tolerance) is read as 0, and a tolerance
  too tight to approximate with gives AutoCAD's chord-length build, as
  for an open spline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 01:54:22 +07:00
2ez4gcxandClaude Opus 5.5 03c8bac609 SPLINE: two fit points with a fit tolerance make the same cubic
AutoCAD 2024 builds a chord-length spline through two points as the cubic
with control points at the thirds whatever the fit tolerance (measured with
tolerance 1: the same control points and knots as with 0, only group 44
differs). The tolerance no longer turns it into a line. The comment on the
interpolation fallback now says what was measured, and the test compares
the result with the tolerance-0 fit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 01:36:48 +07:00
2ez4gcxandClaude Opus 5.5 a9a3b35c91 feat(engine): COPY with COPYMODE, Multiple/mOde, Array and Fit as AutoCAD 2024
COPYMODE (profile, 0 copies until Exit, 1 makes one copy) and the base point
options mOde (sets it) and Multiple (this command only). Enter at the first
second point copies by the base point taken as a displacement. Array asks for
2 to 32767 items, the original included, and spaces them a second point apart
or, with Fit, up to it; Undo takes back the last placement, an array at once.
MAXARRAY caps an array's copies as it caps ARRAY's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 23:38:46 +07:00
2ez4gcxandClaude Opus 5.5 6c81995e03 fix(engine): JOIN onto the source object as AutoCAD 2024 does
Lines on the source's line make it one longer line and arcs on its circle
join counterclockwise from its start, both keeping the source's handle;
arcs that come round to within 1e-6 rad of its start make a circle on the
source's layer. An open polyline source keeps its handle, its own vertices,
elevation, PLINEGEN and (with only lines and arcs) constant width; other
polylines keep their bulges and widths, lines and arcs take the widths of
the source's vertex at that end. The tolerance is AutoCAD's measured 1e-6,
absolute at any coordinate size. The message names a line, arc or circle.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 23:23:26 +07:00
2ez4gcxandClaude Opus 5.5 99ae84f39c SPLINE: the preview adds no fit point with the cursor on the last one
A click on the last fit point adds nothing, but the preview still added
the cursor there, so it showed a corner the command would not make.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 21:34:08 +07:00
2ez4gcxandClaude Opus 5.5 04b56c4f4a Test the fit-option DXF roundtrip over the whole spline
Chord-length knots now run to the fit points' length rather than 1, so the
roundtrip check sampled only the first part of those splines. It now
samples the spline's own domain and checks the domain survives the file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 20:53:28 +07:00
2ez4gcxandClaude Opus 5.5 cbf79599e2 STRETCH: a fit-point spline moves its fit points and is fitted again
AutoCAD 2024 (accoreconsole, entget after STRETCH of a spline stored with
fit points only) moves the fit points inside the area and fits the spline
through them again, keeping its fit data (70 = 1064, 74 = 4); with all of
them inside, it moves whole. Here such a spline moved whole by its first
grip, or not at all. The test pins AutoCAD's fit points for three windows:
the last fit point, a middle one, and the whole spline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 20:38:34 +07:00
2ez4gcxandClaude Opus 5.5 de9f9ccc93 RECTANG: test corners at the limit where they still fit
AutoCAD 2024 (accoreconsole, entget of a 4 by 2 rectangle) keeps corners
exactly as long as the shorter side allows: fillet 1, and chamfer 1 + 1 or
1.2 + 0.8, still fit. A hair longer (fillet 1.0001, chamfer 1.2 + 0.81) and
the corners stay square, each still written twice. The rule already matches;
this pins the six measured rectangles, including which way the two chamfer
distances run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 20:35:08 +07:00
2ez4gcxandClaude Opus 5.5 25afec0fa9 Merge main into fix/stretch-arcs-bulges-splines
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 19:53:36 +07:00
2ez4gcxandClaude Opus 5.5 1b16f3caeb Merge branch 'fix/spline-file-tangent-length' into fix/spline-closed-autocad
Stacks the closed fit-spline change on the DXF tangent-length one (#2703).
Both change the SPLINE reader; the merged reader keeps both rules:

- an open spline keeps a file's 12/13 tangents with their length and is
  rebuilt from fit data with them as the end derivatives (#2703);
- a closed spline drops AutoCAD's closing fit point and takes its
  closing tangent from the curve, not from 12/13.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 18:48:24 +07:00
2ez4gcxandClaude Opus 5.5 8178e578c2 SPLINE: a small uniform scale keeps a spline's end tangents
`transform` dropped a tangent that the map shrank to under EPS of the
tangent's own length. So SCALE 1e-10 lost a (100, 0) tangent, although
the map is invertible.

The check now compares with the map's largest axis scale. An invertible
uniform scale, however small, keeps the tangent. A singular map, or one
that squashes the direction to under EPS of that scale, still drops it.
`scale_factor` (sqrt |det|) would not do: it is 0 for a singular map, so
rounding noise would survive as a direction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 18:46:22 +07:00
2ez4gcxandClaude Opus 5.5 fe1c3eeeab SPLINE: a tangent too short to normalise is dropped, not zero
`sanitized` kept tangents longer than 1e-12, but `Vec2::normalized`
returns zero up to 1e-9, so a direction between the two was stored as
Some(ZERO): a zero end derivative instead of no tangent. Such a direction
is now dropped.

`transform` scales a tangent by the lengths instead of going through
`normalized`, so a short tangent from a file survives MOVE, ROTATE, SCALE
and MIRROR. A map that flattens its direction still drops it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 18:00:43 +07:00
2ez4gcxandClaude Opus 5.5 93e2255722 SPLINE: closed fit-point splines built as AutoCAD 2024 builds them
A closed spline through fit points with chord-length knots and no fit
tolerance is now the cubic AutoCAD 2024 builds (measured with
accoreconsole): the open chord-length interpolation through the fit
points and back to the first, clamped, with the same unit first
derivative at both ends. That tangent is the derivative at the first
point of the cubic through the first four points of the loop, with
square-root-of-chord parameters.

AutoCAD flags this spline periodic (group 70 bit 2) although its knots
are clamped: it sets the bit from the curve, the same first derivative
where it closes. `Spline::is_periodic` now means that (closed and smooth
where it closes); the knot shape it meant before is `Spline::wraps`
(unclamped knots, control points wrapping round), which SPLINEDIT uses
for its control-point edits.

DXF: AutoCAD rebuilds a spline with fit data from its fit points and end
tangents, and opened a closed spline written with its fit points once
as an open spline. The writer now adds the first fit point again at the
end and the tangent where the curve closes as 12 and 13, as AutoCAD
writes it; the reader drops the closing point and takes the tangent from
the curve. AutoCAD reads the written spline back as its own (70 = 1067,
the same control points).

Closed splines with square-root or uniform knots, or a fit tolerance,
are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 17:44:41 +07:00
2ez4gcxandClaude Opus 5.5 5513565da9 SPLINE: a file's end tangents count with their length, as in AutoCAD 2024
A DXF SPLINE stored with fit points and 12/13 tangents only is rebuilt
with each stored vector as its end derivative, length included: AutoCAD
2024 does so (12 = (0, 3) gives control points 2.67 from those of the
unit (0, 1)). The spline keeps the vector, so it is written back as read.
Refits (grips, SPLINEDIT, STRETCH) use it as stored, and transforms turn
it and keep its length, as AutoCAD's MOVE, ROTATE, SCALE, MIRROR and
SPLINEDIT Fit data Move do.

SPLINE, SPLINEDIT and the JSON options still take tangents as unit
directions: fit_with normalises them, and SPLINEDIT's input is already
normalised.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 17:13:41 +07:00
2ez4gcxandClaude Opus 5.5 9a6f025c47 SPLINE: open fit-point splines built as AutoCAD 2024 builds them
An open spline through fit points with chord-length knots and no fit
tolerance is now the cubic AutoCAD 2024 builds (measured with
accoreconsole, `entget` of the control points and knots):

- the knots are the running chord length, not normalised, with the fit
  points' own parameters as the interior knots;
- there are two control points more than fit points: an end with a
  tangent has it as its first derivative, an end without one has no
  second derivative (with one tangent too);
- two fit points without tangents make a cubic with its control points
  at the thirds, no longer a line.

SPLINE also leaves out a click on the point before, as AutoCAD does,
instead of storing a repeated fit point (a kink).

Closed splines, the other knot parametrisations and fit tolerance are
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 16:28:16 +07:00
Aldo ZarateandClaude Opus 5.5 06491fc757 Merge upstream/main into perf/cjk-text
ttf.rs keeps both test modules: the thread cache's and main's font
directory scan.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 22:03:34 -06:00
2ez4gcxandClaude Opus 5.5 897f53c7b3 Merge main into fix/linetype-dash-layout
After #2603, dashes are laid out only with Options::linetypes on: the
runs stroked with a layout (open, or closed from an anchor) and the
polyline centre line keep that check, so hit tests still draw lines
whole.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 07:40:25 +07:00
2ez4gcxandClaude Opus 5.5 97b531eaae RECTANG: Area with cut corners, oversized corners, Rotation as AutoCAD takes it
Three rules measured in AutoCAD 2024 that main's RECTANG does not follow:

- Area sizes the rectangle so that its outline, corners cut, encloses the
  area: _C 1.5 2.5 ... _A 1442.93 _W 35.535 has length 40.817, the
  area plus 2 x 1.5 x 2.5 over the width; a fillet adds (4 - pi) r^2.
  When the corners then don't fit, they stay square and the area is
  the full rectangle's.
- A fillet or chamfer too large for the shorter side leaves each corner
  as two coincident vertices, eight in all, as AutoCAD stores them.
- A typed Rotation is an amount turned in the ANGDIR sense from +X,
  ANGBASE aside: with ANGBASE 90 and ANGDIR 1, 30 turns the rectangle
  30 degrees clockwise. The modes line and the prompt's default show it
  as the drawing shows angles: "Rotation=120.00", "30d30'" with AUNITS 1.

The fit test is one function, shared by the vertices and Area. Of the
40 measured cases that set every mode, main's RECTANG matches 33; this
matches all 40.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 10:59:37 +07:00
2ez4gcxandClaude Opus 5.5 b872742e42 Merge main into the RECTANG fix, keeping #2554's RECTANG
#2554, now in main, rewrote RECTANG's vertex order, corners and
remembered modes along the same measurements as this branch. The
conflicts are resolved by taking main's RECTANG as it is. The next commit
brings back, on top of it, the rules this branch measured that #2554
left out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 10:59:30 +07:00
2ez4gcxandClaude Opus 5.5 b91fa88224 Linetypes: a plot or export keeps the dashes of a run over 50,000 periods
The 50,000-period guard is for a display zoomed out a lot, so it now applies only where there
is a level of detail (min_pattern above 0). A plot or export has none and keeps the pattern on a
run of any length, bounded by the two-million-element work limit; linetype text follows, through
phase. This is the plot exemption of #1277 (#1069) in the new layout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 08:41:26 +07:00
2ez4gcxandClaude Opus 5.5 3e8f468fe3 Linetypes: anchor a closed PLINEGEN run at its second vertex when it coincides with the first
The anchor was the length of the first drawn segment, so when the first two
vertices coincide (Polyline::segments leaves that pair out) the pattern was
anchored at the third vertex. It is now the chord length from the first
vertex to the second (wide::second_vertex_at), 0 for that pair, and the
thin run and the wide band share it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 22:57:33 +07:00
2ez4gcxandClaude Opus 5.5 cc69082a85 PLINE test: check PLINEWID after Width before Halfwidth
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 19:46:51 +07:00
2ez4gcxandClaude Opus 5.5 e6f2ea0405 Linetypes: keep the cap on pattern elements laid out
The rewritten layout capped runs at 50,000 periods but dropped the
earlier limit of 2,000,000 pattern elements, so a long pattern repeated
that often could produce millions of ranges. A run past either limit is
drawn continuous again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 19:21:33 +07:00
2ez4gcxandClaude Opus 5.5 d56ead7ca4 PLINE: the JSON form starts at PLINEWID too
A JSON pline without a width now takes PLINEWID, as the command does,
unless its vertices give their own widths; an explicit width, 0
included, is kept. FILLET and CHAMFER's JSON forms already fall back on
their variables the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 18:49:00 +07:00
2ez4gcxandClaude Opus 5.5 dc07a1032d Linetypes: anchor a closed run at its second vertex as it is drawn
The anchor of a closed PLINEGEN polyline is now the length of its first
segment tessellated at the drawing tolerance, as the run is measured,
not the arc length. With an arc first, a dash now starts right at the
second vertex, matching the filled band, which already measured it so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 18:46:54 +07:00
2ez4gcxandClaude Opus 5.5 6c2d37983e Linetypes: a wide polyline's centre line is dashed as a thin one
With fill off, a polyline with width draws its centre line. It now goes
through the same layout as a polyline without width: stretched around a
closed PLINEGEN one from its second vertex, along the whole of an open
PLINEGEN one, and restarted at each vertex otherwise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 18:15:45 +07:00
2ez4gcxandClaude Opus 5.5 45f9b5653e Merge main into fix/pline-undo-plinewid
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 17:46:30 +07:00
2ez4gcxandClaude Opus 5.5 d79185ed8d RECTANG: take Rotation as AutoCAD does and show it in the drawing's units
Measured in AutoCAD 2024 with ANGBASE 90 and ANGDIR 1: Rotation 30 turns
the rectangle 30 degrees clockwise from +X (ANGBASE aside), and the next
RECTANG shows "Current rectangle modes:  Rotation=120.00", the rotation
from ANGBASE in the ANGDIR sense; the rotation prompt's default reads
<120.00>. With AUNITS 1, 30.5 shows as "Rotation=30d30'". The typed
rotation is now an amount turned in the ANGDIR sense, and both the
modes line and the default use the drawing's angle settings and units.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 17:17:16 +07:00
2ez4gcxandClaude Opus 5.5 6d3f63752b Linetypes: one ranges function that takes the layout
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 15:28:29 +07:00
2ez4gcxandClaude Opus 5.5 3944717ca2 Merge main into fix/linetype-dash-layout
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:54:02 +07:00
2ez4gcxandClaude Opus 5.5 c319cd7ae4 Linetypes: closed wide bands and gap-first phase follow the dashes
A closed PLINEGEN polyline with width now lays its pattern out like a
thin one: stretched around the run from the second vertex
(linetype::ranges_as with Layout::Closed), not centred as an open run.

phase() now gives where the periods of a gap-first pattern start when
the run leaves room for a piece of dash at its start: a gap before the
second element at x, as gap_first lays them, so text in the linetype
sits with its dashes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:54:01 +07:00
2ez4gcxandClaude Opus 5.5 a303ff433c Linetypes: lay dashes out as AutoCAD does
Patterns were laid out from the start of every run with the first dash
whole. AutoCAD 2024 plots, read back stroke by stroke, show otherwise:
an open run is drawn continuous when shorter than one period, and
otherwise the pattern is centred (n = floor(L / period),
p0 = (n·period + first − L) / 2), the first dash starting at the run's
start and the last ending at its end; a pattern opening with a dot puts
dots at both ends, and one opening with a gap has a rule of its own. A
closed run (a circle, a whole ellipse, a closed PLINEGEN polyline) is
stretched to round(L / period) periods from its anchor (angle 0, or the
second vertex).

linetype::layout makes the drawn stretches for both; apply, apply_as
and ranges use it, the draw code picks the closed layout for circles,
whole ellipses and closed PLINEGEN polylines, and text in complex
linetypes follows the same phase. The measured lines, dots, circle,
rectangles and 33 gap-first cases are pinned in the linetype tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 13:11:38 +07:00
2ez4gcxandClaude Opus 5.5 f126a24c42 Merge main into the RECTANG fix
Picks up #2302, which formats crates/render/src/dim/linear.rs; the
gate's fmt step failed on that file, not on this branch's changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 09:06:54 +07:00
2ez4gcxandClaude Opus 5.5 55d8db69dc STRETCH: an arc with both ends inside moves whole
A full-sweep arc (start = end) has a zero chord, so rebuilding it from
the moved ends gave nothing and STRETCH left it in place even when the
window held all of it. When both ends move, translate the arc instead;
rebuild from the ends only when one of them moves.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 09:06:34 +07:00
2ez4gcxandClaude Opus 5.5 b3ff5505c5 Merge main into the STRETCH fix; import Arc explicitly
#2239 replaced stretch.rs's glob import with an explicit list, and the
new arc rule names cadcraft_geom::Arc, which only the glob brought in, so
the branch no longer compiled on main. `use cadcraft_geom::Arc;` after
the use super::{…} block is the only change the merge needs. Reported in
review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 08:45:45 +07:00
2ez4gcxandClaude Opus 5.5 bc36b99152 Merge main into the RECTANG fix; drop the rect_with_corners import
#2239 replaced rect.rs's glob import with an explicit list that names
rect_with_corners, which this PR removes (the new vertex builder replaces
it), so the branch no longer compiled on main. Dropping the name from the
list is the only change the merge needs. Reported in review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 08:41:55 +07:00
Aldo ZarateandClaude Opus 5.5 d8c37cc6c1 Format dim/linear.rs as rustfmt does
Main's fmt check fails on it since #2302; this keeps the PR's gate green.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:40:18 -06:00
Aldo Zarate 8391c1f0de Merge remote-tracking branch 'upstream/main' into perf/cjk-text 2026-10-29 19:39:48 -06:00
Aldo ZarateandClaude Opus 5.5 7941757ed3 Check every placed glyph corner before building its bounds
Bounds2 skips non-finite points, so a glyph with one overflowing corner
could be culled from the few corners left. Any non-finite corner now
leaves the glyph to the mesh code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:36:45 -06:00
Aldo Zarate d325681051 Merge remote-tracking branch 'upstream/main' into perf/cjk-text
# Conflicts:
#	crates/render/src/text.rs
2026-10-29 19:25:42 -06:00
Aldo ZarateandClaude Opus 5.5 e5dd7290e9 Cull glyphs by their own ink box, not a fixed em margin
Screen builds left out a filled glyph when a fixed font-unit box
(-1000..2000) placed by its transform missed the view, so ink reaching
more than an em past its box (flourishes, long ligatures, tall stacks,
large operators) vanished when the view saw only that part. Each
outline now records its font-unit bounds once as it is built, exposed
as ttf::glyph_bounds through the same per-thread and shared outline
caches, and may_show places those four corners instead: exact, and
still four points per glyph however long its outline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 10:53:41 -06:00
Aldo Zarate 000dbb4383 Merge remote-tracking branch 'upstream/main' into perf/cjk-text 2026-10-29 10:41:47 -06:00
2ez4gcxandClaude Opus 5.5 508c28654d STRETCH: pin the spline selection AutoCAD makes, and note the collapsed arc
Two review questions, answered by measuring AutoCAD 2024 (accoreconsole,
read back with entget):

- A crossing window that holds a spline's control point but misses the
  drawn curve selects nothing in AutoCAD ("0 found"), so the spline stays
  put; CADCraft does the same. Only a window that also crosses the curve
  moves the control point, (10,100) to (15,103). Both cases join the test.
- An arc end stretched onto the other end: AutoCAD collapses the arc into
  a zero-radius arc at that point (radius 6e-16). CADCraft keeps the arc
  rather than make an object nothing can draw or pick; the code says so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:59:07 +07:00
2ez4gcxandClaude Opus 5.5 b57647de0a PLINEWID is an ordinary system variable
PLINE now starts at PLINEWID and stores its widths back, but the
variable itself was out of reach: typing PLINEWID was an unknown command
and GETVAR an unknown variable until a Width answer happened to set it.
It joins the header-variable table (a real of at least 0, default 0, as
in AutoCAD), so GETVAR reports 0, SETVAR and the typed name set it, and
SETVAR ? lists it. Suggested in review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:45:54 +07:00
2ez4gcxandClaude Opus 5.5 12e56da913 RECTANG names the modes it carries over, as AutoCAD does
With chamfer, fillet, width, elevation, thickness and rotation carried
over, a plain RECTANG can draw something its own command never asked for,
and nothing said so. It now opens with AutoCAD's line, in AutoCAD's words
and order: "Current rectangle modes:  Chamfer=1.6574 x 2.8497  Rotation=50.50",
"Current rectangle modes:  Elevation=7.5000  Thickness=2.2500  Rotation=30.96"
(both from AutoCAD 2024's log for the same inputs); no line when every
mode is off. POINT already echoes its modes the same way. Suggested in
review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:39:33 +07:00
2ez4gcxandClaude Opus 5.5 a819d82028 Merge main (the module layout of #2220) into the STRETCH fix
#2220 moved STRETCH to cmd/modify/stretch.rs; keep_height and the arc,
polyline-bulge and spline rules move with it, unchanged, below the doc
comment #2220 gave stretch_entity.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 11:51:12 +07:00
2ez4gcxandClaude Opus 5.5 9ce57972c8 Merge main (the module layout of #2220) into the PLINE fix
#2220 moved PLINE's prompt machine to cmd/draw/line_pline.rs; the fix
(PLINEWID as the starting width, Undo returning to the last segment's
mode) moves with it, unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 10:52:10 +07:00
2ez4gcxandClaude Opus 5.5 f49355f6c2 Merge main (the module layout of #2220) into the RECTANG fix
#2220 moved RECTANG from cmd/draw2.rs to cmd/draw2/rect.rs and LastUsed
from lib.rs to last_used.rs. The fix moves with them: rect.rs carries the
AutoCAD vertex rules, draw2 re-exports RectangModes, and LastUsed keeps
the remembered RECTANG options.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 10:28:32 +07:00
2ez4gcxandClaude Opus 5.5 99e973f71f RECTANG: Area adds the corner cut back only when the corners fit
Area sized the rectangle so that its cut corners take nothing off the
area asked for, but it did so even when the fillet or chamfer turned out
too large for the resulting sides and the corners stayed square: Area 4,
length 4, fillet 2 drew a square-cornered 4 x 1.858 rectangle. When the
corners don't fit, the sides now come from the area alone (4 x 1), in the
JSON form and at the prompt. Pointed out in review.

The fit test now lives in one place (corners_fit, with corner_cuts) and
is shared by the vertex builder and the Area sizing. All 64 measured
AutoCAD cases still match vertex for vertex.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:54:20 +07:00
2ez4gcxandClaude Opus 5.5 230d5107fb STRETCH: a collapsed arc segment loses its bulge
When a stretch brings both ends of a polyline arc segment together, the
chord is zero and there is no arc height left to keep; keep_height still
returned the old bulge, which then sat on a zero-length segment. It now
returns 0 (also for a NaN chord). Pointed out in review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:40:33 +07:00
2ez4gcxandClaude Opus 5.5 23a973edfa STRETCH: arcs and polyline arc segments keep their height; spline control points move
STRETCH was checked against AutoCAD 2024 black-box: 36 crossing-window
cases run in accoreconsole (lines, polylines, arcs, circles, text,
ellipses, splines, points, block references), each object read back with
entget. Lines, straight polylines, circles, text, full ellipses, points
and block references already matched; three kinds of object did not.

- Arcs moved whole when their centre was inside the window and were left
  alone otherwise. AutoCAD moves the ends that are inside and keeps the
  arc's height, bulge x chord / 2: the arc (0,0) r20 0-90 deg with its
  start stretched by (5,3) becomes centre (3.1798, -2.2061), radius
  22.4326. The centre alone moves nothing.
- Polyline arc segments kept their bulge, so they ballooned or flattened
  as a vertex moved. AutoCAD keeps their height too: bulge 0.5 over a
  chord of 25 becomes 0.6338 when the chord shrinks to 19.72 (and -1.5
  becomes -1.2303 over a longer one).
- Splines moved whole when their first grip was inside, and stayed put
  otherwise. AutoCAD moves the control points inside the window. Splines
  built from fit points keep the old behaviour, which was not measured.

An elliptical arc with one end inside is still left as it was: AutoCAD
changes the whole ellipse there by a rule one measurement does not pin.

The new test stretch_arcs_bulges_and_splines_match_autocad pins nine of
the measured cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:22:43 +07:00
2ez4gcxandClaude Opus 5.5 95429bb286 PLINE: Undo returns to the last segment's mode, and PLINEWID is the width
PLINE was checked against AutoCAD 2024 black-box: 76 typed inputs run in
accoreconsole, read back with entget and GETVAR. 72 matched; with this
change all 76 do.

- Undo after an arc segment stayed in arc mode, so a following `_L` was
  arc mode's Line instead of line mode's Length and the point became a
  plain vertex. AutoCAD returns to the mode of the segment now last:
  `_A` point `_U` `_L` point continues the last line by the point's
  distance, ending at (64.48701958199356, 48.21692560701169) in the
  measured case.
- PLINEWID was ignored: AutoCAD starts every polyline at that width
  ("Current line-width is 0.7500") and stores the ending width of the
  last Width or Halfwidth answer back into it (`_H 0.5 0.5` leaves
  PLINEWID 1).

The new test pline_undo_mode_and_plinewid_match_autocad pins both with
the measured numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 15:55:12 +07:00
2ez4gcxandClaude Opus 5.5 54e34b02ba RECTANG draws the vertices AutoCAD stores
RECTANG was checked against AutoCAD 2024 black-box: 64 typed inputs run
in accoreconsole, each polyline read back with entget. 18 matched; with
this change all 64 match vertex for vertex.

- Vertex order: AutoCAD starts at the first corner and runs along the
  first axis towards the other corner, so a rectangle is clockwise when
  the corners are picked down-right or up-left. CADCraft always started at
  the lower-left corner and ran counterclockwise.
- Chamfer: the first distance is cut on the edge into each corner and the
  second on the edge out of it, in drawing order. CADCraft cut the first
  along x and the second along y, which mirrors the corners whenever the
  two distances differ.
- Fillet bulges follow the drawing direction: negative on a clockwise
  rectangle.
- A fillet or chamfer too large for the shorter side leaves each corner
  as two coincident vertices (8 vertices, no arcs), not 4 vertices.
- Chamfer and Fillet replace each other: the option set last wins.
  CADCraft kept the fillet when a chamfer was set after it.
- Area sizes the rectangle so that the outline, with its corners cut
  off, encloses the area given: L = (A + 2*d1*d2) / W for a chamfer and
  (A + (4 - pi)*r^2) / W for a fillet. This applies to the JSON form too.
- Chamfer, fillet, width, elevation, thickness and rotation carry over to
  the next RECTANG (AutoCAD opens it with "Current rectangle modes:
  Fillet=2.0000" or "Elevation=7.5000  Thickness=2.2500  Rotation=30.96").
  They are kept in LastUsed; the JSON form stays stateless.

The new test rectang_vertices_match_autocad pins 12 of the measured
cases, one or more per rule. Three older tests change with the measured
behaviour: an oversized fillet now gives 8 coincident-pair vertices, and
two tests that draw several rectangles in one session set the remembered
rotation or fillet back explicitly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 15:43:58 +07:00
Aldo ZarateandClaude Opus 5.5 9a1bd48a26 Per-thread glyph outlines: bound them by points
Each thread kept up to 8192 glyph outlines in front of the shared cache with no size limit, and
held them after the shared cache let them go. They are now held within MAX_SHAPED_POINTS / 16
points per thread, and an outline above a quarter of that is read from the shared cache instead.
The generation test reads the cache before checking the generation, so another test's change in
between can't fail it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 08:10:30 -06:00
Aldo ZarateandClaude Opus 5.5 e57786e726 Per-thread caches: bound meshes by bytes; don't keep a stale font lookup
Each thread's text meshes were capped at 4096 entries but not by size; CJK text at full detail
could hold hundreds of MB per core. They are now capped at 16 MiB per thread (with the shared
cache's size estimate), and a mesh above a quarter of that is read from the shared cache instead.

A font lookup that ran while a font was being registered could keep the old answer (a "not
found") on that thread until the next change. The generation is read before the lookup, and the
answer is kept only under that generation, so a lookup overtaken by a change starts over.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 07:44:08 -06:00
Aldo ZarateandClaude Opus 5.5 4d3ceea73b Merge upstream/main into perf/cjk-text
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 19:41:29 -06:00
Aldo ZarateandClaude Opus 5.5 38e98e43c0 Faster CJK-heavy drawings: per-thread font caches, offscreen glyphs left out
Display lists are built on all cores, but every text looked its font up,
and every character its font lacks (all of a CJK text's) its fallback
font, glyph outline and glyph mesh, through shared tables behind global
locks; text-heavy drawings spent most of the build waiting on them.
Font lookups, fallback faces, FONTALT, glyph outlines and glyph meshes
now have per-thread caches in front of the shared ones (a generation
counter empties them when fonts or FONTALT/FONTFALLBACK change).

On screen, filled glyphs outside the area being looked at are left out,
as hatch patterns already are (the canvas builds again when the view
leaves that area); plots and exports keep every glyph. Zoomed in, every
glyph of every text was filled at that zoom's detail and drawn each
frame, i.e. on every mouse move.

Synthetic 3.8 MB drawing (24,000 TEXT and 2,500 MTEXT in Chinese, 30,000
lines), macOS, Apple silicon: display list at fit 335 -> 103 ms;
triangles at 16x zoom 11.2 M -> 0.44 M, at 64x 19.0 M -> 45 k.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 09:58:53 -06:00
236 changed files with 11602 additions and 1928 deletions
+1 -1
View File
@@ -87,7 +87,7 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker |
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending |
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the craft-i18n#401 phase 1 changes reviewed by a native Vietnamese speaker; older rows not yet proofread in full |
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
| `crates/ui-egui/src/i18n/ta.tsv` | @newsbaba24x7 (AI-assisted) | Original Tamil translations of CADCraft English strings, shared with storytold/craft-i18n `locales/ta/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings; the 1,289 rows from craft-i18n reviewed there for language and terminology by native speakers, and the whole Tamil interface reviewed in the running app by native speakers Radhika and Mohan Raj (2026-11-14); no font assets added (Tamil comes from an installed font or the craft-fonts face) |
Generated
+1272 -86
View File
File diff suppressed because it is too large Load Diff
+36 -32
View File
@@ -14,11 +14,11 @@ repository = "https://github.com/storytold/cadcraft"
# internal
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-constraints = { path = "crates/constraints" }
@@ -28,19 +28,19 @@ cadcraft-io = { path = "crates/io" }
cadcraft-engine = { path = "crates/engine" }
cadcraft-ui-egui = { path = "crates/ui-egui" }
cadcraft-mcp = { path = "crates/mcp" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# SVG/SVGZ import and export geometry (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Which paths stored in a drawing (xrefs, data links) may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
# Delimited text (CSV/TSV) parsing (shared Craft library).
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
@@ -74,8 +74,12 @@ encoding_rs = "0.8.35"
quick-xml = "0.42"
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
@@ -85,7 +89,7 @@ egui-wgpu = "0.37"
# Monotonic time on native and web (performance.now on wasm).
web-time = "1.1"
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
@@ -117,23 +121,23 @@ debug = 0
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
# (Cargo ignores dependency-local patches).
[patch.crates-io]
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+10 -4
View File
@@ -89,9 +89,15 @@
line, prompts with clickable `[Keywords]`, AutoComplete, object snaps, polar tracking, ortho,
direct distance entry, window and crossing selection, grips, and right-click-to-repeat behave
the way decades of drafting habit expect.
- **Open files.** DXF is read and written natively (ASCII and binary, R12 through 2018), and DWG
files (R13 through 2018) open and save through the open-source acadrust library. Export to SVG
and PNG today.
- **Open files.** DXF is read natively (R12 through 2018, with binary support from R13) and
written as 2000 through 2018 (ASCII and binary). DWG files (R13 through 2018; R13 and R14
untested, 2018 tested only on synthetic files) open through the open-source acadrust library
and save as 2000 through 2018. New drawings default to
2018 (AC1032) in both formats. In the app's Save dialog, File ▸ Default Save Format
(also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled
drawings; drawings with a file keep their own version, subject to supported-version mapping
and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later
saves. Export to SVG and PNG today.
- **Fast and native.** Pure Rust and egui, no Electron, no web view. One binary on macOS
(universal), Windows, Linux and FreeBSD, plus a WebAssembly build for the browser.
- **Built for agents.** Every menu item, tool and prompt is a command. Agents can type at the
@@ -114,7 +120,7 @@ numbers):
| Layers & properties | Layers palette and Layer Properties Manager (on/off, freeze, lock, plot, colour, linetype), layer tools (isolate, freeze, off, lock, match, previous), Properties palette with per-object editing, linetypes, lineweights, colour index and true colour |
| Annotation | All DIM* commands with full DIMSTYLE variables, overrides and every arrowhead, associative dimensions that follow geometry, MLEADER, TABLE, TrueType fonts (`.ttf`, `.otf`, `.ttc` collections), MTEXT formatting codes (fonts, heights, colours, stacked fractions), our own single-stroke drafting font |
| Hatch & blocks | Pick-point hatch boundaries with islands, pattern, solid and gradient fills from our own pattern library, BLOCK/INSERT, attributes and nested blocks |
| Files | DXF read (R12–2018, ASCII and binary) and write (R2000), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library) and write (R2000); PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) |
| Files | DXF read (R12–2018, binary from R13) and write (2000–2018, ASCII and binary), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library; R13 and R14 untested, 2018 tested only on synthetic files) and write (2000–2018). New drawings save as 2018 (AC1032); opened drawings keep their supported version, except DWG defaults to at least 2004. In the app's Save dialog, File ▸ Default Save Format (also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version for untitled drawings; drawings with a file keep their own version, subject to supported-version mapping and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later saves. DXF uses R2000 structure with the chosen `$ACADVER`. PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) for version selection and fidelity |
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
+1
View File
@@ -60,6 +60,7 @@ fn install_io() {
// 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);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
}
/// `path` as text, for the engine and io calls that take a file name as a string.
+3
View File
@@ -154,6 +154,9 @@ pub(crate) fn export_framed(s: &Session, out: &Path, window: Option<Bounds2>, io
if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) {
io.errln(format_args!("{m}"));
}
for note in cadcraft_engine::cmd::file::dwg_notes(d) {
io.errln(format_args!("{note}"));
}
}
Ok(())
}
@@ -0,0 +1,41 @@
//! `convert` to DWG says, in one warning, how many linetypes the DWG keeps with only their first
//! 255 dash elements (#1923, F-05); converting to DXF keeps them whole and says nothing.
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A DXF with a 256-element linetype and a line drawn with it.
fn dxf() -> String {
let mut s = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n0\nLTYPE\n2\nLONG\n70\n0\n3\nLong\n72\n65\n73\n256\n40\n192\n");
for i in 0..256 {
s.push_str(if i % 2 == 0 { "49\n1\n74\n0\n" } else { "49\n-0.5\n74\n0\n" });
}
s.push_str("0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n6\nLONG\n10\n0\n20\n0\n11\n10\n21\n0\n0\nENDSEC\n0\nEOF\n");
s
}
#[test]
fn convert_to_dwg_notes_the_linetypes_it_cuts() {
let dir = std::env::temp_dir().join(format!("cc-cli-ltype-dwg-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let source = dir.join("long.dxf");
std::fs::write(&source, dxf()).unwrap();
let source = source.to_str().unwrap();
let notes =
|out: &Output| String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("dash elements")).map(str::to_string).collect::<Vec<_>>();
let out = cli(&["convert", source, dir.join("long.dwg").to_str().unwrap()]);
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
assert!(
matches!(notes(&out).as_slice(), [note] if note.contains("1 linetype") && note.contains("255")),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let out = cli(&["convert", source, dir.join("copy.dxf").to_str().unwrap()]);
assert!(out.status.success() && notes(&out).is_empty(), "{}", String::from_utf8_lossy(&out.stderr));
let _ = std::fs::remove_dir_all(&dir);
}
+3
View File
@@ -1,6 +1,9 @@
mod cli;
mod drafting_spacing;
mod help;
// DWG output needs craft-dwg's bridge.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod ltype_dwg_note;
mod mcp_connect;
mod pdf_import;
mod skipped_records;
+2 -2
View File
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
cadcraft-fonts = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
+5 -2
View File
@@ -54,11 +54,12 @@ mod web {
if let Some(bridge) = &self.2 {
bridge.report_dirty(&self.0);
}
self.0.close_path(ctx);
}
/// Forward raw input to the web `CadApp` and capture Tab at the command line.
/// Forward raw input to the web `CadApp` and hand the frame's root values to the UI runtime.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(ctx, raw);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
self.0.before_input(ctx);
}
/// Preferences and validated panel placement survive reloads; egui memory is not kept.
fn save(&mut self, storage: &mut dyn eframe::Storage) {
@@ -134,6 +135,7 @@ mod web {
// 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);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
let Some(canvas) = app_canvas() else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
@@ -166,6 +168,7 @@ mod web {
canvas,
options,
Box::new(move |cc| {
cadcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
// Embedded, the host sends the drawing: start on the Start tab, not Drawing1.
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
let control = crate::api::install(cc.egui_ctx.clone());
+1 -1
View File
@@ -94,7 +94,7 @@ mod tests {
let mut ui = UiState::default();
let before = serde_json::to_value(&ui).unwrap();
let mut invalid = ui.clone();
invalid.docking.layout.root = None;
invalid.docking = cadcraft_ui_egui::docking::Workspace::default();
assert!(save(&invalid).is_err());
let mut record: Value = serde_json::from_str(&save(&ui).unwrap()).unwrap();
record["docking"] = serde_json::to_value(&invalid.docking).unwrap();
+3 -7
View File
@@ -41,22 +41,18 @@ winit = { version = "0.30", default-features = false, features = ["x11"] }
zbus = { version = "=5.19.0", default-features = false, features = ["async-io", "blocking-api"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Floating panels open in their own OS windows on the desktop; the web build keeps them in the page.
craft-ui = { workspace = true, features = ["native-windows"] }
craft-update = { workspace = true }
rfd = { workspace = true }
sys-locale = "0.3"
[target.'cfg(target_os = "macos")'.dependencies]
# `title_bar::sync_movable`: AppKit's title-band drag leaves the window still under the row's
# controls and under floating panels.
craft-window = { workspace = true }
muda = { version = "0.21", default-features = false }
# Quit CADCraft as a close request of the main window, so the unsaved-changes question runs (#2157).
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
# (system_animations.rs). Already in Cargo.lock through muda.
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] }
# The same winit eframe uses (the storytold fork, patched in the workspace): its opt-in that turns
# AppKit's terminate (Cmd+Q, Dock Quit) into a close request, so unsaved changes are asked about.
# The same winit eframe uses (the storytold fork, patched in the workspace).
# `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs).
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
+52 -40
View File
@@ -61,9 +61,6 @@ struct App {
/// `CADCRAFT_NO_NATIVE_MENU`: the menus stay inside the window.
#[cfg(target_os = "macos")]
menus_in_window: bool,
/// 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,
@@ -141,17 +138,18 @@ impl eframe::App for App {
if std::mem::take(&mut self.cad.quit_requested) {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
self.cad.close_path(ctx);
}
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and capture Tab at the command line.
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and hand the frame's root values to the UI
/// runtime.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
follow_desktop(raw, self.desktop_theme.current());
self.cad.raw_input_hook(ctx, raw);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
self.cad.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
cadcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
self.cad.guarded_ui(ui);
#[cfg(target_os = "macos")]
craft_window::title_bar::sync_movable(ui.ctx(), &mut self.movable);
}
/// A normal exit: the workspace is saved, and this run's autosave files are not needed (a
/// crash leaves them for recovery).
@@ -199,6 +197,7 @@ pub fn install_io() {
// 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);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
}
fn services() -> Services {
@@ -302,17 +301,15 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state
/// saved by the last session is restored instead of opening centred. `stencil`: the stencil bits of
/// its render pass ([`stencil_bits`]).
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui::framework::Decision>) -> eframe::NativeOptions {
let viewport = egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_app_id(os_window::app_id());
eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false)
.with_app_id(os_window::app_id()),
viewport: cadcraft_ui_egui::framework::apply_frame(viewport, frame),
// The size, position and maximized state are kept between sessions (#2595); eframe keeps a
// restored window on the monitors that are connected now.
persist_window: true,
@@ -390,14 +387,23 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
}
/// A refused launch profile ends with a native dialog on a desktop, and with the reason on standard
/// error everywhere else (a headless runner must never wait for a modal).
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// A refused launch profile ends with a native dialog where a modal renders without the app's run
/// loop (Windows, X11/Wayland), and with the reason on standard error everywhere else: a headless
/// runner must never wait for a modal, and on macOS one opened before the event loop never appears.
fn report_launch_profile_error(error: &str) {
eprintln!("CADCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("CADCraft launch profile: {error}");
return;
@@ -544,6 +550,9 @@ fn main() -> eframe::Result {
if stencil == 0 {
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
}
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
let persistence_path = vars
.portable_storage_file
.clone()
@@ -553,7 +562,7 @@ fn main() -> eframe::Result {
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
persistence_path: persistence_path.clone(),
..window_options(restores_window(persistence_path.as_deref()), stencil)
..window_options(restores_window(persistence_path.as_deref()), stencil, frame.as_ref())
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
@@ -576,22 +585,12 @@ fn main() -> eframe::Result {
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
// keeps the native Wayland backend.
#[cfg(all(unix, not(target_os = "macos")))]
if std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On {
if forced_x11 {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
// macOS: Quit CADCraft (Cmd+Q), the Dock's Quit and logout end the app through AppKit's
// terminate, which would skip the unsaved-changes prompt (#2157). winit turns each into a
// close request for the window instead, so it asks first, as the close button does.
#[cfg(target_os = "macos")]
{
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::macos::EventLoopBuilderExtMacOS;
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")]
@@ -604,6 +603,7 @@ fn main() -> eframe::Result {
os_window::name_for(os_window::identity()),
options,
Box::new(move |cc| {
cadcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11, frame.clone())?;
let mut app = CadApp::new(Session::empty(), services());
// The exit hook runs in `on_exit`: macOS ends the process inside AppKit's terminate after
// it, so nothing after `run_native` can be relied on there.
@@ -666,7 +666,7 @@ fn main() -> eframe::Result {
}
app.session.set_lisp_support_dir(Some(support));
}
app.integrated_titlebar = cfg!(target_os = "macos");
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
}
@@ -717,8 +717,6 @@ fn main() -> eframe::Result {
#[cfg(target_os = "macos")]
menus_in_window: vars.no_native_menu == Switch::On,
#[cfg(target_os = "macos")]
movable: None,
#[cfg(target_os = "macos")]
apple_events,
}))
}),
@@ -756,7 +754,7 @@ mod tests {
/// #1129: the first launch opens centred, not cascaded from the top-left corner.
#[test]
fn the_first_launch_opens_centred() {
let o = window_options(false, STENCIL_BITS);
let o = window_options(false, STENCIL_BITS, None);
assert!(o.centered, "centred on launch");
assert!(o.persist_window, "the window state is saved for the next launch");
}
@@ -764,7 +762,7 @@ mod tests {
/// #2595: a saved window state (size, position, maximized) is restored, not centred over.
#[test]
fn a_saved_window_reopens_where_it_was() {
let o = window_options(true, STENCIL_BITS);
let o = window_options(true, STENCIL_BITS, None);
assert!(!o.centered, "centring would move a restored window");
assert!(o.persist_window);
}
@@ -789,8 +787,8 @@ mod tests {
#[test]
fn the_window_carries_the_chosen_stencil_bits() {
for bits in [0, STENCIL_BITS] {
assert_eq!(window_options(false, bits).stencil_buffer, bits);
assert_eq!(window_options(true, bits).stencil_buffer, bits);
assert_eq!(window_options(false, bits, None).stencil_buffer, bits);
assert_eq!(window_options(true, bits, None).stencil_buffer, bits);
}
let format = |bits| eframe::egui_wgpu::depth_format_from_bits(0, bits);
assert_eq!(format(0), None, "no stencil: the canvas builds no clip pipelines");
@@ -844,3 +842,17 @@ mod tests {
assert_eq!(raw.system_theme, None);
}
}
#[cfg(test)]
mod refusal_dialog_tests {
use super::refusal_dialog;
use crate::build_flavor::BuildFlavor;
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
+10 -2
View File
@@ -15,6 +15,9 @@ pub struct NativeMenu {
items: HashMap<String, (String, String, MenuItem)>,
submenus: Vec<(String, Submenu)>,
predefined: Vec<(&'static str, PredefinedMenuItem)>,
/// Quit CADCraft: a close request of the main window, so unsaved drawings are asked about first.
/// muda's predefined Quit ends the process through `terminate:` without asking.
quit: MenuItem,
language: &'static str,
/// Monotonic time of the last enablement refresh. `NEG_INFINITY` makes the first poll refresh
/// immediately: `now_ms` starts near zero, so the old `0.0` sentinel suppressed the first
@@ -58,7 +61,6 @@ impl NativeMenu {
("Hide CADCraft", PredefinedMenuItem::hide(Some(i18n::tr(language, "Hide CADCraft")))),
("Hide Others", PredefinedMenuItem::hide_others(Some(i18n::tr(language, "Hide Others")))),
("Show All", PredefinedMenuItem::show_all(Some(i18n::tr(language, "Show All")))),
("Quit CADCraft", PredefinedMenuItem::quit(Some(i18n::tr(language, "Quit CADCraft")))),
];
// The Mac place for preferences: CADCraft ▸ Settings… (⌘,) opens the Options dialog.
let settings = MenuItem::with_id("cc-settings", i18n::tr(language, "Settings..."), true, accel("Cmd+Comma"));
@@ -69,6 +71,8 @@ impl NativeMenu {
let _ = app_menu.append(&PredefinedMenuItem::separator());
}
}
let quit = MenuItem::with_id(craft_quit::QUIT_MENU_ID, i18n::tr(language, "Quit CADCraft"), true, accel("Cmd+Q"));
let _ = app_menu.append(&quit);
items.insert("cc-about".into(), ("ui.dialog.about".into(), "About CADCraft".into(), about));
items.insert("cc-discord".into(), ("ui.discord".into(), "Join the ArtCraft Discord…".into(), discord));
items.insert("cc-settings".into(), ("options".into(), "Settings...".into(), settings));
@@ -85,6 +89,7 @@ impl NativeMenu {
items,
submenus,
predefined,
quit,
language,
last_refresh: f64::NEG_INFINITY,
recent: app.ui.recent_files.clone(),
@@ -114,7 +119,9 @@ impl NativeMenu {
/// Drain queued menu events into commands (Discord opens externally), rebuild Open Recent, retranslate on a language change and refresh enablement when 300 ms have elapsed.
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
while let Ok(ev) = self.events.try_recv() {
if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
if craft_quit::on_menu_event(ctx, ev.id.as_ref()) {
ctx.request_repaint();
} else if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
if cmd == "ui.discord" {
ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft"));
} else {
@@ -133,6 +140,7 @@ impl NativeMenu {
for (label, item) in &self.predefined {
item.set_text(i18n::tr(language, label));
}
self.quit.set_text(i18n::tr(language, "Quit CADCraft"));
for (label, submenu) in &self.submenus {
submenu.set_text(i18n::tr_menu(language, label));
}
+5 -5
View File
@@ -252,7 +252,7 @@ mod tests {
app.run("ui.dock", json!({"operation":"move", "panel":"layers", "target":"properties", "zone":"left"})).unwrap();
app.run("ui.dock", json!({"operation":"float", "panel":"properties", "rect":[120,90,340,410]})).unwrap();
ui.docking = app.ui.docking;
ui.docking.set_visible(Panel::ToolSets, false, None, permissions).unwrap();
ui.docking.set_visible(Panel::ToolSets, false, None, false, permissions).unwrap();
ui.show_toolsets = false;
store.save_if_changed(&ui, Instant::now()).unwrap();
let saved: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
@@ -263,9 +263,9 @@ mod tests {
assert_eq!(serde_json::to_value(&reloaded.docking).unwrap(), serde_json::to_value(&ui.docking).unwrap());
assert!(!reloaded.show_toolsets);
reveal_panel(&mut reloaded.docking, Panel::ToolSets).unwrap();
let tools = reloaded.docking.layout.location(&Panel::ToolSets).unwrap();
let tools = reloaded.docking.layout().location(&Panel::ToolSets).unwrap();
assert_eq!(serde_json::to_value(&tools.group).unwrap()["column"]["side"], json!("Start"), "{tools:?}");
assert_eq!(reloaded.docking.layout.floating[0].rect, [120.0, 90.0, 340.0, 410.0]);
assert_eq!(reloaded.docking.layout().floating[0].rect, egui::Rect::from_min_size(egui::pos2(120.0, 90.0), egui::vec2(340.0, 410.0)));
fs::remove_dir_all(directory).unwrap();
}
@@ -293,8 +293,8 @@ mod tests {
assert_eq!(ui.toolset_tab, "Modeling");
assert_eq!(ui.history_lines, 4);
assert!(!ui.show_toolsets && ui.show_palettes && !ui.show_toolbar);
assert_eq!(ui.docking.layout, default_workspace().layout);
assert!(ui.docking.hidden.is_empty(), "{:?}", ui.docking.hidden);
assert_eq!(ui.docking.layout(), default_workspace().layout());
assert!(ui.docking.hidden().is_empty(), "{:?}", ui.docking.hidden());
fs::remove_dir_all(directory).unwrap();
}
-3
View File
@@ -2,7 +2,4 @@ allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
]
cognitive-complexity-threshold = 30
+4 -3
View File
@@ -238,8 +238,9 @@ mod tests {
assert!(f.t.near(g.t, 1e-3), "{f:?} {g:?}");
assert!((f.k - g.k).abs() < 1e-2, "{f:?} {g:?}");
}
// An unclamped (periodic) spline has no ends.
let closed = GSpline::from_fit_points_closed(&[Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)]);
assert!(spline_end(&closed, false).is_none());
// An unclamped spline has no ends: one whose control points wrap round.
let fit = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)];
let closed = GSpline::fit_with(&fit, true, cadcraft_geom::FitOptions { knots: cadcraft_geom::KnotParam::Uniform, ..Default::default() });
assert!(closed.wraps() && spline_end(&closed, false).is_none());
}
}
+1 -1
View File
@@ -47,7 +47,7 @@ mod proxy;
mod text;
mod wipeout;
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, mtext_literal};
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
pub use common::{Common, Handle, Lineweight, RawTag, Transparency};
pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid};
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
+67
View File
@@ -1,3 +1,6 @@
use std::cmp::Ordering;
use std::collections::BTreeMap;
use super::common::{Common, Lineweight};
use super::text::{MText, Text};
use super::{Color, Deserialize, EntityKind, Mat3, Serialize, Vec2, Vec3};
@@ -142,6 +145,43 @@ impl AttribProps {
}
}
/// An attribute tag as attributes are matched to their definitions and to each other: ASCII
/// letters in either case are the same tag, other characters must be equal. As an ordered map key
/// it finds the match in a logarithmic number of comparisons, where comparing each attribute with
/// each definition costs their product on a block with many of both (#1923). It orders, rather
/// than hashes, so the cost doesn't depend on hash keys a crafted file could predict (the web
/// build's `RandomState`), as in the layer and block name index.
#[derive(Clone, Copy, Debug)]
pub struct TagKey<'a>(pub &'a str);
impl TagKey<'_> {
/// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case`
/// finds equal.
fn folded(&self) -> impl Iterator<Item = u8> + '_ {
self.0.bytes().map(|b| b.to_ascii_lowercase())
}
}
impl PartialEq for TagKey<'_> {
fn eq(&self, other: &Self) -> bool {
self.0.eq_ignore_ascii_case(other.0)
}
}
impl Eq for TagKey<'_> {}
impl Ord for TagKey<'_> {
fn cmp(&self, other: &Self) -> Ordering {
self.folded().cmp(other.folded())
}
}
impl PartialOrd for TagKey<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Insert {
@@ -204,4 +244,31 @@ impl Insert {
.then_before(Mat3::scale(self.scale.x, self.scale.y))
.then_before(Mat3::translate(-base))
}
/// The reference's attributes by tag: of several with one tag (in any ASCII case), the first.
/// Built once, it tells whether the reference carries a definition's tag, and its value, in
/// one lookup instead of a pass over the attributes per definition (#1923).
pub fn attribs_by_tag(&self) -> BTreeMap<TagKey<'_>, &Attrib> {
let mut by_tag = BTreeMap::new();
for a in &self.attribs {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(a);
}
by_tag
}
}
impl crate::Block {
/// The block's attribute definitions by tag: of several with one tag (in any ASCII case), the
/// first in the block's order, the one an attribute of that tag takes its properties from.
/// Built once for all of a reference's attributes, it matches each in one lookup instead of a
/// pass over the block per attribute (#1923).
pub fn attdefs_by_tag(&self) -> BTreeMap<TagKey<'_>, &crate::Entity> {
let mut by_tag = BTreeMap::new();
for e in self.entities.iter() {
if let EntityKind::AttDef(a) = &e.kind {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(e.as_ref());
}
}
by_tag
}
}
+20 -17
View File
@@ -1,10 +1,10 @@
//! Approximate entity bounds (used for extents, zoom and selection pre-filtering).
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};
use cadcraft_geom::{Arc, Bounds2, EPS, Polyline, Vec2, bulge_to_arc};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim, TagKey};
/// Nested block references deeper than this are ignored (cyclic or hostile files).
pub const MAX_BLOCK_DEPTH: usize = 16;
@@ -283,33 +283,33 @@ fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool {
}
/// The layer an insert's attribute draws on, as the renderer takes it: its own, else its
/// definition's (layer "0" being the insert's).
fn attrib_layer<'a>(d: &'a Drawing, ins: &crate::Insert, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| {
d.block(&ins.block)
.and_then(|blk| blk.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))))
.map_or("0", |be| be.common.layer.as_str())
})
/// definition's, from the block's definitions by tag `defs` (layer "0" being the insert's).
fn attrib_layer<'a>(defs: Option<&BTreeMap<TagKey<'a>, &'a Entity>>, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| defs.and_then(|defs| defs.get(&TagKey(&a.tag))).map_or("0", |be| be.common.layer.as_str()))
}
/// The bounds of a block's contents, in block coordinates: its geometry, which every reference to
/// the block shows, and the value of each constant attribute definition ATTMODE shows, by tag, which
/// only a block reference draws (a dimension's block does not), and only when the reference
/// carries no attribute of that tag. They are kept apart so that the one cache serves every
/// reference, whichever asks first.
/// reference, whichever asks first. Also the block's attribute definitions by tag, for the layer
/// of an attribute that has none of its own.
struct Contents<'a> {
geometry: Bounds2,
constants: Vec<(&'a str, Bounds2)>,
defs: BTreeMap<TagKey<'a>, &'a Entity>,
}
impl Contents<'_> {
/// What reference `ins` shows of the block: its geometry and the constant values `ins` has
/// no attribute for (that attribute is drawn instead, and counted with the attributes).
fn in_reference(&self, ins: &crate::Insert) -> Bounds2 {
self.constants
.iter()
.filter(|(tag, _)| !ins.attribs.iter().any(|r| r.tag.eq_ignore_ascii_case(tag)))
.fold(self.geometry, |b, (_, c)| b.union(c))
if self.constants.is_empty() {
return self.geometry;
}
// The reference's tags are gathered once, not scanned again for each constant (#1923).
let carried = ins.attribs_by_tag();
self.constants.iter().filter(|(tag, _)| !carried.contains_key(&TagKey(tag))).fold(self.geometry, |b, (_, c)| b.union(c))
}
}
@@ -323,7 +323,7 @@ fn contents<'a, 'm>(
) -> Option<&'m Contents<'a>> {
let key = (blk.name.as_str(), depth);
if !blocks.contains_key(&key) {
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new() };
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new(), defs: blk.attdefs_by_tag() };
// ATTMODE, as the renderer applies it to a constant value: 0 shows none, 1 the visible
// ones, 2 all of them.
let attmode = d.header.i64("ATTMODE", 1);
@@ -487,9 +487,12 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
// one draws nothing, so it contributes nothing: ZOOM Extents must not fly off to its
// insertion point. Attributes below still count.
let mut b = Bounds2::EMPTY;
let mut defs = None;
if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy());
let inner = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
let c = contents(d, blk, depth, blocks, off_counts);
defs = c.map(|c| &c.defs);
let inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
// XCLIP: the reference app takes the boundary's box, also where it reaches past the
// block or misses it (an inverted clip can show anything, so it keeps the block's).
@@ -511,7 +514,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
}
}
for a in &ins.attribs {
if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts) {
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts) {
b = b.union(&match a.multiline_text() {
Some(m) => mtext_box(&m),
None => text_box(&a.text, a.text.value.chars().count()),
+22 -14
View File
@@ -105,9 +105,12 @@ pub struct Drawing {
pub foreign: std::sync::Arc<foreign::Foreign>,
/// Layers in table order; [`Drawing::layer`] looks them up by name.
pub layers: NamedList<Layer>,
pub linetypes: Vec<Linetype>,
pub text_styles: Vec<TextStyle>,
pub dim_styles: Vec<DimStyle>,
/// Linetypes in table order; [`Drawing::linetype`] looks them up by name.
pub linetypes: NamedList<Linetype>,
/// Text styles in table order; [`Drawing::text_style`] looks them up by name.
pub text_styles: NamedList<TextStyle>,
/// Dimension styles in table order; [`Drawing::dim_style`] looks them up by name.
pub dim_styles: NamedList<DimStyle>,
pub mleader_styles: Vec<MLeaderStyle>,
pub table_styles: Vec<TableStyle>,
/// Multiline styles (MLSTYLE); STANDARD is always there.
@@ -117,7 +120,8 @@ pub struct Drawing {
pub model: EntityStore,
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
pub model_page: Option<PageSetup>,
pub layouts: Vec<Layout>,
/// Layouts in list order (`tab_order` orders the tabs); [`Drawing::layout`] looks them up by name.
pub layouts: NamedList<Layout>,
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
/// written active again. `None`, or a layout that no longer exists: the first by tab order.
pub active_layout: Option<String>,
@@ -204,16 +208,17 @@ impl Drawing {
Linetype { name: "ByBlock".into(), description: String::new(), pattern: Vec::new() },
Linetype { name: "ByLayer".into(), description: String::new(), pattern: Vec::new() },
Linetype::continuous(),
],
text_styles: vec![TextStyle::default()],
dim_styles: vec![DimStyle::default()],
]
.into(),
text_styles: vec![TextStyle::default()].into(),
dim_styles: vec![DimStyle::default()].into(),
mleader_styles: vec![MLeaderStyle::default()],
table_styles: vec![TableStyle::default()],
mline_styles: vec![MLineStyle::default()],
blocks: NamedMap::default(),
model: EntityStore::new(),
model_page: None,
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(),
active_layout: None,
views: Vec::new(),
vports: Vec::new(),
@@ -323,17 +328,19 @@ impl Drawing {
}
/// The first layer named `name`, without case, to change.
pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
let i = self.layers.position_by_name(name)?;
self.layers.get_mut(i)
self.layers.by_name_mut(name)
}
/// The first linetype named `name`, without case.
pub fn linetype(&self, name: &str) -> Option<&Linetype> {
self.linetypes.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.linetypes.by_name(name)
}
/// The first text style named `name`, without case.
pub fn text_style(&self, name: &str) -> Option<&TextStyle> {
self.text_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.text_styles.by_name(name)
}
/// The first dimension style named `name`, without case.
pub fn dim_style(&self, name: &str) -> Option<&DimStyle> {
self.dim_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.dim_styles.by_name(name)
}
/// The DIM* variables in the header that differ from the current dimension style, as
@@ -405,8 +412,9 @@ impl Drawing {
pub fn block(&self, name: &str) -> Option<&std::sync::Arc<Block>> {
self.blocks.by_name(name)
}
/// The first layout named `name`, without case.
pub fn layout(&self, name: &str) -> Option<&Layout> {
self.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(name))
self.layouts.by_name(name)
}
/// Add a layer if missing; returns whether it was created.
+86 -14
View File
@@ -1,10 +1,12 @@
//! The layer and block tables, whose names are looked up without case through an index instead of a
//! scan once a table is large and looked up often.
//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles
//! and layouts), whose names are looked up without case through an index instead of a scan once a
//! table is large and looked up often.
//!
//! [`Drawing::layer`](crate::Drawing::layer) and [`Drawing::block`](crate::Drawing::block) run for
//! every entity while a drawing is read, measured and drawn. Scanning the table on each made a file
//! of N layers, or of N blocks and N references to blocks it does not have, cost N² name
//! comparisons: tens of seconds to open at a few tens of thousands (#1924, F-04).
//! [`Drawing::layer`](crate::Drawing::layer), [`Drawing::block`](crate::Drawing::block) and the
//! other lookups by name run for every entity while a drawing is read, measured and drawn, and
//! every layout is looked up on each change. Scanning the table on each made a file of N layers,
//! or of N blocks, linetypes or styles and N objects naming ones it does not have, cost N² name
//! comparisons: tens of seconds to open or draw at a few tens of thousands (#1924, F-04).
//!
//! Each table keeps an index from a name with its ASCII letters lower-cased to the table's first
//! entry of that name, so a lookup returns what a scan in table order returns. The index is ordered
@@ -105,14 +107,21 @@ pub trait Named {
fn name(&self) -> &str;
}
impl Named for crate::Layer {
fn name(&self) -> &str {
&self.name
}
/// Entries named by their `name` field.
macro_rules! named_by_field {
($($t:ty),*) => {$(
impl Named for $t {
fn name(&self) -> &str {
&self.name
}
}
)*};
}
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::Layout);
/// A list of named entries in their own order (the drawing's layers). It reads and changes as a
/// `Vec`; [`NamedList::by_name`] finds the first entry of a name without case.
/// A list of named entries in their own order (the drawing's layers, linetypes, text styles,
/// dimension styles and layouts). It reads and changes as a `Vec`; [`NamedList::by_name`] finds the
/// first entry of a name without case.
pub struct NamedList<T> {
list: Vec<T>,
index: Lazy<usize>,
@@ -131,6 +140,12 @@ impl<T: Named> NamedList<T> {
pub fn by_name(&self, name: &str) -> Option<&T> {
self.position_by_name(name).and_then(|i| self.list.get(i))
}
/// The first entry named `name`, without case, to change (which drops the index).
pub fn by_name_mut(&mut self, name: &str) -> Option<&mut T> {
let i = self.position_by_name(name)?;
self.get_mut(i)
}
}
impl<T> Deref for NamedList<T> {
@@ -318,8 +333,8 @@ impl<'a, V> IntoIterator for &'a mut NamedMap<V> {
mod tests {
use std::sync::Arc;
use super::MIN_INDEXED;
use crate::{Block, Drawing, Layer};
use super::{MIN_INDEXED, Named, NamedList};
use crate::{Block, DimStyle, Drawing, Layer, Layout, Linetype, TextStyle};
/// Names to look up: each given name as it is, upper-cased, lower-cased and with a character
/// added (a miss).
@@ -331,6 +346,63 @@ mod tests {
d.layers.index.index.get().is_some()
}
fn indexed<T>(list: &NamedList<T>) -> bool {
list.index.index.get().is_some()
}
/// Every lookup through `find` finds what a scan of `list` in table order finds (the first of a
/// name without case), by pointer, for the list's names and `extra`.
fn check_list<'a, T: Named>(list: &'a NamedList<T>, find: impl Fn(&str) -> Option<&'a T>, extra: &[&str]) {
let names: Vec<String> = list.iter().map(|t| t.name().to_string()).collect();
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
let want = list.iter().find(|t| t.name().eq_ignore_ascii_case(&p)).map(std::ptr::from_ref);
assert_eq!(find(&p).map(std::ptr::from_ref), want, "{p}");
}
}
/// The linetype, text style, dimension style and layout lookups each find what a scan in table
/// order finds (the first of a name without case): while they scan, once the table is indexed,
/// and after `by_name_mut` (RENAME, STYLE, DIMSTYLE, a .lin file reloaded, a layout's UCS)
/// changed the first of a name and dropped the index.
#[test]
fn linetype_style_and_layout_lookups_find_the_first_of_a_name() {
let names: Vec<String> = (0..150).map(|i| format!("N{i}")).chain(["n7", "Dash", "DASH"].map(String::from)).collect();
let mut d = Drawing::new_imperial();
d.linetypes = names.iter().map(|n| Linetype::simple(n, "", &[0.5, -0.25])).collect();
d.text_styles = names.iter().map(|n| TextStyle { name: n.clone(), ..TextStyle::default() }).collect();
d.dim_styles = names.iter().map(|n| DimStyle { name: n.clone(), ..DimStyle::default() }).collect();
d.layouts = names.iter().zip(1..).map(|(n, tab)| Layout::new(n, tab)).collect();
let check = |d: &Drawing, extra: &[&str]| {
check_list(&d.linetypes, |n| d.linetype(n), extra);
check_list(&d.text_styles, |n| d.text_style(n), extra);
check_list(&d.dim_styles, |n| d.dim_style(n), extra);
check_list(&d.layouts, |n| d.layout(n), extra);
};
let all_indexed = |d: &Drawing| indexed(&d.linetypes) && indexed(&d.text_styles) && indexed(&d.dim_styles) && indexed(&d.layouts);
// The first round scans until the index is built; the second reads only the index.
check(&d, &["dash", "missing"]);
assert!(all_indexed(&d));
check(&d, &["dash", "missing"]);
// The first of a name changes, and the later one of that name is found after it.
d.linetypes.by_name_mut("n7").unwrap().name = "Seven".into();
d.text_styles.by_name_mut("n7").unwrap().name = "Seven".into();
d.dim_styles.by_name_mut("n7").unwrap().name = "Seven".into();
d.layouts.by_name_mut("n7").unwrap().name = "Seven".into();
assert!(!indexed(&d.linetypes) && !indexed(&d.text_styles) && !indexed(&d.dim_styles) && !indexed(&d.layouts));
assert_eq!(d.linetype("N7").map(|l| l.name.as_str()), Some("n7"));
assert_eq!(d.text_style("N7").map(|s| s.name.as_str()), Some("n7"));
assert_eq!(d.dim_style("N7").map(|s| s.name.as_str()), Some("n7"));
assert_eq!(d.layout("N7").map(|l| (l.name.as_str(), l.tab_order)), Some(("n7", 151)));
assert_eq!(d.linetypes.get(7).map(|l| l.name.as_str()), Some("Seven"));
check(&d, &["SEVEN", "n7"]);
assert!(all_indexed(&d));
// A miss changes nothing and keeps the index.
assert!(d.dim_styles.by_name_mut("none").is_none());
assert!(indexed(&d.dim_styles));
check(&d, &["dash"]);
}
fn blocks_indexed(d: &Drawing) -> bool {
d.blocks.index.index.get().is_some()
}
+136
View File
@@ -891,6 +891,85 @@ fn constant_values_count_in_extents_as_attmode_shows_them() {
assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one");
}
#[test]
fn an_attribute_lies_on_the_layer_of_the_first_definition_of_its_tag() {
// Two definitions of one tag, in different case, on a frozen layer and on layer 0: an
// attribute without a layer of its own (in a third case) lies on the first one's.
let top = |defs: [(&str, &str); 2]| {
let mut d = Drawing::new_imperial();
let mut frozen = Layer::new("AFRZ");
frozen.frozen = true;
d.layers.push(frozen);
let mut blk = Block::new("B");
blk.entities.push(on_layer("0", line((0.0, 0.0), (1.0, 1.0)), 1));
for (h, (layer, tag)) in (2..).zip(defs) {
blk.entities.push(on_layer(layer, EntityKind::AttDef(plain_attrib(tag)), h));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
let mut a = plain_attrib("Tag");
a.text.insert = Vec3::new(0.0, 500.0, 0.0);
ins.attribs.push(a);
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1.y
};
assert!(top([("AFRZ", "TAG"), ("0", "tag")]) < 100.0, "on the first definition's frozen layer");
assert!(top([("0", "tag"), ("AFRZ", "TAG")]) > 400.0, "on the first definition's layer 0");
}
#[test]
fn constant_definitions_of_one_tag_all_count_unless_the_reference_carries_the_tag() {
// Two constant definitions of one tag, in different case: a reference draws both values,
// unless it carries an attribute of that tag (in a third case), which stands for both.
let max = |attribs: Vec<Attrib>| {
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
for (h, tag, at) in [(2, "C", Vec3::new(0.0, 5000.0, 0.0)), (3, "c", Vec3::new(7000.0, 0.0, 0.0))] {
let mut a = plain_attrib(tag);
a.text.insert = at;
a.constant = true;
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = attribs;
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1
};
for shown in [max(vec![]), max(vec![plain_attrib("D")])] {
assert!(shown.x > 6000.0 && shown.y > 4000.0, "both values count: {shown:?}");
}
let carried = max(vec![plain_attrib("D"), plain_attrib("Cc"), plain_attrib("C")]);
assert!(carried.x < 100.0 && carried.y < 100.0, "neither value counts: {carried:?}");
}
#[test]
fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
// #1923: one reference with N attributes (none with a layer of its own) of a block with N
// constant definitions, the tags N long ones alike up to their last characters, no attribute's
// a definition's. Comparing each attribute with each definition, for its layer and for which
// constant values the reference carries, cost N x N comparisons of whole tags (many seconds
// here); one lookup per attribute or definition costs milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
for (h, i) in (2..).zip(0..N) {
let mut a = plain_attrib(&tag('D', i));
a.constant = true;
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect();
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert!(!d.extents(&Space::Model).is_empty());
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
/// blocks and N references to blocks it does not have, opened in N² name comparisons (#1924).
#[test]
@@ -909,3 +988,60 @@ fn layer_and_block_lookups_by_name_cost_about_the_same_for_any_table_size() {
}
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
}
/// Table entries for the cost tests below.
const NAMED: usize = 40_000;
/// A name of 54 bytes whose first 48 every such name of `kind` shares, so comparing two costs
/// about 50 bytes and not a length check, as in a crafted file.
fn long_name(kind: &str, tail: &str) -> String {
format!("{kind}{}{tail}", "x".repeat(48 - kind.len()))
}
/// The [`NAMED`] names `long_name(kind, "000000")`, `..."000001"`, ...
fn long_names(kind: &str) -> impl Iterator<Item = String> + '_ {
(0..NAMED).map(move |i| long_name(kind, &format!("{i:06}")))
}
/// Each of a table's [`NAMED`] names is looked up in other case (found) and as a missing name of
/// the same length, well within a bound that scanning the table for each lookup misses: a file of
/// N entries and N objects naming one it lacks, or names in other case, drew in N² name
/// comparisons (#1924).
fn lookups_by_name_are_quick(kind: &str, found: impl Fn(&str) -> bool) {
let started = std::time::Instant::now();
for i in 0..NAMED {
assert!(found(&long_name(kind, &format!("{i:06}")).to_ascii_uppercase()), "{kind} {i}");
assert!(!found(&long_name(kind, &format!("z{i:05}"))), "{kind} {i}");
}
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
}
#[test]
fn linetype_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.linetypes = long_names("LT").map(|n| Linetype::simple(&n, "", &[0.5, -0.25])).collect();
lookups_by_name_are_quick("LT", |n| d.linetype(n).is_some());
}
#[test]
fn text_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.text_styles = long_names("S").map(|name| TextStyle { name, ..TextStyle::default() }).collect();
lookups_by_name_are_quick("S", |n| d.text_style(n).is_some());
}
#[test]
fn dim_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.dim_styles = long_names("D").map(|name| DimStyle { name, ..DimStyle::default() }).collect();
lookups_by_name_are_quick("D", |n| d.dim_style(n).is_some());
}
/// Each change to a drawing looks up every layout of the drawing before it by name (the check for
/// non-finite results), so a drawing of N layouts cost N² name comparisons per command.
#[test]
fn layout_lookups_by_name_cost_about_the_same_for_any_table_size() {
let mut d = Drawing::new_imperial();
d.layouts = long_names("L").zip(1..).map(|(n, tab)| Layout::new(&n, tab)).collect();
lookups_by_name_are_quick("L", |n| d.layout(n).is_some());
}
+7 -1
View File
@@ -1,5 +1,5 @@
//! Dimensions and leaders: DIMLINEAR, DIMALIGNED, DIMRADIUS, DIMDIAMETER, DIMANGULAR, DIMARC,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, DIMOVERRIDE,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, QLEADER, DIMOVERRIDE,
//! DIMREASSOCIATE / DIMDISASSOCIATE, DIMTEDIT, DIMSPACE; DIMEDIT, DIMJOGGED, DIMJOGLINE,
//! DIMBREAK and DIMINSPECT in `annotate_dimedit.rs`.
@@ -19,6 +19,7 @@ mod edit;
mod leader;
mod linear;
mod mleader;
mod qleader;
mod radial;
use angular::{AngularM, ArcLenM, run_angular, run_arclen};
@@ -27,6 +28,7 @@ use common::{DimText, add_dim, assoc_enabled, circle_of, dim, pick_at};
use edit::{DimSpaceM, OverrideM, dims_of, run_dimspace, run_dimtedit, run_disassociate, run_override, run_reassociate, run_tedit, run_update};
use linear::{ChainM, LinearM, MAX_CHAIN, OrdinateM, run_aligned, run_baseline, run_continue, run_linear, run_ordinate};
use mleader::{MLeaderM, run_leader, run_mleader};
use qleader::{QLeaderM, run_qleader};
use radial::{RadialM, run_diameter, run_radius};
pub fn specs() -> Vec<CommandSpec> {
@@ -93,6 +95,10 @@ pub fn specs() -> Vec<CommandSpec> {
.alias(&["lead"])
.params("{points: [[x,y]...], text?}")
.interactive(|_| Ok(Box::new(leader::LeaderM::default()))),
CommandSpec::new("qleader", "Quick Leader", run_qleader)
.alias(&["le"])
.params("{points: [[x,y], [x,y], [x,y]?] (2 or 3), width?: text width (default 0), text?: lines split at \\n}")
.interactive(|_| Ok(Box::new(QLeaderM::default()))),
CommandSpec::new("dimstyle.update", "Update", run_update)
.menu(&["Dimension", "Update"])
.params("{handles?}")
+25 -3
View File
@@ -42,8 +42,13 @@ pub(super) struct LeaderM {
}
/// What follows the leader.
enum Annotation {
pub(super) enum Annotation {
Text(Vec<String>),
/// QLEADER's text: its lines and its width.
Quick {
lines: Vec<String>,
width: f64,
},
/// A copy of a text or multiline text: its contents, height, width and style.
Copy(MText),
None,
@@ -263,13 +268,13 @@ pub(super) fn json_leader(s: &mut Session, pts: &[Vec2], text: Option<&str>) ->
}
/// Draw the leader through `pts` and its annotation, as AutoCAD 2024 places them; their handles.
fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
let (Some(&end), Some(&before)) = (pts.last(), pts.len().checked_sub(2).and_then(|i| pts.get(i))) else { return Ok(Vec::new()) };
let z = sizes(s);
// The side the leader runs to: right unless its last segment runs left.
let dir = if end.x < before.x { -1.0 } else { 1.0 };
let mut vertices = pts.to_vec();
if let Annotation::Text(_) | Annotation::Copy(_) = ann {
if let Annotation::Text(_) | Annotation::Quick { .. } | Annotation::Copy(_) = ann {
let d = end - before;
// A copied text is centred on its line, and with DIMTAD on that line is above the leader:
// the leader ends half the text height lower.
@@ -310,6 +315,23 @@ fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Ann
columns: None,
}))?)
}
Annotation::Quick { lines, width } => {
// The middle of the first line level with the end on the right, of the last line on
// the left, whatever DIMTAD.
let (attach, lift) = if dir > 0.0 { (1, z.text / 2.0) } else { (9, -z.text / 2.0) };
Some(s.add_entity(EntityKind::MText(MText {
insert: v3(end + Vec2::new(dir * z.gap, lift)),
height: z.text,
width,
attach,
rotation: 0.0,
style: z.text_style,
contents: lines.join("\\P"),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
}))?)
}
Annotation::Copy(m) => {
let lift = if z.above { z.gap } else { 0.0 };
let attach = if dir > 0.0 { 4 } else { 6 };
+121
View File
@@ -0,0 +1,121 @@
//! QLEADER at the command line, as AutoCAD 2024 runs it with its default settings (accoreconsole,
//! synthetic drawings): up to three points, a text width, then lines of text.
//!
//! The leader is LEADER's, with an arrow and a hook line DIMASZ long when its last segment is more
//! than 15° off horizontal and text follows. The multiline text sits DIMGAP past the leader's end,
//! as wide as the width given: with the middle of its first line level with the end when the
//! leader runs right, and of its last line when it runs left, whatever DIMTAD. Enter at the first
//! line of text leaves the leader without text. The Settings dialog isn't available yet.
use serde_json::{Value, json};
use super::leader::{Annotation, add_leader};
use super::{Accept, Input, Interactive, Prompt, Result, Session, Step, Vec2, bad, points_param, str_param};
use crate::cmd::size_param;
/// QLEADER's default number of leader points.
const MAX_POINTS: usize = 3;
#[derive(Clone, Copy, Default, PartialEq)]
enum Ask {
#[default]
Points,
Width,
FirstLine,
NextLine,
}
#[derive(Default)]
pub(super) struct QLeaderM {
ask: Ask,
pts: Vec<Vec2>,
width: f64,
lines: Vec<String>,
}
impl Interactive for QLeaderM {
fn name(&self) -> &'static str {
"QLEADER"
}
fn prompt(&self, _s: &Session) -> Prompt {
let last = self.pts.last().copied();
match self.ask {
Ask::Points if self.pts.is_empty() => Prompt::new("Specify first leader point,", Accept::POINT).kw(&["Settings"]).default("Settings"),
Ask::Points => Prompt::new("Specify next point", Accept::POINT).base_opt(last),
// The width isn't remembered: AutoCAD 2024 offers 0 again after a width of 20.
Ask::Width => Prompt::new("Specify text width", Accept::POINT_OR_NUMBER).distance().default("0").base_opt(last),
Ask::FirstLine => Prompt::new("Enter first line of annotation text", Accept::TEXT).default("Mtext"),
Ask::NextLine => Prompt::new("Enter next line of annotation text", Accept::TEXT),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match self.ask {
Ask::Points => match i {
Input::Point(p) => {
self.pts.push(p);
if self.pts.len() == MAX_POINTS {
self.ask = Ask::Width;
}
}
Input::Enter | Input::Keyword(_) if self.pts.is_empty() => s.echo("The QLEADER Settings dialog is not available yet."),
// Enter after one point: no leader.
Input::Enter if self.pts.len() < 2 => return Ok(Step::Done),
Input::Enter => self.ask = Ask::Width,
_ => {}
},
Ask::Width => {
// A point gives the width as its distance from the leader's end; a negative
// width is none.
let width = match i {
Input::Point(p) => self.pts.last().map(|e| e.dist(p)),
Input::Text(t) => crate::units::parse_distance(&t),
Input::Enter => Some(0.0),
_ => return Ok(Step::Continue),
};
let finite = width.filter(|w| w.is_finite());
self.width = finite.ok_or_else(|| crate::EngineError::Other("Requires numeric distance or two points.".into()))?.max(0.0);
self.ask = Ask::FirstLine;
}
// Only typed text and Enter: a click in the drawing is no line of text, as at TEXT's.
Ask::FirstLine | Ask::NextLine => match i {
Input::Text(t) if !t.is_empty() => {
self.lines.push(t);
self.ask = Ask::NextLine;
}
Input::Text(_) | Input::Enter => {
let lines = std::mem::take(&mut self.lines);
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width: self.width } };
add_leader(s, &std::mem::take(&mut self.pts), false, true, ann)?;
return Ok(Step::Done);
}
_ => {}
},
}
Ok(Step::Continue)
}
}
/// QLEADER's JSON form: a leader through 2 or 3 `points`, with `text` (one line per line of it) as wide
/// as `width`, placed as the command line places them. The handles of the leader and its text.
pub(super) fn run_qleader(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("points").is_none_or(Value::is_null) {
return Err(bad("qleader", "`points` is required"));
}
let pts = points_param(p, "points").ok_or_else(|| bad("qleader", "`points` must be a list of [x, y] points"))?;
if !(2..=MAX_POINTS).contains(&pts.len()) {
return Err(bad("qleader", "`points` takes 2 or 3 points"));
}
let width = size_param("qleader", p, "width", true)?.unwrap_or(0.0);
if p.get("text").is_some_and(|t| !t.is_null() && !t.is_string()) {
return Err(bad("qleader", "`text` must be a string"));
}
// Empty lines at the end are dropped, as the command line ends at one: a left-running leader
// would otherwise sit level with a blank last line. Text with nothing left is no text.
let mut lines: Vec<String> = str_param(p, "text").map(|t| t.lines().map(str::to_string).collect()).unwrap_or_default();
while lines.last().is_some_and(String::is_empty) {
lines.pop();
}
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width } };
let hs = add_leader(s, &pts, false, true, ann)?;
Ok(json!({ "handles": hs.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
+7 -5
View File
@@ -386,16 +386,18 @@ fn fmt(v: f64) -> String {
format!("{v:.4}")
}
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores.
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores. A whole
/// number as typed: AutoCAD 2024 takes +3 and 03 at its array counts and refuses 5.0, 1e1, 8/2
/// and 3' (measured at ARRAYRECT's rows and columns, ARRAYPOLAR's items and rows, and -ARRAY).
fn count(i: &Input, cur: u64, max: u64) -> Result<Option<u64>> {
match i {
Input::Enter => Ok(Some(cur)),
Input::Text(t) => t
.trim()
.parse::<f64>()
.parse::<u64>()
.ok()
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= max as f64)
.map(|v| Some(v as u64))
.filter(|v| (1..=max).contains(v))
.map(Some)
.ok_or_else(|| other(format!("Requires an integer between 1 and {max} (MAXARRAY limits the size of the array)."))),
_ => Ok(None),
}
@@ -437,7 +439,7 @@ fn run_array(s: &mut Session, p: &Value) -> Result<Value> {
}
/// A count parameter (at least 1); a missing key gives the default, an invalid value is refused.
fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
pub(crate) fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
match p.get(key) {
None | Some(Value::Null) => Ok(default),
Some(v) => v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of at least 1"))),
+183 -60
View File
@@ -403,13 +403,14 @@ fn run_insert(s: &mut Session, p: &Value) -> Result<Value> {
/// MINSERT's JSON form: INSERT's parameters and the grid.
fn run_minsert(s: &mut Session, p: &Value) -> Result<Value> {
// A whole number, as the array commands' JSON counts are: 2.0 and 1e2 are refused too.
let count = |key: &str| -> Result<u32> {
match p.get(key) {
None | Some(Value::Null) => Ok(1),
Some(v) => v
.as_f64()
.filter(|n| n.fract() == 0.0 && *n >= 1.0 && *n <= f64::from(Grid::MAX))
.map(|n| n as u32)
.as_u64()
.and_then(|n| u32::try_from(n).ok())
.filter(|n| (1..=Grid::MAX).contains(n))
.ok_or_else(|| bad("minsert", format!("`{key}` must be an integer between 1 and {}", Grid::MAX))),
}
};
@@ -833,11 +834,35 @@ enum InsStage {
/// rows).
Cell(Vec2),
ColSpacing,
/// The second of two points a preset or the column spacing takes after a point (AutoCAD 2024
/// asks "Specify second point:"), from the first.
Second(TwoPoints, Vec2),
Attribs,
/// A Verify attribute asked again.
Verify,
}
/// What two points give: a preset scale factor (all axes, or one) or the column spacing by their
/// distance, the preset rotation by their direction.
#[derive(Clone, Copy, Debug, PartialEq)]
enum TwoPoints {
Scale,
Axis(usize),
Rotation,
ColSpacing,
}
// AutoCAD 2024's messages at INSERT's and MINSERT's scale, rotation and spacing prompts (measured):
// a scale factor of 0; anything else that isn't a number where two points give a distance or an
// angle, where a point gives the distance from the insertion point, and where only a number does.
const NONZERO: &str = "Value must be nonzero.";
/// Exploded INSERT's scale factor, which must be positive.
const POSITIVE: &str = "Value must be positive and nonzero.";
const TWO_POINTS: &str = "Requires numeric distance or two points.";
const ANGLE_TWO_POINTS: &str = "Requires valid numeric angle or two points.";
const SECOND_POINT: &str = "Requires numeric distance or second point.";
const NUMERIC: &str = "Requires numeric value.";
#[derive(Default)]
struct InsertM {
stage: InsStage,
@@ -1018,6 +1043,66 @@ impl InsertM {
}
Ok(d)
}
/// The Scale preset `f` for every axis.
fn preset_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
self.scale = Some(Vec2::new(f, f));
self.z_scale = Some(f.abs());
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
self.axes = [Some(f), Some(f), Some(f.abs())];
// Exploded insertion asks its one scale factor after the insertion point.
if self.at.is_some() {
return self.advance(s);
}
self.stage = InsStage::Point;
Ok(Step::Continue)
}
/// One axis preset: the others are 1, and no scale factors are asked after the point.
fn preset_axis(&mut self, ax: usize, f: f64) -> Result<Step> {
if let Some(a) = self.axes.get_mut(ax) {
*a = Some(f);
}
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
self.scale = Some(Vec2::new(x, y));
self.z_scale = Some(z.abs());
self.stage = InsStage::Point;
Ok(Step::Continue)
}
fn preset_rotation(&mut self, r: f64) -> Result<Step> {
self.rotation = Some(r);
self.stage = InsStage::Point;
Ok(Step::Continue)
}
/// The second of two points (AutoCAD 2024, measured): their distance is a preset scale factor
/// (0 refused) or the column spacing (0 taken), their direction the preset rotation. Enter
/// keeps a preset's default and is refused for the spacing, as anything else is; a refusal asks
/// the first prompt again.
fn second_point(&mut self, s: &mut Session, what: TwoPoints, a: Vec2, i: Input) -> Result<Step> {
let (first, refused) = match what {
TwoPoints::Scale => (InsStage::PresetScale, TWO_POINTS),
TwoPoints::Axis(ax) => (InsStage::PresetAxis(ax), TWO_POINTS),
TwoPoints::Rotation => (InsStage::PresetRotation, ANGLE_TWO_POINTS),
TwoPoints::ColSpacing => (InsStage::ColSpacing, TWO_POINTS),
};
self.stage = first;
match (what, i) {
(TwoPoints::ColSpacing, Input::Point(b)) => {
self.col_spacing = Some(a.dist(b));
self.advance(s)
}
(TwoPoints::Rotation, Input::Point(b)) => self.preset_rotation(a.angle_to(b)),
(TwoPoints::Rotation, Input::Enter) => self.preset_rotation(0.0),
(TwoPoints::Scale | TwoPoints::Axis(_), Input::Point(b)) if a.dist(b) == 0.0 => Err(EngineError::Other(NONZERO.into())),
(TwoPoints::Scale, Input::Point(b)) => self.preset_scale(s, a.dist(b)),
(TwoPoints::Scale, Input::Enter) => self.preset_scale(s, 1.0),
(TwoPoints::Axis(ax), Input::Point(b)) => self.preset_axis(ax, a.dist(b)),
(TwoPoints::Axis(ax), Input::Enter) => self.preset_axis(ax, 1.0),
_ => Err(EngineError::Other(refused.into())),
}
}
}
/// A distance typed at MINSERT's grid prompts: any finite number, negative or 0 too.
@@ -1025,8 +1110,14 @@ fn distance(t: &str) -> Result<f64> {
number(t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other("Requires a distance.".into()))
}
fn nonzero(t: &str) -> Result<f64> {
number(t).filter(|v| *v != 0.0).ok_or_else(|| EngineError::Other("Requires a non-zero number.".into()))
/// A scale factor typed at `t`: 0 gets AutoCAD 2024's "Value must be nonzero.", anything that
/// isn't a number the prompt's own message.
fn nonzero(t: &str, not_a_number: &str) -> Result<f64> {
let v = number(t).ok_or_else(|| EngineError::Other(not_a_number.into()))?;
if v == 0.0 {
return Err(EngineError::Other(NONZERO.into()));
}
Ok(v)
}
impl Interactive for InsertM {
@@ -1047,22 +1138,31 @@ impl Interactive for InsertM {
}
InsStage::Point => Prompt::new("Specify insertion point", Accept::POINT).kw(&["Basepoint", "Scale", "X", "Y", "Z", "Rotate"]),
InsStage::BasePoint => Prompt::new("Specify base point", Accept::POINT),
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
InsStage::PresetAxis(i) => Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::NUMBER).default("1"),
// Exploded, after the insertion point, it takes a number only.
InsStage::PresetScale if self.at.is_some() => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"),
InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::POINT_OR_NUMBER).default("1"),
InsStage::PresetAxis(i) => {
Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::POINT_OR_NUMBER).default("1")
}
// Typed text is read as before (`<<45` the angle, not an override for a point); a point
// still comes from a click or LISP.
InsStage::PresetRotation => Prompt::new("Specify rotation angle", Accept::NUMBER).default("0"),
// Text is read here, not taken as a distance along the rubber band: the core console
// refuses 5 at this prompt (measured).
InsStage::Second(_, a) => Prompt::new("Specify second point", Accept::POINT_OR_NUMBER).base(a),
InsStage::XScale if self.xyz => Prompt::new("Specify X scale factor", Accept::POINT_OR_NUMBER).kw(&["Corner"]).default("1").base(at),
InsStage::XScale => {
Prompt::new("Enter X scale factor, specify opposite corner", Accept::POINT_OR_NUMBER).kw(&["Corner", "XYZ"]).default("1").base(at)
}
InsStage::Corner => Prompt::new("Specify opposite corner", Accept::POINT).base(at),
InsStage::YScale => Prompt::new("Enter Y scale factor", Accept::NUMBER).default("use X scale factor"),
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::NUMBER).default("use X scale factor"),
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::POINT_OR_NUMBER).default("use X scale factor").base(at),
InsStage::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER).default("0").base(at),
InsStage::Rows => Prompt::new("Enter number of rows (---)", Accept::NUMBER).default("1"),
InsStage::Cols => Prompt::new("Enter number of columns (|||)", Accept::NUMBER).default("1"),
InsStage::RowSpacing => Prompt::new("Enter distance between rows or specify unit cell (---)", Accept::POINT_OR_NUMBER),
InsStage::Cell(a) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::NUMBER),
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::POINT_OR_NUMBER),
InsStage::Attribs => {
let (_, prompt, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
let p = Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT);
@@ -1138,45 +1238,58 @@ impl Interactive for InsertM {
self.stage = InsStage::Point;
}
}
InsStage::PresetScale => {
let f = match i {
Input::Text(t) => nonzero(&t)?,
Input::Enter => 1.0,
_ => return Ok(Step::Continue),
// Exploded, after the insertion point: a positive number only (AutoCAD 2024 refuses a
// point and x with "Requires numeric value.", 0 and -2 with "Value must be positive and
// nonzero.", measured).
InsStage::PresetScale if self.at.is_some() => {
return match i {
Input::Text(t) => {
let f = number(&t).ok_or_else(|| EngineError::Other(NUMERIC.into()))?;
let f = Some(f).filter(|f| *f > 0.0).ok_or_else(|| EngineError::Other(POSITIVE.into()))?;
self.preset_scale(s, f)
}
Input::Enter => self.preset_scale(s, 1.0),
_ => Err(EngineError::Other(NUMERIC.into())),
};
self.scale = Some(Vec2::new(f, f));
self.z_scale = Some(f.abs());
// An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3).
self.axes = [Some(f), Some(f), Some(f.abs())];
// Exploded insertion asks its one scale factor after the insertion point.
if self.at.is_some() {
return self.advance(s);
}
self.stage = InsStage::Point;
}
// One axis preset: the others are 1, and no scale factors are asked after the point.
// A point at a preset is the first of two (AutoCAD 2024, measured).
InsStage::PresetScale => {
return match i {
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::Scale, p);
Ok(Step::Continue)
}
Input::Text(t) => self.preset_scale(s, nonzero(&t, TWO_POINTS)?),
Input::Enter => self.preset_scale(s, 1.0),
_ => Err(EngineError::Other(TWO_POINTS.into())),
};
}
InsStage::PresetAxis(ax) => {
let f = match i {
Input::Text(t) => nonzero(&t)?,
Input::Enter => 1.0,
_ => return Ok(Step::Continue),
return match i {
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::Axis(ax), p);
Ok(Step::Continue)
}
Input::Text(t) => self.preset_axis(ax, nonzero(&t, TWO_POINTS)?),
Input::Enter => self.preset_axis(ax, 1.0),
_ => Err(EngineError::Other(TWO_POINTS.into())),
};
if let Some(a) = self.axes.get_mut(ax) {
*a = Some(f);
}
let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0));
self.scale = Some(Vec2::new(x, y));
self.z_scale = Some(z.abs());
self.stage = InsStage::Point;
}
InsStage::PresetRotation => {
self.rotation = Some(match i {
Input::Text(t) => s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?,
Input::Enter => 0.0,
_ => return Ok(Step::Continue),
});
self.stage = InsStage::Point;
return match i {
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::Rotation, p);
Ok(Step::Continue)
}
Input::Text(t) => {
let r = s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other(ANGLE_TWO_POINTS.into()))?;
self.preset_rotation(r)
}
Input::Enter => self.preset_rotation(0.0),
_ => Err(EngineError::Other(ANGLE_TWO_POINTS.into())),
};
}
InsStage::Second(what, a) => return self.second_point(s, what, a, i),
InsStage::XScale => match i {
Input::Keyword(k) if k == "Corner" => self.stage = InsStage::Corner,
Input::Keyword(k) if k == "XYZ" => self.xyz = true,
@@ -1185,7 +1298,7 @@ impl Interactive for InsertM {
return self.corner_scale(s, sc);
}
Input::Text(t) => {
self.x_scale = Some(nonzero(&t)?);
self.x_scale = Some(nonzero(&t, "Requires a non-zero number.")?);
self.stage = InsStage::YScale;
}
Input::Enter => {
@@ -1202,10 +1315,11 @@ impl Interactive for InsertM {
}
InsStage::YScale => {
let x = self.x_scale.unwrap_or(1.0);
// A number only: AutoCAD 2024 refuses a point here (measured).
let y = match i {
Input::Text(t) => nonzero(&t)?,
Input::Text(t) => nonzero(&t, NUMERIC)?,
Input::Enter => x,
_ => return Ok(Step::Continue),
_ => return Err(EngineError::Other(NUMERIC.into())),
};
self.scale = Some(Vec2::new(x, y));
if self.xyz {
@@ -1214,11 +1328,15 @@ impl Interactive for InsertM {
}
return self.advance(s);
}
// A point gives its distance from the insertion point (AutoCAD 2024, measured).
InsStage::ZScale => {
self.z_scale = Some(match i {
Input::Text(t) => nonzero(&t)?,
Input::Text(t) => nonzero(&t, SECOND_POINT)?,
Input::Enter => self.x_scale.unwrap_or(1.0).abs(),
_ => return Ok(Step::Continue),
Input::Point(p) => {
Some(self.at.unwrap_or_default().dist(p)).filter(|d| *d != 0.0).ok_or_else(|| EngineError::Other(NONZERO.into()))?
}
_ => return Err(EngineError::Other(SECOND_POINT.into())),
});
return self.advance(s);
}
@@ -1232,17 +1350,14 @@ impl Interactive for InsertM {
return self.advance(s);
}
InsStage::Rows | InsStage::Cols => {
// A whole number as typed: AutoCAD 2024 takes +3 and 03 here and refuses 5.0, 5.,
// 1e1, 8/2, 3', 4.5 and a point (measured at the rows, and 5.0 and +3 at the columns).
let n = match i {
Input::Text(t) => t
.trim()
.parse::<f64>()
.ok()
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= f64::from(Grid::MAX))
.map(|v| v as u32)
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?,
Input::Enter => 1,
_ => return Ok(Step::Continue),
};
Input::Text(t) => t.trim().parse::<u32>().ok().filter(|v| (1..=Grid::MAX).contains(v)),
Input::Enter => Some(1),
_ => None,
}
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?;
if self.stage == InsStage::Rows {
self.rows = Some(n);
} else {
@@ -1264,11 +1379,19 @@ impl Interactive for InsertM {
return self.advance(s);
}
}
// A distance, or two points (AutoCAD 2024, measured): Enter is refused too.
InsStage::ColSpacing => {
if let Input::Text(t) = i {
self.col_spacing = Some(distance(&t)?);
return self.advance(s);
}
return match i {
Input::Text(t) => {
self.col_spacing = Some(number(&t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other(TWO_POINTS.into()))?);
self.advance(s)
}
Input::Point(p) => {
self.stage = InsStage::Second(TwoPoints::ColSpacing, p);
Ok(Step::Continue)
}
_ => Err(EngineError::Other(TWO_POINTS.into())),
};
}
InsStage::Attribs => {
let (tag, _, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
+4 -7
View File
@@ -3,7 +3,7 @@
use std::sync::Arc;
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert};
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert, TagKey};
use serde_json::{Value, json};
use crate::cmd::curves::KW;
@@ -102,17 +102,14 @@ impl Interactive for AttdispM {
/// Properties set on single attributes (layer, colour, …) go back to the definitions', as in AutoCAD.
pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec<Attrib> {
let m = ins.transform(blk.base.xy());
// The reference's attributes by tag, gathered once for all the definitions (#1923).
let carried = ins.attribs_by_tag();
defs.iter()
.map(|ad| {
let mut k = EntityKind::Text(ad.text.clone());
k.transform(&m);
let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() };
t.value = ins
.attribs
.iter()
.find(|a| a.tag.eq_ignore_ascii_case(&ad.tag))
.map(|a| a.text.value.clone())
.unwrap_or_else(|| ad.text.value.clone());
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
Attrib {
tag: ad.tag.clone(),
text: t,
+8 -8
View File
@@ -2,7 +2,7 @@
//! become text with the values they show instead of the block's attribute definitions.
use cadcraft_color::Color;
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Insert};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, TagKey};
use serde_json::{Value, json};
use crate::cmd::machines::SelectRun;
@@ -28,22 +28,22 @@ fn run_burst(s: &mut Session, p: &Value) -> Result<Value> {
fn burst_pieces(d: &Drawing, e: &Entity) -> Option<Vec<Entity>> {
let EntityKind::Insert(ins) = &e.kind else { return None };
let mut out: Vec<Entity> = explode_kind(d, e)?.into_iter().filter(|p| !matches!(p.kind, EntityKind::AttDef(_))).collect();
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = d.block(&ins.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
for a in ins.attribs.iter().filter(|a| !a.invisible) {
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
None => EntityKind::Text(a.text.clone()),
};
out.push(Entity { handle: Handle(0), common: attrib_common(d, e, ins, &a.tag, &a.props), kind });
out.push(Entity { handle: Handle(0), common: attrib_common(e, defs.get(&TagKey(&a.tag)).copied(), &a.props), kind });
}
Some(out)
}
/// The properties an attribute is drawn with: its own, else its definition's; layer 0 is the
/// reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the block's
/// objects.
fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, tag: &str, props: &cadcraft_doc::AttribProps) -> Common {
let def =
d.block(&ins.block).and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag))));
/// The properties an attribute is drawn with: its own, else those of its definition `def`; layer
/// 0 is the reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the
/// block's objects.
fn attrib_common(e: &Entity, def: Option<&Entity>, props: &cadcraft_doc::AttribProps) -> Common {
// An attribute without a definition follows the reference.
let base = def.map(|de| de.common.clone()).unwrap_or_else(|| Common { color: Color::ByBlock, ..Common::default() });
let mut c = props.over(&base);
+52 -5
View File
@@ -5,7 +5,7 @@
use cadcraft_doc::color::Color;
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, Transparency};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, TagKey, Transparency};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
@@ -111,11 +111,10 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
.collect();
// An attribute draws with its definition's properties, except those set on it.
let by_block = Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..r.clone() };
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = b.attdefs_by_tag();
out.extend(ins.attribs.iter().filter(|a| !a.invisible).map(|a| {
let def = b.entities.iter().find_map(|e| match &e.kind {
EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag) => Some(&e.common),
_ => None,
});
let def = defs.get(&TagKey(&a.tag)).map(|e| &e.common);
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
@@ -248,3 +247,51 @@ impl Session {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn many_attributes_are_previewed_without_comparing_every_pair_with_the_definitions() {
// #1923: a reference with N attributes of a block with N definitions, the tags N long ones
// alike up to their last characters, no attribute's a definition's. Looking for each
// attribute's definition by comparing it with every one cost N x N comparisons of whole
// tags for each preview (many seconds here); the definitions gathered by tag once cost
// milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let attrib = |tag: String| cadcraft_doc::Attrib {
tag,
text: cadcraft_doc::Text {
insert: cadcraft_geom::Vec3::ZERO,
align_pt: None,
height: 1.0,
value: "v".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
},
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
let mut d = Drawing::new_metric();
let mut blk = cadcraft_doc::Block::new("B");
for (h, i) in (1..).zip(0..N) {
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(attrib(tag('D', i)))));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let ins = cadcraft_doc::Insert { block: "B".into(), attribs: (0..N).map(|i| attrib(tag('A', i))).collect(), ..Default::default() };
let h = d.add(&cadcraft_doc::Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert_eq!(drawn(&d, h).len(), N);
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
}
+24 -15
View File
@@ -8,7 +8,9 @@ use cadcraft_geom::{Mat3, Vec2, Vec3};
use serde_json::{Value, json};
use super::super::curves::KW;
use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder};
use super::super::file::{
Version, drops_unknown, dwg_notes, lost_message, lost_writing, new_folder, own_version, report_dwg_notes, report_lost, report_new_folder,
};
use super::super::machines::{SelOutcome, SelectPhase};
use super::super::modify::erase_kept;
use super::super::{CommandSpec, bad, point_param, str_param, targets};
@@ -46,7 +48,7 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string();
let base = point_param(p, "base");
let folder = new_folder(&path);
let (entities, bytes, lost, version) = match str_param(p, "name") {
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
Some("*") => write(s, "wblock", &path, Source::Whole)?,
Some(name) => write(s, "wblock", &path, Source::Block(name, base))?,
None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?,
@@ -54,6 +56,7 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
report_new_folder(s, &mut r, folder);
report_lost(s, &mut r, &path, version, &lost);
report_dwg_notes(s, &mut r, notes);
Ok(r)
}
@@ -64,7 +67,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string();
let base = point_param(p, "base");
let folder = new_folder(&path);
let (entities, bytes, lost, version) = match str_param(p, "name") {
let (entities, bytes, lost, version, notes) = match str_param(p, "name") {
Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?,
None => {
let hs = targets(s, p)?;
@@ -80,16 +83,17 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
report_new_folder(s, &mut r, folder);
report_lost(s, &mut r, &path, version, &lost);
report_dwg_notes(s, &mut r, notes);
Ok(r)
}
/// Write `what` to `path` through the io hooks; the objects written, the file's size, what the
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams) and
/// the version it was written at, for the caller to report as a save does. The
/// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units
/// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and
/// scaled on insert, and its defaults (text size, current styles, annotation scales).
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version)> {
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams), the
/// version it was written at and what a DWG keeps only in part, for the caller to report as a
/// save does. The written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK
/// does: its units ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in
/// inches and scaled on insert, and its defaults (text size, current styles, annotation scales).
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version, Vec<String>)> {
let src = s.doc()?;
// The base point becomes the written drawing's origin: by default 0,0 for objects and the
// block's base point for a block.
@@ -115,14 +119,19 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi
// The written drawing's own version: the writer is given no other.
let version = own_version(&d, path);
let lost = lost_writing(&d, path, version);
Ok((d.model.len(), bytes.len(), lost, version))
let notes = if drops_unknown(path) { dwg_notes(&d) } else { Vec::new() };
Ok((d.model.len(), bytes.len(), lost, version, notes))
}
/// Say on the command line what the file written at `path` and `version` left out.
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>) {
/// Say on the command line what the file written at `path` and `version` left out, and what a
/// DWG keeps only in part (`notes`).
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>, notes: Vec<String>) {
if let Some(msg) = lost_message(path, version, lost) {
s.echo(msg);
}
for note in notes {
s.echo(note);
}
}
/// A new drawing of `ents`, with `src`'s settings and the layers, linetypes, styles and blocks
@@ -341,7 +350,7 @@ impl DashWblockM {
fn write(&self, s: &mut Session, what: Source) -> Result<Step> {
match write(s, "-wblock", &self.path, what) {
Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost),
Ok((.., lost, version, notes)) => echo_not_saved(s, &self.path, version, &lost, notes),
Err(e) => s.echo(e.to_string()),
}
Ok(Step::Done)
@@ -352,8 +361,8 @@ impl DashWblockM {
return Ok(Step::Done);
}
match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) {
Ok((.., lost, version)) => {
echo_not_saved(s, &self.path, version, &lost);
Ok((.., lost, version, notes)) => {
echo_not_saved(s, &self.path, version, &lost, notes);
erase(s, hs)?;
}
Err(e) => s.echo(e.to_string()),
+3 -3
View File
@@ -266,9 +266,9 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing {
let mut d = Drawing::new_imperial();
d.header = src.header.clone();
d.layers = pick(&src.layers, &used.layers, |l| &l.name).into();
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name);
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name);
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name);
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name).into();
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name).into();
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name).into();
d.mleader_styles = pick(&src.mleader_styles, &used.mleader_styles, |t| &t.name);
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name);
d.blocks = src.blocks.iter().filter(|(k, _)| used.blocks.contains(&up(k))).map(|(k, b)| (k.clone(), b.clone())).collect();
+1 -1
View File
@@ -129,7 +129,7 @@ fn save(s: &mut Session, name: &str, annotative: Option<bool>, replace: bool) ->
if let Some(a) = annotative {
st.annotative = a;
}
let name = match d.dim_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
let name = match d.dim_styles.by_name_mut(&name) {
Some(existing) if replace => {
let kept = existing.name.clone();
*existing = DimStyle { name: kept.clone(), ..st };
+2 -2
View File
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("pline", "Polyline", run_pline)
.menu(&["Draw", "Polyline"])
.alias(&["pl"])
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width?}")
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width? (default PLINEWID unless vertices give widths)}")
.interactive(|_| Ok(Box::new(PlineM::default()))),
CommandSpec::new("circle", "Circle", run_circle)
.menu(&["Draw", "Circle", "Center, Radius"])
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("rectang", "Rectangle", super::draw2::run_rectang2)
.menu(&["Draw", "Rectangle"])
.alias(&["rec", "rectangle"])
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth, rotation? (deg), fillet?, chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
.params("{p1, p2 | dimensions: [l, w] (p2 picks the quadrant) | area + length|breadth (the outline encloses it, cut corners included), rotation? (deg), fillet? (wins over a chamfer), chamfer?: [d1, d2], width?, elevation?, thickness?, center?: bool (p1 is the centre, not a corner; the size spans it evenly)}")
.interactive(|_| Ok(Box::new(super::draw2::RectM2::default()))),
CommandSpec::new("polygon", "Polygon", run_polygon)
.menu(&["Draw", "Polygon"])
+21 -3
View File
@@ -45,15 +45,21 @@ fn current_elevation(s: &Session) -> Result<f64> {
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);
let mut vertex_widths = false;
for v in raw.into_iter().flatten() {
size_param("pline", v, "startWidth", true)?;
size_param("pline", v, "endWidth", true)?;
vertex_widths |= size_param("pline", v, "startWidth", true)?.is_some() | size_param("pline", v, "endWidth", true)?.is_some();
}
let vs: Vec<PolyVertex> = raw.map(|a| a.iter().filter_map(vertex_value).collect()).unwrap_or_default();
if vs.len() < 2 {
return Err(bad("pline", "`vertices` needs at least 2 points"));
}
let width = size_param("pline", p, "width", true)?.unwrap_or(0.0);
// Without a width, the polyline starts at PLINEWID as the command does (unless its vertices
// give their own widths).
let width = match size_param("pline", p, "width", true)? {
Some(w) => w,
None if vertex_widths => 0.0,
None => Some(s.doc()?.header.f64("PLINEWID", 0.0)).filter(|w| w.is_finite() && *w > 0.0).unwrap_or(0.0),
};
let mut k = lwpoly(vs, bool_or(p, "closed", false));
if let EntityKind::LwPolyline(pl) = &mut k {
pl.const_width = width;
@@ -266,8 +272,11 @@ impl Interactive for PlineM {
fn name(&self) -> &'static str {
"PLINE"
}
/// Segments start at PLINEWID, the width the last Width or Halfwidth answer left.
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.elevation = current_elevation(s)?;
let w = s.doc()?.header.f64("PLINEWID", 0.0);
(self.start_w, self.end_w) = if w.is_finite() && w > 0.0 { (w, w) } else { (0.0, 0.0) };
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
@@ -316,6 +325,11 @@ impl Interactive for PlineM {
self.end_w = self.start_w;
}
self.asking_width = if self.asking_width == 1 { 2 } else { 0 };
if self.asking_width == 0 {
// The ending width becomes PLINEWID, the next polyline's width (AutoCAD:
// Halfwidth 0.5 0.5 leaves PLINEWID 1).
s.doc_mut()?.header.set_f64("PLINEWID", self.end_w);
}
return Ok(Step::Continue);
}
if let (Some(a), Some(st)) = (self.ask, self.verts.last().map(|v| v.p)) {
@@ -379,6 +393,10 @@ impl Interactive for PlineM {
l.bulge = 0.0;
(l.start_width, l.end_width) = (0.0, 0.0);
}
// Back to the mode of the segment now last (AutoCAD: `_A` point `_U` returns
// to "Specify next point", where `_L` is Length, not arc mode's Line).
let n = self.verts.len();
self.arc_mode = n >= 2 && self.verts.get(n - 2).is_some_and(|v| v.bulge != 0.0);
self.sync(s, false)?;
Ok(Step::Continue)
}
+7 -1
View File
@@ -125,7 +125,11 @@ impl Interactive for SplineM {
}
match i {
Input::Point(p) => {
self.pts.push(p);
// The same point again is not a further fit point (AutoCAD 2024 leaves it out),
// nor a kink.
if self.pts.last() != Some(&p) {
self.pts.push(p);
}
Ok(Step::Continue)
}
Input::Keyword(k) if k == "Undo" => {
@@ -175,6 +179,8 @@ impl Interactive for SplineM {
}
Some(crate::cmd::spline_opts::SplineAsk::EndTangent) => opts.end_tangent = self.pts.last().map(|l| c - *l).filter(|d| d.len() > 1e-12),
Some(_) => {}
// The cursor on the last point adds nothing, as a click there doesn't.
None if pts.last() == Some(&c) => {}
None => pts.push(c),
}
if pts.len() < 2 {
+1 -1
View File
@@ -7,7 +7,7 @@ use cadcraft_geom::{Arc, Circle, Ellipse, Line, PolyVertex, Polyline, Spline, TA
use serde_json::{Value, json};
use super::curves::{self, Chain, MAX_GEN, TanObj};
use super::helpers::{arc, circle, line, lwpoly, rect_vertices, rect_with_corners, v3};
use super::helpers::{arc, circle, line, lwpoly, rect_corners_fit, rect_vertices, rect_with_corners, v3};
use super::machines::number;
use super::{CommandSpec, bad, bool_or, f64_or, f64_req, point_param, point_req, point_value, points_param, size_param, str_param, targets};
+33 -14
View File
@@ -139,6 +139,15 @@ impl DivideM {
pub(super) fn new(measure: bool) -> Self {
DivideM { measure, obj: None, phase: DivPhase::Object, block: None, align: true }
}
/// The JSON form's parameters for the picked object, before the count or length.
fn params(&self, h: Handle, pick: Vec2) -> Value {
let mut params = json!({ "handle": h.hex(), "align": self.align, "from": [pick.x, pick.y] });
if let Some(b) = &self.block {
params["block"] = json!(b);
}
params
}
}
impl Interactive for DivideM {
@@ -187,27 +196,37 @@ impl Interactive for DivideM {
self.phase = DivPhase::Value;
Ok(Step::Continue)
}
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) => {
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) if self.measure => {
let Some((h, pick)) = self.obj else { return Ok(Step::Cancel) };
let v = match inp {
Input::Text(t) => number(&t).ok_or_else(|| other("Requires a number."))?,
Input::Point(q) => pick.dist(q),
_ => return Ok(Step::Continue),
};
let mut params = json!({ "handle": h.hex(), "align": self.align, "from": [pick.x, pick.y] });
if let Some(b) = &self.block {
params["block"] = json!(b);
}
if self.measure {
params["length"] = json!(v);
run_measure(s, &params)?;
} else {
if !(2.0..=32767.0).contains(&v) || v.fract() != 0.0 {
return Err(other("Requires an integer between 2 and 32767."));
}
params["segments"] = json!(v as u64);
run_divide(s, &params)?;
let mut params = self.params(h, pick);
params["length"] = json!(v);
run_measure(s, &params)?;
Ok(Step::Done)
}
(DivPhase::Value, inp) if !self.measure => {
// A whole number as typed: AutoCAD 2024 takes +5 and 05 here and refuses 5.0, 5.,
// 1e1, 4.5, 1, 32768, x, Enter and a point, naming the Block keyword while the
// prompt still offers it (measured).
let n = match inp {
Input::Text(t) => t.trim().parse::<u64>().ok().filter(|n| (2..=32767).contains(n)),
_ => None,
}
.ok_or_else(|| {
other(if self.block.is_some() {
"Requires an integer between 2 and 32767."
} else {
"Requires an integer between 2 and 32767, or option keyword."
})
})?;
let Some((h, pick)) = self.obj else { return Ok(Step::Cancel) };
let mut params = self.params(h, pick);
params["segments"] = json!(n);
run_divide(s, &params)?;
Ok(Step::Done)
}
(_, Input::Enter) => Ok(Step::Cancel),
+42 -16
View File
@@ -1,6 +1,6 @@
use super::{
Accept, EntityKind, Input, Interactive, PolyVertex, Prompt, Result, Session, Step, Value, Vec2, added, bad, bool_or, curves, f64_or, lwpoly,
number, other, point_param, point_req, rect_with_corners, size_param,
number, other, point_param, point_req, rect_corners_fit, rect_with_corners, size_param,
};
use crate::last_used::RectangModes;
@@ -19,9 +19,30 @@ fn rect_kind(first: Vec2, (w, h): (f64, f64), rot: f64, fillet: f64, chamfer: (f
k
}
/// The area a fillet's or chamfer's four corners take off the full rectangle (a fillet wins).
fn corner_area(fillet: f64, chamfer: (f64, f64)) -> f64 {
if fillet > 0.0 {
(4.0 - std::f64::consts::PI) * fillet * fillet
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 {
2.0 * chamfer.0 * chamfer.1
} else {
0.0
}
}
/// The sides of the rectangle of `area` with one side `side`, its length (or with `breadth`,
/// its width). AutoCAD sizes it so that the outline, corners cut, encloses the area: the corners'
/// area is added back. When the corners then don't fit they stay square, and the area is the full
/// rectangle's.
fn area_sides(area: f64, side: f64, breadth: bool, fillet: f64, chamfer: (f64, f64)) -> (f64, f64) {
let sides = |a: f64| if breadth { (a / side, side) } else { (side, a / side) };
let (w, h) = sides(area + corner_area(fillet, chamfer));
if rect_corners_fit(Vec2::new(w, h), fillet, chamfer) { (w, h) } else { sides(area) }
}
/// The width and height of a rectangle from its `dimensions`, its `p2` corner, its `area` with
/// `length` or `breadth`, or its second corner `p2`, rotated by `rot` about `a`.
fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool) -> Result<(f64, f64)> {
fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool, fillet: f64, chamfer: (f64, f64)) -> Result<(f64, f64)> {
Ok(if let Some(d) = p.get("dimensions").and_then(Value::as_array) {
let l = d.first().and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("rectang", "dimensions: [length, width]"))?;
let wd = d.get(1).and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad("rectang", "dimensions: [length, width]"))?;
@@ -38,8 +59,8 @@ fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool) -> Result<(f64, f64)>
return Err(bad("rectang", "area must be positive"));
}
match (p.get("length").and_then(Value::as_f64), p.get("breadth").and_then(Value::as_f64)) {
(Some(l), _) if l.is_finite() && l > 0.0 => (l, area / l),
(_, Some(b)) if b.is_finite() && b > 0.0 => (area / b, b),
(Some(l), _) if l.is_finite() && l > 0.0 => area_sides(area, l, false, fillet, chamfer),
(_, Some(b)) if b.is_finite() && b > 0.0 => area_sides(area, b, true, fillet, chamfer),
_ => return Err(bad("rectang", "area needs `length` or `breadth`")),
}
} else {
@@ -68,7 +89,7 @@ pub(crate) fn run_rectang2(s: &mut Session, p: &Value) -> Result<Value> {
}
let fillet = size_param("rectang", p, "fillet", true)?.unwrap_or(0.0);
let width = size_param("rectang", p, "width", true)?.unwrap_or(0.0);
let (w, h) = rect_size(p, a, rot, centered)?;
let (w, h) = rect_size(p, a, rot, centered, fillet, ch)?;
if w.abs() < 1e-12 || h.abs() < 1e-12 || !w.is_finite() || !h.is_finite() {
return Err(bad("rectang", "rectangle has no area"));
}
@@ -116,10 +137,13 @@ pub(crate) struct RectM2 {
asking: Option<RAsk>,
}
/// A rectangle's rotation as AutoCAD 2024 shows it: degrees from 0 to 360, two decimals.
fn rotation_text(rotation: f64) -> String {
let t = format!("{:.2}", rotation.to_degrees().rem_euclid(360.0));
if t == "360.00" { "0.00".into() } else { t }
/// A rectangle's rotation (radians counterclockwise from +X) as AutoCAD 2024 shows it: from
/// ANGBASE in the ANGDIR sense, in the drawing's angle units, to two places. Rotation 30 typed
/// with ANGBASE 90 and ANGDIR 1 shows as "120.00", and 30.5 in degrees/minutes/seconds as
/// "30d30'".
fn rotation_text(s: &Session, rotation: f64) -> String {
let au = s.angle_settings();
crate::units::format_angle(au.shown(rotation), au.aunits, 2)
}
/// AutoCAD 2024's line listing the RECTANG modes that are set, `None` when none is ("Current
@@ -144,9 +168,10 @@ fn modes_line(s: &Session, m: &RectangModes) -> Option<String> {
if m.width > 0.0 {
parts.push(format!("Width={}", d(m.width)));
}
let rot = rotation_text(m.rotation);
if rot != "0.00" {
parts.push(format!("Rotation={rot}"));
// Listed when the rectangle is turned from +X at all, to two places, whatever ANGBASE says.
let turned = format!("{:.2}", m.rotation.to_degrees().rem_euclid(360.0));
if turned != "0.00" && turned != "360.00" {
parts.push(format!("Rotation={}", rotation_text(s, m.rotation)));
}
(!parts.is_empty()).then(|| format!("Current rectangle modes: {}", parts.join(" ")))
}
@@ -219,7 +244,7 @@ impl Interactive for RectM2 {
}
/// Asks for the pending option's value, or for the first and second points; in centre mode
/// the first prompt asks for the centre instead of a corner.
fn prompt(&self, _s: &Session) -> Prompt {
fn prompt(&self, s: &Session) -> Prompt {
let num = |m: &str, d: f64| Prompt::new(m, Accept::NUMBER).default(format!("{d:.4}"));
if let Some(a) = self.asking {
return match a {
@@ -237,7 +262,7 @@ impl Interactive for RectM2 {
RAsk::DimW => num("Specify width for rectangles", self.dims.map(|d| d.1).unwrap_or(10.0)),
RAsk::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER)
.kw(&["Pick points"])
.default(rotation_text(self.rotation))
.default(rotation_text(s, self.rotation))
.base_opt(self.first),
RAsk::RotPick1 => Prompt::new("Specify first point", Accept::POINT),
RAsk::RotPick2(b) => Prompt::new("Specify second point", Accept::POINT).base(b),
@@ -299,7 +324,7 @@ impl Interactive for RectM2 {
self.asking = Some(a);
return Err(other("Value must be positive."));
}
let (w, h) = if a == RAsk::AreaLength { (v, self.area / v) } else { (self.area / v, v) };
let (w, h) = area_sides(self.area, v, a == RAsk::AreaWidth, self.fillet, self.chamfer);
return self.make(s, w, h);
}
RAsk::DimL => {
@@ -314,7 +339,8 @@ impl Interactive for RectM2 {
RAsk::Rotation => match i {
Input::Keyword(_) => self.asking = Some(RAsk::RotPick1),
Input::Point(p) => self.rotation = self.first.map(|f| f.angle_to(p)).unwrap_or(0.0),
Input::Text(t) => self.rotation = s.angle_settings().direction(&t).ok_or_else(|| other("Requires a valid angle."))?,
// An amount turned in the ANGDIR sense from +X, ANGBASE aside, as AutoCAD takes it.
Input::Text(t) => self.rotation = s.angle_settings().rotation(&t).ok_or_else(|| other("Requires a valid angle."))?,
_ => {}
},
RAsk::RotPick1 => {
+251 -5
View File
@@ -729,6 +729,57 @@ fn divide_and_measure_command_line() {
s.cancel();
}
#[test]
fn divide_takes_a_whole_number_as_typed() {
// AutoCAD 2024 at "Enter the number of segments or [Block]:": +5, 05, the LISP real 5.0 and
// 32767 are taken; 5.0, 5., 1e1, 4.5, 1, 0, -3, 32768, x, Enter and a point from LISP are
// refused and asked again (measured).
let points = |s: &Session| kinds(s).iter().filter(|k| **k == "Point").count();
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("divide 5,0").unwrap();
let asked = s.prompt_text();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter the number of segments or [Block]:"));
for bad in ["5.0", "5.", "1e1", "4.5", "1", "0", "-3", "32768", "x", "", "(list 1 2)"] {
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, ["Requires an integer between 2 and 32767, or option keyword."], "{bad:?}");
assert_eq!(s.prompt_text(), asked, "{bad:?}");
}
assert_eq!(points(&s), 0);
s.cmdline("+5").unwrap();
assert!(s.running.is_none());
assert_eq!(points(&s), 4);
for (typed, n) in [("05", 4), ("(+ 2.5 2.5)", 4), ("2", 1), ("32767", 32766)] {
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("divide 5,0").unwrap();
s.cmdline(typed).unwrap();
assert!(s.running.is_none(), "{typed}: {}", s.prompt_text());
assert_eq!(points(&s), n, "{typed}");
}
// MEASURE shares the prompt machine and is unchanged: Enter at its length still ends it.
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("measure 5,0").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(points(&s), 0);
// After Block the prompt offers no keyword, and the message names none (AutoCAD 2024, measured).
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let tick = s.execute("circle", &json!({"center": [50, 50], "radius": 0.1})).unwrap();
s.execute("block", &json!({"name": "DOT", "base": [50, 50], "handles": [h(&tick)], "keep": "delete"})).unwrap();
s.cmdline("divide 5,0 b DOT y").unwrap();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter the number of segments:"));
s.cmdline("5.0").unwrap();
assert_eq!(s.log.last().map(String::as_str), Some("Requires an integer between 2 and 32767."));
s.cmdline("5").unwrap();
assert!(s.running.is_none());
assert_eq!(kinds(&s).iter().filter(|k| **k == "Block Reference").count(), 4);
}
// ---------------- REVCLOUD ----------------
#[test]
@@ -1101,6 +1152,198 @@ fn rectang_options_command_line() {
}
}
/// RECTANG against what AutoCAD 2024 stores for the same typed input (black-box: synthetic
/// input in accoreconsole, read back with `entget`): Area with the corners taken off, and
/// corners too large for the sides.
#[test]
fn rectang_area_and_oversized_corners_match_autocad() {
type Case = (&'static [&'static str], &'static [[f64; 3]], [f64; 3]);
// (typed input, vertices [x, y, bulge], [width, elevation, thickness])
let cases: [Case; 4] = [
// RECTANG-028: Area counts the chamfered corners off.
(
&["rectang _C 1.5 2.5 26.36462345136234,-19.7291241693893 _R 0 _A 1442.9297064464572 _W 35.53488991311575"],
&[
[26.36462345136234, -18.2291241693893, 0.0],
[28.86462345136234, -19.7291241693893, 0.0],
[65.68168268505678, -19.7291241693893, 0.0],
[67.18168268505678, -17.2291241693893, 0.0],
[67.18168268505678, 14.30576574372644, 0.0],
[64.68168268505678, 15.80576574372644, 0.0],
[27.86462345136234, 15.80576574372644, 0.0],
[26.36462345136234, 13.30576574372644, 0.0],
],
[0.0, 0.0, 0.0],
),
// RECTANG-035-VN: Area counts the fillets off, at survey coordinates.
(
&["rectang _F 2.0 612322.0691653182,2398792.948957577 _R 0 _A 592.8936847254046 _L 19.287858563349488"],
&[
[612322.0691653182, 2398794.948957577, 0.414213562373095],
[612324.0691653182, 2398792.948957577, 0.0],
[612339.3570238815, 2398792.948957577, 0.414213562373095],
[612341.3570238815, 2398794.948957577, 0.0],
[612341.3570238815, 2398821.866195597, 0.414213562373095],
[612339.3570238815, 2398823.866195598, 0.0],
[612324.0691653182, 2398823.866195598, 0.414213562373095],
[612322.0691653182, 2398821.866195597, 0.0],
],
[0.0, 0.0, 0.0],
),
// RECTANG-029: a fillet too large: each corner two coincident vertices.
(
&["rectang _F 11.37084114989061 -21.46774953784037,-0.023473793210982308 _R 0 -2.5163476213560187,49.88119923361903"],
&[
[-21.46774953784036, -0.0234737932109823, 0.0],
[-21.46774953784036, -0.0234737932109823, 0.0],
[-2.516347621356018, -0.0234737932109823, 0.0],
[-2.516347621356018, -0.0234737932109823, 0.0],
[-2.516347621356018, 49.88119923361903, 0.0],
[-2.516347621356018, 49.88119923361903, 0.0],
[-21.46774953784036, 49.88119923361903, 0.0],
[-21.46774953784036, 49.88119923361903, 0.0],
],
[0.0, 0.0, 0.0],
),
// RECTANG-039-VN: a chamfer too large, rotated, with Dimensions.
(
&[
"rectang _C 18.656567079201356 18.656567079201356 612317.9599920243,2398739.0200147885 _R 30 _D 26.652238684573366 32.64533161964191 612344.6122307089,2398771.6653464083",
],
&[
[612317.9599920243, 2398739.020014788, 0.0],
[612317.9599920243, 2398739.020014788, 0.0],
[612341.041507793, 2398752.34613413, 0.0],
[612341.041507793, 2398752.34613413, 0.0],
[612324.7188419831, 2398780.617820628, 0.0],
[612324.7188419831, 2398780.617820628, 0.0],
[612301.6373262145, 2398767.291701286, 0.0],
[612301.6373262145, 2398767.291701286, 0.0],
],
[0.0, 0.0, 0.0],
),
];
let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0);
for (input, want, [width, elevation, thickness]) in cases {
let mut s = Session::new();
for line in input {
s.cmdline(line).unwrap();
assert!(s.running.is_none(), "{line}: {}", s.prompt_text());
}
let e = s.doc().unwrap().model.last().unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{input:?}: {:?}", e.kind) };
let got: Vec<[f64; 3]> = p.vertices.iter().map(|v| [v.p.x, v.p.y, v.bulge]).collect();
let ok = got.len() == want.len() && got.iter().zip(want).all(|(g, w)| g.iter().zip(w).all(|(a, b)| same(*a, *b)));
assert!(
ok,
"{input:?}
got {got:?}
want {want:?}"
);
assert!(p.closed && same(p.const_width, width) && same(p.elevation, elevation) && same(e.common.thickness, thickness), "{input:?}");
}
// Rotation, elevation and thickness are remembered too: AutoCAD opens the next RECTANG with
// "Current rectangle modes: Elevation=7.5000 Thickness=2.2500 Rotation=30.96".
let mut s = Session::new();
s.cmdline("rectang _E 7.5 _T 2.25 0,0 _R _P 0,0 10,6 10,20").unwrap();
s.cmdline("rectang 100,100 110,105").unwrap();
let e = s.doc().unwrap().model.last().unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
let edge = p.vertices[1].p - p.vertices[0].p;
assert!(p.vertices[0].p == Vec2::new(100.0, 100.0) && same(edge.angle(), 6f64.atan2(10.0)), "{p:?}");
assert!(p.elevation == 7.5 && e.common.thickness == 2.25);
}
/// RECTANG's Rotation follows the drawing's angle settings as AutoCAD 2024's does.
#[test]
fn rectang_rotation_follows_the_angle_settings() {
let modes = |s: &Session| s.log.iter().filter(|l| l.starts_with("Current rectangle modes:")).cloned().collect::<Vec<_>>();
// With ANGBASE 90 and ANGDIR 1, AutoCAD 2024 turns a rectangle given Rotation 30 clockwise
// by 30° from +X (ANGBASE aside), and shows that rotation from ANGBASE: "Rotation=120.00",
// and <120.00> as the next rotation default.
let mut s = Session::new();
s.cmdline("setvar angbase 90").unwrap();
s.cmdline("setvar angdir 1").unwrap();
s.cmdline("rectang 50,0 _R 30 60,5").unwrap();
let e = s.doc().unwrap().model.last().unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
let edge = p.vertices[1].p - p.vertices[0].p;
assert!((edge.y.atan2(edge.x) + 30f64.to_radians()).abs() < 1e-9, "{p:?}");
s.start("rectang").unwrap();
assert_eq!(modes(&s), ["Current rectangle modes: Rotation=120.00"]);
s.cmdline("50,0").unwrap();
s.cmdline("_R").unwrap();
assert!(s.prompt_text().contains("<120.00>"), "{}", s.prompt_text());
s.cancel();
// In degrees/minutes/seconds: "Rotation=30d30'".
let mut s = Session::new();
s.cmdline("setvar aunits 1").unwrap();
s.cmdline("rectang 50,0 _R 30.5 60,5").unwrap();
s.start("rectang").unwrap();
assert_eq!(modes(&s), ["Current rectangle modes: Rotation=30d30'"]);
s.cancel();
}
/// Area allows for cut corners only while they fit: a fillet too large for the resulting sides
/// leaves square corners, so the rectangle is the full area asked for (4 × 1, not 4 × 1.858).
/// Corners exactly as long as the shorter side allows still fit; a hair longer and the corners
/// stay square, each still written twice (AutoCAD 2024, `entget` of a 4 x 2 rectangle).
#[test]
fn rectang_corners_at_the_limit_fit_and_just_over_stay_square() {
let b = (std::f64::consts::PI / 8.0).tan();
let fit: [(&str, &[(f64, f64, f64)]); 4] = [
(
"_F 0.9999",
&[
(0.0, 0.9999, b),
(0.9999, 0.0, 0.0),
(3.0001, 0.0, b),
(4.0, 0.9999, 0.0),
(4.0, 1.0001, b),
(3.0001, 2.0, 0.0),
(0.9999, 2.0, b),
(0.0, 1.0001, 0.0),
],
),
("_F 1", &[(0.0, 1.0, b), (1.0, 0.0, 0.0), (3.0, 0.0, b), (4.0, 1.0, 0.0), (4.0, 1.0, b), (3.0, 2.0, 0.0), (1.0, 2.0, b), (0.0, 1.0, 0.0)]),
(
"_C 1 1",
&[(0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (3.0, 0.0, 0.0), (4.0, 1.0, 0.0), (4.0, 1.0, 0.0), (3.0, 2.0, 0.0), (1.0, 2.0, 0.0), (0.0, 1.0, 0.0)],
),
(
"_C 1.2 0.8",
&[(0.0, 1.2, 0.0), (0.8, 0.0, 0.0), (2.8, 0.0, 0.0), (4.0, 0.8, 0.0), (4.0, 0.8, 0.0), (3.2, 2.0, 0.0), (1.2, 2.0, 0.0), (0.0, 1.2, 0.0)],
),
];
let square =
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 2.0, 0.0), (4.0, 2.0, 0.0), (0.0, 2.0, 0.0), (0.0, 2.0, 0.0)];
let over: [(&str, &[(f64, f64, f64)]); 2] = [("_F 1.0001", &square), ("_C 1.2 0.81", &square)];
for (corners, want) in fit.into_iter().chain(over) {
let mut s = Session::new();
s.cmdline(&format!("rectang {corners} 0,0 4,2")).unwrap();
let EntityKind::LwPolyline(p) = last(&s) else { panic!("no polyline") };
let got: Vec<(f64, f64, f64)> = p.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect();
let ok = got.len() == want.len()
&& got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9 && (g.2 - w.2).abs() < 1e-6);
assert!(ok, "{corners}: {got:?}");
}
}
#[test]
fn rectang_area_with_corners_too_large_stays_exact() {
let check = |s: &Session| {
let pts = rect_pts(s);
let b = cadcraft_geom::Bounds2::from_points(pts.clone());
assert!(near(b.min, 0.0, 0.0) && near(b.max, 4.0, 1.0), "{pts:?}");
assert!(pts.len() == 8 && pts.chunks(2).all(|c| c[0] == c[1]), "{pts:?}");
};
let mut s = Session::new();
s.cmdline("rectang _F 2 0,0 _A 4 _L 4").unwrap();
check(&s);
s.execute("rectang", &json!({"p1": [0, 0], "area": 4, "length": 4, "fillet": 2})).unwrap();
check(&s);
}
/// Guards the JSON `center: true` form for every sizing route: a picked corner mirrored about
/// the centre, full-size `dimensions`, full `area`, rotation about the centre, that the default
/// corner mode is untouched, and that centre mode without a size is rejected.
@@ -1136,7 +1379,7 @@ fn rectang_center_mode_json() {
}
/// Guards that fillet, chamfer, width and thickness still apply in centre mode, and that an
/// oversized fillet falls back to sharp corners without moving the rectangle off centre.
/// oversized fillet leaves sharp corners without moving the rectangle off centre.
#[test]
fn rectang_center_mode_honours_options() {
let mut s = Session::new();
@@ -1153,9 +1396,11 @@ fn rectang_center_mode_honours_options() {
assert_eq!(rect_pts(&s).len(), 8);
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
// A fillet too large for the rectangle falls back to sharp corners, still centred.
// A fillet too large for the rectangle leaves sharp corners, each one two coincident vertices
// as in AutoCAD, still centred.
s.execute("rectang", &json!({"center": true, "p1": [10, 10], "p2": [14, 16], "fillet": 5})).unwrap();
assert_eq!(rect_pts(&s).len(), 4);
let pts = rect_pts(&s);
assert!(pts.len() == 8 && pts.chunks(2).all(|c| c[0] == c[1]), "{pts:?}");
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
}
@@ -1183,8 +1428,9 @@ fn rectang_center_mode_command_line() {
assert!(s.running.is_none(), "{}", s.prompt_text());
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
// Area too: the rectangle of that area is centred on the first point.
s.cmdline("rectang ce 10,10 a 96 l 8").unwrap();
// Area too: the rectangle of that area is centred on the first point (without the fillet
// remembered from above, which would take its corners off the area).
s.cmdline("rectang f 0 ce 10,10 a 96 l 8").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let b = cadcraft_geom::Bounds2::from_points(rect_pts(&s));
assert!(near(b.min, 6.0, 4.0) && near(b.max, 14.0, 16.0), "{b:?}");
+36
View File
@@ -104,6 +104,36 @@ pub fn set_dwg_compat_lost(f: DwgCompatLost) {
let _ = DWG_COMPAT_LOST.set(f);
}
/// Notes on what a DWG keeps of a drawing only in part, such as a linetype with more dash
/// elements than a DWG can count (installed by the app with the DWG writer, a lower layer; see
/// `cadcraft_io::dwg_notes`).
pub type DwgNotes = fn(&Drawing) -> Vec<String>;
static DWG_NOTES: OnceLock<DwgNotes> = OnceLock::new();
pub fn set_dwg_notes(f: DwgNotes) {
let _ = DWG_NOTES.set(f);
}
/// The [`DwgNotes`] of `d`, the drawing a DWG save writes: none without the hook.
pub fn dwg_notes(d: &Drawing) -> Vec<String> {
DWG_NOTES.get().map(|f| f(d)).unwrap_or_default()
}
/// Say on the command line what the DWG just written keeps only in part (`notes`, from
/// [`dwg_notes`]), and list it in the result's `warnings`.
pub(crate) fn report_dwg_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
if notes.is_empty() {
return;
}
for note in &notes {
s.echo(note.clone());
}
if let Some(o) = r.as_object_mut() {
o.insert("warnings".into(), json!(notes));
}
}
/// 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> {
@@ -873,6 +903,8 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() });
if drops_unknown(format!("drawing.{fmt}")) {
report_not_saved(s, &mut r, &lost);
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
report_dwg_notes(s, &mut r, notes);
} else if is_dxf_file(format!("drawing.{fmt}")) {
let lost = host_dxf_lost(s, version);
report_lost(s, &mut r, "drawing.dxf", version, &lost);
@@ -1005,7 +1037,9 @@ pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
let Ok(d) = s.doc() else { return };
let version = own_version(d, path);
let lost = lost_writing(d, path, version);
let notes = if drops_unknown(path) { dwg_notes(d) } else { Vec::new() };
report_lost(s, r, path, version, &lost);
report_dwg_notes(s, r, notes);
}
/// Say on the command line what the file `path`, written at `version`, couldn't keep (`lost`),
@@ -1112,6 +1146,8 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R
report_new_folder(s, &mut r, folder);
if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) {
report_not_saved(s, &mut r, &lost);
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
report_dwg_notes(s, &mut r, notes);
} else if r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
let lost = host_dxf_lost(s, version);
report_lost(s, &mut r, "drawing.dxf", version, &lost);
+2 -8
View File
@@ -455,15 +455,9 @@ fn tinted_dim_style(d: &mut Drawing, name: &str, color: Color, tinted: &mut Tint
if let Some(n) = tinted.names.get(&key) {
return Some(n.clone());
}
let st = d.dim_styles.iter().find(|s| s.name.eq_ignore_ascii_case(name))?.clone();
let st = d.dim_style(name)?.clone();
let base = format!("COMPARE_{}_{}", tag(color), st.name);
let new = tinted.next.find(
"dimension style",
&base,
d.dim_styles.len(),
|i| suffixed(&base, i),
|n| d.dim_styles.iter().any(|s| s.name.eq_ignore_ascii_case(n)),
);
let new = tinted.next.find("dimension style", &base, d.dim_styles.len(), |i| suffixed(&base, i), |n| d.dim_style(n).is_some());
d.dim_styles.push(DimStyle {
name: new.clone(),
dim_line_color: Color::ByBlock,
+33 -14
View File
@@ -68,29 +68,48 @@ pub fn polygon_from_edge(p1: Vec2, p2: Vec2, sides: usize) -> Vec<PolyVertex> {
/// chamfer distances at every corner, in AutoCAD 2024's order: from `a` along X to `b`'s X, then
/// `b`, then back along Y. A chamfer cuts the edge into each corner by its first distance and the
/// edge out of it by its second; each fillet arc starts on the edge into its corner. A fillet or
/// chamfer that doesn't fit leaves the corners square.
/// chamfer too large for the shorter side leaves the corners square, each as two coincident
/// vertices, as AutoCAD stores them.
pub fn rect_with_corners(a: Vec2, b: Vec2, fillet: f64, chamfer: (f64, f64)) -> Vec<PolyVertex> {
let corners = [a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y)];
let short = (b.x - a.x).abs().min((b.y - a.y).abs());
let (d_in, d_out, bulge) = if fillet > 0.0 && fillet * 2.0 <= short + 1e-12 {
// Counter-clockwise round the corners (a positive bulge) when `b` is up and right of `a`, or
// down and left.
let sign = if (b.x - a.x) * (b.y - a.y) >= 0.0 { 1.0 } else { -1.0 };
(fillet, fillet, sign * cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2))
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 && chamfer.0 + chamfer.1 <= short + 1e-12 {
(chamfer.0, chamfer.1, 0.0)
} else {
return corners.into_iter().map(PolyVertex::new).collect();
};
let Some((d_in, d_out)) = rect_corner_cuts(fillet, chamfer) else { return corners.into_iter().map(PolyVertex::new).collect() };
let fits = rect_corners_fit(b - a, fillet, chamfer);
// Counter-clockwise round the corners (a positive bulge) when `b` is up and right of `a`, or
// down and left.
let sign = if (b.x - a.x) * (b.y - a.y) >= 0.0 { 1.0 } else { -1.0 };
let bulge = if fillet > 0.0 { sign * cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2) } else { 0.0 };
let mut out = Vec::with_capacity(8);
for (i, cur) in corners.iter().enumerate() {
let (Some(prev), Some(next)) = (corners.get((i + 3) % 4), corners.get((i + 1) % 4)) else { continue };
out.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge));
out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out));
if fits {
out.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge));
out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out));
} else {
out.extend([PolyVertex::new(*cur), PolyVertex::new(*cur)]);
}
}
out
}
/// How far a rectangle's fillet or chamfer cuts into the edges into and out of each corner, if
/// one is set: the fillet radius on both, or the two chamfer distances. A fillet wins over a
/// chamfer.
fn rect_corner_cuts(fillet: f64, chamfer: (f64, f64)) -> Option<(f64, f64)> {
if fillet > 0.0 {
Some((fillet, fillet))
} else if chamfer.0 > 0.0 && chamfer.1 > 0.0 {
Some(chamfer)
} else {
None
}
}
/// Whether a fillet or chamfer fits a rectangle of `size` (signed sides): its two cuts together
/// no longer than the shorter side. True when neither is set.
pub fn rect_corners_fit(size: Vec2, fillet: f64, chamfer: (f64, f64)) -> bool {
rect_corner_cuts(fillet, chamfer).is_none_or(|(d_in, d_out)| d_in + d_out <= size.x.abs().min(size.y.abs()) + 1e-12)
}
// ---------- the user's support files ----------
/// Largest support file (linetype, hatch pattern or alias file) read.
+1 -2
View File
@@ -62,8 +62,7 @@ impl Scope {
Some(_) => {
let name = given.unwrap_or_default();
let d = s.doc()?;
let l =
d.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(&name)).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
let l = d.layout(&name).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
Ok(Scope::Space(Space::Paper(l.name.clone())))
}
}
+1 -1
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("layout.copy", "Copy Layout", run_copy).params("{from, to?}"),
CommandSpec::new("layout.list", "List Layouts", run_list).params("→ [{name, tabOrder, page, viewports}]").noundo(),
CommandSpec::new("layout.saveas", "Save Layout as Template", saveas::run_saveas)
.params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?}")
.params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?, warnings?}")
.noundo(),
CommandSpec::new("mview", "Viewports", run_mview)
.alias(&["mv"])
+4 -1
View File
@@ -12,7 +12,7 @@ use cadcraft_doc::{Common, Drawing, Entity, EntityKind, EntityStore, Point};
use cadcraft_geom::Vec3;
use serde_json::{Value, json};
use super::super::file::{drops_unknown, io, not_saved, not_saved_message};
use super::super::file::{drops_unknown, dwg_notes, io, not_saved, not_saved_message, report_dwg_notes};
use super::super::{bad, str_param};
use super::layout_name;
use super::prompts::current_layout;
@@ -136,6 +136,9 @@ pub(super) fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("notSaved".into(), json!(lost));
}
}
if drops_unknown(&path) {
report_dwg_notes(s, &mut r, dwg_notes(&t));
}
Ok(r)
}
+376 -50
View File
@@ -129,80 +129,406 @@ pub(crate) fn join(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
if hs.iter().any(|h| crate::cmd::curves::is_locked(s, *h)) {
return Err(EngineError::Other("An object is on a locked layer.".into()));
}
let hs = joinable_picks(s.doc()?, hs);
let hs = &hs[..];
if let Some(h) = join_on_source(s, hs)? {
return Ok(Some(h));
}
let d = s.doc()?;
let mut segs: Vec<Segment> = Vec::new();
// Source entity of each segment in `segs`, so only entities that end up in the chain are removed.
let mut owners: Vec<Handle> = Vec::new();
let mut common = None;
// Each object JOIN can take, as the pieces it is made of: a line or an arc is one piece, an
// open polyline its segments in order, each keeping its vertices, bulge and widths exactly.
// Each also with whether it faces down: an arc or a polyline whose normal points down Z
// (measured with 0,0,-1; a tilted one is taken the same way). A line faces up whatever its
// normal (AutoCAD 2024 joins one with normal 0,0,-1 to a polyline facing up, and no line to a
// polyline facing down; measured).
let mut units: Vec<(bool, Vec<Piece>)> = Vec::new();
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
for h in hs {
let Some(e) = d.entity(*h) else { continue };
common.get_or_insert_with(|| e.common.clone());
match &e.kind {
EntityKind::Line(l) => segs.push(Segment::Line(Line::new(l.a.xy(), l.b.xy()))),
EntityKind::Arc(a) => segs.push(Segment::Arc { arc: Arc::new(a.center.xy(), a.radius, a.start, a.end), ccw: true }),
EntityKind::LwPolyline(p) if !p.closed => segs.extend(Polyline { vertices: p.vertices.clone(), closed: false }.segments()),
_ => {}
let piece =
|ends: (Vec2, Vec2), heights: (f64, f64), bulge: f64, widths: Option<(f64, f64)>| Piece { owner: *h, ends, heights, bulge, widths };
let unit: Vec<Piece> = match &e.kind {
// A line of no length joins as AutoCAD 2024 joins it, a repeated vertex.
EntityKind::Line(l) => vec![piece((l.a.xy(), l.b.xy()), (l.a.z, l.b.z), 0.0, None)],
EntityKind::Arc(a) => {
let arc = Arc::new(a.center.xy(), a.radius, a.start, a.end);
vec![piece((arc.start_point(), arc.end_point()), (a.center.z, a.center.z), cadcraft_geom::arc_to_bulge(arc.sweep()), None)]
}
// Repeated vertices included: AutoCAD 2024 keeps them.
EntityKind::LwPolyline(p) if !p.closed => {
// The elevation is along the polyline's normal: down Z for a mirrored one.
let z = if down(e) { -p.elevation } else { p.elevation };
p.vertices
.windows(2)
.map(|w| {
let widths = if p.const_width > 0.0 { (p.const_width, p.const_width) } else { (w[0].start_width, w[0].end_width) };
piece((w[0].p, w[1].p), (z, z), w[0].bulge, Some(widths))
})
.collect()
}
_ => Vec::new(),
};
if !unit.is_empty() {
units.push((down(e), unit));
}
owners.resize(segs.len(), *h);
}
if segs.len() < 2 {
if units.iter().map(|u| u.1.len()).sum::<usize>() < 2 {
return Err(EngineError::Other("Select at least two objects to join.".into()));
}
// Chain greedily from the first segment.
let mut chain = vec![segs.remove(0)];
let mut used = vec![owners.remove(0)];
// An object facing the other way from a polyline source stays out (AutoCAD 2024, measured: one
// facing up takes no arc facing down, and one facing down no arc or polyline facing up). Onto a
// line or an arc it wasn't measured (the core console's JOIN takes only collinear lines or arcs
// on one circle onto those), so objects facing either way still join there.
let polyline_source = units.first().filter(|u| u.1.first().is_some_and(|p| p.widths.is_some())).map(|u| u.0);
let units: Vec<Vec<Piece>> = units.into_iter().filter(|u| polyline_source.is_none_or(|down| u.0 == down)).map(|u| u.1).collect();
// A new polyline takes the source's properties.
let first = units.first().and_then(|u| u.first()).map(|p| p.owner);
let common = first.and_then(|h| d.entity(h)).map(|e| e.common.clone());
let tol = 1e-6;
loop {
let start = chain.first().map(Segment::start).unwrap_or_default();
let end = chain.last().map(Segment::end).unwrap_or_default();
let Some(i) =
segs.iter().position(|s| s.start().near(end, tol) || s.end().near(end, tol) || s.start().near(start, tol) || s.end().near(start, tol))
else {
break;
};
let s0 = segs.remove(i);
used.push(owners.remove(i));
if s0.start().near(end, tol) {
chain.push(s0);
} else if s0.end().near(end, tol) {
chain.push(s0.reversed());
} else if s0.end().near(start, tol) {
chain.insert(0, s0);
} else {
chain.insert(0, s0.reversed());
}
}
if chain.len() < 2 {
let links = chain_units(units, tol);
// One object alone joins nothing, even a polyline whose ends meet: AutoCAD 2024 leaves it open
// ("0 segments added to polyline").
let closed = links.first().zip(links.last()).is_some_and(|(a, b)| meet(a.start(), b.end(), tol));
let one_object = links.first().is_some_and(|f| links.iter().all(|l| l.owner == f.owner));
if links.len() < 2 || one_object {
return Err(EngineError::Other("Objects are not connected.".into()));
}
let closed = chain.first().zip(chain.last()).is_some_and(|(a, b)| a.start().near(b.end(), tol));
let mut vs: Vec<PolyVertex> = chain
let used = |h: &Handle| links.iter().any(|l| l.owner == *h);
// A polyline's own segments keep their widths.
let mut vs: Vec<PolyVertex> = links
.iter()
.map(|s| PolyVertex {
p: s.start(),
bulge: match s {
Segment::Line(_) => 0.0,
Segment::Arc { arc, ccw } => cadcraft_geom::arc_to_bulge(if *ccw { arc.sweep() } else { -arc.sweep() }),
},
..Default::default()
.map(|l| {
let (start_width, end_width) = l.widths.unwrap_or_default();
PolyVertex { p: l.ends.0, bulge: l.bulge, start_width, end_width }
})
.collect();
if !closed && let Some(l) = chain.last() {
vs.push(PolyVertex::new(l.end()));
if !closed && let Some(l) = links.last() {
vs.push(PolyVertex::new(l.ends.1));
}
let space = s.space();
// A new polyline goes in the source's space, whichever space is current.
let space = first.and_then(|h| d.space_of(h)).unwrap_or_else(|| s.space());
let doc = s.doc_mut()?;
for h in hs.iter().filter(|h| used.contains(*h)) {
// A polyline source takes the other pieces and keeps its handle (AutoCAD 2024: "1 segments
// added to polyline").
if let Some(src) = first
&& let Some(EntityKind::LwPolyline(sp)) = doc.entity(src).map(|e| &e.kind)
&& let Some(onto) = onto_polyline(sp, src, &links, closed)
{
for h in hs.iter().filter(|h| **h != src && used(h)) {
doc.remove_entity(*h);
}
doc.modify_entity(src, |e| e.kind = EntityKind::LwPolyline(onto))?;
s.set_selection(Vec::new());
return Ok(Some(src));
}
for h in hs.iter().filter(|h| used(h)) {
doc.remove_entity(*h);
}
// A new polyline stays at the source's height, as a polyline source keeps its elevation. The
// elevation runs along its normal: negated for one facing down. Not measured: the core
// console's JOIN makes no new polyline.
let height = links.iter().find(|l| Some(l.owner) == first).map_or(0.0, |l| l.heights.0);
let common = common.unwrap_or_default();
let elevation = if common.extrusion.z < 0.0 { -height } else { height };
let mut kind = lwpoly(vs, closed);
if let EntityKind::LwPolyline(p) = &mut kind {
p.elevation = elevation;
}
let nh = doc.new_handle();
if let Some(st) = doc.space_mut(&space) {
st.push(Entity { handle: nh, common: common.unwrap_or_default(), kind: lwpoly(vs, closed) });
st.push(Entity { handle: nh, common, kind });
}
s.set_selection(Vec::new());
Ok(Some(nh))
}
/// The picks JOIN can take, each once, in the order picked: lines, arcs and open polylines. The
/// first of them is the source (AutoCAD 2024 passes over a circle picked first and leaves it).
fn joinable_picks(d: &cadcraft_doc::Drawing, hs: &[Handle]) -> Vec<Handle> {
let mut seen = std::collections::HashSet::new();
let joinable = |h: &Handle| {
d.entity(*h).is_some_and(|e| match &e.kind {
EntityKind::Line(_) => true,
EntityKind::Arc(a) => a.radius > cadcraft_geom::EPS,
EntityKind::LwPolyline(p) => !p.closed,
_ => false,
})
};
hs.iter().copied().filter(|h| joinable(h) && seen.insert(*h)).collect()
}
/// Whether JOIN would make the picked arcs a circle. AutoCAD 2024 asks first ("Combined arc
/// segments form a circle. Convert to circle? [Yes/No] <Yes>:"), and No leaves every arc as it
/// is (measured).
pub(crate) fn join_makes_circle(s: &Session, hs: &[Handle]) -> bool {
let Ok(d) = s.doc() else { return false };
// Elliptical arcs and splines join another way, and a locked object stops the join.
let other_way = |h: &Handle| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Ellipse(_) | EntityKind::Spline(_)));
if hs.iter().any(|h| other_way(h) || crate::cmd::curves::is_locked(s, *h)) {
return false;
}
let picks = joinable_picks(d, hs);
let arcs: Vec<&cadcraft_doc::Arc> = picks
.iter()
.filter_map(|h| match d.entity(*h).map(|e| &e.kind) {
Some(EntityKind::Arc(a)) => Some(a),
_ => None,
})
.collect();
let tol = 1e-6;
match &arcs[..] {
[g, rest @ ..] if !rest.is_empty() && arcs.len() == picks.len() => arc_reach(g, rest, tol).is_some_and(|far| far > cadcraft_geom::TAU - tol),
_ => false,
}
}
/// How far round the source arc `g`'s circle, counterclockwise from its start, it and the
/// `others` reach; `None` when one of them isn't on that circle (less than `tol` off its centre
/// and radius). An arc that starts even a hair before the source's start reaches on round past
/// it: AutoCAD 2024 makes a circle of 7°-100° and an arc stored from 7° less 5e-16 rad, and
/// leaves 7°-100° with one from exactly 7° or 5e-7 rad after it.
fn arc_reach(g: &cadcraft_doc::Arc, others: &[&cadcraft_doc::Arc], tol: f64) -> Option<f64> {
let same_circle =
|o: &cadcraft_doc::Arc| o.center.xy().dist(g.center.xy()) < tol && (o.radius - g.radius).abs() < tol && (o.center.z - g.center.z).abs() < tol;
let reach = |o: &cadcraft_doc::Arc| norm_angle(o.start - g.start) + cadcraft_geom::ccw_sweep(o.start, o.end);
others.iter().all(|o| same_circle(o)).then(|| others.iter().map(|o| reach(o)).fold(reach(g), f64::max))
}
/// The chain JOIN builds from the first object: each next object with an end on one of the
/// chain's ends joins whole, turned round where needed, as AutoCAD 2024 joins them, until a join
/// closes the chain; one that the chain meets only at an inner vertex of a polyline stays out.
/// Ends are compared at the objects' own end points, not ones worked out again from arcs, and at
/// their heights.
fn chain_units(mut units: Vec<Vec<Piece>>, tol: f64) -> Vec<Piece> {
let ends = |u: &[Piece]| u.first().zip(u.last()).map(|(a, b)| (a.start(), b.end()));
let near = |p, q| meet(p, q, tol);
if units.is_empty() {
return Vec::new();
}
// A source that already ends where it starts still takes more, unless it has no length at all
// (AutoCAD 2024, measured with a polyline that ends where it starts and with a line of no
// length).
let mut chain: std::collections::VecDeque<Piece> = units.remove(0).into();
if chain.iter().all(|p| p.ends.0.near(p.ends.1, tol)) {
return chain.into();
}
while let (Some(start), Some(end)) = (chain.front().map(Piece::start), chain.back().map(Piece::end)) {
let meets = |u: &Vec<Piece>| ends(u).is_some_and(|(a, b)| near(a, end) || near(b, end) || near(a, start) || near(b, start));
let Some(i) = units.iter().position(meets) else { break };
let unit = units.remove(i);
let Some((a, b)) = ends(&unit) else { break };
// Where an object that meets the chain at more than one place goes, as AutoCAD 2024 puts
// it (measured): a polyline by its first vertex if it can, and before the chain rather
// than after it; a line or an arc turned round if it can, its end on the chain's end
// before its start on the chain's start.
let polyline = unit.first().is_some_and(|p| p.widths.is_some());
let (before, turned) = if polyline {
if near(a, start) {
(true, true)
} else if near(a, end) {
(false, false)
} else {
(near(b, start), !near(b, start))
}
} else if near(b, end) {
(false, true)
} else if near(a, start) {
(true, true)
} else {
(!near(a, end), false)
};
match (before, turned) {
(false, false) => chain.extend(unit),
(false, true) => chain.extend(unit.into_iter().rev().map(Piece::flipped)),
(true, false) => unit.into_iter().rev().for_each(|p| chain.push_front(p)),
(true, true) => unit.into_iter().for_each(|p| chain.push_front(p.flipped())),
}
// A chain that a join closes takes nothing more.
if chain.front().zip(chain.back()).is_some_and(|(f, l)| near(f.start(), l.end())) {
break;
}
}
chain.into()
}
/// A segment in the chain JOIN builds: the object it came from, its end points as the object has
/// them (turned round when it runs backwards in the chain) and their world heights (a line's own
/// Z, an arc's centre Z, a polyline's elevation, negated for one facing down), its bulge and, for a
/// polyline's own segment, its widths.
#[derive(Clone, Copy)]
struct Piece {
owner: Handle,
ends: (Vec2, Vec2),
heights: (f64, f64),
bulge: f64,
widths: Option<(f64, f64)>,
}
impl Piece {
fn flipped(self) -> Self {
Piece {
ends: (self.ends.1, self.ends.0),
heights: (self.heights.1, self.heights.0),
bulge: -self.bulge,
widths: self.widths.map(|(a, b)| (b, a)),
..self
}
}
fn start(&self) -> (Vec2, f64) {
(self.ends.0, self.heights.0)
}
fn end(&self) -> (Vec2, f64) {
(self.ends.1, self.heights.1)
}
}
/// Whether two ends meet: in plan and at the same height. AutoCAD 2024 leaves an end that meets
/// another only in plan apart (measured: a line or a polyline at 0 and a line at 5, or a polyline
/// at 5 and a line at 0, end to end in plan, stay as they are).
fn meet(p: (Vec2, f64), q: (Vec2, f64), tol: f64) -> bool {
p.0.near(q.0, tol) && (p.1 - q.1).abs() < tol
}
/// The open polyline `sp` (handle `src`) with the chain's other pieces added before and after
/// it, as AutoCAD 2024 JOIN makes it (measured with `entget`): its own vertices stay exactly as
/// they are, and so do its elevation, linetype generation and, when only lines and arcs join,
/// its constant width; another polyline's segments keep their bulges and widths; a line or arc
/// takes the widths of the source's vertex at the end it joins (first or last); and when another
/// polyline joins, the end vertex's widths are cleared.
///
/// `None` when the source's segments aren't one run of the chain (they always are: the chain
/// starts from the source and takes its segments in order).
fn onto_polyline(sp: &cadcraft_doc::LwPolyline, src: Handle, links: &[Piece], closed: bool) -> Option<cadcraft_doc::LwPolyline> {
let run: Vec<usize> = (0..links.len()).filter(|i| links[*i].owner == src).collect();
let (&first, &last) = (run.first()?, run.last()?);
if sp.closed || run.len() != last - first + 1 {
return None;
}
let other_polyline = links.iter().any(|l| l.owner != src && l.widths.is_some());
let mut own = sp.vertices.clone();
if other_polyline && sp.const_width > 0.0 {
// The constant width goes, so spell it out on the source's own segments.
for v in &mut own {
(v.start_width, v.end_width) = (sp.const_width, sp.const_width);
}
}
let widths = |v: &PolyVertex| (v.start_width, v.end_width);
let (head, tail) = (widths(own.first()?), widths(own.last()?));
let vertex = |i: usize, fill: (f64, f64)| {
let (start_width, end_width) = links[i].widths.unwrap_or(fill);
PolyVertex { p: links[i].ends.0, bulge: links[i].bulge, start_width, end_width }
};
let mut vs: Vec<PolyVertex> = (0..first).map(|i| vertex(i, head)).collect();
vs.extend(own);
if last + 1 < links.len() {
// The source's end vertex starts the first piece after it.
let v = vertex(last + 1, tail);
if let Some(end) = vs.last_mut() {
(end.bulge, end.start_width, end.end_width) = (v.bulge, v.start_width, v.end_width);
}
vs.extend((last + 2..links.len()).map(|i| vertex(i, tail)));
vs.push(PolyVertex { p: links.last()?.ends.1, start_width: tail.0, end_width: tail.1, ..Default::default() });
}
if other_polyline && let Some(end) = vs.last_mut() {
(end.start_width, end.end_width) = (0.0, 0.0);
}
if closed {
// The last vertex is the first one again.
vs.pop();
}
Some(cadcraft_doc::LwPolyline { vertices: vs, closed, const_width: if other_polyline { 0.0 } else { sp.const_width }, ..sp.clone() })
}
/// JOIN onto the first object (the source) as AutoCAD 2024 does when the others all lie on its
/// line or its circle: gaps and overlaps are bridged and the source keeps its handle.
///
/// - Lines on the source's line make one line, from the source's start end to the farthest
/// point the way it runs (and back past its start if one reaches behind it).
/// - Arcs on the source's circle join counterclockwise from the source's start to the farthest
/// end; arcs that reach all the way round make a circle, a new object in their place.
///
/// `None` when the objects aren't all of one of those kinds.
fn join_on_source(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
let d = s.doc()?;
let ents: Vec<std::sync::Arc<Entity>> = hs.iter().filter_map(|h| d.entity(*h).cloned()).collect();
let [src, rest @ ..] = &ents[..] else { return Ok(None) };
if rest.is_empty() || ents.len() != hs.len() {
return Ok(None);
}
// AutoCAD 2024 takes lines less than 1e-6 off the source's line, and arcs less than 1e-6
// off its centre and radius, at any size of coordinates (measured at 0, 1000 and 2.4e6), and
// makes a circle of arcs that come round to less than 1e-6 radians from the source's start.
let tol = 1e-6;
let kind = match &src.kind {
EntityKind::Line(l) => {
let (a, b) = (l.a.xy(), l.b.xy());
let len = a.dist(b);
let lines: Vec<&cadcraft_doc::Line> = rest
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(o) => Some(o),
_ => None,
})
.collect();
let level = |z: f64| (z - l.a.z).abs() < tol;
if lines.len() != rest.len() || len <= 0.0 || !level(l.b.z) || !lines.iter().all(|o| level(o.a.z) && level(o.b.z)) {
return Ok(None);
}
let u = (b - a) * (1.0 / len);
let on_line = |p: Vec2| (p - a).cross(u).abs() < tol;
if !lines.iter().all(|o| on_line(o.a.xy()) && on_line(o.b.xy())) {
return Ok(None);
}
let ts = lines.iter().flat_map(|o| [o.a.xy(), o.b.xy()]).map(|p| (p - a).dot(u)).chain([0.0, len]);
let (t0, t1) = ts.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), t| (lo.min(t), hi.max(t)));
let at = |t: f64| (a + u * t).to3(l.a.z);
EntityKind::Line(cadcraft_doc::Line { a: at(t0), b: if t1 == len { l.b } else { at(t1) } })
}
EntityKind::Arc(g) => {
let arcs: Vec<&cadcraft_doc::Arc> = rest
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Arc(o) => Some(o),
_ => None,
})
.collect();
let Some(far) = arc_reach(g, &arcs, tol).filter(|_| arcs.len() == rest.len()) else { return Ok(None) };
if far > cadcraft_geom::TAU - tol {
let circle = Entity {
handle: Handle(0),
common: src.common.clone(),
kind: EntityKind::Circle(cadcraft_doc::Circle { center: g.center, radius: g.radius }),
};
// In the source's space, whichever space is current.
let space = d.space_of(src.handle).unwrap_or_else(|| s.space());
let doc = s.doc_mut()?;
for h in hs {
doc.remove_entity(*h);
}
let nh = doc.new_handle();
if let Some(st) = doc.space_mut(&space) {
st.push(Entity { handle: nh, ..circle });
}
s.set_selection(Vec::new());
return Ok(Some(nh));
}
let end = if far > cadcraft_geom::ccw_sweep(g.start, g.end) { norm_angle(g.start + far) } else { g.end };
EntityKind::Arc(cadcraft_doc::Arc { end, ..g.clone() })
}
_ => return Ok(None),
};
let src_h = src.handle;
let doc = s.doc_mut()?;
for h in hs.iter().filter(|h| **h != src_h) {
doc.remove_entity(*h);
}
doc.modify_entity(src_h, |e| e.kind = kind)?;
s.set_selection(Vec::new());
Ok(Some(src_h))
}
pub(super) fn run_join(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
if p.get("close").and_then(Value::as_bool) == Some(true) {
+193 -18
View File
@@ -1,4 +1,4 @@
use super::break_join::join;
use super::break_join::{join, join_makes_circle};
use super::explode::explode;
use super::transform::{at_elevation, erase, scale_entities, transform_entities};
use super::{
@@ -20,6 +20,18 @@ pub(super) enum Op {
Join,
}
/// COPY's Array option: asking how many items, then where the second one goes (or, with Fit, the
/// last one).
#[derive(Clone, Copy, PartialEq)]
enum CopyArray {
Off,
Count,
Items { n: u16, fit: bool },
}
/// The most items COPY's Array option makes, the original included, as in AutoCAD.
const MAX_COPY_ITEMS: u16 = 32767;
/// Select objects, then collect the points/values the operation needs.
pub(super) struct SelectThen {
op: Op,
@@ -37,9 +49,16 @@ pub(super) struct SelectThen {
/// SCALE Reference: the reference length, once known.
ref_len: Option<f64>,
copy_mode: bool,
/// COPY: one copy and done (COPYMODE 1, until the Multiple option), else copies until Exit.
copy_single: bool,
/// COPY: the objects each placement made, so Undo takes back the last one.
copies: Vec<Vec<Handle>>,
copy_array: CopyArray,
ask_erase: bool,
/// JOIN of a single arc or elliptical arc: the prompt asks for arcs to join to it, or cLose.
join_source: Option<Handle>,
/// JOIN of arcs that make a circle: asking whether to.
ask_circle: bool,
}
impl SelectThen {
@@ -55,8 +74,12 @@ impl SelectThen {
ref_from: None,
ref_len: None,
copy_mode: false,
copy_single: false,
copies: Vec::new(),
copy_array: CopyArray::Off,
ask_erase: false,
join_source: None,
ask_circle: false,
}
}
fn apply(&mut self, s: &mut Session) -> Result<Step> {
@@ -84,8 +107,120 @@ impl SelectThen {
}
}
/// JOIN the selected objects and report what they became.
/// COPY's prompt once the base point is known, as AutoCAD 2024 asks it.
fn copy_prompt(&self, base: Option<Vec2>) -> Prompt {
match self.copy_array {
CopyArray::Count => Prompt::new("Enter number of items to array", Accept::NUMBER),
CopyArray::Items { fit: false, .. } => Prompt::new("Specify second point", Accept::POINT).kw(&["Fit"]).base_opt(base),
CopyArray::Items { fit: true, .. } => Prompt::new("Specify second point", Accept::POINT).kw(&["Array"]).base_opt(base),
CopyArray::Off if self.copies.is_empty() => {
Prompt::new("Specify second point", Accept::POINT).kw(&["Array"]).default("use first point as displacement").base_opt(base)
}
CopyArray::Off => Prompt::new("Specify second point", Accept::POINT).kw(&["Array", "Exit", "Undo"]).default("Exit").base_opt(base),
}
}
/// COPY once the base point is known (AutoCAD 2024, measured): a point places a copy; Enter
/// at the first prompt copies by the base point taken as a displacement, and after a copy
/// ends the command; Array asks for a number of items, the original included, then puts
/// them a second point apart (or, with Fit, spread up to it, Enter keeping them at the
/// base); Undo takes back the last placement. One placement ends a single-copy COPY.
fn copy_input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(base) = self.pts.first().copied() else { return Ok(Step::Continue) };
let placed = match (self.copy_array, i) {
(CopyArray::Count, Input::Enter) => return self.copy_done(s),
(CopyArray::Count, i) => {
// A whole number as typed, from 2 to 32767 whatever the selection: AutoCAD 2024 takes
// +3 and 03 here, refuses 4.0, 1e1, 8/2, 1', 3", 50002 and a point, and doesn't
// apply MAXARRAY (with MAXARRAY 100000, four lines and 26000 items made 104000
// lines; measured).
let n = match i {
Input::Text(t) => t.trim().parse::<u16>().ok().filter(|v| (2..=MAX_COPY_ITEMS).contains(v)),
_ => None,
}
.ok_or_else(|| EngineError::Other(format!("Requires an integer between 2 and {MAX_COPY_ITEMS}.")))?;
// Not AutoCAD's: the copies (items after the first, times the objects) stay within
// ARRAY's own limit, whatever MAXARRAY says, so a large selection can't run out of
// memory.
let copies = u64::from(n - 1).saturating_mul(u64::try_from(self.objs.len()).unwrap_or(u64::MAX));
if copies > cadcraft_doc::MAX_ARRAY_ITEMS {
return Err(EngineError::Other(format!(
"The array would create {copies} objects; the limit is {}. Use fewer items or select fewer objects.",
cadcraft_doc::MAX_ARRAY_ITEMS
)));
}
self.copy_array = CopyArray::Items { n, fit: false };
return Ok(Step::Continue);
}
(CopyArray::Items { n, fit }, Input::Keyword(kw)) if kw == if fit { "Array" } else { "Fit" } => {
self.copy_array = CopyArray::Items { n, fit: !fit };
return Ok(Step::Continue);
}
(CopyArray::Items { n, fit }, i @ (Input::Point(_) | Input::Enter)) => {
let p = if let Input::Point(p) = i { p } else { base };
let step = if fit { (p - base) * (1.0 / f64::from(n - 1)) } else { p - base };
self.copy_array = CopyArray::Off;
let mut made = Vec::new();
for k in 1..n {
match transform_entities(s, &self.objs, &Mat3::translate(step * f64::from(k)), true) {
Ok(hs) => made.extend(hs),
Err(e) => {
// The items made so far are a placement Undo takes back.
self.copies.push(made);
return Err(e);
}
}
}
made
}
(CopyArray::Off, Input::Keyword(kw)) if kw == "Array" => {
self.copy_array = CopyArray::Count;
return Ok(Step::Continue);
}
(CopyArray::Off, Input::Keyword(kw)) if kw == "Undo" => {
if let Some(last) = self.copies.pop() {
let d = s.doc_mut()?;
for h in last {
d.remove_entity(h);
}
if self.copies.is_empty() {
s.echo("Command has been completely undone.");
}
}
return Ok(Step::Continue);
}
(CopyArray::Off, Input::Keyword(kw)) if kw == "Exit" => return self.copy_done(s),
(CopyArray::Off, Input::Enter) if !self.copies.is_empty() => return self.copy_done(s),
(CopyArray::Off, Input::Enter) => {
transform_entities(s, &self.objs, &Mat3::translate(base), true)?;
return self.copy_done(s);
}
(CopyArray::Off, Input::Point(p)) => transform_entities(s, &self.objs, &Mat3::translate(p - base), true)?,
_ => return Ok(Step::Continue),
};
self.copies.push(placed);
if self.copy_single {
return self.copy_done(s);
}
Ok(Step::Continue)
}
fn copy_done(&mut self, s: &mut Session) -> Result<Step> {
s.set_selection(Vec::new());
Ok(Step::Done)
}
/// JOIN the selected objects and report what they became. Arcs that make a circle ask first,
/// as AutoCAD 2024 does.
fn join_now(&mut self, s: &mut Session) -> Result<Step> {
if join_makes_circle(s, &self.objs) {
self.ask_circle = true;
return Ok(Step::Continue);
}
self.join_apply(s)
}
fn join_apply(&mut self, s: &mut Session) -> Result<Step> {
match join(s, &self.objs) {
Ok(h) => {
// Objects outside the joined chain are kept, so count only the ones JOIN consumed
@@ -95,6 +230,9 @@ impl SelectThen {
let what = match h.and_then(|h| d.entity(h)).map(|e| &e.kind) {
Some(EntityKind::Spline(_)) => "spline",
Some(EntityKind::Ellipse(_)) => "ellipse",
Some(EntityKind::Line(_)) => "line",
Some(EntityKind::Arc(_)) => "arc",
Some(EntityKind::Circle(_)) => "circle",
_ => "polyline",
};
s.echo(format!("{n} objects joined into 1 {what}"))
@@ -308,6 +446,9 @@ impl Interactive for SelectThen {
if self.ask_erase {
return Prompt::new("Erase source objects?", Accept::TEXT).kw(&["Yes", "No"]).default("No");
}
if self.ask_circle {
return Prompt::new("Combined arc segments form a circle. Convert to circle?", crate::cmd::curves::KW).kw(&["Yes", "No"]).default("Yes");
}
if let Some(src) = self.join_source {
let ellipse = s.doc().is_ok_and(|d| matches!(d.entity(src).map(|e| &e.kind), Some(EntityKind::Ellipse(_))));
let msg = if ellipse { "Select elliptical arcs to join to source" } else { "Select arcs to join to source" };
@@ -328,7 +469,7 @@ impl Interactive for SelectThen {
match (self.op, k) {
(Op::Move | Op::Copy, 0) => Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]),
(Op::Move, _) => Prompt::new("Specify second point or <use first point as displacement>", Accept::POINT).base_opt(base),
(Op::Copy, _) => Prompt::new("Specify second point", Accept::POINT).kw(&["Array", "Exit", "Undo"]).base_opt(base),
(Op::Copy, _) => self.copy_prompt(base),
(Op::Rotate | Op::Scale, 0) => Prompt::new("Specify base point", Accept::POINT),
// ROTATE and SCALE offer the angle/factor used last time.
(Op::Rotate, _) => {
@@ -361,6 +502,14 @@ impl Interactive for SelectThen {
}
}
}
// No leaves every arc as it is (AutoCAD 2024, measured).
if self.ask_circle {
return match &i {
Input::Keyword(k) if k == "No" => Ok(Step::Done),
Input::Keyword(_) | Input::Enter => self.join_apply(s),
_ => Err(EngineError::Other("Invalid option keyword.".into())),
};
}
if let Some(src) = self.join_source {
return self.join_source_input(s, src, i);
}
@@ -388,10 +537,6 @@ impl Interactive for SelectThen {
self.reference = true;
Ok(Step::Continue)
}
(Op::Copy, _, Input::Keyword(kw)) if kw == "Exit" => {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(_, 0, Input::Point(p)) => {
self.pts.push(p);
Ok(Step::Continue)
@@ -408,15 +553,7 @@ impl Interactive for SelectThen {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(Op::Copy, _, Input::Point(p)) => {
let d = p - self.pts[0];
transform_entities(s, &self.objs, &Mat3::translate(d), true)?;
Ok(Step::Continue)
}
(Op::Copy, _, Input::Enter) => {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(Op::Copy, _, i) => self.copy_input(s, i),
(Op::Rotate, 1, inp @ (Input::Point(_) | Input::Text(_) | Input::Enter)) => {
let a = match inp {
Input::Point(p) => self.pts[0].angle_to(p),
@@ -542,11 +679,13 @@ impl Interactive for SelectThen {
pub(super) struct DisplaceM {
inner: SelectThen,
displacement: bool,
/// COPY's mOde option: asking Single or Multiple.
ask_mode: bool,
}
impl DisplaceM {
pub(super) fn new(op: Op) -> Self {
DisplaceM { inner: SelectThen::new(op), displacement: false }
DisplaceM { inner: SelectThen::new(op), displacement: false, ask_mode: false }
}
/// At "Specify base point": objects selected, no point yet.
fn at_base(&self) -> bool {
@@ -559,14 +698,26 @@ impl Interactive for DisplaceM {
self.inner.name()
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.inner.copy_single = self.inner.op == Op::Copy && s.settings.copymode;
self.inner.begin(s)
}
fn prompt(&self, s: &Session) -> Prompt {
if self.displacement {
return Prompt::new("Specify displacement", Accept::POINT).default("0,0");
}
if self.ask_mode {
let current = if s.settings.copymode { "Single" } else { "Multiple" };
return Prompt::new("Enter a copy mode option", crate::cmd::curves::KW).kw(&["Single", "Multiple"]).default(current);
}
if self.at_base() {
return Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]).default("Displacement");
// COPY: mOde sets COPYMODE; Multiple, offered while it is single, copies until Exit
// this once.
let kw: &[&str] = match self.inner.op {
Op::Copy if self.inner.copy_single => &["Displacement", "mOde", "Multiple"],
Op::Copy => &["Displacement", "mOde"],
_ => &["Displacement"],
};
return Prompt::new("Specify base point", Accept::POINT).kw(kw).default("Displacement");
}
self.inner.prompt(s)
}
@@ -583,10 +734,34 @@ impl Interactive for DisplaceM {
s.set_selection(Vec::new());
return Ok(Step::Done);
}
if self.ask_mode {
match &i {
Input::Keyword(k) if k == "Single" || k == "Multiple" => s.settings.copymode = k == "Single",
Input::Enter => {}
_ => return Ok(Step::Continue),
}
// The mode shown is the mode this COPY runs in, Enter keeping it.
self.inner.copy_single = s.settings.copymode;
self.ask_mode = false;
return Ok(Step::Continue);
}
if self.at_base() && (matches!(&i, Input::Enter) || matches!(&i, Input::Keyword(k) if k == "Displacement")) {
self.displacement = true;
return Ok(Step::Continue);
}
if self.at_base() && self.inner.op == Op::Copy {
match &i {
Input::Keyword(k) if k == "mOde" => {
self.ask_mode = true;
return Ok(Step::Continue);
}
Input::Keyword(k) if k == "Multiple" => {
self.inner.copy_single = false;
return Ok(Step::Continue);
}
_ => {}
}
}
self.inner.input(s, i)
}
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
+55 -4
View File
@@ -3,6 +3,7 @@ use super::{
Accept, Entity, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelectKind, SelectMode, Session, Step, Value, Vec2, bad, json,
line, points_param,
};
use cadcraft_geom::Arc;
/// An area whose vertices STRETCH moves: a window's box, or a polygon closed back to its first
/// point.
@@ -40,6 +41,18 @@ fn add_mline_vertex_hits(s: &Session, area: &StretchArea, hs: &mut Vec<Handle>)
}
}
/// The bulge that keeps an arc's height (bulge × chord / 2) when its chord changes length; none
/// once the chord collapses to a point, which has no arc left to keep.
fn keep_height(bulge: f64, old_chord: f64, new_chord: f64) -> f64 {
if new_chord.is_nan() || new_chord <= 1e-12 {
0.0
} else if old_chord.is_finite() {
bulge * old_chord / new_chord
} else {
bulge
}
}
/// Move the vertices of `e` that lie inside any of the areas `wins` by `d` (STRETCH).
fn stretch_entity(e: &mut Entity, wins: &[StretchArea], d: Vec2) {
let inside = |p: Vec2| wins.iter().any(|a| a.contains(p));
@@ -55,18 +68,56 @@ fn stretch_entity(e: &mut Entity, wins: &[StretchArea], d: Vec2) {
mv(&mut l.b);
}
EntityKind::LwPolyline(pl) => {
let old: Vec<Vec2> = pl.vertices.iter().map(|v| v.p).collect();
for v in &mut pl.vertices {
if inside(v.p) {
v.p += d;
}
}
// An arc segment keeps its height (bulge × chord / 2) as its ends move, as in AutoCAD.
let n = pl.vertices.len();
let segs = if pl.closed { n } else { n.saturating_sub(1) };
for i in 0..segs {
let j = (i + 1) % n;
let (Some(a0), Some(b0), Some(b1)) = (old.get(i), old.get(j), pl.vertices.get(j).map(|v| v.p)) else { continue };
if let Some(v) = pl.vertices.get_mut(i)
&& v.bulge != 0.0
{
v.bulge = keep_height(v.bulge, a0.dist(*b0), v.p.dist(b1));
}
}
}
EntityKind::MLine(m) => m.vertices.iter_mut().for_each(|v| mv(&mut v.p)),
EntityKind::Arc(a) => {
// Arcs keep their shape: move when the centre is inside.
if inside(a.center.xy()) {
a.center.x += d.x;
a.center.y += d.y;
// AutoCAD moves the ends inside the area and keeps the arc's height (bulge × chord / 2);
// the centre alone moves nothing. An end stretched onto the other leaves the arc as it
// was: AutoCAD collapses it into a zero-radius arc at that point (radius 6e-16, start
// 180°, end 0°), an object nothing can draw or pick, which CADCraft does not make.
let g = Arc::new(a.center.xy(), a.radius, a.start, a.end);
let (s0, e0) = (g.start_point(), g.end_point());
let (s_in, e_in) = (inside(s0), inside(e0));
let (s1, e1) = (if s_in { s0 + d } else { s0 }, if e_in { e0 + d } else { e0 });
if s_in && e_in {
// Both ends move: the arc moves whole (a full sweep has no chord to rebuild from).
(a.center.x, a.center.y) = (a.center.x + d.x, a.center.y + d.y);
} else if (s_in || e_in)
&& let Some((r, _)) =
cadcraft_geom::bulge_to_arc(s1, e1, keep_height(cadcraft_geom::arc_to_bulge(g.sweep()), s0.dist(e0), s1.dist(e1)))
{
(a.center.x, a.center.y) = (r.center.x, r.center.y);
(a.radius, a.start, a.end) = (r.radius, r.start, r.end);
}
}
// Control points inside the area move (AutoCAD).
EntityKind::Spline(sp) if sp.fit.is_empty() => sp.control.iter_mut().filter(|p| inside(**p)).for_each(|p| *p += d),
// A spline built from fit points: the fit points inside the area move and it is fitted
// through them again, its fit data kept (AutoCAD 2024). All of them inside, it moves.
EntityKind::Spline(sp) => {
if sp.fit.iter().all(|p| inside(*p)) {
sp.transform(&Mat3::translate(d));
} else if sp.fit.iter().any(|p| inside(*p)) {
let fit: Vec<Vec2> = sp.fit.iter().map(|p| if inside(*p) { *p + d } else { *p }).collect();
*sp = sp.refit(&fit, sp.closed);
}
}
EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(mv),
+44 -2
View File
@@ -4,7 +4,8 @@
use cadcraft_doc::{Common, Entity, EntityKind, Handle, LwPolyline, MAX_BLOCK_DEPTH, Space};
use cadcraft_geom::{
Arc, Ellipse, Line, Mat3, PolyVertex, Polyline, Segment, Spline, TAU, Vec2, ccw_sweep, intersect_ext, line_circle, line_line_infinite, norm_angle,
Arc, Ellipse, Line, Mat3, PolyVertex, Polyline, Segment, Spline, TAU, Vec2, Vec3, ccw_sweep, intersect_ext, line_circle, line_line_infinite,
norm_angle,
};
use serde_json::{Value, json};
@@ -39,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
.params(
"{handle, option: close|open|join|reverse|refit|purge|polyline|move|fitmove|fitadd|fitdelete|kink|tangents|tolerance|vertexadd|vertexmove|vertexdelete|weight|elevate, \
handles2? (join), fit?, index?, to?, before?: bool (fitadd), at? (kink, vertexadd), start?, end? (tangent directions; null = default), tolerance?, weight?, \
order? (elevate), precision?}",
order? (elevate), precision?: 0..99 (polyline, default 10)}",
)
.interactive(|_| Ok(Box::new(SplineditM::default()))),
CommandSpec::new("lengthen", "Lengthen", run_lengthen)
@@ -122,6 +123,47 @@ pub(crate) fn as_lwpoly(k: &EntityKind) -> Option<LwPolyline> {
}
}
/// The polyline PEDIT turns a line or an arc into, and the normal it faces, as AutoCAD 2024 makes
/// them (measured): facing the way the arc faces, and up for a line whatever its normal; at the
/// line's height, or at the arc's centre height measured along its normal (a mirrored arc whose
/// centre is at world Z -5 gives elevation 5, one at Z 5 elevation -5); the thickness stays the
/// object's. A sloped line still comes out at elevation 0: AutoCAD makes a polyline in the line's
/// vertical plane, which a CADCraft polyline can't be. An arc in a tilted plane (normal neither up
/// nor down Z), which CADCraft keeps only approximately, keeps its normal and goes by the sign of
/// its Z as above; AutoCAD's result for one isn't measured. A polyline is returned as it is.
pub(crate) fn polyline_of(e: &Entity) -> Option<(LwPolyline, Vec3)> {
let mut pl = as_lwpoly(&e.kind)?;
let normal = e.common.extrusion;
match &e.kind {
EntityKind::Line(l) => {
if (l.a.z - l.b.z).abs() < 1e-9 {
pl.elevation = l.a.z;
}
Some((pl, Vec3::Z))
}
// The arc's centre is in world coordinates; a polyline's elevation runs along its normal.
// A mirrored arc runs clockwise in plan, and so does its polyline (AutoCAD 2024 starts it
// at the arc's start in the arc's own coordinates).
EntityKind::Arc(a) => {
pl.elevation = if normal.z < 0.0 { -a.center.z } else { a.center.z };
if normal.z < 0.0 {
pl.vertices = curves::reverse_vertices(&pl.vertices, false);
}
Some((pl, normal))
}
_ => Some((pl, normal)),
}
}
/// Puts the polyline `pl`, facing `normal`, in place of the object `h`.
fn set_polyline(s: &mut Session, h: Handle, pl: LwPolyline, normal: Vec3) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
e.kind = EntityKind::LwPolyline(pl);
e.common.extrusion = normal;
})?;
Ok(())
}
mod pedit_multi;
mod pedit_vertex;
+25 -6
View File
@@ -1,6 +1,6 @@
use super::{
Accept, Chain, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Value, bad, bool_or, curves, json,
number, other, targets,
other, targets,
};
// =====================================================================================
@@ -26,7 +26,13 @@ pub(crate) fn arraypath(
return Err(other("Select objects to array."));
}
let (n, step) = match (count, spacing) {
(_, Some(sp)) if sp.is_finite() && sp > 0.0 => (((l / sp).floor() as usize).saturating_add(1), sp),
// As AutoCAD 2024 fills a path by distance: floor(length / spacing) items on a closed path,
// so none lands on or near the first where the path closes, and one more, at the end, on
// an open one (measured). The 1e-9 lets a length that comes out a hair short still fit.
(_, Some(sp)) if sp.is_finite() && sp > 0.0 => {
let fit = (l / sp + 1e-9).floor() as usize;
(if c.closed { fit.max(1) } else { fit.saturating_add(1) }, sp)
}
(Some(n), _) => {
let n = n.max(1);
(n, if c.closed { l / n as f64 } else { l / (n.max(2) - 1) as f64 })
@@ -61,12 +67,25 @@ pub(crate) fn arraypath(
pub(super) fn run_arraypath(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let path = curves::handle_param(p, "path").ok_or_else(|| bad("arraypath", "`path` (handle) is required"))?;
let count = p.get("count").and_then(Value::as_u64).map(|n| usize::try_from(n).unwrap_or(usize::MAX));
let spacing = p.get("spacing").and_then(Value::as_f64);
let r = arraypath(s, &hs, path, count, spacing, bool_or(p, "align", true))?;
// As in the other arrays' JSON forms, a value that isn't a whole number of at least 1 (or a
// positive spacing) is refused, not ignored; missing or null is the default.
let count = crate::cmd::array::count_or("arraypath", p, "count", 6)?;
let spacing = crate::cmd::size_param("arraypath", p, "spacing", false)?;
let r = arraypath(s, &hs, path, Some(usize::try_from(count).unwrap_or(usize::MAX)), spacing, bool_or(p, "align", true))?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
/// The number of items typed at ARRAYPATH's prompt: a whole number from 1 to 32767, written in
/// plain decimals. AutoCAD 2024 takes 5, +5, 05, 5., 5.0, 5.00 and +5.0 there, and refuses 4.5,
/// 1e1, 8/2, 3', 0 and 32768 (measured).
pub(super) fn item_count(t: &str) -> Option<usize> {
let t = t.trim();
let digits = t.strip_prefix('+').unwrap_or(t);
let (whole, fraction) = digits.split_once('.').unwrap_or((digits, ""));
let plain = !whole.is_empty() && whole.bytes().all(|b| b.is_ascii_digit()) && fraction.bytes().all(|b| b == b'0');
whole.parse::<usize>().ok().filter(|n| plain && (1..=32_767).contains(n))
}
#[derive(Default)]
pub(in crate::cmd) struct PathArrayM {
sel: SelectPhase,
@@ -121,7 +140,7 @@ impl Interactive for PathArrayM {
}
(Some(path), inp @ (Input::Text(_) | Input::Enter)) => {
let n = match &inp {
Input::Text(t) => number(t).filter(|n| *n >= 1.0).ok_or_else(|| other("Requires a count of 1 or more."))? as usize,
Input::Text(t) => item_count(t).ok_or_else(|| other("Requires an integer between 1 and 32767."))?,
_ => 6,
};
arraypath(s, &self.objs, path, Some(n), None, true)?;
+99 -29
View File
@@ -1,7 +1,7 @@
use super::{
Accept, Chain, EntityKind, Handle, Input, Interactive, LwPolyline, MAX_GEN, PolyVertex, Prompt, Result, SelOutcome, SelectPhase, Session, Spline,
Step, Value, Vec2, as_lwpoly, bad, bool_or, curves, f64_or, f64_req, json, line, number, other, pedit_vertex, point_req, set_kind, str_param,
targets,
Accept, Chain, Entity, EntityKind, Handle, Input, Interactive, LwPolyline, MAX_GEN, PolyVertex, Prompt, Result, SelOutcome, SelectPhase, Session,
Spline, Step, Value, Vec2, Vec3, as_lwpoly, bad, bool_or, curves, f64_or, f64_req, json, line, number, other, pedit_vertex, point_req,
polyline_of, set_kind, set_polyline, str_param, targets,
};
/// Fit curve: a tangent-continuous pair of arcs (biarc) per segment through every vertex,
@@ -106,7 +106,21 @@ pub(crate) fn spline_vertices(vs: &[PolyVertex], closed: bool, segs: usize) -> V
}
/// Join connected lines/arcs/open polylines onto the ends of polyline `h` (kept in place).
pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f64) -> Result<usize> {
///
/// As AutoCAD 2024 joins (measured), none facing the other way: an arc or a polyline whose normal
/// points down Z where the polyline's points up, or the other way round; a line counts as facing
/// up. Multiple's Join (`same_height` false) takes them at any height (lines at Z 5 and Z 0 join).
///
/// PEDIT's own Join takes only objects in one plane with the polyline: the plane the polyline and
/// every line picked share, when they share one, else the polyline's own. So a sloped line joins
/// only when the polyline and all the lines picked lie in one plane (a vertical one for a sloped
/// line continuing a straight polyline in plan), and then no arc or polyline joins, as those lie
/// flat; otherwise only objects at the polyline's height join (a line, arc or polyline at Z 0
/// stays off one at Z 5). Ends meet within `fuzz` in plan and within 1e-6 in height, which `fuzz`
/// doesn't widen. After a sloped line the chain's end is at the line's far end, so the next object
/// meets it there; AutoCAD's polyline then lies in the lines' plane, CADCraft's keeps the source's
/// elevation and runs through the objects' points seen from above.
pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f64, same_height: bool) -> Result<usize> {
let e = curves::entity(s, h)?;
let mut base = as_lwpoly(&e.kind).ok_or_else(|| other("Select a polyline."))?;
if base.closed {
@@ -114,46 +128,88 @@ pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f6
}
let mut chain = Chain::of(&EntityKind::LwPolyline(base.clone())).unwrap_or_default();
let tol = fuzz.max(1e-6);
let mut pool: Vec<(Handle, Chain)> = Vec::new();
for o in others {
if *o == h {
// Which way an object faces, and its two ends' world heights.
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
let heights = |e: &Entity| match &e.kind {
EntityKind::Line(l) => (l.a.z, l.b.z),
// An arc's centre is in world coordinates.
EntityKind::Arc(a) => (a.center.z, a.center.z),
// A polyline's elevation runs along its normal.
EntityKind::LwPolyline(p) => {
let z = if down(e) { -p.elevation } else { p.elevation };
(z, z)
}
_ => (0.0, 0.0),
};
// Two ends meet: in plan within the fuzz distance, and for PEDIT's own Join at the same height.
let at = |p: Vec2, ph: f64, q: Vec2, qh: f64| p.near(q, tol) && (!same_height || (ph - qh).abs() < 1e-6);
let picked: Vec<(Handle, Entity)> = others.iter().filter(|o| **o != h).filter_map(|o| Some((*o, curves::entity(s, *o).ok()?))).collect();
// The plane PEDIT's own Join works in (AutoCAD 2024, measured): the polyline's points, with a
// point off the chord of an arc segment, which lies flat, and the ends of every line picked.
let z0 = heights(&e).0;
let mut pts: Vec<Vec3> = base.vertices.iter().map(|v| Vec3::new(v.p.x, v.p.y, z0)).collect();
if let Some(w) = base.vertices.windows(2).find(|w| w[0].bulge.abs() > 1e-12) {
let (a, b) = (w[0].p, w[1].p);
let off = (a + b) * 0.5 + Vec2::new(a.y - b.y, b.x - a.x);
pts.push(Vec3::new(off.x, off.y, z0));
}
let lines: Vec<(Vec3, Vec3)> =
picked.iter().filter_map(|(_, oe)| if let EntityKind::Line(l) = &oe.kind { Some((l.a, l.b)) } else { None }).collect();
pts.extend(lines.iter().flat_map(|(a, b)| [*a, *b]));
let shared = coplanar(&pts);
// That plane is the polyline's own, flat, when every line is at its height.
let level = lines.iter().all(|(a, b)| (a.z - z0).abs() < 1e-6 && (b.z - z0).abs() < 1e-6);
let mut pool: Vec<(Handle, Chain, (f64, f64))> = Vec::new();
for (o, oe) in &picked {
if down(oe) != down(&e) {
continue;
}
let Ok(oe) = curves::entity(s, *o) else { continue };
let ok = matches!(&oe.kind, EntityKind::Line(_) | EntityKind::Arc(_)) || matches!(&oe.kind, EntityKind::LwPolyline(p) if !p.closed);
let line = matches!(oe.kind, EntityKind::Line(_));
let (ah, bh) = heights(oe);
// A sloped line lies in no flat plane, and an arc or a polyline in no other.
let off_plane = if shared && !level { !line } else { (ah - bh).abs() >= 1e-6 };
if same_height && off_plane {
continue;
}
let ok = line || matches!(&oe.kind, EntityKind::Arc(_)) || matches!(&oe.kind, EntityKind::LwPolyline(p) if !p.closed);
if ok && let Some(c) = Chain::of(&oe.kind) {
pool.push((*o, c));
pool.push((*o, c, (ah, bh)));
}
}
let (mut st_h, mut en_h) = heights(&e);
let mut joined = Vec::new();
while let (Some(st), Some(en)) = (chain.start(), chain.end()) {
let Some(i) = pool
.iter()
.position(|(_, c)| c.start().zip(c.end()).is_some_and(|(a, b)| a.near(en, tol) || b.near(en, tol) || a.near(st, tol) || b.near(st, tol)))
else {
let meets = |c: &Chain, (ah, bh): (f64, f64)| {
c.start().zip(c.end()).is_some_and(|(a, b)| at(a, ah, en, en_h) || at(b, bh, en, en_h) || at(a, ah, st, st_h) || at(b, bh, st, st_h))
};
let Some(i) = pool.iter().position(|(_, c, z)| meets(c, *z)) else {
break;
};
let (oh, c) = pool.remove(i);
let (oh, c, (ah, bh)) = pool.remove(i);
let (Some(a), Some(b)) = (c.start(), c.end()) else { continue };
if a.near(en, tol) {
if at(a, ah, en, en_h) {
chain.segs.extend(c.segs);
} else if b.near(en, tol) {
en_h = bh;
} else if at(b, bh, en, en_h) {
chain.segs.extend(c.reversed().segs);
} else if b.near(st, tol) {
en_h = ah;
} else if at(b, bh, st, st_h) {
let mut v = c.segs;
v.extend(chain.segs);
chain.segs = v;
st_h = ah;
} else {
let mut v = c.reversed().segs;
v.extend(chain.segs);
chain.segs = v;
st_h = bh;
}
joined.push(oh);
}
if joined.is_empty() {
return Ok(0);
}
chain.closed = chain.start().zip(chain.end()).is_some_and(|(a, b)| a.near(b, tol)) && chain.segs.len() > 1;
chain.closed = chain.start().zip(chain.end()).is_some_and(|(a, b)| at(a, st_h, b, en_h)) && chain.segs.len() > 1;
base.vertices = chain.vertices();
base.closed = chain.closed;
let d = s.doc_mut()?;
@@ -164,14 +220,29 @@ pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f6
Ok(joined.len())
}
/// Whether the points `pts` lie in one plane, to within 1e-6 (points in a line always do).
fn coplanar(pts: &[Vec3]) -> bool {
let Some(&p0) = pts.first() else { return true };
let far = |a: &&Vec3, b: &&Vec3| (**a - p0).len().total_cmp(&(**b - p0).len());
let Some(&p1) = pts.iter().max_by(far) else { return true };
let d = p1 - p0;
// The normal from the point farthest off the line p0 p1, for the least rounding.
let Some(n) = pts.iter().map(|p| d.cross(*p - p0)).max_by(|a, b| a.len().total_cmp(&b.len())) else { return true };
if n.len() <= 1e-6 * d.len() {
return true;
}
let n = n.normalized();
pts.iter().all(|p| n.dot(*p - p0).abs() < 1e-6)
}
pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> Result<Value> {
let e = curves::entity(s, h)?;
if curves::is_locked(s, h) {
return Err(other("The object is on a locked layer."));
}
let mut pl = match &e.kind {
EntityKind::LwPolyline(pl) => pl.clone(),
EntityKind::Line(_) | EntityKind::Arc(_) if bool_or(p, "convert", true) => as_lwpoly(&e.kind).ok_or_else(|| other("Cannot convert."))?,
let (mut pl, normal) = match &e.kind {
EntityKind::LwPolyline(pl) => (pl.clone(), e.common.extrusion),
EntityKind::Line(_) | EntityKind::Arc(_) if bool_or(p, "convert", true) => polyline_of(&e).ok_or_else(|| other("Cannot convert."))?,
_ => return Err(other("Object selected is not a polyline.")),
};
match opt {
@@ -197,14 +268,14 @@ pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> R
"reverse" | "r" => pl.vertices = curves::reverse_vertices(&pl.vertices, pl.closed),
"ltypegen" | "l" => pl.plinegen = bool_or(p, "on", !pl.plinegen),
"join" | "j" => {
set_kind(s, h, EntityKind::LwPolyline(pl))?;
set_polyline(s, h, pl, normal)?;
let others: Vec<Handle> = p
.get("handles2")
.or_else(|| p.get("join"))
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(curves::handle_value).collect())
.unwrap_or_default();
let n = pedit_join(s, h, &others, f64_or(p, "fuzz", 0.0))?;
let n = pedit_join(s, h, &others, f64_or(p, "fuzz", 0.0), true)?;
return Ok(json!({ "handle": h.hex(), "joined": n }));
}
"vertex" | "e" => {
@@ -254,7 +325,7 @@ pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> R
}
_ => return Err(bad("pedit", "unknown option")),
}
set_kind(s, h, EntityKind::LwPolyline(pl))?;
set_polyline(s, h, pl, normal)?;
Ok(json!({ "handle": h.hex() }))
}
@@ -468,10 +539,9 @@ impl Interactive for PeditM {
return Ok(Step::Done);
}
let h = self.h.ok_or_else(|| other("No object."))?;
let k = curves::entity(s, h)?.kind;
let pl = as_lwpoly(&k).ok_or_else(|| other("Cannot convert."))?;
let (pl, normal) = polyline_of(&curves::entity(s, h)?).ok_or_else(|| other("Cannot convert."))?;
self.original = Some(pl.vertices.clone());
set_kind(s, h, EntityKind::LwPolyline(pl))?;
set_polyline(s, h, pl, normal)?;
self.phase = PPhase::Main;
Ok(Step::Continue)
}
@@ -544,7 +614,7 @@ impl Interactive for PeditM {
SelOutcome::Done(hs) => {
let h = self.h.ok_or_else(|| other("No polyline."))?;
self.snapshot(s);
let n = pedit_join(s, h, &hs, 0.0)?;
let n = pedit_join(s, h, &hs, 0.0, true)?;
s.echo(format!("{n} segments added to polyline"));
s.set_selection(vec![h]);
self.phase = PPhase::Main;
+7 -7
View File
@@ -8,7 +8,7 @@ use serde_json::json;
use super::super::curves;
use super::super::machines::{SelOutcome, SelectPhase, number};
use super::pedit::{PPhase, PeditM, clear_widths, pedit_apply, pedit_join, yes_no};
use super::{as_lwpoly, other, set_kind};
use super::{other, polyline_of, set_kind, set_polyline};
use crate::{Accept, Input, Prompt, Result, Session, Step};
/// Most option steps Undo can take back.
@@ -78,13 +78,13 @@ impl PeditM {
let no = !yes_no(&i)?;
let mut kept = Vec::new();
for h in std::mem::take(&mut self.multi) {
let kind = curves::entity(s, h)?.kind;
match kind {
let e = curves::entity(s, h)?;
match e.kind {
EntityKind::LwPolyline(_) => kept.push(h),
_ if no => {}
k => {
if let Some(pl) = as_lwpoly(&k) {
set_kind(s, h, EntityKind::LwPolyline(pl))?;
_ => {
if let Some((pl, normal)) = polyline_of(&e) {
set_polyline(s, h, pl, normal)?;
kept.push(h);
}
}
@@ -219,7 +219,7 @@ impl PeditM {
let open = matches!(curves::entity(s, h)?.kind, EntityKind::LwPolyline(p) if !p.closed);
if open {
// A polyline that took on segments no longer goes back past the Join on Decurve.
if pedit_join(s, h, &rest, fuzz)? > 0 {
if pedit_join(s, h, &rest, fuzz, false)? > 0 {
self.morig.remove(&h);
}
rest.retain(|o| s.doc().is_ok_and(|d| d.entity(*o).is_some()));
+51 -25
View File
@@ -61,8 +61,11 @@ fn edit(sp: &Spline, opt: &str, p: &Value) -> Result<EntityKind> {
spline(sp.refit(&fit, sp.closed))
}
"polyline" => {
let precision = p.get("precision").and_then(Value::as_u64).unwrap_or(10).min(99) as usize;
Ok(EntityKind::LwPolyline(spline_to_poly(sp, precision)))
let precision = match p.get("precision") {
None | Some(Value::Null) => 10,
Some(v) => v.as_u64().filter(|n| *n <= 99).ok_or_else(|| bad("splinedit", "`precision` must be a whole number from 0 to 99"))?,
};
Ok(EntityKind::LwPolyline(spline_to_poly(sp, precision as usize)))
}
"move" => {
let (i, to) = (index(p)?, point_req("splinedit", p, "to")?);
@@ -96,7 +99,9 @@ fn spline_close(sp: &Spline) -> Spline {
return sp.clone();
}
let mut out = if sp.fit.len() >= 2 {
sp.refit(&sp.fit, true)
// The open ends' tangents don't carry over: the closed curve takes its own where it closes.
let opts = cadcraft_geom::FitOptions { start_tangent: None, end_tangent: None, ..sp.fit_opts };
Spline::fit_with_end_derivatives(&sp.fit, true, opts)
} else {
let mut c = sp.control.clone();
c.extend(sp.control.first().copied());
@@ -235,11 +240,11 @@ fn tolerance(sp: &Spline, tol: f64) -> Result<Spline> {
// ---------------- control points ----------------
/// The number of distinct control points: a periodic spline repeats its first `degree` at the
/// end, and a clamped closed one repeats its first at the end.
/// The number of distinct control points: control points that wrap round repeat their first
/// `degree` at the end, and a clamped closed spline repeats its first at the end.
fn distinct(sp: &Spline) -> usize {
let n = sp.control.len();
if sp.is_periodic() {
if sp.wraps() {
n.saturating_sub(sp.degree)
} else if sp.closed && n > 2 && sp.control.first().zip(sp.control.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) {
n - 1
@@ -311,7 +316,7 @@ fn delete_control(sp: &Spline, j: usize) -> Result<Spline> {
}
let mut s = without_fit(sp.clone());
let w = |s: &Spline, i: usize| s.weights.get(i).copied().unwrap_or(1.0);
if sp.is_periodic() {
if sp.wraps() {
if u <= p + 1 {
return Err(other(format!("A closed spline of degree {p} needs more than {} control points.", p + 1)));
}
@@ -379,22 +384,30 @@ fn join(s: &mut Session, h: Handle, sp: &Spline, others: &[Handle]) -> Result<Ve
}
/// A control point added by inserting a knot where the curve passes nearest `at`; the curve
/// keeps its shape. A periodic spline is clamped at its seam first.
/// keeps its shape. Control points that wrap round are clamped at the seam first.
fn add_control(sp: &Spline, at: Vec2) -> Result<Spline> {
let base = if sp.is_periodic() { sp.clamped().ok_or_else(|| other("Cannot add a control point to this spline."))? } else { sp.clone() };
let base = if sp.wraps() { sp.clamped().ok_or_else(|| other("Cannot add a control point to this spline."))? } else { sp.clone() };
let t = curves::spline_param_of(&base, at);
let mut out = base.insert_knot(t).ok_or_else(|| other("Cannot add a control point to this spline."))?;
out.closed = sp.closed;
Ok(out)
}
/// The highest order Elevate order takes: degree 25 is the most `Spline::elevated` builds, and
/// AutoCAD 2024's limit too.
const MAX_ORDER: u64 = 26;
/// AutoCAD 2024's message for an order it refuses: from the spline's own order to 26 (measured at
/// orders 4 and 5).
fn order_range(sp: &Spline) -> crate::EngineError {
other(format!("Requires an integer between {} and {MAX_ORDER}.", sp.degree as u64 + 1))
}
/// The same curve at a higher order (degree + 1), with more control points.
fn elevate(sp: &Spline, order: u64) -> Result<Spline> {
// Degree 25 is the most `Spline::elevated` builds.
let max = 26;
let current = sp.degree as u64 + 1;
if order < current || order > max {
return Err(other(format!("Requires an order between {current} and {max}.")));
if order < current || order > MAX_ORDER {
return Err(order_range(sp));
}
if order == current {
return Ok(sp.clone());
@@ -585,6 +598,22 @@ impl SplineditM {
}
Ok(())
}
/// Elevate order's "Enter new order": a whole number as typed. AutoCAD 2024 takes +5 and 05
/// and refuses 5.0, 5., 1e1, 4.5, 3, 27 and a point, all with the order range; Enter keeps
/// the order (measured).
fn input_order(&mut self, s: &mut Session, sp: &Spline, input: &Input) -> Result<()> {
if *input != Input::Enter {
let order = match input {
Input::Text(t) => t.trim().parse::<u64>().ok(),
_ => None,
}
.ok_or_else(|| order_range(sp))?;
self.apply(s, json!({ "option": "elevate", "order": order }))?;
}
self.sub = Sub::Vertex;
Ok(())
}
}
impl Interactive for SplineditM {
@@ -673,11 +702,15 @@ impl Interactive for SplineditM {
}
Sub::Join => self.input_join(s, h, &sp, &i)?,
Sub::Precision => {
// A whole number as typed: AutoCAD 2024 takes +5 and 05 and refuses 5.0, 5., 4.5,
// 1e1, 8/2, 100, -1 and a point (measured).
let precision = match &i {
Input::Text(t) => number(t).filter(|n| (0.0..=99.0).contains(n)).ok_or_else(|| other("Requires an integer between 0 and 99."))?,
_ => 10.0,
};
self.apply(s, json!({ "option": "polyline", "precision": precision.round() as u64 }))?;
Input::Text(t) => t.trim().parse::<u64>().ok().filter(|n| *n <= 99),
Input::Enter => Some(10),
_ => None,
}
.ok_or_else(|| other("Requires an integer between 0 and 99."))?;
self.apply(s, json!({ "option": "polyline", "precision": precision }))?;
s.set_selection(Vec::new());
return Ok(Step::Done);
}
@@ -784,14 +817,7 @@ impl Interactive for SplineditM {
None if enter => self.sub = Sub::Vertex,
None => {}
},
Sub::VertexOrder => {
if let Input::Text(t) = &i {
let order =
number(t).filter(|o| o.fract() == 0.0 && *o >= 1.0 && *o <= 1000.0).ok_or_else(|| other("Requires a whole number."))?;
self.apply(s, json!({ "option": "elevate", "order": order as u64 }))?;
}
self.sub = Sub::Vertex;
}
Sub::VertexOrder => self.input_order(s, &sp, &i)?,
Sub::VertexDelete => match point {
Some(p) => {
let u = distinct(&sp);
+212
View File
@@ -639,6 +639,32 @@ fn arraypath_json_and_command_line() {
assert!(matches!(last(&s), EntityKind::Line(l) if near(l.a.xy(), -5.0, 20.0) && near(l.b.xy(), -6.0, 20.0)));
assert!(s.execute("arraypath", &json!({"handles": [dot], "path": dot})).is_err());
// By spacing, AutoCAD 2024 fills a closed path with floor(length / spacing) items and an open
// one with one more, at the end (measured on a 100 square and on the same square open).
let square = [[0, 0], [100, 0], [100, 100], [0, 100]];
let r400 = 400.0 / std::f64::consts::TAU;
for (closed, spacing, items) in
[(true, 100, 4), (true, 30, 13), (true, 200, 2), (true, 400, 1), (true, 399, 1), (false, 100, 4), (false, 30, 11), (false, 300, 2)]
{
let mut s = Session::new();
let dot = h(&s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap());
let path = h(&s.execute("pline", &json!({"points": square, "closed": closed})).unwrap());
let r = s.execute("arraypath", &json!({"handles": [dot], "path": path, "spacing": spacing})).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(items - 1), "closed {closed}, spacing {spacing}");
}
// A circle 400 round: 4 items at 100, none on the first (AutoCAD 2024, measured).
let mut s = Session::new();
let dot = h(&s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap());
let path = h(&s.execute("circle", &json!({"center": [0, r400], "radius": r400})).unwrap());
let r = s.execute("arraypath", &json!({"handles": [dot], "path": path, "spacing": 100})).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(3));
// Three sides of 0.35 add up to a hair under 3 × 0.35; the item at the end still fits.
let mut s = Session::new();
let dot = h(&s.execute("circle", &json!({"center": [0, 0], "radius": 0.01})).unwrap());
let path = h(&s.execute("pline", &json!({"points": [[0, 0], [0.35, 0], [0.35, 0.35], [0, 0.35]]})).unwrap());
let r = s.execute("arraypath", &json!({"handles": [dot], "path": path, "spacing": 0.35})).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(3));
let mut s = Session::new();
s.execute("circle", &json!({"center": [0, 1], "radius": 0.25})).unwrap();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
@@ -649,6 +675,40 @@ fn arraypath_json_and_command_line() {
assert_eq!(s.doc().unwrap().model.len(), 4);
}
#[test]
fn arraypath_item_count_as_autocad_takes_it() {
// AutoCAD 2024 at "Enter number of items along path": a whole number from 1 to 32767 in plain
// decimals, 5. and 5.0 included; 4.5, 1e1, 8/2, 3', 0 and 32768 are refused.
let mut s = Session::new();
s.execute("circle", &json!({"center": [0, 1], "radius": 0.25})).unwrap();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.cmdline("arraypath 0.25,1").unwrap();
s.cmdline("").unwrap();
s.cmdline("5,0").unwrap();
let asked = s.prompt_text();
// Measured, then texts that aren't plain whole numbers (not measured).
for t in ["4.5", "1e1", "8/2", "3'", "0", "32768", "+", ".5", "5.0.0", "5.1"] {
s.cmdline(t).unwrap();
assert_eq!(s.log.last().map(String::as_str), Some("Requires an integer between 1 and 32767."), "{t}");
assert_eq!(s.prompt_text(), asked, "{t}");
}
s.cmdline("3").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
// The ends of the range, without drawing 32,767 copies.
assert_eq!((super::patharray::item_count("1"), super::patharray::item_count("32767")), (Some(1), Some(32_767)));
for (typed, items) in [("5", 5), ("5.", 5), ("5.0", 5), ("5.00", 5), ("05.0", 5), ("+5.0", 5), ("05", 5), ("+4", 4), ("1", 1)] {
let mut s = Session::new();
s.execute("circle", &json!({"center": [0, 1], "radius": 0.25})).unwrap();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
for t in ["arraypath 0.25,1", "", "5,0", typed] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none(), "{typed}: {}", s.prompt_text());
// The path and the items (the original is the first).
assert_eq!(s.doc().unwrap().model.len(), 1 + items, "{typed}");
}
}
#[test]
fn textedit_json_and_command_line() {
let mut s = Session::new();
@@ -777,3 +837,155 @@ fn offset_elliptical_arc_follows_picked_side() {
let outer = max_x(json!([20, 20]));
assert!((outer - 11.0).abs() < 0.05, "outer side went inward: max x = {outer}");
}
/// STRETCH against what AutoCAD 2024 stores for the same crossing window and displacement (5, 3)
/// (black-box: synthetic objects in accoreconsole, read back with `entget`): the ends of an arc
/// that are inside move and the arc keeps its height (bulge × chord / 2), as does a polyline arc
/// segment; the centre alone moves nothing; a spline's control points inside move.
#[test]
fn stretch_arcs_bulges_and_splines_match_autocad() {
enum Want {
Arc([f64; 2], f64, f64, f64),
Bulges(&'static [f64]),
Control(&'static [[f64; 2]]),
}
// ((seed command, params), crossing window, what AutoCAD stores)
let cases: Vec<((&str, Value), [[f64; 2]; 2], Want)> = vec![
// SX-ARC-1END: one end of the arc inside.
(
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
[[15.0, -5.0], [30.0, 5.0]],
Want::Arc([3.17984478246544, -2.20611061402141], 22.43262716319083, 0.2342130724507349, 1.713026264953702),
),
// SX2-ARC-ENDPT: the other end inside.
(
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
[[-5.0, 15.0], [5.0, 25.0]],
Want::Arc([1.476584509301813, 4.310815984327269], 19.01841360081773, 6.054532724492258, 1.384456456611818),
),
// SX2-ARC-BIG-END: an arc over 180 degrees, its end inside.
(
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 30.0, "end": 300.0})),
[[5.0, -25.0], [15.0, -12.0]],
Want::Arc([1.341732093243006, -0.7463649967436295], 19.25631435504786, 0.5920576993601167, 5.500876277544912),
),
// SX2-ARC-CEN: only the centre inside: unchanged.
(
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
[[-3.0, -3.0], [16.0, 16.0]],
Want::Arc([0.0, 0.0], 20.0, 0.0, std::f64::consts::FRAC_PI_2),
),
// SX-ARC-ALL: the whole arc inside: moved.
(
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 0.0, "end": 90.0})),
[[-5.0, -5.0], [30.0, 30.0]],
Want::Arc([5.0, 3.0], 20.0, 0.0, std::f64::consts::FRAC_PI_2),
),
// A full-sweep arc (start = end) inside the window: moved whole, though its chord is zero.
(
("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 45.0, "end": 45.0})),
[[-25.0, -25.0], [25.0, 25.0]],
Want::Arc([5.0, 3.0], 20.0, std::f64::consts::FRAC_PI_4, std::f64::consts::FRAC_PI_4),
),
// SX-PLA-V1: the vertex starting an arc segment.
(
(
"pline",
json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": 0.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [60.0, 20.0], "bulge": 0.0}], "closed": false}),
),
[[25.0, -5.0], [35.0, 5.0]],
Want::Bulges(&[0.0, 0.6337751582042422, 0.0, 0.0]),
),
// SX-PLA-V2: the vertex ending an arc segment.
(
(
"pline",
json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": 0.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [60.0, 20.0], "bulge": 0.0}], "closed": false}),
),
[[40.0, 15.0], [50.0, 25.0]],
Want::Bulges(&[0.0, 0.4101116968279916, 0.0, 0.0]),
),
// SX2-PLA-NEG: a negative bulge over 180 degrees.
(
(
"pline",
json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": -1.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [60.0, 20.0], "bulge": 0.0}], "closed": false}),
),
[[40.0, 15.0], [50.0, 25.0]],
Want::Bulges(&[0.0, -1.230335090483974, 0.0, 0.0]),
),
// SX3-SPL-CV-ONLY: a window holding a control point but missing the drawn curve selects
// nothing in AutoCAD ("0 found"), so the spline stays as it was.
(
("spline", json!({"control": [[0.0, 0.0], [10.0, 100.0], [20.0, 100.0], [30.0, 0.0]], "degree": 3})),
[[5.0, 95.0], [15.0, 105.0]],
Want::Control(&[[0.0, 0.0], [10.0, 100.0], [20.0, 100.0], [30.0, 0.0]]),
),
// SX3-SPL-CV-CROSS: the same control point in a window that also crosses the curve moves.
(
("spline", json!({"control": [[0.0, 0.0], [10.0, 100.0], [20.0, 100.0], [30.0, 0.0]], "degree": 3})),
[[5.0, 40.0], [15.0, 105.0]],
Want::Control(&[[0.0, 0.0], [15.0, 103.0], [20.0, 100.0], [30.0, 0.0]]),
),
// SX-SPL: two control points inside.
(
("spline", json!({"control": [[0.0, 0.0], [10.0, 10.0], [20.0, 0.0], [30.0, 10.0]], "degree": 3})),
[[15.0, -5.0], [35.0, 15.0]],
Want::Control(&[[0.0, 0.0], [10.0, 10.0], [25.0, 3.0], [35.0, 13.0]]),
),
];
let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0);
let same_angle = |a: f64, b: f64| {
let d = (a - b).rem_euclid(std::f64::consts::TAU);
d < 1e-9 || std::f64::consts::TAU - d < 1e-9
};
for ((seed, params), window, want) in cases {
let mut s = Session::new();
let hd = h(&s.execute(seed, &params).unwrap());
s.execute("stretch", &json!({"window": window, "delta": [5.0, 3.0]})).unwrap();
match (kind(&s, &hd), want) {
(EntityKind::Arc(a), Want::Arc(c, r, start, end)) => assert!(
same(a.center.x, c[0]) && same(a.center.y, c[1]) && same(a.radius, r) && same_angle(a.start, start) && same_angle(a.end, end),
"{window:?}: {a:?}"
),
(EntityKind::LwPolyline(p), Want::Bulges(want)) => {
let got: Vec<f64> = p.vertices.iter().map(|v| v.bulge).collect();
assert!(got.len() == want.len() && got.iter().zip(want).all(|(a, b)| same(*a, *b)), "{window:?}: {got:?} / {want:?}");
}
(EntityKind::Spline(sp), Want::Control(want)) => {
let ok = sp.control.len() == want.len() && sp.control.iter().zip(want).all(|(p, w)| same(p.x, w[0]) && same(p.y, w[1]));
assert!(ok, "{window:?}: {:?} / {want:?}", sp.control);
}
(k, _) => panic!("{window:?}: {k:?}"),
}
}
// A spline built from fit points: the fit points inside move and it is fitted through them
// again, keeping its fit data; all of them inside, it moves whole (AutoCAD 2024, `entget`
// after STRETCH of a spline stored with these fit points only).
let fit = [[200.0, 0.0], [210.0, 10.0], [220.0, 0.0], [230.0, 10.0]];
let fit_cases: [([[f64; 2]; 2], [f64; 2], [[f64; 2]; 4]); 3] = [
([[225.0, 5.0], [235.0, 15.0]], [5.0, 0.0], [[200.0, 0.0], [210.0, 10.0], [220.0, 0.0], [235.0, 10.0]]),
([[205.0, 5.0], [215.0, 15.0]], [0.0, 5.0], [[200.0, 0.0], [210.0, 15.0], [220.0, 0.0], [230.0, 10.0]]),
([[195.0, -5.0], [235.0, 15.0]], [5.0, 5.0], [[205.0, 5.0], [215.0, 15.0], [225.0, 5.0], [235.0, 15.0]]),
];
for (window, delta, want) in fit_cases {
let mut s = Session::new();
let hd = h(&s.execute("spline", &json!({ "fit": fit })).unwrap());
s.execute("stretch", &json!({ "window": window, "delta": delta })).unwrap();
let EntityKind::Spline(sp) = kind(&s, &hd) else { panic!("not a spline") };
let got: Vec<[f64; 2]> = sp.fit.iter().map(|p| [p.x, p.y]).collect();
assert!(got.len() == 4 && got.iter().zip(want).all(|(g, w)| same(g[0], w[0]) && same(g[1], w[1])), "{window:?}: {got:?}");
// The curve still runs through them.
let (lo, hi) = sp.domain();
for w in want {
let q = cadcraft_geom::Vec2::new(w[0], w[1]);
let near = (0..=4000).map(|i| sp.eval(lo + (hi - lo) * f64::from(i) / 4000.0).dist(q)).fold(f64::INFINITY, f64::min);
assert!(near < 1e-2, "{window:?}: {w:?} is {near} off the curve");
}
}
// A stretch that brings an arc segment's ends together leaves no arc to keep: the bulge goes.
let mut s = Session::new();
let p = pline(&mut s, json!([{"p": [0, 0], "bulge": 0.5}, [10, 0], [20, 0]]), false);
s.execute("stretch", &json!({"window": [[9, -1], [11, 1]], "delta": [-10, 0]})).unwrap();
assert_eq!(poly(&kind(&s, &p)).vertices.iter().map(|v| v.bulge).collect::<Vec<_>>(), [0.0, 0.0, 0.0]);
}
+87 -4
View File
@@ -50,6 +50,7 @@ pub const PROFILE_VARS: &[&str] = &[
"CURSORSIZE",
"PICKFIRST",
"PICKADD",
"COPYMODE",
"PICKDRAG",
"MAXARRAY",
"MEASUREINIT",
@@ -85,18 +86,31 @@ pub fn profile(s: &Session) -> Value {
Value::Object(m)
}
/// The profile variables the drawing keeps in its header rather than in the session's settings.
const DRAWING_VARS: &[&str] = &["SNAPUNIT", "GRIDUNIT"];
/// Set the profile variables named in `values` (an object; other keys are refused). All or
/// nothing: one bad name or value leaves every setting as it was.
/// nothing: one bad name or value leaves every setting, and the drawing, as they were.
pub fn apply(s: &mut Session, values: &Value) -> Result<()> {
let Some(obj) = values.as_object() else { return Err(bad("options", "expected an object of profile variables")) };
let before = s.settings.clone();
// When one of the values is a drawing variable, the drawing as it is: put back whole on a
// refusal, it is the same drawing again, so not marked as changed either.
let touches_drawing = obj.keys().any(|k| DRAWING_VARS.iter().any(|v| v.eq_ignore_ascii_case(k.trim())));
let drawing = if touches_drawing { s.state().ok().map(|st| st.doc.clone()) } else { None };
let put_back = |s: &mut Session| {
s.settings = before.clone();
if let (Some(doc), Ok(st)) = (&drawing, s.state_mut()) {
st.doc = doc.clone();
}
};
for (name, v) in obj {
if !is_profile_var(name) {
s.settings = before;
put_back(s);
return Err(bad("options", format!("{name} is not a profile setting")));
}
if let Err(e) = crate::sysvars::set(s, name, v) {
s.settings = before;
put_back(s);
return Err(bad("options", format!("invalid value for {}: {e}", name.to_ascii_uppercase())));
}
}
@@ -117,7 +131,8 @@ pub fn restore(s: &mut Session, saved: &Value) {
}
}
/// Put every profile variable back to its default.
/// Put every profile variable back to its default, except [`DRAWING_VARS`]: a reset doesn't change
/// the drawing.
pub fn reset(s: &mut Session) {
let d = Settings::default();
let st = &mut s.settings;
@@ -143,8 +158,24 @@ pub fn reset(s: &mut Session) {
st.cursorsize = d.cursorsize;
st.pickfirst = d.pickfirst;
st.pickadd = d.pickadd;
st.copymode = d.copymode;
st.pickdrag = d.pickdrag;
st.maxarray = d.maxarray;
st.dynprompt = d.dynprompt;
st.dyndigrip = d.dyndigrip;
st.dyndivis = d.dyndivis;
st.selectioneffect = d.selectioneffect;
st.selectionpreview = d.selectionpreview;
st.previeweffect = d.previeweffect;
st.previewfilter = d.previewfilter;
st.grips = d.grips;
st.gripobjlimit = d.gripobjlimit;
st.selectionarea = d.selectionarea;
st.windowareacolor = d.windowareacolor;
st.crossingareacolor = d.crossingareacolor;
st.selectionareaopacity = d.selectionareaopacity;
st.pickstyle = d.pickstyle;
st.measureinit = d.measureinit;
}
fn run_options(s: &mut Session, p: &Value) -> Result<Value> {
@@ -191,4 +222,56 @@ mod tests {
restore(&mut b, &saved);
assert_eq!(profile(&b), saved);
}
#[test]
fn a_refused_change_leaves_the_drawings_snap_and_grid_too() {
let mut s = Session::new();
let before = profile(&s);
let refused = [
json!({ "SNAPUNIT": [2, 3], "GRIDUNIT": [4, 5], "WINDOWAREACOLOR": 0 }),
json!({ "GRIDUNIT": [4, 5], "LUNITS": 2 }),
json!({ "WINDOWAREACOLOR": 0 }),
];
for bad_one in refused {
assert!(apply(&mut s, &bad_one).is_err(), "{bad_one}");
assert_eq!(profile(&s), before, "{bad_one}");
// The same drawing, so there is nothing new to save.
assert!(!s.state().unwrap().is_dirty(), "{bad_one}");
}
assert!(s.execute("options", &json!({ "reset": true, "SNAPUNIT": [2, 3], "WINDOWAREACOLOR": 0 })).is_err());
assert_eq!(profile(&s), before);
// The header entries come back exactly: a zero grid spacing (which reads as the snap
// spacing), and a snap spacing the drawing doesn't have. The refused value comes last, so
// both are written first (the keys are taken in name order).
let header = |s: &Session, n: &str| s.doc().unwrap().header.get(n).cloned();
s.doc_mut().unwrap().header.set("GRIDUNIT", cadcraft_doc::HVal::Point(cadcraft_geom::Vec3::new(0.0, 0.0, 0.0)));
s.doc_mut().unwrap().header.vars.remove("SNAPUNIT");
let (grid, snap) = (header(&s, "GRIDUNIT"), header(&s, "SNAPUNIT"));
assert!(apply(&mut s, &json!({ "GRIDUNIT": [4, 5], "SNAPUNIT": [2, 3], "WINDOWAREACOLOR": 0 })).is_err());
assert_eq!((header(&s, "GRIDUNIT"), header(&s, "SNAPUNIT")), (grid, snap));
}
#[test]
fn reset_puts_every_profile_var_back_except_the_drawings() {
let defaults = profile(&Session::new());
let mut s = Session::new();
for name in PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)) {
// A value the variable takes that isn't its default: 0 and 1 swapped, or a number one
// more or less, or an angle.
let was = &defaults[*name];
let n = was.as_f64().unwrap_or(0.0);
let tries = [json!(if n == 0.0 { 1 } else { 0 }), json!(n + 1.0), json!(n - 1.0), json!("15")];
let changed = tries.iter().any(|v| apply(&mut s, &json!({ *name: v })).is_ok() && profile(&s)[*name] != *was);
assert!(changed, "no other value found for {name} (default {was})");
}
assert!(PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)).all(|n| profile(&s)[*n] != defaults[*n]));
apply(&mut s, &json!({ "SNAPUNIT": [2, 3], "GRIDUNIT": [4, 5] })).unwrap();
reset(&mut s);
let after = profile(&s);
for name in PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)) {
assert_eq!(after[*name], defaults[*name], "{name}");
}
// The snap and grid spacing are the drawing's, and stay.
assert_eq!((after["SNAPUNIT"].clone(), after["GRIDUNIT"].clone()), (json!([2.0, 3.0]), json!([4.0, 5.0])));
}
}
+5 -5
View File
@@ -449,7 +449,7 @@ fn run_style(s: &mut Session, p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
// As it was (none for a new style), so dimensions are redrawn only when it changes.
let before = d.text_style(&name).cloned();
let idx = match d.text_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) {
let idx = match d.text_styles.position_by_name(&name) {
Some(i) => i,
None => {
d.text_styles.push(cadcraft_doc::TextStyle { name: name.clone(), ..Default::default() });
@@ -554,7 +554,7 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result<Value> {
if d.text_style(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
return Err(bad("style.rename", format!("a text style `{to}` already exists")));
}
let st = d.text_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("style.rename", "no such style"))?;
let st = d.text_styles.by_name_mut(&from).ok_or_else(|| bad("style.rename", "no such style"))?;
st.name = to.clone();
// References follow the new name.
let fix = |n: &mut String| {
@@ -642,7 +642,7 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result<Value> {
// As it was (none for a new style), so dimensions are redrawn only when it changes.
let before = d.dim_style(&name).cloned();
let base = d.dim_style(&d.header.str("DIMSTYLE", "Standard")).cloned().unwrap_or_default();
let idx = match d.dim_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) {
let idx = match d.dim_styles.position_by_name(&name) {
Some(i) => i,
None => {
d.dim_styles.push(cadcraft_doc::DimStyle { name: name.clone(), ..base });
@@ -792,7 +792,7 @@ fn run_dimstyle_rename(s: &mut Session, p: &Value) -> Result<Value> {
if d.dim_style(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
return Err(bad("dimstyle.rename", format!("a dimension style `{to}` already exists")));
}
let st = d.dim_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("dimstyle.rename", "no such dimension style"))?;
let st = d.dim_styles.by_name_mut(&from).ok_or_else(|| bad("dimstyle.rename", "no such dimension style"))?;
st.name = to.clone();
if d.header.str("DIMSTYLE", "Standard").eq_ignore_ascii_case(&from) {
d.header.set_str("DIMSTYLE", &to);
@@ -1015,7 +1015,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
if d.linetype(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
return Err(bad("rename", format!("a linetype `{to}` already exists")));
}
let st = d.linetypes.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("rename", "no such linetype"))?;
let st = d.linetypes.by_name_mut(&from).ok_or_else(|| bad("rename", "no such linetype"))?;
st.name = to.clone();
// References follow the new name.
let fix = |n: &mut String| {
+1 -1
View File
@@ -59,7 +59,7 @@ fn put(d: &mut Drawing, lt: Linetype, reload: bool, out: &mut Loaded) {
break;
}
}
match d.linetypes.iter_mut().find(|l| l.name.eq_ignore_ascii_case(&lt.name)) {
match d.linetypes.by_name_mut(&lt.name) {
Some(old) if reload => {
out.reloaded.push(old.name.clone());
// The drawing keeps the name as it had it (objects refer to it).
@@ -202,6 +202,7 @@ pub const NO_FILES: &[&str] = &[
"dim",
"mleader",
"leader",
"qleader",
"dimstyle.update",
"dimoverride",
"dimreassociate",
+1
View File
@@ -37,6 +37,7 @@ const NO_OR: &[&str] = &[
"Choose mode for selected object conversion",
"Create annotative block",
"Enter a configuration option",
"Enter a copy mode option",
"Enter a plotting preference",
"Enter an annotation option",
"Enter an option",
+3
View File
@@ -75,6 +75,8 @@ pub struct Settings {
/// FILEDIA: kept for routines that switch file dialogs off around a script; no command reads it yet.
pub filedia: bool,
pub pickadd: bool,
/// COPYMODE: COPY makes one copy and ends (true, 1), or copies until Enter (false, 0).
pub copymode: bool,
/// PICKDRAG: false = two-click windows (0), true = clicks or dragging (2).
/// Drag-only mode (1) is not supported yet.
pub pickdrag: bool,
@@ -180,6 +182,7 @@ impl Default for Settings {
cmdecho: true,
filedia: true,
pickadd: true,
copymode: false,
pickdrag: true,
pickstyle: 1,
gripsize: 5.0,
+2 -2
View File
@@ -162,7 +162,7 @@ impl SpatialIndex {
SpatialIndex {
store: store.clone(),
blocks: (*d.blocks).clone(),
dim_styles: d.dim_styles.clone(),
dim_styles: d.dim_styles.to_vec(),
dimscale: d.header.f64("DIMSCALE", 1.0),
anno: anno_key(d),
hidden_layers: hidden_layers(d).map(str::to_owned).collect(),
@@ -178,7 +178,7 @@ impl SpatialIndex {
self.blocks.len() == d.blocks.len()
&& self.blocks.iter().zip(&d.blocks).all(|((ka, a), (kb, b))| ka == kb && Arc::ptr_eq(a, b))
&& self.dimscale.to_bits() == d.header.f64("DIMSCALE", 1.0).to_bits()
&& self.dim_styles == d.dim_styles
&& self.dim_styles == *d.dim_styles
&& self.anno == anno_key(d)
&& self.hidden_layers.iter().map(String::as_str).eq(hidden_layers(d))
}
+3
View File
@@ -59,6 +59,7 @@ const SESSION_VARS: &[&str] = &[
"CMDECHO",
"FILEDIA",
"PICKADD",
"COPYMODE",
"PICKDRAG",
"PICKSTYLE",
"GRIPSIZE",
@@ -140,6 +141,7 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"CMDECHO" => json!(i32::from(st.cmdecho)),
"FILEDIA" => json!(i32::from(st.filedia)),
"PICKADD" => json!(i32::from(st.pickadd)),
"COPYMODE" => json!(i32::from(st.copymode)),
"PICKDRAG" => json!(i32::from(st.pickdrag) * 2),
"PICKSTYLE" => json!(st.pickstyle),
"GRIPSIZE" => json!(st.gripsize),
@@ -394,6 +396,7 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
"CMDECHO" => st.cmdecho = small(v, 1).ok_or_else(bad)? == 1,
"FILEDIA" => st.filedia = small(v, 1).ok_or_else(bad)? == 1,
"PICKADD" => st.pickadd = as_bool(v).ok_or_else(bad)?,
"COPYMODE" => st.copymode = small(v, 1).ok_or_else(bad)? == 1,
"PICKDRAG" => st.pickdrag = as_i(v).filter(|b| matches!(b, 0 | 2)).map(|b| b == 2).ok_or_else(bad)?,
"PICKSTYLE" => st.pickstyle = as_i(v).filter(|b| (0..=3).contains(b)).and_then(|b| u8::try_from(b).ok()).ok_or_else(bad)?,
"GRIPSIZE" => st.gripsize = as_f64(v).ok_or_else(bad)?.clamp(1.0, 255.0),
+2
View File
@@ -67,6 +67,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
("OFFSETDIST", Kind::AnyReal, Def::Real(-1.0)),
("OFFSETERASE", Kind::Choice(&[0, 1]), Def::Int(0)),
("OFFSETLAYER", Kind::Choice(&[0, 1]), Def::Int(0)),
// The width a new polyline starts at; PLINE's Width and Halfwidth answers set it.
("PLINEWID", Kind::Real { min: 0.0, strict: false }, Def::Real(0.0)),
("POLYSIDES", Kind::Int(3, 1024), Def::Int(4)),
("PROJMODE", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
("REVCLOUDARCLEN", Kind::Real { min: 0.0, strict: true }, Def::Units(0.5, 15.0)),
+56
View File
@@ -1309,6 +1309,62 @@ fn pline_width_answers_taper_the_next_segment() {
assert_eq!(widths(&p), (0.0, vec![(0.0, 0.0), (0.0, 0.0)]));
}
/// PLINE against what AutoCAD 2024 stores for the same typed input (black-box: synthetic input
/// in accoreconsole, read back with `entget` and GETVAR).
#[test]
fn pline_undo_mode_and_plinewid_match_autocad() {
// Undo after an arc segment returns to line mode, where `_L` is Length (a point gives the
// length, along the last segment).
let p = typed_pline(
"pline -0.702422643378533,-28.46727901968281 -27.912058384977463,-34.74188138168937 -22.546524604415925,32.44142803067136 _U \
25.831317263304115,13.510616645626207 _A -33.2372517304228,12.083585785350365 _U _L -22.546524604415925,32.44142803067136",
);
let want = [
(-0.7024226433785329, -28.4672790196828),
(-27.91205838497746, -34.74188138168937),
(25.83131726330411, 13.5106166456262),
(64.48701958199356, 48.21692560701169),
];
assert_eq!(p.vertices.len(), want.len(), "{p:?}");
for (v, (x, y)) in p.vertices.iter().zip(want) {
assert!(v.p.near(Vec2::new(x, y), 1e-9 * x.abs().max(y.abs())) && v.bulge == 0.0, "{p:?}");
}
// PLINEWID is the width a new polyline starts with…
let mut s = Session::new();
s.cmdline("(setvar \"PLINEWID\" 0.75)").unwrap();
s.cmdline("pline -21.06802233135781,9.943678105070298 -29.261665218975015,-28.460093326613574 7.898763272534772,6.73634194079888").unwrap();
s.cmdline("").unwrap();
assert!(matches!(&s.doc().unwrap().model.last().unwrap().kind, EntityKind::LwPolyline(p) if p.const_width == 0.75));
// …and the ending width of the last Width or Halfwidth answer (half-width 0.5: PLINEWID 1).
let mut s = Session::new();
s.cmdline("pline -9.151085154682761,12.9438035725412 _W 0.0934460985004879 1.547654372298795").unwrap();
assert_eq!(s.doc().unwrap().header.f64("PLINEWID", 0.0), 1.547654372298795);
s.cmdline("19.161590651864245,38.23079339857958 26.720225103092986,-9.028145532375504 _H 0.5 0.5 -24.7035288980598,-14.309723714209586").unwrap();
s.cmdline("").unwrap();
assert_eq!(s.doc().unwrap().header.f64("PLINEWID", 0.0), 1.0);
// PLINEWID is an ordinary system variable: 0 until set, typed at the command line or set
// with SETVAR, and that width is where the next polyline starts.
let mut s = Session::new();
let r = s.execute("getvar", &json!({"name": "PLINEWID"})).unwrap();
assert_eq!(r["value"].as_f64(), Some(0.0), "{r}");
s.cmdline("plinewid 0.5").unwrap();
assert_eq!(s.doc().unwrap().header.f64("PLINEWID", 0.0), 0.5);
s.cmdline("pline 0,0 10,0").unwrap();
s.cmdline("").unwrap();
assert!(matches!(&s.doc().unwrap().model.last().unwrap().kind, EntityKind::LwPolyline(p) if p.const_width == 0.5));
// The JSON form starts there too, unless it gives a width or its vertices give theirs.
let width = |s: &mut Session, p: serde_json::Value| {
s.execute("pline", &p).unwrap();
match &s.doc().unwrap().model.last().unwrap().kind {
EntityKind::LwPolyline(p) => p.const_width,
k => panic!("{k:?}"),
}
};
assert_eq!(width(&mut s, json!({"vertices": [[0, 0], [10, 0]]})), 0.5);
assert_eq!(width(&mut s, json!({"vertices": [[0, 0], [10, 0]], "width": 0})), 0.0);
assert_eq!(width(&mut s, json!({"vertices": [{"p": [0, 0], "startWidth": 1, "endWidth": 2}, [10, 0]]})), 0.0);
}
#[test]
fn press_and_drag_selection_window() {
let mut s = Session::new();
+2 -2
View File
@@ -198,7 +198,7 @@ pub fn set_current(d: &mut Drawing, space: &Space, frame: &UcsFrame, name: &str)
h.set_str("UCSNAME", name);
}
Space::Paper(layout) => {
if let Some(l) = d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)) {
if let Some(l) = d.layouts.by_name_mut(layout) {
l.ucs = (!(frame.is_world() && name.is_empty())).then(|| frame.record(name));
}
}
@@ -210,7 +210,7 @@ pub fn set_current(d: &mut Drawing, space: &Space, frame: &UcsFrame, name: &str)
fn previous_mut<'a>(d: &'a mut Drawing, space: &Space) -> Option<&'a mut Vec<Ucs>> {
match space {
Space::Model => Some(&mut d.ucs_previous),
Space::Paper(layout) => d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)).map(|l| &mut l.ucs_previous),
Space::Paper(layout) => d.layouts.by_name_mut(layout).map(|l| &mut l.ucs_previous),
}
}
+31
View File
@@ -229,3 +229,34 @@ fn json_arraypolar_rejects_bad_fill_angles() {
s.execute("arraypolar", &p).unwrap();
}
}
#[test]
fn json_arraypath_rejects_a_bad_count_or_spacing() {
// As arrayrect's and arraypolar's counts: not a whole number of at least 1 is refused, as is a
// spacing that isn't a positive number. Before, these fell back to the default 6 items.
let mut s = Session::new();
let h = s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap()["handle"].clone();
let path = s.execute("line", &json!({"points": [[0, 0], [100, 0]]})).unwrap()["handles"][0].clone();
let before = s.doc().unwrap().model.iter().count();
for (key, bad) in [
("count", json!(0)),
("count", json!(-3)),
("count", json!(4.5)),
("count", json!("8")),
("spacing", json!(0)),
("spacing", json!(-5)),
("spacing", json!("10")),
] {
let p = json!({"handles": [h], "path": path, key: bad});
let e = s.execute("arraypath", &p).unwrap_err();
assert!(e.to_string().contains(&format!("`{key}`")), "{key} {bad}: {e}");
assert_eq!(s.doc().unwrap().model.iter().count(), before, "{key} {bad}");
}
// Missing or null is the default, 6 items: the original and 5 copies.
for p in [json!({"handles": [h], "path": path}), json!({"handles": [h], "path": path, "count": null, "spacing": null})] {
assert_eq!(s.execute("arraypath", &p).unwrap()["handles"].as_array().map(Vec::len), Some(5), "{p}");
}
// One item is the original alone; a spacing of 25 along 100 is 5 items.
assert_eq!(s.execute("arraypath", &json!({"handles": [h], "path": path, "count": 1})).unwrap()["handles"], json!([]));
assert_eq!(s.execute("arraypath", &json!({"handles": [h], "path": path, "spacing": 25})).unwrap()["handles"].as_array().map(Vec::len), Some(4));
}
+151
View File
@@ -0,0 +1,151 @@
//! The counts the ARRAY commands ask for take a whole number as typed, as AutoCAD 2024's do
//! (measured in its core console at ARRAYRECT's rows and columns, ARRAYPOLAR's items and rows,
//! and -ARRAY's rows and items): +3 and 03 are three, and 5.0, 1e1, 8/2 and 3' are refused and
//! asked for again.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{ArrayKind, EntityKind, Handle};
use serde_json::json;
/// Texts AutoCAD 2024 refuses at an array count.
const REFUSED: [&str; 6] = ["5.0", "4.", "1e1", "8/2", "3'", "4.5"];
fn typed(s: &mut Session, inputs: &[&str]) {
for t in inputs {
s.cmdline(t).unwrap();
}
}
/// Each refused text gets the count message, and the same prompt again.
fn refuses_and_asks_again(s: &mut Session) {
let asked = s.prompt_text();
for t in REFUSED {
s.cmdline(t).unwrap();
assert!(s.log.last().is_some_and(|l| l.starts_with("Requires an integer between 1 and")), "{t}: {:?}", s.log.last());
assert_eq!(s.prompt_text(), asked, "{t}");
}
}
fn lines(s: &Session) -> usize {
s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count()
}
fn with_line() -> Session {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[10, 0], [12, 0]] })).unwrap();
s
}
#[test]
fn arrayrect_columns_and_rows() {
let mut s = with_line();
typed(&mut s, &["arrayrect", "l", "", "cou"]);
assert!(s.prompt_text().contains("Enter the number of columns"), "{}", s.prompt_text());
refuses_and_asks_again(&mut s);
s.cmdline("+3").unwrap();
assert!(s.prompt_text().contains("Enter the number of rows"), "{}", s.prompt_text());
refuses_and_asks_again(&mut s);
typed(&mut s, &["03", "as", "n", "x"]);
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), 9);
}
/// The bounds are CADCraft's, which this rule leaves as they were: a count runs from 1 to what
/// MAXARRAY allows for the array's other counts. With MAXARRAY 100 and three rows, 0 and 34 columns
/// are refused and 33 taken; then 4 rows are refused and 3 taken.
#[test]
fn a_count_runs_from_one_to_the_maxarray_limit() {
let mut s = with_line();
s.execute("setvar", &json!({ "name": "MAXARRAY", "value": 100 })).unwrap();
typed(&mut s, &["arrayrect", "l", "", "cou"]);
let refused = |s: &mut Session, texts: &[&str], max: u64| {
let asked = s.prompt_text();
for t in texts {
s.cmdline(t).unwrap();
let msg = format!("Requires an integer between 1 and {max} ");
assert!(s.log.last().is_some_and(|l| l.starts_with(&msg)), "{t}: {:?}", s.log.last());
assert_eq!(s.prompt_text(), asked, "{t}");
}
};
assert!(s.prompt_text().contains("Enter the number of columns"), "{}", s.prompt_text());
refused(&mut s, &["0", "34"], 33);
s.cmdline("33").unwrap();
assert!(s.prompt_text().contains("Enter the number of rows"), "{}", s.prompt_text());
refused(&mut s, &["0", "4"], 3);
typed(&mut s, &["3", "as", "n", "x"]);
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), 99);
}
#[test]
fn arraypolar_items() {
let mut s = with_line();
typed(&mut s, &["arraypolar", "l", "", "0,0", "i"]);
assert!(s.prompt_text().contains("Enter number of items in array"), "{}", s.prompt_text());
refuses_and_asks_again(&mut s);
typed(&mut s, &["+5", "as", "n", "x"]);
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), 5);
}
/// ARRAYEDIT's counts go through the same count parser as ARRAYRECT's, ARRAYPOLAR's and -ARRAY's
/// (`count()` in `crates/engine/src/cmd/array.rs`), so they refuse and take the same texts: here 5.0,
/// 5., 4.5, 1e1 and 8/2 are refused at a rectangular array's columns and rows and a polar array's
/// items, and +5, 05 and 5 are taken. No AutoCAD measurement of ARRAYEDIT is claimed.
#[test]
fn arrayedit_counts() {
let refused = ["5.0", "5.", "4.5", "1e1", "8/2"];
let edit = |s: &mut Session, h: Handle, option: &str, asked: &str, count: &str, after: &[&str]| {
s.set_selection(vec![h]);
typed(s, &["arrayedit", option]);
assert!(s.prompt_text().contains(asked), "{}", s.prompt_text());
let prompt = s.prompt_text();
for t in refused {
s.cmdline(t).unwrap();
assert!(s.log.last().is_some_and(|l| l.starts_with("Requires an integer between 1 and")), "{t}: {:?}", s.log.last());
assert_eq!(s.prompt_text(), prompt, "{t}");
}
s.cmdline(count).unwrap();
typed(s, after);
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
let d = s.doc().unwrap();
d.array_params(d.entity(h).unwrap()).unwrap().kind
};
let mut s = with_line();
let l = s.doc().unwrap().model.iter().next().unwrap().handle.hex();
let r = s.execute("arrayrect", &json!({ "handles": [l], "cols": 4, "rows": 3, "colSpacing": 5, "rowSpacing": 5 })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let ArrayKind::Rect(a) = edit(&mut s, h, "col", "Enter the number of columns", "+5", &["", "x"]) else { panic!("not rectangular") };
assert_eq!((a.cols, a.rows), (5, 3));
let ArrayKind::Rect(a) = edit(&mut s, h, "r", "Enter the number of rows", "05", &["", "", "x"]) else { panic!("not rectangular") };
assert_eq!((a.cols, a.rows), (5, 5));
let mut s = with_line();
let l = s.doc().unwrap().model.iter().next().unwrap().handle.hex();
let r = s.execute("arraypolar", &json!({ "handles": [l], "center": [0, -50], "count": 6 })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let ArrayKind::Polar(a) = edit(&mut s, h, "i", "Enter number of items in array", "5", &["x"]) else { panic!("not polar") };
assert_eq!(a.items, 5);
}
#[test]
fn classic_array_rows_columns_and_items() {
let mut s = with_line();
typed(&mut s, &["-array", "l", "", "r"]);
assert!(s.prompt_text().contains("Enter the number of rows (---)"), "{}", s.prompt_text());
refuses_and_asks_again(&mut s);
s.cmdline("03").unwrap();
assert!(s.prompt_text().contains("Enter the number of columns (|||)"), "{}", s.prompt_text());
refuses_and_asks_again(&mut s);
typed(&mut s, &["+2", "5", "5"]);
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), 6);
let mut s = with_line();
typed(&mut s, &["-array", "l", "", "p", "0,0"]);
assert!(s.prompt_text().contains("Enter the number of items in the array"), "{}", s.prompt_text());
refuses_and_asks_again(&mut s);
typed(&mut s, &["+3", "360", "y"]);
assert!(s.current_prompt().is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), 3);
}
@@ -0,0 +1,98 @@
//! Attributes are matched to their block's definitions, and definitions to a reference's
//! attributes, by tag in one lookup each: BURST and ATTSYNC on a reference with many of both.
use std::sync::Arc;
use cadcraft_doc::{Attrib, EntityKind, Handle};
use cadcraft_engine::Session;
use serde_json::json;
/// Block B with definition T and a reference to it carrying T = "v"; with `n` > 0 the block gets
/// `n` more definitions and the reference's attribute is replaced by `n`, the tags `n` long ones
/// alike up to their last characters, no attribute's a definition's.
fn reference(n: usize) -> (Session, Handle) {
let mut s = Session::new();
s.execute("attdef", &json!({"tag": "T", "default": "d", "at": [0, 1], "height": 1.0})).unwrap();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let hs: Vec<String> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
s.execute("block", &json!({"name": "B", "base": [0, 0], "keep": "delete", "handles": hs})).unwrap();
let r = s.execute("insert", &json!({"name": "B", "at": [0, 0], "attribs": {"T": "v"}})).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
if n > 0 {
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let d = s.doc_mut().unwrap();
let handles: Vec<Handle> = (0..n).map(|_| d.new_handle()).collect();
let blk = Arc::make_mut(d.blocks.get_mut("B").unwrap());
let def = blk.entities.iter().find(|e| matches!(e.kind, EntityKind::AttDef(_))).unwrap().as_ref().clone();
for (i, h) in handles.into_iter().enumerate() {
let mut e = def.clone();
e.handle = h;
if let EntityKind::AttDef(a) = &mut e.kind {
a.tag = tag('D', i);
}
blk.entities.push(e);
}
d.modify_entity(h, |e| {
if let EntityKind::Insert(ins) = &mut e.kind {
let one = ins.attribs[0].clone();
ins.attribs = (0..n).map(|i| Attrib { tag: tag('A', i), ..one.clone() }).collect();
}
})
.unwrap();
}
(s, h)
}
fn attribs(s: &Session, h: Handle) -> Vec<Attrib> {
let EntityKind::Insert(i) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
i.attribs.clone()
}
/// #1923: comparing each attribute with each definition (BURST: for its properties; ATTSYNC: for
/// the value each definition keeps) cost N x N comparisons of whole tags (many seconds here); one
/// lookup each costs milliseconds.
const N: usize = 4000;
#[test]
fn burst_matches_many_attributes_without_comparing_every_pair() {
let (mut s, h) = reference(N);
let t = std::time::Instant::now();
s.execute("burst", &json!({"handles": [h.hex()]})).unwrap();
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Text(_))).count(), N);
}
#[test]
fn attsync_matches_many_definitions_without_comparing_every_pair() {
let (mut s, h) = reference(N);
let t = std::time::Instant::now();
s.execute("attsync", &json!({"name": "B"})).unwrap();
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
// An attribute for each definition (T and the N others), with its default value: the
// reference carried none of their tags.
let a = attribs(&s, h);
assert_eq!(a.len(), N + 1);
assert!(a.iter().all(|a| a.text.value == "d"));
}
#[test]
fn attsync_keeps_the_value_of_the_first_attribute_of_a_tag() {
// A reference carrying two attributes of one tag (in different case, as a file can hold
// them) keeps the first one's value for the definition of that tag.
let (mut s, h) = reference(0);
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Insert(ins) = &mut e.kind {
let mut second = ins.attribs[0].clone();
second.tag = "t".into();
second.text.value = "second".into();
ins.attribs[0].text.value = "first".into();
ins.attribs.push(second);
}
})
.unwrap();
s.execute("attsync", &json!({"name": "B"})).unwrap();
let a = attribs(&s, h);
assert_eq!(a.iter().map(|a| (a.tag.as_str(), a.text.value.as_str())).collect::<Vec<_>>(), [("T", "first")]);
}
+258
View File
@@ -0,0 +1,258 @@
//! COPY at the command line as AutoCAD 2024 runs it (accoreconsole, a line from (0, 0) to (1, 0)
//! copied with `(command "_.COPY" line "" ...)`, then the start point of every line):
//!
//! - COPYMODE 1 makes one copy and ends; Multiple copies until Exit or Enter, and Undo takes back
//! the last placement, a whole array at once;
//! - Enter at the first second point copies by the base point taken as a displacement;
//! - Array asks for a number of items, the original included (2 to 32767), and puts them the
//! second point apart, or spread up to it with Fit; Enter there leaves them at the base.
use cadcraft_engine::Session;
use cadcraft_engine::doc::EntityKind;
use serde_json::json;
/// A session with one line from (0, 0) to (1, 0) and COPYMODE set to `mode`.
fn with_line(mode: i64) -> Session {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [1, 0]] })).unwrap();
s.execute("setvar", &json!({ "name": "COPYMODE", "value": mode })).unwrap();
s
}
/// The start point of every line, sorted.
fn starts(s: &Session) -> Vec<(f64, f64)> {
let mut v: Vec<(f64, f64)> =
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.x, l.a.y)) } else { None }).collect();
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v
}
fn copymode(s: &mut Session) -> serde_json::Value {
s.execute("getvar", &json!({ "name": "COPYMODE" })).unwrap()["value"].clone()
}
/// Types COPY, selects everything, then each of `inputs`.
fn copy(s: &mut Session, inputs: &[&str]) {
for t in ["COPY", "all", ""].iter().chain(inputs) {
s.cmdline(t).unwrap();
}
}
#[test]
fn copymode_1_makes_one_copy_and_ends() {
let mut s = with_line(1);
copy(&mut s, &["0,0"]);
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Array] <use first point as displacement>:");
s.cmdline("10,0").unwrap();
assert!(s.current_prompt().is_none(), "COPY ended");
assert_eq!(starts(&s), [(0.0, 0.0), (10.0, 0.0)]);
assert_eq!(copymode(&mut s), json!(1));
}
#[test]
fn the_base_point_prompt_offers_mode_and_multiple() {
let mut s = with_line(1);
copy(&mut s, &[]);
assert_eq!(s.current_prompt().unwrap().display(), "Specify base point or [Displacement/mOde/Multiple] <Displacement>:");
// Multiple, this once: the option goes and COPYMODE stays 1.
s.cmdline("M").unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Specify base point or [Displacement/mOde] <Displacement>:");
for t in ["0,0", "10,0", "20,0"] {
s.cmdline(t).unwrap();
}
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Array/Exit/Undo] <Exit>:");
s.cmdline("E").unwrap();
assert!(s.current_prompt().is_none());
assert_eq!(starts(&s), [(0.0, 0.0), (10.0, 0.0), (20.0, 0.0)]);
assert_eq!(copymode(&mut s), json!(1));
// Multiple, then mOde with Enter: the mode shown (Single, COPYMODE 1) is the mode COPY runs in.
let mut s = with_line(1);
copy(&mut s, &["M", "O"]);
assert_eq!(s.current_prompt().unwrap().display(), "Enter a copy mode option [Single/Multiple] <Single>:");
for t in ["", "0,0", "5,0"] {
s.cmdline(t).unwrap();
}
assert!(s.current_prompt().is_none(), "one copy");
assert_eq!(starts(&s), [(0.0, 0.0), (5.0, 0.0)]);
// mOde sets COPYMODE.
let mut s = with_line(0);
copy(&mut s, &["O"]);
assert_eq!(s.current_prompt().unwrap().display(), "Enter a copy mode option [Single/Multiple] <Multiple>:");
s.cmdline("S").unwrap();
assert_eq!(copymode(&mut s), json!(1));
for t in ["0,0", "5,0"] {
s.cmdline(t).unwrap();
}
assert!(s.current_prompt().is_none(), "one copy, now single");
assert_eq!(starts(&s), [(0.0, 0.0), (5.0, 0.0)]);
}
#[test]
fn copymode_0_copies_until_enter_and_undo_takes_back_the_last() {
let mut s = with_line(0);
copy(&mut s, &["0,0", "10,0", "20,0", "U", "30,0", ""]);
assert!(s.current_prompt().is_none());
assert_eq!(starts(&s), [(0.0, 0.0), (10.0, 0.0), (30.0, 0.0)]);
// Undoing the only copy goes back to the first prompt.
let mut s = with_line(0);
copy(&mut s, &["0,0", "10,0", "U"]);
assert!(s.log.iter().any(|l| l == "Command has been completely undone."), "{:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Array] <use first point as displacement>:");
s.cmdline("30,0").unwrap();
s.cmdline("").unwrap();
assert_eq!(starts(&s), [(0.0, 0.0), (30.0, 0.0)]);
// An array is one placement: Undo takes all its items back.
let mut s = with_line(0);
copy(&mut s, &["0,0", "10,0", "A", "3", "0,5", "U", "40,0", ""]);
assert_eq!(starts(&s), [(0.0, 0.0), (10.0, 0.0), (40.0, 0.0)]);
// An array after a copy, and more after it.
let mut s = with_line(0);
copy(&mut s, &["3,4", "10,4", "A", "2", "20,4", ""]);
assert_eq!(starts(&s), [(0.0, 0.0), (7.0, 0.0), (17.0, 0.0)]);
}
#[test]
fn enter_at_the_first_second_point_copies_by_the_base_point() {
for mode in [0, 1] {
let mut s = with_line(mode);
copy(&mut s, &["3,4", ""]);
assert!(s.current_prompt().is_none(), "COPYMODE {mode}");
assert_eq!(starts(&s), [(0.0, 0.0), (3.0, 4.0)], "COPYMODE {mode}");
}
// Displacement, and Enter at the base point (its default), make one copy too.
for inputs in [["D", "5,6"], ["", "7,8"]] {
let mut s = with_line(0);
copy(&mut s, &inputs);
assert!(s.current_prompt().is_none(), "{inputs:?}");
assert_eq!(starts(&s).len(), 2, "{inputs:?}");
}
}
#[test]
fn array_puts_the_items_a_second_point_apart_or_fits_them() {
// (inputs after the base point (0, 0), AutoCAD's lines)
let cases: [(&[&str], &[(f64, f64)]); 5] = [
(&["A", "4", "10,5"], &[(0.0, 0.0), (10.0, 5.0), (20.0, 10.0), (30.0, 15.0)]),
(&["A", "4", "F", "30,0"], &[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0), (30.0, 0.0)]),
// Fit, then Array again: back to the spacing.
(&["A", "3", "F", "A", "10,0"], &[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0)]),
// The base point again, or Enter: every item at the base.
(&["A", "3", "0,0"], &[(0.0, 0.0); 3]),
(&["A", "3", ""], &[(0.0, 0.0); 3]),
];
for (inputs, want) in cases {
let mut s = with_line(1);
copy(&mut s, &["0,0"]);
for t in inputs {
s.cmdline(t).unwrap();
}
assert!(s.current_prompt().is_none(), "{inputs:?}");
assert_eq!(starts(&s), want, "{inputs:?}");
}
// Enter at the array's point with the base at (3, 4): still on the original, the base
// isn't taken as a displacement there.
let mut s = with_line(1);
copy(&mut s, &["3,4", "A", "3", ""]);
assert_eq!(starts(&s), [(0.0, 0.0); 3]);
let mut s = with_line(1);
copy(&mut s, &["0,0", "A", "4"]);
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Fit]:");
s.cmdline("F").unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Array]:");
}
#[test]
fn array_takes_2_to_32767_items() {
let mut s = with_line(1);
copy(&mut s, &["0,0", "A"]);
assert_eq!(s.current_prompt().unwrap().display(), "Enter number of items to array:");
// A point from LISP is refused too (AutoCAD 2024 with '(1 2): the same message).
for bad in ["1", "0", "2.5", "32768", "-3", "1'", "8/2", "x", "4.0", "1e1", "3\"", "(list 1 2)"] {
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, ["Requires an integer between 2 and 32767."], "{bad}");
assert_eq!(s.current_prompt().unwrap().display(), "Enter number of items to array:", "{bad}");
}
s.cmdline("32767").unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Fit]:");
// A sign or a leading zero is still a whole number, and so is the LISP real 3.0 (AutoCAD 2024:
// three items each).
for three in ["+3", "03", "(+ 1.5 1.5)"] {
let mut s = with_line(1);
copy(&mut s, &["0,0", "A", three, "5,0"]);
assert_eq!(starts(&s), [(0.0, 0.0), (5.0, 0.0), (10.0, 0.0)], "{three}");
}
// Enter at the number ends COPY with nothing copied.
let mut s = with_line(1);
copy(&mut s, &["0,0", "A", ""]);
assert!(s.current_prompt().is_none());
assert_eq!(starts(&s), [(0.0, 0.0)]);
}
#[test]
fn maxarray_doesnt_limit_the_items() {
// AutoCAD 2024 with MAXARRAY 100000: four lines and 26000 items made 104000 lines (measured).
// Here MAXARRAY is 100 (its least): two lines and 60 items, and 101 lines and 2 items, go past
// it and are still made.
let mut s = with_line(1);
s.execute("line", &json!({ "points": [[0, 5], [1, 5]] })).unwrap();
s.execute("setvar", &json!({ "name": "MAXARRAY", "value": 100 })).unwrap();
copy(&mut s, &["0,0", "A", "60", "10,0"]);
assert!(s.current_prompt().is_none());
assert_eq!(starts(&s).len(), 120);
let mut s = with_line(1);
s.execute("setvar", &json!({ "name": "MAXARRAY", "value": 100 })).unwrap();
for y in 1..=100 {
s.execute("line", &json!({ "points": [[0, y], [1, y]] })).unwrap();
}
copy(&mut s, &["0,0", "A", "2", "10,0"]);
assert!(s.current_prompt().is_none());
assert_eq!(starts(&s).len(), 202);
}
#[test]
fn the_copies_stay_within_ten_million() {
// Not AutoCAD's limit, ARRAY's: 400 lines times 25000 more items is exactly 10 million copies
// and is taken; one item more is refused before anything is made.
let mut s = with_line(1);
for y in 1..400 {
s.execute("line", &json!({ "points": [[0, y], [1, y]] })).unwrap();
}
copy(&mut s, &["0,0", "A", "25002"]);
assert_eq!(
s.log.last().map(String::as_str),
Some("The array would create 10000400 objects; the limit is 10000000. Use fewer items or select fewer objects.")
);
assert_eq!(s.current_prompt().unwrap().display(), "Enter number of items to array:");
assert_eq!(starts(&s).len(), 400);
s.cmdline("25001").unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Specify second point or [Fit]:");
}
#[test]
fn copymode_is_a_profile_variable() {
// OPTIONS reports it, a saved profile brings it back, reset puts it back to 0, and typing its
// name asks for it as for any variable.
let mut s = with_line(1);
assert_eq!(s.execute("options", &json!({})).unwrap()["COPYMODE"], json!(1));
let saved = cadcraft_engine::cmd::options::profile(&s);
let mut t = Session::new();
cadcraft_engine::cmd::options::restore(&mut t, &saved);
assert_eq!(copymode(&mut t), json!(1));
s.execute("options", &json!({ "reset": true })).unwrap();
assert_eq!(copymode(&mut s), json!(0));
s.cmdline("COPYMODE").unwrap();
s.cmdline("1").unwrap();
assert_eq!(copymode(&mut s), json!(1));
}
#[test]
fn copymode_takes_0_or_1() {
let mut s = Session::new();
assert_eq!(copymode(&mut s), json!(0));
for bad in [json!(2), json!(-1), json!("x")] {
assert!(s.execute("setvar", &json!({ "name": "COPYMODE", "value": bad })).is_err(), "{bad}");
}
assert_eq!(copymode(&mut s), json!(0));
}
+102
View File
@@ -129,3 +129,105 @@ fn insert_options_match_autocad() {
s.cmdline("(command \"_.-INSERT\" \"B7\" \"_B\" '(612350.678 2398770.432) '(612365.678 2398775.432) 1 \"\" 0)").unwrap();
assert_eq!(last_insert(&s), (115.0, 55.0, 1.0, 1.0, 1.0, 0.0));
}
/// A session with block B1, a line from (0, 0) to (10, 0) based at the origin.
fn with_b1() -> Session {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
s.execute("block", &json!({ "name": "B1", "base": [0, 0], "keep": "delete", "handles": ["100"] })).unwrap();
s
}
/// Points at the scale and rotation prompts, as AutoCAD 2024 takes them (accoreconsole, unitless;
/// INSERT measured at Scale, Rotate and XYZ's Z, MINSERT at every one): at the Scale, X, Y, Z and
/// Rotate presets a point is the first of two, "Specify second point:" gives their distance or
/// direction, and Enter there keeps the default; at XYZ's Z a point gives its distance from the
/// insertion point.
#[test]
fn points_at_the_scale_and_rotation_prompts() {
let cases = [
("\"_S\" '(3.0 4.0) '(6.0 8.0) '(10.0 0.0) 0", (10.0, 0.0, 5.0, 5.0, 5.0, 0.0)),
("\"_X\" '(3.0 4.0) '(6.0 8.0) '(10.0 0.0) 0", (10.0, 0.0, 5.0, 1.0, 1.0, 0.0)),
("\"_Z\" '(3.0 4.0) '(6.0 8.0) '(10.0 0.0) 0", (10.0, 0.0, 1.0, 1.0, 5.0, 0.0)),
("\"_R\" '(3.0 4.0) '(3.0 8.0) '(10.0 0.0) 1 \"\"", (10.0, 0.0, 1.0, 1.0, 1.0, 90.0)),
// Enter at the second point keeps the preset's default.
("\"_S\" '(3.0 4.0) \"\" '(10.0 0.0) 0", (10.0, 0.0, 1.0, 1.0, 1.0, 0.0)),
("\"_X\" '(3.0 4.0) \"\" '(10.0 0.0) 0", (10.0, 0.0, 1.0, 1.0, 1.0, 0.0)),
("\"_R\" '(3.0 4.0) \"\" '(10.0 0.0) 1 \"\"", (10.0, 0.0, 1.0, 1.0, 1.0, 0.0)),
// <<45 typed at the Rotate preset is still the angle 45, not an override for a point.
("\"_R\" \"<<45\" '(10.0 0.0) 1 \"\"", (10.0, 0.0, 1.0, 1.0, 1.0, 45.0)),
// The same point twice is no turn.
("\"_R\" '(3.0 4.0) '(3.0 4.0) '(10.0 0.0) 1 \"\"", (10.0, 0.0, 1.0, 1.0, 1.0, 0.0)),
];
for (args, want) in cases {
let mut s = with_b1();
s.cmdline(&format!("(command \"_.-INSERT\" \"B1\" {args})")).unwrap();
assert!(s.running.is_none(), "{args}: {}", s.prompt_text());
assert_eq!(last_insert(&s), want, "{args}");
}
// Typed at the command line too: the prompt asks for the second point.
let mut s = with_b1();
s.cmdline("-insert B1 s 3,4").unwrap();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Specify second point:"));
s.cmdline("6,8 10,0 0").unwrap();
assert_eq!(last_insert(&s), (10.0, 0.0, 5.0, 5.0, 5.0, 0.0));
// XYZ's Z: (3, 4) is √65 from the insertion point (10, 0).
let mut s = with_b1();
s.cmdline("(command \"_.-INSERT\" \"B1\" '(10.0 0.0) \"_XYZ\" 2 3 '(3.0 4.0) 0)").unwrap();
let (.., z, _) = last_insert(&s);
assert!((z - 65f64.sqrt()).abs() < 1e-9, "{z}");
}
/// What the scale and rotation prompts refuse, with AutoCAD 2024's messages (accoreconsole,
/// measured), and the prompt asked again ("" for the same one): a refusal at "Specify second point:"
/// asks the first one.
#[test]
fn what_the_scale_and_rotation_prompts_refuse() {
const TWO: &str = "Requires numeric distance or two points.";
const NONZERO: &str = "Value must be nonzero.";
const NUMERIC: &str = "Requires numeric value.";
const SCALE: &str = "Specify scale factor for XYZ axes <1>:";
const Y: &str = "Enter Y scale factor <use X scale factor>:";
const Z: &str = "Specify Z scale factor or <use X scale factor>:";
let cases = [
("-insert B1 s", "x", TWO, SCALE),
("-insert B1 s", "0", NONZERO, SCALE),
("-insert B1 s 3,4", "5", TWO, SCALE),
("-insert B1 s 3,4", "3,4", NONZERO, SCALE),
("-insert B1 x", "x", TWO, "Specify X scale factor <1>:"),
("-insert B1 x", "0", NONZERO, "Specify X scale factor <1>:"),
("-insert B1 x 3,4", "5", TWO, "Specify X scale factor <1>:"),
("-insert B1 x 3,4", "3,4", NONZERO, "Specify X scale factor <1>:"),
("-insert B1 r", "x", "Requires valid numeric angle or two points.", "Specify rotation angle <0>:"),
// A point from LISP: typed text at this prompt is read as an angle, as before.
("-insert B1 r|(list 3 4)", "5", "Requires valid numeric angle or two points.", "Specify rotation angle <0>:"),
("-insert B1 10,0", "0", NONZERO, ""),
("-insert B1 10,0 2", "(list 3 4)", NUMERIC, Y),
("-insert B1 10,0 2", "x", NUMERIC, Y),
("-insert B1 10,0 2", "0", NONZERO, Y),
("-insert B1 10,0 xyz 2 3", "x", "Requires numeric distance or second point.", Z),
("-insert B1 10,0 xyz 2 3", "0", NONZERO, Z),
// XYZ's Z at the insertion point itself: no distance.
("-insert B1 10,0 xyz 2 3", "10,0", NONZERO, Z),
// Exploded, after the insertion point, the scale is a positive number only.
("-insert *B1 10,0", "(list 3 4)", NUMERIC, ""),
("-insert *B1 10,0", "x", NUMERIC, ""),
("-insert *B1 10,0", "0", "Value must be positive and nonzero.", ""),
("-insert *B1 10,0", "-2", "Value must be positive and nonzero.", ""),
];
for (typed, bad, message, again) in cases {
let mut s = with_b1();
// Separate inputs are split at `|`.
for t in typed.split('|') {
s.cmdline(t).unwrap();
}
let before = s.current_prompt().map(|p| p.display());
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> =
s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires") || l.starts_with("Value must")).collect();
assert_eq!(said, [message], "{typed} then {bad}");
let again = if again.is_empty() { before.clone() } else { Some(again.to_string()) };
assert_eq!(s.current_prompt().map(|p| p.display()), again, "{typed} then {bad}");
}
}
File diff suppressed because it is too large Load Diff
+6
View File
@@ -4,6 +4,7 @@ mod annotate_options;
mod annotative;
mod arc_ctrl_direction;
mod array_commands;
mod array_counts;
mod array_key_point;
mod array_live;
mod assoc_array;
@@ -12,6 +13,7 @@ mod attdisp_attsync;
mod attedit_prompts;
mod attrib_modes;
mod attrib_props;
mod attribute_tag_matching;
mod attribute_tools;
mod attribute_value_baseline;
mod block_description;
@@ -33,6 +35,7 @@ mod compare_export;
mod constraint_geometry;
mod constraint_infer;
mod copy_count;
mod copy_modes;
mod count;
mod dash_block;
mod dash_units;
@@ -84,6 +87,7 @@ mod insert_enter;
mod insert_prompts;
mod isometric;
mod join_close;
mod join_on_source;
mod json_param_validation;
mod kept_dimension_snaps;
mod layer_cmdline;
@@ -122,6 +126,7 @@ mod oops_command;
mod options_profile;
mod overkill;
mod parallel_display_list;
mod pedit_heights;
mod pedit_multiple;
mod pedit_splinedit;
mod pick_text;
@@ -143,6 +148,7 @@ mod purge_mlinestyles;
mod purge_prompts;
mod qdim;
mod qdim_modes;
mod qleader;
mod query_entities;
mod quickcalc;
mod recent_commands;
+86 -2
View File
@@ -117,6 +117,73 @@ fn the_prompts_follow_autocad_2024() {
assert_eq!(grid(&i), (3, 2, 20.0, 15.0));
}
#[test]
fn the_column_spacing_takes_two_points() {
// AutoCAD 2024 at "Specify distance between columns (|||):": a point asks "Specify second
// point:", and the two points' distance is the spacing, 0 included; x and Enter there, and
// Enter or 5 at the second point, get "Requires numeric distance or two points." (measured).
let to_spacing = |s: &mut Session| {
let l = handle(&s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap());
s.execute("-block", &json!({"name": "B", "base": [0, 0], "handles": [l]})).unwrap();
for input in ["minsert", "B", "10,0", "1", "", "0", "2", "2", "10"] {
s.cmdline(input).unwrap();
}
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Specify distance between columns (|||):"));
};
for (second, spacing) in [("6,8", 5.0), ("3,4", 0.0)] {
let mut s = Session::new();
to_spacing(&mut s);
s.cmdline("3,4").unwrap();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Specify second point:"));
s.cmdline(second).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let [i] = inserts(&s).try_into().unwrap();
assert_eq!(grid(&i), (2, 2, spacing, 10.0), "{second}");
}
for bad in [&["x"][..], &[""], &["3,4", ""], &["3,4", "5"]] {
let mut s = Session::new();
to_spacing(&mut s);
let logged = s.log.len();
for input in bad {
s.cmdline(input).unwrap();
}
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, ["Requires numeric distance or two points."], "{bad:?}");
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Specify distance between columns (|||):"), "{bad:?}");
}
}
#[test]
fn counts_take_a_whole_number_as_typed() {
// AutoCAD 2024 at "Enter number of rows (---)": +3 and 03 are three rows; 5.0, 5., 1e1, 8/2,
// 3', 4.5, 0 and a point from LISP are refused and asked again (measured; at the columns 5.0
// and +3 too).
let mut s = Session::new();
let l = handle(&s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap());
s.execute("-block", &json!({"name": "B", "base": [0, 0], "handles": [l]})).unwrap();
for input in ["minsert", "B", "0,0", "1", "", "0"] {
s.cmdline(input).unwrap();
}
for row_or_column in ["+3", "03"] {
let asked = s.prompt_text();
for bad in ["5.0", "5.", "1e1", "8/2", "3'", "4.5", "0", "(list 1 2)"] {
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, ["Requires an integer between 1 and 32767."], "{bad}");
assert_eq!(s.prompt_text(), asked, "{bad}");
}
s.cmdline(row_or_column).unwrap();
}
for input in ["10", "20"] {
s.cmdline(input).unwrap();
}
assert!(s.running.is_none(), "{}", s.prompt_text());
let [i] = inserts(&s).try_into().unwrap();
// (columns, rows, column spacing, row spacing)
assert_eq!(grid(&i), (3, 3, 20.0, 10.0));
}
#[test]
fn counts_run_from_1_to_32767() {
// AutoCAD 2024: "Requires an integer between 1 and 32767."
@@ -205,14 +272,31 @@ fn the_json_form_makes_the_same_grid() {
json!({"name": "B", "at": [0, 0], "rows": 0}),
json!({"name": "B", "at": [0, 0], "columns": 32768}),
json!({"name": "B", "at": [0, 0], "rows": 2.5}),
// A whole number written as a float is refused, as by the array commands' JSON forms.
json!({"name": "B", "at": [0, 0], "rows": 2.0}),
json!({"name": "B", "at": [0, 0], "columns": 1e2}),
json!({"name": "B", "at": [0, 0], "rows": "2"}),
json!({"name": "B", "at": [0, 0], "rows": -2}),
// A distance that is not a number is refused, not taken as 0.
json!({"name": "B", "at": [0, 0], "rows": 2, "rowSpacing": "15"}),
json!({"name": "B", "at": [0, 0], "columns": 2, "columnSpacing": true}),
] {
assert!(s.execute("minsert", &bad).is_err(), "{bad}");
}
// A whole number written as 2.0 is a count; `explode` is INSERT's and leaves the grid made.
let r = s.execute("minsert", &json!({"name": "B", "at": [0, 200], "rows": 2.0, "rowSpacing": 15, "explode": true})).unwrap();
// Nothing was made by the refused calls.
assert_eq!(inserts(&s).len(), 2);
// `explode` is INSERT's and leaves the grid made; 32767 is the largest count.
let r = s.execute("minsert", &json!({"name": "B", "at": [0, 200], "rows": 2, "rowSpacing": 15, "explode": true})).unwrap();
assert!(r["handle"].is_string(), "{r}");
assert_eq!(inserts(&s).last().map(grid), Some((1, 2, 0.0, 15.0)));
// A null count is 1 and a null distance 0, as missing ones are: each count on its own, then
// both distances with two rows and two columns (one row or column keeps no distance anyway).
s.execute("minsert", &json!({"name": "B", "at": [0, 250], "rows": null, "columns": 2, "columnSpacing": 20})).unwrap();
assert_eq!(inserts(&s).last().map(grid), Some((2, 1, 20.0, 0.0)));
s.execute("minsert", &json!({"name": "B", "at": [0, 270], "rows": 2, "columns": null, "rowSpacing": 15})).unwrap();
assert_eq!(inserts(&s).last().map(grid), Some((1, 2, 0.0, 15.0)));
s.execute("minsert", &json!({"name": "B", "at": [0, 290], "rows": 2, "columns": 2, "rowSpacing": null, "columnSpacing": null})).unwrap();
assert_eq!(inserts(&s).last().map(grid), Some((2, 2, 0.0, 0.0)));
s.execute("minsert", &json!({"name": "B", "at": [0, 300], "columns": 32767, "columnSpacing": 1})).unwrap();
assert_eq!(inserts(&s).last().map(grid), Some((32767, 1, 1.0, 0.0)));
}
+365
View File
@@ -0,0 +1,365 @@
//! PEDIT on lines, arcs and polylines away from Z 0, as AutoCAD 2024 runs it (accoreconsole,
//! `entget` of the polyline made, on self-built drawings). A mirrored object here is one whose
//! normal is 0,0,-1, kept in world coordinates as the DXF reader keeps it.
use cadcraft_doc::{Entity, EntityKind, Handle, LwPolyline};
use cadcraft_engine::Session;
use cadcraft_geom::Vec3;
use serde_json::{Value, json};
fn handle(v: &Value) -> Handle {
Handle::parse_hex(v["handle"].as_str().or_else(|| v["handles"][0].as_str()).unwrap()).unwrap()
}
fn entity(s: &Session, h: Handle) -> Entity {
(**s.doc().unwrap().entity(h).unwrap()).clone()
}
fn edit(s: &mut Session, h: Handle, f: impl FnOnce(&mut Entity)) {
s.doc_mut().unwrap().modify_entity(h, f).unwrap();
}
/// A line from `a` to `b`.
fn line(s: &mut Session, a: [f64; 3], b: [f64; 3]) -> Handle {
let h = handle(&s.execute("line", &json!({ "points": [[a[0], a[1]], [b[0], b[1]]] })).unwrap());
edit(s, h, |e| {
if let EntityKind::Line(l) = &mut e.kind {
(l.a.z, l.b.z) = (a[2], b[2]);
}
});
h
}
/// An arc round `c` (world) from `a1` to `a2` degrees, counterclockwise in plan.
fn arc(s: &mut Session, c: [f64; 3], r: f64, a1: f64, a2: f64) -> Handle {
let h = handle(&s.execute("arc", &json!({ "center": [c[0], c[1]], "radius": r, "start": a1, "end": a2 })).unwrap());
edit(s, h, |e| {
if let EntityKind::Arc(a) = &mut e.kind {
a.center.z = c[2];
}
});
h
}
/// An open polyline through `points` at `elevation`.
fn pline(s: &mut Session, points: Value, elevation: f64) -> Handle {
let h = handle(&s.execute("pline", &json!({ "points": points })).unwrap());
edit(s, h, |e| {
if let EntityKind::LwPolyline(p) = &mut e.kind {
p.elevation = elevation;
}
});
h
}
fn face_down(s: &mut Session, h: Handle) {
edit(s, h, |e| e.common.extrusion = Vec3::new(0.0, 0.0, -1.0));
}
fn polyline(e: &Entity) -> LwPolyline {
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline: {e:?}") };
p.clone()
}
/// PEDIT's JSON form with nothing to change, which only turns a line or an arc into a polyline.
fn convert(s: &mut Session, h: Handle) -> Entity {
s.execute("pedit", &json!({ "handle": h.hex(), "option": "ltypegen", "on": false })).unwrap();
entity(s, h)
}
#[test]
fn a_line_or_an_arc_becomes_a_polyline_at_its_height() {
// AutoCAD 2024: a line at Z 5 and an arc whose centre is at Z 5 give elevation 5 facing up;
// a thickness of 2 stays, a line's and an arc's; a line facing down still gives a polyline
// facing up.
let mut s = Session::new();
let l = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
edit(&mut s, l, |e| e.common.thickness = 2.0);
let e = convert(&mut s, l);
assert_eq!((polyline(&e).elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::Z, 2.0));
let a = arc(&mut s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
edit(&mut s, a, |e| e.common.thickness = 2.0);
let e = convert(&mut s, a);
let p = polyline(&e);
assert_eq!((p.elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::Z, 2.0));
assert!((p.vertices[0].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{p:?}");
// Below Z 0 too (AutoCAD 2024: 38 = -5 for the arc's centre at Z -5).
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
let e = convert(&mut s, a);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (-5.0, Vec3::Z));
let l = line(&mut s, [0.0, 20.0, 5.0], [10.0, 20.0, 5.0]);
face_down(&mut s, l);
let e = convert(&mut s, l);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (5.0, Vec3::Z));
// A mirrored arc keeps its normal (AutoCAD 2024: 210 0,0,-1, elevation 5 for the arc at world
// Z -5) and runs as it does in its own coordinates: from world (15,5) to (10,0), bulge
// -0.414214 in plan (0.414214 in its own coordinates).
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
let e = convert(&mut s, a);
let p = polyline(&e);
assert_eq!((p.elevation, e.common.extrusion), (5.0, Vec3::new(0.0, 0.0, -1.0)));
let v: Vec<(f64, f64)> = p.vertices.iter().map(|v| (v.p.x, v.p.y)).collect();
assert!((v[0].0 - 15.0).abs() < 1e-9 && (v[0].1 - 5.0).abs() < 1e-9 && (v[1].0 - 10.0).abs() < 1e-9 && v[1].1.abs() < 1e-9, "{v:?}");
assert!((p.vertices[0].bulge + std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{p:?}");
// The elevation runs along the normal the other way too: a mirrored arc at world Z 5 gives -5,
// and one 2 thick at world Z -5 keeps the thickness (AutoCAD 2024: 38 = -5; 38 = 5, 39 = 2).
let a = arc(&mut s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
let e = convert(&mut s, a);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (-5.0, Vec3::new(0.0, 0.0, -1.0)));
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
edit(&mut s, a, |e| e.common.thickness = 2.0);
let e = convert(&mut s, a);
assert_eq!((polyline(&e).elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::new(0.0, 0.0, -1.0), 2.0));
// A sloped line still comes out at elevation 0, facing up: AutoCAD 2024 makes a polyline in the
// line's vertical plane (normal 0,1,0), which a CADCraft polyline can't be.
let l = line(&mut s, [0.0, 40.0, 0.0], [10.0, 40.0, 5.0]);
let e = convert(&mut s, l);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (0.0, Vec3::Z));
// A refused option leaves a line as it was, its normal included.
let l = line(&mut s, [0.0, 60.0, 5.0], [10.0, 60.0, 5.0]);
face_down(&mut s, l);
let before = entity(&s, l);
let r = s.execute("pedit", &json!({ "handle": l.hex(), "option": "vertex", "index": 0, "action": "break" }));
assert!(r.is_err(), "{r:?}");
assert_eq!(entity(&s, l), before);
}
/// PEDIT Join from the first object onto the second; whether the second was taken.
fn joins(s: &mut Session, first: Handle, second: Handle) -> bool {
let r = s.execute("pedit", &json!({ "handle": first.hex(), "option": "join", "join": [second.hex()] })).unwrap();
let taken = r["joined"] == json!(1);
assert_eq!(taken, s.doc().unwrap().entity(second).is_none(), "{r}");
taken
}
#[test]
fn join_takes_only_objects_at_the_polylines_height_facing_its_way() {
// AutoCAD 2024, from a line at Z 5 ending at (10,0): "1 segments added to polyline" or "0".
let next: [(&str, bool, fn(&mut Session) -> Handle); 6] = [
("a line at Z 5", true, |s| line(s, [10.0, 0.0, 5.0], [10.0, 5.0, 5.0])),
("a line at Z 0", false, |s| line(s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0])),
("an arc at Z 5", true, |s| arc(s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0)),
("an arc at Z 0", false, |s| arc(s, [10.0, 5.0, 0.0], 5.0, 270.0, 0.0)),
("a mirrored line at Z 5", true, |s| {
let h = line(s, [10.0, 0.0, 5.0], [10.0, 5.0, 5.0]);
face_down(s, h);
h
}),
("a mirrored arc at Z 5", false, |s| {
let h = arc(s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
face_down(s, h);
h
}),
];
for (what, want, make) in next {
let mut s = Session::new();
let base = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let other = make(&mut s);
assert_eq!(joins(&mut s, base, other), want, "{what}");
let p = polyline(&entity(&s, base));
assert_eq!((p.elevation, p.vertices.len()), (5.0, if want { 3 } else { 2 }), "{what}");
if want && what.contains("arc") {
// AutoCAD 2024: bulge 0.414214 on the arc's segment.
assert!((p.vertices[1].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{what}: {p:?}");
}
}
// From a mirrored polyline at elevation 5 (world Z -5, from (0,0) to (10,0)): no line at its
// world height, but a mirrored arc there and another mirrored polyline at elevation 5; and a
// polyline at elevation 5 takes no polyline at 0.
let mirrored: [(&str, bool, fn(&mut Session) -> Handle); 3] = [
("a line at Z -5", false, |s| line(s, [10.0, 0.0, -5.0], [10.0, 5.0, -5.0])),
("a mirrored arc at Z -5", true, |s| {
let h = arc(s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
face_down(s, h);
h
}),
("a mirrored polyline at elevation 5", true, |s| {
let h = pline(s, json!([[10, 0], [10, 5]]), 5.0);
face_down(s, h);
h
}),
];
for (what, want, make) in mirrored {
let mut s = Session::new();
let base = pline(&mut s, json!([[0, 0], [10, 0]]), 5.0);
face_down(&mut s, base);
let other = make(&mut s);
assert_eq!(joins(&mut s, base, other), want, "{what}");
// AutoCAD 2024: the polyline keeps elevation 5 and normal 0,0,-1; the arc's segment has
// bulge -0.414214 in the polyline's own coordinates, 0.414214 seen from above.
let e = entity(&s, base);
let p = polyline(&e);
assert_eq!((p.elevation, e.common.extrusion, p.vertices.len()), (5.0, Vec3::new(0.0, 0.0, -1.0), if want { 3 } else { 2 }), "{what}");
if want && what.contains("arc") {
assert!((p.vertices[1].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{what}: {p:?}");
}
}
let mut s = Session::new();
let base = pline(&mut s, json!([[0, 0], [10, 0]]), 5.0);
let other = pline(&mut s, json!([[10, 0], [10, 5]]), 0.0);
assert!(!joins(&mut s, base, other), "a polyline at elevation 0");
}
#[test]
fn multiple_join_takes_objects_at_any_height_but_not_facing_the_other_way() {
// AutoCAD 2024: PEDIT Multiple, a line at Z 5 and one at Z 0 meeting it in plan, convert and
// Join with no fuzz: "1 segments added to polyline", one polyline at elevation 5.
let mut s = Session::new();
line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
line(&mut s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0]);
s.cmdline("pedit m 5,0 10,2.5").unwrap();
s.cmdline("").unwrap();
s.cmdline("y j 0").unwrap();
s.cmdline("").unwrap();
let objects: Vec<Entity> = s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect();
assert_eq!(objects.len(), 1, "{objects:?}");
let p = polyline(&objects[0]);
assert_eq!((p.elevation, p.vertices.len()), (5.0, 3));
// A line at Z 0 to (10,0) and a mirrored arc from there to (15,5), picked in either order:
// both become polylines, the arc's facing down, and Join takes neither ("0 segments added").
for arc_first in [false, true] {
let mut s = Session::new();
line(&mut s, [0.0, 0.0, 0.0], [10.0, 0.0, 0.0]);
let a = arc(&mut s, [10.0, 5.0, 0.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
// The arc picked on it, at 315 degrees.
s.cmdline(if arc_first { "pedit m 13.5355339,1.4644661 5,0" } else { "pedit m 5,0 13.5355339,1.4644661" }).unwrap();
s.cmdline("").unwrap();
s.cmdline("y j 0").unwrap();
s.cmdline("").unwrap();
let objects: Vec<Entity> = s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect();
assert_eq!(objects.len(), 2, "arc first {arc_first}: {objects:?}");
assert!(objects.iter().all(|e| matches!(e.kind, EntityKind::LwPolyline(_))), "{objects:?}");
// AutoCAD 2024: the arc's polyline at elevation 0 with normal 0,0,-1, the line's facing up.
let (arcs, lines): (Vec<&Entity>, Vec<&Entity>) = objects.iter().partition(|e| e.common.extrusion.z < 0.0);
assert_eq!((arcs.len(), lines.len()), (1, 1), "{objects:?}");
let p = polyline(arcs[0]);
assert!(p.elevation == 0.0 && p.vertices[0].bulge != 0.0 && lines[0].common.extrusion == Vec3::Z, "{objects:?}");
}
}
#[test]
fn join_continues_from_a_sloped_lines_far_end_height() {
// AutoCAD 2024: from a line at Z 5, a sloped line down to Z 0 and a line on at Z 0 both join
// ("2 segments added"), at the polyline's end and at its start alike, the sloped line drawn
// either way. AutoCAD makes that polyline in the lines' vertical plane; a CADCraft polyline
// stays at the source's elevation.
for (base, sloped, next) in [
([[0.0, 0.0, 5.0], [10.0, 0.0, 5.0]], [[10.0, 0.0, 5.0], [20.0, 0.0, 0.0]], [[20.0, 0.0, 0.0], [30.0, 0.0, 0.0]]),
([[0.0, 0.0, 5.0], [10.0, 0.0, 5.0]], [[20.0, 0.0, 0.0], [10.0, 0.0, 5.0]], [[20.0, 0.0, 0.0], [30.0, 0.0, 0.0]]),
([[10.0, 0.0, 5.0], [20.0, 0.0, 5.0]], [[0.0, 0.0, 0.0], [10.0, 0.0, 5.0]], [[-10.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
([[10.0, 0.0, 5.0], [20.0, 0.0, 5.0]], [[10.0, 0.0, 5.0], [0.0, 0.0, 0.0]], [[-10.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
] {
let mut s = Session::new();
let h = line(&mut s, base[0], base[1]);
let a = line(&mut s, sloped[0], sloped[1]);
let b = line(&mut s, next[0], next[1]);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [a.hex(), b.hex()] })).unwrap();
assert_eq!(r["joined"], json!(2), "{base:?}: {r}");
assert_eq!(polyline(&entity(&s, h)).vertices.len(), 4);
}
}
#[test]
fn a_chain_closes_only_at_one_height() {
// AutoCAD 2024: three sides of a triangle at Z 5 join into a closed polyline; with its last
// side at Z 0, that side stays a line and the polyline stays open ("1 segments added").
for (last_z, joined, closed) in [(5.0, 2, true), (0.0, 1, false)] {
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let a = line(&mut s, [10.0, 0.0, 5.0], [10.0, 10.0, 5.0]);
let b = line(&mut s, [10.0, 10.0, last_z], [0.0, 0.0, last_z]);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [a.hex(), b.hex()] })).unwrap();
assert_eq!(r["joined"], json!(joined), "last side at {last_z}: {r}");
assert_eq!(polyline(&entity(&s, h)).closed, closed, "last side at {last_z}");
}
// A line at Z 5 and a sloped line back over it to Z 0: the ends meet in plan at Z 5 and at Z 0,
// and the polyline stays open (AutoCAD 2024: "1 segments added", 70 = 0).
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let back = line(&mut s, [10.0, 0.0, 5.0], [0.0, 0.0, 0.0]);
assert!(joins(&mut s, h, back));
let p = polyline(&entity(&s, h));
assert_eq!((p.vertices.len(), p.closed), (3, false));
}
#[test]
fn join_takes_a_sloped_line_only_in_one_plane_with_the_polyline_and_every_line_picked() {
// AutoCAD 2024 joins only objects in one plane with the polyline: the plane the polyline and
// every line picked share, when they share one, else the polyline's own, flat, where no sloped
// line lies. From a line at Z 5, (0,0) to (10,0):
let cases: [(&str, &[[[f64; 3]; 2]], usize); 4] = [
// a sloped line at right angles in plan, a tilted plane: "1 segments added";
("at an angle", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 0.0]]], 1),
// a triangle at Z 5 whose last side slopes from (10,10,5) to (0,0,0): that side stays a line;
("a triangle's sloped side", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 5.0]], [[10.0, 10.0, 5.0], [0.0, 0.0, 0.0]]], 1),
// a corner at Z 5, then a sloped line on in plan: the sloped line stays a line;
("after a corner", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 5.0]], [[10.0, 10.0, 5.0], [10.0, 20.0, 0.0]]], 1),
// a sloped line on in plan, then a line at Z 0 from its foot turning off their vertical
// plane: the three share no plane, and neither joins ("0 segments added").
("then a turn", &[[[10.0, 0.0, 5.0], [20.0, 0.0, 0.0]], [[20.0, 0.0, 0.0], [20.0, 10.0, 0.0]]], 0),
];
for (what, lines, joined) in cases {
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let picked: Vec<String> = lines.iter().map(|[a, b]| line(&mut s, *a, *b).hex()).collect();
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": picked })).unwrap();
assert_eq!(r["joined"], json!(joined), "{what}: {r}");
let left = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
assert_eq!(left, lines.len() - joined, "{what}");
}
// A sloped line on in plan, then an arc at Z 0 from its foot: the line joins, the arc, which
// lies flat, doesn't ("1 segments added").
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let l = line(&mut s, [10.0, 0.0, 5.0], [20.0, 0.0, 0.0]);
let a = arc(&mut s, [20.0, 5.0, 0.0], 5.0, 270.0, 0.0);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [l.hex(), a.hex()] })).unwrap();
assert_eq!(r["joined"], json!(1), "{r}");
assert!(s.doc().unwrap().entity(l).is_none() && s.doc().unwrap().entity(a).is_some());
}
#[test]
fn join_meets_within_the_fuzz_in_plan_and_1e_6_in_height() {
// The JSON form's fuzz bridges a gap in plan only: a line 0.3 off the end joins with fuzz 0.5
// at the polyline's height, to within 1e-6, and not 0.001 above it.
for (z, want) in [(5.0, true), (5.0 + 1e-9, true), (5.001, false)] {
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let o = line(&mut s, [10.3, 0.0, z], [10.3, 5.0, z]);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [o.hex()], "fuzz": 0.5 })).unwrap();
assert_eq!(r["joined"] == json!(1), want, "Z {z}: {r}");
}
// Multiple's Join takes the line 0.001 above too, as it takes one at any height.
let mut s = Session::new();
line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
line(&mut s, [10.3, 0.0, 5.001], [10.3, 5.0, 5.001]);
s.cmdline("pedit m 5,0 10.3,2.5").unwrap();
s.cmdline("").unwrap();
s.cmdline("y j 0.5").unwrap();
s.cmdline("").unwrap();
assert_eq!(s.doc().unwrap().model.iter().count(), 1);
}
#[test]
fn the_command_line_converts_and_joins_the_same_way() {
// PEDIT typed: a mirrored line at Z 5 becomes a polyline at elevation 5 facing up, and Join
// leaves a line at Z 0 off it ("0 segments added to polyline").
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
face_down(&mut s, h);
let other = line(&mut s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0]);
s.cmdline("pedit 5,0 y").unwrap();
let e = entity(&s, h);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (5.0, Vec3::Z));
let n = s.log.len();
s.cmdline("j 10,2.5").unwrap();
s.cmdline("").unwrap();
assert!(s.log[n..].iter().any(|l| l.contains("0 segments added to polyline")), "{:?}", &s.log[n..]);
assert!(s.doc().unwrap().entity(other).is_some());
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
}
+138 -2
View File
@@ -151,6 +151,19 @@ fn fit_spline(s: &mut Session) -> String {
h(&s.execute("spline", &json!({ "fit": [[0, 0], [2, 2], [4, 0], [6, 2]] })).unwrap())
}
#[test]
fn close_gives_a_closed_fit_its_own_tangent() {
// SPLINEDIT Close refits the fit points closed: the open ends' tangents don't carry over, the
// closed curve takes its own where it closes, as SPLINE ... Close builds it.
let mut s = Session::new();
let fit = json!([[0, 0], [4, 0], [6, 3], [1, 4]]);
let sp = h(&s.execute("spline", &json!({ "fit": fit, "startTangent": [0, 1] })).unwrap());
s.execute("splinedit", &json!({ "handle": sp, "option": "close" })).unwrap();
let closed = spline(&s, &sp);
let own = h(&s.execute("spline", &json!({ "fit": fit, "closed": true })).unwrap());
assert_eq!(closed, spline(&s, &own));
}
#[test]
fn fit_data_options_at_the_command_line() {
let mut s = Session::new();
@@ -281,9 +294,10 @@ fn control_edits_drop_fit_data_and_keep_closed_splines_closed() {
let x = spline(&s, &sp);
assert!(x.fit.is_empty() && x.control[1] == Vec2::new(1.0, 5.0));
let c = h(&s.execute("spline", &json!({ "fit": [[0, 0], [4, 0], [4, 4], [0, 4], [-2, 2]], "closed": true })).unwrap());
// Control points that wrap round (uniform knots): the first `degree` repeat at the end.
let c = h(&s.execute("spline", &json!({ "fit": [[0, 0], [4, 0], [4, 4], [0, 4], [-2, 2]], "closed": true, "knots": "uniform" })).unwrap());
let before = spline(&s, &c);
assert!(before.is_periodic());
assert!(before.wraps() && before.is_periodic());
let u = before.control.len() - before.degree;
s.execute("splinedit", &json!({ "handle": c, "option": "vertexmove", "index": 0, "to": [-1, -1] })).unwrap();
let x = spline(&s, &c);
@@ -297,6 +311,23 @@ fn control_edits_drop_fit_data_and_keep_closed_splines_closed() {
let (lo, hi) = x.domain();
assert!(x.eval(lo).near(x.eval(hi), 1e-9), "still closed");
assert!(s.execute("splinedit", &json!({ "handle": c, "option": "vertexdelete", "index": 99 })).is_err());
// Clamped (chord-length knots, as AutoCAD 2024 builds a closed fit spline): only the first
// control point repeats, at the end. Moving it leaves a corner where the curve closes.
let c = h(&s.execute("spline", &json!({ "fit": [[0, 0], [4, 0], [4, 4], [0, 4], [-2, 2]], "closed": true })).unwrap());
let before = spline(&s, &c);
assert!(before.is_periodic() && !before.wraps());
let last = before.control.len() - 1;
s.execute("splinedit", &json!({ "handle": c, "option": "vertexmove", "index": 0, "to": [-1, -1] })).unwrap();
let x = spline(&s, &c);
assert_eq!((x.control[0], x.control[last]), (Vec2::new(-1.0, -1.0), Vec2::new(-1.0, -1.0)), "both ends move");
assert!(x.closed && !x.is_periodic(), "a corner where it closes");
s.execute("splinedit", &json!({ "handle": c, "option": "vertexdelete", "index": 2 })).unwrap();
let x = spline(&s, &c);
assert!(x.is_valid() && x.closed && x.control.len() == before.control.len() - 1);
let (lo, hi) = x.domain();
assert!(x.eval(lo).near(x.eval(hi), 1e-9), "still closed");
assert!(s.execute("splinedit", &json!({ "handle": c, "option": "vertexdelete", "index": 0 })).is_err(), "the start point stays");
}
/// Largest distance from samples of `a` to the curve `b` (a shape comparison).
@@ -369,3 +400,108 @@ fn edit_vertex_add_and_elevate_order_keep_the_shape() {
}
assert!(s.execute("splinedit", &json!({ "handle": c, "option": "vertexadd" })).is_err());
}
#[test]
fn elevate_order_takes_a_whole_number_as_typed() {
// AutoCAD 2024 at "Enter new order <4>:" on a cubic: +5, 05 and the LISP real 5.0 make it order
// 5, and 4 keeps it; 5.0, 5., 1e1, 4.5, 3, 27 and a point from LISP get "Requires an integer
// between 4 and 26." and the prompt again. At order 5 the range starts at 5 (measured).
let control = json!({ "control": [[0, 0], [2, 3], [4, 0], [6, 3], [8, 0]] });
let refused = |s: &mut Session, bad: &str, message: &str| {
let asked = s.prompt_text();
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, [message], "{bad}");
assert_eq!(s.prompt_text(), asked, "{bad}");
};
for typed in ["+5", "05", "(+ 2.5 2.5)"] {
let mut s = Session::new();
let sp = h(&s.execute("spline", &control).unwrap());
s.cmdline("splinedit 0,0 e e").unwrap();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter new order <4>:"));
for bad in ["5.0", "5.", "1e1", "4.5", "3", "27", "(list 1 2)"] {
refused(&mut s, bad, "Requires an integer between 4 and 26.");
}
assert_eq!(spline(&s, &sp).degree, 3);
s.cmdline(typed).unwrap();
assert_eq!(spline(&s, &sp).degree, 4, "{typed}");
assert!(s.prompt_text().contains("vertex editing option"), "{}", s.prompt_text());
// Now order 5: 4 is below it, 5 keeps it.
s.cmdline("e").unwrap();
assert_eq!(s.current_prompt().map(|p| p.display()).as_deref(), Some("Enter new order <5>:"));
refused(&mut s, "4", "Requires an integer between 5 and 26.");
s.cmdline("5").unwrap();
assert_eq!(spline(&s, &sp).degree, 4, "{typed}");
assert!(s.prompt_text().contains("vertex editing option"), "{typed}: {}", s.prompt_text());
}
// 26 is the highest order (AutoCAD 2024: taken, degree 25).
let mut s = Session::new();
let sp = h(&s.execute("spline", &control).unwrap());
s.cmdline("splinedit 0,0 e e 26").unwrap();
assert_eq!(spline(&s, &sp).degree, 25);
// 4 keeps a cubic as it is, and so does Enter.
for keep in ["4", ""] {
let mut s = Session::new();
let sp = h(&s.execute("spline", &control).unwrap());
let before = spline(&s, &sp);
s.cmdline("splinedit 0,0 e e").unwrap();
s.cmdline(keep).unwrap();
assert!(s.prompt_text().contains("vertex editing option"), "{keep:?}: {}", s.prompt_text());
assert_eq!(spline(&s, &sp).control, before.control, "{keep:?}");
}
}
#[test]
fn the_polyline_precision_is_a_whole_number_as_typed() {
// AutoCAD 2024 at "Specify a precision <10>:": +5, 05, 0, 99 and the LISP real 5.0 are taken;
// 5.0, 5., 4.5, 1e1, 8/2, 100, -1, a point and the real 4.6 from LISP are refused and asked
// again (measured).
let control = json!({ "control": [[0, 0], [2, 3], [4, 0], [6, 3], [8, 0]] });
for (typed, precision) in [("+5", 5), ("05", 5), ("0", 0), ("99", 99), ("", 10), ("(+ 2.5 2.5)", 5)] {
// The same spline converted through the JSON form, for the vertices to expect.
let mut s = Session::new();
let sp = h(&s.execute("spline", &control).unwrap());
s.execute("splinedit", &json!({ "handle": sp, "option": "polyline", "precision": precision })).unwrap();
let EntityKind::LwPolyline(want) = kind(&s, &sp) else { panic!("converted") };
let mut s = Session::new();
let sp = h(&s.execute("spline", &control).unwrap());
s.cmdline("splinedit 0,0 p").unwrap();
let asked = s.prompt_text();
for bad in ["5.0", "5.", "4.5", "1e1", "8/2", "100", "-1", "(list 1 2)", "(+ 2.3 2.3)"] {
let logged = s.log.len();
s.cmdline(bad).unwrap();
let said: Vec<&str> = s.log.iter().skip(logged).map(String::as_str).filter(|l| l.starts_with("Requires")).collect();
assert_eq!(said, ["Requires an integer between 0 and 99."], "{bad}");
assert_eq!(s.prompt_text(), asked, "{bad}");
}
s.cmdline(typed).unwrap();
assert!(s.running.is_none(), "{typed:?}: {}", s.prompt_text());
let EntityKind::LwPolyline(got) = kind(&s, &sp) else { panic!("{typed:?} converted") };
assert_eq!(pts(&got), pts(&want), "{typed:?}");
}
}
#[test]
fn the_json_polyline_precision_is_a_whole_number_from_0_to_99() {
let mut s = Session::new();
let sp = h(&s.execute("spline", &json!({ "control": [[0, 0], [2, 3], [4, 0], [6, 3], [8, 0]] })).unwrap());
for bad in [json!(100), json!(-1), json!(4.5), json!(5.0), json!("5")] {
assert!(s.execute("splinedit", &json!({ "handle": sp, "option": "polyline", "precision": bad })).is_err(), "{bad}");
assert!(matches!(kind(&s, &sp), EntityKind::Spline(_)), "{bad}");
}
s.execute("splinedit", &json!({ "handle": sp, "option": "polyline", "precision": 99 })).unwrap();
assert!(matches!(kind(&s, &sp), EntityKind::LwPolyline(_)));
// Without a precision, or with null, it is 10, the prompt's default.
let [a, b, c] = [json!({ "precision": 10 }), json!({}), json!({ "precision": null })].map(|mut p| {
let sp = h(&s.execute("spline", &json!({ "control": [[0, 0], [2, 3], [4, 0], [6, 3], [8, 0]] })).unwrap());
p["handle"] = json!(sp);
p["option"] = json!("polyline");
s.execute("splinedit", &p).unwrap();
let EntityKind::LwPolyline(poly) = kind(&s, &sp) else { panic!("converted") };
pts(&poly)
});
assert_eq!(a, b);
assert_eq!(a, c);
}
+253
View File
@@ -0,0 +1,253 @@
//! QLEADER at the command line as AutoCAD 2024 runs it with its default settings (accoreconsole,
//! `(command "_.QLEADER" ...)` on a metric drawing, then `entget` of the LEADER and the MTEXT):
//! up to three points, a text width, lines of text; the text sits DIMGAP past the leader's end
//! with the middle of its first line level with it on the right, of its last line on the left.
use cadcraft_engine::doc::EntityKind;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{Input, Session};
use serde_json::json;
/// What QLEADER drew: the leader's vertices, and the text's insertion point, height, width,
/// attachment and contents (rounded to 1e-9).
type Drawn = (Vec<(f64, f64)>, Option<((f64, f64), f64, f64, u8, String)>);
fn drawn(s: &Session) -> Drawn {
let r = |v: f64| (v * 1e9).round() / 1e9;
let d = s.doc().unwrap();
let leader = d
.model
.iter()
.find_map(|e| if let EntityKind::Leader(l) = &e.kind { Some(l.vertices.iter().map(|p| (r(p.x), r(p.y))).collect()) } else { None });
let text = d.model.iter().find_map(|e| match &e.kind {
EntityKind::MText(m) => Some(((r(m.insert.x), r(m.insert.y)), r(m.height), r(m.width), m.attach, m.contents.clone())),
_ => None,
});
(leader.unwrap_or_default(), text)
}
/// A drawing with the measured scripts' dimension settings: DIMTAD 1, DIMGAP 0.625, DIMASZ 2.5,
/// DIMSCALE 1 and DIMTXT 2.5.
fn session() -> Session {
let mut s = Session::new();
for (name, v) in [("DIMTAD", 1.0), ("DIMGAP", 0.625), ("DIMASZ", 2.5), ("DIMSCALE", 1.0), ("DIMTXT", 2.5)] {
s.execute("setvar", &json!({ "name": name, "value": v })).unwrap();
}
s
}
/// Types QLEADER then each of `inputs`, and checks it ended.
fn qleader(s: &mut Session, inputs: &[&str]) {
s.cmdline("QLEADER").unwrap();
for t in inputs {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none(), "{inputs:?}: {}", s.prompt_text());
}
#[test]
fn qleader_places_the_text_as_autocad_does() {
// (inputs, AutoCAD's leader vertices, text insertion point, width, attachment, contents)
type Case<'a> = (&'a [&'a str], &'a [(f64, f64)], (f64, f64), f64, u8, &'a str);
let cases: [Case; 8] = [
// Three points, the last segment level: no hook line.
(&["0,0", "20,15", "40,15", "0", "ABC", ""], &[(0.0, 0.0), (20.0, 15.0), (40.0, 15.0)], (40.625, 16.25), 0.0, 1, "ABC"),
// Two points: a hook line DIMASZ (2.5) long into the end.
(&["0,0", "20,15", "", "0", "ABC", ""], &[(0.0, 0.0), (17.5, 15.0), (20.0, 15.0)], (20.625, 16.25), 0.0, 1, "ABC"),
(
&["0,0", "20,15", "35,30", "20", "AB", "CD", ""],
&[(0.0, 0.0), (20.0, 15.0), (32.5, 30.0), (35.0, 30.0)],
(35.625, 31.25),
20.0,
1,
"AB\\PCD",
),
// Running left: the middle of the last line level with the end.
(&["0,0", "-20,15", "-40,15", "0", "AB", "CD", ""], &[(0.0, 0.0), (-20.0, 15.0), (-40.0, 15.0)], (-40.625, 13.75), 0.0, 9, "AB\\PCD"),
(&["0,0", "-20,15", "-40,15", "0", "A", "B", "C", ""], &[(0.0, 0.0), (-20.0, 15.0), (-40.0, 15.0)], (-40.625, 13.75), 0.0, 9, "A\\PB\\PC"),
// A short leader running left: the hook line comes from past the start.
(&["0.5,0.25", "0.48,0.265", "", "0", "ABC", ""], &[(0.5, 0.25), (2.98, 0.265), (0.48, 0.265)], (-0.145, -0.985), 0.0, 9, "ABC"),
// Straight up: it counts as running right.
(&["0,0", "0,20", "", "0", "ABC", ""], &[(0.0, 0.0), (-2.5, 20.0), (0.0, 20.0)], (0.625, 21.25), 0.0, 1, "ABC"),
// Survey coordinates, running left.
(
&["612345.678,2398765.432", "612325.678,2398780.432", "612305.678,2398780.432", "0", "ABC", ""],
&[(612345.678, 2398765.432), (612325.678, 2398780.432), (612305.678, 2398780.432)],
(612305.053, 2398779.182),
0.0,
9,
"ABC",
),
];
for (inputs, leader, at, width, attach, text) in cases {
let mut s = session();
qleader(&mut s, inputs);
assert_eq!(drawn(&s), (leader.to_vec(), Some((at, 2.5, width, attach, text.to_string()))), "{inputs:?}");
}
}
#[test]
fn qleader_scales_with_dimscale_and_ignores_dimtad() {
// DIMGAP 2 and DIMSCALE 2: text 5 high, 4 past the end; the hook line 5 long.
let mut s = session();
s.execute("setvar", &json!({ "name": "DIMGAP", "value": 2.0 })).unwrap();
s.execute("setvar", &json!({ "name": "DIMSCALE", "value": 2.0 })).unwrap();
qleader(&mut s, &["0,0", "20,15", "35,30", "0", "ABC", ""]);
let want = vec![(0.0, 0.0), (20.0, 15.0), (30.0, 30.0), (35.0, 30.0)];
assert_eq!(drawn(&s), (want, Some(((39.0, 32.5), 5.0, 0.0, 1, "ABC".to_string()))));
// DIMTAD 0 or 1, the same place.
for tad in [0, 1] {
let mut s = session();
s.execute("setvar", &json!({ "name": "DIMTAD", "value": tad })).unwrap();
qleader(&mut s, &["0,0", "20,15", "40,15", "0", "ABC", ""]);
assert_eq!(drawn(&s).1, Some(((40.625, 16.25), 2.5, 0.0, 1, "ABC".to_string())), "DIMTAD {tad}");
}
}
#[test]
fn qleader_prompts_and_its_width() {
let mut s = session();
let mut asked = Vec::new();
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15", "50,15", "ABC", ""] {
asked.push(s.current_prompt().unwrap().display());
s.cmdline(t).unwrap();
}
assert_eq!(
asked,
[
"Specify first leader point, or [Settings] <Settings>:",
"Specify next point:",
"Specify next point:",
"Specify text width <0>:",
"Enter first line of annotation text <Mtext>:",
"Enter next line of annotation text:",
]
);
// A point gives the width as its distance from the end, so Dynamic Input shows a distance.
assert_eq!(drawn(&s).1.map(|t| t.2), Some(10.0));
let mut s = session();
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15"] {
s.cmdline(t).unwrap();
}
assert!(s.current_prompt().unwrap().distance);
// Text that isn't a distance is refused and asked again; Enter is no width.
let _ = s.cmdline("abc");
assert!(s.log.iter().any(|l| l.contains("Requires numeric distance or two points.")), "{:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:");
for t in ["", "ABC", ""] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
assert_eq!(drawn(&s).1.map(|t| t.2), Some(0.0));
// A point so far off that its distance overflows is refused like bad text.
let mut s = session();
s.cmdline("QLEADER").unwrap();
for p in [Vec2::new(0.0, 0.0), Vec2::new(1e308, 0.0)] {
s.input(Input::Point(p)).unwrap();
}
s.cmdline("").unwrap();
let _ = s.input(Input::Point(Vec2::new(-1e308, 0.0)));
assert!(s.log.iter().any(|l| l.contains("Requires numeric distance or two points.")), "{:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:");
// A negative width is none. A width isn't remembered: AutoCAD 2024 offers 0 again after 20.
for width in ["-5", "20"] {
let mut s = session();
qleader(&mut s, &["0,0", "20,15", "40,15", width, "ABC", ""]);
assert_eq!(drawn(&s).1.map(|t| t.2), Some(width.parse::<f64>().unwrap().max(0.0)));
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15"] {
s.cmdline(t).unwrap();
}
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:", "{width}");
}
}
#[test]
fn a_click_at_the_text_prompts_is_no_line_of_text() {
let mut s = session();
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15", "0"] {
s.cmdline(t).unwrap();
}
s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Enter first line of annotation text <Mtext>:");
s.cmdline("AB").unwrap();
s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Enter next line of annotation text:");
s.cmdline("CD").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none());
assert_eq!(drawn(&s).1.map(|t| t.4), Some("AB\\PCD".to_string()));
}
#[test]
fn qleader_without_text_or_points() {
// Enter at the first line: the leader alone.
let mut s = session();
qleader(&mut s, &["0,0", "20,15", "40,15", "0", ""]);
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0), (40.0, 15.0)], None));
// Sloped, without text: no hook line either (AutoCAD 2024: two vertices).
let mut s = session();
qleader(&mut s, &["0,0", "20,15", "", "0", ""]);
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0)], None));
// Enter after one point: nothing.
let mut s = session();
qleader(&mut s, &["0,0", ""]);
assert_eq!(s.doc().unwrap().model.iter().count(), 0);
// Settings, typed or by Enter: no dialog yet, the first point is asked again.
for settings in ["S", ""] {
let mut s = session();
s.cmdline("QLEADER").unwrap();
s.cmdline(settings).unwrap();
assert!(s.log.iter().any(|l| l == "The QLEADER Settings dialog is not available yet."), "{settings:?}: {:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify first leader point, or [Settings] <Settings>:", "{settings:?}");
}
// LE starts it too.
let mut s = session();
s.cmdline("LE").unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Specify first leader point, or [Settings] <Settings>:");
}
#[test]
fn qleader_by_json() {
let mut s = session();
let r = s.execute("qleader", &json!({ "points": [[0, 0], [20, 15], [35, 30]], "width": 20, "text": "AB\r\nCD" })).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(2));
let want = vec![(0.0, 0.0), (20.0, 15.0), (32.5, 30.0), (35.0, 30.0)];
assert_eq!(drawn(&s), (want, Some(((35.625, 31.25), 2.5, 20.0, 1, "AB\\PCD".to_string()))));
// Text with nothing on its lines is no text: the leader alone, without a hook line.
for text in ["", "\n", "\r\n\r\n"] {
let mut s = session();
let r = s.execute("qleader", &json!({ "points": [[0, 0], [20, 15]], "width": 0, "text": text })).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(1), "{text:?}");
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0)], None), "{text:?}");
}
// Empty lines at the end are dropped: running left, the text sits as the command line puts it.
let mut s = session();
s.execute("qleader", &json!({ "points": [[0, 0], [-20, 15], [-40, 15]], "text": "AB\n\n" })).unwrap();
assert_eq!(drawn(&s).1, Some(((-40.625, 13.75), 2.5, 0.0, 9, "AB".to_string())));
// 2 or 3 points, a width of 0 or more, text as a string.
for bad in [
json!({ "points": [[0, 0]] }),
json!({ "points": [[0, 0], [1, 1], [2, 1], [3, 1]] }),
json!({ "points": [[0, 0], [1, 1]], "width": -1 }),
json!({ "points": [[0, 0], [1, 1]], "width": "x" }),
json!({ "points": [[0, 0], [1, 1]], "text": 5 }),
json!({ "points": [[0, 0], [1, 1]], "text": ["AB", "CD"] }),
] {
let before = s.doc().unwrap().model.iter().count();
assert!(s.execute("qleader", &bad).is_err(), "{bad}");
assert_eq!(s.doc().unwrap().model.iter().count(), before, "{bad}");
}
// A point that can't be read is named as such, not as missing points.
for (bad, says) in [
(json!({}), "`points` is required"),
(json!({ "points": null }), "`points` is required"),
(json!({ "points": [[0, 0], ["x", 1]] }), "`points` must be a list of [x, y] points"),
] {
let e = s.execute("qleader", &bad).unwrap_err().to_string();
assert!(e.contains(says), "{bad}: {e}");
}
}
+5 -3
View File
@@ -43,12 +43,14 @@ fn insertion_snaps_to_a_multileader_text() {
#[test]
fn geometric_center_of_a_closed_spline() {
let mut s = Session::new();
// A closed fit spline symmetric about (5,5): its centroid is the centre.
// A closed fit spline through the corners of a square: the centroid of its area, as AutoCAD
// 2024 gives it (MASSPROP of its region; the curve is not symmetric, its tangent where it
// closes comes from the first points).
s.execute("spline", &json!({"fit": [[0, 5], [5, 0], [10, 5], [5, 10]], "closed": true})).unwrap();
let c = Vec2::new(5.0, 5.0);
let c = Vec2::new(5.02693946, 5.04916453);
let hit = snap::osnap(s.doc().unwrap(), &Space::Model, c + Vec2::new(0.05, 0.0), 0.5, mode::GCEN, None, false).expect("a geometric center");
assert_eq!(hit.mode, mode::GCEN);
assert!(hit.point.dist(c) < 1e-3, "{:?}", hit.point);
assert!(hit.point.dist(c) < 1e-5, "{:?}", hit.point);
// An open spline has none.
let mut s = Session::new();
s.execute("spline", &json!({"fit": [[0, 5], [5, 0], [10, 5], [5, 10]]})).unwrap();
+47 -1
View File
@@ -21,6 +21,29 @@ fn logged(s: &Session, text: &str) -> bool {
const FIT: &str = "0,0 1,0.2 5,3 6,3.1 9,0";
#[test]
fn a_click_on_the_last_point_adds_no_fit_point() {
// AutoCAD 2024's SPLINE leaves a click on the point before out (measured with
// accoreconsole): no repeated fit point, so no kink.
let mut s = Session::new();
s.cmdline("spline 0,0 5,0 5,0 10,5").unwrap();
s.cmdline("").unwrap();
assert_eq!(last_spline(&s).fit, vec![Vec2::ZERO, Vec2::new(5.0, 0.0), Vec2::new(10.0, 5.0)]);
// Nor does the preview add one with the cursor on the last point: it shows the curve a
// click there would leave, not a corner.
let mut s = Session::new();
s.cmdline("spline 0,0 5,0 10,5").unwrap();
let shown: Vec<Vec<Vec2>> = s
.preview(Vec2::new(10.0, 5.0))
.into_iter()
.filter_map(|e| match e.kind {
EntityKind::Spline(sp) => Some(sp.fit),
_ => None,
})
.collect();
assert_eq!(shown, vec![vec![Vec2::ZERO, Vec2::new(5.0, 0.0), Vec2::new(10.0, 5.0)]]);
}
#[test]
fn knots_option_sets_the_parametrisation_and_is_remembered() {
let mut s = Session::new();
@@ -130,7 +153,9 @@ fn object_option_converts_polylines() {
assert_eq!(doc.model.iter().count(), 1, "converted in place");
let EntityKind::Spline(sp) = last(&s) else { panic!("not converted") };
assert_eq!(sp.fit.len(), n);
assert!(sp.eval(0.0).near(Vec2::ZERO, 1e-9) && sp.eval(1.0).near(Vec2::new(30.0, 10.0), 1e-9));
// Chord-length knots run over the length of the fit points, not 0..1.
let (lo, hi) = sp.domain();
assert!(sp.eval(lo).near(Vec2::ZERO, 1e-9) && sp.eval(hi).near(Vec2::new(30.0, 10.0), 1e-9));
// JSON form: a closed polyline becomes a closed spline; arcs are refused.
let sq = s.execute("pline", &json!({"vertices": [[0, 20], [10, 20], [10, 30], [0, 30]], "closed": true})).unwrap()["handle"].clone();
@@ -172,6 +197,27 @@ fn json_form_takes_the_fit_options() {
assert_eq!(sp.fit_opts.end_tangent, Some(-Vec2::Y));
}
#[test]
fn reverse_keeps_a_closed_spline_seam() {
// As AutoCAD 2024's REVERSE (accoreconsole, `entget`): the curve and its fit points still start
// at (0,0), the other fit points turn round, and so does the tangent where it closes; a
// fit-point grip or SPLINEDIT edit then rebuilds the same reversed curve.
let mut s = Session::new();
s.cmdline("spline 0,0 4,0 6,3 1,4 c").unwrap();
let before = last_spline(&s);
let h = s.doc().unwrap().model.iter().last().map(|e| e.handle.hex()).unwrap();
s.execute("reverse", &json!({ "handle": h })).unwrap();
let sp = last_spline(&s);
let fit = [Vec2::ZERO, Vec2::new(1.0, 4.0), Vec2::new(6.0, 3.0), Vec2::new(4.0, 0.0)];
assert_eq!(sp.fit, fit);
assert_eq!(sp.fit_opts.start_tangent, before.fit_opts.start_tangent.map(|t| -t));
let (lo, hi) = sp.domain();
assert!(sp.eval(lo).near(Vec2::ZERO, 1e-12) && sp.eval(hi).near(Vec2::ZERO, 1e-12));
s.execute("splinedit", &json!({ "handle": h, "option": "move", "index": 2, "to": [6, 3] })).unwrap();
let again = last_spline(&s);
assert!(again.control.iter().zip(&sp.control).all(|(a, b)| a.near(*b, 1e-9)), "{:?} vs {:?}", again.control, sp.control);
}
#[test]
fn cv_method_keeps_cv_on_enter_and_can_switch_back_to_fit() {
for entry in ["spline.cv", "spline m cv"] {
@@ -23,6 +23,7 @@ fn install() {
});
set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
cadcraft_engine::cmd::file::set_dwg_notes(cadcraft_io::dwg_notes);
}
/// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes.
@@ -117,6 +118,60 @@ fn legacy_visualstyles_warn_only_for_2007_dwg() {
}
}
/// A linetype with more dash elements than a DWG counts is saved with its first 255, and each
/// way of writing a DWG says so in one note (#1923, F-05); a DXF keeps it whole and says nothing.
#[test]
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
fn a_dwg_save_notes_the_linetypes_it_cuts() {
use cadcraft_engine::doc::{Common, DashElement, EntityKind, Line, Linetype, Space};
use cadcraft_engine::geom::Vec3;
install();
cadcraft_io::dwg_worker::allow_in_process();
let dir = TempDir::new("ltype-notes");
let linetype = |name: &str, n: usize| Linetype {
name: name.into(),
description: String::new(),
pattern: (0..n).map(|i| DashElement::dash(if i % 2 == 0 { 1.0 } else { -0.5 })).collect(),
};
let mut d = Drawing::new_metric();
d.linetypes.extend([linetype("LONG", 256), linetype("FITS", 255)]);
// Lines drawn with it in model space and on a sheet, so WBLOCK and LAYOUT SAVEAS keep it.
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) });
let common = Common { linetype: "LONG".into(), ..Common::default() };
let model_line = d.add(&Space::Model, common.clone(), line.clone()).unwrap();
d.add(&Space::Paper("Layout1".into()), common, line).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "ltypes.dxf", None);
let one_note = |r: &Value| matches!(r["warnings"].as_array().map(Vec::as_slice), Some([note]) if note.as_str().is_some_and(|t| t.contains("1 linetype") && t.contains("255")));
let notes_since = |s: &Session, n: usize| s.log[n..].iter().filter(|l| l.contains("dash elements")).count();
let dwg = dir.path_str("out.dwg");
let writes = [
("saveas", json!({ "path": dwg })),
("document.bytes", json!({ "format": "dwg" })),
("export", json!({ "format": "dwg" })),
("wblock", json!({ "path": dir.path_str("all.dwg"), "name": "*" })),
("layout.saveas", json!({ "name": "Layout1", "path": dir.path_str("sheet.dwg") })),
("-wblock", json!({ "path": dir.path_str("line.dwg"), "handles": [model_line.0] })),
];
for (cmd, p) in writes {
let n = s.log.len();
let r = s.execute(cmd, &p).unwrap();
assert!(one_note(&r), "{cmd}: {r}");
assert_eq!(notes_since(&s, n), 1, "{cmd}: {:?}", &s.log[n..]);
}
// -WBLOCK at the command line says it too (a DWG file has no precision prompt).
let n = s.log.len();
let path = dir.path_str("typed.dwg").replace('\\', "/");
s.cmdline(&format!("(command \"_.-WBLOCK\" \"{path}\" \"*\")")).unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(notes_since(&s, n), 1, "{:?}", &s.log[n..]);
let back = cadcraft_io::read(&std::fs::read(&dwg).unwrap(), "out.dwg").unwrap();
assert_eq!(back.linetype("LONG").map(|l| l.pattern.len()), Some(255));
let n = s.log.len();
let r = s.execute("saveas", &json!({ "path": dir.path_str("out.dxf") })).unwrap();
assert!(r.get("warnings").is_none() && !s.log[n..].iter().any(|l| l.contains("dash elements")), "{r} {:?}", &s.log[n..]);
}
#[test]
fn a_proxy_no_version_writes_is_not_reported() {
install();
+8
View File
@@ -64,6 +64,14 @@ mod tests {
let _ = crate::ttf::fallback_for('\u{65E5}');
}
#[test]
fn lookups_cached_per_thread_see_a_font_registered_later() {
// Asked before it exists (cached as missing), then registered: found.
assert!(crate::ttf::find("CADCraft Late Test").is_none());
crate::ttf::register_static("cadcraftlatetest-regular", &TINY_SFNT);
assert!(crate::ttf::find("CADCraft Late Test").is_some());
}
#[test]
fn no_barred_family_is_embedded() {
// AGENTS.md: no Adobe fonts. Noto Sans CJK is Source Han Sans; `build.rs` skips them.
+202 -4
View File
@@ -22,11 +22,13 @@
//! Fonts) are searched first: a font placed there wins over an installed one with the same file
//! name.
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, RwLock};
use cadcraft_geom::Vec2;
use cadcraft_geom::{Bounds2, Vec2};
use skrifa::instance::{LocationRef, Size};
use skrifa::outline::{DrawSettings, OutlinePen};
use skrifa::raw::FileRef;
@@ -498,6 +500,8 @@ pub fn rescan() {
g.face_names.clear();
drop(g);
GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
// The per-thread lookup caches start over too: the folders' fonts are gone from the shared tables.
changed();
// SHX files in the same folders: the SHX font table looks there too.
crate::shx::set_font_dirs(shx_dirs(&user_dirs()));
}
@@ -835,6 +839,7 @@ pub fn register(name: &str, bytes: Vec<u8>) {
g.registered.insert(k);
g.resolved.clear();
g.fallback = Fallback::default();
changed();
}
/// Register font bytes that live for the whole process under a name; they are copied only when
@@ -848,6 +853,7 @@ pub(crate) fn register_static(name: &str, bytes: &'static [u8]) {
g.paths.insert(k, Source::Static(bytes));
g.resolved.clear();
g.fallback = Fallback::default();
changed();
}
/// Normalise a style font name ("arial.ttf", "Arial", "ARIALBD.TTF") to a lookup key.
@@ -867,9 +873,98 @@ fn is_stroke_name(k: &str) -> bool {
|| k == "romans"
}
/// Bumped whenever a font lookup can answer differently (a font registered, FONTALT or
/// FONTFALLBACK changed), so the per-thread caches start over.
static LOOKUP_GENERATION: AtomicU64 = AtomicU64::new(0);
fn changed() {
// Release: a thread that sees the new generation also sees what changed.
LOOKUP_GENERATION.fetch_add(1, Ordering::Release);
}
/// The generation now, taken before a lookup whose answer [`keep`] may cache.
fn lookup_generation() -> u64 {
LOOKUP_GENERATION.load(Ordering::Acquire)
}
/// `f` on this thread's cache, only when lookups haven't changed since `seen` ([`lookup_generation`]
/// before the lookup): an answer found while a font was being registered may be the old one, and
/// is used once but not kept.
fn keep(seen: u64, f: impl FnOnce(&mut Local)) {
LOCAL.with(|l| {
let mut l = l.borrow_mut();
// Kept under `seen` itself: should lookups change after this check, the next lookup
// finds a newer generation and starts over without it.
if lookup_generation() != seen {
return;
}
if l.generation != seen {
*l = Local { generation: seen, ..Local::default() };
}
f(&mut l);
});
}
/// Most entries each per-thread cache holds before it starts over.
const MAX_LOCAL: usize = 8192;
/// Per-thread answers of [`find`] (by the name as given) and [`fallback_for`]. Display lists are
/// built on all cores and look a font up for every text and a fallback for every character a
/// text's font lacks (all of a CJK text's): through the shared tables each lookup took global
/// locks, so text-heavy drawings spent most of their build waiting on them (#662, #666).
#[derive(Default)]
struct Local {
generation: u64,
find: HashMap<String, Option<Face>>,
fallback: HashMap<char, Option<Face>>,
/// FONTALT, asked for every text whose font isn't installed.
alt: Option<String>,
/// Glyph outlines, in front of the shared [`glyph_cache`] (whose lock every core reads).
glyphs: HashMap<GlyphCacheKey, Arc<GlyphOutline>>,
/// The points of the outlines in `glyphs`, held within [`MAX_LOCAL_GLYPH_POINTS`].
glyph_points: usize,
}
/// Most outline points each thread keeps in front of the shared cache: a part of its budget, since
/// every core has its own and they keep outlines alive after the shared cache lets them go. An
/// outline above a quarter of it is read from the shared cache each time.
const MAX_LOCAL_GLYPH_POINTS: usize = MAX_SHAPED_POINTS / 16;
thread_local! {
static LOCAL: RefCell<Local> = RefCell::new(Local::default());
}
/// `f` on this thread's cache, emptied first when lookups changed since it was filled.
fn local<R>(f: impl FnOnce(&mut Local) -> R) -> R {
LOCAL.with(|l| {
let mut l = l.borrow_mut();
let generation = lookup_generation();
if l.generation != generation {
*l = Local { generation, ..Local::default() };
}
f(&mut l)
})
}
/// A face of an installed (or registered) font by file name or family name. Stroke-font names
/// (".shx", empty) return `None`.
pub fn find(name: &str) -> Option<Face> {
if let Some(r) = local(|l| l.find.get(name).cloned()) {
return r;
}
let seen = lookup_generation();
let r = find_shared(name);
keep(seen, |l| {
if l.find.len() >= MAX_LOCAL {
l.find.clear();
}
l.find.insert(name.to_string(), r.clone());
});
r
}
/// [`find`] through the shared table.
fn find_shared(name: &str) -> Option<Face> {
let k = key(name);
if is_stroke_name(&k) {
return None;
@@ -919,12 +1014,19 @@ fn split_list(s: &str) -> Vec<String> {
/// FONTALT: the font used for a text style font that can't be found. Empty = the built-in
/// stroke font.
pub fn font_alt() -> String {
prefs().alt.clone()
if let Some(a) = local(|l| l.alt.clone()) {
return a;
}
let seen = lookup_generation();
let a = prefs().alt.clone();
keep(seen, |l| l.alt = Some(a.clone()));
a
}
/// Set FONTALT ("" or "." clears it).
pub fn set_font_alt(name: &str) {
prefs().alt = clean_name(name);
changed();
}
/// FONTFALLBACK: fonts tried first for characters a text's font lacks, comma-separated.
@@ -935,6 +1037,7 @@ pub fn fallback_fonts() -> String {
/// Set FONTFALLBACK from a comma- or semicolon-separated list ("" or "." clears it).
pub fn set_fallback_fonts(list: &str) {
prefs().fallback = split_list(list);
changed();
}
/// Characters worth a fallback search (not spaces, controls or private-use code points).
@@ -949,6 +1052,22 @@ pub fn fallback_for(c: char) -> Option<Face> {
if !wants_fallback(c) {
return None;
}
if let Some(r) = local(|l| l.fallback.get(&c).cloned()) {
return r;
}
let seen = lookup_generation();
let r = fallback_shared(c);
keep(seen, |l| {
if l.fallback.len() >= MAX_LOCAL {
l.fallback.clear();
}
l.fallback.insert(c, r.clone());
});
r
}
/// [`fallback_for`] through the shared tables.
fn fallback_shared(c: char) -> Option<Face> {
let (list, alt) = {
let p = prefs();
(p.fallback.clone(), p.alt.clone())
@@ -969,6 +1088,8 @@ pub fn fallback_for(c: char) -> Option<Face> {
pub(crate) struct GlyphOutline {
pub(crate) contours: Arc<[Vec<Vec2>]>,
pub(crate) points: usize,
/// The extent of `contours`, found once as the outline is built (empty when it has none).
bounds: Bounds2,
pub(crate) advance: f64,
pub(crate) cap: f64,
/// The font maps the character (false: the missing-glyph shape).
@@ -988,9 +1109,10 @@ enum GlyphKey {
/// Cached glyph outlines keyed by (font bytes address, length, face, glyph). Fonts live for the
/// whole process in the font table, so the address identifies them. A read-write lock: display
/// lists are built on all cores and nearly every lookup is a hit, which a mutex serialized.
type GlyphCacheKey = (usize, usize, u32, GlyphKey);
#[derive(Default)]
struct GlyphCache {
glyphs: HashMap<(usize, usize, u32, GlyphKey), Arc<GlyphOutline>>,
glyphs: HashMap<GlyphCacheKey, Arc<GlyphOutline>>,
points: usize,
}
@@ -1163,10 +1285,45 @@ pub fn glyph_contours(face: &Face, gid: u16) -> Arc<[Vec<Vec2>]> {
glyph_by_id(face, u32::from(gid)).contours.clone()
}
/// The extent of [`glyph_contours`] in the same font units (empty for a glyph without ink), so
/// renderers can test a placement against a view without visiting the outline's points.
pub fn glyph_bounds(face: &Face, gid: u16) -> Bounds2 {
glyph_by_id(face, u32::from(gid)).bounds
}
/// Load or build a glyph outline with bounded flattening, retaining its advance even when contours are discarded.
/// Cache insertion clears existing entries when the glyph-count or aggregate point allowance would be exceeded.
fn outline(face: &Face, k: GlyphKey) -> Arc<GlyphOutline> {
let key = (face.bytes.as_ptr() as usize, face.bytes.len(), face.index, k);
if let Some(g) = local(|l| l.glyphs.get(&key).cloned()) {
return g;
}
let g = outline_shared(face, key);
local(|l| l.keep_glyph(key, &g));
g
}
impl Local {
/// Keep an outline in front of the shared cache, within [`MAX_LOCAL`] entries and
/// [`MAX_LOCAL_GLYPH_POINTS`] points (started over when either would be passed); an outline
/// above a quarter of the points isn't kept.
fn keep_glyph(&mut self, key: GlyphCacheKey, g: &Arc<GlyphOutline>) {
if g.points > MAX_LOCAL_GLYPH_POINTS / 4 {
return;
}
if self.glyphs.len() >= MAX_LOCAL || self.glyph_points.saturating_add(g.points) > MAX_LOCAL_GLYPH_POINTS {
self.glyphs.clear();
self.glyph_points = 0;
}
if self.glyphs.insert(key, g.clone()).is_none() {
self.glyph_points = self.glyph_points.saturating_add(g.points);
}
}
}
/// [`outline`] through the shared cache.
fn outline_shared(face: &Face, key: GlyphCacheKey) -> Arc<GlyphOutline> {
let k = key.3;
if let Some(g) = glyph_cache().read().unwrap_or_else(PoisonError::into_inner).glyphs.get(&key) {
return g.clone();
}
@@ -1184,7 +1341,8 @@ fn outline(face: &Face, k: GlyphKey) -> Arc<GlyphOutline> {
let advance = f64::from(f.glyph_metrics(Size::new(UPEM), LocationRef::default()).advance_width(gid).unwrap_or(UPEM * 0.5));
let (cap, mapped, gid) = (cap_height(&f), mapped.is_some(), gid.to_u32());
let points = pen.contours.iter().map(Vec::len).sum();
let g = Arc::new(GlyphOutline { points, contours: pen.contours.into(), advance, cap, mapped, gid, face: Some(face.clone()) });
let bounds = Bounds2::from_points(pen.contours.iter().flatten().copied());
let g = Arc::new(GlyphOutline { points, bounds, contours: pen.contours.into(), advance, cap, mapped, gid, face: Some(face.clone()) });
let mut cache = glyph_cache().write().unwrap_or_else(PoisonError::into_inner);
if cache.glyphs.len() >= MAX_CACHED_GLYPHS || cache.points.saturating_add(points) > MAX_SHAPED_POINTS {
cache.glyphs.clear();
@@ -1601,6 +1759,46 @@ mod geometry_budget_tests {
}
}
#[cfg(test)]
mod local_cache_tests {
use super::*;
/// An answer looked up while lookups changed (a font registered meanwhile) is not kept: the
/// thread asks again instead of keeping a stale "not found".
#[test]
fn a_lookup_overtaken_by_a_change_is_not_kept() {
let seen = lookup_generation();
changed();
keep(seen, |l| l.alt = Some("stale".into()));
assert_ne!(local(|l| l.alt.clone()), Some("stale".to_string()));
let now = lookup_generation();
keep(now, |l| l.alt = Some("fresh".into()));
// Kept unless yet another change came in between (other tests may register fonts).
let cached = local(|l| l.alt.clone());
if lookup_generation() == now {
assert_eq!(cached, Some("fresh".to_string()));
}
}
/// Each thread's outlines stay within [`MAX_LOCAL_GLYPH_POINTS`], and an outline too large
/// for it isn't kept.
#[test]
fn a_threads_outlines_stay_within_their_point_budget() {
let mut l = Local::default();
let key = |i: u32| (0usize, 0usize, 0u32, GlyphKey::Id(i));
let big = MAX_LOCAL_GLYPH_POINTS / 8;
let g = Arc::new(GlyphOutline { points: big, cap: 1.0, ..Default::default() });
for i in 0..100 {
l.keep_glyph(key(i), &g);
assert!(l.glyph_points <= MAX_LOCAL_GLYPH_POINTS, "{}", l.glyph_points);
assert_eq!(l.glyph_points, l.glyphs.len() * big);
}
let huge = Arc::new(GlyphOutline { points: MAX_LOCAL_GLYPH_POINTS / 2, cap: 1.0, ..Default::default() });
l.keep_glyph(key(500), &huge);
assert!(!l.glyphs.contains_key(&key(500)), "an outline above a quarter of the budget isn't kept");
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod scan_tests {
use super::*;
+32 -5
View File
@@ -94,6 +94,21 @@ fn elevate_bezier(p: &[H]) -> Vec<H> {
.collect()
}
/// A closed spline's fit points in the other direction, still from the seam: the first point
/// (with its repeats, a kink) stays first and the rest turn round, as AutoCAD 2024's REVERSE
/// leaves them; a repeated closing point stays last.
fn reversed_loop(fit: &[Vec2]) -> Vec<Vec2> {
let Some(seam) = fit.first().copied() else { return Vec::new() };
let at_seam = |q: &&Vec2| q.near(seam, 1e-12);
let lead = fit.iter().take_while(at_seam).count();
let trail = fit.iter().skip(lead).rev().take_while(at_seam).count();
let middle = fit.get(lead..fit.len() - trail).unwrap_or(&[]);
let mut out = fit.get(..lead).unwrap_or(&[]).to_vec();
out.extend(middle.iter().rev());
out.extend(fit.get(fit.len() - trail..).unwrap_or(&[]));
out
}
/// Basis functions of degree `p` in `n[..=p]` and of degree `p - 1` in `lower[..p]` for `p >= 1`,
/// in one Cox-de Boor sweep: the degree `p - 1` values are the state just before the last step,
/// so they match [`basis`] exactly. `left` and `right` are scratch of `p + 1` values; the outputs
@@ -346,7 +361,7 @@ impl Spline {
}
/// Reversed direction: control points, weights, fit points and knots (and the fit end
/// tangents swap ends and turn round).
/// tangents swap ends and turn round). A closed spline still starts at its first fit point.
pub fn reversed(&self) -> Spline {
let (lo, hi) = (self.knots.first().copied().unwrap_or(0.0), self.knots.last().copied().unwrap_or(1.0));
Spline {
@@ -354,7 +369,7 @@ impl Spline {
knots: self.knots.iter().rev().map(|k| lo + hi - k).collect(),
control: self.control.iter().rev().copied().collect(),
weights: self.weights.iter().rev().copied().collect(),
fit: self.fit.iter().rev().copied().collect(),
fit: if self.closed { reversed_loop(&self.fit) } else { self.fit.iter().rev().copied().collect() },
closed: self.closed,
fit_opts: crate::FitOptions {
start_tangent: self.fit_opts.end_tangent.map(|t| -t),
@@ -846,13 +861,25 @@ mod tests {
assert!(s.split_at(0.0).is_none() && s.split_at(f64::NAN).is_none());
}
#[test]
fn a_closed_fit_list_reverses_from_its_seam() {
let (a, b, c, d) = (Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(6.0, 3.0), Vec2::new(1.0, 4.0));
assert_eq!(reversed_loop(&[a, b, c, d]), [a, d, c, b]);
// A kink at the seam stays first, a repeated closing point last.
assert_eq!(reversed_loop(&[a, a, b, c, d]), [a, a, d, c, b]);
assert_eq!(reversed_loop(&[a, b, c, d, a]), [a, d, c, b, a]);
assert_eq!(reversed_loop(&[a, a]), [a, a]);
assert!(reversed_loop(&[]).is_empty());
}
#[test]
fn periodic_spline_clamps_to_the_same_curve() {
let fit = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 1.0), Vec2::new(5.0, 4.0), Vec2::new(1.0, 5.0)];
let p = Spline::from_fit(&fit, true);
assert!(p.is_periodic());
// Uniform parameters: the control points wrap round (a chord-length fit is clamped).
let p = Spline::fit_with(&fit, true, crate::FitOptions { knots: crate::KnotParam::Uniform, ..Default::default() });
assert!(p.wraps() && p.is_periodic());
let c = p.clamped().unwrap();
assert!(!c.is_periodic());
assert!(!c.wraps() && c.is_periodic(), "the same smooth closed curve");
let ((plo, phi), (clo, chi)) = (p.domain(), c.domain());
for i in 0..=20 {
let f = f64::from(i) / 20.0;
+25 -5
View File
@@ -43,10 +43,10 @@ impl Spline {
Spline::fit_with(fit, false, FitOptions::default())
}
/// Smooth closed (periodic) cubic interpolation through fit points. Chord-length parameters
/// include the closing chord; the knot vector is the periodic (unclamped) extension and the
/// first `degree` control points repeat at the end, so the curve has continuous tangent and
/// curvature at the seam. A repeated closing fit point is dropped.
/// Smooth closed cubic interpolation through fit points, as AutoCAD 2024 builds it: through
/// the fit points and back to the first, with chord-length parameters, clamped, and with the
/// same first derivative at both ends (see `Spline::fit_with`). A repeated closing fit point
/// is dropped.
pub fn from_fit_points_closed(fit: &[Vec2]) -> Spline {
Spline::fit_with(fit, true, FitOptions::default())
}
@@ -56,11 +56,31 @@ impl Spline {
Spline::fit_with(fit, closed, FitOptions::default())
}
/// Closed with an unclamped (periodic) knot vector, as DXF flags it (group 70 bit 2).
/// Closed and smooth where it closes: AutoCAD's "periodic" (DXF group 70 bit 2), which
/// AutoCAD 2024 sets from the curve itself. Either the control points wrap round
/// ([`Spline::wraps`]), or the knots are clamped and the curve has the same first derivative
/// at both ends, as in AutoCAD's closed fit-point spline. The same direction with another
/// length is not enough: AutoCAD clears the bit then too.
pub fn is_periodic(&self) -> bool {
self.wraps() || (self.closed && self.is_valid() && self.closes_smoothly())
}
/// Closed with an unclamped knot vector: the first `degree` control points repeat at the end,
/// so the control points wrap round the seam (the knot shape; see [`Spline::is_periodic`]
/// for the curve's).
pub fn wraps(&self) -> bool {
self.closed && self.knots.first() != self.knots.get(self.degree)
}
/// The ends meet with the same first derivative (to 1e-9 of its length). The spline must be
/// valid.
fn closes_smoothly(&self) -> bool {
let (lo, hi) = self.domain();
let (d0, d1) = (self.derivative(lo), self.derivative(hi));
let speed = d0.len().max(d1.len());
speed > 0.0 && d0.near(d1, 1e-9 * speed) && self.eval(lo).near(self.eval(hi), 1e-9 * speed * (hi - lo))
}
pub fn is_valid(&self) -> bool {
let n = self.control.len();
n > self.degree
+20 -3
View File
@@ -550,22 +550,39 @@ fn fits_are_bit_identical_to_the_dense_solver() {
let tolerant = FitOptions { tolerance: 0.5, ..FitOptions::default() };
let tangents = FitOptions { start_tangent: Some(Vec2::new(0.0, 1.0)), end_tangent: Some(Vec2::new(1.0, -1.0)), ..FitOptions::default() };
let chord = FitOptions { knots: crate::KnotParam::Chord, ..FitOptions::default() };
// Chord-length knots fit open curves with `chord_interpolate` and closed ones with
// `chord_closed`; the others with `interpolate`, whose end tangents add rows of their own, and
// with the cyclic matrix.
let sqrt = FitOptions { knots: crate::KnotParam::SqrtChord, ..FitOptions::default() };
let uniform = FitOptions { knots: crate::KnotParam::Uniform, ..FitOptions::default() };
let sqrt_tangents = FitOptions { knots: crate::KnotParam::SqrtChord, ..tangents };
for n in [3, 4, 5, 7, 12, 30, 100] {
for round in 0..4 {
let zero_every = [0, 2, 3, 1][round];
let pts = fit_points(n, &mut seed, zero_every);
for closed in [false, true] {
for (name, opts) in [("default", FitOptions::default()), ("tolerance", tolerant), ("tangents", tangents), ("chord", chord)] {
for (name, opts) in [
("default", FitOptions::default()),
("tolerance", tolerant),
("tangents", tangents),
("chord", chord),
("sqrt", sqrt),
("uniform", uniform),
("sqrt tangents", sqrt_tangents),
] {
assert_fit_unchanged(&pts, closed, opts, &format!("n={n} closed={closed} {name} zero_every={zero_every}"));
}
}
}
}
// Large point sets: open interpolation (banded) and a closed one (full bandwidth), and a
// tolerance fit at the size the approximation search still accepts.
// Large point sets: open and closed interpolation with chord-length and square-root knots (the
// closed square-root one is the cyclic matrix, full bandwidth), and a tolerance fit at the size
// the approximation search still accepts.
let big = fit_points(1000, &mut seed, 0);
assert_fit_unchanged(&big, false, FitOptions::default(), "n=1000 open");
assert_fit_unchanged(&big, false, sqrt, "n=1000 open sqrt");
assert_fit_unchanged(&big[..150], true, FitOptions::default(), "n=150 closed");
assert_fit_unchanged(&big[..150], true, sqrt, "n=150 closed sqrt");
assert_fit_unchanged(&big[..300], false, tolerant, "n=300 tolerance");
// Repeated points are kinks, which fit each piece on its own.
let mut kinked = fit_points(40, &mut seed, 0);
+640 -39
View File
@@ -67,10 +67,13 @@ impl KnotParam {
pub struct FitOptions {
#[serde(default)]
pub knots: KnotParam,
/// Unit tangent direction at the first fit point; `None` lets the end follow the points.
/// Tangent at the first fit point; `None` lets the end follow the points. SPLINE, SPLINEDIT
/// and the JSON options give a unit direction; one read from a file keeps its length through
/// refits and transforms ([`Spline::fit_with_end_derivatives`]). A closed spline with
/// chord-length knots keeps its tangent where it closes here and as the end tangent.
#[serde(default)]
pub start_tangent: Option<Vec2>,
/// Unit tangent direction at the last fit point.
/// Tangent at the last fit point, as the start one.
#[serde(default)]
pub end_tangent: Option<Vec2>,
/// Largest allowed distance between the curve and a fit point; 0 passes through them.
@@ -79,14 +82,22 @@ pub struct FitOptions {
}
impl FitOptions {
/// Normalised tangents (zero or non-finite directions dropped) and a finite, non-negative
/// tolerance: what a spline stores.
/// Normalised tangents (non-finite directions and those too short to normalise dropped) and a
/// finite, non-negative tolerance: what [`Spline::fit_with`] stores.
pub fn sanitized(self) -> FitOptions {
let dir = |t: Option<Vec2>| t.filter(|v| v.x.is_finite() && v.y.is_finite() && v.len() > 1e-12).map(Vec2::normalized);
let o = self.sanitized_keeping_length();
// `normalized` gives zero for a direction too short to scale to a unit.
let unit = |t: Option<Vec2>| t.map(Vec2::normalized).filter(|d| d.len() > 0.5);
FitOptions { start_tangent: unit(o.start_tangent), end_tangent: unit(o.end_tangent), ..o }
}
/// As [`FitOptions::sanitized`], but the tangents keep their length.
pub fn sanitized_keeping_length(self) -> FitOptions {
let valid = |t: Option<Vec2>| t.filter(|v| v.x.is_finite() && v.y.is_finite() && v.len() > 1e-12);
FitOptions {
knots: self.knots,
start_tangent: dir(self.start_tangent),
end_tangent: dir(self.end_tangent),
start_tangent: valid(self.start_tangent),
end_tangent: valid(self.end_tangent),
tolerance: if self.tolerance.is_finite() { self.tolerance.max(0.0) } else { 0.0 },
}
}
@@ -103,31 +114,34 @@ const MAX_INTERP_POINTS: usize = 4_096;
impl Spline {
/// Build a spline through (or, with a tolerance, near) `fit`, open or closed. Closed curves
/// are periodic and ignore end tangents; a tolerance approximates them with fewer periodic
/// are smooth where they close and ignore the end tangents given. With chord-length knots
/// they are clamped as AutoCAD 2024 builds them, and keep AutoCAD's tangent where they close
/// as both end tangents (which [`Spline::refit`] then keeps, as AutoCAD keeps 12/13);
/// otherwise their knots are periodic. A tolerance approximates them with fewer periodic
/// control points. A fit point given twice in a row is a kink (SPLINEDIT Fit data Kink): the
/// curve passes through it with a corner (a knot of full multiplicity) and the pieces on
/// either side are fitted on their own.
pub fn fit_with(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline {
let opts = opts.sanitized();
let kinked = if fit.len() <= MAX_KINK_POINTS { kinked_fit(fit, closed, opts) } else { None };
let mut s = if let Some(s) = kinked {
s
} else {
// Repeats at the ends of an open curve are no corners: fit without them.
let (pts, _) = kinks(fit, false);
let mut s = if closed { closed_fit(&pts, opts.knots, opts.tolerance) } else { open_fit(&pts, opts) };
if pts.len() != fit.len() && !closed {
s.fit = fit.to_vec();
}
s
};
s.fit_opts = if closed { FitOptions { start_tangent: None, end_tangent: None, ..opts } } else { opts };
s
let opts = if closed { FitOptions { start_tangent: None, end_tangent: None, ..opts } } else { opts };
fit_sanitized(fit, closed, opts.sanitized())
}
/// As [`Spline::fit_with`], but an end tangent is the end derivative itself, length included
/// (per unit of chord with chord-length knots), as AutoCAD 2024 rebuilds a SPLINE stored with
/// fit data only (DXF 12/13): with 12 = (0, 3) the second control point is three times as far
/// from the first as with (0, 1). `fit_with`, behind SPLINE and the JSON options, takes
/// tangents as directions. A closed spline with chord-length knots takes the start tangent
/// (its stored tangent where it closes) at both ends, as AutoCAD keeps it through fit-point
/// edits, REVERSE and DXF.
pub fn fit_with_end_derivatives(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline {
fit_sanitized(fit, closed, opts.sanitized_keeping_length())
}
/// Rebuild from new fit points with this spline's knot parametrisation, tangents and tolerance.
/// The tangents count as stored, so one read from a file keeps its length, as in AutoCAD's
/// SPLINEDIT Fit data Move.
pub fn refit(&self, fit: &[Vec2], closed: bool) -> Spline {
Spline::fit_with(fit, closed, self.fit_opts)
Spline::fit_with_end_derivatives(fit, closed, self.fit_opts)
}
/// Which knot parametrisation produced this spline's knots from its fit points (DXF files
@@ -190,12 +204,26 @@ impl Spline {
.unwrap_or(KnotParam::Chord)
}
/// Apply an affine map to the control and fit points and turn the end tangents with it.
/// Apply an affine map to the control and fit points and turn the end tangents with it. A
/// tangent keeps its length, as in AutoCAD, where SCALE 2 leaves 12 = (0, 3) as it is. A map
/// that flattens a tangent's direction (to under EPS of the map's largest axis scale) drops it.
pub fn transform(&mut self, m: &Mat3) {
for c in self.control.iter_mut().chain(self.fit.iter_mut()) {
*c = m.apply(*c);
}
let turn = |t: Option<Vec2>| t.map(|v| m.apply_vec(v).normalized()).filter(|v| v.len() > 0.5);
// The map's largest axis scale: a direction it shrinks to under EPS of that is flattened.
// Not `scale_factor`, which is 0 for a singular map and would keep rounding noise.
let scale = Vec2::new(m.a, m.b).len().max(Vec2::new(m.c, m.d).len());
let turn = |t: Option<Vec2>| {
t.and_then(|v| {
let w = m.apply_vec(v);
let (lv, lw) = (v.len(), w.len());
// Scaled by lengths, not through `normalized`, which zeroes a short tangent. A map
// that flattens the tangent's direction drops it; an invertible uniform scale,
// however small, does not.
(lw.is_finite() && lw > crate::EPS * scale * lv).then(|| w / lw * lv)
})
};
self.fit_opts.start_tangent = turn(self.fit_opts.start_tangent);
self.fit_opts.end_tangent = turn(self.fit_opts.end_tangent);
}
@@ -224,10 +252,32 @@ fn chord_length(pts: &[Vec2]) -> f64 {
pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.dist(*b))).sum()
}
/// [`Spline::fit_with`] with `opts` already sanitized.
fn fit_sanitized(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline {
let kinked = if fit.len() <= MAX_KINK_POINTS { kinked_fit(fit, closed, opts) } else { None };
let mut s = if let Some(s) = kinked {
s
} else {
// Repeats at the ends of an open curve are no corners: fit without them.
let (pts, _) = kinks(fit, false);
let mut s = if closed { closed_fit(&pts, opts.knots, opts.tolerance, opts.start_tangent) } else { open_fit(&pts, opts) };
if pts.len() != fit.len() && !closed {
s.fit = fit.to_vec();
}
s
};
// A closed spline keeps only the tangent its fit used where it closes.
s.fit_opts = if closed { FitOptions { start_tangent: s.fit_opts.start_tangent, end_tangent: s.fit_opts.end_tangent, ..opts } } else { opts };
s
}
fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline {
let n = fit.len();
let tangents = opts.start_tangent.is_some() || opts.end_tangent.is_some();
if n < 2 || (n == 2 && !tangents) {
// Two points without tangents are a line, except that AutoCAD 2024's chord-length fit makes
// it a cubic ([`chord_interpolate`]: control points at the thirds), with a fit tolerance too.
let chord_fit = opts.knots == KnotParam::Chord;
if n < 2 || (n == 2 && !tangents && !chord_fit) {
let mut s = if n < 2 {
Spline { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], control: fit.to_vec(), ..Spline::default() }
} else {
@@ -237,7 +287,8 @@ fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline {
return s;
}
let u = params(fit, opts.knots, false);
// Tangents are directions; the derivative's length is the curve length in parameter space.
// A tangent is the derivative per unit of chord (a unit direction unless read from a file):
// per unit of the normalised parameter it is that times the chord length.
let len = chord_length(fit).max(1e-12);
let d0 = opts.start_tangent.map(|t| t * len);
let d1 = opts.end_tangent.map(|t| t * len);
@@ -255,7 +306,131 @@ fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline {
if n > MAX_INTERP_POINTS {
return through_control();
}
interpolate(fit, &u, d0, d1).unwrap_or_else(through_control)
// No approximation (none asked for, too few or too many points for one, or none within the
// tolerance): the curve passes through the points. With chord-length knots it is AutoCAD
// 2024's interpolation (measured without a tolerance, and for two points with one); the other
// parametrisations interpolate with normalised knots.
let chord = if opts.knots == KnotParam::Chord { chord_interpolate(fit, opts.start_tangent, opts.end_tangent) } else { None };
chord.or_else(|| interpolate(fit, &u, d0, d1)).unwrap_or_else(through_control)
}
/// AutoCAD 2024's cubic through fit points with chord-length parameters, as it builds a fit-point
/// spline: the parameters are the running chord length, not normalised, and they are the interior
/// knots themselves; two control points more than fit points meet the end conditions. An end with
/// a tangent has it as its first derivative, length included (one per unit of chord for a unit
/// direction); an end without one has no curvature (second derivative 0). `None` for fewer than
/// two points or two in the same place.
fn chord_interpolate(fit: &[Vec2], d0: Option<Vec2>, d1: Option<Vec2>) -> Option<Spline> {
let n = fit.len();
if n < 2 {
return None;
}
let mut t = Vec::with_capacity(n);
let mut total = 0.0;
t.push(total);
for w in fit.windows(2) {
let (a, b) = (w.first()?, w.get(1)?);
let d = a.dist(*b);
if !(d > 0.0 && d.is_finite()) {
return None;
}
total += d;
t.push(total);
}
let p = 3;
let m = n + 2;
let mut knots = vec![0.0; p + 1];
knots.extend(t.get(1..n - 1)?.iter().copied());
knots.extend([total; 4]);
let k = |i: usize| knots.get(i).copied().unwrap_or(0.0);
let mut a = vec![vec![0.0; m]; m];
let (mut xs, mut ys) = (vec![0.0; m], vec![0.0; m]);
let mut row = 0;
let mut put = |coeffs: &[(usize, f64)], rhs: Vec2, a: &mut Vec<Vec<f64>>| {
if let Some(r) = a.get_mut(row) {
for (j, v) in coeffs {
if let Some(c) = r.get_mut(*j) {
*c += *v;
}
}
}
if let (Some(x), Some(y)) = (xs.get_mut(row), ys.get_mut(row)) {
(*x, *y) = (rhs.x, rhs.y);
}
row += 1;
};
// At the start the first derivative is 3 (P1 - P0) / k(4), and the second derivative is 0
// when (P1 - P0) / k(4) = (P2 - P1) / k(5); the end mirrors it. Each end's row sits next to
// that end's point rows, so the system stays banded for `solve`.
let (s1, s2) = (1.0 / (k(p + 1) - k(1)), 1.0 / (k(p + 2) - k(2)));
match d0 {
Some(d) => put(&[(0, -3.0 * s1), (1, 3.0 * s1)], d, &mut a),
None => put(&[(0, s1), (1, -(s1 + s2)), (2, s2)], Vec2::ZERO, &mut a),
}
for (ti, q) in t.iter().zip(fit) {
let span = find_span(m - 1, p, *ti, &knots);
let coeffs: Vec<(usize, f64)> = basis(span, *ti, p, &knots).into_iter().enumerate().map(|(j, v)| (span + j - p, v)).collect();
put(&coeffs, *q, &mut a);
}
let (e1, e2) = (1.0 / (k(m + p - 1) - k(m - 1)), 1.0 / (k(m + p - 2) - k(m - 2)));
match d1 {
Some(d) => put(&[(m - 2, -3.0 * e1), (m - 1, 3.0 * e1)], d, &mut a),
None => put(&[(m - 3, e2), (m - 2, -(e1 + e2)), (m - 1, e1)], Vec2::ZERO, &mut a),
}
let (cx, cy) = (solve(a.clone(), xs)?, solve(a, ys)?);
let control: Vec<Vec2> = cx.into_iter().zip(cy).map(|(x, y)| Vec2::new(x, y)).collect();
if control.iter().any(|c| !c.x.is_finite() || !c.y.is_finite()) {
return None;
}
Some(Spline { degree: p, knots, control, fit: fit.to_vec(), ..Spline::default() })
}
/// The unit tangent AutoCAD 2024 gives a closed fit-point spline where it closes: the derivative
/// at the first point of the cubic through the first four points of the loop (the fit points and
/// back to the first), with square-root-of-chord parameters. `None` with fewer than four, or two
/// together.
fn closing_tangent(ring: &[Vec2]) -> Option<Vec2> {
let q: [Vec2; 4] = [*ring.first()?, *ring.get(1)?, *ring.get(2)?, *ring.get(3)?];
let mut t = [0.0; 4];
for i in 1..4 {
let step = q[i - 1].dist(q[i]).sqrt();
if !(step > 0.0 && step.is_finite()) {
return None;
}
t[i] = t[i - 1] + step;
}
// Derivatives of the Lagrange basis polynomials at t[0].
let mut d = q[0] * (1..4).map(|j| 1.0 / (t[0] - t[j])).sum::<f64>();
for i in 1..4 {
let c = (1..4).filter(|j| *j != i).fold(1.0 / (t[i] - t[0]), |c, j| c * (t[0] - t[j]) / (t[i] - t[j]));
d += q[i] * c;
}
// Divided by its length, not `normalized`, which gives zero for a short one (a small drawing).
let len = d.len();
(len > 0.0 && len.is_finite()).then(|| d / len)
}
/// AutoCAD 2024's closed fit-point spline with chord-length parameters: the open cubic through
/// the fit points and back to the first ([`chord_interpolate`]), clamped, with the same first
/// derivative at both ends: `tangent`, else the unit one from [`closing_tangent`]. It keeps that
/// tangent as both end tangents, as AutoCAD keeps it (DXF 12/13) through fit-point edits. `pts`
/// is without its closing point.
fn chord_closed(pts: &[Vec2], tangent: Option<Vec2>) -> Option<Spline> {
if pts.len() < 3 {
return None;
}
let mut ring = pts.to_vec();
ring.push(*pts.first()?);
let d = match tangent {
Some(t) => t,
None => closing_tangent(&ring)?,
};
let mut s = chord_interpolate(&ring, Some(d), Some(d))?;
s.fit = pts.to_vec();
s.closed = true;
s.fit_opts.start_tangent = Some(d);
s.fit_opts.end_tangent = Some(d);
Some(s)
}
/// Global interpolation: one control point per fit point plus one per end-derivative
@@ -501,9 +676,13 @@ fn kinked_fit(fit: &[Vec2], closed: bool, opts: FitOptions) -> Option<Spline> {
// Ends of an open curve are corners anyway, so only interior kinks count.
let interior = |i: usize| closed || (i > 0 && i + 1 < n);
let first = (0..n).find(|i| kink.get(*i).copied().unwrap_or(false) && interior(*i))?;
let mut stored = fit.to_vec();
if closed {
pts.rotate_left(first);
kink.rotate_left(first);
// The curve starts at its first kink, so the fit points do too (each kink given twice):
// a closed spline starts at its first fit point, which DXF and refits rely on.
stored = pts.iter().zip(&kink).flat_map(|(q, k)| std::iter::repeat_n(*q, if *k { 2 } else { 1 })).collect();
pts.push(*pts.first()?);
kink.push(true);
}
@@ -539,7 +718,7 @@ fn kinked_fit(fit: &[Vec2], closed: bool, opts: FitOptions) -> Option<Spline> {
control.extend(piece.control.iter().skip(usize::from(j > 0)).copied());
at += len / total.max(1e-300);
}
let s = Spline { degree: p, knots, control, fit: fit.to_vec(), closed, ..Spline::default() };
let s = Spline { degree: p, knots, control, fit: stored, closed, ..Spline::default() };
s.is_valid().then_some(s)
}
@@ -656,7 +835,7 @@ fn periodic_least_squares(pts: &[Vec2], t: &[f64], m: usize, p: usize) -> Option
}
#[expect(clippy::many_single_char_names, reason = "Closed interpolation keeps the NURBS Book parameter, degree and matrix notation.")]
fn closed_fit(fit: &[Vec2], kind: KnotParam, tol: f64) -> Spline {
fn closed_fit(fit: &[Vec2], kind: KnotParam, tol: f64, tangent: Option<Vec2>) -> Spline {
let mut pts = fit.to_vec();
if pts.len() > 3 && pts.first().zip(pts.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) {
pts.pop();
@@ -683,6 +862,13 @@ fn closed_fit(fit: &[Vec2], kind: KnotParam, tol: f64) -> Spline {
{
return s;
}
// Interpolation: AutoCAD's with chord-length knots, also when the tolerance is too small to
// approximate with (AutoCAD writes 44 = 1e-10 for none).
if kind == KnotParam::Chord
&& let Some(s) = chord_closed(&pts, tangent)
{
return s;
}
let m = n + p;
let knots = periodic_knots(&t, n, p);
// Interpolation at t_i; control index k and k + n are the same unknown.
@@ -717,7 +903,9 @@ mod tests {
fn passes_through(s: &Spline, fit: &[Vec2], tol: f64) -> bool {
let u = params(fit, s.fit_opts.knots, s.closed);
fit.iter().zip(&u).all(|(f, t)| s.eval(*t).dist(*f) < tol)
// The parameters run over the spline's domain (chord-length knots are not normalised).
let (lo, hi) = s.domain();
fit.iter().zip(&u).all(|(f, t)| s.eval(lo + t * (hi - lo)).dist(*f) < tol)
}
#[test]
@@ -746,6 +934,8 @@ mod tests {
for k in KnotParam::ALL {
let s = Spline::fit_with(&fit, true, FitOptions { knots: k, ..FitOptions::default() });
assert!(s.is_valid() && s.is_periodic() && passes_through(&s, &fit, 1e-3), "closed {k:?}");
// Chord-length knots are clamped, as AutoCAD 2024 builds them; the others wrap round.
assert_eq!(s.wraps(), k != KnotParam::Chord, "closed {k:?}");
assert_eq!(s.infer_knot_param(), k);
}
}
@@ -764,9 +954,11 @@ mod tests {
let end = (s.eval(hi) - s.eval(hi - h)).normalized();
assert!(start.near(Vec2::new(0.0, 1.0), 1e-4), "{start:?}");
assert!(end.near(Vec2::new(1.0, -1.0).normalized(), 1e-4), "{end:?}");
// One tangent only, and two fit points with tangents (a cubic Bezier).
// One tangent only: the other end has no curvature, so still two control points more
// than fit points (as AutoCAD 2024 builds it, `chord_fits_match_autocad_2024`); and two
// fit points with tangents (a cubic Bezier).
let one = Spline::fit_with(&fit, false, FitOptions { start_tangent: Some(Vec2::Y), ..FitOptions::default() });
assert!(one.is_valid() && one.control.len() == fit.len() + 1 && passes_through(&one, &fit, 1e-3));
assert!(one.is_valid() && one.control.len() == fit.len() + 2 && passes_through(&one, &fit, 1e-3));
let two = [Vec2::ZERO, Vec2::new(4.0, 0.0)];
let b = Spline::fit_with(
&two,
@@ -774,9 +966,309 @@ mod tests {
FitOptions { start_tangent: Some(Vec2::Y), end_tangent: Some(Vec2::new(0.0, -1.0)), ..FitOptions::default() },
);
assert!(b.is_valid() && b.degree == 3 && b.control.len() == 4);
assert!(b.eval(0.5).y > 0.5, "the tangents bow the curve up");
// Closed curves ignore tangents.
assert_eq!(Spline::fit_with(&fit, true, opts).fit_opts.start_tangent, None);
let (blo, bhi) = b.domain();
assert!(b.eval((blo + bhi) / 2.0).y > 0.5, "the tangents bow the curve up");
// A new closed curve ignores the tangents given: with chord-length knots it keeps its own
// where it closes, with periodic knots none. A refit (a stored tangent) takes the start
// one at both ends.
let own = Spline::fit_with(&fit, true, FitOptions::default());
let c = Spline::fit_with(&fit, true, opts);
assert_eq!(c, own);
let u = Spline::fit_with(&fit, true, FitOptions { knots: KnotParam::Uniform, ..opts });
assert_eq!((u.fit_opts.start_tangent, u.fit_opts.end_tangent), (None, None));
let r = Spline::fit_with_end_derivatives(&fit, true, FitOptions { start_tangent: Some(Vec2::Y), ..FitOptions::default() });
let (lo, hi) = r.domain();
assert_eq!((r.fit_opts.start_tangent, r.fit_opts.end_tangent), (Some(Vec2::Y), Some(Vec2::Y)));
assert!(r.derivative(lo).near(Vec2::Y, 1e-9) && r.derivative(hi).near(Vec2::Y, 1e-9) && r.is_periodic());
}
#[test]
fn chord_fits_match_autocad_2024() {
// The control points AutoCAD 2024 builds (accoreconsole, `entget`) for a SPLINE stored
// with these fit points only, with a start tangent (0, 1) only and with an end tangent
// (0.6, -0.8) only. The knots are the running chord length, not normalised, with the fit
// points' own as the interior ones; an end without a tangent has no second derivative.
let fit = [Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(8.0, 2.0), Vec2::new(12.0, 1.0), Vec2::new(15.0, 4.0)];
let none = [
(0.0, 0.0),
(1.382372321772683, -0.2385675034006123),
(4.310283884394332, -0.7438615842143153),
(7.681946892002376, 3.278160343960215),
(12.35784449278344, -0.2891721570669931),
(14.110931758619, 2.556721307187103),
(15.0, 4.0),
];
let start = [
(0.0, 0.0),
(0.0, 1.3333333333333002),
(5.032653247327764, -1.5652705405003644),
(7.49793879823205, 3.4873966488309946),
(12.40378970003823, -0.34141662738096556),
(14.12639202373297, 2.539141380790994),
(15.0, 4.0),
];
let end = [
(0.0, 0.0),
(1.381988814451124, -0.2629235571276922),
(4.309088095530778, -0.8198045875666935),
(7.687216672987758, 3.6128373151524897),
(12.33964126060851, -1.445235877194591),
(14.15147186257614, 5.131370849898474),
(15.0, 4.0),
];
let chords: Vec<f64> = fit.windows(2).map(|w| w[0].dist(w[1])).collect();
let interior = [chords[0], chords[0] + chords[1], chords[0] + chords[1] + chords[2]];
let total: f64 = chords.iter().sum();
let cases = [
(FitOptions::default(), none),
(FitOptions { start_tangent: Some(Vec2::Y), ..FitOptions::default() }, start),
(FitOptions { end_tangent: Some(Vec2::new(0.6, -0.8)), ..FitOptions::default() }, end),
];
for (opts, want) in cases {
let s = Spline::fit_with(&fit, false, opts);
assert_eq!(s.control.len(), want.len());
assert!(s.control.iter().zip(want).all(|(c, (x, y))| c.near(Vec2::new(x, y), 1e-9)), "{:?}", s.control);
assert_eq!(s.knots.len(), 11);
assert!(s.knots[..4].iter().all(|k| *k == 0.0) && s.knots[7..].iter().all(|k| (k - total).abs() < 1e-12));
assert!(s.knots[4..7].iter().zip(interior).all(|(k, w)| (k - w).abs() < 1e-12), "{:?}", s.knots);
}
// Two fit points, drawn with SPLINE: a cubic with its control points at the thirds and
// knots 0 and the length, four times each (AutoCAD 2024's `entget`).
let two = [Vec2::new(-0.7167548102689167, -5.126502360792934), Vec2::new(0.039252452435714846, 5.571959062465009)];
let s = Spline::fit_with(&two, false, FitOptions::default());
let want = [
(-0.7167548102689167, -5.126502360792933),
(-0.4647523893673729, -1.560348553040286),
(-0.212749968465829, 2.005805254712361),
(0.03925245243571484, 5.571959062465008),
];
assert!(s.degree == 3 && s.control.len() == 4, "{s:?}");
assert!(s.control.iter().zip(want).all(|(c, (x, y))| c.near(Vec2::new(x, y), 1e-9)), "{:?}", s.control);
let length = 10.72513980357368;
assert!(
s.knots.len() == 8 && s.knots[..4].iter().all(|k| *k == 0.0) && s.knots[4..].iter().all(|k| (k - length).abs() < 1e-9),
"{:?}",
s.knots
);
// A fit tolerance makes no difference to two points: AutoCAD 2024 with Fit tolerance 1
// from (0,0) to (10,5) has the same cubic, control points at the thirds, knots 0 and √125.
let two = [Vec2::ZERO, Vec2::new(10.0, 5.0)];
let s = Spline::fit_with(&two, false, FitOptions { tolerance: 1.0, ..FitOptions::default() });
let want = [(0.0, 0.0), (10.0 / 3.0, 5.0 / 3.0), (20.0 / 3.0, 10.0 / 3.0), (10.0, 5.0)];
assert!(s.degree == 3 && s.control.len() == 4, "{s:?}");
assert!(s.control.iter().zip(want).all(|(c, (x, y))| c.near(Vec2::new(x, y), 1e-9)), "{:?}", s.control);
let length = 125f64.sqrt();
assert!(
s.knots.len() == 8 && s.knots[..4].iter().all(|k| *k == 0.0) && s.knots[4..].iter().all(|k| (k - length).abs() < 1e-9),
"{:?}",
s.knots
);
assert_eq!(s.fit_opts.tolerance, 1.0);
// The same curve as without a tolerance.
let exact = Spline::fit_with(&two, false, FitOptions::default());
assert_eq!((&s.control, &s.knots, s.degree), (&exact.control, &exact.knots, exact.degree));
}
#[test]
fn closed_chord_fits_match_autocad_2024() {
// The control points and knots AutoCAD 2024 builds for SPLINE through these points and
// Close (accoreconsole, `entget`, the default tangent): the open chord-length cubic through
// the points and back to the first, clamped, with the same unit tangent at both ends. That
// tangent comes from the first four points of the loop only: the last two cases share it.
let a4 = [Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(6.0, 3.0), Vec2::new(1.0, 4.0)];
let b3 = [Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)];
let c5 = [a4[0], a4[1], a4[2], a4[3], Vec2::new(-2.0, 2.0)];
let c5b = [a4[0], a4[1], a4[2], a4[3], Vec2::new(-1.0, 1.0)];
let cases: [(&[Vec2], &[(f64, f64)], (f64, f64)); 4] = [
(
&a4,
&[
(0.0, 0.0),
(0.9768273968569969, -0.9075163990404586),
(4.110440110427768, -0.7122257786209955),
(7.696509078097733, 3.854015801004462),
(0.3665121443407813, 5.739691001923484),
(-1.006890633809635, 0.9354464925559993),
(0.0, 0.0),
],
(0.7326205476427477, -0.6806372992803439),
),
(
&b3,
&[
(0.0, 0.0),
(1.175326912235153, -0.6295906822321484),
(5.619959780685314, -1.4331768242180658),
(2.310179647706573, 5.2420172430121),
(-1.059425361874152, 0.567505371835594),
(0.0, 0.0),
],
(0.8814951841763651, -0.4721930116741209),
),
(
&c5,
&[
(0.0, 0.0),
(0.9768273968569857, -0.9075163990405031),
(4.161096925358192, -0.7652522140755877),
(7.509998209072992, 4.049251260863201),
(1.553476197327273, 4.730697783233012),
(-3.373822964706317, 2.2285807243904117),
(-0.6907212763663778, 0.6417109997994999),
(0.0, 0.0),
],
(0.7326205476427394, -0.6806372992803528),
),
(
&c5b,
&[
(0.0, 0.0),
(0.9768273968569822, -0.9075163990405031),
(4.136366708588512, -0.7312571003463972),
(7.601051194287697, 3.9240863010656994),
(1.118388923026953, 5.328785600648075),
(-1.947013227175678, 1.4046091221343886),
(-0.3453606381831876, 0.3208554998997215),
(0.0, 0.0),
],
(0.7326205476427366, -0.6806372992803559),
),
];
for (fit, want, tangent) in cases {
let s = Spline::fit_with(fit, true, FitOptions::default());
assert!(s.is_valid() && s.closed && s.degree == 3, "{s:?}");
assert_eq!(s.control.len(), want.len());
assert!(s.control.iter().zip(want).all(|(c, (x, y))| c.near(Vec2::new(*x, *y), 1e-9)), "{:?}", s.control);
// Knots: zeros, the running chord length round the loop at the fit points after the
// first, and its total four times.
let mut run = vec![0.0];
for (a, b) in fit.iter().zip(fit.iter().skip(1).chain([&fit[0]])) {
run.push(run.last().unwrap() + a.dist(*b));
}
let total = *run.last().unwrap();
let want_knots: Vec<f64> = [0.0; 3].into_iter().chain(run[..fit.len()].iter().copied()).chain([total; 4]).collect();
assert_eq!(s.knots.len(), want_knots.len());
assert!(s.knots.iter().zip(&want_knots).all(|(k, w)| (k - w).abs() < 1e-12), "{:?}", s.knots);
// The tangent where it closes is the first derivative at both ends, so the curve is
// periodic (smooth where it closes) with clamped knots.
let (lo, hi) = s.domain();
let d = Vec2::new(tangent.0, tangent.1);
assert!(s.derivative(lo).near(d, 1e-9) && s.derivative(hi).near(d, 1e-9), "{:?} {:?}", s.derivative(lo), s.derivative(hi));
assert!(s.is_periodic() && !s.wraps());
assert!(s.fit_opts.start_tangent.is_some_and(|t| t.near(d, 1e-12)) && s.fit_opts.end_tangent == s.fit_opts.start_tangent);
assert_eq!(s.fit, fit, "the first fit point is not repeated");
assert_eq!(s.infer_knot_param(), KnotParam::Chord);
}
}
#[test]
fn closed_splines_keep_their_closing_tangent_as_in_autocad() {
// AutoCAD 2024 (accoreconsole, `entget`) on SPLINE (0,0) (4,0) (6,3) (1,4) Close: its
// tangent where it closes, D, stays 12 and 13 through edits; here it stays both end
// tangents.
let fit = [Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(6.0, 3.0), Vec2::new(1.0, 4.0)];
let s = Spline::fit_with(&fit, true, FitOptions::default());
let d = Vec2::new(0.7326205476427478, -0.6806372992803439);
let near = |a: &[Vec2], b: &[(f64, f64)]| a.len() == b.len() && a.iter().zip(b).all(|(p, (x, y))| p.near(Vec2::new(*x, *y), 1e-9));
assert!(s.fit_opts.start_tangent.is_some_and(|t| t.near(d, 1e-12)) && s.fit_opts.end_tangent == s.fit_opts.start_tangent);
// SPLINEDIT Fit data Move of (1, 4) to (1, 5) keeps D, though the first four points of the
// loop, which give a new spline its tangent, change.
let up = Vec2::new(1.0, 5.0);
let moved = s.refit(&[fit[0], fit[1], fit[2], up], true);
let want = [
(0.0, 0.0),
(0.9768273968569969, -0.9075163990404586),
(4.139797324573113, -0.6528392109186482),
(7.666093574908103, 3.731946546410586),
(-0.03708934486751076, 7.208547566545824),
(-1.245215489496467, 1.156860956903188),
(0.0, 0.0),
];
assert!(near(&moved.control, &want), "{:?}", moved.control);
assert!(moved.fit_opts.start_tangent.is_some_and(|t| t.near(d, 1e-12)));
// REVERSE: the seam stays the first fit point, the others turn round, and so does D.
let r = s.reversed();
assert_eq!(r.fit, [fit[0], fit[3], fit[2], fit[1]]);
assert!(r.fit_opts.start_tangent.is_some_and(|t| t.near(-d, 1e-12)) && r.fit_opts.end_tangent == r.fit_opts.start_tangent);
let want = [
(0.0, 0.0),
(-1.006890633809634, 0.9354464925559991),
(0.3665121443407817, 5.739691001923484),
(7.696509078097734, 3.854015801004462),
(4.110440110427767, -0.7122257786209955),
(0.9768273968569975, -0.907516399040459),
(0.0, 0.0),
];
assert!(near(&r.control, &want), "{:?}", r.control);
let knots = [
0.0,
0.0,
0.0,
0.0,
4.12310562561766,
9.222125139210444,
12.82767641467443,
16.82767641467443,
16.82767641467443,
16.82767641467443,
16.82767641467443,
];
assert!(r.knots.len() == knots.len() && r.knots.iter().zip(knots).all(|(a, b)| (a - b).abs() < 1e-12), "{:?}", r.knots);
// ... and a move after it keeps the turned tangent: the moved curve, reversed.
let rm = r.refit(&[fit[0], up, fit[2], fit[1]], true);
let want = [
(0.0, 0.0),
(-1.245215489496467, 1.156860956903188),
(-0.03708934486751225, 7.208547566545823),
(7.666093574908103, 3.731946546410587),
(4.139797324573113, -0.6528392109186484),
(0.9768273968569966, -0.9075163990404583),
(0.0, 0.0),
];
assert!(near(&rm.control, &want), "{:?}", rm.control);
// SPLINEDIT Fit data Delete keeps D too, even of the first fit point, where the curve then
// closes at the next one.
let want = [
(4.0, 0.0),
(4.880500316661478, -0.8180242275162029),
(8.321543841772677, 4.998519358162528),
(-2.146496779397366, 4.974687083605885),
(2.778965753928753, 1.134395498800573),
(4.0, 0.0),
];
assert!(near(&s.refit(&fit[1..], true).control, &want));
let want = [
(0.0, 0.0),
(0.9768273968569969, -0.9075163990404586),
(6.486660720359312, -1.195604109659142),
(0.6839072671675914, 6.97368772380304),
(-1.006890633809635, 0.9354464925559993),
(0.0, 0.0),
];
assert!(near(&s.refit(&[fit[0], fit[1], fit[3]], true).control, &want));
// SPLINEDIT Open keeps the fit points and D as both end tangents.
let o = s.refit(&fit, false);
let want = [
(0.0, 0.0),
(0.9768273968569969, -0.9075163990404586),
(3.849239755252805, -0.7101778392295987),
(8.658209992380792, 3.846475592325253),
(-0.2452154894964675, 5.156860956903188),
(1.0, 4.0),
];
assert!(near(&o.control, &want), "{:?}", o.control);
}
#[test]
fn a_short_closing_derivative_still_gives_a_tangent() {
// A loop 1e-20 across: the derivative of the cubic through its first points is about
// 1e-10 long, short enough for `normalized` to make it zero (a cusp where it closes).
let ring = [Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(6.0, 3.0), Vec2::new(1.0, 4.0), Vec2::ZERO];
let d = closing_tangent(&ring).unwrap();
let small: Vec<Vec2> = ring.iter().map(|q| *q * 1e-20).collect();
assert!(closing_tangent(&small).is_some_and(|t| t.near(d, 1e-12)), "{:?}", closing_tangent(&small));
// Two points together give none.
assert!(closing_tangent(&[Vec2::ZERO, Vec2::ZERO, Vec2::X, Vec2::Y]).is_none());
}
#[test]
@@ -833,9 +1325,10 @@ mod tests {
assert!(s.eval(lo).near(s.eval(hi), 1e-9), "still closed");
assert_eq!(s.fit, fit);
assert_eq!(s.fit_opts.tolerance.to_bits(), tol.to_bits());
// Too tight a tolerance interpolates.
// Too tight a tolerance interpolates, as AutoCAD 2024 builds the closed spline (the curve
// without a tolerance, which keeps the one asked for).
let tiny = Spline::fit_with(&fit, true, FitOptions { tolerance: 1e-9, ..FitOptions::default() });
assert_eq!(tiny.control.len(), exact.control.len());
assert_eq!((&tiny.knots, &tiny.control, tiny.fit_opts.tolerance), (&exact.knots, &exact.control, 1e-9));
// Every parametrisation approximates.
for k in KnotParam::ALL {
let s = Spline::fit_with(&fit, true, FitOptions { tolerance: tol, knots: k, ..FitOptions::default() });
@@ -878,6 +1371,20 @@ mod tests {
let (lo, hi) = s.domain();
assert!(s.eval(lo).near(Vec2::ZERO, 1e-9) && s.eval(hi).near(Vec2::ZERO, 1e-9));
assert!(c.iter().all(|q| on_curve(&s, *q)));
// A kink further on: the curve starts there, and so do its fit points (the seam is the
// first fit point, which DXF and refits take it to be), also once reversed.
let k = Vec2::new(4.0, 0.0);
let c = [Vec2::ZERO, k, k, Vec2::new(4.0, 4.0), Vec2::new(0.0, 4.0)];
let s = Spline::fit_with(&c, true, FitOptions::default());
assert_eq!(s.fit, [k, k, Vec2::new(4.0, 4.0), Vec2::new(0.0, 4.0), Vec2::ZERO]);
let (lo, hi) = s.domain();
assert!(s.eval(lo).near(k, 1e-9) && s.eval(hi).near(k, 1e-9));
assert_eq!(s.refit(&s.fit, true).control, s.control, "a refit gives the same curve");
let r = s.reversed();
assert_eq!(r.fit, [k, k, Vec2::ZERO, Vec2::new(0.0, 4.0), Vec2::new(4.0, 4.0)]);
let (rlo, rhi) = r.domain();
let again = r.refit(&r.fit, true);
assert!(again.eval(again.domain().0).near(k, 1e-9) && (0..=8).all(|i| on_curve(&again, r.eval(rlo + (rhi - rlo) * i as f64 / 8.0))));
// Kinks at the ends of an open curve change nothing.
let e = [Vec2::ZERO, Vec2::ZERO, Vec2::new(2.0, 2.0), Vec2::new(4.0, 0.0)];
let plain = Spline::fit_with(&e[1..], false, FitOptions::default());
@@ -915,6 +1422,19 @@ mod tests {
}
let tight: Vec<Vec2> = (0..8).map(|i| Vec2::new(f64::from(i) * 1e-13, 0.0)).collect();
let _ = Spline::fit_with(&tight, true, FitOptions { tolerance: 1.0, ..FitOptions::default() });
// A file's tangent keeps its length, however extreme.
let kept = Spline::fit_with_end_derivatives(&fit, false, bad);
assert!(kept.is_valid() && kept.fit_opts.start_tangent.is_none() && kept.fit_opts.end_tangent.is_none());
for len in [1e-11, 1e150, 1e308, f64::MAX] {
for knots in KnotParam::ALL {
for tolerance in [0.0, 0.5] {
let t = Some(Vec2::new(len, -len));
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { knots, start_tangent: t, end_tangent: t, tolerance });
s.transform(&Mat3::scale(2.0, 0.5));
let _ = s.refit(&fit, false);
}
}
}
}
/// Above the interpolation cap the fit points become control points instead of a dense
@@ -951,6 +1471,87 @@ mod tests {
s.transform(&Mat3::rotate(std::f64::consts::FRAC_PI_2));
assert!(s.fit_opts.start_tangent.is_some_and(|t| t.near(Vec2::Y, 1e-12)));
}
#[test]
fn a_stored_tangent_keeps_its_length_through_edits_as_in_autocad() {
// AutoCAD 2024 (accoreconsole) on a SPLINE stored with these fit points and 12 = (0, 3).
let fit = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(8.0, 2.0), Vec2::new(12.0, 1.0), Vec2::new(15.0, 4.0)];
let t0 = Some(Vec2::new(0.0, 3.0));
let s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: t0, ..FitOptions::default() });
// SPLINEDIT Fit data Move of the third fit point to (8, 3) refits with (0, 3) as stored.
let moved = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(8.0, 3.0), Vec2::new(12.0, 1.0), Vec2::new(15.0, 4.0)];
let r = s.refit(&moved, false);
let autocad = [
(0.0, 0.0),
(0.0, 4.0),
(5.412665758603298, -3.5553537661153),
(7.3671281655678, 5.7160776616114),
(12.24746922455167, -0.8468238208691),
(14.09874022239649, 2.4130068961106),
(15.0, 4.0),
];
assert_eq!(r.control.len(), autocad.len());
for (c, (x, y)) in r.control.iter().zip(autocad) {
assert!(c.near(Vec2::new(x, y), 1e-9), "{c:?} vs ({x}, {y})");
}
assert_eq!(r.fit_opts.start_tangent, t0);
// MOVE, ROTATE 90, SCALE 2 and MIRROR about y = x turn 12 and keep its length, so a refit
// of the moved fit points gives the moved curve.
for (m, t) in [
(Mat3::translate(Vec2::new(10.0, 0.0)), Vec2::new(0.0, 3.0)),
(Mat3::rotate(std::f64::consts::FRAC_PI_2), Vec2::new(-3.0, 0.0)),
(Mat3::scale(2.0, 2.0), Vec2::new(0.0, 3.0)),
(Mat3::mirror(Vec2::ZERO, Vec2::new(1.0, 1.0)), Vec2::new(3.0, 0.0)),
] {
let mut e = s.clone();
e.transform(&m);
assert!(e.fit_opts.start_tangent.is_some_and(|v| v.near(t, 1e-12)), "{:?} vs {t:?}", e.fit_opts.start_tangent);
let again = e.refit(&e.fit, false);
assert!(again.control.iter().zip(&e.control).all(|(a, b)| a.near(*b, 1e-9)), "{:?} vs {:?}", again.control, e.control);
}
}
#[test]
fn short_tangents_are_no_zero_directions() {
let fit = pts();
// A direction too short to scale to a unit is no tangent, not a zero one.
let short = Some(Vec2::new(0.0, 1e-10));
let s = Spline::fit_with(&fit, false, FitOptions { start_tangent: short, end_tangent: short, ..FitOptions::default() });
assert_eq!((s.fit_opts.start_tangent, s.fit_opts.end_tangent), (None, None));
// A file's short tangent is kept, and a transform turns it rather than dropping it.
let mut f = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: short, ..FitOptions::default() });
assert_eq!(f.fit_opts.start_tangent, short);
f.transform(&Mat3::rotate(std::f64::consts::FRAC_PI_2));
assert!(f.fit_opts.start_tangent.is_some_and(|t| t.near(Vec2::new(-1e-10, 0.0), 1e-24)), "{:?}", f.fit_opts.start_tangent);
// A map that flattens its direction drops it.
f.transform(&Mat3::scale(0.0, 1.0));
assert_eq!(f.fit_opts.start_tangent, None);
}
#[test]
fn a_small_uniform_scale_keeps_the_tangent_and_a_singular_map_drops_it() {
let fit = pts();
let t = Some(Vec2::new(100.0, 0.0));
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: t, ..FitOptions::default() });
// Invertible, however small: the tangent stays, with its length.
s.transform(&Mat3::scale(1e-10, 1e-10));
assert!(s.fit_opts.start_tangent.is_some_and(|v| v.near(Vec2::new(100.0, 0.0), 1e-9)), "{:?}", s.fit_opts.start_tangent);
// A singular map that flattens the direction to rounding noise (0.1 + 0.2 - 0.3) drops it.
let flat = Some(Vec2::new(0.1 + 0.2, -0.3));
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: flat, ..FitOptions::default() });
s.transform(&Mat3 { a: 1.0, b: 1.0, c: 1.0, d: 1.0, e: 0.0, f: 0.0 });
assert_eq!(s.fit_opts.start_tangent, None);
// So does one that squashes it to under 1e-9 of its largest axis scale, along either axis.
for (t, m) in [(Vec2::new(0.0, 3.0), Mat3::scale(1.0, 1e-12)), (Vec2::new(3.0, 0.0), Mat3::scale(1e-12, 1.0))] {
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: Some(t), ..FitOptions::default() });
s.transform(&m);
assert_eq!(s.fit_opts.start_tangent, None, "{t:?}");
}
// A turned length that overflows gives no tangent rather than NaN.
let mut s = Spline::fit_with_end_derivatives(&fit, false, FitOptions { start_tangent: Some(Vec2::new(1e10, 0.0)), ..FitOptions::default() });
s.transform(&Mat3::scale(1e300, 1e300));
assert_eq!(s.fit_opts.start_tangent, None);
}
}
#[cfg(test)]
+57 -1
View File
@@ -175,7 +175,7 @@ fn spline_interpolates_fit_points() {
assert!(d < 0.05, "fit point {f:?} missed by {d}");
}
assert!(s.eval(0.0).near(fit[0], 1e-9));
assert!(s.eval(1.0).near(fit[4], 1e-9));
assert!(s.eval(s.domain().1).near(fit[4], 1e-9));
}
#[test]
@@ -201,6 +201,62 @@ fn closed_spline_is_smooth_at_the_seam() {
assert_eq!(Spline::from_fit_points_closed(&dup).fit.len(), 4);
}
#[test]
fn periodic_means_the_same_derivative_where_it_closes() {
// AutoCAD 2024 sets group 70 bit 2 from the curve: its closed fit spline through (0,0)
// (4,0) (6,3) (1,4), made again without fit data, keeps it with clamped knots; with the
// second control point moved along the first leg (the same direction, twice as long), or
// across it by a fraction of its length, it drops it (accoreconsole, `entmake` + `entget`;
// AutoCAD drops it from 1e-11).
let control = vec![
Vec2::new(0.0, 0.0),
Vec2::new(0.9768273968569969, -0.9075163990404586),
Vec2::new(4.110440110427768, -0.7122257786209955),
Vec2::new(7.696509078097733, 3.854015801004462),
Vec2::new(0.3665121443407813, 5.739691001923484),
Vec2::new(-1.006890633809635, 0.9354464925559993),
Vec2::new(0.0, 0.0),
];
let knots = vec![
0.0,
0.0,
0.0,
0.0,
4.0,
7.605551275463989,
12.70457078905677,
16.82767641467443,
16.82767641467443,
16.82767641467443,
16.82767641467443,
];
let s = Spline { degree: 3, knots, control, closed: true, ..Spline::default() };
assert!(s.is_valid() && s.is_periodic() && !s.wraps());
let leg = s.control[1] - s.control[0];
let moved = |to: Vec2| {
let mut m = s.clone();
m.control[1] = to;
m
};
assert!(!moved(s.control[0] + leg * 2.0).is_periodic(), "the same direction is not enough");
let across = Vec2::new(-leg.y, leg.x) * 1e-7;
assert!(!moved(s.control[1] + across).is_periodic());
// The last two control points moved together: the same derivative, but the ends apart.
let mut apart = s.clone();
for c in &mut apart.control[5..] {
*c += Vec2::new(0.0, 1e-3);
}
assert!(!apart.is_periodic(), "the ends must meet");
assert!(!Spline { closed: false, ..s.clone() }.is_periodic(), "an open spline is not periodic");
// Control points that wrap round (unclamped knots) are periodic too.
let w = Spline::fit_with(
&[Vec2::ZERO, Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)],
true,
crate::FitOptions { knots: crate::KnotParam::SqrtChord, ..Default::default() },
);
assert!(w.wraps() && w.is_periodic());
}
#[test]
fn ellipse_points() {
let e = Ellipse::full(Vec2::ZERO, Vec2::new(4.0, 0.0), 0.5);
+4 -12
View File
@@ -617,20 +617,12 @@ pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs) -> Vec<Tag> {
p(&mut t, 10, b.scale);
f(&mut t, 43, b.rotation);
i(&mut t, 176, 1);
// Attribute values by their ATTDEF in the block.
let defs: Vec<(Handle, &str)> = d
.block(&b.block)
.map(|blk| {
blk.entities
.iter()
.filter_map(|e| if let EntityKind::AttDef(ad) = &e.kind { Some((e.handle, ad.tag.as_str())) } else { None })
.collect()
})
.unwrap_or_default();
// Attribute values by their ATTDEF in the block, the definitions gathered by tag once.
let defs = d.block(&b.block).map(|blk| blk.attdefs_by_tag()).unwrap_or_default();
let mut n = 0i64;
for a in &b.attribs {
let Some((h, _)) = defs.iter().find(|(_, tag)| tag.eq_ignore_ascii_case(&a.tag)) else { continue };
s(&mut t, 330, &h.hex());
let Some(def) = defs.get(&cadcraft_doc::TagKey(&a.tag)) else { continue };
s(&mut t, 330, &def.handle.hex());
i(&mut t, 177, n);
f(&mut t, 44, 0.0);
s(&mut t, 302, &a.text.value);
+19 -4
View File
@@ -251,10 +251,23 @@ impl LayerSet {
}
}
/// The position of the first layout of each name, so finding the layout of each of many objects
/// is a map lookup rather than a scan of the layouts: a file of N layouts and N objects in the
/// last of them read in N² name comparisons (#1924). The reader keeps the layouts' names and order
/// while it fills them.
pub(super) fn layout_positions(d: &Drawing) -> std::collections::BTreeMap<String, usize> {
let mut at = std::collections::BTreeMap::new();
for (i, l) in d.layouts.iter().enumerate() {
at.entry(l.name.clone()).or_insert(i);
}
at
}
/// Place the BLOCKS entities: model and paper space blocks go to their space, the rest become
/// block definitions.
pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec<BlockDef>, rx: &mut Rx, paper_block_for: &HashMap<String, String>, first_layout: &str) {
let mut layers = LayerSet::new(d);
let layout_at = layout_positions(d);
for (name, base, description, ents, xref) in blocks {
let up = name.to_ascii_uppercase();
if up == "*MODEL_SPACE" {
@@ -265,8 +278,8 @@ pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec<BlockDef>, rx: &mut Rx,
continue;
}
if up.starts_with("*PAPER_SPACE") {
let lname = paper_block_for.get(&up).cloned().unwrap_or_else(|| first_layout.to_string());
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) {
let lname = paper_block_for.get(&up).map_or(first_layout, String::as_str);
if let Some(l) = layout_at.get(lname).and_then(|&i| d.layouts.get_mut(i)) {
for (_, _, e) in ents {
l.entities.push(e);
}
@@ -324,11 +337,12 @@ pub(super) fn place_entities(
first_layout: &str,
) {
let mut layers = LayerSet::new(d);
let layout_at = layout_positions(d);
for (owner, paper, e) in entities {
layers.ensure(d, &e.common.layer);
match paper_layout(owner, paper, rx, paper_block_for, first_layout) {
Some(lname) => {
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) {
if let Some(l) = layout_at.get(&lname).and_then(|&i| d.layouts.get_mut(i)) {
l.entities.push(e);
}
}
@@ -417,6 +431,7 @@ pub(super) fn apply_sortents(
Some(if up.starts_with("*PAPER_SPACE") { paper_for.get(&up).cloned().unwrap_or_else(|| first_layout.to_string()) + "\0paper" } else { up })
};
let last: HashMap<String, usize> = tables.iter().enumerate().filter_map(|(i, (owner, _))| Some((target(owner)?, i))).collect();
let layout_at = layout_positions(d);
for (i, (owner, map)) in tables.iter().enumerate() {
if target(owner).and_then(|t| last.get(&t)) != Some(&i) {
continue;
@@ -432,7 +447,7 @@ pub(super) fn apply_sortents(
d.model.sort_by_key(key);
} else if up.starts_with("*PAPER_SPACE") {
let lname = paper_for.get(&up).map(String::as_str).unwrap_or(first_layout);
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) {
if let Some(l) = layout_at.get(lname).and_then(|&i| d.layouts.get_mut(i)) {
l.entities.sort_by_key(key);
}
} else if let Some(b) = d.blocks.get_mut(name.as_str()) {
+29 -6
View File
@@ -106,24 +106,47 @@ fn spline(t: &T) -> Spline {
let knots = t.all_f(40);
let control = t.pts(10);
let weights = t.all_f(41);
let fit = t.pts(11);
let tangent = |c: i32| t.f(c).map(|_| t.p(c).xy());
let fit_opts =
cadcraft_geom::FitOptions { knots: Default::default(), start_tangent: tangent(12), end_tangent: tangent(13), tolerance: t.fd(44, 0.0) }
.sanitized();
let mut fit = t.pts(11);
let closed = t.i(70).unwrap_or(0) & 1 != 0;
// AutoCAD ends a closed spline's fit points with the first again; here it is implied.
if closed && fit.len() > 3 && fit.first().zip(fit.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) {
fit.pop();
}
let tangent = |c: i32| t.f(c).map(|_| t.p(c).xy());
// AutoCAD writes no fit tolerance as 1e-10; read as a tolerance, an approximation could meet it.
let tolerance = t.fd(44, 0.0);
let tolerance = if tolerance <= 1e-10 { 0.0 } else { tolerance };
// AutoCAD takes a 12/13 tangent with its length (for a closed spline, its tangent where it
// closes), keeps it through fit-point edits and writes it back as it read it.
let fit_opts = cadcraft_geom::FitOptions { knots: Default::default(), start_tangent: tangent(12), end_tangent: tangent(13), tolerance }
.sanitized_keeping_length();
let mut sp = Spline { degree, knots, control, weights, fit: fit.clone(), closed, fit_opts };
if !sp.is_valid() && fit.len() >= 2 {
sp = Spline::fit_with(&fit, sp.closed, fit_opts);
sp = Spline::fit_with_end_derivatives(&fit, sp.closed, fit_opts);
} else if !sp.is_valid() && sp.control.len() >= 2 {
sp = Spline::from_control(sp.control.clone(), degree);
} else if fit.len() >= 3 {
// DXF keeps the knots, not how they were spaced: recover it for later refits.
sp.fit_opts.knots = sp.infer_knot_param();
}
// The writer gives every closed spline its curve's tangents where it closes, but only one
// built as AutoCAD's closed fit spline keeps them (as `Spline::fit_with` stores them); for the
// others a refit takes none, before a save or after it.
if sp.closed && !keeps_closing_tangent(&sp) {
sp.fit_opts.start_tangent = None;
sp.fit_opts.end_tangent = None;
}
sp
}
/// A closed spline that keeps a tangent where it closes: AutoCAD's closed fit spline, with three
/// fit points or more, no kink (a fit point twice in a row) and clamped knots (periodic knots,
/// square-root, uniform or within a fit tolerance, wrap round).
fn keeps_closing_tangent(sp: &Spline) -> bool {
let kinked = sp.fit.windows(2).any(|w| w.first().zip(w.get(1)).is_some_and(|(a, b)| a.near(*b, 1e-12)));
sp.fit.len() >= 3 && !kinked && !sp.wraps()
}
pub(super) fn entity_with_table_budget(
kind: &str,
tags: &[Tag],
+4 -2
View File
@@ -195,6 +195,7 @@ impl Objects {
/// Layouts' UCSs: the World UCS, unusable axes or no such layout leave it unset.
fn apply_layout_ucss(&self, d: &mut Drawing, rx: &Rx) {
let layout_at = super::document::layout_positions(d);
for (name, origin, x, y, named) in &self.layout_ucss {
let usable = origin.is_finite() && crate::dxf_ext::usable_axes(*x, *y);
// The named UCS group 345 points at, only while the layout's frame is still that
@@ -209,7 +210,7 @@ impl Objects {
if !usable || (world && ucs_name.is_empty()) {
continue;
}
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == *name) {
if let Some(l) = layout_at.get(name).and_then(|&i| d.layouts.get_mut(i)) {
l.ucs = Some(Ucs { name: ucs_name, origin: *origin, x_axis: *x, y_axis: *y });
}
}
@@ -348,8 +349,9 @@ impl Objects {
}
self.apply_mleader_styles(d, rx);
crate::dxf_mleader::apply(d, &rx.mleader_fix, &self.names);
let layout_at = super::document::layout_positions(d);
for (name, view) in &self.layout_views {
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == *name) {
if let Some(l) = layout_at.get(name).and_then(|&i| d.layouts.get_mut(i)) {
l.view = Some(*view);
}
}
+10 -2
View File
@@ -114,6 +114,11 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
// The same for linetypes (first definition wins) and text styles (last definition wins).
let mut linetype_names: std::collections::HashSet<String> = d.linetypes.iter().map(|l| l.name.to_ascii_lowercase()).collect();
let mut style_index: HashMap<String, usize> = d.text_styles.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
// And for dimension styles (a later record replaces the first of its name, which keeps its
// place); ordered by name rather than hashed, so its cost does not depend on hash keys. Built
// in reverse, so the first style of a name is the one kept.
let mut dim_style_index: std::collections::BTreeMap<String, usize> =
d.dim_styles.iter().enumerate().rev().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
for (kind, tg) in recs {
let t = T(tg);
match kind.as_str() {
@@ -280,9 +285,12 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
fields.extend(crate::dxf_ext::read_newer_dimvars(tg, &rx.styles, &rx.brs, &rx.ltypes));
let mut st = DimStyle { name: name.clone(), annotative: annotative(tg), ..DimStyle::default() };
st.apply_fields(&fields);
match d.dim_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case(&name)) {
match dim_style_index.get(&name.to_ascii_lowercase()).and_then(|&i| d.dim_styles.get_mut(i)) {
Some(x) => *x = st,
None => d.dim_styles.push(st),
None => {
dim_style_index.insert(name.to_ascii_lowercase(), d.dim_styles.len());
d.dim_styles.push(st);
}
}
}
"VPORT" => vport_record(d, &t, false),
+29 -5
View File
@@ -8,7 +8,7 @@ use std::collections::{HashMap, HashSet};
use cadcraft_color::Color;
use cadcraft_doc::{
AssocSnap, Attrib, Block, Common, DimAssoc, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, EntityStore, Gradient, Group, HAlign,
HVal, Handle, Hatch, Insert, Layout, Leader, Line, Lineweight, LwPolyline, MLeader, MLeaderStyle, MText, PageSetup, Point, Solid, Space, Table,
HVal, Handle, Hatch, Layout, Leader, Line, Lineweight, LwPolyline, MLeader, MLeaderStyle, MText, PageSetup, Point, Solid, Space, Table,
TableStyle, Text, Transparency, Ucs, VAlign, VportConfig, VportTile,
};
use cadcraft_geom::{Bounds2, Vec2, Vec3};
@@ -156,17 +156,23 @@ pub fn tags(d: &Drawing, version: Version) -> Vec<Tag> {
/// [`tags`], with the foreign objects the file keeps, by their handles in the drawing.
fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::HashSet<cadcraft_doc::Handle>) {
let (mut tags, kept) = sections::tags_kept_for(d, version, version, version < Version::R2004, false);
let (mut tags, kept, _) = sections::tags_kept_for(d, version, version, version < Version::R2004, false);
// Kept proxies in this version's layout (#3229). Not for the DWG bridge, whose writer reads
// them in the layout of the DWG they came from.
proxy::proxy_layout(&mut tags, version);
(tags, kept)
}
/// The most dash elements a linetype keeps in a DWG. The DWG writer (acadrust) stores the count in
/// one byte, so a longer pattern would come back with its count modulo 256 (none at all for 256),
/// and a DWG save keeps the first 255 instead ([`dwg_notes`] says so).
pub const DWG_MAX_LINETYPE_ELEMENTS: usize = 255;
/// The R2000 DXF the DWG bridge converts to a `dwg` version DWG: its entity types are the DWG
/// version's (MULTILEADER from 2007).
/// version's (MULTILEADER from 2007), and its linetypes have at most
/// [`DWG_MAX_LINETYPE_ELEMENTS`] elements.
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 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);
@@ -186,7 +192,7 @@ pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> (String, craft_dwg::Unwri
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 (_, 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);
@@ -195,6 +201,24 @@ pub fn dwg_compat_lost(d: &Drawing, version: Version) -> craft_dwg::Unwritten {
lost
}
/// What a DWG keeps of `d` only in part, as notes for the user: one counting the linetypes with
/// more dash elements than a DWG counts, which it saves with their first
/// [`DWG_MAX_LINETYPE_ELEMENTS`]. Empty when the DWG keeps every linetype whole.
pub fn dwg_notes(d: &Drawing) -> Vec<String> {
let max = DWG_MAX_LINETYPE_ELEMENTS;
if d.linetypes.iter().all(|l| l.pattern.len() <= max) {
return Vec::new();
}
// The writer decides which linetypes the file holds (an xref's own only when a layer uses
// them), so it does the counting; the LTYPE table is the same in every DWG version.
let (_, _, cut) = sections::tags_kept_for(d, Version::R2000, Version::R2004, false, true);
match cut {
0 => Vec::new(),
1 => vec![format!("DWG: 1 linetype has more than {max} dash elements; only its first {max} were saved.")],
n => vec![format!("DWG: {n} linetypes have more than {max} dash elements; only the first {max} of each were saved.")],
}
}
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()
}
+7 -9
View File
@@ -1,7 +1,7 @@
use super::ctx::{AssocObj, Ctx};
use super::{
Attrib, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, HAlign, HashMap, Insert, Lineweight, Text, Transparency,
VAlign, Vec3, Version, W, dxf_ext,
Attrib, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, HAlign, HashMap, Lineweight, Text, Transparency, VAlign, Vec3, Version, W,
dxf_ext,
};
/// `AcadAnnotative` xdata marking an annotative style.
@@ -145,13 +145,11 @@ pub(super) fn layer_and_props(w: &mut W, c: &Common, base: Option<&Common>) {
}
}
/// The properties attribute `a` of block reference `e` (of `ins`) is drawn with: its own, else its
/// definition's; an attribute defined on layer 0 is on the reference's layer. Also the
/// definition's properties.
pub(super) fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, a: &Attrib) -> (Common, Common) {
let def = d
.block(&ins.block)
.and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))));
/// The properties attribute `a` of block reference `e` is drawn with: its own, else its
/// definition's, from the block's definitions by tag `defs`; an attribute defined on layer 0 is on
/// the reference's layer. Also the definition's properties.
pub(super) fn attrib_common(e: &Entity, defs: &std::collections::BTreeMap<cadcraft_doc::TagKey<'_>, &Entity>, a: &Attrib) -> (Common, Common) {
let def = defs.get(&cadcraft_doc::TagKey(&a.tag));
let base = def.map(|de| de.common.clone()).unwrap_or_default();
let mut c = a.props.over(&base);
if c.layer == "0" {
+21 -5
View File
@@ -215,20 +215,34 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
w.s(0, "SPLINE");
common(w, e, owner, paper, "AcDbSpline");
let flags = 8 | i64::from(s.closed) | if s.is_periodic() { 2 } else { 0 } | if s.weights.is_empty() { 0 } else { 4 };
// AutoCAD 2024 rebuilds a spline with fit data from its fit points and end tangents,
// whatever its flags say. A closed one starts at its first fit point, has it again at
// the end and its tangent where it closes at both ends: without the point AutoCAD
// opens it, and without the tangents its ends are free. A closed spline without a
// stored tangent (periodic knots, a fit tolerance, a kink where it closes) gives the
// curve's own. The reader drops one closing point, so it goes after a list that ends
// with the first point already (a kink where it closes) too; only three points ending
// so, which the reader keeps as they are, go without it.
let ends_at_first = s.fit.first().zip(s.fit.last()).is_some_and(|(a, b)| a.near(*b, 1e-12));
let closing = s.closed && s.fit.len() > 2 && !(s.fit.len() == 3 && ends_at_first);
w.i(70, flags);
w.i(71, s.degree as i64);
w.i(72, s.knots.len() as i64);
w.i(73, s.control.len() as i64);
w.i(74, s.fit.len() as i64);
w.i(74, (s.fit.len() + usize::from(closing)) as i64);
w.f(42, 1e-10);
w.f(43, 1e-10);
// Fit data: tolerance and end tangents (the knot parametrisation is implied by the knots).
if !s.fit.is_empty() {
w.f(44, s.fit_opts.tolerance);
if let Some(t) = s.fit_opts.start_tangent {
let (lo, hi) = s.domain();
let seam = |t: f64| Some(s.unit_tangent(t)).filter(|d| *d != Vec2::ZERO);
let (t0, t1) = (s.fit_opts.start_tangent, s.fit_opts.end_tangent);
let (t0, t1) = if s.closed { (t0.or_else(|| seam(lo)), t1.or_else(|| seam(hi))) } else { (t0, t1) };
if let Some(t) = t0 {
w.p(12, t.to3(0.0));
}
if let Some(t) = s.fit_opts.end_tangent {
if let Some(t) = t1 {
w.p(13, t.to3(0.0));
}
}
@@ -241,7 +255,7 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
w.f(41, *wt);
}
}
for f in &s.fit {
for f in s.fit.iter().chain(s.fit.first().filter(|_| closing)) {
w.p(11, f.to3(0.0));
}
}
@@ -372,13 +386,15 @@ 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() {
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = d.block(&i.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
for (index, a) in i.attribs.iter().enumerate() {
let ah = w.h();
w.s(0, "ATTRIB");
w.s(5, ah);
w.s(330, e.handle.hex());
w.s(100, "AcDbEntity");
let (c, base) = attrib_common(d, e, i, a);
let (c, base) = attrib_common(e, &defs, a);
layer_and_props(w, &c, Some(&base));
// Hidden with its definition (a dynamic block's visibility state hides it).
if !base.visible {
+1 -1
View File
@@ -84,7 +84,7 @@ pub(super) fn model_ucs(d: &Drawing) -> Ucs {
/// style are its overrides and are written instead, so they are kept with the drawing (#3100).
fn dim_header_vars(w: &mut W, d: &Drawing) {
let name = d.header.str("DIMSTYLE", "Standard");
let Some(style) = d.dim_styles.iter().find(|s| s.name.eq_ignore_ascii_case(&name)) else { return };
let Some(style) = d.dim_style(&name) else { return };
let mut v = serde_json::to_value(style).unwrap_or_default();
if let Some(fields) = v.as_object_mut() {
fields.extend(d.dim_overrides());
+21 -9
View File
@@ -17,9 +17,14 @@ struct TableWritePlan<'a> {
version: Version,
cx: &'a mut Ctx,
ext: cadcraft_geom::Bounds2,
/// The most dash elements a linetype is written with (a DWG's count is one byte); `None`
/// writes every element.
max_dashes: Option<usize>,
}
fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String> {
/// The tables; the LTYPE handles by upper-case name, and how many linetypes were written with
/// only their first `plan.max_dashes` elements.
fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> (HashMap<String, String>, usize) {
let d = plan.d;
let version = plan.version;
let cx = plan.cx;
@@ -32,8 +37,13 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
// in the STYLE table below: (tag position, style name, is a shape) are filled in there.
let mut ltype_handles: HashMap<String, String> = HashMap::new();
let mut ltype_style_refs: Vec<(usize, Option<String>, bool)> = Vec::new();
let mut linetypes_cut = 0usize;
let th = table_head(w, "LTYPE", d.linetypes.len());
for lt in &d.linetypes {
let pattern = plan.max_dashes.and_then(|max| lt.pattern.get(..max)).unwrap_or(&lt.pattern);
if pattern.len() < lt.pattern.len() {
linetypes_cut = linetypes_cut.saturating_add(1);
}
let h = record_head(w, "LTYPE", &th, "AcDbLinetypeTableRecord");
ltype_handles.entry(lt.name.to_ascii_uppercase()).or_insert(h.clone());
cx.ltypes.entry(lt.name.to_ascii_uppercase()).or_insert(h);
@@ -41,9 +51,9 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
w.i(70, if crate::dxf_xref::dependent(&lt.name) { 48 } else { 0 });
w.s(3, &lt.description);
w.i(72, 65);
w.i(73, lt.pattern.len() as i64);
w.f(40, lt.pattern_length());
for el in &lt.pattern {
w.i(73, pattern.len() as i64);
w.f(40, pattern.iter().map(|el| el.length.abs()).sum());
for el in pattern {
w.f(49, el.length);
// 74: 2 = text, 4 = shape, + 1 when the rotation is absolute (DXF Reference, LTYPE).
let (kind, shape) = match (&el.text, el.shape) {
@@ -191,7 +201,7 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
}
w.s(0, "ENDTAB");
write_dimstyles(w, d, cx, version);
ltype_handles
(ltype_handles, linetypes_cut)
}
/// The LAYER table; when the drawing has layer states AutoCAD can hold, the table's extension
@@ -1056,14 +1066,15 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
/// The drawing's DXF tags, declaring `version` in `$ACADVER`, with what `target` (the version the
/// file ends up in) has, and the foreign objects the file keeps, by their handles in the drawing.
/// `bridge`: the text is for the DWG bridge, not a DXF file. The versions alone can't say so: an
/// R2000 DWG is bridged from R2000 text.
/// R2000 DWG is bridged from R2000 text. The bridge's linetypes keep at most
/// [`super::DWG_MAX_LINETYPE_ELEMENTS`] elements; the last value counts those cut.
pub(super) fn tags_kept_for(
d: &Drawing,
version: Version,
target: Version,
frozen_341: bool,
bridge: bool,
) -> (Vec<Tag>, std::collections::HashSet<Handle>) {
) -> (Vec<Tag>, std::collections::HashSet<Handle>, usize) {
// An in-place block edit in progress is not written: the drawing as before it.
let committed = d.committed();
let d: &Drawing = &committed;
@@ -1182,7 +1193,8 @@ pub(super) fn tags_kept_for(
write_classes(&mut w, &cx, &every);
let ltype_handles = write_tables(&mut w, TableWritePlan { d, version, cx: &mut cx, ext: d.extents(&Space::Model) });
let max_dashes = bridge.then_some(super::DWG_MAX_LINETYPE_ELEMENTS);
let (ltype_handles, linetypes_cut) = write_tables(&mut w, TableWritePlan { d, version, cx: &mut cx, ext: d.extents(&Space::Model), max_dashes });
// BLOCK_RECORD
let th = table_head(&mut w, "BLOCK_RECORD", 1 + ps_brs.len() + user_blocks.len() + dim_defs.len() + arrow_defs.len() + table_defs.len());
@@ -1344,7 +1356,7 @@ pub(super) fn tags_kept_for(
add_class_instance_counts(&mut w.t, target);
mark_xrefs(&mut w.t, d);
plot_settings_compatibility(&mut w.t, target);
(w.t, kept)
(w.t, kept, linetypes_cut)
}
fn plot_settings_compatibility(tags: &mut Vec<Tag>, target: Version) {
+1 -1
View File
@@ -38,7 +38,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::{DWG_MAX_LINETYPE_ELEMENTS, dwg_compat_lost, dwg_notes, entity_groups, proxies_lost};
pub use pdf::{PdfOptions, pdf, plot};
/// How a drawing is saved as DXF or DWG.
+1 -1
View File
@@ -34,7 +34,7 @@ pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
let d = match (space, margins) {
(Space::Paper(n), Some(m)) => {
let mut c = d.clone();
if let Some(l) = c.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(n)) {
if let Some(l) = c.layouts.by_name_mut(n) {
l.page.margins_mm = m;
}
with_margins = c;

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