M0: CADCraft skeleton and vertical slice

Workspace (geom, dxf, color, doc, fonts, render, io, engine, ui-egui, mcp; apps cadcraft,
cadcraft-cli, cadcraft-web; xtask), AutoCAD-for-Mac style UI with code-drawn icons, command line
with prompts/keywords/AutoComplete, draw and modify commands, object snaps, polar/ortho,
selection, undo, layers and properties palettes, DXF read/write, SVG/PNG export, MCP server,
JSON control channel, CLI, wasm build, README, ROADMAP, AGENTS.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Brandon Thomas
2026-10-05 23:22:25 -04:00
co-authored by Claude Opus 5.5
parent ebfebbdbf4
commit d9ab00c53c
132 changed files with 30261 additions and 5 deletions
+9 -2
View File
@@ -1,3 +1,10 @@
*~
plan/
plans/
/target
/plan/
/plans/
/dist/
/log/
/temp/
.DS_Store
*.swp
/apps/cadcraft-web/dist/
+49
View File
@@ -0,0 +1,49 @@
# CADCraft — instructions for agents
CADCraft is a clean-room, open-source, pure-Rust computer-aided design and drafting application targeting Autodesk AutoCAD parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows, Linux and FreeBSD, and on the web via WASM. Siblings with the same conventions: `../photocraft` (Photoshop-class), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../printcraft` (Acrobat), `../effectcraft` (After Effects), `../designcraft` (InDesign).
Standards and learnings shared across the crafting apps live in `../../craftrules` (or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its standards, and contribute reusable learnings back there. Never code: repos don't share code.
## Start every session here
1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/autocad/*` (`01-observed-ui.md` holds measured observations of the running reference app; `04-menu-tree.txt` the menu tree by name).
2. Library decisions: `plan/adr/0001-geometry-libraries.md` (what we may depend on, what is rejected for licence reasons).
3. Follow the autonomous operation protocol (`plan/execution-plan.md` §6). Don't stop to ask unless it lists the decision as the owner's.
`plan/` is gitignored (local only).
## Never crash
People trust CADCraft with their drawings; a crash loses their work. **This outranks feature work.** Standard: [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md).
- **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`).
- **Errors are `Result<T, E>`** through the crate's error type and `?`. An unfinished feature returns an error or reports "not available yet"; it never panics.
- **Input-derived numbers are hostile** (DXF/DWG files, command-line text, MCP/control params): `get()` not `[i]`, checked arithmetic, no NaN casts, cap input-sized allocations and loop counts.
- **Bound recursion** (nested/cyclic block references: `MAX_BLOCK_DEPTH`).
- **Last-resort guard:** `Session::execute` and interactive command input run under `catch_unwind`; an escaped panic restores the drawing and reports an error.
- **Prove it:** every crash fix lands with a regression test (see `hostile_params_never_panic`, `hostile_dxf_does_not_panic`).
- Every production crate root carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`.
## Non-negotiables
- **Clean-room.** AutoCAD is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic drawings, take screenshots (by window id) stored only under `plan/autocad/screenshots/` (never committed). **Never** read, disassemble or copy anything inside the AutoCAD bundle (names/listings only); never copy Autodesk fonts (SHX), hatch patterns (`.pat`), linetypes (`.lin`), templates, CUI/PGP files, icons, artwork or help text; never commit files produced by AutoCAD. File formats come from public specifications (Autodesk's published DXF Reference, the Open Design Alliance's public DWG specification) and our own synthetic tests. Never copy or link GPL/LGPL/AGPL code (LibreDWG, LibreCAD, QCAD, FreeCAD's planegcs, SolveSpace, OpenCASCADE) — don't even read their sources.
- **Assets — absolutely essential.** CADCraft contains **no Autodesk, Adobe or Avid iconography, images, fonts, patterns or artwork — ever.** Every icon is drawn in code (`crates/ui-egui/src/icons.rs`), every hatch pattern and linetype is our own definition (`crates/doc/src/library.rs`), the drafting font is our own (`crates/fonts/src/stroke.rs`). Any file asset must be original, public domain/CC0, OSI-licensed, or redistributable Creative Commons (or licensed open source by a contributor who made it), and **must have a row in `ATTRIBUTION.md`** with author, source and licence (`cargo xtask assets` enforces it). The only exception is the ArtCraft brand in `docs/brand/` (trademarks, `docs/brand/LICENSE-brand.txt`). Screenshots of Autodesk software are never committed. Breaking this rule is the most serious mistake you can make in this repo.
- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`), never a `Cargo.toml` dependency. Code and tests must work without it.
- **Shared test corpora** live in separate repos (`storytold/<app>-corpus`); never commit large binary fixtures here.
- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (`CommandSpec`: id = AutoCAD's command name in lower case, label, menu path, shortcut, aliases, params doc, `enabled`, JSON `run`, optional `interactive` prompt machine) + tests. UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The command line, menus, toolbar, Tool Sets, scripts, CLI, control channel and MCP all reach the same commands.
- **Programmatic calls never open dialogs.** `engine.execute` runs the JSON form with defaults; only menu/toolbar invocation starts the interactive prompt sequence.
- **Layering** is enforced by `cargo xtask layers`: L0 `geom`, `dxf` → L1 `color`, `doc` → L2 `fonts`, `render` → L3 `io` → L4 `engine` → L5 `ui-egui`, `mcp` → apps. Nothing below L5 depends on egui/eframe/winit/wgpu/rfd. **The UI crate is swappable.**
- **The UI is thin**: panels read engine state and act through `app.run(id, params)` / `app.start(id)` / `app.cmdline(text)`. Colours come from `theme::Tokens`.
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). Commit after every feature arc that builds, and push to `main`.
## Running and looking at the app
- `cargo run --release -p cadcraft -- --sample --control PORT` (sample drawing + control channel). Pick a free port; other crafting apps use control ports too.
- Drive it with JSON lines on `127.0.0.1:PORT`:
- `{"id":1,"method":"cmdline.input","params":{"text":"circle 0,0 5"}}` — type at the command line exactly like a user (prompts, keywords, `@dx,dy`, `@d<a`, direct distance entry).
- `{"id":2,"method":"engine.execute","params":{"command":"line","params":{"points":[[0,0],[10,0]]}}}` — JSON form.
- `{"id":3,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}` then read the PNG.
- Methods: `crates/ui-egui/src/control.rs`; protocol doc: `docs/control-protocol.md`.
- **For UI work, look at the result** (screenshot, read the PNG) and compare with `plan/autocad/screenshots/`. If no frame is presented (screen locked) use `ui.render` or `cadcraft-cli`.
- Headless: `cadcraft-cli run --sample --script 'LINE 0,0 10,10\n' --export out.png`; `cadcraft-cli info file.dxf`; `cadcraft-cli mcp`.
- Shell gotcha: `mv`/`cp` may be aliased interactive — use `/bin/mv -f` / `/bin/cp -f`.
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done (disk).
## Roadmap
`ROADMAP.md` (committed) tracks status, milestones, parity and estimates. Update it whenever a milestone task lands. `cargo xtask parity` recomputes the command-catalog parity in `docs/parity.md`.
+43
View File
@@ -0,0 +1,43 @@
# Asset attribution
Every non-code asset in this repository (images, icons, fonts, example drawings, presets) is listed
here with its author, source and licence. `cargo xtask assets` (part of `cargo xtask ci`) fails if
an asset file is missing from this table.
**Policy (mandatory):** CADCraft contains **no Autodesk, Adobe or Avid iconography, images,
artwork, fonts, hatch patterns, linetypes, templates or presets.** Every asset is original work by
CADCraft contributors or third-party material under an open licence (OSI open source, public domain
/ CC0, or Creative Commons that allows redistribution). Screenshots of Autodesk software are never
committed. Font files are not added here: shared fonts live in
[storytold/craft-fonts](https://github.com/storytold/craft-fonts), an optional build input. The one
exception is the ArtCraft brand in `docs/brand/`: ArtCraft trademarks, not open source, used under
`docs/brand/LICENSE-brand.txt`.
Generated-in-code assets are original and have no file to list:
- the UI icon set (`crates/ui-egui/src/icons.rs`);
- the "CADCraft Stroke" single-stroke drafting font (`crates/fonts/src/stroke.rs`);
- the standard linetype and hatch-pattern libraries (`crates/doc/src/library.rs`; industry-common
names, our own dash/spacing values);
- the colour index palette, generated from its structure (`crates/color/src/lib.rs`);
- the sample drawings (`crates/engine/src/sample.rs`).
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
| `assets/app-icon/cadcraft-16.png` | CADCraft contributors | generated (provisional drafting-triangle icon) | MIT OR Apache-2.0 | Provisional until the mascot icon is drawn |
| `assets/app-icon/cadcraft-32.png` | CADCraft contributors | generated | MIT OR Apache-2.0 | |
| `assets/app-icon/cadcraft-48.png` | CADCraft contributors | generated | MIT OR Apache-2.0 | |
| `assets/app-icon/cadcraft-64.png` | CADCraft contributors | generated | MIT OR Apache-2.0 | |
| `assets/app-icon/cadcraft-128.png` | CADCraft contributors | generated | MIT OR Apache-2.0 | |
| `assets/app-icon/cadcraft-256.png` | CADCraft contributors | generated | MIT OR Apache-2.0 | |
| `assets/app-icon/cadcraft-512.png` | CADCraft contributors | generated | MIT OR Apache-2.0 | |
| `assets/app-icon/cadcraft-1024.png` | CADCraft contributors | generated | MIT OR Apache-2.0 | |
| `assets/app-icon/cadcraft-macos-512.png` | CADCraft contributors | generated (macOS margin variant) | MIT OR Apache-2.0 | |
| `docs/images/ui-bracket.png` | CADCraft contributors | screenshot of CADCraft itself (sample drawing generated in code) | MIT OR Apache-2.0 | Original; no Autodesk UI |
| `docs/brand/artcraft-logo-white.png` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source |
| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source |
| `docs/brand/artcraft-logo.png` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source |
| `docs/brand/artcraft-logo.svg` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source |
| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source |
| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source |
| `docs/brand/artcraft-mark.png` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source |
| `docs/brand/artcraft-mark.svg` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source |
+49
View File
@@ -0,0 +1,49 @@
# CADCraft — instructions for agents
CADCraft is a clean-room, open-source, pure-Rust computer-aided design and drafting application targeting Autodesk AutoCAD parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows, Linux and FreeBSD, and on the web via WASM. Siblings with the same conventions: `../photocraft` (Photoshop-class), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../printcraft` (Acrobat), `../effectcraft` (After Effects), `../designcraft` (InDesign).
Standards and learnings shared across the crafting apps live in `../../craftrules` (or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its standards, and contribute reusable learnings back there. Never code: repos don't share code.
## Start every session here
1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/autocad/*` (`01-observed-ui.md` holds measured observations of the running reference app; `04-menu-tree.txt` the menu tree by name).
2. Library decisions: `plan/adr/0001-geometry-libraries.md` (what we may depend on, what is rejected for licence reasons).
3. Follow the autonomous operation protocol (`plan/execution-plan.md` §6). Don't stop to ask unless it lists the decision as the owner's.
`plan/` is gitignored (local only).
## Never crash
People trust CADCraft with their drawings; a crash loses their work. **This outranks feature work.** Standard: [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md).
- **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`).
- **Errors are `Result<T, E>`** through the crate's error type and `?`. An unfinished feature returns an error or reports "not available yet"; it never panics.
- **Input-derived numbers are hostile** (DXF/DWG files, command-line text, MCP/control params): `get()` not `[i]`, checked arithmetic, no NaN casts, cap input-sized allocations and loop counts.
- **Bound recursion** (nested/cyclic block references: `MAX_BLOCK_DEPTH`).
- **Last-resort guard:** `Session::execute` and interactive command input run under `catch_unwind`; an escaped panic restores the drawing and reports an error.
- **Prove it:** every crash fix lands with a regression test (see `hostile_params_never_panic`, `hostile_dxf_does_not_panic`).
- Every production crate root carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`.
## Non-negotiables
- **Clean-room.** AutoCAD is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic drawings, take screenshots (by window id) stored only under `plan/autocad/screenshots/` (never committed). **Never** read, disassemble or copy anything inside the AutoCAD bundle (names/listings only); never copy Autodesk fonts (SHX), hatch patterns (`.pat`), linetypes (`.lin`), templates, CUI/PGP files, icons, artwork or help text; never commit files produced by AutoCAD. File formats come from public specifications (Autodesk's published DXF Reference, the Open Design Alliance's public DWG specification) and our own synthetic tests. Never copy or link GPL/LGPL/AGPL code (LibreDWG, LibreCAD, QCAD, FreeCAD's planegcs, SolveSpace, OpenCASCADE) — don't even read their sources.
- **Assets — absolutely essential.** CADCraft contains **no Autodesk, Adobe or Avid iconography, images, fonts, patterns or artwork — ever.** Every icon is drawn in code (`crates/ui-egui/src/icons.rs`), every hatch pattern and linetype is our own definition (`crates/doc/src/library.rs`), the drafting font is our own (`crates/fonts/src/stroke.rs`). Any file asset must be original, public domain/CC0, OSI-licensed, or redistributable Creative Commons (or licensed open source by a contributor who made it), and **must have a row in `ATTRIBUTION.md`** with author, source and licence (`cargo xtask assets` enforces it). The only exception is the ArtCraft brand in `docs/brand/` (trademarks, `docs/brand/LICENSE-brand.txt`). Screenshots of Autodesk software are never committed. Breaking this rule is the most serious mistake you can make in this repo.
- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`), never a `Cargo.toml` dependency. Code and tests must work without it.
- **Shared test corpora** live in separate repos (`storytold/<app>-corpus`); never commit large binary fixtures here.
- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (`CommandSpec`: id = AutoCAD's command name in lower case, label, menu path, shortcut, aliases, params doc, `enabled`, JSON `run`, optional `interactive` prompt machine) + tests. UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The command line, menus, toolbar, Tool Sets, scripts, CLI, control channel and MCP all reach the same commands.
- **Programmatic calls never open dialogs.** `engine.execute` runs the JSON form with defaults; only menu/toolbar invocation starts the interactive prompt sequence.
- **Layering** is enforced by `cargo xtask layers`: L0 `geom`, `dxf` → L1 `color`, `doc` → L2 `fonts`, `render` → L3 `io` → L4 `engine` → L5 `ui-egui`, `mcp` → apps. Nothing below L5 depends on egui/eframe/winit/wgpu/rfd. **The UI crate is swappable.**
- **The UI is thin**: panels read engine state and act through `app.run(id, params)` / `app.start(id)` / `app.cmdline(text)`. Colours come from `theme::Tokens`.
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). Commit after every feature arc that builds, and push to `main`.
## Running and looking at the app
- `cargo run --release -p cadcraft -- --sample --control PORT` (sample drawing + control channel). Pick a free port; other crafting apps use control ports too.
- Drive it with JSON lines on `127.0.0.1:PORT`:
- `{"id":1,"method":"cmdline.input","params":{"text":"circle 0,0 5"}}` — type at the command line exactly like a user (prompts, keywords, `@dx,dy`, `@d<a`, direct distance entry).
- `{"id":2,"method":"engine.execute","params":{"command":"line","params":{"points":[[0,0],[10,0]]}}}` — JSON form.
- `{"id":3,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}` then read the PNG.
- Methods: `crates/ui-egui/src/control.rs`; protocol doc: `docs/control-protocol.md`.
- **For UI work, look at the result** (screenshot, read the PNG) and compare with `plan/autocad/screenshots/`. If no frame is presented (screen locked) use `ui.render` or `cadcraft-cli`.
- Headless: `cadcraft-cli run --sample --script 'LINE 0,0 10,10\n' --export out.png`; `cadcraft-cli info file.dxf`; `cadcraft-cli mcp`.
- Shell gotcha: `mv`/`cp` may be aliased interactive — use `/bin/mv -f` / `/bin/cp -f`.
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done (disk).
## Roadmap
`ROADMAP.md` (committed) tracks status, milestones, parity and estimates. Update it whenever a milestone task lands. `cargo xtask parity` recomputes the command-catalog parity in `docs/parity.md`.
Generated
+4590
View File
File diff suppressed because it is too large Load Diff
+64
View File
@@ -0,0 +1,64 @@
[workspace]
resolver = "3"
members = ["crates/*", "apps/*", "xtask"]
# default-members
[workspace.package]
version = "0.1.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.90"
repository = "https://github.com/storytold/cadcraft"
[workspace.dependencies]
# internal
cadcraft-geom = { path = "crates/geom" }
cadcraft-dxf = { path = "crates/dxf" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-fonts = { path = "crates/fonts" }
cadcraft-render = { path = "crates/render" }
cadcraft-io = { path = "crates/io" }
cadcraft-engine = { path = "crates/engine" }
cadcraft-ui-egui = { path = "crates/ui-egui" }
cadcraft-mcp = { path = "crates/mcp" }
# foundation
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
log = "0.4"
rayon = "1"
# rendering / formats
tiny-skia = { version = "0.11", default-features = false, features = ["std", "simd", "png-format"] }
skrifa = "0.47"
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
# ui
egui = "0.36"
eframe = { version = "0.36", default-features = false }
egui-wgpu = "0.36"
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
[workspace.lints.rust]
unsafe_code = "forbid"
[workspace.lints.clippy]
dbg_macro = "warn"
todo = "warn"
too_many_arguments = "allow"
type_complexity = "allow"
[profile.dev.package."*"]
opt-level = 2
[profile.dev]
opt-level = 1
[profile.release]
opt-level = 3
lto = "thin"
codegen-units = 16
debug = 0
+177
View File
@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 ArtCraft Team and the CADCraft contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+18
View File
@@ -0,0 +1,18 @@
CADCraft
Copyright (c) 2026 ArtCraft Team and the CADCraft contributors.
Licensed under the MIT License or the Apache License, Version 2.0, at your option
(LICENSE-MIT, LICENSE-APACHE).
The ArtCraft name, wordmark and logos in docs/brand/ are trademarks of the ArtCraft Team. They are
not open source and are not covered by the license above; their terms are in
docs/brand/LICENSE-brand.txt.
Third-party material
None: every bundled asset is original to CADCraft (icons, drafting font, hatch patterns and
linetypes are drawn or defined in code). The per-file list is in ATTRIBUTION.md. Builds made with
the optional craft-fonts input (CRAFT_FONTS_DIR) embed the fonts listed in its ATTRIBUTION.md,
each under the SIL Open Font License 1.1.
CADCraft is an independent project and is not affiliated with, sponsored by or endorsed by
Autodesk, Inc. AutoCAD and DWG are trademarks of Autodesk, Inc.
+217 -3
View File
@@ -1,4 +1,218 @@
CADCraft
=========
<p align="center">
<a href="https://getartcraft.com/">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/brand/artcraft-logo-white.svg">
<img alt="ArtCraft" src="docs/brand/artcraft-logo.svg" width="200">
</picture>
</a>
</p>
By ArtCraft
<h1 align="center">CADCraft</h1>
<p align="center">
<b>Computer-aided design and drafting; an open-source, clean-room reimplementation of Autodesk AutoCAD, rebuilt in pure Rust.</b>
</p>
<p align="center">
A fast, open-source take on the AutoCAD workflow: the command line, object snaps, layers,
dimensions, hatches, blocks and DXF drawings you already know. It runs natively on macOS,
Windows, Linux and FreeBSD, and in the browser via WebAssembly.<br>
<i>By the ArtCraft team.</i>
</p>
<p align="center">
<img alt="Written in Rust" src="https://img.shields.io/badge/written%20in-Rust-0b6f88?style=flat-square&logo=rust&logoColor=white">
<img alt="Runs on macOS, Windows, Linux, FreeBSD and the web" src="https://img.shields.io/badge/runs%20on-macOS%20%C2%B7%20Windows%20%C2%B7%20Linux%20%C2%B7%20BSD%20%C2%B7%20Web-14a3c7?style=flat-square">
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20%2F%20Apache--2.0-0b6f88?style=flat-square">
<img alt="Agent-drivable over MCP" src="https://img.shields.io/badge/agents-MCP-14a3c7?style=flat-square">
<img alt="Status: early development" src="https://img.shields.io/badge/status-early%20development-f07a3a?style=flat-square">
</p>
<p align="center">
<a href="https://discord.gg/artcraft"><img alt="Join the ArtCraft community on Discord" src="https://img.shields.io/badge/Join%20us%20on%20Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white" height="40"></a>
</p>
<p align="center">
<a href="https://getartcraft.com/apps/cadcraft"><b>CADCraft on getartcraft.com</b></a> ·
<a href="https://getartcraft.com/">ArtCraft</a> ·
<a href="https://getartcraft.com/apps">All Crafting Apps</a>
</p>
<br>
<p align="center">
<img src="docs/images/ui-bracket.png" alt="CADCraft with a mechanical drawing of a mounting bracket open: a front view with bolt holes, red centre lines, a yellow hidden circle and cyan dimensions, a hatched section view, notes and a title block; the Tool Sets palette is on the left, Layers and Properties on the right and the command line at the bottom is asking for the next point of a LINE" width="100%">
<br><sub><b>Mounting bracket</b>: a two-view part drawing with dimensions, centre lines, hidden lines and an ANSI31 section hatch — drawn, dimensioned and rendered by CADCraft.</sub>
</p>
> [!NOTE]
> **ArtCraft is a community of artists from all walks of life.** Painters, photographers,
> filmmakers, illustrators, designers, animators, hobbyists, and people who picked up a pencil
> last week. If you make things, you're one of us. **[Come say hi on Discord](https://discord.gg/artcraft).**
<p align="center">
<a href="#why-cadcraft">Why CADCraft</a> ·
<a href="#what-works-today">What works today</a> ·
<a href="#quick-start">Quick start</a> ·
<a href="#drive-it-from-agents-mcp-and-the-cli">Agents, MCP and the CLI</a> ·
<a href="#architecture">Architecture</a> ·
<a href="#roadmap">Roadmap</a> ·
<a href="#the-crafting-apps">The Crafting Apps</a> ·
<a href="#license-and-credits">License and credits</a>
</p>
## Why CADCraft
- **The workflow you know.** Type `L`, click two points, type `@5<45`, press Enter. The command
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); DWG is
on the roadmap. 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
command line exactly like a person, call any command with JSON, inspect the drawing to verify
their work, and render it — over MCP, a JSON control channel, or the CLI.
- **Free.** MIT OR Apache-2.0, with no account and no subscription.
## What works today
CADCraft is in early, fast development. Honest status (see [ROADMAP.md](ROADMAP.md) for parity
numbers):
| Area | Status |
|---|---|
| Drawing area | Model space with adaptive grid, axes, pan/zoom (wheel, middle-drag, pinch), crosshair cursor with pickbox, UCS icon, ViewCube, viewport label |
| Command line | Prompts with keywords, history, AutoComplete, aliases, `@dx,dy`, `@d<a`, `#x,y`, direct distance entry, Enter/space/right-click to repeat, transparent commands, `.scr`-style scripts |
| Draw | LINE, PLINE (arcs, widths), CIRCLE (center/radius/diameter, 2P, 3P), ARC, RECTANG (fillet/chamfer), POLYGON, ELLIPSE (+arcs), SPLINE, POINT, XLINE, RAY, DONUT, TEXT, MTEXT |
| Modify | ERASE, MOVE, COPY, ROTATE, SCALE, MIRROR, STRETCH, OFFSET, TRIM, EXTEND, FILLET, CHAMFER, BREAK, JOIN, EXPLODE, rectangular/polar ARRAY, draw order, OVERKILL |
| Precision | Object snaps (endpoint, midpoint, center, geometric center, node, quadrant, intersection, insertion, perpendicular, tangent, nearest), polar tracking, ortho, grid snap |
| 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 | Dimensions (linear, aligned, radius, diameter, angular, ordinate, arc length) rendered from DIMSTYLE settings, our own single-stroke drafting font, `%%d %%p %%c` codes, MTEXT wrapping and attachment |
| Hatch & blocks | Pattern and solid hatches with our own pattern library, block references with attributes and nested blocks |
| Files | DXF read/write, SVG and PNG export |
| Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) |
## Quick start
```sh
git clone https://github.com/storytold/cadcraft
cd cadcraft
cargo run --release -p cadcraft -- --sample # opens the sample drawing
```
Then try typing at the command line:
```text
line 0,0 @10,0 @0,5 c a closed triangle
circle 5,2 1 a circle
offset 0.25 then pick the circle and a side
zoom e zoom to extents
```
The web build: `cd apps/cadcraft-web && trunk serve` (needs [trunk](https://trunkrs.dev)).
## Drive it from agents, MCP and the CLI
```sh
# MCP server on stdio, headless:
cadcraft-cli mcp
# …or bridged to the running app (start it with --control 7979):
cadcraft-cli mcp --connect 127.0.0.1:7979
# One-shot headless runs:
cadcraft-cli run --sample --script 'CIRCLE 22,3 1\n' --save out.dxf --export out.png
cadcraft-cli info drawing.dxf
cadcraft-cli convert drawing.dxf drawing.svg
```
MCP tools include `command_line` (type at the prompt), `execute` (any command with JSON),
`inspect_drawing`, `query_entities`, `render` (returns a PNG) and, when connected to the app,
`screenshot` and `ui_click`. The desktop app's JSON control channel is documented in
[docs/control-protocol.md](docs/control-protocol.md).
## Architecture
```text
geom ─┐ f64 geometry: arcs, bulges, splines, intersections, offsets
dxf │ (standalone) DXF tag reader/writer
color ┤ colour index, true colour
doc ┤ drawing database, copy-on-write entity store (cheap undo)
fonts ┤ render stroke font + TEXT/MTEXT layout │ display lists, linetypes, hatches, dims, CPU raster
io ┤ DXF mapping, SVG/PNG export
engine┤ sessions, commands, command line + prompts, snaps, selection, undo
ui-egui · mcp the swappable egui front end · MCP server
apps: cadcraft · cadcraft-cli · cadcraft-web
```
Nothing below `ui-egui` knows about egui, so the front end can be replaced. `cargo xtask ci`
checks formatting, clippy, tests, asset attribution, the crate layering and the wasm build.
## Roadmap
See [ROADMAP.md](ROADMAP.md) for milestones, measured parity and the estimate of remaining work.
## The Crafting Apps
CADCraft is one of the **Crafting Apps**: free, open-source creative tools from the
[ArtCraft](https://getartcraft.com/) team, each written from scratch in Rust and each able to
stand on its own.
| | App | What it's for | Code | Learn more |
|:-:|---|---|---|---|
| <img src="https://raw.githubusercontent.com/storytold/photocraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.photocraft.png" alt="" width="32" height="32"> | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) |
| <img src="https://raw.githubusercontent.com/storytold/vectorcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.vectorcraft.png" alt="" width="32" height="32"> | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) |
| <img src="https://raw.githubusercontent.com/storytold/filmcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.filmcraft.png" alt="" width="32" height="32"> | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) |
| <img src="https://raw.githubusercontent.com/storytold/lightcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.lightcraft.png" alt="" width="32" height="32"> | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) |
| <img src="https://raw.githubusercontent.com/storytold/printcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.printcraft.png" alt="" width="32" height="32"> | **PrintCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/printcraft) | [Website](https://getartcraft.com/apps/printcraft) |
| <img src="https://raw.githubusercontent.com/storytold/effectcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png" alt="" width="32" height="32"> | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
| <img src="https://raw.githubusercontent.com/storytold/cadcraft/main/assets/app-icon/cadcraft-64.png" alt="" width="32" height="32"> | **CADCraft** | **Computer-aided design and drafting · you are here** | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control.
<br>
<p align="center">
<a href="https://discord.gg/artcraft"><img alt="Join the ArtCraft community on Discord" src="https://img.shields.io/badge/Join%20us%20on%20Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white" height="40"></a>
</p>
<h3 align="center">Come make things with us</h3>
<p align="center">
Our Discord is where artists of every kind hang out: people who paint, shoot, draw, cut film,
set type, and people still figuring out what they like to make. Share what you're working on,
ask for help, tell us what's broken, or tell us what you wish these tools could do.
Whatever your medium and however long you've been at it, you're welcome here.
</p>
<p align="center">
<a href="https://discord.gg/artcraft"><b>discord.gg/artcraft</b></a> ·
<a href="https://getartcraft.com/">getartcraft.com</a> ·
<a href="https://getartcraft.com/apps">The Crafting Apps</a> ·
<a href="https://getartcraft.com/apps/cadcraft">CADCraft</a>
</p>
## License and credits
CADCraft is dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option.
Copyright (c) 2026 ArtCraft Team and the CADCraft contributors. Required notices are in [NOTICE](NOTICE).
Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
CADCraft's icons, its single-stroke drafting font, its hatch patterns and its linetypes are all
original work, drawn or defined in code. The sample drawings are generated in code too.
The ArtCraft name, wordmark and logos in [`docs/brand/`](docs/brand/) are trademarks of the
ArtCraft Team and are not covered by this license. They may be used only unmodified, and only as
part of this repository and CADCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Forks and modified versions must remove them.
<sub>Autodesk, AutoCAD and DWG are trademarks or registered trademarks of Autodesk, Inc. in the United States and/or other countries. CADCraft is an independent, open-source project and is not affiliated with, sponsored by or endorsed by Autodesk, Inc.; these names are used only to describe the workflows and file formats it is compatible with.</sub>
<p align="center">
<a href="https://getartcraft.com/"><img alt="ArtCraft" src="docs/brand/artcraft-mark.svg" width="28"></a><br>
<sub>Made by the <a href="https://getartcraft.com/">ArtCraft</a> team and community.</sub>
</p>
+52
View File
@@ -0,0 +1,52 @@
# CADCraft roadmap
Status as of **2026-10-07**. CADCraft targets full parity with AutoCAD (2D drafting first, then
annotation, layouts and plotting, DWG, parametrics and 3D), plus things AutoCAD doesn't have:
agent control over MCP, a scriptable CLI, a web build and a free licence.
## Where we are
| Measure | Value |
|---|---|
| Menu breadth (`cargo xtask parity`, [docs/parity.md](docs/parity.md)) | **119 / 491 reference menu items (24%)** |
| Registered commands | 130 (41 with interactive prompts) |
| **Estimated overall feature parity (weighted by how much each area matters)** | **≈ 12%** |
| Tests | geometry, colour, document, fonts, render, DXF, engine (commands, prompts, snaps, selection, undo, scripts, hostile input), MCP agent tasks, xtask |
| Gates | `cargo xtask ci`: fmt, clippy -D warnings, tests, asset attribution, layering, wasm — green |
The weighted estimate counts depth: most covered menu items work in their common forms but lack
some options (e.g. ARC has 3-point and start-center-end but not all eleven variants; TRIM works on
lines, arcs, circles and polylines but not ellipses or splines; dimensions render but have no
interactive DIM commands yet).
## Milestones
| # | Milestone | Status | Estimate (Opus 5.5 wall-clock hours) |
|---|---|---|---|
| M0 | Skeleton + vertical slice: workspace, AutoCAD-style UI, command line, draw/modify basics, DXF, CLI, MCP, web | **done** | — |
| M1 | Drafting core: every Draw-menu 2D command and option, dynamic input fields, object snap tracking, temporary snap overrides, TTR/TTT circles, REVCLOUD, WIPEOUT, REGION, BOUNDARY | in progress (~60%) | 20 |
| M2 | Modify: grips (stretch/move/rotate/scale/mirror, multifunctional), PEDIT, SPLINEDIT, LENGTHEN, BLEND, ALIGN, associative arrays, trim/extend for all curve types, MATCHPROP UI, Quick Properties | ~45% | 30 |
| M3 | Layers & properties: full Layer Properties Manager (filters, VP overrides, states), linetype manager, lineweight display, transparency, QSELECT dialog, Properties for every object type | ~45% | 20 |
| M4 | Annotation: DIM* commands, DIMSTYLE manager, associative dimensions, MLEADER + styles, in-place MTEXT editor, fields, tables + table styles, annotative scaling, TrueType fonts, SHX reader | ~15% | 60 |
| M5 | Hatch & blocks: pick-point boundary detection, islands, gradients, BLOCK/WBLOCK/INSERT dialogs, attributes (ATTDEF/ATTEDIT/BATTMAN), block editor, dynamic block parameters, xrefs, groups, Blocks palette | ~20% | 70 |
| M6 | Layouts & plotting: paper space, viewports (rect/polygonal/object, scale, lock, per-VP layers), page setups, PLOT to PDF/PNG/SVG, plot styles (CTB/STB), PUBLISH | ~5% | 60 |
| M7 | Files: DWG read (R2000–2018), DWG write, DXF fidelity (all object types, round-trip of unknown data), RECOVER/AUDIT, PURGE, templates, autosave, ETRANSMIT, PDF/raster underlays | ~15% | 120 |
| M8 | Inquiry & utilities: MEASUREGEOM, MASSPROP, QuickCalc, Find/Replace, spell check, COUNT, DWG Compare, Settings/OPTIONS, CUI-style customisation, alias editor | ~20% | 30 |
| M9 | Parametric: geometric + dimensional constraints, AutoConstrain, Parameters Manager (constraint solver, see plan/adr/0001) | 0% | 50 |
| M10 | Performance: GPU canvas (wgpu batches), R-tree spatial index, incremental regen, 1M-entity drawings at 60 fps | ~10% | 30 |
| M11 | 3D: UCS, orbit, visual styles, solids (box…loft, booleans, fillet edges), meshes, surfaces, sections, rendering | 0% | 200 |
| M12 | Automation: an embedded safe AutoLISP-compatible interpreter, action recorder, sheet sets, CLI/MCP parity tests | ~25% | 60 |
| M13 | 1.0 polish: preferences, workspaces, themes, localisation, accessibility, signed packages for every platform, docs | ~10% | 40 |
| | **Remaining total** | | **≈ 790 hours** |
At roughly 790 more hours of Opus 5.5 wall-clock work (with parallel agents this compresses to
about 200–250 hours of elapsed time), CADCraft would reach broad AutoCAD parity. 2D drafting parity
(M1–M8) is the first ≈ 410 hours.
## Current focus
1. Interactive DIM commands (DIMLINEAR, DIMALIGNED, DIMRADIUS, DIMDIAMETER, DIMANGULAR, DIMCONTINUE, DIMBASELINE).
2. HATCH with pick-point boundary detection; BLOCK / INSERT.
3. Grip editing.
4. Release pipeline (signed macOS universal, Windows x64/x86, Linux AppImage/deb/rpm, FreeBSD, web).
5. GPU canvas for large drawings.
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "cadcraft-cli"
description = "CADCraft command-line tool: info, convert, run scripts, export, commands, MCP server"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[lints]
workspace = true
[dependencies]
cadcraft-engine = { workspace = true }
cadcraft-io = { workspace = true }
cadcraft-mcp = { workspace = true }
cadcraft-render = { workspace = true }
serde_json = { workspace = true }
+159
View File
@@ -0,0 +1,159 @@
//! `cadcraft-cli`: headless CADCraft.
//!
//! ```text
//! cadcraft-cli info FILE.dxf summary as JSON
//! cadcraft-cli convert IN.dxf OUT.(dxf|svg|png) convert / export
//! cadcraft-cli run [FILE|--sample|--metric] [--script TEXT|--script-file F.scr] [--cmd 'id {json}']... [--save OUT] [--export OUT.png]
//! cadcraft-cli commands [FILTER] command catalog (JSON)
//! cadcraft-cli mcp [--connect HOST:PORT] MCP server on stdio (headless or bridged to the app)
//! ```
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
use std::process::ExitCode;
use cadcraft_engine::Session;
use serde_json::{Value, json};
const USAGE: &str = "usage:
cadcraft-cli info FILE.dxf
cadcraft-cli convert IN.dxf OUT.(dxf|svg|png)
cadcraft-cli run [FILE | --sample | --metric] [--script TEXT] [--script-file F.scr] [--cmd 'id {json}']... [--save OUT.dxf] [--export OUT.(png|svg)]
cadcraft-cli commands [FILTER]
cadcraft-cli mcp [--connect HOST:PORT]
cadcraft-cli --version";
fn install_io() {
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
});
}
fn open(s: &mut Session, path: &str) -> Result<(), String> {
s.execute("open", &json!({ "path": path })).map(|_| ()).map_err(|e| e.to_string())
}
fn info(path: &str) -> Result<(), String> {
let mut s = Session::empty();
open(&mut s, path)?;
let v = s.execute("drawing.inspect", &json!({ "entities": false })).map_err(|e| e.to_string())?;
println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
Ok(())
}
fn export(s: &Session, out: &str) -> Result<(), String> {
let d = s.doc().map_err(|e| e.to_string())?;
let bytes = cadcraft_io::write(d, out).map_err(|e| e.to_string())?;
std::fs::write(out, &bytes).map_err(|e| format!("{out}: {e}"))?;
eprintln!("wrote {out} ({} bytes)", bytes.len());
Ok(())
}
fn run(args: &[String]) -> Result<(), String> {
let mut s = Session::empty();
let mut it = args.iter();
let mut save = None;
let mut exp = None;
let mut steps: Vec<(String, String)> = Vec::new();
while let Some(a) = it.next() {
match a.as_str() {
"--sample" => {
s.open_drawing(cadcraft_engine::sample::default_sample(), "Bracket", None);
}
"--metric" => {
s.new_drawing(true);
}
"--script" => steps.push(("script".into(), it.next().ok_or("--script needs text")?.replace("\\n", "\n"))),
"--script-file" => {
let p = it.next().ok_or("--script-file needs a path")?;
steps.push(("script".into(), std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?));
}
"--cmd" => steps.push(("cmd".into(), it.next().ok_or("--cmd needs `id {json}`")?.clone())),
"--save" => save = Some(it.next().ok_or("--save needs a path")?.clone()),
"--export" => exp = Some(it.next().ok_or("--export needs a path")?.clone()),
f if !f.starts_with("--") => open(&mut s, f)?,
other => return Err(format!("unknown option {other}")),
}
}
if s.docs.is_empty() {
s.new_drawing(false);
}
for (kind, body) in steps {
match kind.as_str() {
"script" => s.script(&body).map_err(|e| e.to_string())?,
_ => {
let (id, json) = body.split_once(' ').unwrap_or((&body, "{}"));
let params: Value = serde_json::from_str(json).map_err(|e| format!("--cmd {id}: {e}"))?;
let r = s.execute(id, &params).map_err(|e| e.to_string())?;
if !r.is_null() {
println!("{r}");
}
}
}
}
for l in &s.log {
eprintln!("{l}");
}
if let Some(p) = save {
export(&s, &p)?;
}
if let Some(p) = exp {
export(&s, &p)?;
}
Ok(())
}
fn main() -> ExitCode {
install_io();
let args: Vec<String> = std::env::args().skip(1).collect();
let rest: Vec<String> = args.iter().skip(1).cloned().collect();
let r = match args.first().map(String::as_str) {
Some("info") => rest.first().ok_or_else(|| USAGE.to_string()).and_then(|p| info(p)),
Some("convert") => match rest.as_slice() {
[i, o] => {
let mut s = Session::empty();
open(&mut s, i).and_then(|_| export(&s, o))
}
_ => Err(USAGE.into()),
},
Some("run") => run(&rest),
Some("commands") => {
let s = Session::new();
let f = rest.first().map(|x| x.to_ascii_lowercase());
let v: Vec<Value> = cadcraft_engine::command_specs()
.iter()
.filter(|c| f.as_ref().is_none_or(|f| c.id.contains(f.as_str()) || c.label.to_ascii_lowercase().contains(f.as_str())))
.map(|c| serde_json::to_value(c.info(&s)).unwrap_or_default())
.collect();
println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
Ok(())
}
Some("mcp") => {
let backend: Box<dyn cadcraft_mcp::Backend> = match rest.iter().position(|a| a == "--connect").and_then(|i| rest.get(i + 1)) {
Some(addr) => match cadcraft_mcp::Remote::connect(addr) {
Ok(r) => Box::new(r),
Err(e) => {
eprintln!("cadcraft-cli: cannot connect to {addr}: {e}");
return ExitCode::FAILURE;
}
},
None => Box::new(cadcraft_mcp::Headless::default()),
};
let stdin = std::io::stdin();
let stdout = std::io::stdout();
cadcraft_mcp::Server::new(backend).serve(stdin.lock(), stdout.lock()).map_err(|e| e.to_string())
}
Some("--version" | "-V") => {
println!("cadcraft-cli {}", env!("CARGO_PKG_VERSION"));
Ok(())
}
_ => Err(USAGE.into()),
};
match r {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("{e}");
ExitCode::FAILURE
}
}
}
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "cadcraft-web"
description = "CADCraft in the browser (eframe web runner, WebGPU with WebGL2 fallback)"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[lints]
workspace = true
[[bin]]
name = "cadcraft-web"
path = "src/main.rs"
[dependencies]
cadcraft-engine = { workspace = true }
cadcraft-ui-egui = { workspace = true }
cadcraft-io = { workspace = true }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "Location"] }
+10
View File
@@ -0,0 +1,10 @@
# Build with: trunk build --release (from apps/cadcraft-web)
[build]
target = "index.html"
dist = "../../dist/web"
public_url = "./"
filehash = true
[serve]
addresses = ["127.0.0.1"]
port = 8771
+19
View File
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>CADCraft</title>
<link data-trunk rel="rust" data-bin="cadcraft-web" data-wasm-opt="z" data-weak-refs />
<style>
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #22282f; }
#cadcraft_canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
#cadcraft_loading { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center;
color: #b8b8b8; font: 14px system-ui, sans-serif; pointer-events: none; }
</style>
</head>
<body>
<canvas id="cadcraft_canvas"></canvas>
<div id="cadcraft_loading">Loading CADCraft&hellip;</div>
</body>
</html>
+84
View File
@@ -0,0 +1,84 @@
//! CADCraft in the browser.
//!
//! Runs the same [`cadcraft_ui_egui::CadApp`] as the desktop app through eframe's web runner
//! (wgpu: WebGPU where available, WebGL2 otherwise). Build with `trunk build --release` from this
//! directory (output in `dist/web`). URL flags: `?webgl` forces WebGL2, `?sample` opens the sample
//! drawing.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(target_arch = "wasm32")]
mod web {
use cadcraft_engine::Session;
use cadcraft_ui_egui::{CadApp, Services};
use wasm_bindgen::JsCast as _;
const CANVAS_ID: &str = "cadcraft_canvas";
const LOADING_ID: &str = "cadcraft_loading";
struct Shell(CadApp);
impl eframe::App for Shell {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
self.0.logic(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.0.ui(ui);
}
}
fn query() -> String {
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}
pub fn start() {
eframe::WebLogger::init(log::LevelFilter::Info).ok();
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
});
wasm_bindgen_futures::spawn_local(async {
let Some(document) = web_sys::window().and_then(|w| w.document()) else { return };
let Some(canvas) = document.get_element_by_id(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()) else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
};
let mut options = eframe::WebOptions::default();
if query().contains("webgl")
&& let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup
{
create.instance_descriptor.backends = eframe::wgpu::Backends::GL;
}
let result = eframe::WebRunner::new()
.start(
canvas,
options,
Box::new(move |_cc| {
let mut app = CadApp::new(Session::new(), Services::default());
if query().contains("sample") {
let _ = app.run("ui.sample", serde_json::json!({}));
}
Ok(Box::new(Shell(app)))
}),
)
.await;
if let Some(el) = document.get_element_by_id(LOADING_ID) {
match result {
Ok(()) => el.remove(),
Err(e) => {
el.set_inner_html(&format!("<p>CADCraft failed to start: {e:?}</p><p>A browser with WebGPU or WebGL2 is required.</p>"))
}
}
}
});
}
}
#[cfg(target_arch = "wasm32")]
fn main() {
web::start();
}
#[cfg(not(target_arch = "wasm32"))]
fn main() {
eprintln!("cadcraft-web only runs in the browser: build it with `trunk build --release` in apps/cadcraft-web");
}
+29
View File
@@ -0,0 +1,29 @@
[package]
name = "cadcraft"
description = "CADCraft desktop app"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
default-run = "cadcraft"
[lints]
workspace = true
[dependencies]
cadcraft-engine = { workspace = true }
cadcraft-ui-egui = { workspace = true }
cadcraft-io = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "links"] }
egui = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
[build-dependencies]
winresource = "0.1"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
rfd = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.21", default-features = false }
+28
View File
@@ -0,0 +1,28 @@
//! Windows only: embed the app icon and version info into `cadcraft.exe`. Elsewhere a no-op.
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=../../assets/app-icon/cadcraft.ico");
println!("cargo:rerun-if-env-changed=CADCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=CADCRAFT_BUILD_SHA");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
if std::path::Path::new("../../assets/app-icon/cadcraft.ico").exists() {
res.set_icon("../../assets/app-icon/cadcraft.ico");
}
res.set("ProductName", "CADCraft")
.set("FileDescription", "CADCraft computer-aided design")
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) 2026 ArtCraft Team and the CADCraft contributors. MIT OR Apache-2.0.")
.set("OriginalFilename", "cadcraft.exe")
.set("InternalName", "cadcraft");
if let Err(e) = res.compile() {
if std::env::var_os("CADCRAFT_REQUIRE_WINRES").is_some() {
eprintln!("embedding Windows resources failed: {e}");
std::process::exit(1);
}
println!("cargo:warning=cadcraft.exe built without icon/version resources: {e}");
}
}
+62
View File
@@ -0,0 +1,62 @@
//! Loopback JSON-lines control server: one request per line, one reply per line.
//! This is the transport the MCP server (`cadcraft-cli mcp --connect`) wraps.
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::Duration;
use cadcraft_ui_egui::ControlRequest;
use serde_json::{Value, json};
pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
let (tx, rx) = channel::<ControlRequest>();
let listener = match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => l,
Err(e) => {
eprintln!("cadcraft: control server failed to bind 127.0.0.1:{port}: {e}");
return rx;
}
};
eprintln!("cadcraft: control server listening on 127.0.0.1:{port}");
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let tx = tx.clone();
let ctx = ctx.clone();
std::thread::spawn(move || serve(stream, tx, ctx));
}
});
rx
}
fn serve(stream: TcpStream, tx: Sender<ControlRequest>, ctx: egui::Context) {
let Ok(read) = stream.try_clone() else { return };
let mut out = stream;
for line in BufReader::new(read).lines() {
let Ok(line) = line else { break };
if line.trim().is_empty() {
continue;
}
let reply = match serde_json::from_str::<Value>(&line) {
Ok(msg) => {
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
let params = msg.get("params").cloned().unwrap_or(json!({}));
let (req, rrx) = ControlRequest::new(method, params);
if tx.send(req).is_err() {
break;
}
ctx.request_repaint();
let mut r = rrx.recv_timeout(Duration::from_secs(60)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"}));
if let Some(o) = r.as_object_mut() {
o.insert("id".into(), id);
}
r
}
Err(e) => json!({"ok": false, "error": format!("bad JSON: {e}")}),
};
if writeln!(out, "{reply}").is_err() {
break;
}
}
}
+143
View File
@@ -0,0 +1,143 @@
//! CADCraft desktop app.
//!
//! Usage: `cadcraft [--control <port>] [--sample] [files…]`
//!
//! `--control <port>` (or `CADCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server:
//! `{"id":1,"method":"cmdline.input","params":{"text":"circle 0,0 5"}}` → `{"id":1,"ok":true,…}`.
//! See `cadcraft_ui_egui::control` for the methods.
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod control_server;
#[cfg(target_os = "macos")]
mod native_menu;
use cadcraft_engine::Session;
use cadcraft_ui_egui::{CadApp, Services};
struct App(CadApp, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
impl eframe::App for App {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
{
if self.1.is_none() && std::env::var_os("CADCRAFT_NO_NATIVE_MENU").is_none() {
self.1 = Some(native_menu::NativeMenu::install(&mut self.0));
}
if let Some(m) = &mut self.1 {
m.poll(&mut self.0, ctx);
}
}
self.0.logic(ctx);
if self.0.quit_requested {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
}
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(raw);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.0.ui(ui);
}
}
/// File format hooks for the engine (it stays I/O-agnostic).
pub fn install_io() {
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
});
}
fn services() -> Services {
Services {
pick_open: Some(Box::new(|| {
rfd::FileDialog::new()
.add_filter("Drawing (DXF)", &["dxf"])
.add_filter("All files", &["*"])
.pick_file()
.map(|p| p.to_string_lossy().to_string())
})),
pick_save: Some(Box::new(|name: &str| {
rfd::FileDialog::new()
.set_file_name(name)
.add_filter("Drawing (DXF)", &["dxf"])
.add_filter("SVG", &["svg"])
.add_filter("PNG", &["png"])
.save_file()
.map(|p| p.to_string_lossy().to_string())
})),
}
}
const APP_ID: &str = "ai.storyteller.cadcraft";
fn app_icon() -> Option<egui::IconData> {
let png: &[u8] = include_bytes!("../../../assets/app-icon/cadcraft-256.png");
eframe::icon_data::from_png_bytes(png).map_err(|e| log::warn!("app icon: {e}")).ok()
}
fn version_string() -> String {
let sha = option_env!("CADCRAFT_BUILD_SHA").unwrap_or("dev");
format!("cadcraft {} ({sha})", env!("CARGO_PKG_VERSION"))
}
fn main() -> eframe::Result {
let mut control_port: Option<u16> = std::env::var("CADCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut files = Vec::new();
let mut sample = false;
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--control" => control_port = args.next().and_then(|p| p.parse().ok()),
"--sample" => sample = true,
"--version" | "-V" => {
println!("{}", version_string());
return Ok(());
}
_ => files.push(a),
}
}
install_io();
let mut options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("CADCraft")
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size([900.0, 560.0])
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false)
.with_app_id(APP_ID),
..Default::default()
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
}
eframe::run_native(
"CADCraft",
options,
Box::new(move |cc| {
let mut app = CadApp::new(Session::empty(), services());
app.integrated_titlebar = cfg!(target_os = "macos");
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx);
}
if sample {
let _ = app.run("ui.sample", serde_json::json!({}));
}
for f in &files {
app.open_path(f);
}
if app.session.docs.is_empty() {
app.session.new_drawing(false);
}
Ok(Box::new(App(
app,
#[cfg(target_os = "macos")]
None,
)))
}),
)
}
+98
View File
@@ -0,0 +1,98 @@
//! macOS: CADCraft's menu tree as the native system menu bar. Items dispatch through the same
//! command path as the in-window menus; enablement is refreshed a few times per second.
use std::collections::HashMap;
use std::str::FromStr;
use cadcraft_ui_egui::CadApp;
use cadcraft_ui_egui::menus::{self, Entry};
use muda::accelerator::Accelerator;
use muda::{Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
pub struct NativeMenu {
_menu: Menu,
items: HashMap<String, (String, MenuItem)>,
last_refresh: f64,
}
/// Accelerator for "Cmd+Shift+S" (modifier-less shortcuts stay in the app so typing works).
fn accel(sc: &str) -> Option<Accelerator> {
if !(sc.contains("Cmd") || sc.contains("Ctrl") || sc.contains("Alt")) {
return None;
}
Accelerator::from_str(&sc.replace("Cmd", "CMD").replace("Alt", "ALT").replace("Shift", "SHIFT").replace("Ctrl", "CTRL")).ok()
}
impl NativeMenu {
pub fn install(app: &mut CadApp) -> Self {
let menu = Menu::new();
let mut items = HashMap::new();
let mut counter = 0usize;
let app_menu = Submenu::new("CADCraft", true);
let about = MenuItem::with_id("cc-about", "About CADCraft", true, None);
let discord = MenuItem::with_id("cc-discord", "Join the ArtCraft Discord…", true, None);
let _ = app_menu.append_items(&[
&about,
&discord,
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::services(None),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::hide(None),
&PredefinedMenuItem::hide_others(None),
&PredefinedMenuItem::show_all(None),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::quit(None),
]);
items.insert("cc-about".into(), ("ui.dialog.about".into(), about));
items.insert("cc-discord".into(), ("ui.discord".into(), discord));
let _ = menu.append(&app_menu);
for (title, entries) in menus::tree(app) {
let sub = Submenu::new(&title, true);
build(&sub, &entries, &mut items, &mut counter);
let _ = menu.append(&sub);
}
menu.init_for_nsapp();
Self { _menu: menu, items, last_refresh: 0.0 }
}
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
while let Ok(ev) = MenuEvent::receiver().try_recv() {
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 {
menus::activate(app, &cmd.clone());
}
ctx.request_repaint();
}
}
let now = cadcraft_ui_egui::now_ms();
if now - self.last_refresh < 300.0 {
return;
}
self.last_refresh = now;
for (cmd, item) in self.items.values() {
let en = cadcraft_engine::find_command(cmd).is_none_or(|c| (c.enabled)(&app.session).is_ok());
item.set_enabled(en);
}
}
}
fn build(parent: &Submenu, entries: &[Entry], items: &mut HashMap<String, (String, MenuItem)>, counter: &mut usize) {
for e in entries {
match e {
Entry::Sub { label, children } => {
let sub = Submenu::new(label, true);
build(&sub, children, items, counter);
let _ = parent.append(&sub);
}
Entry::Item { label, id, shortcut, enabled } => {
*counter += 1;
let mid = format!("cc{counter}");
let i = MenuItem::with_id(mid.clone(), label, *enabled, shortcut.as_deref().and_then(accel));
let _ = parent.append(&i);
items.insert(mid, (id.clone(), i));
}
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 807 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

+4
View File
@@ -0,0 +1,4 @@
allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "cadcraft-color"
description = "CADCraft colour: AutoCAD Color Index palette, true colour, ByLayer/ByBlock"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
serde = { workspace = true }
+265
View File
@@ -0,0 +1,265 @@
//! CAD colours: the 256-entry colour index (ACI), 24-bit true colour, and the logical
//! ByLayer / ByBlock values. The index palette is generated from its well-known structure
//! (24 hues × 5 values × 2 saturations, plus primaries and greys), not copied from any file.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
use serde::{Deserialize, Serialize};
/// An 8-bit sRGB colour.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Rgb(pub u8, pub u8, pub u8);
impl Rgb {
pub fn to_u32(self) -> u32 {
(u32::from(self.0) << 16) | (u32::from(self.1) << 8) | u32::from(self.2)
}
pub fn from_u32(v: u32) -> Rgb {
Rgb(((v >> 16) & 0xff) as u8, ((v >> 8) & 0xff) as u8, (v & 0xff) as u8)
}
pub fn hex(self) -> String {
format!("#{:02x}{:02x}{:02x}", self.0, self.1, self.2)
}
pub fn parse_hex(s: &str) -> Option<Rgb> {
let s = s.trim().trim_start_matches('#');
if s.len() != 6 || !s.is_ascii() {
return None;
}
u32::from_str_radix(s, 16).ok().map(Rgb::from_u32)
}
/// Relative luminance (0..1) for contrast decisions.
pub fn luma(self) -> f64 {
(0.2126 * f64::from(self.0) + 0.7152 * f64::from(self.1) + 0.0722 * f64::from(self.2)) / 255.0
}
}
/// An entity or layer colour.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "camelCase")]
pub enum Color {
#[default]
ByLayer,
ByBlock,
/// ACI 1..=255.
Index(u8),
True(Rgb),
}
impl Color {
pub const WHITE: Color = Color::Index(7);
/// DXF group 62 value: 0 = ByBlock, 256 = ByLayer.
pub fn to_aci(self) -> i16 {
match self {
Color::ByLayer => 256,
Color::ByBlock => 0,
Color::Index(i) => i16::from(i),
Color::True(rgb) => i16::from(nearest_aci(rgb)),
}
}
pub fn from_aci(v: i16) -> Color {
match v {
0 => Color::ByBlock,
1..=255 => Color::Index(v as u8),
_ => Color::ByLayer,
}
}
/// Resolve to RGB given the layer and block colours.
pub fn resolve(self, layer: Color, block: Color) -> Rgb {
match self {
Color::ByLayer => match layer {
Color::ByLayer | Color::ByBlock => aci_rgb(7),
c => c.resolve(Color::Index(7), Color::Index(7)),
},
Color::ByBlock => match block {
Color::ByLayer | Color::ByBlock => aci_rgb(7),
c => c.resolve(Color::Index(7), Color::Index(7)),
},
Color::Index(i) => aci_rgb(i),
Color::True(c) => c,
}
}
/// Short display name like AutoCAD's Properties palette ("ByLayer", "Red", "Color 34", "255,128,0").
pub fn name(self) -> String {
match self {
Color::ByLayer => "ByLayer".into(),
Color::ByBlock => "ByBlock".into(),
Color::Index(i) => match i {
1 => "Red".into(),
2 => "Yellow".into(),
3 => "Green".into(),
4 => "Cyan".into(),
5 => "Blue".into(),
6 => "Magenta".into(),
7 => "White".into(),
_ => format!("Color {i}"),
},
Color::True(Rgb(r, g, b)) => format!("{r},{g},{b}"),
}
}
/// Parse "red", "7", "bylayer", "255,0,0", "#ff0000".
pub fn parse(s: &str) -> Option<Color> {
let t = s.trim().to_ascii_lowercase();
let named = ["", "red", "yellow", "green", "cyan", "blue", "magenta", "white"];
if let Some(i) = named.iter().position(|n| !n.is_empty() && *n == t) {
return Some(Color::Index(i as u8));
}
match t.as_str() {
"bylayer" => return Some(Color::ByLayer),
"byblock" => return Some(Color::ByBlock),
"black" => return Some(Color::Index(7)),
_ => {}
}
if let Some(rest) = t.strip_prefix("color ") {
return rest.trim().parse::<u8>().ok().filter(|i| *i >= 1).map(Color::Index);
}
if let Ok(i) = t.parse::<u16>() {
return match i {
0 => Some(Color::ByBlock),
256 => Some(Color::ByLayer),
1..=255 => Some(Color::Index(i as u8)),
_ => None,
};
}
if t.starts_with('#') {
return Rgb::parse_hex(&t).map(Color::True);
}
let parts: Vec<_> = t.split(',').map(|p| p.trim().parse::<u8>()).collect();
if let [Ok(r), Ok(g), Ok(b)] = parts.as_slice() {
return Some(Color::True(Rgb(*r, *g, *b)));
}
None
}
}
/// The RGB of ACI `i` (0 and out-of-range map to white/7).
pub fn aci_rgb(i: u8) -> Rgb {
PALETTE.get(usize::from(i)).copied().unwrap_or(Rgb(255, 255, 255))
}
/// The palette as a 256-entry table (entry 0 = ByBlock placeholder = black).
pub static PALETTE: std::sync::LazyLock<[Rgb; 256]> = std::sync::LazyLock::new(build_palette);
fn build_palette() -> [Rgb; 256] {
let mut p = [Rgb(0, 0, 0); 256];
let base = [
Rgb(0, 0, 0),
Rgb(255, 0, 0),
Rgb(255, 255, 0),
Rgb(0, 255, 0),
Rgb(0, 255, 255),
Rgb(0, 0, 255),
Rgb(255, 0, 255),
Rgb(255, 255, 255),
Rgb(128, 128, 128),
Rgb(192, 192, 192),
];
for (slot, c) in p.iter_mut().zip(base) {
*slot = c;
}
let values = [255.0, 165.0, 127.0, 76.0, 38.0];
for i in 10..250usize {
let hue = (i - 10) / 10; // 0..24, 15° each
let sub = i % 10;
let v: f64 = values.get(sub / 2).copied().unwrap_or(255.0);
let half = sub % 2 == 1;
let (r, g, b) = hue_fractions(hue);
let ch = |f: f64| -> u8 {
let f = if half { 0.5 + 0.5 * f } else { f };
(v * f).floor().clamp(0.0, 255.0) as u8
};
if let Some(slot) = p.get_mut(i) {
*slot = Rgb(ch(r), ch(g), ch(b));
}
}
let greys = [51u8, 91, 132, 173, 214, 255];
for (k, g) in greys.iter().enumerate() {
if let Some(slot) = p.get_mut(250 + k) {
*slot = Rgb(*g, *g, *g);
}
}
p
}
/// Channel fractions for hue step 0..24 (red → yellow → green → cyan → blue → magenta → red).
fn hue_fractions(h: usize) -> (f64, f64, f64) {
let seg = h / 4;
let t = (h % 4) as f64 / 4.0;
match seg {
0 => (1.0, t, 0.0),
1 => (1.0 - t, 1.0, 0.0),
2 => (0.0, 1.0, t),
3 => (0.0, 1.0 - t, 1.0),
4 => (t, 0.0, 1.0),
_ => (1.0, 0.0, 1.0 - t),
}
}
/// The closest index colour to an RGB value (1..=255).
pub fn nearest_aci(c: Rgb) -> u8 {
let mut best = (u32::MAX, 7u8);
for i in 1..=255u8 {
let p = aci_rgb(i);
let d = |a: u8, b: u8| (i32::from(a) - i32::from(b)).pow(2) as u32;
let dist = d(p.0, c.0) + d(p.1, c.1) + d(p.2, c.2);
if dist < best.0 {
best = (dist, i);
}
}
best.1
}
/// Canvas display colour: ACI 7 (and any near-white/near-black) flips to contrast with the
/// background, as CAD programs do on dark or light model space.
pub fn display_rgb(c: Rgb, background: Rgb) -> Rgb {
let dark_bg = background.luma() < 0.5;
if dark_bg && c.luma() < 0.06 {
Rgb(255, 255, 255)
} else if !dark_bg && c.luma() > 0.94 {
Rgb(0, 0, 0)
} else {
c
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn palette_known_entries() {
assert_eq!(aci_rgb(1), Rgb(255, 0, 0));
assert_eq!(aci_rgb(10), Rgb(255, 0, 0));
assert_eq!(aci_rgb(11), Rgb(255, 127, 127));
assert_eq!(aci_rgb(12), Rgb(165, 0, 0));
assert_eq!(aci_rgb(13), Rgb(165, 82, 82));
assert_eq!(aci_rgb(20), Rgb(255, 63, 0));
assert_eq!(aci_rgb(30), Rgb(255, 127, 0));
assert_eq!(aci_rgb(50), Rgb(255, 255, 0));
assert_eq!(aci_rgb(90), Rgb(0, 255, 0));
assert_eq!(aci_rgb(130), Rgb(0, 255, 255));
assert_eq!(aci_rgb(170), Rgb(0, 0, 255));
assert_eq!(aci_rgb(210), Rgb(255, 0, 255));
assert_eq!(aci_rgb(250), Rgb(51, 51, 51));
assert_eq!(aci_rgb(255), Rgb(255, 255, 255));
}
#[test]
fn aci_roundtrip_and_parse() {
assert_eq!(Color::from_aci(256), Color::ByLayer);
assert_eq!(Color::from_aci(0), Color::ByBlock);
assert_eq!(Color::Index(5).to_aci(), 5);
assert_eq!(Color::parse("Red"), Some(Color::Index(1)));
assert_eq!(Color::parse("bylayer"), Some(Color::ByLayer));
assert_eq!(Color::parse("255,128,0"), Some(Color::True(Rgb(255, 128, 0))));
assert_eq!(Color::parse("#00ff00"), Some(Color::True(Rgb(0, 255, 0))));
assert_eq!(Color::parse("300"), None);
assert_eq!(Color::parse("color 34"), Some(Color::Index(34)));
assert_eq!(nearest_aci(Rgb(250, 2, 3)), 1);
}
#[test]
fn white_flips_on_light_background() {
assert_eq!(display_rgb(Rgb(255, 255, 255), Rgb(255, 255, 255)), Rgb(0, 0, 0));
assert_eq!(display_rgb(Rgb(255, 255, 255), Rgb(33, 40, 48)), Rgb(255, 255, 255));
}
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "cadcraft-doc"
description = "CADCraft drawing database: entities, symbol tables, blocks, layouts, copy-on-write store"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
cadcraft-geom = { workspace = true }
cadcraft-color = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+897
View File
@@ -0,0 +1,897 @@
//! Entities: the graphical objects of a drawing.
use cadcraft_color::Color;
use cadcraft_geom::{
Arc as GArc, Bounds2, Circle as GCircle, Ellipse as GEllipse, Line as GLine, Mat3, PolyVertex, Polyline, Segment, Spline as GSpline, Vec2, Vec3,
};
use serde::{Deserialize, Serialize};
/// A database handle (DXF group 5), unique per drawing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Handle(pub u64);
impl Handle {
pub fn hex(self) -> String {
format!("{:X}", self.0)
}
pub fn parse_hex(s: &str) -> Option<Handle> {
u64::from_str_radix(s.trim(), 16).ok().map(Handle)
}
}
/// Lineweight in hundredths of a millimetre, or a logical value.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Lineweight {
#[default]
ByLayer,
ByBlock,
Default,
/// 0..=211 (hundredths of mm).
Mm100(u16),
}
impl Lineweight {
/// The standard lineweight values (mm × 100).
pub const STANDARD: [u16; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, 60, 70, 80, 90, 100, 106, 120, 140, 158, 200, 211];
pub fn to_dxf(self) -> i16 {
match self {
Lineweight::ByLayer => -1,
Lineweight::ByBlock => -2,
Lineweight::Default => -3,
Lineweight::Mm100(v) => v.min(211) as i16,
}
}
pub fn from_dxf(v: i16) -> Lineweight {
match v {
-2 => Lineweight::ByBlock,
-3 => Lineweight::Default,
0..=211 => Lineweight::Mm100(v as u16),
_ => Lineweight::ByLayer,
}
}
pub fn name(self) -> String {
match self {
Lineweight::ByLayer => "ByLayer".into(),
Lineweight::ByBlock => "ByBlock".into(),
Lineweight::Default => "Default".into(),
Lineweight::Mm100(v) => format!("{:.2} mm", f64::from(v) / 100.0),
}
}
}
/// Transparency: ByLayer, ByBlock, or 0..=90 percent.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Transparency {
#[default]
ByLayer,
ByBlock,
Percent(u8),
}
/// Properties every entity has.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Common {
pub layer: String,
pub color: Color,
pub linetype: String,
pub lineweight: Lineweight,
pub ltscale: f64,
pub transparency: Transparency,
pub visible: bool,
pub thickness: f64,
pub extrusion: Vec3,
}
impl Default for Common {
fn default() -> Self {
Common {
layer: "0".into(),
color: Color::ByLayer,
linetype: "ByLayer".into(),
lineweight: Lineweight::ByLayer,
ltscale: 1.0,
transparency: Transparency::ByLayer,
visible: true,
thickness: 0.0,
extrusion: Vec3::Z,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Entity {
pub handle: Handle,
#[serde(default)]
pub common: Common,
pub kind: EntityKind,
}
impl Entity {
pub fn new(handle: Handle, kind: EntityKind) -> Self {
Entity { handle, common: Common::default(), kind }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Line {
pub a: Vec3,
pub b: Vec3,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Point {
pub p: Vec3,
#[serde(default)]
pub angle: f64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Circle {
pub center: Vec3,
pub radius: f64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Arc {
pub center: Vec3,
pub radius: f64,
/// Radians, CCW.
pub start: f64,
pub end: f64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Ellipse {
pub center: Vec3,
pub major: Vec3,
pub ratio: f64,
pub start: f64,
pub end: f64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LwPolyline {
pub vertices: Vec<PolyVertex>,
pub closed: bool,
#[serde(default)]
pub const_width: f64,
#[serde(default)]
pub elevation: f64,
/// Polyline linetype generation (PLINEGEN).
#[serde(default)]
pub plinegen: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Polyline3d {
pub points: Vec<Vec3>,
pub closed: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum HAlign {
#[default]
Left,
Center,
Right,
Aligned,
Middle,
Fit,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum VAlign {
#[default]
Baseline,
Bottom,
Middle,
Top,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Text {
pub insert: Vec3,
#[serde(default)]
pub align_pt: Option<Vec3>,
pub height: f64,
pub value: String,
#[serde(default)]
pub rotation: f64,
#[serde(default = "one")]
pub width_factor: f64,
#[serde(default)]
pub oblique: f64,
#[serde(default = "standard")]
pub style: String,
#[serde(default)]
pub halign: HAlign,
#[serde(default)]
pub valign: VAlign,
}
fn one() -> f64 {
1.0
}
fn standard() -> String {
"Standard".into()
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MText {
pub insert: Vec3,
pub height: f64,
/// Reference rectangle width (0 = no wrapping).
#[serde(default)]
pub width: f64,
/// 1..=9: TL TC TR ML MC MR BL BC BR.
#[serde(default = "attach_tl")]
pub attach: u8,
#[serde(default)]
pub rotation: f64,
#[serde(default = "standard")]
pub style: String,
/// Raw MTEXT contents with inline codes (\P, {\fArial|b1;...}, \S1/2; …).
pub contents: String,
#[serde(default = "one")]
pub line_spacing: f64,
}
fn attach_tl() -> u8 {
1
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Attrib {
pub tag: String,
pub text: Text,
#[serde(default)]
pub invisible: bool,
#[serde(default)]
pub constant: bool,
#[serde(default)]
pub prompt: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Insert {
pub block: String,
pub insert: Vec3,
#[serde(default = "unit_scale")]
pub scale: Vec3,
#[serde(default)]
pub rotation: f64,
#[serde(default)]
pub attribs: Vec<Attrib>,
#[serde(default = "one_u")]
pub cols: u32,
#[serde(default = "one_u")]
pub rows: u32,
#[serde(default)]
pub col_spacing: f64,
#[serde(default)]
pub row_spacing: f64,
}
fn unit_scale() -> Vec3 {
Vec3::new(1.0, 1.0, 1.0)
}
fn one_u() -> u32 {
1
}
impl Insert {
/// Block-to-world transform (2D part).
pub fn transform(&self, base: Vec2) -> Mat3 {
Mat3::translate(self.insert.xy())
.then_before(Mat3::rotate(self.rotation))
.then_before(Mat3::scale(self.scale.x, self.scale.y))
.then_before(Mat3::translate(-base))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum DimKind {
/// Rotated linear dimension (horizontal = 0, vertical = 90°).
Linear {
rotation: f64,
},
Aligned,
Angular,
Angular3P,
Diameter,
Radius,
Ordinate {
x_type: bool,
},
ArcLength,
}
/// A dimension. Definition points follow DXF: `defpt` (10: dimension line point),
/// `p13`/`p14` (extension origins), `p15`/`p16` (arc/angle points), `text_mid` (11).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Dimension {
pub kind: DimKind,
pub defpt: Vec3,
pub text_mid: Vec3,
#[serde(default)]
pub p13: Vec3,
#[serde(default)]
pub p14: Vec3,
#[serde(default)]
pub p15: Vec3,
#[serde(default)]
pub p16: Vec3,
/// "" = measured value, "<>" inside = measurement placeholder, " " = suppressed.
#[serde(default)]
pub text: String,
#[serde(default = "standard")]
pub style: String,
#[serde(default)]
pub measurement: f64,
#[serde(default)]
pub text_rotation: f64,
/// User moved the text (text_mid is authoritative).
#[serde(default)]
pub user_text_pos: bool,
/// Anonymous block with the rendered geometry (from files); regenerated when edited.
#[serde(default)]
pub block: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Leader {
pub vertices: Vec<Vec3>,
#[serde(default = "yes")]
pub arrow: bool,
#[serde(default)]
pub spline: bool,
#[serde(default = "standard")]
pub style: String,
}
fn yes() -> bool {
true
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MLeader {
pub leaders: Vec<Vec<Vec3>>,
pub landing: Vec3,
pub dogleg: f64,
pub text: Option<MText>,
#[serde(default = "standard")]
pub style: String,
#[serde(default = "one")]
pub arrow_size: f64,
}
/// A hatch boundary loop: closed polyline with bulges.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HatchLoop {
pub vertices: Vec<PolyVertex>,
#[serde(default)]
pub outer: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Hatch {
pub pattern: String,
pub solid: bool,
pub loops: Vec<HatchLoop>,
#[serde(default = "one")]
pub scale: f64,
#[serde(default)]
pub angle: f64,
#[serde(default)]
pub associative: bool,
/// 0 normal (odd parity), 1 outer, 2 ignore.
#[serde(default)]
pub style: u8,
#[serde(default)]
pub elevation: f64,
/// Gradient fill: name + second colour.
#[serde(default)]
pub gradient: Option<Gradient>,
#[serde(default)]
pub origin: Vec2,
#[serde(default)]
pub background: Option<Color>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Gradient {
pub name: String,
pub color1: Color,
pub color2: Color,
#[serde(default)]
pub angle: f64,
#[serde(default)]
pub centered: bool,
}
/// SOLID / TRACE: up to four corners (DXF order 1,2,4,3 when drawn).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Solid {
pub corners: [Vec3; 4],
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Face3d {
pub corners: [Vec3; 4],
#[serde(default)]
pub hidden_edges: u8,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RayLine {
pub base: Vec3,
pub dir: Vec3,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Viewport {
pub center: Vec3,
pub width: f64,
pub height: f64,
pub view_center: Vec2,
pub view_height: f64,
#[serde(default)]
pub id: u32,
#[serde(default)]
pub locked: bool,
#[serde(default)]
pub frozen_layers: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Image {
pub insert: Vec3,
pub u: Vec3,
pub v: Vec3,
pub size: Vec2,
pub path: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Wipeout {
pub boundary: Vec<Vec2>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TableCell {
pub text: String,
#[serde(default)]
pub merged: Option<(u32, u32)>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Table {
pub insert: Vec3,
pub col_widths: Vec<f64>,
pub row_heights: Vec<f64>,
pub cells: Vec<Vec<TableCell>>,
#[serde(default = "standard")]
pub style: String,
#[serde(default = "default_text_h")]
pub text_height: f64,
}
fn default_text_h() -> f64 {
0.18
}
/// A raw DXF group: kept for round-tripping entities we do not model.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RawTag {
pub code: i32,
pub value: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Unknown {
pub dxf_type: String,
pub tags: Vec<RawTag>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum EntityKind {
Line(Line),
Point(Point),
Circle(Circle),
Arc(Arc),
Ellipse(Ellipse),
LwPolyline(LwPolyline),
Polyline3d(Polyline3d),
Spline(GSpline),
Ray(RayLine),
XLine(RayLine),
Text(Text),
MText(MText),
AttDef(Attrib),
Insert(Insert),
Dimension(Dimension),
Leader(Leader),
MLeader(MLeader),
Hatch(Hatch),
Solid(Solid),
Trace(Solid),
Face3d(Face3d),
Viewport(Viewport),
Image(Image),
Wipeout(Wipeout),
Table(Table),
Unknown(Unknown),
}
/// A primitive the entity decomposes into, for snapping, selection, trimming and rendering.
#[derive(Clone, Debug, PartialEq)]
pub enum Prim {
Seg(Segment),
Circle(GCircle),
Ellipse(GEllipse),
Spline(GSpline),
Point(Vec2),
/// An infinite line (`ray == false`) or a ray from `base` along `dir`.
Infinite {
base: Vec2,
dir: Vec2,
ray: bool,
},
/// A filled polygon (solids, wide polylines, hatch fill) — the outline is also selectable.
Fill(Vec<Vec2>),
}
impl EntityKind {
/// AutoCAD's object type name as shown in the Properties palette.
pub fn type_name(&self) -> &'static str {
match self {
EntityKind::Line(_) => "Line",
EntityKind::Point(_) => "Point",
EntityKind::Circle(_) => "Circle",
EntityKind::Arc(_) => "Arc",
EntityKind::Ellipse(_) => "Ellipse",
EntityKind::LwPolyline(_) => "Polyline",
EntityKind::Polyline3d(_) => "3D Polyline",
EntityKind::Spline(_) => "Spline",
EntityKind::Ray(_) => "Ray",
EntityKind::XLine(_) => "Xline",
EntityKind::Text(_) => "Text",
EntityKind::MText(_) => "MText",
EntityKind::AttDef(_) => "Attribute Definition",
EntityKind::Insert(_) => "Block Reference",
EntityKind::Dimension(_) => "Dimension",
EntityKind::Leader(_) => "Leader",
EntityKind::MLeader(_) => "Multileader",
EntityKind::Hatch(_) => "Hatch",
EntityKind::Solid(_) => "2D Solid",
EntityKind::Trace(_) => "Trace",
EntityKind::Face3d(_) => "3D Face",
EntityKind::Viewport(_) => "Viewport",
EntityKind::Image(_) => "Raster Image",
EntityKind::Wipeout(_) => "Wipeout",
EntityKind::Table(_) => "Table",
EntityKind::Unknown(_) => "Proxy",
}
}
/// DXF entity type name.
pub fn dxf_name(&self) -> &str {
match self {
EntityKind::Line(_) => "LINE",
EntityKind::Point(_) => "POINT",
EntityKind::Circle(_) => "CIRCLE",
EntityKind::Arc(_) => "ARC",
EntityKind::Ellipse(_) => "ELLIPSE",
EntityKind::LwPolyline(_) => "LWPOLYLINE",
EntityKind::Polyline3d(_) => "POLYLINE",
EntityKind::Spline(_) => "SPLINE",
EntityKind::Ray(_) => "RAY",
EntityKind::XLine(_) => "XLINE",
EntityKind::Text(_) => "TEXT",
EntityKind::MText(_) => "MTEXT",
EntityKind::AttDef(_) => "ATTDEF",
EntityKind::Insert(_) => "INSERT",
EntityKind::Dimension(_) => "DIMENSION",
EntityKind::Leader(_) => "LEADER",
EntityKind::MLeader(_) => "MULTILEADER",
EntityKind::Hatch(_) => "HATCH",
EntityKind::Solid(_) => "SOLID",
EntityKind::Trace(_) => "TRACE",
EntityKind::Face3d(_) => "3DFACE",
EntityKind::Viewport(_) => "VIEWPORT",
EntityKind::Image(_) => "IMAGE",
EntityKind::Wipeout(_) => "WIPEOUT",
EntityKind::Table(_) => "ACAD_TABLE",
EntityKind::Unknown(u) => u.dxf_type.as_str(),
}
}
/// Geometric primitives in WCS (2D projection). Text/blocks/dimensions return their
/// insertion points only; their full geometry comes from the renderer's expansion.
pub fn prims(&self) -> Vec<Prim> {
match self {
EntityKind::Line(l) => vec![Prim::Seg(Segment::Line(GLine::new(l.a.xy(), l.b.xy())))],
EntityKind::Point(p) => vec![Prim::Point(p.p.xy())],
EntityKind::Circle(c) => vec![Prim::Circle(GCircle::new(c.center.xy(), c.radius))],
EntityKind::Arc(a) => vec![Prim::Seg(Segment::Arc { arc: GArc::new(a.center.xy(), a.radius, a.start, a.end), ccw: true })],
EntityKind::Ellipse(e) => {
vec![Prim::Ellipse(GEllipse { center: e.center.xy(), major: e.major.xy(), ratio: e.ratio, start: e.start, end: e.end })]
}
EntityKind::LwPolyline(p) => {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
pl.segments().into_iter().map(Prim::Seg).collect()
}
EntityKind::Polyline3d(p) => {
let mut v: Vec<Prim> =
p.points.windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(w.first()?.xy(), w.get(1)?.xy()))))).collect();
if p.closed
&& let (Some(a), Some(b)) = (p.points.last(), p.points.first())
{
v.push(Prim::Seg(Segment::Line(GLine::new(a.xy(), b.xy()))));
}
v
}
EntityKind::Spline(s) => vec![Prim::Spline(s.clone())],
EntityKind::Ray(r) => vec![Prim::Infinite { base: r.base.xy(), dir: r.dir.xy().normalized(), ray: true }],
EntityKind::XLine(r) => vec![Prim::Infinite { base: r.base.xy(), dir: r.dir.xy().normalized(), ray: false }],
EntityKind::Solid(s) | EntityKind::Trace(s) => {
let c = &s.corners;
vec![Prim::Fill(vec![c[0].xy(), c[1].xy(), c[3].xy(), c[2].xy()])]
}
EntityKind::Face3d(f) => {
let c = &f.corners;
let pts = [c[0].xy(), c[1].xy(), c[2].xy(), c[3].xy(), c[0].xy()];
pts.windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(*w.first()?, *w.get(1)?))))).collect()
}
EntityKind::Hatch(h) => {
h.loops.iter().flat_map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.segments()).map(Prim::Seg).collect()
}
EntityKind::Wipeout(w) => {
let mut pts = w.boundary.clone();
if let Some(f) = pts.first().copied() {
pts.push(f);
}
pts.windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(*w.first()?, *w.get(1)?))))).collect()
}
EntityKind::Viewport(v) => {
let c = v.center.xy();
let h = Vec2::new(v.width / 2.0, v.height / 2.0);
let b = Bounds2::new(c - h, c + h).corners();
(0..4).map(|i| Prim::Seg(Segment::Line(GLine::new(b[i], b[(i + 1) % 4])))).collect()
}
EntityKind::Leader(l) => {
l.vertices.windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(w.first()?.xy(), w.get(1)?.xy()))))).collect()
}
EntityKind::Text(t) => vec![Prim::Point(t.insert.xy())],
EntityKind::MText(t) => vec![Prim::Point(t.insert.xy())],
EntityKind::AttDef(a) => vec![Prim::Point(a.text.insert.xy())],
EntityKind::Insert(i) => vec![Prim::Point(i.insert.xy())],
EntityKind::Dimension(d) => vec![Prim::Point(d.defpt.xy())],
EntityKind::MLeader(m) => m
.leaders
.iter()
.flat_map(|l| l.windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(w.first()?.xy(), w.get(1)?.xy()))))))
.collect(),
EntityKind::Image(i) => vec![Prim::Point(i.insert.xy())],
EntityKind::Table(t) => vec![Prim::Point(t.insert.xy())],
EntityKind::Unknown(_) => Vec::new(),
}
}
/// Apply a 2D affine transform (move/rotate/uniform scale/mirror). Non-uniform scale turns
/// circles into ellipses only where the kind supports it; otherwise radii use the mean scale.
pub fn transform(&mut self, m: &Mat3) {
let t3 = |p: &mut Vec3| {
let q = m.apply(p.xy());
p.x = q.x;
p.y = q.y;
};
let s = m.scale_factor();
let rot = m.rotation();
let mirror = m.is_mirroring();
match self {
EntityKind::Line(l) => {
t3(&mut l.a);
t3(&mut l.b);
}
EntityKind::Point(p) => t3(&mut p.p),
EntityKind::Circle(c) => {
t3(&mut c.center);
c.radius *= s;
}
EntityKind::Arc(a) => {
let sp = m.apply(Vec2::polar(a.center.xy(), a.radius, a.start));
let ep = m.apply(Vec2::polar(a.center.xy(), a.radius, a.end));
t3(&mut a.center);
a.radius *= s;
let c = a.center.xy();
if mirror {
a.start = c.angle_to(ep);
a.end = c.angle_to(sp);
} else {
a.start = c.angle_to(sp);
a.end = c.angle_to(ep);
}
}
EntityKind::Ellipse(e) => {
let sp = m.apply(e.center.xy() + e.major.xy() * e.start.cos() + e.major.xy().perp() * (e.ratio * e.start.sin()));
let ep = m.apply(e.center.xy() + e.major.xy() * e.end.cos() + e.major.xy().perp() * (e.ratio * e.end.sin()));
t3(&mut e.center);
let mj = m.apply_vec(e.major.xy());
e.major = mj.to3(0.0);
let full = (cadcraft_geom::ccw_sweep(e.start, e.end) - cadcraft_geom::TAU).abs() < 1e-9;
if !full {
let ge = GEllipse { center: e.center.xy(), major: mj, ratio: e.ratio, start: 0.0, end: cadcraft_geom::TAU };
let (ps, pe) = (ge.param_of(sp), ge.param_of(ep));
if mirror {
e.start = pe;
e.end = ps;
} else {
e.start = ps;
e.end = pe;
}
}
}
EntityKind::LwPolyline(p) => {
for v in &mut p.vertices {
v.p = m.apply(v.p);
v.start_width *= s;
v.end_width *= s;
if mirror {
v.bulge = -v.bulge;
}
}
p.const_width *= s;
}
EntityKind::Polyline3d(p) => p.points.iter_mut().for_each(t3),
EntityKind::Spline(sp) => {
for c in sp.control.iter_mut().chain(sp.fit.iter_mut()) {
*c = m.apply(*c);
}
}
EntityKind::Ray(r) | EntityKind::XLine(r) => {
t3(&mut r.base);
r.dir = m.apply_vec(r.dir.xy()).normalized().to3(0.0);
}
EntityKind::Text(t) => transform_text(t, m, s, rot, mirror),
EntityKind::AttDef(a) => transform_text(&mut a.text, m, s, rot, mirror),
EntityKind::MText(t) => {
t3(&mut t.insert);
t.height *= s;
t.width *= s;
t.rotation = cadcraft_geom::norm_angle(t.rotation + rot);
}
EntityKind::Insert(i) => {
t3(&mut i.insert);
i.scale.x *= s;
i.scale.y *= s;
i.scale.z *= s;
i.rotation = cadcraft_geom::norm_angle(i.rotation + rot);
if mirror {
i.scale.y = -i.scale.y;
i.rotation = cadcraft_geom::norm_angle(rot - (i.rotation - rot));
}
for a in &mut i.attribs {
transform_text(&mut a.text, m, s, rot, false);
}
i.col_spacing *= s;
i.row_spacing *= s;
}
EntityKind::Dimension(d) => {
for p in [&mut d.defpt, &mut d.text_mid, &mut d.p13, &mut d.p14, &mut d.p15, &mut d.p16] {
t3(p);
}
if let DimKind::Linear { rotation } = &mut d.kind {
*rotation = cadcraft_geom::norm_angle(*rotation + rot);
}
d.block = None;
}
EntityKind::Leader(l) => l.vertices.iter_mut().for_each(t3),
EntityKind::MLeader(ml) => {
for l in &mut ml.leaders {
l.iter_mut().for_each(t3);
}
t3(&mut ml.landing);
if let Some(t) = &mut ml.text {
t3(&mut t.insert);
t.height *= s;
}
}
EntityKind::Hatch(h) => {
for l in &mut h.loops {
for v in &mut l.vertices {
v.p = m.apply(v.p);
if mirror {
v.bulge = -v.bulge;
}
}
}
h.scale *= s;
h.angle = cadcraft_geom::norm_angle(h.angle + rot);
h.origin = m.apply(h.origin);
}
EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(t3),
EntityKind::Face3d(f) => f.corners.iter_mut().for_each(t3),
EntityKind::Viewport(v) => {
t3(&mut v.center);
v.width *= s;
v.height *= s;
}
EntityKind::Image(i) => {
t3(&mut i.insert);
i.u = m.apply_vec(i.u.xy()).to3(0.0);
i.v = m.apply_vec(i.v.xy()).to3(0.0);
}
EntityKind::Wipeout(w) => w.boundary.iter_mut().for_each(|p| *p = m.apply(*p)),
EntityKind::Table(t) => {
t3(&mut t.insert);
t.col_widths.iter_mut().for_each(|w| *w *= s);
t.row_heights.iter_mut().for_each(|h| *h *= s);
t.text_height *= s;
}
EntityKind::Unknown(_) => {}
}
}
/// Grip points (editable defining points), in display order.
pub fn grips(&self) -> Vec<Vec2> {
match self {
EntityKind::Line(l) => vec![l.a.xy(), l.a.xy().mid(l.b.xy()), l.b.xy()],
EntityKind::Point(p) => vec![p.p.xy()],
EntityKind::Circle(c) => {
let o = c.center.xy();
vec![o, o + Vec2::X * c.radius, o + Vec2::Y * c.radius, o - Vec2::X * c.radius, o - Vec2::Y * c.radius]
}
EntityKind::Arc(a) => {
let g = GArc::new(a.center.xy(), a.radius, a.start, a.end);
vec![g.start_point(), g.mid_point(), g.end_point(), a.center.xy()]
}
EntityKind::Ellipse(e) => {
let c = e.center.xy();
let mj = e.major.xy();
let mn = mj.perp() * e.ratio;
vec![c, c + mj, c + mn, c - mj, c - mn]
}
EntityKind::LwPolyline(p) => {
let mut g: Vec<Vec2> = Vec::new();
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
for (i, v) in p.vertices.iter().enumerate() {
g.push(v.p);
if let Some(s) = pl.segments().get(i) {
g.push(s.mid());
}
}
g
}
EntityKind::Polyline3d(p) => p.points.iter().map(|q| q.xy()).collect(),
EntityKind::Spline(s) => {
if s.fit.is_empty() {
s.control.clone()
} else {
s.fit.clone()
}
}
EntityKind::Ray(r) | EntityKind::XLine(r) => vec![r.base.xy(), r.base.xy() + r.dir.xy()],
EntityKind::Text(t) => vec![t.insert.xy()],
EntityKind::MText(t) => vec![t.insert.xy()],
EntityKind::AttDef(a) => vec![a.text.insert.xy()],
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.attribs.iter().map(|a| a.text.insert.xy())).collect(),
EntityKind::Dimension(d) => vec![d.p13.xy(), d.p14.xy(), d.defpt.xy(), d.text_mid.xy()],
EntityKind::Leader(l) => l.vertices.iter().map(|v| v.xy()).collect(),
EntityKind::MLeader(m) => m.leaders.iter().flat_map(|l| l.iter().map(|v| v.xy())).chain(std::iter::once(m.landing.xy())).collect(),
EntityKind::Hatch(h) => {
let b = Bounds2::from_points(h.loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p)));
vec![b.center()]
}
EntityKind::Solid(s) | EntityKind::Trace(s) => s.corners.iter().map(|c| c.xy()).collect(),
EntityKind::Face3d(f) => f.corners.iter().map(|c| c.xy()).collect(),
EntityKind::Viewport(v) => {
let c = v.center.xy();
let h = Vec2::new(v.width / 2.0, v.height / 2.0);
Bounds2::new(c - h, c + h).corners().to_vec()
}
EntityKind::Image(i) => vec![i.insert.xy()],
EntityKind::Wipeout(w) => w.boundary.clone(),
EntityKind::Table(t) => vec![t.insert.xy()],
EntityKind::Unknown(_) => Vec::new(),
}
}
}
fn transform_text(t: &mut Text, m: &Mat3, s: f64, rot: f64, mirror: bool) {
let q = m.apply(t.insert.xy());
t.insert.x = q.x;
t.insert.y = q.y;
if let Some(a) = &mut t.align_pt {
let q = m.apply(a.xy());
a.x = q.x;
a.y = q.y;
}
t.height *= s;
// MIRRTEXT = 0 (the default): mirrored text keeps reading left to right.
t.rotation = cadcraft_geom::norm_angle(t.rotation + if mirror { 0.0 } else { rot });
}
+126
View File
@@ -0,0 +1,126 @@
//! Approximate entity bounds (used for extents, zoom and selection pre-filtering).
use cadcraft_geom::{Bounds2, Polyline, Vec2};
use crate::{Drawing, Entity, EntityKind, Prim};
/// Nested block references deeper than this are ignored (cyclic or hostile files).
pub const MAX_BLOCK_DEPTH: usize = 16;
fn text_box(insert: Vec2, height: f64, len: usize, width_factor: f64, rotation: f64) -> Bounds2 {
let w = height * 0.8 * width_factor.abs().max(0.01) * len.max(1) as f64;
let pts = [Vec2::ZERO, Vec2::new(w, 0.0), Vec2::new(w, height), Vec2::new(0.0, height)].map(|p| insert + p.rotate(rotation));
Bounds2::from_points(pts)
}
pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 {
match &e.kind {
EntityKind::Text(t) => text_box(
t.align_pt.filter(|_| t.halign != crate::HAlign::Left).unwrap_or(t.insert).xy(),
t.height,
t.value.chars().count(),
t.width_factor,
t.rotation,
),
EntityKind::AttDef(a) => text_box(a.text.insert.xy(), a.text.height, a.tag.chars().count(), a.text.width_factor, a.text.rotation),
EntityKind::MText(t) => {
let lines = t.contents.split("\\P").count().max(1);
let longest = t.contents.split("\\P").map(|l| l.chars().count()).max().unwrap_or(1);
let w = if t.width > 0.0 { t.width } else { t.height * 0.8 * longest as f64 };
let h = t.height * 1.66 * lines as f64;
let (dx, dy) = match t.attach {
2 | 5 | 8 => (-w / 2.0, 0.0),
3 | 6 | 9 => (-w, 0.0),
_ => (0.0, 0.0),
};
let top = match t.attach {
4..=6 => h / 2.0,
7..=9 => h,
_ => 0.0,
};
let o = t.insert.xy();
let pts = [Vec2::new(dx, top + dy), Vec2::new(dx + w, top + dy), Vec2::new(dx + w, top - h + dy), Vec2::new(dx, top - h + dy)]
.map(|p| o + p.rotate(t.rotation));
Bounds2::from_points(pts)
}
EntityKind::Insert(ins) => {
if depth >= MAX_BLOCK_DEPTH {
return Bounds2::EMPTY;
}
let Some(blk) = d.block(&ins.block) else { return Bounds2::from_points([ins.insert.xy()]) };
let m = ins.transform(blk.base.xy());
let mut inner = Bounds2::EMPTY;
for be in blk.entities.iter() {
inner = inner.union(&entity_bounds(d, be, depth + 1));
}
let mut b =
if inner.is_empty() { Bounds2::from_points([ins.insert.xy()]) } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
if ins.cols > 1 || ins.rows > 1 {
let off = Vec2::new(ins.col_spacing * f64::from(ins.cols.saturating_sub(1)), ins.row_spacing * f64::from(ins.rows.saturating_sub(1)))
.rotate(ins.rotation);
b = b.union(&Bounds2::from_points(b.corners().map(|c| c + off)));
}
for a in &ins.attribs {
if !a.invisible {
b = b.union(&text_box(a.text.insert.xy(), a.text.height, a.text.value.chars().count(), a.text.width_factor, a.text.rotation));
}
}
b
}
EntityKind::Dimension(dm) => {
let mut b = Bounds2::from_points(
[dm.defpt.xy(), dm.text_mid.xy(), dm.p13.xy(), dm.p14.xy()].into_iter().filter(|p| *p != Vec2::ZERO || dm.defpt.xy() == Vec2::ZERO),
);
if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n))
&& depth < MAX_BLOCK_DEPTH
{
for be in blk.entities.iter() {
b = b.union(&entity_bounds(d, be, depth + 1));
}
}
b
}
EntityKind::MLeader(m) => {
let mut b = Bounds2::from_points(m.leaders.iter().flatten().map(|v| v.xy()).chain(std::iter::once(m.landing.xy())));
if let Some(t) = &m.text {
b.add(t.insert.xy());
}
b
}
EntityKind::Table(t) => {
let w: f64 = t.col_widths.iter().sum();
let h: f64 = t.row_heights.iter().sum();
Bounds2::new(t.insert.xy(), t.insert.xy() + Vec2::new(w, -h))
}
EntityKind::Image(i) => {
let o = i.insert.xy();
let u = i.u.xy() * i.size.x;
let v = i.v.xy() * i.size.y;
Bounds2::from_points([o, o + u, o + v, o + u + v])
}
EntityKind::LwPolyline(p) => Polyline { vertices: p.vertices.clone(), closed: p.closed }.bounds().expand(p.const_width / 2.0),
kind => {
let mut b = Bounds2::EMPTY;
for p in kind.prims() {
let pb = match p {
Prim::Seg(s) => s.bounds(),
Prim::Circle(c) => c.bounds(),
Prim::Ellipse(e) => e.bounds(),
Prim::Spline(s) => s.bounds(),
Prim::Point(p) => Bounds2::from_points([p]),
// Infinite lines don't contribute to extents (as in ZOOM Extents).
Prim::Infinite { base, ray, .. } => {
if ray {
Bounds2::from_points([base])
} else {
Bounds2::EMPTY
}
}
Prim::Fill(pts) => Bounds2::from_points(pts),
};
b = b.union(&pb);
}
b
}
}
}
+146
View File
@@ -0,0 +1,146 @@
//! Header (drawing-scoped system) variables.
use std::collections::BTreeMap;
use cadcraft_geom::Vec3;
use serde::{Deserialize, Serialize};
/// A header variable value.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum HVal {
Int(i64),
Real(f64),
Str(String),
Point(Vec3),
}
impl HVal {
pub fn as_f64(&self) -> Option<f64> {
match self {
HVal::Int(i) => Some(*i as f64),
HVal::Real(r) => Some(*r),
HVal::Str(s) => s.trim().parse().ok(),
HVal::Point(_) => None,
}
}
pub fn as_i64(&self) -> Option<i64> {
match self {
HVal::Int(i) => Some(*i),
HVal::Real(r) if r.is_finite() => Some(r.round() as i64),
HVal::Str(s) => s.trim().parse().ok(),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
HVal::Str(s) => Some(s),
_ => None,
}
}
pub fn display(&self) -> String {
match self {
HVal::Int(i) => i.to_string(),
HVal::Real(r) => format!("{r:.4}"),
HVal::Str(s) => format!("\"{s}\""),
HVal::Point(p) => format!("{:.4},{:.4},{:.4}", p.x, p.y, p.z),
}
}
}
/// Header variables keyed by name without the `$` (e.g. `LTSCALE`), uppercase.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Header {
pub vars: BTreeMap<String, HVal>,
}
impl Header {
pub fn get(&self, name: &str) -> Option<&HVal> {
self.vars.get(&name.trim_start_matches('$').to_ascii_uppercase())
}
pub fn set(&mut self, name: &str, v: HVal) {
self.vars.insert(name.trim_start_matches('$').to_ascii_uppercase(), v);
}
pub fn f64(&self, name: &str, default: f64) -> f64 {
self.get(name).and_then(HVal::as_f64).filter(|v| v.is_finite()).unwrap_or(default)
}
pub fn i64(&self, name: &str, default: i64) -> i64 {
self.get(name).and_then(HVal::as_i64).unwrap_or(default)
}
pub fn str(&self, name: &str, default: &str) -> String {
self.get(name).and_then(HVal::as_str).map(str::to_string).unwrap_or_else(|| default.to_string())
}
pub fn point(&self, name: &str) -> Option<Vec3> {
match self.get(name)? {
HVal::Point(p) => Some(*p),
_ => None,
}
}
pub fn set_f64(&mut self, name: &str, v: f64) {
self.set(name, HVal::Real(v));
}
pub fn set_i64(&mut self, name: &str, v: i64) {
self.set(name, HVal::Int(v));
}
pub fn set_str(&mut self, name: &str, v: &str) {
self.set(name, HVal::Str(v.into()));
}
fn common() -> Header {
let mut h = Header::default();
h.set_str("ACADVER", "AC1032");
h.set_str("CLAYER", "0");
h.set_i64("CECOLOR", 256);
h.set_str("CELTYPE", "ByLayer");
h.set_i64("CELWEIGHT", -1);
h.set_f64("CELTSCALE", 1.0);
h.set_f64("LTSCALE", 1.0);
h.set_i64("PSLTSCALE", 1);
h.set_str("TEXTSTYLE", "Standard");
h.set_str("DIMSTYLE", "Standard");
h.set_str("CMLEADERSTYLE", "Standard");
h.set_str("CTABLESTYLE", "Standard");
h.set_i64("LUNITS", 2);
h.set_i64("LUPREC", 4);
h.set_i64("AUNITS", 0);
h.set_i64("AUPREC", 0);
h.set_f64("ANGBASE", 0.0);
h.set_i64("ANGDIR", 0);
h.set_i64("PDMODE", 0);
h.set_f64("PDSIZE", 0.0);
h.set_i64("FILLMODE", 1);
h.set_i64("MIRRTEXT", 0);
h.set_i64("ATTMODE", 1);
h.set_f64("THICKNESS", 0.0);
h.set_f64("ELEVATION", 0.0);
h.set_i64("LWDISPLAY", 0);
h.set("INSBASE", HVal::Point(Vec3::ZERO));
h
}
pub fn imperial() -> Header {
let mut h = Header::common();
h.set_i64("MEASUREMENT", 0);
h.set_i64("INSUNITS", 1);
h.set_f64("TEXTSIZE", 0.2);
h.set_f64("DIMSCALE", 1.0);
h.set_f64("FILLETRAD", 0.0);
h.set_f64("CHAMFERA", 0.0);
h.set_f64("CHAMFERB", 0.0);
h.set("LIMMIN", HVal::Point(Vec3::ZERO));
h.set("LIMMAX", HVal::Point(Vec3::new(12.0, 9.0, 0.0)));
h
}
pub fn metric() -> Header {
let mut h = Header::common();
h.set_i64("MEASUREMENT", 1);
h.set_i64("INSUNITS", 4);
h.set_f64("TEXTSIZE", 2.5);
h.set_f64("DIMSCALE", 1.0);
h.set_f64("FILLETRAD", 0.0);
h.set("LIMMIN", HVal::Point(Vec3::ZERO));
h.set("LIMMAX", HVal::Point(Vec3::new(420.0, 297.0, 0.0)));
h
}
}
+237
View File
@@ -0,0 +1,237 @@
//! The CADCraft drawing database.
//!
//! A [`Drawing`] holds the header variables, symbol tables (layers, linetypes, styles), block
//! definitions, model space and paper-space layouts. Entity collections are copy-on-write
//! ([`EntityStore`]), so a whole-drawing clone is cheap and serves as an undo snapshot.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod entity;
mod extents;
mod header;
pub mod library;
mod store;
mod tables;
use std::collections::BTreeMap;
pub use cadcraft_color as color;
pub use cadcraft_geom as geom;
pub use entity::*;
pub use extents::{MAX_BLOCK_DEPTH, entity_bounds};
pub use header::{HVal, Header};
pub use store::EntityStore;
pub use tables::*;
#[derive(Debug, thiserror::Error)]
pub enum DocError {
#[error("no such layer `{0}`")]
NoLayer(String),
#[error("no such block `{0}`")]
NoBlock(String),
#[error("no such entity {0:?}")]
NoEntity(Handle),
#[error("{0}")]
Invalid(String),
}
pub type Result<T> = std::result::Result<T, DocError>;
/// Which entity collection: model space or a named layout's paper space.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Space {
#[default]
Model,
Paper(String),
}
#[derive(Clone, Debug, PartialEq)]
pub struct Drawing {
pub header: Header,
pub layers: Vec<Layer>,
pub linetypes: Vec<Linetype>,
pub text_styles: Vec<TextStyle>,
pub dim_styles: Vec<DimStyle>,
pub mleader_styles: Vec<MLeaderStyle>,
pub table_styles: Vec<TableStyle>,
pub blocks: BTreeMap<String, std::sync::Arc<Block>>,
pub model: EntityStore,
pub layouts: Vec<Layout>,
pub views: Vec<NamedView>,
pub ucss: Vec<Ucs>,
pub layer_states: Vec<LayerState>,
pub groups: Vec<Group>,
/// Next free handle.
pub handseed: u64,
}
impl Default for Drawing {
fn default() -> Self {
Drawing::new_imperial()
}
}
impl Drawing {
/// An empty drawing with the standard tables (inch-based, like acad.dwt-style defaults).
pub fn new_imperial() -> Self {
let mut d = Drawing::bare();
d.header = Header::imperial();
d
}
/// An empty metric drawing (millimetres, ISO-25 dimensions).
pub fn new_metric() -> Self {
let mut d = Drawing::bare();
d.header = Header::metric();
d.dim_styles.push(DimStyle::iso25());
d.header.set_str("DIMSTYLE", "ISO-25");
d
}
fn bare() -> Self {
Drawing {
header: Header::default(),
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }],
linetypes: vec![
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()],
mleader_styles: vec![MLeaderStyle::default()],
table_styles: vec![TableStyle::default()],
blocks: BTreeMap::new(),
model: EntityStore::new(),
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
views: Vec::new(),
ucss: Vec::new(),
layer_states: Vec::new(),
groups: Vec::new(),
handseed: 0x100,
}
}
/// Allocate a fresh handle.
pub fn new_handle(&mut self) -> Handle {
let h = Handle(self.handseed);
self.handseed = self.handseed.saturating_add(1);
h
}
/// Make sure future handles don't collide with `h` (after loading a file).
pub fn bump_handseed(&mut self, h: Handle) {
if h.0 >= self.handseed {
self.handseed = h.0.saturating_add(1);
}
}
pub fn layer(&self, name: &str) -> Option<&Layer> {
self.layers.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
self.layers.iter_mut().find(|l| l.name.eq_ignore_ascii_case(name))
}
pub fn linetype(&self, name: &str) -> Option<&Linetype> {
self.linetypes.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
pub fn text_style(&self, name: &str) -> Option<&TextStyle> {
self.text_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
pub fn dim_style(&self, name: &str) -> Option<&DimStyle> {
self.dim_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
pub fn block(&self, name: &str) -> Option<&std::sync::Arc<Block>> {
self.blocks.get(name).or_else(|| self.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v))
}
pub fn layout(&self, name: &str) -> Option<&Layout> {
self.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// Add a layer if missing; returns whether it was created.
pub fn ensure_layer(&mut self, name: &str) -> bool {
if self.layer(name).is_some() {
return false;
}
self.layers.push(Layer::new(name));
true
}
pub fn space(&self, space: &Space) -> Option<&EntityStore> {
match space {
Space::Model => Some(&self.model),
Space::Paper(n) => self.layouts.iter().find(|l| &l.name == n).map(|l| &l.entities),
}
}
pub fn space_mut(&mut self, space: &Space) -> Option<&mut EntityStore> {
match space {
Space::Model => Some(&mut self.model),
Space::Paper(n) => self.layouts.iter_mut().find(|l| &l.name == n).map(|l| &mut l.entities),
}
}
/// Find an entity in model space or any layout.
pub fn entity(&self, h: Handle) -> Option<&std::sync::Arc<Entity>> {
self.model.get(h).or_else(|| self.layouts.iter().find_map(|l| l.entities.get(h)))
}
pub fn space_of(&self, h: Handle) -> Option<Space> {
if self.model.contains(h) {
return Some(Space::Model);
}
self.layouts.iter().find(|l| l.entities.contains(h)).map(|l| Space::Paper(l.name.clone()))
}
pub fn modify_entity<F: FnOnce(&mut Entity)>(&mut self, h: Handle, f: F) -> Result<()> {
let sp = self.space_of(h).ok_or(DocError::NoEntity(h))?;
let store = self.space_mut(&sp).ok_or(DocError::NoEntity(h))?;
if store.modify(h, f) { Ok(()) } else { Err(DocError::NoEntity(h)) }
}
pub fn remove_entity(&mut self, h: Handle) -> Option<std::sync::Arc<Entity>> {
let sp = self.space_of(h)?;
self.space_mut(&sp)?.remove(h)
}
/// Add an entity to a space with a new handle, using the given common properties.
pub fn add(&mut self, space: &Space, common: Common, kind: EntityKind) -> Result<Handle> {
let h = self.new_handle();
self.ensure_layer(&common.layer);
let store = self.space_mut(space).ok_or_else(|| DocError::Invalid(format!("no such space {space:?}")))?;
store.push(Entity { handle: h, common, kind });
Ok(h)
}
/// Effective visibility of an entity (its own flag, its layer on/thawed).
pub fn is_visible(&self, e: &Entity) -> bool {
e.common.visible && self.layer(&e.common.layer).is_none_or(Layer::visible)
}
/// Bounds of all visible entities in a space.
pub fn extents(&self, space: &Space) -> cadcraft_geom::Bounds2 {
let mut b = cadcraft_geom::Bounds2::EMPTY;
if let Some(store) = self.space(space) {
for e in store.iter() {
if self.is_visible(e) {
b = b.union(&entity_bounds(self, e, 0));
}
}
}
b
}
/// Total entity count across model and paper space.
pub fn entity_count(&self) -> usize {
self.model.len() + self.layouts.iter().map(|l| l.entities.len()).sum::<usize>()
}
/// Next unused anonymous block name with the given prefix (e.g. `*D`).
pub fn anonymous_block_name(&self, prefix: &str) -> String {
let mut i = 1usize;
loop {
let n = format!("{prefix}{i}");
if self.block(&n).is_none() || i > 1_000_000 {
return n;
}
i += 1;
}
}
}
#[cfg(test)]
mod tests;
+195
View File
@@ -0,0 +1,195 @@
//! CADCraft's own standard libraries: linetypes and hatch patterns.
//!
//! These definitions were written for CADCraft (CC0 / public domain as part of this codebase).
//! The names follow the industry-common names users expect (DASHED, CENTER, ANSI31…); the
//! dash and spacing values are our own.
use crate::{DashElement, Linetype};
/// The standard linetype library (inch-based lengths; metric drawings scale with LTSCALE).
pub fn standard_linetypes() -> Vec<Linetype> {
let s = |name: &str, desc: &str, d: &[f64]| Linetype::simple(name, desc, d);
vec![
s("BORDER", "Border __ __ . __ __ . __ __ .", &[0.5, -0.25, 0.5, -0.25, 0.0, -0.25]),
s("CENTER", "Center ____ _ ____ _ ____", &[1.25, -0.25, 0.25, -0.25]),
s("CENTER2", "Center (.5x) ___ _ ___ _", &[0.75, -0.125, 0.125, -0.125]),
s("CENTERX2", "Center (2x) ________ __ ________", &[2.5, -0.5, 0.5, -0.5]),
s("DASHDOT", "Dash dot __ . __ . __ .", &[0.5, -0.25, 0.0, -0.25]),
s("DASHDOT2", "Dash dot (.5x) _._._._.", &[0.25, -0.125, 0.0, -0.125]),
s("DASHED", "Dashed __ __ __ __", &[0.5, -0.25]),
s("DASHED2", "Dashed (.5x) _ _ _ _ _", &[0.25, -0.125]),
s("DASHEDX2", "Dashed (2x) ____ ____ ____", &[1.0, -0.5]),
s("DIVIDE", "Divide ____ . . ____ . .", &[0.5, -0.25, 0.0, -0.25, 0.0, -0.25]),
s("DOT", "Dot . . . . . . . .", &[0.0, -0.25]),
s("DOT2", "Dot (.5x) ........", &[0.0, -0.125]),
s("HIDDEN", "Hidden __ __ __ __", &[0.25, -0.125]),
s("HIDDEN2", "Hidden (.5x) _ _ _ _ _", &[0.125, -0.0625]),
s("HIDDENX2", "Hidden (2x) ____ ____ ____", &[0.5, -0.25]),
s("PHANTOM", "Phantom ______ __ __ ______", &[1.25, -0.25, 0.25, -0.25, 0.25, -0.25]),
s("PHANTOM2", "Phantom (.5x) ___ _ _ ___", &[0.625, -0.125, 0.125, -0.125, 0.125, -0.125]),
Linetype {
name: "FENCELINE1".into(),
description: "Fenceline circle ----0-----0----".into(),
pattern: vec![
DashElement::dash(0.25),
DashElement::dash(-0.1),
DashElement { text: Some("o".into()), scale: 0.1, ..DashElement::dash(-0.1) },
DashElement::dash(0.5),
],
},
s("ZIGZAG", "Zig zag /\\/\\/\\/\\/", &[0.0001, -0.2, 0.0001, -0.2]),
]
}
/// A hatch pattern line family: angle (degrees), origin, offset (shift along, spacing), dashes.
#[derive(Clone, Debug, PartialEq)]
pub struct PatternLine {
pub angle: f64,
pub origin: (f64, f64),
pub delta: (f64, f64),
pub dashes: Vec<f64>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct HatchPattern {
pub name: &'static str,
pub description: &'static str,
pub lines: Vec<PatternLine>,
}
fn pl(angle: f64, origin: (f64, f64), delta: (f64, f64), dashes: &[f64]) -> PatternLine {
PatternLine { angle, origin, delta, dashes: dashes.to_vec() }
}
/// The standard hatch pattern library.
pub fn standard_patterns() -> Vec<HatchPattern> {
vec![
HatchPattern { name: "SOLID", description: "Solid fill", lines: vec![] },
HatchPattern { name: "ANSI31", description: "Iron, brick, stone masonry", lines: vec![pl(45.0, (0.0, 0.0), (0.0, 0.125), &[])] },
HatchPattern {
name: "ANSI32",
description: "Steel",
lines: vec![pl(45.0, (0.0, 0.0), (0.0, 0.375), &[]), pl(45.0, (0.176777, 0.0), (0.0, 0.375), &[])],
},
HatchPattern {
name: "ANSI33",
description: "Bronze, brass, copper",
lines: vec![pl(45.0, (0.0, 0.0), (0.0, 0.25), &[]), pl(45.0, (0.176777, 0.0), (0.0, 0.25), &[0.125, -0.0625])],
},
HatchPattern {
name: "ANSI34",
description: "Plastic, rubber",
lines: (0..4).map(|i| pl(45.0, (0.176777 * f64::from(i) / 2.0, 0.0), (0.0, 0.75), &[])).collect(),
},
HatchPattern {
name: "ANSI35",
description: "Fire brick, refractory",
lines: vec![pl(45.0, (0.0, 0.0), (0.0, 0.25), &[]), pl(45.0, (0.176777, 0.0), (0.0, 0.25), &[0.3125, -0.0625, 0.0, -0.0625])],
},
HatchPattern {
name: "ANSI36",
description: "Marble, slate, glass",
lines: vec![pl(45.0, (0.0, 0.0), (0.21875, 0.125), &[0.3125, -0.0625, 0.0, -0.0625])],
},
HatchPattern {
name: "ANSI37",
description: "Lead, zinc, magnesium",
lines: vec![pl(45.0, (0.0, 0.0), (0.0, 0.125), &[]), pl(135.0, (0.0, 0.0), (0.0, 0.125), &[])],
},
HatchPattern {
name: "ANSI38",
description: "Aluminum",
lines: vec![pl(45.0, (0.0, 0.0), (0.0, 0.125), &[]), pl(135.0, (0.0, 0.0), (0.25, 0.125), &[0.3125, -0.1875])],
},
HatchPattern { name: "LINE", description: "Parallel horizontal lines", lines: vec![pl(0.0, (0.0, 0.0), (0.0, 0.125), &[])] },
HatchPattern {
name: "NET",
description: "Horizontal / vertical grid",
lines: vec![pl(0.0, (0.0, 0.0), (0.0, 0.125), &[]), pl(90.0, (0.0, 0.0), (0.0, 0.125), &[])],
},
HatchPattern {
name: "NET3",
description: "Network pattern 0-60-120",
lines: vec![pl(0.0, (0.0, 0.0), (0.0, 0.125), &[]), pl(60.0, (0.0, 0.0), (0.0, 0.125), &[]), pl(120.0, (0.0, 0.0), (0.0, 0.125), &[])],
},
HatchPattern { name: "DOTS", description: "A series of dots", lines: vec![pl(0.0, (0.0, 0.0), (0.03125, 0.0625), &[0.0, -0.0625])] },
HatchPattern { name: "DASH", description: "Dashed lines", lines: vec![pl(0.0, (0.0, 0.0), (0.125, 0.125), &[0.125, -0.125])] },
HatchPattern {
name: "BRICK",
description: "Brick or masonry-type surface",
lines: vec![
pl(0.0, (0.0, 0.0), (0.0, 0.25), &[]),
pl(90.0, (0.0, 0.0), (0.25, 0.25), &[0.25, -0.25]),
pl(90.0, (0.25, 0.0), (0.25, 0.25), &[-0.25, 0.25]),
],
},
HatchPattern {
name: "SQUARE",
description: "Small aligned squares",
lines: vec![pl(0.0, (0.0, 0.0), (0.0, 0.125), &[0.125, -0.125]), pl(90.0, (0.0, 0.0), (0.0, 0.125), &[0.125, -0.125])],
},
HatchPattern {
name: "CROSS",
description: "A series of crosses",
lines: vec![pl(0.0, (0.0, 0.0), (0.25, 0.25), &[0.125, -0.375]), pl(90.0, (0.0625, -0.0625), (0.25, 0.25), &[0.125, -0.375])],
},
HatchPattern {
name: "EARTH",
description: "Earth or ground (subterranean)",
lines: vec![
pl(0.0, (0.0, 0.0), (0.25, 0.25), &[0.25, -0.25]),
pl(0.0, (0.0, 0.09375), (0.25, 0.25), &[0.25, -0.25]),
pl(0.0, (0.0, 0.1875), (0.25, 0.25), &[0.25, -0.25]),
pl(90.0, (0.03125, 0.21875), (0.25, 0.25), &[0.25, -0.25]),
pl(90.0, (0.125, 0.21875), (0.25, 0.25), &[0.25, -0.25]),
pl(90.0, (0.21875, 0.21875), (0.25, 0.25), &[0.25, -0.25]),
],
},
HatchPattern {
name: "GRASS",
description: "Grass area",
lines: vec![
pl(90.0, (0.0, 0.0), (std::f64::consts::FRAC_1_SQRT_2, std::f64::consts::FRAC_1_SQRT_2), &[0.1875, -1.226]),
pl(45.0, (0.0, 0.0), (0.0, 1.0), &[0.1875, -0.8125]),
pl(135.0, (0.0, 0.0), (0.0, 1.0), &[0.1875, -0.8125]),
],
},
HatchPattern {
name: "HONEY",
description: "Honeycomb pattern",
lines: vec![
pl(0.0, (0.0, 0.0), (0.1875, 0.108253), &[0.125, -0.25]),
pl(120.0, (0.0, 0.0), (0.1875, 0.108253), &[0.125, -0.25]),
pl(60.0, (0.125, 0.0), (0.1875, 0.108253), &[0.125, -0.25]),
],
},
HatchPattern {
name: "ZIGZAG",
description: "Staircase effect",
lines: vec![pl(0.0, (0.0, 0.0), (0.125, 0.125), &[0.125, -0.125]), pl(90.0, (0.125, 0.0), (0.125, 0.125), &[0.125, -0.125])],
},
HatchPattern {
name: "AR-CONC",
description: "Random dot and stone pattern",
lines: vec![
pl(50.0, (0.0, 0.0), (0.4, 0.25), &[0.15, -0.6]),
pl(355.0, (0.0, 0.0), (0.27, 0.3), &[0.12, -0.5]),
pl(100.0, (0.12, 0.05), (0.35, 0.33), &[0.1, -0.55]),
pl(0.0, (0.07, 0.02), (0.21, 0.17), &[0.0, -0.4]),
],
},
HatchPattern {
name: "AR-SAND",
description: "Random dot pattern",
lines: vec![
pl(37.5, (0.0, 0.0), (0.112, 0.0912), &[0.0, -0.22, 0.0, -0.14]),
pl(7.5, (0.0, 0.0), (0.157, 0.0724), &[0.0, -0.19, 0.0, -0.31]),
pl(-32.5, (0.0, 0.0), (0.091, 0.1312), &[0.0, -0.27, 0.0, -0.11]),
],
},
]
}
pub fn pattern(name: &str) -> Option<HatchPattern> {
standard_patterns().into_iter().find(|p| p.name.eq_ignore_ascii_case(name))
}
+248
View File
@@ -0,0 +1,248 @@
//! A copy-on-write entity store with draw order.
//!
//! Entities live in chunks (`Arc<Vec<Arc<Entity>>>`) in draw order, and a sharded handle index
//! maps each handle to the stable id of its chunk. Cloning a store (an undo snapshot) copies
//! only the chunk and shard pointers; an edit copies one chunk and one shard.
use std::collections::HashMap;
use std::sync::Arc;
use crate::{Entity, Handle};
const CHUNK_MAX: usize = 1024;
const SHARDS: usize = 64;
#[derive(Clone, Debug, Default)]
struct Chunk {
id: u32,
items: Vec<Arc<Entity>>,
}
#[derive(Clone, Debug)]
pub struct EntityStore {
chunks: Vec<Arc<Chunk>>,
shards: Vec<Arc<HashMap<Handle, u32>>>,
len: usize,
next_chunk: u32,
}
impl Default for EntityStore {
fn default() -> Self {
EntityStore { chunks: Vec::new(), shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(), len: 0, next_chunk: 0 }
}
}
impl PartialEq for EntityStore {
fn eq(&self, other: &Self) -> bool {
self.len == other.len && self.iter().zip(other.iter()).all(|(a, b)| a == b)
}
}
fn shard_of(h: Handle) -> usize {
// Fibonacci hashing spreads sequential handles across shards.
((h.0.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 58) as usize) % SHARDS
}
impl EntityStore {
pub fn new() -> Self {
Self::default()
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Iterate in draw order.
pub fn iter(&self) -> impl Iterator<Item = &Arc<Entity>> + '_ {
self.chunks.iter().flat_map(|c| c.items.iter())
}
pub fn handles(&self) -> Vec<Handle> {
self.iter().map(|e| e.handle).collect()
}
pub fn contains(&self, h: Handle) -> bool {
self.chunk_id(h).is_some()
}
fn chunk_id(&self, h: Handle) -> Option<u32> {
self.shards.get(shard_of(h)).and_then(|s| s.get(&h).copied())
}
fn chunk_pos(&self, id: u32) -> Option<usize> {
self.chunks.iter().position(|c| c.id == id)
}
pub fn get(&self, h: Handle) -> Option<&Arc<Entity>> {
let pos = self.chunk_pos(self.chunk_id(h)?)?;
self.chunks.get(pos)?.items.iter().find(|e| e.handle == h)
}
fn set_index(&mut self, h: Handle, chunk: Option<u32>) {
if let Some(shard) = self.shards.get_mut(shard_of(h)) {
let m = Arc::make_mut(shard);
match chunk {
Some(c) => {
m.insert(h, c);
}
None => {
m.remove(&h);
}
}
}
}
fn new_chunk(&mut self) -> Arc<Chunk> {
let id = self.next_chunk;
self.next_chunk = self.next_chunk.wrapping_add(1);
Arc::new(Chunk { id, items: Vec::with_capacity(64) })
}
/// Append on top of the draw order. Replaces an entity with the same handle in place.
pub fn push(&mut self, e: Entity) {
if self.contains(e.handle) {
self.replace(e);
return;
}
let needs_new = self.chunks.last().is_none_or(|c| c.items.len() >= CHUNK_MAX);
if needs_new {
let c = self.new_chunk();
self.chunks.push(c);
}
let h = e.handle;
let Some(last) = self.chunks.last_mut() else { return };
let chunk = Arc::make_mut(last);
chunk.items.push(Arc::new(e));
let id = chunk.id;
self.set_index(h, Some(id));
self.len += 1;
}
/// Insert at the bottom of the draw order.
pub fn push_front(&mut self, e: Entity) {
if self.contains(e.handle) {
self.replace(e);
return;
}
let needs_new = self.chunks.first().is_none_or(|c| c.items.len() >= CHUNK_MAX);
if needs_new {
let c = self.new_chunk();
self.chunks.insert(0, c);
}
let h = e.handle;
let Some(first) = self.chunks.first_mut() else { return };
let chunk = Arc::make_mut(first);
chunk.items.insert(0, Arc::new(e));
let id = chunk.id;
self.set_index(h, Some(id));
self.len += 1;
}
/// Replace the entity with the same handle, keeping its draw position. Returns false if absent.
pub fn replace(&mut self, e: Entity) -> bool {
let Some(id) = self.chunk_id(e.handle) else { return false };
let Some(pos) = self.chunk_pos(id) else { return false };
let Some(c) = self.chunks.get_mut(pos) else { return false };
let chunk = Arc::make_mut(c);
if let Some(slot) = chunk.items.iter_mut().find(|x| x.handle == e.handle) {
*slot = Arc::new(e);
true
} else {
false
}
}
pub fn remove(&mut self, h: Handle) -> Option<Arc<Entity>> {
let id = self.chunk_id(h)?;
let pos = self.chunk_pos(id)?;
let c = self.chunks.get_mut(pos)?;
let chunk = Arc::make_mut(c);
let i = chunk.items.iter().position(|x| x.handle == h)?;
let e = chunk.items.remove(i);
let empty = chunk.items.is_empty();
if empty {
self.chunks.remove(pos);
}
self.set_index(h, None);
self.len = self.len.saturating_sub(1);
Some(e)
}
/// Modify an entity in place through a closure (copy-on-write).
pub fn modify<F: FnOnce(&mut Entity)>(&mut self, h: Handle, f: F) -> bool {
let Some(id) = self.chunk_id(h) else { return false };
let Some(pos) = self.chunk_pos(id) else { return false };
let Some(c) = self.chunks.get_mut(pos) else { return false };
let chunk = Arc::make_mut(c);
match chunk.items.iter_mut().find(|x| x.handle == h) {
Some(slot) => {
f(Arc::make_mut(slot));
true
}
None => false,
}
}
pub fn bring_to_front(&mut self, h: Handle) -> bool {
match self.remove(h) {
Some(e) => {
self.push(Arc::unwrap_or_clone(e));
true
}
None => false,
}
}
pub fn send_to_back(&mut self, h: Handle) -> bool {
match self.remove(h) {
Some(e) => {
self.push_front(Arc::unwrap_or_clone(e));
true
}
None => false,
}
}
/// The last entity in draw order (AutoCAD's "Last" selection).
pub fn last(&self) -> Option<&Arc<Entity>> {
self.chunks.last().and_then(|c| c.items.last())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{EntityKind, Point};
use cadcraft_geom::Vec2;
fn ent(h: u64) -> Entity {
Entity::new(Handle(h), EntityKind::Point(Point { p: Vec2::new(h as f64, 0.0).to3(0.0), angle: 0.0 }))
}
#[test]
fn push_get_remove() {
let mut s = EntityStore::new();
for h in 1..=3000 {
s.push(ent(h));
}
assert_eq!(s.len(), 3000);
assert!(s.get(Handle(1500)).is_some());
assert!(s.remove(Handle(1500)).is_some());
assert!(s.get(Handle(1500)).is_none());
assert_eq!(s.len(), 2999);
assert_eq!(s.iter().count(), 2999);
}
#[test]
fn snapshots_are_independent() {
let mut s = EntityStore::new();
for h in 1..=10 {
s.push(ent(h));
}
let snap = s.clone();
s.remove(Handle(3));
s.modify(Handle(4), |e| e.common.layer = "X".into());
assert!(snap.get(Handle(3)).is_some());
assert_eq!(snap.get(Handle(4)).map(|e| e.common.layer.as_str()), Some("0"));
assert_eq!(s.get(Handle(4)).map(|e| e.common.layer.as_str()), Some("X"));
}
#[test]
fn draw_order_moves() {
let mut s = EntityStore::new();
for h in 1..=5 {
s.push(ent(h));
}
s.bring_to_front(Handle(1));
assert_eq!(s.last().map(|e| e.handle), Some(Handle(1)));
s.send_to_back(Handle(5));
assert_eq!(s.iter().next().map(|e| e.handle), Some(Handle(5)));
assert_eq!(s.len(), 5);
}
}
+412
View File
@@ -0,0 +1,412 @@
//! Symbol tables and non-graphical objects: layers, linetypes, text and dimension styles,
//! blocks, layouts, named views and UCSs.
use std::sync::Arc;
use cadcraft_color::Color;
use cadcraft_geom::{Vec2, Vec3};
use serde::{Deserialize, Serialize};
use crate::{EntityStore, Lineweight};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Layer {
pub name: String,
/// Always an index or true colour (never ByLayer/ByBlock).
pub color: Color,
pub linetype: String,
pub lineweight: Lineweight,
pub on: bool,
pub frozen: bool,
pub locked: bool,
pub plot: bool,
/// 0..=90 percent.
pub transparency: u8,
pub description: String,
pub plot_style: String,
}
impl Default for Layer {
fn default() -> Self {
Layer {
name: "0".into(),
color: Color::Index(7),
linetype: "Continuous".into(),
lineweight: Lineweight::Default,
on: true,
frozen: false,
locked: false,
plot: true,
transparency: 0,
description: String::new(),
plot_style: "Normal".into(),
}
}
}
impl Layer {
pub fn new(name: &str) -> Self {
Layer { name: name.into(), ..Default::default() }
}
pub fn visible(&self) -> bool {
self.on && !self.frozen
}
}
/// A linetype element: dash (> 0), gap (< 0) or dot (0); optional embedded text/shape.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DashElement {
pub length: f64,
#[serde(default)]
pub text: Option<String>,
#[serde(default)]
pub shape: Option<u16>,
#[serde(default)]
pub style: Option<String>,
#[serde(default)]
pub scale: f64,
#[serde(default)]
pub rotation: f64,
#[serde(default)]
pub offset: Vec2,
}
impl DashElement {
pub fn dash(length: f64) -> Self {
DashElement { length, text: None, shape: None, style: None, scale: 1.0, rotation: 0.0, offset: Vec2::ZERO }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Linetype {
pub name: String,
pub description: String,
pub pattern: Vec<DashElement>,
}
impl Linetype {
pub fn continuous() -> Self {
Linetype { name: "Continuous".into(), description: "Solid line".into(), pattern: Vec::new() }
}
pub fn simple(name: &str, description: &str, dashes: &[f64]) -> Self {
Linetype { name: name.into(), description: description.into(), pattern: dashes.iter().map(|d| DashElement::dash(*d)).collect() }
}
pub fn pattern_length(&self) -> f64 {
self.pattern.iter().map(|d| d.length.abs()).sum()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct TextStyle {
pub name: String,
/// Font file or family name (TTF family or a stroke-font name).
pub font: String,
pub big_font: String,
/// 0 = not fixed.
pub height: f64,
pub width_factor: f64,
pub oblique: f64,
pub backwards: bool,
pub upside_down: bool,
pub vertical: bool,
pub annotative: bool,
}
impl Default for TextStyle {
fn default() -> Self {
TextStyle {
name: "Standard".into(),
font: "CADCraft Stroke".into(),
big_font: String::new(),
height: 0.0,
width_factor: 1.0,
oblique: 0.0,
backwards: false,
upside_down: false,
vertical: false,
annotative: false,
}
}
}
/// Dimension style variables (the subset that affects geometry and text).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct DimStyle {
pub name: String,
/// DIMSCALE overall scale.
pub scale: f64,
/// DIMASZ arrow size.
pub arrow_size: f64,
/// DIMEXO extension line offset from origin.
pub ext_offset: f64,
/// DIMEXE extension beyond dimension line.
pub ext_extend: f64,
/// DIMTXT text height.
pub text_height: f64,
/// DIMGAP gap around text.
pub text_gap: f64,
/// DIMDEC decimal places.
pub decimals: u8,
/// DIMADEC angular decimals.
pub angular_decimals: u8,
/// DIMLFAC linear scale factor.
pub linear_factor: f64,
/// DIMTAD text above line (0 centred, 1 above).
pub text_above: u8,
/// DIMTIH / DIMTOH text inside/outside horizontal.
pub text_inside_horizontal: bool,
pub text_outside_horizontal: bool,
/// DIMBLK arrowhead name ("" = closed filled).
pub arrow_block: String,
/// DIMTSZ tick size (> 0 replaces arrows with ticks).
pub tick_size: f64,
/// DIMCLRD / DIMCLRE / DIMCLRT.
pub dim_line_color: Color,
pub ext_line_color: Color,
pub text_color: Color,
pub text_style: String,
/// DIMPOST prefix/suffix "<>" template.
pub post: String,
/// DIMCEN centre mark size (negative = lines).
pub center_mark: f64,
/// DIMZIN zero suppression bits.
pub zero_suppression: u8,
/// DIMLUNIT: 1 sci, 2 dec, 3 eng, 4 arch, 5 frac, 6 windows.
pub linear_unit: u8,
/// DIMTOL / DIMLIM, DIMTP/DIMTM.
pub tolerance: bool,
pub tol_plus: f64,
pub tol_minus: f64,
/// DIMDLI baseline spacing.
pub baseline_spacing: f64,
pub annotative: bool,
}
impl Default for DimStyle {
fn default() -> Self {
DimStyle {
name: "Standard".into(),
scale: 1.0,
arrow_size: 0.18,
ext_offset: 0.0625,
ext_extend: 0.18,
text_height: 0.18,
text_gap: 0.09,
decimals: 4,
angular_decimals: 0,
linear_factor: 1.0,
text_above: 0,
text_inside_horizontal: true,
text_outside_horizontal: true,
arrow_block: String::new(),
tick_size: 0.0,
dim_line_color: Color::ByBlock,
ext_line_color: Color::ByBlock,
text_color: Color::ByBlock,
text_style: "Standard".into(),
post: String::new(),
center_mark: 0.09,
zero_suppression: 0,
linear_unit: 2,
tolerance: false,
tol_plus: 0.0,
tol_minus: 0.0,
baseline_spacing: 0.38,
annotative: false,
}
}
}
impl DimStyle {
/// The ISO-25 style for metric drawings.
pub fn iso25() -> Self {
DimStyle {
name: "ISO-25".into(),
arrow_size: 2.5,
ext_offset: 0.625,
ext_extend: 1.25,
text_height: 2.5,
text_gap: 0.625,
decimals: 2,
text_above: 1,
text_inside_horizontal: false,
text_outside_horizontal: false,
center_mark: 2.5,
zero_suppression: 8,
baseline_spacing: 3.75,
..Default::default()
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct MLeaderStyle {
pub name: String,
pub arrow_size: f64,
pub text_height: f64,
pub landing_gap: f64,
pub dogleg: f64,
pub text_style: String,
}
impl Default for MLeaderStyle {
fn default() -> Self {
MLeaderStyle { name: "Standard".into(), arrow_size: 0.18, text_height: 0.18, landing_gap: 0.09, dogleg: 0.36, text_style: "Standard".into() }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct TableStyle {
pub name: String,
pub text_height: f64,
pub margin: f64,
pub title: bool,
pub header: bool,
}
impl Default for TableStyle {
fn default() -> Self {
TableStyle { name: "Standard".into(), text_height: 0.18, margin: 0.06, title: true, header: true }
}
}
/// A block definition.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Block {
pub name: String,
pub base: Vec3,
#[serde(skip)]
pub entities: EntityStore,
#[serde(default)]
pub description: String,
/// Anonymous (`*D12`, `*U3`…) blocks are generated geometry.
#[serde(default)]
pub anonymous: bool,
#[serde(default)]
pub xref_path: Option<String>,
#[serde(default)]
pub explodable: bool,
#[serde(default)]
pub units: u8,
}
impl Block {
pub fn new(name: &str) -> Self {
Block {
name: name.into(),
base: Vec3::ZERO,
entities: EntityStore::new(),
description: String::new(),
anonymous: name.starts_with('*'),
xref_path: None,
explodable: true,
units: 0,
}
}
}
/// Paper size and plot settings for a layout (page setup).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PageSetup {
pub device: String,
pub paper: String,
/// Paper size in millimetres (portrait width/height before rotation).
pub width_mm: f64,
pub height_mm: f64,
pub margins_mm: [f64; 4],
pub landscape: bool,
/// "layout" | "extents" | "display" | "window" | "limits".
pub plot_area: String,
pub scale_to_fit: bool,
/// Paper units per drawing unit.
pub scale: f64,
pub plot_style_table: String,
pub center: bool,
pub lineweights: bool,
}
impl Default for PageSetup {
fn default() -> Self {
PageSetup {
device: "None".into(),
paper: "ANSI A (8.50 x 11.00 Inches)".into(),
width_mm: 215.9,
height_mm: 279.4,
margins_mm: [6.35, 6.35, 6.35, 6.35],
landscape: true,
plot_area: "layout".into(),
scale_to_fit: false,
scale: 1.0,
plot_style_table: String::new(),
center: false,
lineweights: true,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Layout {
pub name: String,
pub tab_order: u32,
pub page: PageSetup,
#[serde(skip)]
pub entities: EntityStore,
/// Saved paper-space view (centre, height).
#[serde(default)]
pub view: Option<(Vec2, f64)>,
}
impl Layout {
pub fn new(name: &str, tab_order: u32) -> Self {
Layout { name: name.into(), tab_order, page: PageSetup::default(), entities: EntityStore::new(), view: None }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NamedView {
pub name: String,
pub center: Vec2,
pub height: f64,
pub width: f64,
#[serde(default)]
pub layer_state: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Ucs {
pub name: String,
pub origin: Vec3,
pub x_axis: Vec3,
pub y_axis: Vec3,
}
/// A saved layer state (LAYERSTATE).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LayerState {
pub name: String,
pub layers: Vec<Layer>,
}
/// A named group of entities (GROUP).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Group {
pub name: String,
pub description: String,
pub selectable: bool,
pub members: Vec<crate::Handle>,
}
/// Shared ownership helper: blocks are cloned on write.
pub type BlockRef = Arc<Block>;
+108
View File
@@ -0,0 +1,108 @@
use crate::*;
use cadcraft_geom::{Mat3, Vec2, Vec3};
fn line(a: (f64, f64), b: (f64, f64)) -> EntityKind {
EntityKind::Line(Line { a: Vec3::new(a.0, a.1, 0.0), b: Vec3::new(b.0, b.1, 0.0) })
}
#[test]
fn new_drawing_has_standard_tables() {
let d = Drawing::new_imperial();
assert!(d.layer("0").is_some());
assert!(d.linetype("continuous").is_some());
assert!(d.text_style("Standard").is_some());
assert_eq!(d.header.f64("TEXTSIZE", 0.0), 0.2);
let m = Drawing::new_metric();
assert!(m.dim_style("ISO-25").is_some());
}
#[test]
fn add_and_extents() {
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), line((0.0, 0.0), (10.0, 5.0))).unwrap();
d.add(&Space::Model, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(20.0, 0.0, 0.0), radius: 2.0 })).unwrap();
let b = d.extents(&Space::Model);
assert_eq!(b.min, Vec2::new(0.0, -2.0));
assert_eq!(b.max, Vec2::new(22.0, 5.0));
}
#[test]
fn hidden_layers_excluded_from_extents() {
let mut d = Drawing::new_imperial();
let c = Common { layer: "Hidden".into(), ..Default::default() };
d.add(&Space::Model, c, line((100.0, 100.0), (200.0, 200.0))).unwrap();
d.add(&Space::Model, Common::default(), line((0.0, 0.0), (1.0, 1.0))).unwrap();
d.layer_mut("Hidden").unwrap().on = false;
assert_eq!(d.extents(&Space::Model).max, Vec2::new(1.0, 1.0));
}
#[test]
fn transform_arc_mirror_keeps_shape() {
let mut k = EntityKind::Arc(Arc { center: Vec3::ZERO, radius: 1.0, start: 0.0, end: std::f64::consts::FRAC_PI_2 });
k.transform(&Mat3::mirror(Vec2::ZERO, Vec2::Y));
if let EntityKind::Arc(a) = k {
let g = cadcraft_geom::Arc::new(a.center.xy(), a.radius, a.start, a.end);
assert!(g.mid_point().near(Vec2::from_angle(3.0 * std::f64::consts::FRAC_PI_4), 1e-9));
} else {
panic!()
}
}
#[test]
fn insert_bounds_with_cyclic_block_terminate() {
let mut d = Drawing::new_imperial();
let mut b = Block::new("A");
b.entities.push(Entity::new(
Handle(1),
EntityKind::Insert(Insert {
block: "A".into(),
insert: Vec3::ZERO,
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: vec![],
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
}),
));
b.entities.push(Entity::new(Handle(2), line((0.0, 0.0), (1.0, 1.0))));
d.blocks.insert("A".into(), std::sync::Arc::new(b));
let h = d
.add(
&Space::Model,
Common::default(),
EntityKind::Insert(Insert {
block: "A".into(),
insert: Vec3::new(5.0, 5.0, 0.0),
scale: Vec3::new(2.0, 2.0, 1.0),
rotation: 0.0,
attribs: vec![],
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
}),
)
.unwrap();
let e = d.entity(h).unwrap().clone();
let bb = entity_bounds(&d, &e, 0);
assert_eq!(bb.max, Vec2::new(7.0, 7.0));
}
#[test]
fn entity_serde_roundtrip() {
let e = Entity::new(Handle(7), line((1.0, 2.0), (3.0, 4.0)));
let s = serde_json::to_string(&e).unwrap();
let back: Entity = serde_json::from_str(&s).unwrap();
assert_eq!(e, back);
}
#[test]
fn paper_space_entities() {
let mut d = Drawing::new_imperial();
let h = d.add(&Space::Paper("Layout1".into()), Common::default(), line((0.0, 0.0), (1.0, 0.0))).unwrap();
assert_eq!(d.space_of(h), Some(Space::Paper("Layout1".into())));
assert!(d.remove_entity(h).is_some());
assert_eq!(d.entity_count(), 0);
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "cadcraft-dxf"
description = "Standalone DXF tag reader/writer (ASCII and binary), from the published DXF reference"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
thiserror = { workspace = true }
+458
View File
@@ -0,0 +1,458 @@
//! A standalone DXF tag reader and writer.
//!
//! DXF is a sequence of (group code, value) pairs. This crate parses ASCII and binary DXF into a
//! flat list of [`Tag`]s, splits them into sections and entities, and writes tags back. Mapping
//! tags to a drawing model is left to the caller. Written from Autodesk's published DXF
//! Reference; depends on nothing else in the workspace.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
use std::fmt::Write as _;
#[derive(Debug, thiserror::Error)]
pub enum DxfError {
#[error("not a DXF file")]
NotDxf,
#[error("line {line}: bad group code `{text}`")]
BadCode { line: usize, text: String },
#[error("unexpected end of file")]
Eof,
#[error("file too large")]
TooLarge,
}
pub type Result<T> = std::result::Result<T, DxfError>;
/// A typed group value.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
Str(String),
Real(f64),
Int(i64),
Bool(bool),
/// Binary chunk (310–319, 1004) as hex text.
Hex(String),
}
impl Value {
pub fn as_str(&self) -> String {
match self {
Value::Str(s) | Value::Hex(s) => s.clone(),
Value::Real(r) => format_real(*r),
Value::Int(i) => i.to_string(),
Value::Bool(b) => i64::from(*b).to_string(),
}
}
pub fn as_f64(&self) -> f64 {
match self {
Value::Real(r) if r.is_finite() => *r,
Value::Int(i) => *i as f64,
Value::Str(s) => s.trim().parse::<f64>().ok().filter(|v| v.is_finite()).unwrap_or(0.0),
Value::Bool(b) => f64::from(u8::from(*b)),
_ => 0.0,
}
}
pub fn as_i64(&self) -> i64 {
match self {
Value::Int(i) => *i,
Value::Real(r) if r.is_finite() => *r as i64,
Value::Str(s) => s.trim().parse::<i64>().unwrap_or_else(|_| s.trim().parse::<f64>().map(|f| f as i64).unwrap_or(0)),
Value::Bool(b) => i64::from(*b),
_ => 0,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Tag {
pub code: i32,
pub value: Value,
}
impl Tag {
pub fn new(code: i32, value: Value) -> Self {
Tag { code, value }
}
pub fn s(code: i32, v: impl Into<String>) -> Self {
Tag { code, value: Value::Str(v.into()) }
}
pub fn f(code: i32, v: f64) -> Self {
Tag { code, value: Value::Real(if v.is_finite() { v } else { 0.0 }) }
}
pub fn i(code: i32, v: i64) -> Self {
Tag { code, value: Value::Int(v) }
}
pub fn str(&self) -> String {
self.value.as_str()
}
pub fn f64(&self) -> f64 {
self.value.as_f64()
}
pub fn i64(&self) -> i64 {
self.value.as_i64()
}
}
/// The value type for a group code (DXF Reference, "Group Code Value Types").
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Str,
Real,
Int16,
Int32,
Int64,
Bool,
Hex,
}
pub fn kind_of(code: i32) -> Kind {
match code {
0..=9 => Kind::Str,
10..=59 => Kind::Real,
60..=79 => Kind::Int16,
90..=99 => Kind::Int32,
100..=109 => Kind::Str,
110..=149 => Kind::Real,
160..=169 => Kind::Int64,
170..=179 => Kind::Int16,
210..=239 => Kind::Real,
270..=289 => Kind::Int16,
290..=299 => Kind::Bool,
300..=309 => Kind::Str,
310..=319 => Kind::Hex,
320..=369 => Kind::Str,
370..=389 => Kind::Int16,
390..=399 => Kind::Str,
400..=409 => Kind::Int16,
410..=419 => Kind::Str,
420..=429 => Kind::Int32,
430..=439 => Kind::Str,
440..=449 => Kind::Int32,
450..=459 => Kind::Int32,
460..=469 => Kind::Real,
470..=479 => Kind::Str,
480..=481 => Kind::Str,
999 => Kind::Str,
1000..=1003 => Kind::Str,
1004 => Kind::Hex,
1005..=1009 => Kind::Str,
1010..=1059 => Kind::Real,
1060..=1070 => Kind::Int16,
1071 => Kind::Int32,
_ => Kind::Str,
}
}
fn typed(code: i32, text: &str) -> Value {
let t = text.trim();
match kind_of(code) {
Kind::Real => t.parse::<f64>().ok().filter(|v| v.is_finite()).map(Value::Real).unwrap_or(Value::Real(0.0)),
Kind::Int16 | Kind::Int32 | Kind::Int64 => {
t.parse::<i64>().map(Value::Int).unwrap_or_else(|_| Value::Int(t.parse::<f64>().map(|f| f as i64).unwrap_or(0)))
}
Kind::Bool => Value::Bool(t.parse::<i64>().unwrap_or(0) != 0),
Kind::Hex => Value::Hex(t.to_string()),
Kind::Str => Value::Str(text.trim_end_matches(['\r', '\n']).to_string()),
}
}
const BINARY_SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\0";
const MAX_TAGS: usize = 50_000_000;
/// Decode bytes as text: UTF-8 when valid, otherwise Latin-1 (old ANSI_1252 files).
fn decode_text(b: &[u8]) -> String {
match std::str::from_utf8(b) {
Ok(s) => s.to_string(),
Err(_) => b.iter().map(|&c| char::from(c)).collect(),
}
}
/// Parse a DXF file (ASCII or binary).
pub fn parse(bytes: &[u8]) -> Result<Vec<Tag>> {
if bytes.starts_with(BINARY_SENTINEL) {
return parse_binary(bytes.get(BINARY_SENTINEL.len()..).unwrap_or(&[]));
}
parse_ascii(&decode_text(bytes))
}
/// Unescape `\U+XXXX` sequences used by DXF R2007+ for non-ASCII characters.
fn unescape_unicode(s: &str) -> String {
if !s.contains("\\U+") {
return s.to_string();
}
let mut out = String::with_capacity(s.len());
let chars: Vec<char> = s.chars().collect();
let mut i = 0;
while let Some(&c) = chars.get(i) {
if c == '\\' && chars.get(i + 1) == Some(&'U') && chars.get(i + 2) == Some(&'+') {
let hex: String = chars.iter().skip(i + 3).take(4).collect();
if hex.len() == 4
&& let Some(ch) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)
{
out.push(ch);
i += 7;
continue;
}
}
out.push(c);
i += 1;
}
out
}
#[allow(clippy::while_let_loop)]
pub fn parse_ascii(text: &str) -> Result<Vec<Tag>> {
let mut tags = Vec::new();
let mut lines = text.lines().enumerate();
loop {
let Some((ln, code_line)) = lines.next() else { break };
let ct = code_line.trim();
if ct.is_empty() {
continue;
}
let code: i32 = ct.parse().map_err(|_| DxfError::BadCode { line: ln + 1, text: ct.chars().take(40).collect() })?;
let Some((_, val)) = lines.next() else { return Err(DxfError::Eof) };
let v = typed(code, val);
let v = match v {
Value::Str(s) => Value::Str(unescape_unicode(&s)),
o => o,
};
tags.push(Tag { code, value: v });
if tags.len() > MAX_TAGS {
return Err(DxfError::TooLarge);
}
if code == 0 && tags.last().is_some_and(|t| t.str() == "EOF") {
break;
}
}
if tags.is_empty() {
return Err(DxfError::NotDxf);
}
Ok(tags)
}
struct Cur<'a> {
b: &'a [u8],
p: usize,
}
impl Cur<'_> {
fn take(&mut self, n: usize) -> Result<&[u8]> {
let end = self.p.checked_add(n).ok_or(DxfError::Eof)?;
let s = self.b.get(self.p..end).ok_or(DxfError::Eof)?;
self.p = end;
Ok(s)
}
fn u8(&mut self) -> Result<u8> {
Ok(*self.take(1)?.first().ok_or(DxfError::Eof)?)
}
fn i16(&mut self) -> Result<i16> {
let s = self.take(2)?;
Ok(i16::from_le_bytes([s[0], s[1]]))
}
fn i32(&mut self) -> Result<i32> {
let s = self.take(4)?;
Ok(i32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
fn i64(&mut self) -> Result<i64> {
let s = self.take(8)?;
let mut a = [0u8; 8];
a.copy_from_slice(s);
Ok(i64::from_le_bytes(a))
}
fn f64(&mut self) -> Result<f64> {
let s = self.take(8)?;
let mut a = [0u8; 8];
a.copy_from_slice(s);
Ok(f64::from_le_bytes(a))
}
fn cstr(&mut self) -> Result<String> {
let start = self.p;
while self.p < self.b.len() && self.b.get(self.p) != Some(&0) {
self.p += 1;
}
let s = decode_text(self.b.get(start..self.p).unwrap_or(&[]));
if self.p >= self.b.len() {
return Err(DxfError::Eof);
}
self.p += 1;
Ok(s)
}
}
/// Binary DXF (R13+: 2-byte group codes).
pub fn parse_binary(b: &[u8]) -> Result<Vec<Tag>> {
let mut c = Cur { b, p: 0 };
let mut tags = Vec::new();
while c.p < b.len() {
let mut code = i32::from(c.i16()?);
if code == 255 {
code = i32::from(c.i16()?);
}
let v = match kind_of(code) {
Kind::Str => Value::Str(c.cstr()?),
Kind::Real => Value::Real(c.f64()?),
Kind::Int16 => Value::Int(i64::from(c.i16()?)),
Kind::Int32 => Value::Int(i64::from(c.i32()?)),
Kind::Int64 => Value::Int(c.i64()?),
Kind::Bool => Value::Bool(c.u8()? != 0),
Kind::Hex => {
let n = usize::from(c.u8()?);
let bytes = c.take(n)?;
let mut s = String::with_capacity(n * 2);
for x in bytes {
let _ = write!(s, "{x:02X}");
}
Value::Hex(s)
}
};
let eof = code == 0 && matches!(&v, Value::Str(s) if s == "EOF");
tags.push(Tag { code, value: v });
if tags.len() > MAX_TAGS {
return Err(DxfError::TooLarge);
}
if eof {
break;
}
}
Ok(tags)
}
/// Format a real the way DXF writers usually do (shortest round-trip, with a decimal point).
pub fn format_real(v: f64) -> String {
if !v.is_finite() {
return "0.0".into();
}
let s = format!("{v}");
if s.contains('.') || s.contains('e') || s.contains("inf") || s.contains("NaN") { s } else { format!("{s}.0") }
}
/// Write tags as ASCII DXF (CRLF line ends, codes right-aligned to 3 as is conventional).
pub fn write_ascii(tags: &[Tag]) -> String {
let mut out = String::with_capacity(tags.len() * 16);
for t in tags {
let _ = write!(out, "{:>3}\r\n", t.code);
let v = match &t.value {
Value::Str(s) => s.replace(['\r', '\n'], " "),
Value::Real(r) => format_real(*r),
Value::Int(i) => i.to_string(),
Value::Bool(b) => i64::from(*b).to_string(),
Value::Hex(h) => h.clone(),
};
out.push_str(&v);
out.push_str("\r\n");
}
out
}
/// A section: `0 SECTION / 2 NAME ... 0 ENDSEC`.
#[derive(Clone, Debug, Default)]
pub struct Section {
pub name: String,
pub tags: Vec<Tag>,
}
/// Split a tag stream into sections.
pub fn sections(tags: &[Tag]) -> Vec<Section> {
let mut out = Vec::new();
let mut i = 0;
while i < tags.len() {
let is_sec = tags.get(i).is_some_and(|t| t.code == 0 && t.str() == "SECTION");
if is_sec {
let name = tags.get(i + 1).filter(|t| t.code == 2).map(Tag::str).unwrap_or_default();
let start = i + 2;
let mut j = start;
while j < tags.len() && !(tags.get(j).is_some_and(|t| t.code == 0 && t.str() == "ENDSEC")) {
j += 1;
}
out.push(Section { name, tags: tags.get(start..j).unwrap_or(&[]).to_vec() });
i = j + 1;
} else {
i += 1;
}
}
out
}
/// Split a run of tags into records starting at each code-0 tag: (type, tags after the 0).
pub fn records(tags: &[Tag]) -> Vec<(String, Vec<Tag>)> {
let mut out: Vec<(String, Vec<Tag>)> = Vec::new();
for t in tags {
if t.code == 0 {
out.push((t.str(), Vec::new()));
} else if let Some(last) = out.last_mut() {
last.1.push(t.clone());
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ascii_roundtrip() {
let tags = vec![
Tag::s(0, "SECTION"),
Tag::s(2, "ENTITIES"),
Tag::s(0, "LINE"),
Tag::s(8, "0"),
Tag::f(10, 1.5),
Tag::f(20, 2.0),
Tag::i(62, 1),
Tag::s(0, "ENDSEC"),
Tag::s(0, "EOF"),
];
let text = write_ascii(&tags);
let back = parse(text.as_bytes()).unwrap();
assert_eq!(back, tags);
let secs = sections(&back);
assert_eq!(secs.len(), 1);
assert_eq!(secs[0].name, "ENTITIES");
let recs = records(&secs[0].tags);
assert_eq!(recs[0].0, "LINE");
assert_eq!(recs[0].1.len(), 4);
}
#[test]
fn binary_parse() {
let mut b = BINARY_SENTINEL.to_vec();
let push_str = |b: &mut Vec<u8>, code: i16, s: &str| {
b.extend_from_slice(&code.to_le_bytes());
b.extend_from_slice(s.as_bytes());
b.push(0);
};
push_str(&mut b, 0, "LINE");
b.extend_from_slice(&10i16.to_le_bytes());
b.extend_from_slice(&3.25f64.to_le_bytes());
b.extend_from_slice(&62i16.to_le_bytes());
b.extend_from_slice(&5i16.to_le_bytes());
push_str(&mut b, 0, "EOF");
let tags = parse(&b).unwrap();
assert_eq!(tags[1], Tag::f(10, 3.25));
assert_eq!(tags[2], Tag::i(62, 5));
}
#[test]
fn malformed_inputs() {
assert!(parse(b"").is_err());
assert!(parse(b"abc\nxyz\n").is_err());
assert!(parse(b"0\n").is_err());
let mut b = BINARY_SENTINEL.to_vec();
b.extend_from_slice(&10i16.to_le_bytes());
b.extend_from_slice(&[1, 2, 3]);
assert!(parse(&b).is_err());
// Bad numbers become 0 rather than failing.
let t = parse(b"10\nnotanumber\n0\nEOF\n").unwrap();
assert_eq!(t[0].f64(), 0.0);
}
#[test]
fn unicode_escapes_and_latin1() {
let t = parse(b"1\nCaf\\U+00E9\n0\nEOF\n").unwrap();
assert_eq!(t[0].str(), "Café");
let t = parse(b"1\nCaf\xe9\n0\nEOF\n").unwrap();
assert_eq!(t[0].str(), "Café");
}
}
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "cadcraft-engine"
description = "CADCraft engine: sessions, commands, the command line and prompts, snaps, selection, undo"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
cadcraft-geom = { workspace = true }
cadcraft-color = { workspace = true }
cadcraft-doc = { workspace = true }
cadcraft-fonts = { workspace = true }
cadcraft-render = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
File diff suppressed because it is too large Load Diff
+274
View File
@@ -0,0 +1,274 @@
//! Edit menu: undo/redo, clipboard, selection.
use cadcraft_doc::{Entity, Handle, entity_bounds};
use cadcraft_geom::{Bounds2, Mat3, Vec2};
use serde_json::{Value, json};
use super::*;
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("undo", "Undo", run_undo).menu(&["Edit", "Undo"]).key("Cmd+Z").alias(&["u"]).params("{count?: n}").noundo(),
CommandSpec::new("redo", "Redo", run_redo).menu(&["Edit", "Redo"]).key("Cmd+Shift+Z").alias(&["mredo"]).params("{count?: n}").noundo(),
CommandSpec::new("cutclip", "Cut", run_cut).menu(&["Edit", "Cut"]).key("Cmd+X").params("{handles?}"),
CommandSpec::new("copyclip", "Copy", run_copyclip).menu(&["Edit", "Copy"]).key("Cmd+C").params("{handles?}").noundo(),
CommandSpec::new("copybase", "Copy with Base Point", run_copybase)
.menu(&["Edit", "Copy with Base Point"])
.key("Cmd+Shift+C")
.params("{handles?, base: [x,y]}")
.noundo(),
CommandSpec::new("pasteclip", "Paste", run_paste)
.menu(&["Edit", "Paste"])
.key("Cmd+V")
.params("{at?: [x,y]} (default: same offset as copied)")
.interactive(|_| Ok(Box::new(PasteM { orig: false }))),
CommandSpec::new("pasteorig", "Paste to Original Coordinates", run_pasteorig).menu(&["Edit", "Paste to Original Coordinates"]).params("{}"),
CommandSpec::new("erase.selection", "Clear", run_clear).menu(&["Edit", "Clear"]).key("Delete").enabled(has_selection).params("{}"),
CommandSpec::new("selectall", "Select All", run_selectall).menu(&["Edit", "Select All"]).key("Cmd+A").alias(&["ai_selall"]).noundo(),
CommandSpec::new("select", "Select", run_select)
.params("{handles: [hex]} | {window: [[x,y],[x,y]], crossing?: bool} | {at: [x,y]} | {clear: true} | {add?: bool}")
.noundo()
.interactive(|_| Ok(Box::new(SelectM::default()))),
CommandSpec::new("qselect", "Quick Select...", run_qselect)
.menu(&["Edit", "Quick Select..."])
.params("{type?: \"Line\"|..., layer?, color?}")
.noundo(),
]
}
fn run_undo(s: &mut Session, p: &Value) -> Result<Value> {
let n = p.get("count").and_then(Value::as_u64).unwrap_or(1).clamp(1, 1000);
let mut labels = Vec::new();
for _ in 0..n {
match s.undo()? {
Some(l) => labels.push(l),
None => break,
}
}
if labels.is_empty() {
return Ok(json!({ "message": "Everything has been undone" }));
}
Ok(json!({ "undone": labels, "message": labels.join(", ").to_string() }))
}
fn run_redo(s: &mut Session, p: &Value) -> Result<Value> {
let n = p.get("count").and_then(Value::as_u64).unwrap_or(1).clamp(1, 1000);
let mut labels = Vec::new();
for _ in 0..n {
match s.redo()? {
Some(l) => labels.push(l),
None => break,
}
}
Ok(json!({ "redone": labels, "message": if labels.is_empty() { "Nothing to redo".to_string() } else { labels.join(", ") } }))
}
fn copy_to_clip(s: &mut Session, hs: &[Handle], base: Option<Vec2>) -> Result<usize> {
let d = s.doc()?;
let ents: Vec<Entity> = hs.iter().filter_map(|h| d.entity(*h).map(|e| (**e).clone())).collect();
let b = ents.iter().fold(Bounds2::EMPTY, |acc, e| acc.union(&entity_bounds(d, e, 0)));
s.clipboard_base = base.unwrap_or(b.min);
let n = ents.len();
s.clipboard = ents;
Ok(n)
}
fn run_copyclip(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let n = copy_to_clip(s, &hs, None)?;
Ok(json!({ "copied": n }))
}
fn run_copybase(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let base = point_param(p, "base");
let n = copy_to_clip(s, &hs, base)?;
Ok(json!({ "copied": n }))
}
fn run_cut(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let n = copy_to_clip(s, &hs, None)?;
let d = s.doc_mut()?;
for h in &hs {
d.remove_entity(*h);
}
s.set_selection(Vec::new());
Ok(json!({ "cut": n }))
}
pub(crate) fn paste(s: &mut Session, offset: Vec2) -> Result<Vec<Handle>> {
let clip = s.clipboard.clone();
let space = s.space();
let m = Mat3::translate(offset);
let d = s.doc_mut()?;
let mut out = Vec::new();
for mut e in clip {
e.handle = d.new_handle();
e.kind.transform(&m);
d.ensure_layer(&e.common.layer);
out.push(e.handle);
if let Some(st) = d.space_mut(&space) {
st.push(e);
}
}
s.set_selection(out.clone());
Ok(out)
}
fn run_paste(s: &mut Session, p: &Value) -> Result<Value> {
if s.clipboard.is_empty() {
return Err(bad("pasteclip", "the clipboard is empty"));
}
let off = match point_param(p, "at") {
Some(at) => at - s.clipboard_base,
None => Vec2::ZERO,
};
let r = paste(s, off)?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
fn run_pasteorig(s: &mut Session, _p: &Value) -> Result<Value> {
let r = paste(s, Vec2::ZERO)?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
fn run_clear(s: &mut Session, _p: &Value) -> Result<Value> {
let hs = s.selection();
let d = s.doc_mut()?;
let mut n = 0;
for h in hs {
if d.remove_entity(h).is_some() {
n += 1;
}
}
s.set_selection(Vec::new());
Ok(json!({ "erased": n }))
}
fn run_selectall(s: &mut Session, _p: &Value) -> Result<Value> {
let space = s.space();
let d = s.doc()?;
let hs: Vec<Handle> = d
.space(&space)
.map(|st| st.iter().filter(|e| d.is_visible(e) && d.layer(&e.common.layer).is_none_or(|l| !l.locked)).map(|e| e.handle).collect())
.unwrap_or_default();
let n = hs.len();
s.set_selection(hs);
Ok(json!({ "selected": n }))
}
fn run_select(s: &mut Session, p: &Value) -> Result<Value> {
if bool_or(p, "clear", false) {
s.set_selection(Vec::new());
return Ok(json!({ "selected": 0 }));
}
let space = s.space();
let add = bool_or(p, "add", false);
let picked: Vec<Handle> = if let Some(w) = points_param(p, "window") {
let (Some(a), Some(b)) = (w.first(), w.get(1)) else { return Err(bad("select", "window needs 2 corners")) };
crate::select::select_window(s.doc()?, &space, Bounds2::new(*a, *b), bool_or(p, "crossing", false))
} else if let Some(at) = point_param(p, "at") {
let ap = f64_or(p, "aperture", s.pixel_size() * s.settings.pickbox * 1.5);
crate::select::pick(s.doc()?, &space, at, ap).into_iter().collect()
} else if let Some(f) = points_param(p, "fence") {
crate::select::select_fence(s.doc()?, &space, &f)
} else {
targets(s, p)?
};
let mut sel = if add { s.selection() } else { Vec::new() };
sel.extend(picked);
s.set_selection(sel);
let sel = s.selection();
Ok(json!({ "selected": sel.len(), "handles": sel.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
fn run_qselect(s: &mut Session, p: &Value) -> Result<Value> {
let space = s.space();
let d = s.doc()?;
let ty = str_param(p, "type").map(str::to_ascii_lowercase);
let layer = str_param(p, "layer").map(str::to_ascii_lowercase);
let color = str_param(p, "color").and_then(cadcraft_color::Color::parse);
let hs: Vec<Handle> = d
.space(&space)
.map(|st| {
st.iter()
.filter(|e| ty.as_ref().is_none_or(|t| e.kind.type_name().to_ascii_lowercase() == *t || e.kind.dxf_name().to_ascii_lowercase() == *t))
.filter(|e| layer.as_ref().is_none_or(|l| e.common.layer.to_ascii_lowercase() == *l))
.filter(|e| color.is_none_or(|c| e.common.color == c))
.map(|e| e.handle)
.collect()
})
.unwrap_or_default();
let n = hs.len();
s.set_selection(hs);
Ok(json!({ "selected": n, "message": format!("{n} item(s) selected") }))
}
struct PasteM {
orig: bool,
}
impl Interactive for PasteM {
fn name(&self) -> &'static str {
"PASTECLIP"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
if s.clipboard.is_empty() {
s.echo("Clipboard is empty.");
return Ok(Step::Done);
}
if self.orig {
paste(s, Vec2::ZERO)?;
return Ok(Step::Done);
}
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
Prompt::new("Specify insertion point", Accept::POINT)
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Point(p) => {
let base = s.clipboard_base;
paste(s, p - base)?;
Ok(Step::Done)
}
Input::Enter => Ok(Step::Done),
_ => Ok(Step::Continue),
}
}
fn preview(&self, s: &Session, c: Vec2) -> Vec<cadcraft_doc::EntityKind> {
let m = Mat3::translate(c - s.clipboard_base);
s.clipboard
.iter()
.take(500)
.map(|e| {
let mut k = e.kind.clone();
k.transform(&m);
k
})
.collect()
}
}
#[derive(Default)]
struct SelectM {
sel: super::machines::SelectPhase,
}
impl Interactive for SelectM {
fn name(&self) -> &'static str {
"SELECT"
}
fn prompt(&self, _s: &Session) -> Prompt {
self.sel.prompt()
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match self.sel.feed(s, &i)? {
super::machines::SelOutcome::More => Ok(Step::Continue),
_ => Ok(Step::Done),
}
}
}
+198
View File
@@ -0,0 +1,198 @@
//! File menu: new, close, switching drawings. Open/save of DWG/DXF go through the io layer,
//! registered by the host (desktop/CLI) via [`crate::cmd::file::set_io`].
use std::sync::OnceLock;
use cadcraft_doc::Drawing;
use serde_json::{Value, json};
use super::*;
use crate::{Result, Session};
/// File format hooks (installed by the app so the engine stays I/O-agnostic and wasm-safe).
pub struct IoHooks {
pub read: fn(&[u8], &str) -> std::result::Result<Drawing, String>,
pub write: fn(&Drawing, &str) -> std::result::Result<Vec<u8>, String>,
}
static IO: OnceLock<IoHooks> = OnceLock::new();
pub fn set_io(h: IoHooks) {
let _ = IO.set(h);
}
pub fn io() -> Option<&'static IoHooks> {
IO.get()
}
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("new", "New Drawing...", run_new)
.menu(&["File", "New Drawing..."])
.key("Cmd+N")
.alias(&["qnew"])
.params("{metric?: bool}")
.enabled(always)
.noundo(),
CommandSpec::new("open", "Open...", run_open)
.menu(&["File", "Open..."])
.key("Cmd+O")
.params("{path} | {data: base64, name}")
.enabled(always)
.noundo(),
CommandSpec::new("close", "Close", run_close).menu(&["File", "Close"]).key("Cmd+W").params("{index?}").noundo(),
CommandSpec::new("closeall", "Close All", run_closeall).menu(&["File", "Close All"]).enabled(always).noundo(),
CommandSpec::new("qsave", "Save", run_save).menu(&["File", "Save"]).key("Cmd+S").alias(&["save"]).params("{path?}").noundo(),
CommandSpec::new("saveas", "Save As...", run_saveas)
.menu(&["File", "Save As..."])
.key("Cmd+Shift+S")
.params("{path, format?: dxf|dwg}")
.noundo(),
CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").enabled(always).noundo(),
CommandSpec::new("document.bytes", "Drawing as bytes", run_bytes).params("{format?: dxf} → {data: base64}").noundo(),
]
}
fn run_new(s: &mut Session, p: &Value) -> Result<Value> {
let i = s.new_drawing(bool_or(p, "metric", false));
Ok(json!({ "index": i, "title": s.docs.get(i).map(|d| d.title.clone()) }))
}
fn file_name(path: &str) -> String {
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string())
}
pub(crate) fn open_bytes(s: &mut Session, bytes: &[u8], name: &str, path: Option<String>) -> Result<usize> {
let hooks = io().ok_or_else(|| bad("open", "file formats are not available in this build"))?;
let d = (hooks.read)(bytes, name).map_err(|e| bad("open", e))?;
Ok(s.open_drawing(d, &file_name(name), path))
}
fn run_open(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(_path) = str_param(p, "path") {
#[cfg(not(target_arch = "wasm32"))]
let path = _path;
#[cfg(not(target_arch = "wasm32"))]
{
let bytes = std::fs::read(path).map_err(|e| bad("open", format!("{path}: {e}")))?;
let i = open_bytes(s, &bytes, path, Some(path.to_string()))?;
return Ok(json!({ "index": i, "entities": s.docs.get(i).map(|d| d.doc.entity_count()) }));
}
#[cfg(target_arch = "wasm32")]
return Err(bad("open", "paths are not available on the web; pass `data`"));
}
let data = str_param(p, "data").ok_or_else(|| bad("open", "`path` or `data` (base64) is required"))?;
let bytes = base64_decode(data).ok_or_else(|| bad("open", "invalid base64"))?;
let name = str_param(p, "name").unwrap_or("Drawing.dxf");
let i = open_bytes(s, &bytes, name, None)?;
Ok(json!({ "index": i }))
}
fn run_close(s: &mut Session, p: &Value) -> Result<Value> {
let i = p.get("index").and_then(Value::as_u64).map(|i| i as usize).unwrap_or(s.active);
if i >= s.docs.len() {
return Err(bad("close", "no such drawing"));
}
s.cancel();
s.docs.remove(i);
if s.active >= s.docs.len() {
s.active = s.docs.len().saturating_sub(1);
}
ok()
}
fn run_closeall(s: &mut Session, _p: &Value) -> Result<Value> {
s.cancel();
s.docs.clear();
s.active = 0;
ok()
}
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<usize> {
let hooks = io().ok_or_else(|| bad("save", "file formats are not available in this build"))?;
let bytes = (hooks.write)(s.doc()?, path).map_err(|e| bad("save", e))?;
#[cfg(not(target_arch = "wasm32"))]
{
let tmp = format!("{path}.cadcraft-tmp");
std::fs::write(&tmp, &bytes).map_err(|e| bad("save", format!("{path}: {e}")))?;
std::fs::rename(&tmp, path).map_err(|e| bad("save", format!("{path}: {e}")))?;
}
let st = s.state_mut()?;
st.saved = st.doc.clone();
st.path = Some(path.to_string());
st.title = file_name(path);
Ok(bytes.len())
}
fn run_save(s: &mut Session, p: &Value) -> Result<Value> {
let path = match str_param(p, "path") {
Some(p) => p.to_string(),
None => s.state()?.path.clone().ok_or_else(|| bad("qsave", "drawing has no file name yet; use saveas {path}"))?,
};
let n = save_to(s, &path)?;
Ok(json!({ "path": path, "bytes": n }))
}
fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("saveas", "`path` is required"))?.to_string();
let n = save_to(s, &path)?;
Ok(json!({ "path": path, "bytes": n }))
}
fn run_switch(s: &mut Session, p: &Value) -> Result<Value> {
let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("document.switch", "`index` is required"))? as usize;
if i >= s.docs.len() {
return Err(bad("document.switch", "no such drawing"));
}
s.cancel();
s.active = i;
ok()
}
fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
let hooks = io().ok_or_else(|| bad("document.bytes", "file formats are not available in this build"))?;
let fmt = str_param(p, "format").unwrap_or("dxf");
let bytes = (hooks.write)(s.doc()?, &format!("drawing.{fmt}")).map_err(|e| bad("document.bytes", e))?;
Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len() }))
}
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
pub fn base64_encode(data: &[u8]) -> String {
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
for i in 0..4 {
if i <= chunk.len() {
out.push(char::from(B64[((n >> (18 - 6 * i)) & 63) as usize]));
} else {
out.push('=');
}
}
}
out
}
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(s.len() * 3 / 4);
let mut buf = 0u32;
let mut bits = 0;
for c in s.bytes() {
let v = match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'+' | b'-' => 62,
b'/' | b'_' => 63,
b'=' | b'\n' | b'\r' | b' ' => continue,
_ => return None,
};
buf = (buf << 6) | u32::from(v);
bits += 6;
if bits >= 8 {
bits -= 8;
out.push(((buf >> bits) & 0xff) as u8);
}
}
Some(out)
}
+93
View File
@@ -0,0 +1,93 @@
//! Shared geometry helpers for commands.
use cadcraft_doc::{EntityKind, Line};
use cadcraft_geom::{PolyVertex, Vec2, Vec3};
pub fn v3(p: Vec2) -> Vec3 {
p.to3(0.0)
}
pub fn line(a: Vec2, b: Vec2) -> EntityKind {
EntityKind::Line(Line { a: v3(a), b: v3(b) })
}
pub fn circle(c: Vec2, r: f64) -> EntityKind {
EntityKind::Circle(cadcraft_doc::Circle { center: v3(c), radius: r.abs() })
}
pub fn arc(a: &cadcraft_geom::Arc) -> EntityKind {
EntityKind::Arc(cadcraft_doc::Arc { center: v3(a.center), radius: a.radius, start: a.start, end: a.end })
}
pub fn lwpoly(vs: Vec<PolyVertex>, closed: bool) -> EntityKind {
EntityKind::LwPolyline(cadcraft_doc::LwPolyline { vertices: vs, closed, const_width: 0.0, elevation: 0.0, plinegen: false })
}
pub fn rect_vertices(a: Vec2, b: Vec2) -> Vec<PolyVertex> {
[a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y)].into_iter().map(PolyVertex::new).collect()
}
/// Regular polygon vertices: inscribed (vertex at `radius`) or circumscribed (edge midpoint at `radius`).
pub fn polygon_vertices(center: Vec2, sides: usize, radius_pt: Vec2, inscribed: bool) -> Vec<PolyVertex> {
let n = sides.clamp(3, 1024);
let d = radius_pt - center;
let r = d.len();
let a0 = d.angle();
let step = cadcraft_geom::TAU / n as f64;
let (r, a0) = if inscribed { (r, a0) } else { (r / (step / 2.0).cos(), a0 - step / 2.0) };
(0..n).map(|i| PolyVertex::new(Vec2::polar(center, r, a0 + step * i as f64))).collect()
}
/// Polygon from an edge (first two vertices).
pub fn polygon_from_edge(p1: Vec2, p2: Vec2, sides: usize) -> Vec<PolyVertex> {
let n = sides.clamp(3, 1024);
let step = cadcraft_geom::TAU / n as f64;
let mut pts = vec![p1, p2];
let len = p1.dist(p2);
let mut ang = p1.angle_to(p2);
for _ in 2..n {
ang += step;
let last = pts.last().copied().unwrap_or(p2);
pts.push(Vec2::polar(last, len, ang));
}
pts.into_iter().map(PolyVertex::new).collect()
}
/// Rectangle vertices with fillet radius or chamfer distances at every corner.
pub fn rect_with_corners(a: Vec2, b: Vec2, fillet: f64, chamfer: (f64, f64)) -> Vec<PolyVertex> {
let (x0, x1) = (a.x.min(b.x), a.x.max(b.x));
let (y0, y1) = (a.y.min(b.y), a.y.max(b.y));
let w = x1 - x0;
let h = y1 - y0;
if fillet > 0.0 && fillet * 2.0 <= w.min(h) + 1e-12 {
let r = fillet;
let bul = cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2);
return vec![
PolyVertex::new(Vec2::new(x0 + r, y0)),
PolyVertex::with_bulge(Vec2::new(x1 - r, y0), bul),
PolyVertex::new(Vec2::new(x1, y0 + r)),
PolyVertex::with_bulge(Vec2::new(x1, y1 - r), bul),
PolyVertex::new(Vec2::new(x1 - r, y1)),
PolyVertex::with_bulge(Vec2::new(x0 + r, y1), bul),
PolyVertex::new(Vec2::new(x0, y1 - r)),
PolyVertex::with_bulge(Vec2::new(x0, y0 + r), bul),
];
}
let (c1, c2) = chamfer;
if c1 > 0.0 && c2 > 0.0 && c1 + c1 <= w + 1e-12 && c2 + c2 <= h + 1e-12 {
return [
Vec2::new(x0 + c1, y0),
Vec2::new(x1 - c1, y0),
Vec2::new(x1, y0 + c2),
Vec2::new(x1, y1 - c2),
Vec2::new(x1 - c1, y1),
Vec2::new(x0 + c1, y1),
Vec2::new(x0, y1 - c2),
Vec2::new(x0, y0 + c2),
]
.into_iter()
.map(PolyVertex::new)
.collect();
}
rect_vertices(Vec2::new(x0, y0), Vec2::new(x1, y1))
}
+450
View File
@@ -0,0 +1,450 @@
//! Inquiry: DIST, ID, LIST, AREA, drawing inspection for agents.
use cadcraft_doc::{EntityKind, Handle};
use cadcraft_geom::{Polyline, Vec2};
use serde_json::{Value, json};
use super::*;
use crate::units::{format_angle, format_distance};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("dist", "Distance", run_dist)
.menu(&["Tools", "Inquiry", "Distance"])
.alias(&["di"])
.params("{p1, p2}")
.noundo()
.transparent()
.interactive(|_| Ok(Box::new(DistM::default()))),
CommandSpec::new("id", "ID Point", run_id)
.menu(&["Tools", "Inquiry", "ID Point"])
.params("{at}")
.noundo()
.transparent()
.interactive(|_| Ok(Box::new(IdM))),
CommandSpec::new("list", "List", run_list)
.menu(&["Tools", "Inquiry", "List"])
.alias(&["li", "ls"])
.params("{handles?}")
.noundo()
.interactive(|_| Ok(Box::new(ListM::default()))),
CommandSpec::new("area", "Area", run_area)
.menu(&["Tools", "Inquiry", "Area"])
.alias(&["aa"])
.params("{points: [[x,y],...]} | {handle}")
.noundo()
.interactive(|_| Ok(Box::new(AreaM::default()))),
CommandSpec::new("time", "Time", run_time).menu(&["Tools", "Inquiry", "Time"]).noundo(),
CommandSpec::new("status", "Status", run_status).menu(&["Tools", "Inquiry", "Status"]).noundo(),
CommandSpec::new("drawing.inspect", "Inspect Drawing", run_inspect).params("{entities?: bool, limit?: n}").noundo(),
CommandSpec::new("entities", "Query Entities", run_entities).params("{type?, layer?, window?: [[x,y],[x,y]], limit?, offset?}").noundo(),
CommandSpec::new("count", "Count", run_count).menu(&["Tools", "Count"]).params("{block?}").noundo(),
]
}
fn fmt_d(s: &Session, v: f64) -> String {
let h = s.doc().map(|d| (d.header.i64("LUNITS", 2), d.header.i64("LUPREC", 4))).unwrap_or((2, 4));
format_distance(v, h.0, h.1)
}
fn fmt_a(s: &Session, v: f64) -> String {
let h = s.doc().map(|d| (d.header.i64("AUNITS", 0), d.header.i64("AUPREC", 0))).unwrap_or((0, 0));
format_angle(v, h.0, h.1)
}
fn dist_text(s: &Session, a: Vec2, b: Vec2) -> String {
let d = b - a;
format!(
"Distance = {}, Angle in XY Plane = {}, Angle from XY Plane = 0\nDelta X = {}, Delta Y = {}, Delta Z = {}",
fmt_d(s, a.dist(b)),
fmt_a(s, d.angle()),
fmt_d(s, d.x),
fmt_d(s, d.y),
fmt_d(s, 0.0)
)
}
fn run_dist(s: &mut Session, p: &Value) -> Result<Value> {
let a = point_req("dist", p, "p1")?;
let b = point_req("dist", p, "p2")?;
Ok(json!({ "distance": a.dist(b), "angle": (b - a).angle().to_degrees(), "dx": b.x - a.x, "dy": b.y - a.y, "message": dist_text(s, a, b) }))
}
fn run_id(s: &mut Session, p: &Value) -> Result<Value> {
let a = point_req("id", p, "at")?;
s.last_point = a;
Ok(json!({ "x": a.x, "y": a.y, "message": format!("X = {} Y = {} Z = {}", fmt_d(s, a.x), fmt_d(s, a.y), fmt_d(s, 0.0)) }))
}
fn list_text(s: &Session, h: Handle) -> String {
let Ok(d) = s.doc() else { return String::new() };
let Some(e) = d.entity(h) else { return String::new() };
let space = if d.model.contains(h) { "Model space" } else { "Paper space" };
let mut t = format!(
" {} Layer: \"{}\"\n Space: {}\n Handle = {}",
e.kind.dxf_name(),
e.common.layer,
space,
h.hex()
);
match &e.kind {
EntityKind::Line(l) => {
t.push_str(&format!(
"\n from point, X={} Y={} Z={}\n to point, X={} Y={} Z={}",
fmt_d(s, l.a.x),
fmt_d(s, l.a.y),
fmt_d(s, 0.0),
fmt_d(s, l.b.x),
fmt_d(s, l.b.y),
fmt_d(s, 0.0)
));
t.push_str(&format!(
"\n Length = {}, Angle in XY Plane = {}",
fmt_d(s, l.a.xy().dist(l.b.xy())),
fmt_a(s, l.a.xy().angle_to(l.b.xy()))
));
}
EntityKind::Circle(c) => {
t.push_str(&format!(
"\n center point, X={} Y={} Z={}\n radius {}\n circumference {}\n area {}",
fmt_d(s, c.center.x),
fmt_d(s, c.center.y),
fmt_d(s, 0.0),
fmt_d(s, c.radius),
fmt_d(s, c.radius * cadcraft_geom::TAU),
fmt_d(s, c.radius * c.radius * cadcraft_geom::PI)
));
}
EntityKind::Arc(a) => {
t.push_str(&format!(
"\n center point, X={} Y={} Z={}\n radius {}\n start angle {}\n end angle {}",
fmt_d(s, a.center.x),
fmt_d(s, a.center.y),
fmt_d(s, 0.0),
fmt_d(s, a.radius),
fmt_a(s, a.start),
fmt_a(s, a.end)
));
}
EntityKind::LwPolyline(p) => {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
t.push_str(&format!("\n {}\n Constant width {}", if p.closed { "Closed" } else { "Open" }, fmt_d(s, p.const_width)));
if p.closed {
t.push_str(&format!("\n area {}\n perimeter {}", fmt_d(s, pl.area().abs()), fmt_d(s, pl.len())));
} else {
t.push_str(&format!("\n length {}", fmt_d(s, pl.len())));
}
for v in &p.vertices {
t.push_str(&format!("\n at point X={} Y={} Z={}", fmt_d(s, v.p.x), fmt_d(s, v.p.y), fmt_d(s, 0.0)));
}
}
EntityKind::Text(tx) => {
t.push_str(&format!(
"\n Style = \"{}\"\n start point, X={} Y={}\n height {}\n text {}\n rotation angle {}",
tx.style,
fmt_d(s, tx.insert.x),
fmt_d(s, tx.insert.y),
fmt_d(s, tx.height),
tx.value,
fmt_a(s, tx.rotation)
));
}
other => {
if let Ok(js) = serde_json::to_string(other) {
t.push_str(&format!("\n {js}"));
}
}
}
t
}
fn run_list(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let texts: Vec<String> = hs.iter().map(|h| list_text(s, *h)).collect();
Ok(json!({ "message": texts.join("\n\n") }))
}
fn area_of(pts: &[Vec2]) -> (f64, f64) {
let a = cadcraft_geom::shoelace(pts).abs();
let n = pts.len();
let per: f64 = (0..n).filter_map(|i| Some(pts.get(i)?.dist(*pts.get((i + 1) % n)?))).sum();
(a, per)
}
fn run_area(s: &mut Session, p: &Value) -> Result<Value> {
let (a, per) = if let Some(pts) = points_param(p, "points") {
area_of(&pts)
} else {
let h = targets(s, p)?.first().copied().ok_or_else(|| bad("area", "`points` or `handle` is required"))?;
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| bad("area", "no such object"))?;
match &e.kind {
EntityKind::Circle(c) => (c.radius * c.radius * cadcraft_geom::PI, c.radius * cadcraft_geom::TAU),
EntityKind::LwPolyline(pl) => {
let g = Polyline { vertices: pl.vertices.clone(), closed: true };
(g.area().abs(), g.len())
}
EntityKind::Ellipse(el) => {
let a = el.major.xy().len();
let b = a * el.ratio;
(cadcraft_geom::PI * a * b, cadcraft_geom::PI * (3.0 * (a + b) - ((3.0 * a + b) * (a + 3.0 * b)).sqrt()))
}
EntityKind::Hatch(hh) => hh.loops.iter().fold((0.0, 0.0), |acc, l| {
let g = Polyline { vertices: l.vertices.clone(), closed: true };
(acc.0 + g.area().abs(), acc.1 + g.len())
}),
_ => return Err(bad("area", "object has no area")),
}
};
Ok(json!({ "area": a, "perimeter": per, "message": format!("Area = {}, Perimeter = {}", fmt_d(s, a), fmt_d(s, per)) }))
}
fn run_time(s: &mut Session, _p: &Value) -> Result<Value> {
let rev = s.state()?.revision;
Ok(json!({ "message": format!("Drawing revision: {rev}\nEdits recorded: {}", s.state()?.undo.len()) }))
}
fn run_status(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc()?;
let ext = d.extents(&cadcraft_doc::Space::Model);
let msg = format!(
"{} objects in {}\nModel space limits are X: {} Y: {} (Off)\nModel space uses X: {} Y: {}\n X: {} Y: {}\nCurrent layer: {}\nCurrent color: {}\nCurrent linetype: {}",
d.entity_count(),
s.state()?.title,
fmt_d(s, d.header.point("LIMMIN").map(|p| p.x).unwrap_or(0.0)),
fmt_d(s, d.header.point("LIMMIN").map(|p| p.y).unwrap_or(0.0)),
fmt_d(s, ext.min.x),
fmt_d(s, ext.min.y),
fmt_d(s, ext.max.x),
fmt_d(s, ext.max.y),
d.header.str("CLAYER", "0"),
cadcraft_color::Color::from_aci(d.header.i64("CECOLOR", 256) as i16).name(),
d.header.str("CELTYPE", "ByLayer"),
);
Ok(json!({ "message": msg }))
}
fn entity_summary(e: &cadcraft_doc::Entity) -> Value {
json!({ "handle": e.handle.hex(), "type": e.kind.type_name(), "layer": e.common.layer, "color": e.common.color.name(), "geometry": e.kind })
}
fn run_inspect(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.state()?;
let d = &st.doc;
let limit = p.get("limit").and_then(Value::as_u64).unwrap_or(200) as usize;
let space = st.space.clone();
let ext = d.extents(&space);
let mut counts: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();
if let Some(store) = d.space(&space) {
for e in store.iter() {
*counts.entry(e.kind.type_name()).or_default() += 1;
}
}
let mut out = json!({
"title": st.title,
"path": st.path,
"dirty": st.is_dirty(),
"space": match &space { cadcraft_doc::Space::Model => "Model".to_string(), cadcraft_doc::Space::Paper(n) => n.clone() },
"entityCount": d.entity_count(),
"counts": counts,
"extents": if ext.is_empty() { Value::Null } else { json!([[ext.min.x, ext.min.y], [ext.max.x, ext.max.y]]) },
"layers": d.layers.iter().map(|l| json!({"name": l.name, "on": l.on, "frozen": l.frozen, "locked": l.locked, "color": l.color.name(), "linetype": l.linetype})).collect::<Vec<_>>(),
"currentLayer": d.header.str("CLAYER", "0"),
"linetypes": d.linetypes.iter().map(|l| l.name.clone()).collect::<Vec<_>>(),
"textStyles": d.text_styles.iter().map(|l| l.name.clone()).collect::<Vec<_>>(),
"dimStyles": d.dim_styles.iter().map(|l| l.name.clone()).collect::<Vec<_>>(),
"blocks": d.blocks.keys().filter(|k| !k.starts_with('*')).cloned().collect::<Vec<_>>(),
"layouts": d.layouts.iter().map(|l| l.name.clone()).collect::<Vec<_>>(),
"selection": st.selection.iter().map(|h| h.hex()).collect::<Vec<_>>(),
"undo": st.undo.iter().rev().take(20).map(|u| u.label.clone()).collect::<Vec<_>>(),
"view": { "center": [st.view().center.x, st.view().center.y], "height": st.view().height },
});
if bool_or(p, "entities", true)
&& let (Some(o), Some(store)) = (out.as_object_mut(), d.space(&space))
{
o.insert("entities".into(), Value::Array(store.iter().take(limit).map(|e| entity_summary(e)).collect()));
}
Ok(out)
}
fn run_entities(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.state()?;
let d = &st.doc;
let ty = str_param(p, "type").map(str::to_ascii_lowercase);
let layer = str_param(p, "layer").map(str::to_ascii_lowercase);
let window = points_param(p, "window").and_then(|w| Some(cadcraft_geom::Bounds2::new(*w.first()?, *w.get(1)?)));
let limit = p.get("limit").and_then(Value::as_u64).unwrap_or(500) as usize;
let offset = p.get("offset").and_then(Value::as_u64).unwrap_or(0) as usize;
let Some(store) = d.space(&st.space) else { return Ok(json!({ "entities": [] })) };
let matches: Vec<Value> = store
.iter()
.filter(|e| ty.as_ref().is_none_or(|t| e.kind.type_name().to_ascii_lowercase() == *t || e.kind.dxf_name().to_ascii_lowercase() == *t))
.filter(|e| layer.as_ref().is_none_or(|l| e.common.layer.to_ascii_lowercase() == *l))
.filter(|e| window.is_none_or(|w| w.intersects(&cadcraft_doc::entity_bounds(d, e, 0))))
.skip(offset)
.take(limit)
.map(|e| entity_summary(e))
.collect();
Ok(json!({ "count": matches.len(), "entities": matches }))
}
fn run_count(s: &mut Session, p: &Value) -> Result<Value> {
let d = s.doc()?;
let mut counts: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
for e in d.model.iter() {
if let EntityKind::Insert(i) = &e.kind {
*counts.entry(i.block.clone()).or_default() += 1;
}
}
if let Some(b) = str_param(p, "block") {
return Ok(json!({ "block": b, "count": counts.get(b).copied().unwrap_or(0) }));
}
Ok(json!({ "blocks": counts }))
}
#[derive(Default)]
struct DistM {
first: Option<Vec2>,
}
impl Interactive for DistM {
fn name(&self) -> &'static str {
"DIST"
}
fn prompt(&self, _s: &Session) -> Prompt {
match self.first {
None => Prompt::new("Specify first point", Accept::POINT),
Some(a) => Prompt::new("Specify second point", Accept::POINT).kw(&["Multiple points"]).base(a),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match (self.first, i) {
(None, Input::Point(p)) => {
self.first = Some(p);
Ok(Step::Continue)
}
(Some(a), Input::Point(b)) => {
let t = dist_text(s, a, b);
for l in t.lines() {
s.echo(l.to_string());
}
Ok(Step::Done)
}
(_, Input::Enter) => Ok(Step::Done),
_ => Ok(Step::Continue),
}
}
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
self.first.map(|a| vec![super::helpers::line(a, c)]).unwrap_or_default()
}
}
struct IdM;
impl Interactive for IdM {
fn name(&self) -> &'static str {
"ID"
}
fn prompt(&self, _s: &Session) -> Prompt {
Prompt::new("Specify point", Accept::POINT)
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if let Input::Point(p) = i {
let m = format!("X = {} Y = {} Z = {}", fmt_d(s, p.x), fmt_d(s, p.y), fmt_d(s, 0.0));
s.echo(m);
}
Ok(Step::Done)
}
}
#[derive(Default)]
struct ListM {
sel: super::machines::SelectPhase,
}
impl Interactive for ListM {
fn name(&self) -> &'static str {
"LIST"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.sel = super::machines::SelectPhase::begin(s);
if self.sel.done {
let hs = self.sel.picked.clone();
for h in hs {
let t = list_text(s, h);
for l in t.lines() {
s.echo(l.to_string());
}
}
return Ok(Step::Done);
}
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
self.sel.prompt()
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match self.sel.feed(s, &i)? {
super::machines::SelOutcome::More => Ok(Step::Continue),
super::machines::SelOutcome::Empty => Ok(Step::Done),
super::machines::SelOutcome::Done(hs) => {
for h in hs {
let t = list_text(s, h);
for l in t.lines() {
s.echo(l.to_string());
}
}
Ok(Step::Done)
}
}
}
}
#[derive(Default)]
struct AreaM {
pts: Vec<Vec2>,
}
impl Interactive for AreaM {
fn name(&self) -> &'static str {
"AREA"
}
fn prompt(&self, _s: &Session) -> Prompt {
match self.pts.len() {
0 => Prompt::new("Specify first corner point", Accept::POINT).kw(&["Object", "Add area", "Subtract area"]).default("Object"),
1 => Prompt::new("Specify next point", Accept::POINT).kw(&["Arc", "Length", "Undo"]).base_opt(self.pts.last().copied()),
_ => Prompt::new("Specify next point", Accept::POINT)
.kw(&["Arc", "Length", "Undo", "Total"])
.default("Total")
.base_opt(self.pts.last().copied()),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Point(p) => {
self.pts.push(p);
Ok(Step::Continue)
}
Input::Keyword(k) if k == "Undo" => {
self.pts.pop();
Ok(Step::Continue)
}
Input::Enter | Input::Keyword(_) if self.pts.len() >= 3 => {
let (a, per) = area_of(&self.pts);
let m = format!("Area = {}, Perimeter = {}", fmt_d(s, a), fmt_d(s, per));
s.echo(m);
Ok(Step::Done)
}
Input::Enter => Ok(Step::Done),
_ => Ok(Step::Continue),
}
}
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
if self.pts.is_empty() {
return Vec::new();
}
let mut v: Vec<cadcraft_geom::PolyVertex> = self.pts.iter().map(|p| cadcraft_geom::PolyVertex::new(*p)).collect();
v.push(cadcraft_geom::PolyVertex::new(c));
vec![super::helpers::lwpoly(v, true)]
}
}
+315
View File
@@ -0,0 +1,315 @@
//! Layers: LAYER (programmatic sub-ids), layer tools (LAYMCUR, LAYISO, LAYOFF, LAYFRZ…).
use cadcraft_color::Color;
use cadcraft_doc::{Layer, Lineweight};
use serde_json::{Value, json};
use super::*;
use crate::{Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("layer", "Layers", run_list).menu(&["Format", "Layers"]).alias(&["la", "layers"]).noundo(),
CommandSpec::new("layer.new", "New Layer", run_new).params("{name, color?, linetype?, lineweight? (mm), current?: bool}"),
CommandSpec::new("layer.set", "Set Layer Properties", run_set)
.params("{name, on?, frozen?, locked?, plot?, color?, linetype?, lineweight?, transparency?, description?, newName?}"),
CommandSpec::new("layer.current", "Make Current", run_current)
.menu(&["Format", "Layer Tools", "Make Current"])
.alias(&["clayer"])
.params("{name}"),
CommandSpec::new("layer.delete", "Delete Layer", run_delete).params("{name}"),
CommandSpec::new("laymcur", "Make Object's Layer Current", run_laymcur).params("{handles?}"),
CommandSpec::new("laymch", "Layer Match", run_laymch).menu(&["Format", "Layer Tools", "Layer Match"]).params("{handles?, layer}"),
CommandSpec::new("laycur", "Change to Current Layer", run_laycur)
.menu(&["Format", "Layer Tools", "Change to Current Layer"])
.params("{handles?}"),
CommandSpec::new("layiso", "Isolate Layer", run_layiso).menu(&["Format", "Layer Tools", "Isolate Layer"]).params("{handles?}"),
CommandSpec::new("layuniso", "Unisolate Layer", run_layuniso).menu(&["Format", "Layer Tools", "Unisolate Layer"]),
CommandSpec::new("layfrz", "Freeze Layer", |s, p| set_obj_layers(s, p, |l| l.frozen = true))
.menu(&["Format", "Layer Tools", "Freeze Layer"])
.params("{handles?}"),
CommandSpec::new("layoff", "Layer Off", |s, p| set_obj_layers(s, p, |l| l.on = false))
.menu(&["Format", "Layer Tools", "Layer Off"])
.params("{handles?}"),
CommandSpec::new("laylck", "Lock Layer", |s, p| set_obj_layers(s, p, |l| l.locked = true))
.menu(&["Format", "Layer Tools", "Lock Layer"])
.params("{handles?}"),
CommandSpec::new("layulk", "Unlock Layer", |s, p| set_obj_layers(s, p, |l| l.locked = false))
.menu(&["Format", "Layer Tools", "Unlock Layer"])
.params("{handles?}"),
CommandSpec::new("layon", "Turn All Layers On", |s, _| all_layers(s, |l| l.on = true)),
CommandSpec::new("laythw", "Thaw All Layers", |s, _| all_layers(s, |l| l.frozen = false)),
CommandSpec::new("layerp", "Previous Layer", run_layerp).menu(&["Format", "Layer Tools", "Previous Layer"]),
CommandSpec::new("layerstate.save", "Save Layer State", run_state_save).menu(&["Format", "Layer States Manager..."]).params("{name}"),
CommandSpec::new("layerstate.restore", "Restore Layer State", run_state_restore).params("{name}"),
]
}
fn layer_json(l: &Layer, current: bool) -> Value {
json!({
"name": l.name, "on": l.on, "frozen": l.frozen, "locked": l.locked, "plot": l.plot,
"color": l.color.name(), "colorRgb": l.color.resolve(Color::Index(7), Color::Index(7)).hex(),
"linetype": l.linetype, "lineweight": l.lineweight.name(), "transparency": l.transparency,
"description": l.description, "current": current,
})
}
fn run_list(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc()?;
let cur = d.header.str("CLAYER", "0");
Ok(json!({ "layers": d.layers.iter().map(|l| layer_json(l, l.name.eq_ignore_ascii_case(&cur))).collect::<Vec<_>>() }))
}
fn parse_lw(v: &Value) -> Option<Lineweight> {
if let Some(f) = v.as_f64() {
return Some(Lineweight::Mm100((f * 100.0).round().clamp(0.0, 211.0) as u16));
}
match v.as_str()?.to_ascii_lowercase().as_str() {
"bylayer" => Some(Lineweight::ByLayer),
"byblock" => Some(Lineweight::ByBlock),
"default" => Some(Lineweight::Default),
s => s.trim_end_matches("mm").trim().parse::<f64>().ok().map(|f| Lineweight::Mm100((f * 100.0).round().clamp(0.0, 211.0) as u16)),
}
}
fn apply(l: &mut Layer, p: &Value) -> Result<()> {
if let Some(v) = p.get("on").and_then(Value::as_bool) {
l.on = v;
}
if let Some(v) = p.get("frozen").and_then(Value::as_bool) {
l.frozen = v;
}
if let Some(v) = p.get("locked").and_then(Value::as_bool) {
l.locked = v;
}
if let Some(v) = p.get("plot").and_then(Value::as_bool) {
l.plot = v;
}
if let Some(c) = p.get("color") {
let c = c
.as_str()
.and_then(Color::parse)
.or_else(|| c.as_u64().and_then(|i| u8::try_from(i).ok()).filter(|i| *i > 0).map(Color::Index))
.ok_or_else(|| bad("layer", "bad colour"))?;
if matches!(c, Color::ByLayer | Color::ByBlock) {
return Err(bad("layer", "a layer colour must be an index or true colour"));
}
l.color = c;
}
if let Some(lt) = str_param(p, "linetype") {
l.linetype = lt.to_string();
}
if let Some(lw) = p.get("lineweight") {
l.lineweight = parse_lw(lw).ok_or_else(|| bad("layer", "bad lineweight"))?;
}
if let Some(t) = p.get("transparency").and_then(Value::as_u64) {
l.transparency = t.min(90) as u8;
}
if let Some(d) = str_param(p, "description") {
l.description = d.to_string();
}
Ok(())
}
fn valid_name(n: &str) -> bool {
!n.trim().is_empty() && n.len() <= 255 && !n.chars().any(|c| "<>/\\\":;?*|,=`".contains(c))
}
fn run_new(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layer.new", "`name` is required"))?.to_string();
if !valid_name(&name) {
return Err(bad("layer.new", "invalid layer name"));
}
let d = s.doc_mut()?;
if d.layer(&name).is_some() {
return Err(bad("layer.new", format!("layer `{name}` already exists")));
}
let mut l = Layer::new(&name);
apply(&mut l, p)?;
d.layers.push(l);
if bool_or(p, "current", false) {
d.header.set_str("CLAYER", &name);
}
ok()
}
fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layer.set", "`name` is required"))?.to_string();
let new_name = str_param(p, "newName").map(str::to_string);
let d = s.doc_mut()?;
let cur = d.header.str("CLAYER", "0");
let l = d.layer_mut(&name).ok_or_else(|| bad("layer.set", format!("no layer `{name}`")))?;
apply(l, p)?;
if p.get("frozen").and_then(Value::as_bool) == Some(true) && l.name.eq_ignore_ascii_case(&cur) {
l.frozen = false;
return Err(bad("layer.set", "cannot freeze the current layer"));
}
if let Some(nn) = new_name {
if l.name == "0" || l.name.eq_ignore_ascii_case("Defpoints") {
return Err(bad("layer.set", "cannot rename layer 0 or Defpoints"));
}
if !valid_name(&nn) {
return Err(bad("layer.set", "invalid layer name"));
}
let old = l.name.clone();
l.name = nn.clone();
// Re-point entities.
let hs: Vec<_> = d.model.iter().filter(|e| e.common.layer.eq_ignore_ascii_case(&old)).map(|e| e.handle).collect();
for h in hs {
d.model.modify(h, |e| e.common.layer = nn.clone());
}
if cur.eq_ignore_ascii_case(&old) {
d.header.set_str("CLAYER", &nn);
}
}
ok()
}
fn run_current(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layer.current", "`name` is required"))?.to_string();
let d = s.doc_mut()?;
let l = d.layer_mut(&name).ok_or_else(|| bad("layer.current", format!("no layer `{name}`")))?;
l.frozen = false;
let n = l.name.clone();
prev_push(d);
d.header.set_str("CLAYER", &n);
ok()
}
fn prev_push(d: &mut cadcraft_doc::Drawing) {
let snap = serde_json::to_string(&d.layers).unwrap_or_default();
d.header.set_str("CADCRAFT_LAYERP", &snap);
}
fn run_layerp(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
let snap = d.header.str("CADCRAFT_LAYERP", "");
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layerp", "No previous layer state."))?;
d.layers = layers;
Ok(json!({"message": "Restored previous layer states."}))
}
fn run_delete(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layer.delete", "`name` is required"))?.to_string();
let d = s.doc_mut()?;
if name == "0" || name.eq_ignore_ascii_case("Defpoints") || d.header.str("CLAYER", "0").eq_ignore_ascii_case(&name) {
return Err(bad("layer.delete", "cannot delete layer 0, Defpoints or the current layer"));
}
let used = d.model.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name))
|| d.layouts.iter().any(|l| l.entities.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name)));
if used {
return Err(bad("layer.delete", "layer has objects on it"));
}
d.layers.retain(|l| !l.name.eq_ignore_ascii_case(&name));
ok()
}
fn obj_layers(s: &Session, p: &Value) -> Result<Vec<String>> {
let hs = targets(s, p)?;
let d = s.doc()?;
let mut v: Vec<String> = hs.iter().filter_map(|h| d.entity(*h).map(|e| e.common.layer.clone())).collect();
v.sort();
v.dedup();
Ok(v)
}
fn run_laymcur(s: &mut Session, p: &Value) -> Result<Value> {
let ls = obj_layers(s, p)?;
let l = ls.first().cloned().ok_or_else(|| bad("laymcur", "select an object"))?;
s.doc_mut()?.header.set_str("CLAYER", &l);
Ok(json!({ "message": format!("{l} is now the current layer.") }))
}
fn run_laymch(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let layer = str_param(p, "layer").ok_or_else(|| bad("laymch", "`layer` is required"))?.to_string();
let d = s.doc_mut()?;
d.ensure_layer(&layer);
for h in &hs {
d.modify_entity(*h, |e| e.common.layer = layer.clone())?;
}
Ok(json!({ "changed": hs.len() }))
}
fn run_laycur(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let d = s.doc_mut()?;
let cur = d.header.str("CLAYER", "0");
for h in &hs {
d.modify_entity(*h, |e| e.common.layer = cur.clone())?;
}
Ok(json!({ "changed": hs.len() }))
}
fn run_layiso(s: &mut Session, p: &Value) -> Result<Value> {
let keep = obj_layers(s, p)?;
if keep.is_empty() {
return Err(bad("layiso", "select objects on the layers to isolate"));
}
let d = s.doc_mut()?;
prev_push(d);
d.header.set_str("CADCRAFT_LAYISO", &serde_json::to_string(&d.layers).unwrap_or_default());
for l in &mut d.layers {
if !keep.iter().any(|k| k.eq_ignore_ascii_case(&l.name)) {
l.on = false;
}
}
if let Some(k) = keep.first() {
d.header.set_str("CLAYER", k);
}
Ok(json!({ "message": format!("Layer(s) {} have been isolated.", keep.join(", ")) }))
}
fn run_layuniso(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
let snap = d.header.str("CADCRAFT_LAYISO", "");
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layuniso", "No isolated layers."))?;
d.layers = layers;
ok()
}
fn set_obj_layers(s: &mut Session, p: &Value, f: fn(&mut Layer)) -> Result<Value> {
let ls = obj_layers(s, p)?;
let d = s.doc_mut()?;
let cur = d.header.str("CLAYER", "0");
prev_push(d);
for n in &ls {
if let Some(l) = d.layer_mut(n) {
let was_frozen = l.frozen;
f(l);
if l.frozen && !was_frozen && l.name.eq_ignore_ascii_case(&cur) {
l.frozen = false;
}
}
}
s.set_selection(Vec::new());
Ok(json!({ "layers": ls }))
}
fn all_layers(s: &mut Session, f: fn(&mut Layer)) -> Result<Value> {
let d = s.doc_mut()?;
prev_push(d);
d.layers.iter_mut().for_each(f);
ok()
}
fn run_state_save(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.save", "`name` is required"))?.to_string();
let d = s.doc_mut()?;
let layers = d.layers.clone();
d.layer_states.retain(|st| st.name != name);
d.layer_states.push(cadcraft_doc::LayerState { name, layers });
ok()
}
fn run_state_restore(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.restore", "`name` is required"))?;
let d = s.doc_mut()?;
let st = d.layer_states.iter().find(|st| st.name == name).cloned().ok_or_else(|| bad("layerstate.restore", "no such layer state"))?;
for saved in st.layers {
if let Some(l) = d.layer_mut(&saved.name) {
*l = saved;
}
}
ok()
}
+101
View File
@@ -0,0 +1,101 @@
//! Building blocks for interactive commands: object selection and simple point sequences.
use cadcraft_doc::Handle;
use crate::{Accept, Input, Prompt, Result, Session};
/// A "Select objects:" phase. Uses the pickfirst selection when there is one.
#[derive(Clone, Debug, Default)]
pub struct SelectPhase {
pub picked: Vec<Handle>,
pub done: bool,
pub single: bool,
pub removing: bool,
}
pub enum SelOutcome {
/// Keep prompting.
More,
/// Selection finished with these objects.
Done(Vec<Handle>),
/// Selection finished empty: the command should end.
Empty,
}
impl SelectPhase {
/// Start with the pickfirst selection, if any (then the phase is already done).
pub fn begin(s: &mut Session) -> Self {
let pre = s.selection();
if !pre.is_empty() && s.settings.pickfirst {
s.remember_selection(&pre);
SelectPhase { picked: pre, done: true, single: false, removing: false }
} else {
SelectPhase::default()
}
}
pub fn single() -> Self {
SelectPhase { single: true, ..Default::default() }
}
pub fn prompt(&self) -> Prompt {
let msg = if self.removing {
"Remove objects"
} else if self.single {
"Select object"
} else {
"Select objects"
};
Prompt::new(msg, Accept::SELECT)
}
pub fn feed(&mut self, s: &mut Session, i: &Input) -> Result<SelOutcome> {
match i {
Input::Pick(hs) => {
let before = self.picked.len();
if self.removing {
self.picked.retain(|h| !hs.contains(h));
} else {
for h in hs {
if !self.picked.contains(h) {
self.picked.push(*h);
}
}
}
let n = hs.len();
let _ = before;
if n > 0 {
s.echo(format!("{n} found, {} total", self.picked.len()));
} else {
s.echo("0 found");
}
s.set_selection(self.picked.clone());
if self.single && !self.picked.is_empty() {
return Ok(self.finish(s));
}
Ok(SelOutcome::More)
}
Input::Text(t) | Input::Keyword(t) => {
match t.trim().to_ascii_lowercase().as_str() {
"r" | "remove" => self.removing = true,
"a" | "add" => self.removing = false,
_ => s.echo("*Invalid selection*"),
}
Ok(SelOutcome::More)
}
Input::Enter => Ok(self.finish(s)),
_ => Ok(SelOutcome::More),
}
}
fn finish(&mut self, s: &mut Session) -> SelOutcome {
self.done = true;
if self.picked.is_empty() {
SelOutcome::Empty
} else {
s.remember_selection(&self.picked);
SelOutcome::Done(self.picked.clone())
}
}
}
/// Parse a number from text input.
pub fn number(t: &str) -> Option<f64> {
crate::units::parse_distance(t)
}
+219
View File
@@ -0,0 +1,219 @@
//! The command registry. Ids are AutoCAD command names in lower case; menu paths follow
//! AutoCAD's menu bar so the catalog doubles as the parity metric.
mod draw;
mod edit;
pub mod file;
mod inquiry;
mod layer;
mod modify;
mod props;
mod settings;
mod view;
pub mod helpers;
pub mod machines;
use cadcraft_doc::Handle;
use cadcraft_geom::Vec2;
use serde::Serialize;
use serde_json::Value;
use crate::{EngineError, Interactive, Result, Session};
pub type Run = fn(&mut Session, &Value) -> Result<Value>;
pub type Enabled = fn(&Session) -> std::result::Result<(), String>;
pub type Factory = fn(&Session) -> Result<Box<dyn Interactive>>;
pub struct CommandSpec {
pub id: &'static str,
pub label: &'static str,
/// Menu placement, e.g. `["Draw", "Circle", "Center, Radius"]`. Empty = not in menus.
pub menu: &'static [&'static str],
pub shortcut: Option<&'static str>,
pub aliases: &'static [&'static str],
pub params: &'static str,
pub enabled: Enabled,
pub run: Run,
pub undoable: bool,
pub interactive: Option<Factory>,
/// Can run inside another command with a leading apostrophe.
pub transparent: bool,
}
impl CommandSpec {
pub const fn new(id: &'static str, label: &'static str, run: Run) -> Self {
CommandSpec {
id,
label,
menu: &[],
shortcut: None,
aliases: &[],
params: "",
enabled: has_doc,
run,
undoable: true,
interactive: None,
transparent: false,
}
}
pub const fn menu(mut self, m: &'static [&'static str]) -> Self {
self.menu = m;
self
}
pub const fn key(mut self, k: &'static str) -> Self {
self.shortcut = Some(k);
self
}
pub const fn alias(mut self, a: &'static [&'static str]) -> Self {
self.aliases = a;
self
}
pub const fn params(mut self, p: &'static str) -> Self {
self.params = p;
self
}
pub const fn enabled(mut self, e: Enabled) -> Self {
self.enabled = e;
self
}
pub const fn noundo(mut self) -> Self {
self.undoable = false;
self
}
pub const fn interactive(mut self, f: Factory) -> Self {
self.interactive = Some(f);
self
}
pub const fn transparent(mut self) -> Self {
self.transparent = true;
self
}
pub fn info(&self, s: &Session) -> CommandInfo {
let e = (self.enabled)(s);
CommandInfo {
id: self.id,
label: self.label,
menu: self.menu.to_vec(),
shortcut: self.shortcut,
aliases: self.aliases.to_vec(),
params: self.params,
interactive: self.interactive.is_some(),
enabled: e.is_ok(),
disabled_reason: e.err(),
}
}
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandInfo {
pub id: &'static str,
pub label: &'static str,
pub menu: Vec<&'static str>,
pub shortcut: Option<&'static str>,
pub aliases: Vec<&'static str>,
pub params: &'static str,
pub interactive: bool,
pub enabled: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub disabled_reason: Option<String>,
}
pub fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
pub fn has_doc(s: &Session) -> std::result::Result<(), String> {
s.state().map(|_| ()).map_err(|_| "no drawing open".into())
}
pub fn has_selection(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
if s.selection().is_empty() { Err("nothing selected".into()) } else { Ok(()) }
}
pub fn command_specs() -> &'static [CommandSpec] {
static SPECS: std::sync::OnceLock<Vec<CommandSpec>> = std::sync::OnceLock::new();
SPECS.get_or_init(|| {
let mut v = Vec::new();
v.extend(file::specs());
v.extend(edit::specs());
v.extend(view::specs());
v.extend(draw::specs());
v.extend(modify::specs());
v.extend(layer::specs());
v.extend(props::specs());
v.extend(inquiry::specs());
v.extend(settings::specs());
v
})
}
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
let l = id.to_ascii_lowercase();
command_specs().iter().find(|c| c.id == l)
}
/// Resolve a typed name or alias (AutoCAD-style short names such as `L`, `C`, `PL`) to an id.
pub fn resolve_alias(name: &str) -> String {
let l = name.to_ascii_lowercase();
if find_command(&l).is_some() {
return l;
}
command_specs().iter().find(|c| c.aliases.iter().any(|a| a.eq_ignore_ascii_case(&l))).map(|c| c.id.to_string()).unwrap_or(l)
}
// ---------- param helpers ----------
pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
pub(crate) fn f64_or(p: &Value, key: &str, default: f64) -> f64 {
p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(default)
}
pub(crate) fn f64_req(cmd: &str, p: &Value, key: &str) -> Result<f64> {
p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` (number) is required")))
}
pub(crate) fn bool_or(p: &Value, key: &str, default: bool) -> bool {
p.get(key).and_then(Value::as_bool).unwrap_or(default)
}
pub(crate) fn str_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> {
p.get(key).and_then(Value::as_str)
}
pub fn point_value(v: &Value) -> Option<Vec2> {
if let Some(a) = v.as_array() {
let x = a.first()?.as_f64()?;
let y = a.get(1)?.as_f64()?;
let p = Vec2::new(x, y);
return p.is_finite().then_some(p);
}
if let Some(s) = v.as_str() {
return crate::prompt::parse_point(s, Vec2::ZERO);
}
let x = v.get("x")?.as_f64()?;
let y = v.get("y")?.as_f64()?;
let p = Vec2::new(x, y);
p.is_finite().then_some(p)
}
pub(crate) fn point_param(p: &Value, key: &str) -> Option<Vec2> {
p.get(key).and_then(point_value)
}
pub(crate) fn point_req(cmd: &str, p: &Value, key: &str) -> Result<Vec2> {
point_param(p, key).ok_or_else(|| bad(cmd, format!("`{key}` ([x, y]) is required")))
}
pub(crate) fn points_param(p: &Value, key: &str) -> Option<Vec<Vec2>> {
p.get(key)?.as_array()?.iter().map(point_value).collect()
}
/// Handles from `handles` (hex strings or numbers) or the current selection.
pub(crate) fn targets(s: &Session, p: &Value) -> Result<Vec<Handle>> {
if let Some(a) = p.get("handles").and_then(Value::as_array) {
let hs: Vec<Handle> = a.iter().filter_map(|v| v.as_str().and_then(Handle::parse_hex).or_else(|| v.as_u64().map(Handle))).collect();
return Ok(hs);
}
if let Some(h) = p.get("handle").and_then(|v| v.as_str().and_then(Handle::parse_hex).or_else(|| v.as_u64().map(Handle))) {
return Ok(vec![h]);
}
Ok(s.selection())
}
pub(crate) fn ok() -> Result<Value> {
Ok(Value::Null)
}
File diff suppressed because it is too large Load Diff
+459
View File
@@ -0,0 +1,459 @@
//! Properties: per-object property edits, current properties, MATCHPROP, linetypes, units.
use cadcraft_color::Color;
use cadcraft_doc::{EntityKind, Lineweight};
use cadcraft_geom::Vec3;
use serde_json::{Value, json};
use super::*;
use crate::{Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(),
CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, transparency?, visible?, <geometry fields: radius, center, start, end, text, height, rotation…>}"),
CommandSpec::new("matchprop", "Match Properties", run_matchprop).menu(&["Modify", "Match Properties"]).alias(&["ma", "painter"]).params("{source, targets: [hex]}"),
CommandSpec::new("color", "Color...", run_color).menu(&["Format", "Color..."]).alias(&["col", "colour"]).params("{color: \"ByLayer\" | \"red\" | 1..255 | \"r,g,b\"}"),
CommandSpec::new("linetype", "Linetype...", run_linetype).menu(&["Format", "Linetype..."]).alias(&["lt", "ltype"]).params("{current?: name, load?: name | \"*\"}"),
CommandSpec::new("lweight", "Lineweight...", run_lweight).menu(&["Format", "Lineweight..."]).alias(&["lw", "lineweight"]).params("{lineweight: mm | ByLayer}"),
CommandSpec::new("ltscale", "Linetype Scale", run_ltscale).alias(&["lts"]).params("{scale}"),
CommandSpec::new("units", "Units...", run_units).menu(&["Format", "Units..."]).alias(&["un"]).params("{lunits?: 1..5, luprec?: 0..8, aunits?: 0..4, auprec?: 0..8, insunits?}"),
CommandSpec::new("limits", "Drawing Limits", run_limits).menu(&["Format", "Drawing Limits"]).params("{min: [x,y], max: [x,y]}"),
CommandSpec::new("style", "Text Style...", run_style).menu(&["Format", "Text Style..."]).alias(&["st"]).params("{name, font?, height?, widthFactor?, oblique?, current?}"),
CommandSpec::new("dimstyle", "Dimension Style...", run_dimstyle).menu(&["Format", "Dimension Style..."]).alias(&["d", "dst", "ddim"]).params("{name, current?, <style fields>}"),
CommandSpec::new("ddptype", "Point Style...", run_ptype).menu(&["Format", "Point Style..."]).params("{pdmode, pdsize}"),
CommandSpec::new("rename", "Rename...", run_rename).menu(&["Format", "Rename..."]).params("{table: layer|linetype|style|dimstyle|block, from, to}"),
]
}
fn entity_props(d: &cadcraft_doc::Drawing, e: &cadcraft_doc::Entity) -> Value {
let mut v = json!({
"handle": e.handle.hex(),
"type": e.kind.type_name(),
"layer": e.common.layer,
"color": e.common.color.name(),
"linetype": e.common.linetype,
"lineweight": e.common.lineweight.name(),
"ltscale": e.common.ltscale,
"visible": e.common.visible,
});
let geo = serde_json::to_value(&e.kind).unwrap_or(Value::Null);
if let (Some(o), Some(g)) = (v.as_object_mut(), geo.as_object()) {
o.insert("geometry".into(), Value::Object(g.clone()));
let b = cadcraft_doc::entity_bounds(d, e, 0);
if !b.is_empty() {
o.insert("bounds".into(), json!([[b.min.x, b.min.y], [b.max.x, b.max.y]]));
}
match &e.kind {
EntityKind::Line(l) => {
o.insert("length".into(), json!(l.a.xy().dist(l.b.xy())));
o.insert("angle".into(), json!(l.a.xy().angle_to(l.b.xy()).to_degrees()));
}
EntityKind::Circle(c) => {
o.insert("diameter".into(), json!(c.radius * 2.0));
o.insert("circumference".into(), json!(c.radius * cadcraft_geom::TAU));
o.insert("area".into(), json!(c.radius * c.radius * cadcraft_geom::PI));
}
EntityKind::Arc(a) => {
o.insert("arcLength".into(), json!(a.radius * cadcraft_geom::ccw_sweep(a.start, a.end)));
o.insert("totalAngle".into(), json!(cadcraft_geom::ccw_sweep(a.start, a.end).to_degrees()));
}
EntityKind::LwPolyline(p) => {
let pl = cadcraft_geom::Polyline { vertices: p.vertices.clone(), closed: p.closed };
o.insert("length".into(), json!(pl.len()));
if p.closed {
o.insert("area".into(), json!(pl.area().abs()));
}
}
_ => {}
}
}
v
}
fn run_get(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let d = s.doc()?;
if hs.is_empty() {
let h = &d.header;
return Ok(json!({
"selection": "No selection",
"color": Color::from_aci(h.i64("CECOLOR", 256) as i16).name(),
"layer": h.str("CLAYER", "0"),
"linetype": h.str("CELTYPE", "ByLayer"),
"linetypeScale": h.f64("CELTSCALE", 1.0),
"lineweight": Lineweight::from_dxf(h.i64("CELWEIGHT", -1) as i16).name(),
"textStyle": h.str("TEXTSTYLE", "Standard"),
"dimStyle": h.str("DIMSTYLE", "Standard"),
"textHeight": h.f64("TEXTSIZE", 0.2),
}));
}
let ents: Vec<Value> = hs.iter().filter_map(|h| d.entity(*h).map(|e| entity_props(d, e))).collect();
Ok(json!({ "count": ents.len(), "objects": ents }))
}
fn parse_color(v: &Value) -> Option<Color> {
v.as_str().and_then(Color::parse).or_else(|| v.as_i64().and_then(|i| i16::try_from(i).ok()).map(Color::from_aci))
}
fn set_xy(p: &mut Vec3, v: &Value) {
if let Some(q) = point_value(v) {
p.x = q.x;
p.y = q.y;
}
}
fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
if hs.is_empty() {
return Err(bad("properties.set", "nothing selected"));
}
let color = p.get("color").map(|c| parse_color(c).ok_or_else(|| bad("properties.set", "bad colour"))).transpose()?;
let lw = p.get("lineweight").map(|v| match v.as_str().map(str::to_ascii_lowercase).as_deref() {
Some("bylayer") => Lineweight::ByLayer,
Some("byblock") => Lineweight::ByBlock,
Some("default") => Lineweight::Default,
_ => Lineweight::Mm100(
(v.as_f64().or_else(|| v.as_str().and_then(|s| s.trim_end_matches("mm").trim().parse().ok())).unwrap_or(0.25) * 100.0)
.round()
.clamp(0.0, 211.0) as u16,
),
});
let d = s.doc_mut()?;
if let Some(l) = str_param(p, "layer") {
d.ensure_layer(l);
}
for h in &hs {
d.modify_entity(*h, |e| {
if let Some(l) = str_param(p, "layer") {
e.common.layer = l.to_string();
}
if let Some(c) = color {
e.common.color = c;
}
if let Some(lt) = str_param(p, "linetype") {
e.common.linetype = lt.to_string();
}
if let Some(w) = lw {
e.common.lineweight = w;
}
if let Some(x) = p.get("ltscale").and_then(Value::as_f64).filter(|x| *x > 0.0) {
e.common.ltscale = x;
}
if let Some(v) = p.get("visible").and_then(Value::as_bool) {
e.common.visible = v;
}
let num = |k: &str| p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite());
match &mut e.kind {
EntityKind::Line(l) => {
if let Some(v) = p.get("start") {
set_xy(&mut l.a, v);
}
if let Some(v) = p.get("end") {
set_xy(&mut l.b, v);
}
}
EntityKind::Circle(c) => {
if let Some(v) = p.get("center") {
set_xy(&mut c.center, v);
}
if let Some(r) = num("radius").filter(|r| *r > 0.0) {
c.radius = r;
}
if let Some(dm) = num("diameter").filter(|r| *r > 0.0) {
c.radius = dm / 2.0;
}
}
EntityKind::Arc(a) => {
if let Some(v) = p.get("center") {
set_xy(&mut a.center, v);
}
if let Some(r) = num("radius").filter(|r| *r > 0.0) {
a.radius = r;
}
if let Some(x) = num("startAngle") {
a.start = cadcraft_geom::norm_angle(x.to_radians());
}
if let Some(x) = num("endAngle") {
a.end = cadcraft_geom::norm_angle(x.to_radians());
}
}
EntityKind::Text(t) => {
if let Some(v) = str_param(p, "text") {
t.value = v.to_string();
}
if let Some(x) = num("height").filter(|x| *x > 0.0) {
t.height = x;
}
if let Some(x) = num("rotation") {
t.rotation = x.to_radians();
}
if let Some(x) = num("widthFactor").filter(|x| *x > 0.0) {
t.width_factor = x;
}
if let Some(v) = p.get("position") {
set_xy(&mut t.insert, v);
}
}
EntityKind::MText(t) => {
if let Some(v) = str_param(p, "text") {
t.contents = v.replace('\n', "\\P");
}
if let Some(x) = num("height").filter(|x| *x > 0.0) {
t.height = x;
}
if let Some(x) = num("width").filter(|x| *x >= 0.0) {
t.width = x;
}
if let Some(x) = num("rotation") {
t.rotation = x.to_radians();
}
}
EntityKind::LwPolyline(pl) => {
if let Some(x) = num("width").filter(|x| *x >= 0.0) {
pl.const_width = x;
}
if let Some(c) = p.get("closed").and_then(Value::as_bool) {
pl.closed = c;
}
}
EntityKind::Insert(i) => {
if let Some(x) = num("rotation") {
i.rotation = x.to_radians();
}
if let Some(x) = num("scale").filter(|x| *x != 0.0) {
i.scale = Vec3::new(x, x, x);
}
}
EntityKind::Dimension(dm) => {
if let Some(v) = str_param(p, "textOverride") {
dm.text = v.to_string();
dm.block = None;
}
}
EntityKind::Hatch(h) => {
if let Some(v) = str_param(p, "pattern") {
h.pattern = v.to_ascii_uppercase();
h.solid = h.pattern == "SOLID";
}
if let Some(x) = num("scale").filter(|x| *x > 0.0) {
h.scale = x;
}
if let Some(x) = num("angle") {
h.angle = x.to_radians();
}
}
_ => {}
}
})?;
}
Ok(json!({ "changed": hs.len() }))
}
fn run_matchprop(s: &mut Session, p: &Value) -> Result<Value> {
let src =
p.get("source").and_then(Value::as_str).and_then(cadcraft_doc::Handle::parse_hex).ok_or_else(|| bad("matchprop", "`source` is required"))?;
let tg: Vec<cadcraft_doc::Handle> = p
.get("targets")
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(|v| v.as_str().and_then(cadcraft_doc::Handle::parse_hex)).collect())
.unwrap_or_default();
let d = s.doc_mut()?;
let c = d.entity(src).map(|e| e.common.clone()).ok_or_else(|| bad("matchprop", "no such source"))?;
for h in &tg {
d.modify_entity(*h, |e| {
e.common.layer = c.layer.clone();
e.common.color = c.color;
e.common.linetype = c.linetype.clone();
e.common.lineweight = c.lineweight;
e.common.ltscale = c.ltscale;
e.common.transparency = c.transparency;
})?;
}
Ok(json!({ "changed": tg.len() }))
}
fn run_color(s: &mut Session, p: &Value) -> Result<Value> {
let c = p.get("color").and_then(parse_color).ok_or_else(|| bad("color", "`color` is required"))?;
let d = s.doc_mut()?;
match c {
Color::True(rgb) => {
d.header.set_i64("CECOLOR", i64::from(cadcraft_color::nearest_aci(rgb)));
d.header.set_i64("CECOLOR_RGB", i64::from(rgb.to_u32()));
}
other => {
d.header.set_i64("CECOLOR", i64::from(other.to_aci()));
d.header.vars.remove("CECOLOR_RGB");
}
}
ok()
}
fn run_linetype(s: &mut Session, p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
if let Some(load) = str_param(p, "load") {
let lib = cadcraft_doc::library::standard_linetypes();
let mut n = 0;
for lt in lib {
if (load == "*" || lt.name.eq_ignore_ascii_case(load)) && d.linetype(&lt.name).is_none() {
d.linetypes.push(lt);
n += 1;
}
}
if n == 0 && load != "*" && d.linetype(load).is_none() {
return Err(bad("linetype", format!("linetype `{load}` not found in the library")));
}
}
if let Some(cur) = str_param(p, "current") {
if !["bylayer", "byblock"].contains(&cur.to_ascii_lowercase().as_str()) && d.linetype(cur).is_none() {
return Err(bad("linetype", format!("linetype `{cur}` is not loaded")));
}
d.header.set_str("CELTYPE", cur);
}
Ok(
json!({ "loaded": d.linetypes.iter().map(|l| json!({"name": l.name, "description": l.description})).collect::<Vec<_>>(), "library": cadcraft_doc::library::standard_linetypes().iter().map(|l| l.name.clone()).collect::<Vec<_>>() }),
)
}
fn run_lweight(s: &mut Session, p: &Value) -> Result<Value> {
let v = p.get("lineweight").ok_or_else(|| bad("lweight", "`lineweight` is required"))?;
let code = match v.as_str().map(str::to_ascii_lowercase).as_deref() {
Some("bylayer") => -1,
Some("byblock") => -2,
Some("default") => -3,
_ => (v.as_f64().ok_or_else(|| bad("lweight", "bad lineweight"))? * 100.0).round().clamp(0.0, 211.0) as i64,
};
s.doc_mut()?.header.set_i64("CELWEIGHT", code);
ok()
}
fn run_ltscale(s: &mut Session, p: &Value) -> Result<Value> {
let v = f64_req("ltscale", p, "scale")?;
if v <= 0.0 {
return Err(bad("ltscale", "scale must be positive"));
}
s.doc_mut()?.header.set_f64("LTSCALE", v);
Ok(json!({ "message": "Regenerating model." }))
}
fn run_units(s: &mut Session, p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
for (k, lo, hi) in [("lunits", 1, 5), ("luprec", 0, 8), ("aunits", 0, 4), ("auprec", 0, 8), ("insunits", 0, 24)] {
if let Some(v) = p.get(k).and_then(Value::as_i64) {
d.header.set_i64(&k.to_ascii_uppercase(), v.clamp(lo, hi));
}
}
let h = &d.header;
Ok(
json!({ "lunits": h.i64("LUNITS", 2), "luprec": h.i64("LUPREC", 4), "aunits": h.i64("AUNITS", 0), "auprec": h.i64("AUPREC", 0), "insunits": h.i64("INSUNITS", 1) }),
)
}
fn run_limits(s: &mut Session, p: &Value) -> Result<Value> {
let a = point_req("limits", p, "min")?;
let b = point_req("limits", p, "max")?;
let d = s.doc_mut()?;
d.header.set("LIMMIN", cadcraft_doc::HVal::Point(a.to3(0.0)));
d.header.set("LIMMAX", cadcraft_doc::HVal::Point(b.to3(0.0)));
ok()
}
fn run_style(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("style", "`name` is required"))?.to_string();
let d = s.doc_mut()?;
let idx = match d.text_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) {
Some(i) => i,
None => {
d.text_styles.push(cadcraft_doc::TextStyle { name: name.clone(), ..Default::default() });
d.text_styles.len() - 1
}
};
if let Some(st) = d.text_styles.get_mut(idx) {
if let Some(f) = str_param(p, "font") {
st.font = f.to_string();
}
if let Some(h) = p.get("height").and_then(Value::as_f64).filter(|h| *h >= 0.0) {
st.height = h;
}
if let Some(w) = p.get("widthFactor").and_then(Value::as_f64).filter(|w| *w > 0.0) {
st.width_factor = w;
}
if let Some(o) = p.get("oblique").and_then(Value::as_f64) {
st.oblique = o.to_radians();
}
}
if bool_or(p, "current", true) {
d.header.set_str("TEXTSTYLE", &name);
}
ok()
}
fn run_dimstyle(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("dimstyle", "`name` is required"))?.to_string();
let d = s.doc_mut()?;
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)) {
Some(i) => i,
None => {
d.dim_styles.push(cadcraft_doc::DimStyle { name: name.clone(), ..base });
d.dim_styles.len() - 1
}
};
if let Some(st) = d.dim_styles.get_mut(idx) {
// Merge any provided fields through serde.
let mut cur = serde_json::to_value(&*st).unwrap_or(Value::Null);
if let (Some(o), Some(src)) = (cur.as_object_mut(), p.as_object()) {
for (k, v) in src {
if k != "name" && k != "current" && o.contains_key(k) {
o.insert(k.clone(), v.clone());
}
}
}
if let Ok(ns) = serde_json::from_value::<cadcraft_doc::DimStyle>(cur) {
*st = ns;
}
}
if bool_or(p, "current", true) {
d.header.set_str("DIMSTYLE", &name);
}
Ok(json!({ "styles": d.dim_styles.iter().map(|s| s.name.clone()).collect::<Vec<_>>() }))
}
fn run_ptype(s: &mut Session, p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
if let Some(m) = p.get("pdmode").and_then(Value::as_i64) {
d.header.set_i64("PDMODE", m);
}
if let Some(z) = p.get("pdsize").and_then(Value::as_f64) {
d.header.set_f64("PDSIZE", z);
}
ok()
}
fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
let table = str_param(p, "table").unwrap_or("layer").to_ascii_lowercase();
let from = str_param(p, "from").ok_or_else(|| bad("rename", "`from` is required"))?.to_string();
let to = str_param(p, "to").ok_or_else(|| bad("rename", "`to` is required"))?.to_string();
match table.as_str() {
"layer" => {
s.execute("layer.set", &json!({ "name": from, "newName": to }))?;
}
"style" => {
let d = s.doc_mut()?;
let st = d.text_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("rename", "no such style"))?;
st.name = to;
}
"dimstyle" => {
let d = s.doc_mut()?;
let st = d.dim_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("rename", "no such dimension style"))?;
st.name = to;
}
"linetype" => {
let d = s.doc_mut()?;
let st = d.linetypes.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("rename", "no such linetype"))?;
st.name = to;
}
_ => return Err(bad("rename", "unsupported table")),
}
ok()
}
+167
View File
@@ -0,0 +1,167 @@
//! Drafting settings and system variables: ORTHO, OSNAP, GRID, SNAP, POLAR, SETVAR/GETVAR.
use serde_json::{Value, json};
use super::*;
use crate::{Result, Session};
fn toggle(s: &mut Session, p: &Value, get: fn(&mut crate::Settings) -> &mut bool, name: &str) -> Result<Value> {
let v = get(&mut s.settings);
*v = p.get("on").and_then(Value::as_bool).unwrap_or(!*v);
let on = *v;
s.touch();
Ok(json!({ "on": on, "message": format!("<{name} {}>", if on { "on" } else { "off" }) }))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("ortho", "Ortho Mode", |s, p| toggle(s, p, |st| &mut st.orthomode, "Ortho"))
.key("F8")
.params("{on?: bool}")
.enabled(always)
.noundo()
.transparent(),
CommandSpec::new("grid", "Grid Display", |s, p| toggle(s, p, |st| &mut st.gridmode, "Grid"))
.key("F7")
.params("{on?: bool}")
.enabled(always)
.noundo()
.transparent(),
CommandSpec::new("snap", "Snap Mode", |s, p| toggle(s, p, |st| &mut st.snapmode, "Snap"))
.key("F9")
.params("{on?: bool}")
.enabled(always)
.noundo()
.transparent(),
CommandSpec::new("polar", "Polar Tracking", |s, p| toggle(s, p, |st| &mut st.polarmode, "Polar"))
.key("F10")
.params("{on?: bool}")
.enabled(always)
.noundo()
.transparent(),
CommandSpec::new("otrack", "Object Snap Tracking", |s, p| toggle(s, p, |st| &mut st.otrack, "Object Snap Tracking"))
.key("F11")
.params("{on?: bool}")
.enabled(always)
.noundo()
.transparent(),
CommandSpec::new("dynmode", "Dynamic Input", |s, p| toggle(s, p, |st| &mut st.dynmode, "Dynamic Input"))
.key("F12")
.params("{on?: bool}")
.enabled(always)
.noundo()
.transparent(),
CommandSpec::new("lwdisplay", "Show/Hide Lineweight", |s, p| toggle(s, p, |st| &mut st.lwdisplay, "Lineweight"))
.params("{on?: bool}")
.enabled(always)
.noundo()
.transparent(),
CommandSpec::new("isodraft", "Isometric Drafting", |s, p| toggle(s, p, |st| &mut st.isodraft, "Isodraft"))
.params("{on?: bool}")
.enabled(always)
.noundo()
.transparent(),
CommandSpec::new("transparencydisplay", "Show/Hide Transparency", |s, p| toggle(s, p, |st| &mut st.transparency_display, "Transparency"))
.params("{on?: bool}")
.enabled(always)
.noundo(),
CommandSpec::new("selectioncycling", "Selection Cycling", |s, p| toggle(s, p, |st| &mut st.selection_cycling, "Selection Cycling"))
.params("{on?: bool}")
.enabled(always)
.noundo(),
CommandSpec::new("osnap", "Object Snap", run_osnap)
.key("F3")
.alias(&["os", "ddosnap"])
.params("{on?: bool, modes?: [\"end\",\"mid\",...] | osmode?: n}")
.enabled(always)
.noundo()
.transparent(),
CommandSpec::new("dsettings", "Drafting Settings...", run_dsettings)
.menu(&["Tools", "Drafting Settings..."])
.alias(&["ds", "se"])
.params("{snapunit?: [x,y], gridunit?: [x,y], polarang? (degrees), gridmajor?}")
.enabled(always)
.noundo(),
CommandSpec::new("setvar", "Set Variable", run_setvar)
.menu(&["Tools", "Inquiry", "Set Variable"])
.alias(&["set"])
.params("{name, value}")
.transparent(),
CommandSpec::new("getvar", "Get Variable", run_getvar).params("{name}").enabled(always).noundo(),
CommandSpec::new("sysvars", "List System Variables", |s, _| Ok(crate::sysvars::list(s))).enabled(always).noundo(),
]
}
fn run_osnap(s: &mut Session, p: &Value) -> Result<Value> {
use crate::snap::mode;
if let Some(n) = p.get("osmode").and_then(Value::as_u64) {
s.settings.osmode = (n as u32) & 0x7fff;
}
if let Some(ms) = p.get("modes").and_then(Value::as_array) {
let mut bits = 0u32;
for m in ms.iter().filter_map(Value::as_str) {
let b = match m.to_ascii_lowercase().get(..3).unwrap_or("") {
"end" => mode::END,
"mid" => mode::MID,
"cen" => mode::CEN,
"nod" => mode::NOD,
"qua" => mode::QUA,
"int" => mode::INT,
"ins" => mode::INS,
"per" => mode::PER,
"tan" => mode::TAN,
"nea" => mode::NEA,
"gce" => mode::GCEN,
"app" => mode::APP,
"ext" => mode::EXT,
"par" => mode::PAR,
_ => 0,
};
bits |= b;
}
s.settings.osmode = bits;
}
if p.get("osmode").is_none() && p.get("modes").is_none() {
let on = p.get("on").and_then(Value::as_bool).unwrap_or(s.settings.osmode & mode::OFF != 0);
if on {
s.settings.osmode &= !mode::OFF;
} else {
s.settings.osmode |= mode::OFF;
}
}
s.touch();
let on = s.settings.osmode & mode::OFF == 0;
let active: Vec<&str> = mode::ALL.iter().filter(|(b, _)| s.settings.osmode & b != 0).map(|(_, n)| *n).collect();
Ok(json!({ "on": on, "osmode": s.settings.osmode, "modes": active, "message": format!("<Osnap {}>", if on { "on" } else { "off" }) }))
}
fn run_dsettings(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = point_param(p, "snapunit").filter(|v| v.x > 0.0 && v.y > 0.0) {
s.settings.snapunit = v;
}
if let Some(v) = point_param(p, "gridunit").filter(|v| v.x > 0.0 && v.y > 0.0) {
s.settings.gridunit = v;
}
if let Some(a) = p.get("polarang").and_then(Value::as_f64).filter(|a| *a > 0.0) {
s.settings.polarang = a.to_radians();
}
if let Some(m) = p.get("gridmajor").and_then(Value::as_u64) {
s.settings.gridmajor = (m as u32).clamp(1, 100);
}
s.touch();
Ok(serde_json::to_value(&s.settings).unwrap_or(Value::Null))
}
fn run_setvar(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("setvar", "`name` is required"))?;
let v = p.get("value").ok_or_else(|| bad("setvar", "`value` is required"))?;
crate::sysvars::set(s, name, v)?;
s.touch();
Ok(json!({ "name": name.to_ascii_uppercase(), "value": crate::sysvars::get(s, name) }))
}
fn run_getvar(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("getvar", "`name` is required"))?;
let v = crate::sysvars::get(s, name).ok_or_else(|| bad("getvar", format!("unknown variable `{name}`")))?;
Ok(json!({ "name": name.to_ascii_uppercase(), "value": v }))
}
+321
View File
@@ -0,0 +1,321 @@
//! View menu: ZOOM, PAN, REGEN, REDRAW, layout switching.
use cadcraft_doc::{Space, entity_bounds};
use cadcraft_geom::{Bounds2, Vec2};
use serde_json::{Value, json};
use super::machines::number;
use super::*;
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step, View};
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("zoom", "Zoom", run_zoom)
.menu(&["View", "Zoom", "Realtime"])
.alias(&["z"])
.params("{mode: extents|all|window|previous|in|out|center|scale|object, p1?, p2?, center?, height?, factor?}")
.noundo()
.transparent()
.interactive(|_| Ok(Box::new(ZoomM::default()))),
CommandSpec::new("zoom.previous", "Zoom Previous", |s, _| zoom(s, &json!({"mode":"previous"})))
.menu(&["View", "Zoom", "Previous"])
.noundo()
.transparent(),
CommandSpec::new("zoom.window", "Zoom Window", run_zoom)
.menu(&["View", "Zoom", "Window"])
.params("{p1, p2}")
.noundo()
.transparent()
.interactive(|_| Ok(Box::new(ZoomM { window: true, ..Default::default() }))),
CommandSpec::new("zoom.in", "Zoom In", |s, _| zoom(s, &json!({"mode":"in"}))).menu(&["View", "Zoom", "In"]).noundo().transparent(),
CommandSpec::new("zoom.out", "Zoom Out", |s, _| zoom(s, &json!({"mode":"out"}))).menu(&["View", "Zoom", "Out"]).noundo().transparent(),
CommandSpec::new("zoom.all", "Zoom All", |s, _| zoom(s, &json!({"mode":"all"}))).menu(&["View", "Zoom", "All"]).noundo().transparent(),
CommandSpec::new("zoom.extents", "Zoom Extents", |s, _| zoom(s, &json!({"mode":"extents"})))
.menu(&["View", "Zoom", "Extents"])
.noundo()
.transparent(),
CommandSpec::new("zoom.object", "Zoom Object", |s, p| {
zoom(s, &json!({"mode":"object", "handles": p.get("handles").cloned().unwrap_or(Value::Null)}))
})
.menu(&["View", "Zoom", "Object"])
.params("{handles?}")
.noundo()
.transparent(),
CommandSpec::new("pan", "Pan", run_pan)
.menu(&["View", "Pan", "Realtime"])
.alias(&["p"])
.params("{delta: [dx,dy]} | {from, to} | {center}")
.noundo()
.transparent()
.interactive(|_| Ok(Box::new(PanM::default()))),
CommandSpec::new("pan.left", "Pan Left", |s, _| pan_frac(s, Vec2::new(-0.25, 0.0))).menu(&["View", "Pan", "Left"]).noundo().transparent(),
CommandSpec::new("pan.right", "Pan Right", |s, _| pan_frac(s, Vec2::new(0.25, 0.0))).menu(&["View", "Pan", "Right"]).noundo().transparent(),
CommandSpec::new("pan.up", "Pan Up", |s, _| pan_frac(s, Vec2::new(0.0, 0.25))).menu(&["View", "Pan", "Up"]).noundo().transparent(),
CommandSpec::new("pan.down", "Pan Down", |s, _| pan_frac(s, Vec2::new(0.0, -0.25))).menu(&["View", "Pan", "Down"]).noundo().transparent(),
CommandSpec::new("regen", "Regen", |s, _| {
s.touch();
Ok(json!({"message": "Regenerating model."}))
})
.menu(&["View", "Regen"])
.alias(&["re"])
.noundo(),
CommandSpec::new("regenall", "Regen All", |s, _| {
s.touch();
Ok(json!({"message": "Regenerating all viewports."}))
})
.menu(&["View", "Regen All"])
.alias(&["rea"])
.noundo(),
CommandSpec::new("redraw", "Redraw", |s, _| {
s.touch();
ok()
})
.menu(&["View", "Redraw"])
.alias(&["r"])
.noundo()
.transparent(),
CommandSpec::new("view.set", "Set View", run_view_set).params("{center: [x,y], height}").noundo(),
CommandSpec::new("view.get", "Get View", |s, _| {
let v = s.state()?.view();
Ok(json!({"center": [v.center.x, v.center.y], "height": v.height, "viewportPx": [s.viewport_px.0, s.viewport_px.1]}))
})
.noundo(),
CommandSpec::new("layout.set", "Switch Layout", run_layout_set).params("{name: \"Model\" | layout name}").noundo(),
]
}
fn ext_bounds(s: &Session) -> Result<Bounds2> {
let space = s.space();
Ok(s.doc()?.extents(&space))
}
fn fit(s: &mut Session, b: Bounds2) -> Result<()> {
if b.is_empty() {
return Ok(());
}
let (w, h) = s.viewport_px;
let aspect = w / h.max(1.0);
let height = b.height().max(b.width() / aspect.max(1e-6)).max(1e-9);
s.state_mut()?.set_view(View { center: b.center(), height });
Ok(())
}
pub(crate) fn zoom(s: &mut Session, p: &Value) -> Result<Value> {
let mode = str_param(p, "mode").unwrap_or("extents").to_ascii_lowercase();
match mode.as_str() {
"extents" | "e" => s.zoom_extents()?,
"all" | "a" => {
let d = s.doc()?;
let lo = d.header.point("LIMMIN").map(|p| p.xy()).unwrap_or(Vec2::ZERO);
let hi = d.header.point("LIMMAX").map(|p| p.xy()).unwrap_or(Vec2::new(12.0, 9.0));
let b = ext_bounds(s)?.union(&Bounds2::new(lo, hi));
fit(s, b.expand(b.height().max(b.width()) * 0.02))?;
}
"window" | "w" => {
let a = point_req("zoom", p, "p1")?;
let b = point_req("zoom", p, "p2")?;
fit(s, Bounds2::new(a, b))?;
}
"previous" | "p" => {
let st = s.state_mut()?;
if let Some(v) = st.view_history.pop() {
st.set_view_quiet(v);
} else {
return Ok(json!({"message": "No previous view saved."}));
}
}
"in" | "out" => {
let f = if mode == "in" { 2.0 } else { 0.5 };
let st = s.state_mut()?;
let v = st.view();
st.set_view(View { center: v.center, height: v.height / f });
}
"center" | "c" => {
let c = point_req("zoom", p, "center")?;
let st = s.state_mut()?;
let h = f64_or(p, "height", st.view().height);
st.set_view(View { center: c, height: h.max(1e-9) });
}
"scale" | "s" => {
let f = f64_req("zoom", p, "factor")?;
if f <= 0.0 {
return Err(bad("zoom", "factor must be positive"));
}
let st = s.state_mut()?;
let v = st.view();
st.set_view(View { center: v.center, height: v.height / f });
}
"object" | "o" => {
let hs = targets(s, p)?;
let d = s.doc()?;
let b = hs.iter().filter_map(|h| d.entity(*h)).fold(Bounds2::EMPTY, |a, e| a.union(&entity_bounds(d, e, 0)));
fit(s, b.expand(b.height().max(b.width()) * 0.05))?;
}
_ => return Err(bad("zoom", "unknown mode")),
}
s.touch();
Ok(Value::Null)
}
fn run_zoom(s: &mut Session, p: &Value) -> Result<Value> {
zoom(s, if p.is_null() { &Value::Null } else { p })
}
fn pan_frac(s: &mut Session, f: Vec2) -> Result<Value> {
let (w, h) = s.viewport_px;
let st = s.state_mut()?;
let v = st.view();
let ww = v.height * w / h.max(1.0);
st.set_view(View { center: v.center + Vec2::new(f.x * ww, f.y * v.height), height: v.height });
ok()
}
fn run_pan(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.state_mut()?;
let v = st.view();
let c = if let Some(c) = point_param(p, "center") {
c
} else if let Some(d) = point_param(p, "delta") {
v.center - d
} else {
let a = point_req("pan", p, "from")?;
let b = point_req("pan", p, "to")?;
v.center - (b - a)
};
st.set_view(View { center: c, height: v.height });
ok()
}
fn run_view_set(s: &mut Session, p: &Value) -> Result<Value> {
let c = point_req("view.set", p, "center")?;
let h = f64_req("view.set", p, "height")?;
if h <= 0.0 {
return Err(bad("view.set", "height must be positive"));
}
s.state_mut()?.set_view(View { center: c, height: h });
ok()
}
fn run_layout_set(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").unwrap_or("Model");
let space = if name.eq_ignore_ascii_case("model") {
Space::Model
} else {
let l = s.doc()?.layout(name).ok_or_else(|| bad("layout.set", format!("no layout `{name}`")))?;
Space::Paper(l.name.clone())
};
let st = s.state_mut()?;
st.space = space.clone();
st.selection.clear();
if let Space::Paper(n) = &space
&& !st.views.iter().any(|(sp, _)| sp == &space)
{
// Default paper view: the sheet.
let page = st.doc.layout(n).map(|l| l.page.clone()).unwrap_or_default();
let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) };
let unit = if st.doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 };
st.set_view_quiet(View { center: Vec2::new(w * unit / 2.0, h * unit / 2.0), height: h * unit * 1.15 });
}
s.touch();
ok()
}
#[derive(Default)]
struct ZoomM {
window: bool,
first: Option<Vec2>,
}
impl Interactive for ZoomM {
fn name(&self) -> &'static str {
"ZOOM"
}
fn prompt(&self, _s: &Session) -> Prompt {
match (self.window, self.first) {
(false, None) => Prompt::new("Specify corner of window, enter a scale factor (nX or nXP)", Accept::POINT_OR_NUMBER)
.kw(&["All", "Center", "Dynamic", "Extents", "Previous", "Scale", "Window", "Object"])
.default("real time"),
(true, None) => Prompt::new("Specify first corner", Accept::POINT),
(_, Some(a)) => Prompt::new("Specify opposite corner", Accept::POINT).base(a),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Keyword(k) => {
let mode = match k.as_str() {
"All" => "all",
"Extents" => "extents",
"Previous" => "previous",
"Window" => {
self.window = true;
return Ok(Step::Continue);
}
"Object" => "object",
_ => "extents",
};
zoom(s, &json!({ "mode": mode }))?;
Ok(Step::Done)
}
Input::Point(p) => match self.first {
None => {
self.first = Some(p);
Ok(Step::Continue)
}
Some(a) => {
fit(s, Bounds2::new(a, p))?;
Ok(Step::Done)
}
},
Input::Text(t) => {
let tl = t.trim().to_ascii_lowercase();
let num = tl.trim_end_matches("xp").trim_end_matches('x');
let f = number(num)
.filter(|f| *f > 0.0)
.ok_or_else(|| crate::EngineError::Other("Requires a point, scale factor or option keyword.".into()))?;
if tl.ends_with('x') {
zoom(s, &json!({ "mode": "scale", "factor": f }))?;
} else {
// Plain number: scale relative to limits (approximation: like nX).
zoom(s, &json!({ "mode": "scale", "factor": f }))?;
}
Ok(Step::Done)
}
Input::Enter => Ok(Step::Done),
_ => Ok(Step::Continue),
}
}
fn preview(&self, _s: &Session, c: Vec2) -> Vec<cadcraft_doc::EntityKind> {
self.first.map(|a| vec![super::helpers::lwpoly(super::helpers::rect_vertices(a, c), true)]).unwrap_or_default()
}
}
#[derive(Default)]
struct PanM {
first: Option<Vec2>,
}
impl Interactive for PanM {
fn name(&self) -> &'static str {
"PAN"
}
fn prompt(&self, _s: &Session) -> Prompt {
match self.first {
None => Prompt::new("Specify base point or displacement (drag with the middle mouse button for realtime pan)", Accept::POINT),
Some(a) => Prompt::new("Specify second point", Accept::POINT).base(a),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match (self.first, i) {
(None, Input::Point(p)) => {
self.first = Some(p);
Ok(Step::Continue)
}
(Some(a), Input::Point(b)) => {
run_pan(s, &json!({ "from": [a.x, a.y], "to": [b.x, b.y] }))?;
Ok(Step::Done)
}
(_, Input::Enter) => Ok(Step::Done),
_ => Ok(Step::Continue),
}
}
}
+871
View File
@@ -0,0 +1,871 @@
//! The CADCraft engine.
//!
//! Every user-visible action is a command with a stable id (AutoCAD's command names in lower
//! case: `line`, `circle`, `zoom`, `layer`…, plus dotted ids for UI operations). Commands run two
//! ways: programmatically with JSON parameters ([`Session::execute`], no dialogs, used by the
//! control channel, MCP, CLI and scripts) and interactively through prompts ([`Session::start`],
//! [`Session::input`], [`Session::cmdline`]) exactly like typing at AutoCAD's command line.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
pub mod cmd;
pub mod prompt;
pub mod sample;
pub mod select;
pub mod snap;
pub mod sysvars;
pub mod units;
use std::sync::Arc;
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Space};
use cadcraft_geom::{Bounds2, Vec2};
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub use cadcraft_doc as doc;
pub use cadcraft_geom as geom;
pub use cadcraft_render as render;
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use prompt::{Accept, Input, Interactive, Prompt, Step};
#[derive(Debug, thiserror::Error)]
pub enum EngineError {
#[error("unknown command `{0}`")]
UnknownCommand(String),
#[error("command `{0}` is not available right now: {1}")]
Disabled(String, String),
#[error("invalid parameters for `{cmd}`: {msg}")]
BadParams { cmd: String, msg: String },
#[error("no active document")]
NoDocument,
#[error("{0}")]
Other(String),
/// A command panicked; the guard kept the drawing as it was (a bug: please report it).
#[error("internal error in `{0}` (the drawing was kept as it was): {1}")]
Internal(String, String),
}
impl From<cadcraft_doc::DocError> for EngineError {
fn from(e: cadcraft_doc::DocError) -> Self {
EngineError::Other(e.to_string())
}
}
pub type Result<T> = std::result::Result<T, EngineError>;
/// A 2D view of a space: world centre and visible height in drawing units.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct View {
pub center: Vec2,
pub height: f64,
}
impl Default for View {
fn default() -> Self {
View { center: Vec2::new(6.0, 4.5), height: 10.0 }
}
}
#[derive(Clone, Debug)]
pub struct Snapshot {
pub label: String,
pub doc: Arc<Drawing>,
pub selection: Vec<Handle>,
}
/// One open drawing.
#[derive(Clone, Debug)]
pub struct DocState {
pub doc: Arc<Drawing>,
pub undo: Vec<Snapshot>,
pub redo: Vec<Snapshot>,
pub selection: Vec<Handle>,
pub previous_selection: Vec<Handle>,
pub path: Option<String>,
pub title: String,
pub saved: Arc<Drawing>,
pub revision: u64,
pub space: Space,
pub views: Vec<(Space, View)>,
pub view_history: Vec<View>,
pub uid: u64,
}
static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
impl DocState {
pub fn new(doc: Drawing, title: &str, path: Option<String>) -> Self {
let doc = Arc::new(doc);
DocState {
saved: doc.clone(),
doc,
undo: Vec::new(),
redo: Vec::new(),
selection: Vec::new(),
previous_selection: Vec::new(),
path,
title: title.into(),
revision: 1,
space: Space::Model,
views: Vec::new(),
view_history: Vec::new(),
uid: NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
}
}
pub fn is_dirty(&self) -> bool {
!Arc::ptr_eq(&self.doc, &self.saved)
}
pub fn view(&self) -> View {
self.views.iter().find(|(s, _)| *s == self.space).map(|(_, v)| *v).unwrap_or_default()
}
pub fn set_view(&mut self, v: View) {
if !(v.center.is_finite() && v.height.is_finite() && v.height > 1e-12) {
return;
}
let old = self.view();
if old != v {
self.view_history.push(old);
if self.view_history.len() > 50 {
self.view_history.remove(0);
}
}
match self.views.iter_mut().find(|(s, _)| *s == self.space) {
Some((_, slot)) => *slot = v,
None => self.views.push((self.space.clone(), v)),
}
}
/// Set without recording view history (realtime pan/zoom frames).
pub fn set_view_quiet(&mut self, v: View) {
if !(v.center.is_finite() && v.height.is_finite() && v.height > 1e-12) {
return;
}
match self.views.iter_mut().find(|(s, _)| *s == self.space) {
Some((_, slot)) => *slot = v,
None => self.views.push((self.space.clone(), v)),
}
}
}
/// Session-level drafting settings (the AutoCAD system variables stored in the registry/profile).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Settings {
pub osmode: u32,
pub orthomode: bool,
pub polarmode: bool,
/// POLARANG (radians).
pub polarang: f64,
pub gridmode: bool,
pub snapmode: bool,
pub snapunit: Vec2,
pub gridunit: Vec2,
/// Major grid line every N minor lines (GRIDMAJOR).
pub gridmajor: u32,
pub dynmode: bool,
pub lwdisplay: bool,
pub transparency_display: bool,
pub selection_cycling: bool,
pub otrack: bool,
/// PICKBOX in pixels.
pub pickbox: f64,
/// APERTURE in pixels.
pub aperture: f64,
pub pickfirst: bool,
pub pickadd: bool,
pub gripsize: f64,
pub cursorsize: f64,
pub isodraft: bool,
pub annoallvisible: bool,
pub annoautoscale: bool,
}
impl Default for Settings {
fn default() -> Self {
Settings {
osmode: 4133,
orthomode: false,
polarmode: true,
polarang: std::f64::consts::FRAC_PI_2,
gridmode: true,
snapmode: false,
snapunit: Vec2::new(0.5, 0.5),
gridunit: Vec2::new(0.5, 0.5),
gridmajor: 5,
dynmode: true,
lwdisplay: false,
transparency_display: false,
selection_cycling: false,
otrack: true,
pickbox: 3.0,
aperture: 10.0,
pickfirst: true,
pickadd: true,
gripsize: 5.0,
cursorsize: 5.0,
isodraft: false,
annoallvisible: true,
annoautoscale: false,
}
}
}
/// An interactive command in progress.
pub struct Running {
pub id: String,
pub machine: Box<dyn Interactive>,
pub before: Arc<Drawing>,
pub selection_before: Vec<Handle>,
}
/// A pending window/crossing selection started by a click on empty space.
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub struct PendingWindow {
pub corner: Vec2,
pub during_command: bool,
}
/// The editor session: open drawings, settings, the running command and the command log.
pub struct Session {
pub docs: Vec<DocState>,
pub active: usize,
pub settings: Settings,
pub running: Option<Running>,
pub log: Vec<String>,
pub last_command: Option<String>,
/// LASTPOINT.
pub last_point: Vec2,
/// Cursor position in world coordinates (from the UI; used for direct distance entry).
pub cursor: Vec2,
/// Viewport size in pixels (from the UI; used for zoom and pick apertures).
pub viewport_px: (f64, f64),
pub clipboard: Vec<Entity>,
pub clipboard_base: Vec2,
pub pending_window: Option<PendingWindow>,
pub untitled_counter: u32,
}
impl Default for Session {
fn default() -> Self {
Session::new()
}
}
impl Session {
pub fn new() -> Self {
let mut s = Session::empty();
s.new_drawing(false);
s
}
/// A session with no open drawing (the Start tab).
pub fn empty() -> Self {
Session {
docs: Vec::new(),
active: 0,
settings: Settings::default(),
running: None,
log: Vec::new(),
last_command: None,
last_point: Vec2::ZERO,
cursor: Vec2::ZERO,
viewport_px: (1200.0, 800.0),
clipboard: Vec::new(),
clipboard_base: Vec2::ZERO,
pending_window: None,
untitled_counter: 0,
}
}
pub fn new_drawing(&mut self, metric: bool) -> usize {
self.untitled_counter += 1;
let d = if metric { Drawing::new_metric() } else { Drawing::new_imperial() };
let mut st = DocState::new(d, &format!("Drawing{}", self.untitled_counter), None);
st.set_view_quiet(if metric { View { center: Vec2::new(210.0, 148.5), height: 297.0 } } else { View::default() });
self.docs.push(st);
self.active = self.docs.len() - 1;
self.active
}
pub fn open_drawing(&mut self, d: Drawing, title: &str, path: Option<String>) -> usize {
let mut st = DocState::new(d, title, path);
let ext = st.doc.extents(&Space::Model);
if !ext.is_empty() {
st.set_view_quiet(View {
center: ext.center(),
height: (ext.height().max(ext.width() * self.viewport_px.1 / self.viewport_px.0.max(1.0)) * 1.1).max(1e-6),
});
}
self.docs.push(st);
self.active = self.docs.len() - 1;
self.active
}
pub fn state(&self) -> Result<&DocState> {
self.docs.get(self.active).ok_or(EngineError::NoDocument)
}
pub fn state_mut(&mut self) -> Result<&mut DocState> {
self.docs.get_mut(self.active).ok_or(EngineError::NoDocument)
}
pub fn doc(&self) -> Result<&Drawing> {
Ok(&self.state()?.doc)
}
/// Copy-on-write access to the drawing.
pub fn doc_mut(&mut self) -> Result<&mut Drawing> {
Ok(Arc::make_mut(&mut self.state_mut()?.doc))
}
pub fn space(&self) -> Space {
self.state().map(|s| s.space.clone()).unwrap_or_default()
}
pub fn selection(&self) -> Vec<Handle> {
self.state().map(|s| s.selection.clone()).unwrap_or_default()
}
pub fn set_selection(&mut self, sel: Vec<Handle>) {
if let Ok(st) = self.state_mut() {
let mut seen = std::collections::HashSet::new();
st.selection = sel.into_iter().filter(|h| seen.insert(*h)).collect();
}
}
/// Message on the command line history.
pub fn echo(&mut self, msg: impl Into<String>) {
let m = msg.into();
log::debug!("{m}");
self.log.push(m);
if self.log.len() > 5000 {
self.log.drain(..1000);
}
}
/// Common properties for new objects (CLAYER, CECOLOR, CELTYPE, CELWEIGHT, CELTSCALE).
pub fn current_common(&self) -> Common {
let Ok(d) = self.doc() else { return Common::default() };
let h = &d.header;
Common {
layer: h.str("CLAYER", "0"),
color: cadcraft_color::Color::from_aci(h.i64("CECOLOR", 256) as i16),
linetype: h.str("CELTYPE", "ByLayer"),
lineweight: cadcraft_doc::Lineweight::from_dxf(h.i64("CELWEIGHT", -1) as i16),
ltscale: h.f64("CELTSCALE", 1.0),
..Common::default()
}
}
/// Add an entity to the current space with current properties.
pub fn add_entity(&mut self, kind: EntityKind) -> Result<Handle> {
let common = self.current_common();
let space = self.space();
let true_color = self.doc()?.header.get("CECOLOR_RGB").and_then(|v| v.as_i64());
let mut common = common;
if let Some(rgb) = true_color {
common.color = cadcraft_color::Color::True(cadcraft_color::Rgb::from_u32(rgb as u32));
}
let h = self.doc_mut()?.add(&space, common, kind)?;
Ok(h)
}
/// World units per pixel at the current view.
pub fn pixel_size(&self) -> f64 {
let v = self.state().map(|s| s.view()).unwrap_or_default();
v.height / self.viewport_px.1.max(1.0)
}
// ---------------- programmatic execution ----------------
/// Run a command with JSON parameters (no dialogs). Records undo when the drawing changes.
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
(spec.enabled)(self).map_err(|m| EngineError::Disabled(spec.id.into(), m))?;
let before = self.state().ok().map(|s| (s.doc.clone(), s.selection.clone(), s.uid));
let run = spec.run;
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(self, params)));
let result = match result {
Ok(r) => r,
Err(p) => {
let msg =
p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_else(|| "panic".into());
// Restore the drawing as it was.
if let Some((doc, sel, uid)) = &before
&& let Some(st) = self.docs.iter_mut().find(|d| d.uid == *uid)
{
st.doc = doc.clone();
st.selection = sel.clone();
}
return Err(EngineError::Internal(id.into(), msg));
}
};
if spec.undoable
&& let Some((doc, sel, uid)) = before
&& let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid)
&& !Arc::ptr_eq(&doc, &st.doc)
{
st.undo.push(Snapshot { label: spec.label.to_string(), doc, selection: sel });
st.redo.clear();
st.revision += 1;
if st.undo.len() > 2000 {
st.undo.remove(0);
}
}
result
}
/// Bump the revision without an undo step (view-only or settings changes that redraw).
pub fn touch(&mut self) {
if let Ok(st) = self.state_mut() {
st.revision += 1;
}
}
// ---------------- interactive commands ----------------
/// Start a command by name or alias as if typed at the command line.
pub fn start(&mut self, name: &str) -> Result<()> {
let name = name.trim();
let (transparent, name) = match name.strip_prefix('\'') {
Some(n) => (true, n),
None => (false, name),
};
let lower = name.trim_start_matches(['_', '.', '-']).to_ascii_lowercase();
let id = cmd::resolve_alias(&lower);
let spec = find_command(&id).ok_or_else(|| EngineError::UnknownCommand(name.to_string()))?;
if transparent && spec.transparent && self.running.is_some() {
// Transparent commands (zoom, pan…) run without cancelling the active one.
if spec.interactive.is_none() {
self.echo(format!(">>{}", spec.label));
return self.execute(spec.id, &Value::Null).map(|_| ());
}
}
if self.running.is_some() {
self.cancel();
}
(spec.enabled)(self).map_err(|m| EngineError::Disabled(spec.id.into(), m))?;
self.last_command = Some(spec.id.to_string());
self.echo(format!("Command: {}", spec.id.to_ascii_uppercase()));
match spec.interactive {
Some(factory) => {
let machine = factory(self)?;
let st = self.state()?;
let before = st.doc.clone();
let selection_before = st.selection.clone();
self.running = Some(Running { id: spec.id.to_string(), machine, before, selection_before });
self.pending_window = None;
// Some commands complete immediately (e.g. ERASE with a pickfirst selection).
self.feed(None)?;
Ok(())
}
None => {
let r = self.execute(spec.id, &Value::Null)?;
if let Some(s) = r.as_str() {
self.echo(s.to_string());
} else if !r.is_null()
&& let Some(msg) = r.get("message").and_then(Value::as_str)
{
self.echo(msg.to_string());
}
Ok(())
}
}
}
/// Give an input to the running command. With no command running, `Enter` repeats the last
/// command (as in AutoCAD) and points do nothing.
pub fn input(&mut self, input: Input) -> Result<()> {
if self.running.is_none() {
if input == Input::Enter
&& let Some(last) = self.last_command.clone()
{
return self.start(&last);
}
return Ok(());
}
// Generic selection handling during "Select objects:" prompts.
let input = self.preprocess_selection(input)?;
match input {
Some(i) => self.feed(Some(i)),
None => Ok(()),
}
}
fn preprocess_selection(&mut self, input: Input) -> Result<Option<Input>> {
let Some(prompt) = self.current_prompt() else { return Ok(Some(input)) };
if !prompt.accept.select {
return Ok(Some(input));
}
let space = self.space();
match input {
Input::Point(p) => {
let ap = self.pixel_size() * self.settings.pickbox.max(1.0) * 1.5;
if let Some(pw) = self.pending_window.take() {
let crossing = p.x < pw.corner.x;
let hs = select::select_window(self.doc()?, &space, Bounds2::new(pw.corner, p), crossing);
return Ok(Some(Input::Pick(hs)));
}
match select::pick(self.doc()?, &space, p, ap) {
Some(h) => Ok(Some(Input::Pick(vec![h]))),
None => {
self.pending_window = Some(PendingWindow { corner: p, during_command: true });
Ok(None)
}
}
}
Input::Text(t) | Input::Keyword(t) => {
let tl = t.trim().to_ascii_lowercase();
let d = self.doc()?;
let store = d.space(&space);
let picked = match tl.as_str() {
"all" => store.map(|s| s.iter().filter(|e| d.is_visible(e)).map(|e| e.handle).collect()),
"l" | "last" => store.and_then(|s| s.last()).map(|e| vec![e.handle]),
"p" | "previous" => Some(self.state()?.previous_selection.clone()),
_ => None,
};
match picked {
Some(hs) => Ok(Some(Input::Pick(hs))),
None => Ok(Some(Input::Text(t))),
}
}
Input::Cancel => {
self.pending_window = None;
Ok(Some(Input::Cancel))
}
other => Ok(Some(other)),
}
}
fn feed(&mut self, input: Option<Input>) -> Result<()> {
let Some(mut run) = self.running.take() else { return Ok(()) };
let step = match input {
Some(Input::Cancel) => Ok(Step::Cancel),
Some(i) => {
if let Input::Point(p) = &i {
self.last_point = *p;
}
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run.machine.input(self, i)));
match r {
Ok(r) => r,
Err(_) => Err(EngineError::Internal(run.id.clone(), "panic".into())),
}
}
None => run.machine.begin(self),
};
match step {
Ok(Step::Continue) => {
self.running = Some(run);
Ok(())
}
Ok(Step::Done) => {
self.finish(run, false);
Ok(())
}
Ok(Step::Cancel) => {
self.echo("*Cancel*");
self.finish(run, true);
Ok(())
}
Err(EngineError::Internal(id, m)) => {
// Restore and end the command.
if let Ok(st) = self.state_mut() {
st.doc = run.before.clone();
}
self.echo(format!("Internal error in {id}: {m}"));
Err(EngineError::Internal(id, m))
}
Err(e) => {
// Invalid input: report and keep prompting (AutoCAD re-prompts).
self.echo(e.to_string());
self.running = Some(run);
Ok(())
}
}
}
fn finish(&mut self, run: Running, cancelled: bool) {
self.pending_window = None;
let label = find_command(&run.id).map(|c| c.label).unwrap_or("Command");
let _ = cancelled;
if let Ok(st) = self.state_mut()
&& !Arc::ptr_eq(&run.before, &st.doc)
{
st.undo.push(Snapshot { label: label.to_string(), doc: run.before, selection: run.selection_before });
st.redo.clear();
st.revision += 1;
}
}
/// Cancel the running command (Esc). With no command, clears the selection.
pub fn cancel(&mut self) {
if self.running.is_some() {
let _ = self.feed(Some(Input::Cancel));
} else {
self.pending_window = None;
self.set_selection(Vec::new());
}
}
pub fn current_prompt(&self) -> Option<Prompt> {
self.running.as_ref().map(|r| r.machine.prompt(self))
}
/// The text shown on the command line: the active prompt, or "Command:".
pub fn prompt_text(&self) -> String {
match &self.running {
Some(r) => format!("{} {}", r.id.to_ascii_uppercase(), r.machine.prompt(self).display()),
None => "Command:".into(),
}
}
/// Rubber-band preview entities for the cursor.
pub fn preview(&self, cursor: Vec2) -> Vec<Entity> {
let Some(r) = &self.running else { return Vec::new() };
let common = self.current_common();
r.machine.preview(self, cursor).into_iter().map(|k| Entity { handle: Handle(0), common: common.clone(), kind: k }).collect()
}
/// Process one line typed at the command line (Enter pressed).
pub fn cmdline(&mut self, text: &str) -> Result<()> {
let t = text.trim_end_matches(['\r', '\n']);
match &self.running {
None => {
let t = t.trim();
if t.is_empty() {
return self.input(Input::Enter);
}
// `cmd {json}`: programmatic call with parameters.
if let Some((name, json)) = t.split_once(' ')
&& json.trim_start().starts_with('{')
{
let params: Value =
serde_json::from_str(json.trim()).map_err(|e| EngineError::BadParams { cmd: name.into(), msg: e.to_string() })?;
let id = cmd::resolve_alias(&name.to_ascii_lowercase());
let r = self.execute(&id, &params)?;
if !r.is_null() {
self.echo(r.to_string());
}
return Ok(());
}
// Expressions like "LINE 0,0 5,5" in one line: first token is the command.
let mut parts = t.split_whitespace();
let name = parts.next().unwrap_or("");
self.start(name)?;
for rest in parts {
if self.running.is_none() {
break;
}
self.typed(rest)?;
}
Ok(())
}
Some(_) => {
// Space acts as Enter except where the prompt wants free text.
let text_prompt = self.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point && !p.accept.number);
if text_prompt || !t.contains(' ') {
return self.typed(t);
}
for tok in t.split_whitespace() {
if self.running.is_none() {
break;
}
self.typed(tok)?;
}
Ok(())
}
}
}
/// One token typed while a command runs.
fn typed(&mut self, t: &str) -> Result<()> {
let Some(prompt) = self.current_prompt() else { return Ok(()) };
let tt = t.trim();
if tt.is_empty() {
return self.input(Input::Enter);
}
// Transparent command.
if tt.starts_with('\'') {
return self.start(tt);
}
if let Some(k) = prompt.match_keyword(tt)
&& !(prompt.accept.number && tt.parse::<f64>().is_ok())
{
return self.input(Input::Keyword(k));
}
if prompt.accept.point {
if let Some(p) = prompt::parse_point(tt, self.last_point) {
return self.input(Input::Point(p));
}
// Direct distance entry along the rubber band.
if let (Some(base), Some(dist)) = (prompt.base, units::parse_distance(tt))
&& !prompt.accept.number
{
let mut c = self.cursor;
if self.settings.orthomode {
c = snap::ortho(base, c);
}
let dir = (c - base).normalized();
let dir = if dir == Vec2::ZERO { Vec2::X } else { dir };
return self.input(Input::Point(base + dir * dist));
}
}
self.input(Input::Text(tt.to_string()))
}
/// Run a script: one input per line; within a line, spaces separate inputs except at text
/// prompts (as AutoCAD scripts do).
pub fn script(&mut self, text: &str) -> Result<()> {
for line in text.lines() {
let line = line.trim_end();
if line.trim_start().starts_with(';') {
continue;
}
if line.is_empty() {
self.cmdline("")?;
continue;
}
let mut rest = line;
loop {
let text_prompt = self.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point);
if text_prompt || self.running.is_none() && rest.contains('{') {
self.cmdline(rest)?;
break;
}
match rest.split_once(' ') {
Some((tok, r)) => {
if self.running.is_none() {
self.start(tok)?;
} else {
self.typed(tok)?;
}
rest = r;
}
None => {
if self.running.is_none() {
self.start(rest)?;
} else {
self.typed(rest)?;
}
break;
}
}
}
}
Ok(())
}
// ---------------- undo ----------------
pub fn undo(&mut self) -> Result<Option<String>> {
let st = self.state_mut()?;
let Some(snap) = st.undo.pop() else { return Ok(None) };
let cur = Snapshot { label: snap.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() };
st.doc = snap.doc;
st.selection = Vec::new();
st.redo.push(cur);
st.revision += 1;
Ok(Some(snap.label))
}
pub fn redo(&mut self) -> Result<Option<String>> {
let st = self.state_mut()?;
let Some(snap) = st.redo.pop() else { return Ok(None) };
let cur = Snapshot { label: snap.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() };
st.doc = snap.doc;
st.selection = Vec::new();
st.undo.push(cur);
st.revision += 1;
Ok(Some(snap.label))
}
// ---------------- picking without a command ----------------
/// A click with no command running: pick/toggle objects or start a selection window.
pub fn idle_click(&mut self, p: Vec2, shift: bool) -> Result<()> {
let space = self.space();
if let Some(pw) = self.pending_window.take() {
let crossing = p.x < pw.corner.x;
let hs = select::select_window(self.doc()?, &space, Bounds2::new(pw.corner, p), crossing);
let mut sel = if shift { Vec::new() } else { self.selection() };
if shift {
let cur = self.selection();
sel = cur.into_iter().filter(|h| !hs.contains(h)).collect();
} else {
sel.extend(hs);
}
self.set_selection(sel);
return Ok(());
}
let ap = self.pixel_size() * self.settings.pickbox.max(1.0) * 1.5;
match select::pick(self.doc()?, &space, p, ap) {
Some(h) => {
let mut sel = self.selection();
if shift {
sel.retain(|x| *x != h);
} else if !sel.contains(&h) {
sel.push(h);
}
self.set_selection(sel);
}
None => self.pending_window = Some(PendingWindow { corner: p, during_command: false }),
}
Ok(())
}
/// Remember the selection used by a command as "Previous".
pub fn remember_selection(&mut self, sel: &[Handle]) {
if let Ok(st) = self.state_mut() {
st.previous_selection = sel.to_vec();
}
}
// ---------------- views ----------------
pub fn zoom_extents(&mut self) -> Result<()> {
let space = self.space();
let ext = self.doc()?.extents(&space);
let (w, h) = self.viewport_px;
let ext = if ext.is_empty() {
let d = self.doc()?;
let lo = d.header.point("LIMMIN").map(|p| p.xy()).unwrap_or(Vec2::ZERO);
let hi = d.header.point("LIMMAX").map(|p| p.xy()).unwrap_or(Vec2::new(12.0, 9.0));
Bounds2::new(lo, hi)
} else {
ext
};
let aspect = w / h.max(1.0);
let height = ext.height().max(ext.width() / aspect.max(1e-6)).max(1e-6) * 1.05;
self.state_mut()?.set_view(View { center: ext.center(), height });
Ok(())
}
/// Zoom by `factor` (> 1 zooms in) keeping `about` fixed on screen.
pub fn zoom_about(&mut self, factor: f64, about: Vec2) -> Result<()> {
if !(factor.is_finite() && factor > 0.0) {
return Ok(());
}
let st = self.state_mut()?;
let v = st.view();
let h = (v.height / factor).clamp(1e-9, 1e12);
let k = h / v.height;
let c = about + (v.center - about) * k;
st.set_view_quiet(View { center: c, height: h });
Ok(())
}
/// Serializable summary for inspect/automation.
pub fn summary(&self) -> Value {
let docs: Vec<Value> = self
.docs
.iter()
.enumerate()
.map(|(i, d)| {
serde_json::json!({
"index": i, "title": d.title, "path": d.path, "dirty": d.is_dirty(),
"entities": d.doc.entity_count(), "active": i == self.active, "revision": d.revision,
})
})
.collect();
serde_json::json!({
"documents": docs,
"prompt": self.prompt_text(),
"running": self.running.as_ref().map(|r| r.id.clone()),
"selection": self.selection().iter().map(|h| h.hex()).collect::<Vec<_>>(),
"settings": self.settings,
})
}
}
#[cfg(test)]
mod tests;
+200
View File
@@ -0,0 +1,200 @@
//! Interactive commands: prompts, inputs and the command-line coordinate grammar.
use cadcraft_doc::{EntityKind, Handle};
use cadcraft_geom::Vec2;
use serde::Serialize;
use crate::{Result, Session};
/// What the current prompt accepts.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Accept {
pub point: bool,
pub number: bool,
pub text: bool,
pub select: bool,
/// Enter is meaningful (ends the command or takes the default).
pub enter: bool,
}
impl Accept {
pub const POINT: Accept = Accept { point: true, number: false, text: false, select: false, enter: true };
pub const POINT_OR_NUMBER: Accept = Accept { point: true, number: true, text: false, select: false, enter: true };
pub const NUMBER: Accept = Accept { point: false, number: true, text: false, select: false, enter: true };
pub const TEXT: Accept = Accept { point: false, number: false, text: true, select: false, enter: true };
pub const SELECT: Accept = Accept { point: true, number: false, text: false, select: true, enter: true };
}
/// A prompt shown on the command line.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Prompt {
pub message: String,
/// Keyword options, written with their shortcut letters capitalised (e.g. "Undo", "Close").
pub keywords: Vec<String>,
pub default: Option<String>,
pub accept: Accept,
/// Rubber-band origin (for direct distance entry, ortho and polar).
pub base: Option<Vec2>,
}
impl Prompt {
pub fn new(message: impl Into<String>, accept: Accept) -> Self {
Prompt { message: message.into(), keywords: Vec::new(), default: None, accept, base: None }
}
pub fn kw(mut self, k: &[&str]) -> Self {
self.keywords = k.iter().map(|s| s.to_string()).collect();
self
}
pub fn base(mut self, p: Vec2) -> Self {
self.base = Some(p);
self
}
pub fn base_opt(mut self, p: Option<Vec2>) -> Self {
self.base = p;
self
}
pub fn default(mut self, d: impl Into<String>) -> Self {
self.default = Some(d.into());
self
}
/// "Specify next point or [Undo/Close] <default>:".
pub fn display(&self) -> String {
let mut s = self.message.clone();
if !self.keywords.is_empty() {
s.push_str(if self.message.is_empty() { "[" } else { " or [" });
s.push_str(&self.keywords.join("/"));
s.push(']');
}
if let Some(d) = &self.default {
s.push_str(&format!(" <{d}>"));
}
s.push(':');
s
}
/// Match typed text against keywords: full word or the capitalised shortcut, case-insensitive.
pub fn match_keyword(&self, text: &str) -> Option<String> {
let t = text.trim();
if t.is_empty() {
return None;
}
let tl = t.to_ascii_lowercase();
for k in &self.keywords {
let shortcut: String = k.chars().filter(|c| c.is_ascii_uppercase() || c.is_ascii_digit()).collect::<String>().to_ascii_lowercase();
let shortcut =
if shortcut.is_empty() { k.chars().next().map(|c| c.to_ascii_lowercase().to_string()).unwrap_or_default() } else { shortcut };
let kl = k.to_ascii_lowercase();
if tl == kl || tl == shortcut || (tl.len() >= shortcut.len() && kl.starts_with(&tl)) {
return Some(k.clone());
}
}
None
}
}
/// An input to the active command.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "kind", content = "value", rename_all = "camelCase")]
pub enum Input {
Point(Vec2),
Keyword(String),
/// Free text or a number/distance/angle to be parsed by the command.
Text(String),
/// Objects picked during a selection prompt.
Pick(Vec<Handle>),
Enter,
Cancel,
}
/// What happens after an input.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Step {
Continue,
Done,
Cancel,
}
/// A prompt-driven command.
pub trait Interactive: Send {
fn name(&self) -> &'static str;
fn prompt(&self, s: &Session) -> Prompt;
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step>;
/// Called once when the command starts (may finish at once, e.g. with a pickfirst selection).
fn begin(&mut self, _s: &mut Session) -> Result<Step> {
Ok(Step::Continue)
}
/// Rubber-band geometry for the cursor position.
fn preview(&self, _s: &Session, _cursor: Vec2) -> Vec<EntityKind> {
Vec::new()
}
}
/// Parse a typed point: `x,y[,z]`, `@dx,dy`, `@dist<angle`, `dist<angle`, `#x,y` (absolute).
/// Relative forms use `last`.
pub fn parse_point(text: &str, last: Vec2) -> Option<Vec2> {
let t = text.trim();
if t.is_empty() {
return None;
}
let (rel, body) = if let Some(b) = t.strip_prefix('@') {
(true, b.trim())
} else if let Some(b) = t.strip_prefix('#') {
(false, b.trim())
} else {
(false, t)
};
if rel && body.is_empty() {
return Some(last);
}
let p = if let Some((d, a)) = body.split_once('<') {
let dist = crate::units::parse_distance(d)?;
let ang = crate::units::parse_angle(a)?;
Vec2::from_angle(ang) * dist
} else {
let parts: Vec<&str> = body.split(',').collect();
if parts.len() < 2 || parts.len() > 3 {
return None;
}
let x = crate::units::parse_distance(parts.first()?)?;
let y = crate::units::parse_distance(parts.get(1)?)?;
if let Some(z) = parts.get(2) {
crate::units::parse_distance(z)?;
}
Vec2::new(x, y)
};
let r = if rel { last + p } else { p };
r.is_finite().then_some(r)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn points() {
let last = Vec2::new(10.0, 10.0);
assert_eq!(parse_point("3,4", last), Some(Vec2::new(3.0, 4.0)));
assert_eq!(parse_point("3,4,5", last), Some(Vec2::new(3.0, 4.0)));
assert_eq!(parse_point("@1,2", last), Some(Vec2::new(11.0, 12.0)));
assert!(parse_point("@5<90", last).unwrap().near(Vec2::new(10.0, 15.0), 1e-9));
assert!(parse_point("5<0", last).unwrap().near(Vec2::new(5.0, 0.0), 1e-9));
assert_eq!(parse_point("#1,1", last), Some(Vec2::new(1.0, 1.0)));
assert_eq!(parse_point("@", last), Some(last));
assert_eq!(parse_point("1", last), None);
assert_eq!(parse_point("a,b", last), None);
assert_eq!(parse_point("1,2,3,4", last), None);
}
#[test]
fn keywords() {
let p = Prompt::new("Specify next point", Accept::POINT).kw(&["Undo", "Close"]);
assert_eq!(p.display(), "Specify next point or [Undo/Close]:");
assert_eq!(p.match_keyword("u").as_deref(), Some("Undo"));
assert_eq!(p.match_keyword("CL").as_deref(), Some("Close"));
assert_eq!(p.match_keyword("x"), None);
let q = Prompt::new("", Accept::POINT).kw(&["3P", "2P", "Ttr"]);
assert_eq!(q.match_keyword("3p").as_deref(), Some("3P"));
assert_eq!(q.match_keyword("t").as_deref(), Some("Ttr"));
}
}
+271
View File
@@ -0,0 +1,271 @@
//! Sample drawings generated in code (original CADCraft content, used for demos and tests).
use cadcraft_color::Color;
use cadcraft_doc::{Common, DimKind, Dimension, Drawing, EntityKind, Hatch, HatchLoop, Layer, Lineweight, MText, Space, Text};
use cadcraft_geom::{PolyVertex, Vec2, Vec3, arc_to_bulge};
use crate::cmd::helpers::{arc, circle, line, lwpoly, rect_vertices, v3};
fn layer(name: &str, color: u8, lt: &str, lw: u16) -> Layer {
Layer { name: name.into(), color: Color::Index(color), linetype: lt.into(), lineweight: Lineweight::Mm100(lw), ..Layer::default() }
}
fn on(layer: &str) -> Common {
Common { layer: layer.into(), ..Common::default() }
}
fn dim(kind: DimKind, p13: Vec2, p14: Vec2, defpt: Vec2) -> EntityKind {
EntityKind::Dimension(Dimension {
kind,
defpt: v3(defpt),
text_mid: Vec3::ZERO,
p13: v3(p13),
p14: v3(p14),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: None,
})
}
fn text(at: Vec2, h: f64, s: &str) -> EntityKind {
EntityKind::Text(Text {
insert: v3(at),
align_pt: None,
height: h,
value: s.into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
})
}
/// A mechanical part drawing: a flanged mounting bracket in two views with dimensions,
/// centre lines, hidden lines, a section hatch and a title block. Units: inches.
pub fn bracket() -> Drawing {
let mut d = Drawing::new_imperial();
d.linetypes.extend(cadcraft_doc::library::standard_linetypes());
d.layers.extend([
layer("Outline", 7, "Continuous", 50),
layer("Center", 1, "CENTER", 18),
layer("Hidden", 2, "HIDDEN", 25),
layer("Dimensions", 4, "Continuous", 18),
layer("Hatch", 8, "Continuous", 13),
layer("Notes", 3, "Continuous", 18),
layer("Title", 7, "Continuous", 35),
]);
d.header.set_f64("LTSCALE", 0.5);
d.header.set_str("CLAYER", "Outline");
if let Some(ds) = d.dim_styles.first_mut() {
ds.arrow_size = 0.12;
ds.text_height = 0.14;
ds.decimals = 2;
ds.text_above = 1;
ds.text_gap = 0.05;
ds.ext_offset = 0.06;
ds.ext_extend = 0.1;
}
let m = Space::Model;
let mut add = |c: Common, k: EntityKind| {
let _ = d.add(&m, c, k);
};
// ---- Front view: plate 8 x 5 with filleted corners, origin (1, 1).
let (x0, y0, w, h, r) = (1.0, 1.0, 8.0, 5.0, 0.5);
let b = arc_to_bulge(std::f64::consts::FRAC_PI_2);
let outline = vec![
PolyVertex::new(Vec2::new(x0 + r, y0)),
PolyVertex::with_bulge(Vec2::new(x0 + w - r, y0), b),
PolyVertex::new(Vec2::new(x0 + w, y0 + r)),
PolyVertex::with_bulge(Vec2::new(x0 + w, y0 + h - r), b),
PolyVertex::new(Vec2::new(x0 + w - r, y0 + h)),
PolyVertex::with_bulge(Vec2::new(x0 + r, y0 + h), b),
PolyVertex::new(Vec2::new(x0, y0 + h - r)),
PolyVertex::with_bulge(Vec2::new(x0, y0 + r), b),
];
add(on("Outline"), lwpoly(outline, true));
// Bolt holes.
let holes = [Vec2::new(2.0, 2.0), Vec2::new(8.0, 2.0), Vec2::new(2.0, 5.0), Vec2::new(8.0, 5.0)];
for hc in holes {
add(on("Outline"), circle(hc, 0.3125));
add(on("Center"), line(hc - Vec2::X * 0.55, hc + Vec2::X * 0.55));
add(on("Center"), line(hc - Vec2::Y * 0.55, hc + Vec2::Y * 0.55));
}
// Central boss with bore.
let c = Vec2::new(5.0, 3.5);
add(on("Outline"), circle(c, 1.5));
add(on("Outline"), circle(c, 0.875));
add(on("Hidden"), circle(c, 1.125));
add(on("Center"), line(c - Vec2::X * 1.9, c + Vec2::X * 1.9));
add(on("Center"), line(c - Vec2::Y * 1.9, c + Vec2::Y * 1.9));
// Slot.
let slot = vec![
PolyVertex::new(Vec2::new(3.25, 1.6)),
PolyVertex::with_bulge(Vec2::new(6.75, 1.6), 1.0),
PolyVertex::new(Vec2::new(6.75, 1.1) + Vec2::Y * 0.0),
];
let _ = slot;
let slot = vec![
PolyVertex::new(Vec2::new(4.0, 1.5)),
PolyVertex::with_bulge(Vec2::new(6.0, 1.5), 1.0),
PolyVertex::new(Vec2::new(6.0, 1.9)),
PolyVertex::with_bulge(Vec2::new(4.0, 1.9), 1.0),
];
add(on("Outline"), lwpoly(slot, true));
// ---- Side view (section A-A) to the right: plate 0.5 thick + boss 1.5 tall.
let sx = 11.0;
let sec_plate = rect_vertices(Vec2::new(sx, y0), Vec2::new(sx + 0.5, y0 + h));
add(on("Outline"), lwpoly(sec_plate.clone(), true));
let boss = rect_vertices(Vec2::new(sx + 0.5, c.y - 1.5), Vec2::new(sx + 2.0, c.y + 1.5));
add(on("Outline"), lwpoly(boss.clone(), true));
// Bore (hidden in side view → shown as section void).
add(on("Outline"), line(Vec2::new(sx, c.y - 0.875), Vec2::new(sx + 2.0, c.y - 0.875)));
add(on("Outline"), line(Vec2::new(sx, c.y + 0.875), Vec2::new(sx + 2.0, c.y + 0.875)));
add(on("Center"), line(Vec2::new(sx - 0.4, c.y), Vec2::new(sx + 2.4, c.y)));
// Section hatch on the solid parts (two regions around the bore).
let hatch = |a: Vec2, bb: Vec2| {
EntityKind::Hatch(Hatch {
pattern: "ANSI31".into(),
solid: false,
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true }],
scale: 1.0,
angle: 0.0,
associative: false,
style: 0,
elevation: 0.0,
gradient: None,
origin: Vec2::ZERO,
background: None,
})
};
add(on("Hatch"), hatch(Vec2::new(sx, c.y + 0.875), Vec2::new(sx + 0.5, y0 + h)));
add(on("Hatch"), hatch(Vec2::new(sx, y0), Vec2::new(sx + 0.5, c.y - 0.875)));
add(on("Hatch"), hatch(Vec2::new(sx + 0.5, c.y + 0.875), Vec2::new(sx + 2.0, c.y + 1.5)));
add(on("Hatch"), hatch(Vec2::new(sx + 0.5, c.y - 1.5), Vec2::new(sx + 2.0, c.y - 0.875)));
// ---- Dimensions.
add(on("Dimensions"), dim(DimKind::Linear { rotation: 0.0 }, Vec2::new(x0, y0), Vec2::new(x0 + w, y0), Vec2::new(5.0, 0.35)));
add(
on("Dimensions"),
dim(DimKind::Linear { rotation: std::f64::consts::FRAC_PI_2 }, Vec2::new(x0, y0), Vec2::new(x0, y0 + h), Vec2::new(0.3, 3.5)),
);
add(on("Dimensions"), dim(DimKind::Linear { rotation: 0.0 }, Vec2::new(2.0, 5.0), Vec2::new(8.0, 5.0), Vec2::new(5.0, 6.6)));
add(on("Dimensions"), dim(DimKind::Linear { rotation: 0.0 }, Vec2::new(sx, y0 + h), Vec2::new(sx + 2.0, c.y + 1.5), Vec2::new(sx + 1.0, 6.6)));
add(
on("Dimensions"),
EntityKind::Dimension(Dimension {
kind: DimKind::Diameter,
defpt: v3(c + Vec2::from_angle(0.8) * 1.5),
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::ZERO,
p15: v3(c - Vec2::from_angle(0.8) * 1.5),
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: None,
}),
);
add(
on("Dimensions"),
EntityKind::Dimension(Dimension {
kind: DimKind::Radius,
defpt: v3(Vec2::new(8.0, 2.0)),
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::ZERO,
p15: v3(Vec2::new(8.0, 2.0) + Vec2::from_angle(-0.7) * 0.3125),
p16: Vec3::ZERO,
text: "4X <>".into(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: None,
}),
);
// ---- Notes and title block.
add(on("Notes"), text(Vec2::new(sx - 0.2, -0.3), 0.16, "SECTION A-A"));
add(on("Notes"), text(Vec2::new(4.1, -0.3), 0.16, "FRONT VIEW"));
add(
on("Notes"),
EntityKind::MText(MText { insert: v3(Vec2::new(14.2, 6.2)), height: 0.12, width: 3.4, attach: 1, rotation: 0.0, style: "Standard".into(), contents: "NOTES:\\P1. MATERIAL: 6061-T6 ALUMINUM.\\P2. BREAK ALL SHARP EDGES 0.02 MAX.\\P3. BORE %%c1.750 THRU, H7.\\P4. FINISH: CLEAR ANODIZE.".into(), line_spacing: 1.0 }),
);
let tb0 = Vec2::new(14.0, -0.5);
add(on("Title"), lwpoly(rect_vertices(tb0, tb0 + Vec2::new(4.0, 2.0)), true));
add(on("Title"), line(tb0 + Vec2::new(0.0, 1.2), tb0 + Vec2::new(4.0, 1.2)));
add(on("Title"), line(tb0 + Vec2::new(0.0, 0.6), tb0 + Vec2::new(4.0, 0.6)));
add(on("Title"), line(tb0 + Vec2::new(2.0, 0.0), tb0 + Vec2::new(2.0, 0.6)));
add(on("Title"), text(tb0 + Vec2::new(0.15, 1.5), 0.22, "MOUNTING BRACKET"));
add(on("Title"), text(tb0 + Vec2::new(0.15, 0.82), 0.12, "CADCRAFT SAMPLE DWG NO. CC-0001"));
add(on("Title"), text(tb0 + Vec2::new(0.15, 0.22), 0.12, "SCALE 1:1"));
add(on("Title"), text(tb0 + Vec2::new(2.15, 0.22), 0.12, "SHEET 1 OF 1"));
// Drawing border.
add(on("Title"), lwpoly(rect_vertices(Vec2::new(-0.5, -0.5), Vec2::new(18.0, 7.5)), true));
let _ = arc;
d
}
/// A small architectural floor plan (feet-inches, drawn in inches).
pub fn floor_plan() -> Drawing {
let mut d = Drawing::new_imperial();
d.linetypes.extend(cadcraft_doc::library::standard_linetypes());
d.layers.extend([
layer("A-WALL", 7, "Continuous", 50),
layer("A-DOOR", 3, "Continuous", 25),
layer("A-GLAZ", 4, "Continuous", 18),
layer("A-ANNO", 2, "Continuous", 18),
layer("A-FURN", 8, "Continuous", 13),
]);
d.header.set_i64("LUNITS", 4);
d.header.set_i64("LUPREC", 4);
let m = Space::Model;
let mut add = |c: Common, k: EntityKind| {
let _ = d.add(&m, c, k);
};
let ft = 12.0;
let t = 6.0;
// Outer walls 30' x 20'.
add(on("A-WALL"), lwpoly(rect_vertices(Vec2::ZERO, Vec2::new(30.0 * ft, 20.0 * ft)), true));
add(on("A-WALL"), lwpoly(rect_vertices(Vec2::new(t, t), Vec2::new(30.0 * ft - t, 20.0 * ft - t)), true));
// Interior wall.
add(on("A-WALL"), lwpoly(rect_vertices(Vec2::new(14.0 * ft, t), Vec2::new(14.0 * ft + 4.0, 20.0 * ft - t)), true));
// Door swing.
let hinge = Vec2::new(14.0 * ft + 4.0, 6.0 * ft);
add(on("A-DOOR"), line(hinge, hinge + Vec2::X * 36.0));
add(on("A-DOOR"), arc(&cadcraft_geom::Arc::new(hinge, 36.0, 0.0, std::f64::consts::FRAC_PI_2)));
// Windows.
for x in [5.0, 20.0] {
add(on("A-GLAZ"), line(Vec2::new(x * ft, 0.0), Vec2::new(x * ft + 48.0, 0.0)));
add(on("A-GLAZ"), line(Vec2::new(x * ft, t), Vec2::new(x * ft + 48.0, t)));
add(on("A-GLAZ"), line(Vec2::new(x * ft, t / 2.0), Vec2::new(x * ft + 48.0, t / 2.0)));
}
add(on("A-ANNO"), text(Vec2::new(5.0 * ft, 10.0 * ft), 9.0, "LIVING ROOM"));
add(on("A-ANNO"), text(Vec2::new(19.0 * ft, 10.0 * ft), 9.0, "BEDROOM"));
add(on("A-ANNO"), dim(DimKind::Linear { rotation: 0.0 }, Vec2::ZERO, Vec2::new(30.0 * ft, 0.0), Vec2::new(15.0 * ft, -3.0 * ft)));
// Furniture.
add(on("A-FURN"), lwpoly(rect_vertices(Vec2::new(20.0 * ft, 14.0 * ft), Vec2::new(25.0 * ft, 19.0 * ft)), true));
add(on("A-FURN"), circle(Vec2::new(7.0 * ft, 14.0 * ft), 24.0));
d
}
/// The sample used by `--sample`.
pub fn default_sample() -> Drawing {
bracket()
}
pub fn _unused() -> EntityKind {
line(Vec2::ZERO, Vec2::X)
}
+176
View File
@@ -0,0 +1,176 @@
//! Hit testing and window/crossing selection.
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, Prim, Space, entity_bounds};
use cadcraft_geom::{Bounds2, Line, Vec2};
/// Polylines approximating an entity for hit testing, tessellated at `tol`.
pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
match &e.kind {
EntityKind::Text(_)
| EntityKind::MText(_)
| EntityKind::Insert(_)
| EntityKind::Dimension(_)
| EntityKind::AttDef(_)
| EntityKind::Table(_)
| EntityKind::MLeader(_)
| EntityKind::Image(_) => {
// Text-like objects are hit inside their box.
let b = entity_bounds(d, e, 0);
if b.is_empty() {
return Vec::new();
}
let c = b.corners();
let mut v = vec![vec![c[0], c[1], c[2], c[3], c[0]]];
if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::Insert(_) | EntityKind::MLeader(_)) {
let list = cadcraft_render::build_entities(
d,
std::iter::once(e),
&cadcraft_render::Options { tolerance: tol, text: false, ..Default::default() },
);
v = list.prims.iter().map(|p| list.points(p).to_vec()).collect();
v.push(vec![c[0], c[1], c[2], c[3], c[0]]);
}
v
}
kind => {
let mut out = Vec::new();
for p in kind.prims() {
let mut pts = Vec::new();
match p {
Prim::Seg(s) => s.tessellate(tol, &mut pts),
Prim::Circle(c) => c.tessellate(tol, &mut pts),
Prim::Ellipse(el) => el.tessellate(tol, &mut pts),
Prim::Spline(s) => pts = s.tessellate(tol),
Prim::Point(p) => pts = vec![p, p],
Prim::Infinite { base, dir, ray } => {
let far = 1e9;
pts = vec![if ray { base } else { base - dir * far }, base + dir * far];
}
Prim::Fill(f) => {
pts = f.clone();
if let Some(first) = f.first() {
pts.push(*first);
}
}
}
out.push(pts);
}
out
}
}
}
fn dist_to_polyline(pts: &[Vec2], p: Vec2) -> f64 {
if pts.len() == 1 {
return pts.first().map(|q| q.dist(p)).unwrap_or(f64::INFINITY);
}
pts.windows(2).filter_map(|w| Some(Line::new(*w.first()?, *w.get(1)?).dist(p))).fold(f64::INFINITY, f64::min)
}
/// Distance from `p` to the entity (0 inside text boxes and solid fills).
pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 {
let polys = hit_polylines(d, e, tol);
let mut best = polys.iter().map(|pl| dist_to_polyline(pl, p)).fold(f64::INFINITY, f64::min);
let filled = matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Solid(_) | EntityKind::Table(_))
|| matches!(&e.kind, EntityKind::Hatch(h) if h.solid);
if filled && entity_bounds(d, e, 0).contains(p) {
best = 0.0;
}
best
}
fn selectable(d: &Drawing, e: &Entity) -> bool {
d.is_visible(e)
}
/// The topmost entity within `aperture` of `p`.
pub fn pick(d: &Drawing, space: &Space, p: Vec2, aperture: f64) -> Option<Handle> {
let store = d.space(space)?;
let probe = Bounds2::new(p, p).expand(aperture);
let mut best: Option<(f64, Handle)> = None;
let ents: Vec<_> = store.iter().collect();
for e in ents.iter().rev() {
if !selectable(d, e) {
continue;
}
let infinite = matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_));
if !infinite && !entity_bounds(d, e, 0).expand(aperture).intersects(&probe) {
continue;
}
let dist = entity_distance(d, e, p, aperture / 4.0);
if dist <= aperture && best.is_none_or(|(bd, _)| dist < bd - 1e-12) {
best = Some((dist, e.handle));
if dist == 0.0 {
break;
}
}
}
best.map(|(_, h)| h)
}
fn seg_hits_box(a: Vec2, b: Vec2, bx: &Bounds2) -> bool {
if bx.contains(a) || bx.contains(b) {
return true;
}
let c = bx.corners();
(0..4).any(|i| cadcraft_geom::line_line(&Line::new(a, b), &Line::new(c[i], c[(i + 1) % 4])).is_some())
}
/// Window selection (entirely inside) or crossing selection (inside or touching).
pub fn select_window(d: &Drawing, space: &Space, bx: Bounds2, crossing: bool) -> Vec<Handle> {
let Some(store) = d.space(space) else { return Vec::new() };
let tol = (bx.width() + bx.height()).max(1e-9) / 2000.0;
let mut out = Vec::new();
for e in store.iter() {
if !selectable(d, e) {
continue;
}
let infinite = matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_));
let eb = entity_bounds(d, e, 0);
if !infinite && bx.contains_box(&eb) {
out.push(e.handle);
continue;
}
if !crossing || (!infinite && !eb.intersects(&bx)) {
continue;
}
let polys = hit_polylines(d, e, tol);
let hit = polys.iter().any(|pl| {
if pl.len() == 1 {
pl.first().is_some_and(|p| bx.contains(*p))
} else {
pl.windows(2).any(|w| w.first().zip(w.get(1)).is_some_and(|(a, b)| seg_hits_box(*a, *b, &bx)))
}
});
// A crossing box entirely inside a filled/text object also selects it.
if hit || (eb.contains_box(&bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Insert(_))) {
out.push(e.handle);
}
}
out
}
/// Fence selection: entities crossed by the fence polyline.
pub fn select_fence(d: &Drawing, space: &Space, fence: &[Vec2]) -> Vec<Handle> {
let Some(store) = d.space(space) else { return Vec::new() };
let fb = Bounds2::from_points(fence.iter().copied());
let tol = (fb.width() + fb.height()).max(1e-9) / 2000.0;
let mut out = Vec::new();
for e in store.iter() {
if !selectable(d, e) || !entity_bounds(d, e, 0).intersects(&fb.expand(tol)) {
continue;
}
let polys = hit_polylines(d, e, tol);
let hit = fence.windows(2).any(|f| {
let (Some(a), Some(b)) = (f.first(), f.get(1)) else { return false };
let fl = Line::new(*a, *b);
polys.iter().any(|pl| {
pl.windows(2).any(|w| w.first().zip(w.get(1)).is_some_and(|(p, q)| cadcraft_geom::line_line(&fl, &Line::new(*p, *q)).is_some()))
})
});
if hit {
out.push(e.handle);
}
}
out
}
+389
View File
@@ -0,0 +1,389 @@
//! Object snaps (OSNAP), polar tracking and ortho.
use cadcraft_doc::{Drawing, EntityKind, Prim, Space, entity_bounds};
use cadcraft_geom::{Bounds2, Circle, PI, Segment, Vec2, intersect_ext};
use serde::Serialize;
/// OSMODE bits.
pub mod mode {
pub const END: u32 = 1;
pub const MID: u32 = 2;
pub const CEN: u32 = 4;
pub const NOD: u32 = 8;
pub const QUA: u32 = 16;
pub const INT: u32 = 32;
pub const INS: u32 = 64;
pub const PER: u32 = 128;
pub const TAN: u32 = 256;
pub const NEA: u32 = 512;
pub const GCEN: u32 = 1024;
pub const APP: u32 = 2048;
pub const EXT: u32 = 4096;
pub const PAR: u32 = 8192;
/// Running snaps temporarily off (F3).
pub const OFF: u32 = 16384;
pub const ALL: [(u32, &str); 14] = [
(END, "Endpoint"),
(MID, "Midpoint"),
(CEN, "Center"),
(GCEN, "Geometric Center"),
(NOD, "Node"),
(QUA, "Quadrant"),
(INT, "Intersection"),
(EXT, "Extension"),
(INS, "Insertion"),
(PER, "Perpendicular"),
(TAN, "Tangent"),
(NEA, "Nearest"),
(APP, "Apparent Intersection"),
(PAR, "Parallel"),
];
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SnapHit {
pub point: Vec2,
pub mode: u32,
pub name: &'static str,
}
fn name_of(m: u32) -> &'static str {
mode::ALL.iter().find(|(b, _)| *b == m).map(|(_, n)| *n).unwrap_or("Snap")
}
fn prim_segments(p: &Prim) -> Vec<Segment> {
match p {
Prim::Seg(s) => vec![*s],
Prim::Circle(c) => vec![Segment::Arc { arc: cadcraft_geom::Arc::new(c.center, c.radius, 0.0, 0.0), ccw: true }],
Prim::Infinite { base, dir, .. } => vec![Segment::Line(cadcraft_geom::Line::new(*base - *dir * 1e7, *base + *dir * 1e7))],
Prim::Ellipse(e) => {
let mut pts = Vec::new();
e.tessellate(e.major.len() * 1e-3, &mut pts);
pts.windows(2).filter_map(|w| Some(Segment::Line(cadcraft_geom::Line::new(*w.first()?, *w.get(1)?)))).collect()
}
Prim::Spline(s) => {
let pts = s.tessellate(1e-3);
pts.windows(2).filter_map(|w| Some(Segment::Line(cadcraft_geom::Line::new(*w.first()?, *w.get(1)?)))).collect()
}
Prim::Fill(f) => {
let n = f.len();
(0..n).filter_map(|i| Some(Segment::Line(cadcraft_geom::Line::new(*f.get(i)?, *f.get((i + 1) % n)?)))).collect()
}
Prim::Point(_) => Vec::new(),
}
}
/// Find the best object snap near `cursor` within `aperture` (world units).
pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>) -> Option<SnapHit> {
if osmode == 0 || osmode & mode::OFF != 0 {
return None;
}
let store = d.space(space)?;
let probe = Bounds2::new(cursor, cursor).expand(aperture);
let mut cands: Vec<(u32, Vec2)> = Vec::new();
let mut near_prims: Vec<Prim> = Vec::new();
let mut count = 0usize;
for e in store.iter() {
if !d.is_visible(e) {
continue;
}
let inf = matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_));
if !inf && !entity_bounds(d, e, 0).expand(aperture).intersects(&probe) {
continue;
}
count += 1;
if count > 2000 {
break;
}
if osmode & mode::INS != 0 {
match &e.kind {
EntityKind::Text(t) => cands.push((mode::INS, t.insert.xy())),
EntityKind::MText(t) => cands.push((mode::INS, t.insert.xy())),
EntityKind::Insert(i) => cands.push((mode::INS, i.insert.xy())),
_ => {}
}
}
if osmode & mode::END != 0
&& let EntityKind::Solid(s) | EntityKind::Trace(s) = &e.kind
{
cands.extend(s.corners.iter().map(|c| (mode::END, c.xy())));
}
for p in e.kind.prims() {
match &p {
Prim::Seg(s) => {
if osmode & mode::END != 0 {
cands.push((mode::END, s.start()));
cands.push((mode::END, s.end()));
}
if osmode & mode::MID != 0 {
cands.push((mode::MID, s.mid()));
}
if let Segment::Arc { arc, .. } = s {
if osmode & mode::CEN != 0 {
cands.push((mode::CEN, arc.center));
}
if osmode & mode::QUA != 0 {
for k in 0..4 {
let a = k as f64 * PI / 2.0;
if arc.contains_angle(a) {
cands.push((mode::QUA, Vec2::polar(arc.center, arc.radius, a)));
}
}
}
}
}
Prim::Circle(c) => {
if osmode & mode::CEN != 0 {
cands.push((mode::CEN, c.center));
}
if osmode & mode::QUA != 0 {
for k in 0..4 {
cands.push((mode::QUA, Vec2::polar(c.center, c.radius, k as f64 * PI / 2.0)));
}
}
}
Prim::Ellipse(el) => {
if osmode & mode::CEN != 0 {
cands.push((mode::CEN, el.center));
}
if osmode & mode::QUA != 0 {
for k in 0..4 {
cands.push((mode::QUA, el.at_param(k as f64 * PI / 2.0)));
}
}
if osmode & mode::END != 0 && !el.is_full() {
cands.push((mode::END, el.at_param(el.start)));
cands.push((mode::END, el.at_param(el.end)));
}
}
Prim::Spline(s) => {
if osmode & mode::END != 0 && !s.closed {
let (lo, hi) = s.domain();
cands.push((mode::END, s.eval(lo)));
cands.push((mode::END, s.eval(hi)));
}
}
Prim::Point(pt) => {
if osmode & mode::NOD != 0 && matches!(e.kind, EntityKind::Point(_)) {
cands.push((mode::NOD, *pt));
}
}
Prim::Infinite { base, .. } => {
if osmode & mode::END != 0 && matches!(e.kind, EntityKind::Ray(_)) {
cands.push((mode::END, *base));
}
}
Prim::Fill(_) => {}
}
near_prims.push(p);
}
if osmode & mode::GCEN != 0
&& let EntityKind::LwPolyline(pl) = &e.kind
&& pl.closed
{
let pts = cadcraft_geom::Polyline { vertices: pl.vertices.clone(), closed: true }.tessellate(aperture / 10.0);
if let Some(c) = centroid(&pts) {
cands.push((mode::GCEN, c));
}
}
}
// Intersections between nearby primitives.
if osmode & (mode::INT | mode::APP) != 0 {
let segs: Vec<Vec<Segment>> = near_prims.iter().take(200).map(prim_segments).collect();
for i in 0..segs.len() {
for j in i + 1..segs.len() {
for a in segs.get(i).into_iter().flatten() {
for b in segs.get(j).into_iter().flatten() {
for x in intersect_ext(&fix_circle(a), &fix_circle(b), false) {
if x.dist(cursor) <= aperture {
cands.push((mode::INT, x));
}
}
}
}
}
}
}
// Perpendicular / tangent from the base point.
if let Some(bp) = base {
for p in &near_prims {
if osmode & mode::PER != 0 {
match p {
Prim::Seg(Segment::Line(l)) => cands.push((mode::PER, l.project(bp))),
Prim::Seg(Segment::Arc { arc, .. }) => cands.push((mode::PER, Circle::new(arc.center, arc.radius).closest(bp))),
Prim::Circle(c) => cands.push((mode::PER, c.closest(bp))),
Prim::Infinite { base: b0, dir, .. } => cands.push((mode::PER, *b0 + *dir * (bp - *b0).dot(*dir))),
_ => {}
}
}
if osmode & mode::TAN != 0 {
let circ = match p {
Prim::Seg(Segment::Arc { arc, .. }) => Some(Circle::new(arc.center, arc.radius)),
Prim::Circle(c) => Some(*c),
_ => None,
};
if let Some(c) = circ {
cands.extend(c.tangent_points(bp).into_iter().map(|t| (mode::TAN, t)));
}
}
}
}
let best = cands.iter().filter(|(_, p)| p.dist(cursor) <= aperture).min_by(|a, b| {
// Prefer more specific modes when nearly equidistant.
let da = a.1.dist(cursor) - if a.0 == mode::INT || a.0 == mode::END { aperture * 0.15 } else { 0.0 };
let db = b.1.dist(cursor) - if b.0 == mode::INT || b.0 == mode::END { aperture * 0.15 } else { 0.0 };
da.total_cmp(&db)
});
if let Some((m, p)) = best {
return Some(SnapHit { point: *p, mode: *m, name: name_of(*m) });
}
if osmode & mode::NEA != 0 {
let mut nb: Option<(f64, Vec2)> = None;
for p in &near_prims {
for s in prim_segments(p) {
let c = fix_circle(&s).closest(cursor);
let dd = c.dist(cursor);
if dd <= aperture && nb.is_none_or(|(bd, _)| dd < bd) {
nb = Some((dd, c));
}
}
if let Prim::Circle(c) = p {
let q = c.closest(cursor);
if q.dist(cursor) <= aperture {
nb = Some((q.dist(cursor), q));
}
}
}
if let Some((_, p)) = nb {
return Some(SnapHit { point: p, mode: mode::NEA, name: "Nearest" });
}
}
None
}
/// Full circles are stored as zero-sweep arcs in `prim_segments`; give them a full sweep.
fn fix_circle(s: &Segment) -> Segment {
match *s {
Segment::Arc { arc, ccw } if (arc.start - arc.end).abs() < 1e-15 => {
Segment::Arc { arc: cadcraft_geom::Arc { start: 0.0, end: cadcraft_geom::TAU - 1e-12, ..arc }, ccw }
}
other => other,
}
}
fn centroid(pts: &[Vec2]) -> Option<Vec2> {
let n = pts.len();
if n < 3 {
return None;
}
let mut a = 0.0;
let mut c = Vec2::ZERO;
for i in 0..n {
let (p, q) = (pts.get(i)?, pts.get((i + 1) % n)?);
let cr = p.cross(*q);
a += cr;
c += (*p + *q) * cr;
}
if a.abs() < 1e-12 { None } else { Some(c / (3.0 * a)) }
}
/// Constrain `p` relative to `base` to the nearest multiple of 90° (ortho).
pub fn ortho(base: Vec2, p: Vec2) -> Vec2 {
let d = p - base;
if d.x.abs() >= d.y.abs() { Vec2::new(p.x, base.y) } else { Vec2::new(base.x, p.y) }
}
/// Polar tracking: if the direction base→p is within `tol` radians of a multiple of `inc`,
/// return the point projected onto that ray and the angle.
pub fn polar(base: Vec2, p: Vec2, inc: f64, tol: f64) -> Option<(Vec2, f64)> {
if inc <= 1e-9 {
return None;
}
let d = p - base;
let len = d.len();
if len < 1e-12 {
return None;
}
let a = d.angle();
let k = (a / inc).round();
let snapped = k * inc;
if (a - snapped).abs() <= tol {
let dir = Vec2::from_angle(snapped);
Some((base + dir * d.dot(dir), cadcraft_geom::norm_angle(snapped)))
} else {
None
}
}
/// Grid snap.
pub fn grid_snap(p: Vec2, unit: Vec2, origin: Vec2) -> Vec2 {
let sx = if unit.x > 1e-12 { ((p.x - origin.x) / unit.x).round() * unit.x + origin.x } else { p.x };
let sy = if unit.y > 1e-12 { ((p.y - origin.y) / unit.y).round() * unit.y + origin.y } else { p.y };
Vec2::new(sx, sy)
}
#[cfg(test)]
mod tests {
use super::*;
use cadcraft_doc::{Common, Line};
use cadcraft_geom::Vec3;
fn drawing() -> Drawing {
let mut d = Drawing::new_imperial();
let l = |a: (f64, f64), b: (f64, f64)| EntityKind::Line(Line { a: Vec3::new(a.0, a.1, 0.0), b: Vec3::new(b.0, b.1, 0.0) });
d.add(&Space::Model, Common::default(), l((0.0, 0.0), (10.0, 0.0))).unwrap();
d.add(&Space::Model, Common::default(), l((5.0, -5.0), (5.0, 5.0))).unwrap();
d.add(&Space::Model, Common::default(), EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::new(20.0, 0.0, 0.0), radius: 2.0 })).unwrap();
d
}
#[test]
fn endpoint_and_mid() {
let d = drawing();
let h = osnap(&d, &Space::Model, Vec2::new(9.8, 0.1), 0.5, mode::END | mode::MID, None).unwrap();
assert_eq!(h.point, Vec2::new(10.0, 0.0));
let m = osnap(&d, &Space::Model, Vec2::new(5.1, 0.1), 0.5, mode::MID, None).unwrap();
assert_eq!(m.point, Vec2::new(5.0, 0.0));
}
#[test]
fn intersection() {
let d = drawing();
let h = osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, mode::INT, None).unwrap();
assert!(h.point.near(Vec2::new(5.0, 0.0), 1e-9));
assert_eq!(h.name, "Intersection");
}
#[test]
fn center_quadrant_tangent() {
let d = drawing();
assert_eq!(osnap(&d, &Space::Model, Vec2::new(20.1, 0.1), 0.5, mode::CEN, None).unwrap().point, Vec2::new(20.0, 0.0));
assert!(osnap(&d, &Space::Model, Vec2::new(20.0, 2.1), 0.5, mode::QUA, None).unwrap().point.near(Vec2::new(20.0, 2.0), 1e-9));
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)));
assert!(t.is_some());
}
#[test]
fn perpendicular_from_base() {
let d = drawing();
let h = osnap(&d, &Space::Model, Vec2::new(3.0, 0.2), 0.5, mode::PER, Some(Vec2::new(3.0, 4.0))).unwrap();
assert!(h.point.near(Vec2::new(3.0, 0.0), 1e-9));
}
#[test]
fn ortho_and_polar() {
assert_eq!(ortho(Vec2::ZERO, Vec2::new(5.0, 1.0)), Vec2::new(5.0, 0.0));
assert_eq!(ortho(Vec2::ZERO, Vec2::new(1.0, 5.0)), Vec2::new(0.0, 5.0));
let (p, a) = polar(Vec2::ZERO, Vec2::new(5.0, 5.1), 45f64.to_radians(), 3f64.to_radians()).unwrap();
assert!((a - PI / 4.0).abs() < 1e-12);
assert!((p.x - p.y).abs() < 1e-9);
assert_eq!(grid_snap(Vec2::new(0.74, 1.26), Vec2::new(0.5, 0.5), Vec2::ZERO), Vec2::new(0.5, 1.5));
}
#[test]
fn off_bit_disables() {
let d = drawing();
assert!(osnap(&d, &Space::Model, Vec2::new(9.8, 0.1), 0.5, mode::END | mode::OFF, None).is_none());
}
}
+157
View File
@@ -0,0 +1,157 @@
//! System variables: session settings plus drawing header variables, by name.
use serde_json::{Value, json};
use crate::{EngineError, Result, Session};
const SESSION_VARS: &[&str] = &[
"OSMODE",
"ORTHOMODE",
"POLARMODE",
"POLARANG",
"GRIDMODE",
"SNAPMODE",
"SNAPUNIT",
"GRIDUNIT",
"GRIDMAJOR",
"DYNMODE",
"LWDISPLAY",
"PICKBOX",
"APERTURE",
"PICKFIRST",
"PICKADD",
"GRIPSIZE",
"CURSORSIZE",
"LASTPOINT",
];
pub fn get(s: &Session, name: &str) -> Option<Value> {
let n = name.trim().to_ascii_uppercase();
let st = &s.settings;
let v = match n.as_str() {
"OSMODE" => json!(st.osmode),
"ORTHOMODE" => json!(i32::from(st.orthomode)),
"POLARMODE" => json!(i32::from(st.polarmode)),
"POLARANG" => json!(st.polarang.to_degrees()),
"GRIDMODE" => json!(i32::from(st.gridmode)),
"SNAPMODE" => json!(i32::from(st.snapmode)),
"SNAPUNIT" => json!([st.snapunit.x, st.snapunit.y]),
"GRIDUNIT" => json!([st.gridunit.x, st.gridunit.y]),
"GRIDMAJOR" => json!(st.gridmajor),
"DYNMODE" => json!(i32::from(st.dynmode)),
"LWDISPLAY" => json!(i32::from(st.lwdisplay)),
"PICKBOX" => json!(st.pickbox),
"APERTURE" => json!(st.aperture),
"PICKFIRST" => json!(i32::from(st.pickfirst)),
"PICKADD" => json!(i32::from(st.pickadd)),
"GRIPSIZE" => json!(st.gripsize),
"CURSORSIZE" => json!(st.cursorsize),
"LASTPOINT" => json!([s.last_point.x, s.last_point.y, 0.0]),
"CMDNAMES" => json!(s.running.as_ref().map(|r| r.id.to_ascii_uppercase()).unwrap_or_default()),
"DWGNAME" => json!(s.state().map(|d| d.title.clone()).unwrap_or_default()),
"DBMOD" => json!(s.state().map(|d| i32::from(d.is_dirty())).unwrap_or(0)),
"CTAB" => json!(
s.state()
.map(|d| match &d.space {
cadcraft_doc::Space::Model => "Model".to_string(),
cadcraft_doc::Space::Paper(n) => n.clone(),
})
.unwrap_or_default()
),
"VIEWCTR" => {
let v = s.state().ok()?.view();
json!([v.center.x, v.center.y, 0.0])
}
"VIEWSIZE" => json!(s.state().ok()?.view().height),
"EXTMIN" | "EXTMAX" => {
let d = s.doc().ok()?;
let e = d.extents(&s.space());
let p = if n == "EXTMIN" { e.min } else { e.max };
json!([p.x, p.y, 0.0])
}
_ => {
let h = s.doc().ok()?.header.get(&n)?;
serde_json::to_value(h).ok()?
}
};
Some(v)
}
fn as_bool(v: &Value) -> Option<bool> {
v.as_bool().or_else(|| v.as_i64().map(|i| i != 0)).or_else(|| v.as_str().and_then(|s| s.trim().parse::<i64>().ok()).map(|i| i != 0))
}
fn as_f64(v: &Value) -> Option<f64> {
v.as_f64().or_else(|| v.as_str().and_then(crate::units::parse_distance)).filter(|f| f.is_finite())
}
fn as_pt(v: &Value) -> Option<cadcraft_geom::Vec2> {
crate::cmd::point_value(v).or_else(|| as_f64(v).map(|f| cadcraft_geom::Vec2::new(f, f)))
}
pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
let n = name.trim().to_ascii_uppercase();
let bad = || EngineError::BadParams { cmd: "setvar".into(), msg: format!("invalid value for {n}") };
let st = &mut s.settings;
match n.as_str() {
"OSMODE" => st.osmode = v.as_u64().or_else(|| v.as_str().and_then(|s| s.trim().parse().ok())).ok_or_else(bad)? as u32 & 0x7fff,
"ORTHOMODE" => st.orthomode = as_bool(v).ok_or_else(bad)?,
"POLARMODE" => st.polarmode = as_bool(v).ok_or_else(bad)?,
"POLARANG" => st.polarang = as_f64(v).filter(|a| *a > 0.0).ok_or_else(bad)?.to_radians(),
"GRIDMODE" => st.gridmode = as_bool(v).ok_or_else(bad)?,
"SNAPMODE" => st.snapmode = as_bool(v).ok_or_else(bad)?,
"SNAPUNIT" => st.snapunit = as_pt(v).filter(|p| p.x > 0.0 && p.y > 0.0).ok_or_else(bad)?,
"GRIDUNIT" => st.gridunit = as_pt(v).filter(|p| p.x > 0.0 && p.y > 0.0).ok_or_else(bad)?,
"GRIDMAJOR" => st.gridmajor = as_f64(v).ok_or_else(bad)?.clamp(1.0, 100.0) as u32,
"DYNMODE" => st.dynmode = as_bool(v).ok_or_else(bad)?,
"LWDISPLAY" => st.lwdisplay = as_bool(v).ok_or_else(bad)?,
"PICKBOX" => st.pickbox = as_f64(v).ok_or_else(bad)?.clamp(0.0, 50.0),
"APERTURE" => st.aperture = as_f64(v).ok_or_else(bad)?.clamp(1.0, 50.0),
"PICKFIRST" => st.pickfirst = as_bool(v).ok_or_else(bad)?,
"PICKADD" => st.pickadd = as_bool(v).ok_or_else(bad)?,
"GRIPSIZE" => st.gripsize = as_f64(v).ok_or_else(bad)?.clamp(1.0, 255.0),
"CURSORSIZE" => st.cursorsize = as_f64(v).ok_or_else(bad)?.clamp(1.0, 100.0),
_ => {
let d = s.doc_mut()?;
let val = match v {
Value::Number(x) if x.is_i64() => cadcraft_doc::HVal::Int(x.as_i64().unwrap_or(0)),
Value::Number(x) => cadcraft_doc::HVal::Real(x.as_f64().filter(|f| f.is_finite()).ok_or_else(bad)?),
Value::String(t) => match t.trim().parse::<i64>() {
Ok(i) => cadcraft_doc::HVal::Int(i),
Err(_) => match t.trim().parse::<f64>() {
Ok(f) if f.is_finite() => cadcraft_doc::HVal::Real(f),
_ => cadcraft_doc::HVal::Str(t.clone()),
},
},
Value::Bool(b) => cadcraft_doc::HVal::Int(i64::from(*b)),
Value::Array(_) => cadcraft_doc::HVal::Point(as_pt(v).ok_or_else(bad)?.to3(0.0)),
_ => return Err(bad()),
};
// Keep the header type stable for known numeric vars.
if let Some(old) = d.header.get(&n)
&& matches!(old, cadcraft_doc::HVal::Real(_))
&& let Some(f) = val.as_f64()
{
d.header.set_f64(&n, f);
return Ok(());
}
d.header.set(&n, val);
}
}
Ok(())
}
pub fn list(s: &Session) -> Value {
let mut m = serde_json::Map::new();
for n in SESSION_VARS {
if let Some(v) = get(s, n) {
m.insert((*n).to_string(), v);
}
}
if let Ok(d) = s.doc() {
for (k, v) in &d.header.vars {
if !k.starts_with("CADCRAFT_") {
m.insert(k.clone(), serde_json::to_value(v).unwrap_or(Value::Null));
}
}
}
Value::Object(m)
}
+324
View File
@@ -0,0 +1,324 @@
use cadcraft_doc::EntityKind;
use cadcraft_geom::Vec2;
use serde_json::json;
use crate::*;
fn kinds(s: &Session) -> Vec<&'static str> {
s.doc().unwrap().model.iter().map(|e| e.kind.type_name()).collect()
}
#[test]
fn line_via_command_line() {
let mut s = Session::new();
s.cmdline("LINE").unwrap();
s.cmdline("0,0").unwrap();
s.cmdline("10,0").unwrap();
s.cmdline("@0,5").unwrap();
s.cmdline("c").unwrap();
assert!(s.running.is_none());
assert_eq!(kinds(&s), vec!["Line", "Line", "Line"]);
// One undo step for the whole command.
s.undo().unwrap();
assert_eq!(s.doc().unwrap().model.len(), 0);
s.redo().unwrap();
assert_eq!(s.doc().unwrap().model.len(), 3);
}
#[test]
fn line_undo_option_and_aliases() {
let mut s = Session::new();
s.cmdline("l 0,0 5,5 10,0 u").unwrap();
assert_eq!(s.doc().unwrap().model.len(), 1);
s.cmdline("").unwrap(); // Enter ends
assert!(s.running.is_none());
}
#[test]
fn polar_and_direct_distance() {
let mut s = Session::new();
s.cmdline("line 1,1").unwrap();
s.cursor = Vec2::new(100.0, 1.0);
s.cmdline("4").unwrap(); // direct distance along +X
s.cmdline("@3<90").unwrap();
s.cmdline("").unwrap();
let ends: Vec<_> = s.doc().unwrap().model.iter().map(|e| e.kind.grips()).collect();
assert!(ends[0][2].near(Vec2::new(5.0, 1.0), 1e-9));
assert!(ends[1][2].near(Vec2::new(5.0, 4.0), 1e-9));
}
#[test]
fn circle_variants() {
let mut s = Session::new();
s.cmdline("circle 0,0 5").unwrap();
s.cmdline("c 10,0 d 4").unwrap();
s.cmdline("circle 3p 0,0 2,2 4,0").unwrap();
s.cmdline("circle 2p 0,0 0,6").unwrap();
let d = s.doc().unwrap();
let radii: Vec<f64> = d.model.iter().filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some(c.radius) } else { None }).collect();
assert_eq!(radii.len(), 4);
assert!((radii[0] - 5.0).abs() < 1e-9);
assert!((radii[1] - 2.0).abs() < 1e-9);
assert!((radii[2] - 2.0).abs() < 1e-9);
assert!((radii[3] - 3.0).abs() < 1e-9);
}
#[test]
fn rectangle_polygon_and_pline() {
let mut s = Session::new();
s.cmdline("rectang 0,0 4,3").unwrap();
s.cmdline("polygon 6 10,10 i 2").unwrap();
s.cmdline("pline 0,0 5,0 a 5,5 l 0,5 c").unwrap();
let d = s.doc().unwrap();
let mut it = d.model.iter();
match &it.next().unwrap().kind {
EntityKind::LwPolyline(p) => assert_eq!(p.vertices.len(), 4),
_ => panic!(),
}
match &it.next().unwrap().kind {
EntityKind::LwPolyline(p) => assert_eq!(p.vertices.len(), 6),
_ => panic!(),
}
match &it.next().unwrap().kind {
EntityKind::LwPolyline(p) => {
assert!(p.closed);
assert!(p.vertices[1].bulge.abs() > 0.1, "arc segment has a bulge");
}
_ => panic!(),
}
}
#[test]
fn json_execute_and_errors() {
let mut s = Session::new();
let r = s.execute("circle", &json!({"center": [1, 2], "radius": 3})).unwrap();
assert!(r["handle"].is_string());
assert!(s.execute("circle", &json!({"center": [1, 2]})).is_err());
assert!(s.execute("circle", &json!("not an object")).is_err());
assert!(s.execute("nope", &json!({})).is_err());
// Bad params don't create undo steps.
assert_eq!(s.state().unwrap().undo.len(), 1);
}
#[test]
fn move_with_pickfirst_and_window_selection() {
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [1, 0]]})).unwrap();
s.execute("line", &json!({"points": [[5, 5], [6, 5]]})).unwrap();
s.viewport_px = (1000.0, 1000.0);
s.state_mut().unwrap().set_view(View { center: Vec2::new(3.0, 3.0), height: 10.0 });
// Window selection from left to right picks only the first line.
s.cmdline("move").unwrap();
s.input(Input::Point(Vec2::new(-1.0, -1.0))).unwrap();
s.input(Input::Point(Vec2::new(2.0, 1.0))).unwrap();
s.input(Input::Enter).unwrap();
s.cmdline("0,0").unwrap();
s.cmdline("10,0").unwrap();
assert!(s.running.is_none());
let g: Vec<_> = s.doc().unwrap().model.iter().map(|e| e.kind.grips()[0]).collect();
assert!(g[0].near(Vec2::new(10.0, 0.0), 1e-9));
assert!(g[1].near(Vec2::new(5.0, 5.0), 1e-9));
}
#[test]
fn erase_all_and_selection_keywords() {
let mut s = Session::new();
s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap();
s.execute("circle", &json!({"center": [5, 0], "radius": 1})).unwrap();
s.cmdline("erase").unwrap();
s.cmdline("all").unwrap();
s.cmdline("").unwrap();
assert_eq!(s.doc().unwrap().model.len(), 0);
}
#[test]
fn trim_line_between_edges() {
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.execute("line", &json!({"points": [[3, -2], [3, 2]]})).unwrap();
s.execute("line", &json!({"points": [[7, -2], [7, 2]]})).unwrap();
let h = s.doc().unwrap().model.iter().next().unwrap().handle;
s.execute("trim", &json!({"handle": h.hex(), "pick": [5, 0]})).unwrap();
let lines: Vec<_> = s
.doc()
.unwrap()
.model
.iter()
.filter(|e| matches!(&e.kind, EntityKind::Line(l) if l.a.y == 0.0 && l.b.y == 0.0))
.map(|e| e.kind.grips())
.collect();
assert_eq!(lines.len(), 2);
}
#[test]
fn extend_line_to_boundary() {
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [5, 0]]})).unwrap();
s.execute("line", &json!({"points": [[8, -2], [8, 2]]})).unwrap();
let h = s.doc().unwrap().model.iter().next().unwrap().handle;
s.execute("extend", &json!({"handle": h.hex(), "pick": [4.5, 0]})).unwrap();
let g = s.doc().unwrap().entity(h).unwrap().kind.grips();
assert!(g[2].near(Vec2::new(8.0, 0.0), 1e-9));
}
#[test]
fn fillet_two_lines() {
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
s.execute("line", &json!({"points": [[0, 0], [0, 10]]})).unwrap();
let hs: Vec<_> = s.doc().unwrap().model.handles();
let r = s.execute("fillet", &json!({"h1": hs[0].hex(), "p1": [5, 0], "h2": hs[1].hex(), "p2": [0, 5], "radius": 2})).unwrap();
assert!(r["arc"].is_string());
let g = s.doc().unwrap().entity(hs[0]).unwrap().kind.grips();
assert!(g[0].near(Vec2::new(10.0, 0.0), 1e-9) || g[2].near(Vec2::new(10.0, 0.0), 1e-9));
assert!(g.iter().any(|p| p.near(Vec2::new(2.0, 0.0), 1e-9)));
}
#[test]
fn offset_circle_and_polyline() {
let mut s = Session::new();
let c = s.execute("circle", &json!({"center": [0, 0], "radius": 5})).unwrap();
s.execute("offset", &json!({"handle": c["handle"], "distance": 1, "side": [0, 0]})).unwrap();
let r = s.execute("rectang", &json!({"p1": [0, 0], "p2": [10, 10]})).unwrap();
s.execute("offset", &json!({"handle": r["handle"], "distance": 1, "side": [5, 5]})).unwrap();
let d = s.doc().unwrap();
let last = d.model.last().unwrap();
match &last.kind {
EntityKind::LwPolyline(p) => {
let b = cadcraft_geom::Bounds2::from_points(p.vertices.iter().map(|v| v.p));
assert!(b.min.near(Vec2::new(1.0, 1.0), 1e-9), "{b:?}");
assert!(b.max.near(Vec2::new(9.0, 9.0), 1e-9));
}
_ => panic!(),
}
}
#[test]
fn copy_rotate_scale_mirror() {
let mut s = Session::new();
let l = s.execute("line", &json!({"points": [[0, 0], [1, 0]]})).unwrap();
let h = l["handles"][0].clone();
s.execute("copy", &json!({"handles": [h], "delta": [0, 2], "count": 3})).unwrap();
assert_eq!(s.doc().unwrap().model.len(), 4);
s.execute("rotate", &json!({"handles": [h], "base": [0, 0], "angle": 90})).unwrap();
s.execute("scale", &json!({"handles": [h], "base": [0, 0], "factor": 3})).unwrap();
let hh = cadcraft_doc::Handle::parse_hex(h.as_str().unwrap()).unwrap();
let g = s.doc().unwrap().entity(hh).unwrap().kind.grips();
assert!(g[2].near(Vec2::new(0.0, 3.0), 1e-9));
s.execute("mirror", &json!({"handles": [h], "p1": [-1, 0], "p2": [-1, 1]})).unwrap();
assert_eq!(s.doc().unwrap().model.len(), 5);
}
#[test]
fn layers_and_properties() {
let mut s = Session::new();
s.execute("layer.new", &json!({"name": "Walls", "color": "red", "current": true})).unwrap();
let c = s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap();
let h = cadcraft_doc::Handle::parse_hex(c["handle"].as_str().unwrap()).unwrap();
assert_eq!(s.doc().unwrap().entity(h).unwrap().common.layer, "Walls");
assert!(s.execute("layer.set", &json!({"name": "Walls", "frozen": true})).is_err());
s.execute("properties.set", &json!({"handles": [h.hex()], "color": 3, "radius": 4})).unwrap();
let e = s.doc().unwrap().entity(h).unwrap();
assert_eq!(e.common.color, cadcraft_color::Color::Index(3));
assert!(matches!(&e.kind, EntityKind::Circle(c) if c.radius == 4.0));
assert!(s.execute("layer.new", &json!({"name": "bad/name"})).is_err());
}
#[test]
fn zoom_extents_fits_drawing() {
let mut s = Session::new();
s.viewport_px = (1000.0, 500.0);
s.execute("line", &json!({"points": [[0, 0], [100, 10]]})).unwrap();
s.execute("zoom.extents", &json!({})).unwrap();
let v = s.state().unwrap().view();
assert!((v.center.x - 50.0).abs() < 1e-9);
assert!(v.height >= 50.0);
}
#[test]
fn sysvars_roundtrip() {
let mut s = Session::new();
s.execute("setvar", &json!({"name": "osmode", "value": 7})).unwrap();
assert_eq!(s.settings.osmode, 7);
s.execute("setvar", &json!({"name": "LTSCALE", "value": 2.5})).unwrap();
assert_eq!(s.doc().unwrap().header.f64("LTSCALE", 0.0), 2.5);
assert!(s.execute("setvar", &json!({"name": "ORTHOMODE", "value": "x"})).is_err());
assert_eq!(sysvars::get(&s, "orthomode"), Some(json!(0)));
}
#[test]
fn script_runs_commands() {
let mut s = Session::new();
s.script("LINE 0,0 10,0 10,10\n\nCIRCLE 5,5 2\nTEXT 0,-2 0.5 0 Hello world\n").unwrap();
assert_eq!(kinds(&s), vec!["Line", "Line", "Circle", "Text"]);
let t = s.doc().unwrap().model.last().unwrap();
assert!(matches!(&t.kind, EntityKind::Text(t) if t.value == "Hello world"));
}
#[test]
fn enter_repeats_last_command() {
let mut s = Session::new();
s.cmdline("circle 0,0 1").unwrap();
s.cmdline("").unwrap();
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("circle"));
s.cmdline("5,5 1").unwrap();
assert_eq!(s.doc().unwrap().model.len(), 2);
}
#[test]
fn cancel_keeps_partial_line_as_one_undo() {
let mut s = Session::new();
s.cmdline("line 0,0 1,0 2,0").unwrap();
s.cancel();
assert_eq!(s.doc().unwrap().model.len(), 2);
s.undo().unwrap();
assert_eq!(s.doc().unwrap().model.len(), 0);
}
#[test]
fn hostile_params_never_panic() {
let mut s = Session::new();
for c in command_specs() {
for p in [
json!(null),
json!([]),
json!("x"),
json!({"points": [[1e308, -1e308], ["a"]]}),
json!({"handles": ["zz", 99999]}),
json!({"radius": -1, "center": [0, 0]}),
] {
let _ = s.execute(c.id, &p);
}
}
}
#[test]
fn every_interactive_command_starts_and_cancels() {
for c in command_specs().iter().filter(|c| c.interactive.is_some()) {
let mut s = Session::new();
s.start(c.id).unwrap();
let _ = s.prompt_text();
let _ = s.preview(Vec2::new(1.0, 1.0));
s.input(Input::Point(Vec2::new(1.0, 2.0))).unwrap();
let _ = s.preview(Vec2::new(3.0, 1.0));
s.cancel();
assert!(s.running.is_none(), "{} still running", c.id);
}
}
#[test]
fn sample_drawing_builds() {
let d = sample::bracket();
assert!(d.model.len() > 30);
let l = cadcraft_render::build(&d, &cadcraft_doc::Space::Model, &cadcraft_render::Options::default());
assert!(l.prims.len() > 100);
}
#[test]
fn osnap_toggle() {
let mut s = Session::new();
s.execute("osnap", &json!({"modes": ["end", "mid", "cen"]})).unwrap();
assert_eq!(s.settings.osmode, 7);
s.execute("osnap", &json!({"on": false})).unwrap();
assert!(s.settings.osmode & snap::mode::OFF != 0);
}
+226
View File
@@ -0,0 +1,226 @@
//! Linear and angular unit formatting and parsing (LUNITS/LUPREC, AUNITS/AUPREC).
use std::f64::consts::PI;
/// Format a distance per LUNITS (1 scientific, 2 decimal, 3 engineering, 4 architectural,
/// 5 fractional) and LUPREC.
pub fn format_distance(v: f64, lunits: i64, luprec: i64) -> String {
if !v.is_finite() {
return "0".into();
}
let prec = luprec.clamp(0, 8) as usize;
match lunits {
1 => format!("{:.*E}", prec, v),
3 => {
let neg = v < 0.0;
let a = v.abs();
let ft = (a / 12.0).floor();
let inch = a - ft * 12.0;
format!("{}{}'-{:.*}\"", if neg { "-" } else { "" }, ft as i64, prec, inch)
}
4 => {
let neg = v < 0.0;
let a = v.abs();
let denom = 1i64 << prec.min(8);
let total = (a * denom as f64).round() as i64;
let ft = total / (12 * denom);
let rem = total - ft * 12 * denom;
let inch = rem / denom;
let frac = rem % denom;
let fs = if frac == 0 {
String::new()
} else {
let g = gcd(frac, denom);
format!(" {}/{}", frac / g, denom / g)
};
format!("{}{}'-{}{}\"", if neg { "-" } else { "" }, ft, inch, fs)
}
5 => {
let neg = v < 0.0;
let a = v.abs();
let denom = 1i64 << prec.min(8);
let total = (a * denom as f64).round() as i64;
let whole = total / denom;
let frac = total % denom;
let fs = if frac == 0 {
String::new()
} else {
let g = gcd(frac, denom);
format!(" {}/{}", frac / g, denom / g)
};
format!("{}{}{}", if neg { "-" } else { "" }, whole, fs)
}
_ => format!("{:.*}", prec, v),
}
}
fn gcd(a: i64, b: i64) -> i64 {
if b == 0 { a.abs().max(1) } else { gcd(b, a % b) }
}
/// Format an angle (radians) per AUNITS (0 decimal degrees, 1 deg/min/sec, 2 grads, 3 radians,
/// 4 surveyor's) and AUPREC.
pub fn format_angle(a: f64, aunits: i64, auprec: i64) -> String {
let prec = auprec.clamp(0, 8) as usize;
let deg = cadcraft_geom::norm_angle(a).to_degrees();
match aunits {
1 => {
let d = deg.floor();
let m = ((deg - d) * 60.0).floor();
let s = (deg - d - m / 60.0) * 3600.0;
format!("{}d{}'{:.*}\"", d as i64, m as i64, prec.saturating_sub(4), s)
}
2 => format!("{:.*}g", prec, deg / 0.9),
3 => format!("{:.*}r", prec, cadcraft_geom::norm_angle(a)),
4 => {
// N/S <angle from N/S toward E/W> E/W
let (ns, ew, ang) = if deg <= 90.0 {
("N", "E", 90.0 - deg)
} else if deg <= 180.0 {
("N", "W", deg - 90.0)
} else if deg <= 270.0 {
("S", "W", 270.0 - deg)
} else {
("S", "E", deg - 270.0)
};
format!("{ns} {:.*}d {ew}", prec, ang)
}
_ => format!("{:.*}", prec, deg),
}
}
/// Parse a distance typed by the user: decimal, `1'6"`, `1'-6 1/2"`, `6 1/2`, `3/4`, `1e3`.
pub fn parse_distance(s: &str) -> Option<f64> {
let t = s.trim();
if t.is_empty() {
return None;
}
if let Ok(v) = t.parse::<f64>() {
return v.is_finite().then_some(v);
}
let (neg, t) = match t.strip_prefix('-') {
Some(r) => (true, r.trim()),
None => (false, t),
};
let mut total = 0.0;
let mut rest = t;
if let Some(i) = rest.find('\'') {
let ft: f64 = rest.get(..i)?.trim().parse().ok()?;
total += ft * 12.0;
rest = rest.get(i + 1..)?.trim_start_matches('-').trim();
}
let rest = rest.trim_end_matches('"').trim();
if !rest.is_empty() {
total += parse_mixed(rest)?;
}
let v = if neg { -total } else { total };
v.is_finite().then_some(v)
}
fn parse_mixed(s: &str) -> Option<f64> {
let parts: Vec<&str> = s.split_whitespace().collect();
let frac = |p: &str| -> Option<f64> {
if let Some((a, b)) = p.split_once('/') {
let d: f64 = b.trim().parse().ok()?;
if d == 0.0 {
return None;
}
Some(a.trim().parse::<f64>().ok()? / d)
} else {
p.parse().ok()
}
};
match parts.as_slice() {
[a] => frac(a),
[a, b] => Some(a.parse::<f64>().ok()? + frac(b)?),
_ => None,
}
}
/// Parse an angle typed by the user (degrees by default): `45`, `45d30'`, `0.5r`, `100g`, `N45dE`.
pub fn parse_angle(s: &str) -> Option<f64> {
let t = s.trim().to_ascii_lowercase();
if t.is_empty() {
return None;
}
if let Some(r) = t.strip_suffix('r') {
return r.trim().parse::<f64>().ok().filter(|v| v.is_finite());
}
if let Some(g) = t.strip_suffix('g') {
return g.trim().parse::<f64>().ok().filter(|v| v.is_finite()).map(|v| (v * 0.9).to_radians());
}
if let Some(rest) = t.strip_prefix('n').or_else(|| t.strip_prefix('s')) {
let north = t.starts_with('n');
let (ang_s, east) = if let Some(a) = rest.strip_suffix('e') {
(a, true)
} else {
let a = rest.strip_suffix('w')?;
(a, false)
};
let a = parse_dms(ang_s.trim())?;
let deg = match (north, east) {
(true, true) => 90.0 - a,
(true, false) => 90.0 + a,
(false, false) => 270.0 - a,
(false, true) => 270.0 + a,
};
return Some(deg.to_radians());
}
parse_dms(&t).map(f64::to_radians)
}
fn parse_dms(t: &str) -> Option<f64> {
if let Ok(v) = t.parse::<f64>() {
return v.is_finite().then_some(v);
}
let (d, rest) = t.split_once('d').unwrap_or((t, ""));
let mut deg: f64 = d.trim().parse().ok()?;
let rest = rest.trim();
if !rest.is_empty() {
let (m, rest2) = rest.split_once('\'').unwrap_or((rest, ""));
if !m.trim().is_empty() {
deg += m.trim().parse::<f64>().ok()? / 60.0;
}
let s = rest2.trim().trim_end_matches('"');
if !s.is_empty() {
deg += s.parse::<f64>().ok()? / 3600.0;
}
}
deg.is_finite().then_some(deg)
}
pub const DEG: f64 = PI / 180.0;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decimal_and_arch() {
assert_eq!(format_distance(28.98524, 2, 4), "28.9852");
assert_eq!(format_distance(18.5, 4, 4), "1'-6 1/2\"");
assert_eq!(format_distance(6.25, 5, 2), "6 1/4");
assert_eq!(format_distance(30.0, 3, 2), "2'-6.00\"");
}
#[test]
fn parse_distances() {
assert_eq!(parse_distance("12.5"), Some(12.5));
assert_eq!(parse_distance("1'6\""), Some(18.0));
assert_eq!(parse_distance("1'-6 1/2\""), Some(18.5));
assert_eq!(parse_distance("3/4"), Some(0.75));
assert_eq!(parse_distance("1/0"), None);
assert_eq!(parse_distance("abc"), None);
assert_eq!(parse_distance(""), None);
}
#[test]
fn angles() {
assert!((parse_angle("90").unwrap() - PI / 2.0).abs() < 1e-12);
assert!((parse_angle("45d30'").unwrap().to_degrees() - 45.5).abs() < 1e-9);
assert!((parse_angle("N45dE").unwrap().to_degrees() - 45.0).abs() < 1e-9);
assert!((parse_angle("1.5r").unwrap() - 1.5).abs() < 1e-12);
assert_eq!(format_angle(PI / 2.0, 0, 0), "90");
assert_eq!(format_angle(PI / 4.0, 4, 0), "N 45d E");
}
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "cadcraft-fonts"
description = "CADCraft text: the built-in single-stroke drafting font and TEXT/MTEXT layout"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
cadcraft-geom = { workspace = true }
+284
View File
@@ -0,0 +1,284 @@
//! CADCraft text layout.
//!
//! Turns TEXT and MTEXT into stroke polylines with the built-in single-stroke font
//! ("CADCraft Stroke"). Handles the `%%` control codes, alignment modes, width factor,
//! obliquing, MTEXT inline formatting (paragraphs, stacking, height changes), word wrap and
//! attachment points.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod mtext;
mod stroke;
use cadcraft_geom::{Bounds2, Vec2};
pub use mtext::{MTextLayout, layout_mtext, plain_mtext};
/// Name of the built-in font.
pub const BUILTIN_FONT: &str = "CADCraft Stroke";
/// One laid-out run of text: strokes in local coordinates (baseline at y = 0, x from 0).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Run {
pub strokes: Vec<Vec<Vec2>>,
pub width: f64,
}
/// Replace `%%` control codes: `%%d` degree, `%%p` plus/minus, `%%c` diameter, `%%%` percent,
/// `%%nnn` character code. Underline/overline toggles (`%%u`, `%%o`) are returned as flags
/// per character.
pub fn decode_controls(s: &str) -> Vec<(char, bool, bool)> {
let mut out = Vec::with_capacity(s.len());
let mut under = false;
let mut over = false;
let chars: Vec<char> = s.chars().collect();
let mut i = 0;
while i < chars.len() {
let c = chars.get(i).copied().unwrap_or(' ');
if c == '%' && chars.get(i + 1) == Some(&'%') {
let code = chars.get(i + 2).copied().unwrap_or(' ');
match code.to_ascii_lowercase() {
'd' => out.push(('°', under, over)),
'p' => out.push(('±', under, over)),
'c' => out.push(('⌀', under, over)),
'%' => out.push(('%', under, over)),
'u' => under = !under,
'o' => over = !over,
d if d.is_ascii_digit() => {
let digits: String = chars.iter().skip(i + 2).take(3).take_while(|c| c.is_ascii_digit()).collect();
let n: u32 = digits.parse().unwrap_or(32);
out.push((char::from_u32(n).unwrap_or('?'), under, over));
i += 2 + digits.len();
continue;
}
_ => {
out.push(('%', under, over));
i += 1;
continue;
}
}
i += 3;
continue;
}
out.push((c, under, over));
i += 1;
}
out
}
/// Advance width of one character at height 1 and width factor 1.
pub fn char_advance(c: char) -> f64 {
match stroke::glyph(c) {
Some((w, _)) => (w + stroke::GAP) / stroke::CAP,
None if c.is_whitespace() => (2.4 + stroke::GAP) / stroke::CAP,
None => (4.0 + stroke::GAP) / stroke::CAP,
}
}
/// Lay out a single line at `height`, with `width_factor` and `oblique` (radians).
pub fn layout_line(s: &str, height: f64, width_factor: f64, oblique: f64) -> Run {
let h = if height.is_finite() && height > 0.0 { height } else { 1.0 };
let wf = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 };
let sc = h / stroke::CAP;
let shear = oblique.tan().clamp(-10.0, 10.0);
let mut run = Run::default();
let mut x = 0.0;
let mut under_start: Option<f64> = None;
let mut over_start: Option<f64> = None;
for (c, under, over) in decode_controls(s) {
let adv = char_advance(c) * h * wf;
match stroke::glyph(c) {
Some((_, spec)) => {
for st in stroke::strokes(spec) {
let pts: Vec<Vec2> = st.iter().map(|(gx, gy)| Vec2::new(x + (gx * sc * wf) + gy * sc * shear, gy * sc)).collect();
if pts.len() == 1 {
if let Some(p) = pts.first() {
run.strokes.push(vec![*p, *p + Vec2::new(sc * 0.2, 0.0)]);
}
} else {
run.strokes.push(pts);
}
}
}
None if !c.is_whitespace() => {
// Unknown glyph: a small box, like a missing-glyph rectangle.
let w = 4.0 * sc * wf;
run.strokes.push(vec![Vec2::new(x, 0.0), Vec2::new(x + w, 0.0), Vec2::new(x + w, h), Vec2::new(x, h), Vec2::new(x, 0.0)]);
}
None => {}
}
// Decorations.
match (under, under_start) {
(true, None) => under_start = Some(x),
(false, Some(sx)) => {
run.strokes.push(vec![Vec2::new(sx, -h * 0.2), Vec2::new(x, -h * 0.2)]);
under_start = None;
}
_ => {}
}
match (over, over_start) {
(true, None) => over_start = Some(x),
(false, Some(sx)) => {
run.strokes.push(vec![Vec2::new(sx, h * 1.2), Vec2::new(x, h * 1.2)]);
over_start = None;
}
_ => {}
}
x += adv;
}
let end = (x - stroke::GAP * sc * wf).max(0.0);
if let Some(sx) = under_start {
run.strokes.push(vec![Vec2::new(sx, -h * 0.2), Vec2::new(end, -h * 0.2)]);
}
if let Some(sx) = over_start {
run.strokes.push(vec![Vec2::new(sx, h * 1.2), Vec2::new(end, h * 1.2)]);
}
run.width = end;
run
}
/// Width of a line without building strokes.
pub fn line_width(s: &str, height: f64, width_factor: f64) -> f64 {
let n: f64 = decode_controls(s).iter().map(|(c, _, _)| char_advance(*c)).sum();
(n * height * width_factor - stroke::GAP / stroke::CAP * height * width_factor).max(0.0)
}
/// Horizontal / vertical alignment for single-line text (matches DXF 72/73 semantics).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Align {
#[default]
Left,
Center,
Right,
/// Fit between two points, scaling height.
Aligned,
/// Centred horizontally and vertically.
Middle,
/// Fit between two points, scaling width.
Fit,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum VAlign {
#[default]
Baseline,
Bottom,
Middle,
Top,
}
/// Place a single-line TEXT in world coordinates. Returns strokes and the text's bounding box.
#[allow(clippy::too_many_arguments)]
pub fn place_text(
s: &str,
insert: Vec2,
align_pt: Option<Vec2>,
height: f64,
rotation: f64,
width_factor: f64,
oblique: f64,
h: Align,
v: VAlign,
) -> (Vec<Vec<Vec2>>, Bounds2) {
let mut height = if height > 0.0 && height.is_finite() { height } else { 1.0 };
let mut wf = width_factor;
let mut rot = rotation;
let mut origin = insert;
if matches!(h, Align::Aligned | Align::Fit)
&& let Some(p2) = align_pt
{
let len = insert.dist(p2);
rot = insert.angle_to(p2);
let w = line_width(s, height, wf);
if w > 1e-12 && len > 1e-12 {
let k = len / w;
if h == Align::Aligned {
height *= k;
} else {
wf *= k;
}
}
}
let run = layout_line(s, height, wf, oblique);
let anchor = match h {
Align::Left | Align::Aligned | Align::Fit => insert,
_ => align_pt.unwrap_or(insert),
};
let dx = match h {
Align::Left | Align::Aligned | Align::Fit => 0.0,
Align::Center | Align::Middle => -run.width / 2.0,
Align::Right => -run.width,
};
let dy = match (h, v) {
(Align::Middle, _) => -height / 2.0,
(_, VAlign::Baseline) => 0.0,
(_, VAlign::Bottom) => height / 3.0,
(_, VAlign::Middle) => -height / 2.0,
(_, VAlign::Top) => -height,
};
if !matches!(h, Align::Left | Align::Aligned | Align::Fit) {
origin = anchor;
}
let local = Vec2::new(dx, dy);
let xf = |p: Vec2| origin + (p + local).rotate(rot);
let strokes: Vec<Vec<Vec2>> = run.strokes.iter().map(|st| st.iter().map(|p| xf(*p)).collect()).collect();
let bb = Bounds2::from_points(
[Vec2::new(0.0, -height / 3.0), Vec2::new(run.width, -height / 3.0), Vec2::new(run.width, height), Vec2::new(0.0, height)].map(xf),
);
(strokes, bb)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_ascii_printable_has_a_glyph() {
for c in ' '..='~' {
assert!(stroke::glyph(c).is_some(), "missing glyph {c:?}");
}
}
#[test]
fn glyph_points_stay_in_grid() {
for c in ' '..='~' {
let (w, spec) = stroke::glyph(c).unwrap();
for st in stroke::strokes(spec) {
for (x, y) in st {
assert!(x >= 0.0 && x <= w, "{c:?} x={x} w={w}");
assert!((-2.0..=6.0).contains(&y), "{c:?} y={y}");
}
}
}
}
#[test]
fn control_codes() {
let d: String = decode_controls("45%%d %%p0.1 %%c10 100%%%").iter().map(|x| x.0).collect();
assert_eq!(d, "45° ±0.1 ⌀10 100%");
let u = decode_controls("%%uab%%uc");
assert!(u[0].1 && u[1].1 && !u[2].1);
assert_eq!(decode_controls("%%065")[0].0, 'A');
assert_eq!(decode_controls("%%").len(), 2);
}
#[test]
fn line_metrics_scale_with_height() {
let a = layout_line("HELLO", 1.0, 1.0, 0.0);
let b = layout_line("HELLO", 2.0, 1.0, 0.0);
assert!((b.width - 2.0 * a.width).abs() < 1e-9);
assert!((line_width("HELLO", 1.0, 1.0) - a.width).abs() < 1e-9);
}
#[test]
fn center_alignment_centres_on_point() {
let (_, bb) = place_text("ABC", Vec2::ZERO, Some(Vec2::new(10.0, 0.0)), 1.0, 0.0, 1.0, 0.0, Align::Center, VAlign::Baseline);
assert!((bb.center().x - 10.0).abs() < 1e-9);
}
#[test]
fn fit_spans_both_points() {
let (_, bb) = place_text("ABC", Vec2::ZERO, Some(Vec2::new(10.0, 0.0)), 1.0, 0.0, 1.0, 0.0, Align::Fit, VAlign::Baseline);
assert!((bb.width() - 10.0).abs() < 1e-6);
assert!((bb.max.y - 1.0).abs() < 1e-9);
}
}
+169
View File
@@ -0,0 +1,169 @@
//! MTEXT: inline-format parsing, word wrap and attachment.
use cadcraft_geom::{Bounds2, Vec2};
use crate::{layout_line, line_width};
/// Strip MTEXT formatting codes to plain text with `\n` paragraph breaks.
/// Stacked fractions `\S1/2;` become `1/2`; `\~` is a space; braces are dropped.
pub fn plain_mtext(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let chars: Vec<char> = s.chars().collect();
let mut i = 0;
while let Some(&c) = chars.get(i) {
match c {
'\\' => {
let code = chars.get(i + 1).copied().unwrap_or(' ');
match code {
'P' => {
out.push('\n');
i += 2;
}
'N' => {
out.push('\n');
i += 2;
}
'~' => {
out.push(' ');
i += 2;
}
'\\' | '{' | '}' => {
out.push(code);
i += 2;
}
'S' => {
// \Snum^den; \Snum/den; \Snum#den;
let mut j = i + 2;
let mut stack = String::new();
while let Some(&ch) = chars.get(j) {
if ch == ';' {
break;
}
stack.push(match ch {
'^' | '#' => '/',
c => c,
});
j += 1;
}
out.push_str(stack.trim_end_matches('/'));
i = j + 1;
}
'L' | 'l' | 'O' | 'o' | 'K' | 'k' => i += 2,
// Codes with an argument terminated by ';' (\f, \F, \H, \W, \Q, \T, \A, \C, \c, \p).
_ => {
let mut j = i + 2;
while let Some(&ch) = chars.get(j) {
if ch == ';' {
break;
}
j += 1;
}
i = j + 1;
}
}
}
'{' | '}' => i += 1,
'\r' => i += 1,
_ => {
out.push(c);
i += 1;
}
}
}
out
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MTextLayout {
pub strokes: Vec<Vec<Vec2>>,
pub bounds: Bounds2,
pub lines: Vec<String>,
}
/// Lay out MTEXT. `attach` 1..=9 (TL, TC, TR, ML, MC, MR, BL, BC, BR).
pub fn layout_mtext(contents: &str, insert: Vec2, height: f64, width: f64, attach: u8, rotation: f64, line_spacing: f64) -> MTextLayout {
let h = if height > 0.0 && height.is_finite() { height } else { 1.0 };
let text = plain_mtext(contents);
let mut lines: Vec<String> = Vec::new();
for para in text.split('\n') {
if width > 0.0 {
let mut cur = String::new();
for word in para.split(' ') {
let trial = if cur.is_empty() { word.to_string() } else { format!("{cur} {word}") };
if !cur.is_empty() && line_width(&trial, h, 1.0) > width {
lines.push(std::mem::take(&mut cur));
cur = word.to_string();
} else {
cur = trial;
}
}
lines.push(cur);
} else {
lines.push(para.to_string());
}
}
let pitch = h * 5.0 / 3.0 * if line_spacing > 0.0 && line_spacing.is_finite() { line_spacing } else { 1.0 };
let block_w = if width > 0.0 { width } else { lines.iter().map(|l| line_width(l, h, 1.0)).fold(0.0, f64::max) };
let n = lines.len().max(1) as f64;
let block_h = h + pitch * (n - 1.0);
let col = (attach.clamp(1, 9) - 1) % 3;
let row = (attach.clamp(1, 9) - 1) / 3;
// Top of the first line's cap height relative to the insert point.
let top = match row {
0 => 0.0,
1 => block_h / 2.0,
_ => block_h,
};
let mut out = MTextLayout { lines: lines.clone(), ..Default::default() };
for (i, line) in lines.iter().enumerate() {
let run = layout_line(line, h, 1.0, 0.0);
let x = match col {
0 => 0.0,
1 => -run.width / 2.0,
_ => -run.width,
};
let base_y = top - h - pitch * i as f64;
for st in run.strokes {
out.strokes.push(st.into_iter().map(|p| insert + (p + Vec2::new(x, base_y)).rotate(rotation)).collect());
}
}
let x0 = match col {
0 => 0.0,
1 => -block_w / 2.0,
_ => -block_w,
};
out.bounds = Bounds2::from_points(
[Vec2::new(x0, top), Vec2::new(x0 + block_w, top), Vec2::new(x0 + block_w, top - block_h), Vec2::new(x0, top - block_h)]
.map(|p| insert + p.rotate(rotation)),
);
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strips_formatting() {
assert_eq!(plain_mtext("{\\fArial|b1;Bold}\\Pline 2"), "Bold\nline 2");
assert_eq!(plain_mtext("1\\S1/2;\""), "11/2\"");
assert_eq!(plain_mtext("a\\~b\\\\c"), "a b\\c");
assert_eq!(plain_mtext("\\H2.5x;Big"), "Big");
assert_eq!(plain_mtext("unterminated \\H2"), "unterminated ");
}
#[test]
fn wraps_to_width() {
let l = layout_mtext("the quick brown fox jumps over the lazy dog", Vec2::ZERO, 1.0, 8.0, 1, 0.0, 1.0);
assert!(l.lines.len() > 2);
assert!(l.bounds.max.y.abs() < 1e-9);
assert!((l.bounds.width() - 8.0).abs() < 1e-9);
}
#[test]
fn middle_centre_attach() {
let l = layout_mtext("AB", Vec2::new(5.0, 5.0), 1.0, 0.0, 5, 0.0, 1.0);
let c = l.bounds.center();
assert!((c.x - 5.0).abs() < 1e-9 && (c.y - 5.0).abs() < 1e-9);
}
}
+131
View File
@@ -0,0 +1,131 @@
//! "CADCraft Stroke": an original single-stroke drafting font, designed for CADCraft on a
//! small grid (public domain / CC0 as part of this codebase).
//!
//! Each glyph is `(width, strokes)`. A stroke is a run of points; each point is two characters:
//! an x digit `0..=6` and a y letter where `a` = -2, `c` = 0 (baseline), `g` = 4 (x-height),
//! `i` = 6 (cap height). Strokes are separated by spaces.
pub(crate) const CAP: f64 = 6.0;
pub(crate) const GAP: f64 = 1.6;
pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> {
let g: (f64, &str) = match c {
' ' => (2.4, ""),
'A' => (4.0, "0c2i4c 1f3f"),
'B' => (4.0, "0c0i3i4h4g3f0f 3f4e4d3c0c"),
'C' => (4.0, "4h3i1i0h0d1c3c4d"),
'D' => (4.0, "0c0i3i4h4d3c0c"),
'E' => (4.0, "4i0i0c4c 0f3f"),
'F' => (4.0, "4i0i0c 0f3f"),
'G' => (4.0, "4h3i1i0h0d1c3c4d4f2f"),
'H' => (4.0, "0c0i 4c4i 0f4f"),
'I' => (2.0, "0i2i 1i1c 0c2c"),
'J' => (4.0, "4i4d3c1c0d0e"),
'K' => (4.0, "0c0i 4i0e 1f4c"),
'L' => (4.0, "0i0c4c"),
'M' => (4.0, "0c0i2f4i4c"),
'N' => (4.0, "0c0i4c4i"),
'O' => (4.0, "1c0d0h1i3i4h4d3c1c"),
'P' => (4.0, "0c0i3i4h4g3f0f"),
'Q' => (4.0, "1c0d0h1i3i4h4d3c1c 2e4b"),
'R' => (4.0, "0c0i3i4h4g3f0f 2f4c"),
'S' => (4.0, "4h3i1i0h0g1f3f4e4d3c1c0d"),
'T' => (4.0, "0i4i 2i2c"),
'U' => (4.0, "0i0d1c3c4d4i"),
'V' => (4.0, "0i2c4i"),
'W' => (4.0, "0i1c2f3c4i"),
'X' => (4.0, "0i4c 0c4i"),
'Y' => (4.0, "0i2f4i 2f2c"),
'Z' => (4.0, "0i4i0c4c"),
'0' => (4.0, "1c0d0h1i3i4h4d3c1c"),
'1' => (4.0, "1h2i2c 1c3c"),
'2' => (4.0, "0h1i3i4h4g0c4c"),
'3' => (4.0, "0h1i3i4h4g3f2f 3f4e4d3c1c0d"),
'4' => (4.0, "3c3i0e4e"),
'5' => (4.0, "4i0i0f3f4e4d3c1c0d"),
'6' => (4.0, "4h3i1i0h0d1c3c4d4e3f1f0e"),
'7' => (4.0, "0i4i1c"),
'8' => (4.0, "1f0g0h1i3i4h4g3f1f0e0d1c3c4d4e3f"),
'9' => (4.0, "4f1f0g0h1i3i4h4d3c1c0d"),
'a' => (4.0, "4g4c 4f3g1g0f0d1c3c4d"),
'b' => (4.0, "0i0c 0d1c3c4d4f3g1g0f"),
'c' => (4.0, "4f3g1g0f0d1c3c4d"),
'd' => (4.0, "4i4c 4d3c1c0d0f1g3g4f"),
'e' => (4.0, "0e4e4f3g1g0f0d1c3c4d"),
'f' => (3.0, "3i2i1h1c 0g3g"),
'g' => (4.0, "4g4b3a1a0b 4f3g1g0f0d1c3c4d"),
'h' => (4.0, "0i0c 0f1g3g4f4c"),
'i' => (1.0, "0c0g 0h0i"),
'j' => (2.0, "2g2b1a0a 2h2i"),
'k' => (4.0, "0i0c 3g0d 1e3c"),
'l' => (2.0, "1i1d2c"),
'm' => (4.0, "0c0g 0f1g2f2c 2f3g4f4c"),
'n' => (4.0, "0c0g 0f1g3g4f4c"),
'o' => (4.0, "1c0d0f1g3g4f4d3c1c"),
'p' => (4.0, "0g0a 0f1g3g4f4d3c1c0d"),
'q' => (4.0, "4g4a 4f3g1g0f0d1c3c4d"),
'r' => (3.0, "0c0g 0e2g3g"),
's' => (4.0, "4f3g1g0f1e3e4d3c1c0d"),
't' => (3.0, "1i1d2c3c 0g3g"),
'u' => (4.0, "0g0d1c3c4d 4g4c"),
'v' => (4.0, "0g2c4g"),
'w' => (4.0, "0g1c2f3c4g"),
'x' => (4.0, "0g4c 0c4g"),
'y' => (4.0, "0g2c 4g1a0a"),
'z' => (4.0, "0g4g0c4c"),
'!' => (1.0, "0i0e 0d0c"),
'"' => (2.0, "0i0g 2i2g"),
'#' => (4.0, "1c1i 3c3i 0e4e 0g4g"),
'$' => (4.0, "4h3i1i0h0g1f3f4e4d3c1c0d 2i2c"),
'%' => (4.0, "0c4i 0i0h1h1i0i 3c3d4d4c3c"),
'&' => (4.0, "4c1h1i2i3h0e0d1c2c4e"),
'\'' => (1.0, "0i0g"),
'(' => (2.0, "2i1h0f0e1d2c"),
')' => (2.0, "0i1h2f2e1d0c"),
'*' => (4.0, "2h2d 0g4e 0e4g"),
'+' => (4.0, "2d2h 0f4f"),
',' => (1.0, "1d1c0b"),
'-' => (4.0, "0f4f"),
'.' => (1.0, "0c0d"),
'/' => (4.0, "0c4i"),
':' => (1.0, "0c0d 0g0h"),
';' => (1.0, "1d1c0b 1g1h"),
'<' => (4.0, "4h0f4d"),
'=' => (4.0, "0e4e 0g4g"),
'>' => (4.0, "0h4f0d"),
'?' => (4.0, "0h1i3i4h4g2f2e 2d2c"),
'@' => (4.0, "3e3g1g1e3e4f4h3i1i0h0d1c4c"),
'[' => (2.0, "2i0i0c2c"),
'\\' => (4.0, "0i4c"),
']' => (2.0, "0i2i2c0c"),
'^' => (4.0, "0g2i4g"),
'_' => (4.0, "0b4b"),
'`' => (1.0, "0i1h"),
'{' => (2.0, "2i1h1g0f1e1d2c"),
'|' => (1.0, "0i0a"),
'}' => (2.0, "0i1h1g2f1e1d0c"),
'~' => (4.0, "0g1h3f4g"),
'°' => (2.0, "1i0h1g2h1i"),
'±' => (4.0, "2e2i 0g4g 0d4d"),
'Ø' | 'ø' | '⌀' => (4.0, "1c0d0h1i3i4h4d3c1c 0c4i"),
_ => return None,
};
Some(g)
}
/// Decode one stroke string into point lists in font units.
pub(crate) fn strokes(spec: &str) -> Vec<Vec<(f64, f64)>> {
spec.split(' ')
.filter(|s| !s.is_empty())
.map(|s| {
let b = s.as_bytes();
b.chunks(2)
.filter_map(|p| {
let x = f64::from(p.first()?.checked_sub(b'0')?);
let y = f64::from(p.get(1)?.checked_sub(b'a')?) - 2.0;
Some((x, y))
})
.collect()
})
.collect()
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "cadcraft-geom"
description = "CADCraft geometry: f64 vectors, curves, arcs, splines, intersections, offsets, snaps"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
serde = { workspace = true }
+77
View File
@@ -0,0 +1,77 @@
use serde::{Deserialize, Serialize};
use crate::Vec2;
/// Axis-aligned bounding box. An empty box has `min > max`.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Bounds2 {
pub min: Vec2,
pub max: Vec2,
}
impl Default for Bounds2 {
fn default() -> Self {
Bounds2::EMPTY
}
}
impl Bounds2 {
pub const EMPTY: Bounds2 = Bounds2 { min: Vec2 { x: f64::INFINITY, y: f64::INFINITY }, max: Vec2 { x: f64::NEG_INFINITY, y: f64::NEG_INFINITY } };
pub fn new(a: Vec2, b: Vec2) -> Self {
Bounds2 { min: a.min(b), max: a.max(b) }
}
pub fn from_points<I: IntoIterator<Item = Vec2>>(it: I) -> Self {
let mut b = Bounds2::EMPTY;
for p in it {
b.add(p);
}
b
}
pub fn is_empty(&self) -> bool {
!(self.min.x <= self.max.x && self.min.y <= self.max.y)
}
pub fn add(&mut self, p: Vec2) {
if p.is_finite() {
self.min = self.min.min(p);
self.max = self.max.max(p);
}
}
pub fn union(&self, o: &Bounds2) -> Bounds2 {
if o.is_empty() {
return *self;
}
if self.is_empty() {
return *o;
}
Bounds2 { min: self.min.min(o.min), max: self.max.max(o.max) }
}
pub fn width(&self) -> f64 {
if self.is_empty() { 0.0 } else { self.max.x - self.min.x }
}
pub fn height(&self) -> f64 {
if self.is_empty() { 0.0 } else { self.max.y - self.min.y }
}
pub fn center(&self) -> Vec2 {
if self.is_empty() { Vec2::ZERO } else { self.min.mid(self.max) }
}
pub fn contains(&self, p: Vec2) -> bool {
p.x >= self.min.x && p.x <= self.max.x && p.y >= self.min.y && p.y <= self.max.y
}
/// True when `o` lies entirely inside.
pub fn contains_box(&self, o: &Bounds2) -> bool {
!o.is_empty() && self.contains(o.min) && self.contains(o.max)
}
pub fn intersects(&self, o: &Bounds2) -> bool {
!(self.is_empty() || o.is_empty() || o.min.x > self.max.x || o.max.x < self.min.x || o.min.y > self.max.y || o.max.y < self.min.y)
}
pub fn expand(&self, d: f64) -> Bounds2 {
if self.is_empty() {
return *self;
}
Bounds2 { min: self.min - Vec2::new(d, d), max: self.max + Vec2::new(d, d) }
}
pub fn corners(&self) -> [Vec2; 4] {
[self.min, Vec2::new(self.max.x, self.min.y), self.max, Vec2::new(self.min.x, self.max.y)]
}
}
+516
View File
@@ -0,0 +1,516 @@
use serde::{Deserialize, Serialize};
use crate::{Bounds2, EPS, PI, TAU, Vec2, angle_in_sweep, arc_segments, ccw_sweep, norm_angle};
/// A straight segment.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Line {
pub a: Vec2,
pub b: Vec2,
}
impl Line {
pub fn new(a: Vec2, b: Vec2) -> Self {
Line { a, b }
}
pub fn len(&self) -> f64 {
self.a.dist(self.b)
}
pub fn dir(&self) -> Vec2 {
(self.b - self.a).normalized()
}
pub fn mid(&self) -> Vec2 {
self.a.mid(self.b)
}
/// Parameter (0..1 on the segment) of the projection of `p`.
pub fn param_of(&self, p: Vec2) -> f64 {
let d = self.b - self.a;
let l2 = d.len2();
if l2 <= EPS * EPS { 0.0 } else { (p - self.a).dot(d) / l2 }
}
pub fn at(&self, t: f64) -> Vec2 {
self.a.lerp(self.b, t)
}
/// Closest point on the segment.
pub fn closest(&self, p: Vec2) -> Vec2 {
self.at(self.param_of(p).clamp(0.0, 1.0))
}
/// Foot of the perpendicular on the infinite line.
pub fn project(&self, p: Vec2) -> Vec2 {
self.at(self.param_of(p))
}
pub fn dist(&self, p: Vec2) -> f64 {
self.closest(p).dist(p)
}
/// Signed side: > 0 left of a→b.
pub fn side(&self, p: Vec2) -> f64 {
(self.b - self.a).cross(p - self.a)
}
pub fn offset(&self, d: f64) -> Line {
let n = (self.b - self.a).normalized().perp() * d;
Line::new(self.a + n, self.b + n)
}
}
/// A circular arc, CCW from `start` to `end` angle.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Arc {
pub center: Vec2,
pub radius: f64,
pub start: f64,
pub end: f64,
}
impl Arc {
pub fn new(center: Vec2, radius: f64, start: f64, end: f64) -> Self {
Arc { center, radius: radius.abs(), start: norm_angle(start), end: norm_angle(end) }
}
pub fn sweep(&self) -> f64 {
ccw_sweep(self.start, self.end)
}
pub fn start_point(&self) -> Vec2 {
Vec2::polar(self.center, self.radius, self.start)
}
pub fn end_point(&self) -> Vec2 {
Vec2::polar(self.center, self.radius, self.end)
}
pub fn mid_point(&self) -> Vec2 {
Vec2::polar(self.center, self.radius, self.start + self.sweep() / 2.0)
}
pub fn len(&self) -> f64 {
self.radius * self.sweep()
}
pub fn contains_angle(&self, a: f64) -> bool {
angle_in_sweep(a, self.start, self.end)
}
/// Point at parameter `t` in 0..1 along the sweep.
pub fn at(&self, t: f64) -> Vec2 {
Vec2::polar(self.center, self.radius, self.start + self.sweep() * t)
}
/// Arc through three points, or `None` when collinear.
pub fn from_3_points(p1: Vec2, p2: Vec2, p3: Vec2) -> Option<Arc> {
let c = Circle::from_3_points(p1, p2, p3)?;
let a1 = c.center.angle_to(p1);
let a2 = c.center.angle_to(p2);
let a3 = c.center.angle_to(p3);
// CCW from p1 to p3 must pass p2; otherwise go the other way.
if angle_in_sweep(a2, a1, a3) { Some(Arc::new(c.center, c.radius, a1, a3)) } else { Some(Arc::new(c.center, c.radius, a3, a1)) }
}
/// Arc from start point, center and end point (CCW).
pub fn from_start_center_end(s: Vec2, c: Vec2, e: Vec2) -> Arc {
Arc::new(c, s.dist(c), c.angle_to(s), c.angle_to(e))
}
pub fn closest(&self, p: Vec2) -> Vec2 {
let a = self.center.angle_to(p);
if self.contains_angle(a) && p.dist(self.center) > EPS {
Vec2::polar(self.center, self.radius, a)
} else {
let s = self.start_point();
let e = self.end_point();
if s.dist(p) <= e.dist(p) { s } else { e }
}
}
pub fn bounds(&self) -> Bounds2 {
let mut b = Bounds2::from_points([self.start_point(), self.end_point()]);
for k in 0..4 {
let a = k as f64 * PI / 2.0;
if self.contains_angle(a) {
b.add(Vec2::polar(self.center, self.radius, a));
}
}
b
}
pub fn tessellate(&self, tol: f64, out: &mut Vec<Vec2>) {
let sweep = self.sweep();
let n = arc_segments(self.radius, sweep, tol);
for i in 0..=n {
out.push(Vec2::polar(self.center, self.radius, self.start + sweep * i as f64 / n as f64));
}
}
}
/// A full circle.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Circle {
pub center: Vec2,
pub radius: f64,
}
impl Circle {
pub fn new(center: Vec2, radius: f64) -> Self {
Circle { center, radius: radius.abs() }
}
pub fn from_3_points(p1: Vec2, p2: Vec2, p3: Vec2) -> Option<Circle> {
let d = 2.0 * (p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y));
if d.abs() < 1e-12 {
return None;
}
let s1 = p1.len2();
let s2 = p2.len2();
let s3 = p3.len2();
let ux = (s1 * (p2.y - p3.y) + s2 * (p3.y - p1.y) + s3 * (p1.y - p2.y)) / d;
let uy = (s1 * (p3.x - p2.x) + s2 * (p1.x - p3.x) + s3 * (p2.x - p1.x)) / d;
let c = Vec2::new(ux, uy);
Some(Circle::new(c, c.dist(p1)))
}
pub fn from_2_points(p1: Vec2, p2: Vec2) -> Circle {
Circle::new(p1.mid(p2), p1.dist(p2) / 2.0)
}
pub fn closest(&self, p: Vec2) -> Vec2 {
let d = p - self.center;
if d.len() < EPS { self.center + Vec2::X * self.radius } else { self.center + d.normalized() * self.radius }
}
pub fn bounds(&self) -> Bounds2 {
Bounds2::new(self.center - Vec2::new(self.radius, self.radius), self.center + Vec2::new(self.radius, self.radius))
}
pub fn tessellate(&self, tol: f64, out: &mut Vec<Vec2>) {
Arc { center: self.center, radius: self.radius, start: 0.0, end: TAU }.tessellate(tol, out);
}
/// Tangent points from external point `p`.
pub fn tangent_points(&self, p: Vec2) -> Vec<Vec2> {
let d = p.dist(self.center);
if d <= self.radius + EPS {
return Vec::new();
}
let base = self.center.angle_to(p);
let off = (self.radius / d).clamp(-1.0, 1.0).acos();
vec![Vec2::polar(self.center, self.radius, base + off), Vec2::polar(self.center, self.radius, base - off)]
}
}
/// An ellipse (or elliptical arc), DXF-style: center, major-axis endpoint vector, ratio, params.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Ellipse {
pub center: Vec2,
pub major: Vec2,
pub ratio: f64,
pub start: f64,
pub end: f64,
}
impl Ellipse {
pub fn full(center: Vec2, major: Vec2, ratio: f64) -> Self {
Ellipse { center, major, ratio, start: 0.0, end: TAU }
}
pub fn is_full(&self) -> bool {
(ccw_sweep(self.start, self.end) - TAU).abs() < 1e-9
}
pub fn minor(&self) -> Vec2 {
self.major.perp() * self.ratio
}
pub fn at_param(&self, t: f64) -> Vec2 {
self.center + self.major * t.cos() + self.minor() * t.sin()
}
pub fn sweep(&self) -> f64 {
ccw_sweep(self.start, self.end)
}
pub fn tessellate(&self, tol: f64, out: &mut Vec<Vec2>) {
let r = self.major.len();
let sweep = self.sweep();
let n = arc_segments(r, sweep, tol).max(8);
for i in 0..=n {
out.push(self.at_param(self.start + sweep * i as f64 / n as f64));
}
}
pub fn bounds(&self) -> Bounds2 {
let mut pts = Vec::new();
self.tessellate(self.major.len() * 1e-4, &mut pts);
Bounds2::from_points(pts)
}
/// Parameter of the point on the ellipse nearest the direction of `p` (approximate).
pub fn param_of(&self, p: Vec2) -> f64 {
let ma = self.major.len();
if ma < EPS {
return 0.0;
}
let ux = self.major / ma;
let local = p - self.center;
let x = local.dot(ux);
let y = local.dot(ux.perp());
let mb = ma * self.ratio;
norm_angle((y / mb.max(EPS)).atan2(x / ma))
}
pub fn closest(&self, p: Vec2) -> Vec2 {
let mut pts = Vec::new();
self.tessellate(self.major.len() * 1e-3, &mut pts);
nearest_on_polyline(&pts, p).unwrap_or(self.center)
}
}
/// The nearest point to `p` on a polyline (through tessellated points).
pub(crate) fn nearest_on_polyline(pts: &[Vec2], p: Vec2) -> Option<Vec2> {
let mut best: Option<(f64, Vec2)> = None;
for w in pts.windows(2) {
if let [a, b] = w {
let c = Line::new(*a, *b).closest(p);
let d = c.dist(p);
if best.is_none_or(|(bd, _)| d < bd) {
best = Some((d, c));
}
}
}
best.map(|(_, c)| c).or_else(|| pts.first().copied())
}
/// A primitive segment: a line or an arc (polyline pieces, boundary loops, offsets).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum Segment {
Line(Line),
/// An arc with direction: `ccw == false` runs from end to start in arc terms.
Arc {
arc: Arc,
ccw: bool,
},
}
impl Segment {
pub fn start(&self) -> Vec2 {
match self {
Segment::Line(l) => l.a,
Segment::Arc { arc, ccw: true } => arc.start_point(),
Segment::Arc { arc, ccw: false } => arc.end_point(),
}
}
pub fn end(&self) -> Vec2 {
match self {
Segment::Line(l) => l.b,
Segment::Arc { arc, ccw: true } => arc.end_point(),
Segment::Arc { arc, ccw: false } => arc.start_point(),
}
}
pub fn len(&self) -> f64 {
match self {
Segment::Line(l) => l.len(),
Segment::Arc { arc, .. } => arc.len(),
}
}
pub fn mid(&self) -> Vec2 {
match self {
Segment::Line(l) => l.mid(),
Segment::Arc { arc, .. } => arc.mid_point(),
}
}
pub fn closest(&self, p: Vec2) -> Vec2 {
match self {
Segment::Line(l) => l.closest(p),
Segment::Arc { arc, .. } => arc.closest(p),
}
}
pub fn bounds(&self) -> Bounds2 {
match self {
Segment::Line(l) => Bounds2::new(l.a, l.b),
Segment::Arc { arc, .. } => arc.bounds(),
}
}
/// Points along the segment in its direction, including both ends.
pub fn tessellate(&self, tol: f64, out: &mut Vec<Vec2>) {
match self {
Segment::Line(l) => {
out.push(l.a);
out.push(l.b);
}
Segment::Arc { arc, ccw } => {
let start = out.len();
arc.tessellate(tol, out);
if !ccw && let Some(s) = out.get_mut(start..) {
s.reverse()
}
}
}
}
/// Point at parameter `t` (0..1) in segment direction.
pub fn at(&self, t: f64) -> Vec2 {
match self {
Segment::Line(l) => l.at(t),
Segment::Arc { arc, ccw: true } => arc.at(t),
Segment::Arc { arc, ccw: false } => arc.at(1.0 - t),
}
}
pub fn reversed(&self) -> Segment {
match *self {
Segment::Line(l) => Segment::Line(Line::new(l.b, l.a)),
Segment::Arc { arc, ccw } => Segment::Arc { arc, ccw: !ccw },
}
}
/// Tangent direction (unit) at parameter t.
pub fn tangent(&self, t: f64) -> Vec2 {
match self {
Segment::Line(l) => l.dir(),
Segment::Arc { arc, ccw } => {
let p = self.at(t);
let r = (p - arc.center).perp().normalized();
if *ccw { r } else { -r }
}
}
}
/// Offset by `d` to the left of travel direction. `None` if an arc collapses.
pub fn offset(&self, d: f64) -> Option<Segment> {
match *self {
Segment::Line(l) => Some(Segment::Line(l.offset(d))),
Segment::Arc { arc, ccw } => {
// Left of a CCW arc is toward the center.
let r = if ccw { arc.radius - d } else { arc.radius + d };
if r <= EPS {
return None;
}
Some(Segment::Arc { arc: Arc { radius: r, ..arc }, ccw })
}
}
}
}
/// A polyline vertex: position, bulge to the next vertex (tan(θ/4)), and optional widths.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct PolyVertex {
pub p: Vec2,
#[serde(default)]
pub bulge: f64,
#[serde(default)]
pub start_width: f64,
#[serde(default)]
pub end_width: f64,
}
impl PolyVertex {
pub fn new(p: Vec2) -> Self {
PolyVertex { p, ..Default::default() }
}
pub fn with_bulge(p: Vec2, bulge: f64) -> Self {
PolyVertex { p, bulge, ..Default::default() }
}
}
/// Convert a bulge segment to an arc. `None` for a straight (zero-bulge or degenerate) segment.
pub fn bulge_to_arc(a: Vec2, b: Vec2, bulge: f64) -> Option<(Arc, bool)> {
if bulge.abs() < 1e-12 || !bulge.is_finite() || a.near(b, EPS) {
return None;
}
let theta = 4.0 * bulge.atan(); // signed included angle
let chord = a.dist(b);
let r = chord / (2.0 * (theta / 2.0).sin().abs());
let mid = a.mid(b);
let sagitta_dir = (b - a).normalized().perp();
// distance from chord midpoint to center
let h = r * (theta / 2.0).cos().abs();
// For bulge > 0 (CCW), center is to the left of a→b when |θ| < π.
let sign = if bulge > 0.0 { 1.0 } else { -1.0 };
let center = if theta.abs() < PI { mid + sagitta_dir * (h * sign) } else { mid - sagitta_dir * (h * sign) };
let sa = center.angle_to(a);
let ea = center.angle_to(b);
if bulge > 0.0 { Some((Arc::new(center, r, sa, ea), true)) } else { Some((Arc::new(center, r, ea, sa), false)) }
}
/// Bulge for an arc traversed from `a` to `b` with the given sweep (signed: + = CCW).
pub fn arc_to_bulge(signed_sweep: f64) -> f64 {
(signed_sweep / 4.0).tan()
}
/// A 2D polyline with bulges (LWPOLYLINE).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Polyline {
pub vertices: Vec<PolyVertex>,
pub closed: bool,
}
impl Polyline {
pub fn from_points(pts: &[Vec2], closed: bool) -> Self {
Polyline { vertices: pts.iter().map(|p| PolyVertex::new(*p)).collect(), closed }
}
/// The segments, including the closing segment when closed.
pub fn segments(&self) -> Vec<Segment> {
let n = self.vertices.len();
let mut out = Vec::with_capacity(n);
let count = if self.closed { n } else { n.saturating_sub(1) };
for i in 0..count {
let (Some(v), Some(w)) = (self.vertices.get(i), self.vertices.get((i + 1) % n.max(1))) else { continue };
if v.p.near(w.p, EPS) && v.bulge.abs() < 1e-12 {
continue;
}
match bulge_to_arc(v.p, w.p, v.bulge) {
Some((arc, ccw)) => out.push(Segment::Arc { arc, ccw }),
None => out.push(Segment::Line(Line::new(v.p, w.p))),
}
}
out
}
pub fn len(&self) -> f64 {
self.segments().iter().map(Segment::len).sum()
}
pub fn bounds(&self) -> Bounds2 {
let mut b = Bounds2::from_points(self.vertices.iter().map(|v| v.p));
for s in self.segments() {
b = b.union(&s.bounds());
}
b
}
pub fn tessellate(&self, tol: f64) -> Vec<Vec2> {
let mut out: Vec<Vec2> = Vec::new();
for s in self.segments() {
let mut pts = Vec::new();
s.tessellate(tol, &mut pts);
let skip = usize::from(out.last().is_some_and(|l| pts.first().is_some_and(|f| l.near(*f, 1e-9))));
out.extend(pts.into_iter().skip(skip));
}
if out.is_empty() {
out.extend(self.vertices.first().map(|v| v.p));
}
out
}
/// Signed area (CCW positive) of a closed polyline including bulge areas.
pub fn area(&self) -> f64 {
let pts = self.tessellate(1e-4);
shoelace(&pts)
}
pub fn closest(&self, p: Vec2) -> Option<Vec2> {
let mut best: Option<(f64, Vec2)> = None;
for s in self.segments() {
let c = s.closest(p);
let d = c.dist(p);
if best.is_none_or(|(bd, _)| d < bd) {
best = Some((d, c));
}
}
best.map(|(_, c)| c).or_else(|| self.vertices.first().map(|v| v.p))
}
/// True if `p` is inside a closed polyline (even-odd on the tessellation).
pub fn contains(&self, p: Vec2) -> bool {
point_in_polygon(&self.tessellate(1e-3), p)
}
}
/// Signed polygon area (CCW positive).
pub fn shoelace(pts: &[Vec2]) -> f64 {
let n = pts.len();
if n < 3 {
return 0.0;
}
let mut s = 0.0;
for i in 0..n {
if let (Some(a), Some(b)) = (pts.get(i), pts.get((i + 1) % n)) {
s += a.cross(*b);
}
}
s / 2.0
}
/// Even-odd point-in-polygon test.
pub fn point_in_polygon(poly: &[Vec2], p: Vec2) -> bool {
let n = poly.len();
if n < 3 {
return false;
}
let mut inside = false;
let mut j = n - 1;
for i in 0..n {
if let (Some(a), Some(b)) = (poly.get(i), poly.get(j))
&& (a.y > p.y) != (b.y > p.y)
{
let x = (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x;
if p.x < x {
inside = !inside;
}
}
j = i;
}
inside
}
+101
View File
@@ -0,0 +1,101 @@
use crate::{Arc, Circle, EPS, Line, Segment, Vec2};
/// Intersection of two infinite lines through (a1,a2) and (b1,b2), with parameters on each.
pub fn line_line_infinite(a1: Vec2, a2: Vec2, b1: Vec2, b2: Vec2) -> Option<(Vec2, f64, f64)> {
let r = a2 - a1;
let s = b2 - b1;
let den = r.cross(s);
if den.abs() < 1e-14 * (r.len() * s.len()).max(1e-300) {
return None;
}
let t = (b1 - a1).cross(s) / den;
let u = (b1 - a1).cross(r) / den;
Some((a1 + r * t, t, u))
}
/// Intersection of two finite segments.
pub fn line_line(a: &Line, b: &Line) -> Option<Vec2> {
let (p, t, u) = line_line_infinite(a.a, a.b, b.a, b.b)?;
let tol = 1e-9;
((-tol..=1.0 + tol).contains(&t) && (-tol..=1.0 + tol).contains(&u)).then_some(p)
}
/// Intersections of the infinite line through `l` with a circle. Returns points with line params.
pub fn line_circle(l: &Line, c: &Circle) -> Vec<(Vec2, f64)> {
let d = l.b - l.a;
let f = l.a - c.center;
let a = d.dot(d);
if a < EPS * EPS {
return Vec::new();
}
let b = 2.0 * f.dot(d);
let cc = f.dot(f) - c.radius * c.radius;
let disc = b * b - 4.0 * a * cc;
if disc < -1e-12 * a {
return Vec::new();
}
if disc.abs() <= 1e-12 * a {
let t = -b / (2.0 * a);
return vec![(l.at(t), t)];
}
let sq = disc.max(0.0).sqrt();
let t1 = (-b - sq) / (2.0 * a);
let t2 = (-b + sq) / (2.0 * a);
vec![(l.at(t1), t1), (l.at(t2), t2)]
}
/// Intersections of two full circles.
pub fn circle_circle(c1: &Circle, c2: &Circle) -> Vec<Vec2> {
let d = c1.center.dist(c2.center);
if d < EPS || d > c1.radius + c2.radius + 1e-9 || d < (c1.radius - c2.radius).abs() - 1e-9 {
return Vec::new();
}
let a = (c1.radius * c1.radius - c2.radius * c2.radius + d * d) / (2.0 * d);
let h2 = c1.radius * c1.radius - a * a;
let dir = (c2.center - c1.center) / d;
let p = c1.center + dir * a;
if h2 <= 1e-12 {
return vec![p];
}
let h = h2.sqrt();
vec![p + dir.perp() * h, p - dir.perp() * h]
}
fn on_arc(a: &Arc, p: Vec2) -> bool {
a.contains_angle(a.center.angle_to(p))
}
/// Intersections between two segments (finite).
pub fn intersect_segments(s1: &Segment, s2: &Segment) -> Vec<Vec2> {
intersect_segments_ext(s1, s2, false)
}
/// Intersections; with `extend` true, lines are infinite and arcs are full circles
/// (used by TRIM/EXTEND edge mode and apparent intersections).
pub fn intersect_segments_ext(s1: &Segment, s2: &Segment, extend: bool) -> Vec<Vec2> {
let tol = 1e-9;
match (s1, s2) {
(Segment::Line(a), Segment::Line(b)) => {
if extend {
line_line_infinite(a.a, a.b, b.a, b.b).map(|x| vec![x.0]).unwrap_or_default()
} else {
line_line(a, b).into_iter().collect()
}
}
(Segment::Line(l), Segment::Arc { arc, .. }) | (Segment::Arc { arc, .. }, Segment::Line(l)) => {
line_circle(l, &Circle::new(arc.center, arc.radius))
.into_iter()
.filter(|(p, t)| extend || ((-tol..=1.0 + tol).contains(t) && on_arc(arc, *p)))
.map(|(p, _)| p)
.collect()
}
(Segment::Arc { arc: a, .. }, Segment::Arc { arc: b, .. }) => {
circle_circle(&Circle::new(a.center, a.radius), &Circle::new(b.center, b.radius))
.into_iter()
.filter(|p| extend || (on_arc(a, *p) && on_arc(b, *p)))
.collect()
}
}
}
pub use intersect_segments_ext as intersect_ext;
+72
View File
@@ -0,0 +1,72 @@
//! CADCraft geometry: double-precision 2D/3D math for drafting.
//!
//! Everything a CAD kernel needs below the document model: vectors and affine transforms,
//! bounding boxes, angles, lines, circular arcs (and polyline bulges), ellipses, NURBS splines,
//! intersections, closest points, offsets and tessellation. All angles are radians,
//! counter-clockwise from +X, as in DXF.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod bounds;
mod curve;
mod intersect;
mod mat;
mod spline;
mod vec;
pub use bounds::Bounds2;
pub use curve::{Arc, Circle, Ellipse, Line, PolyVertex, Polyline, Segment, arc_to_bulge, bulge_to_arc, point_in_polygon, shoelace};
pub use intersect::{circle_circle, intersect_ext, intersect_segments, line_circle, line_line, line_line_infinite};
pub use mat::{Mat3, Mat4};
pub use spline::Spline;
pub use vec::{Vec2, Vec3};
/// Geometric tolerance for coincidence tests in drawing units.
pub const EPS: f64 = 1e-9;
pub const TAU: f64 = std::f64::consts::TAU;
pub const PI: f64 = std::f64::consts::PI;
/// Normalize an angle to `[0, 2π)`.
pub fn norm_angle(a: f64) -> f64 {
if !a.is_finite() {
return 0.0;
}
let r = a.rem_euclid(TAU);
if r >= TAU { 0.0 } else { r }
}
/// Counter-clockwise sweep from `start` to `end`, in `(0, 2π]`.
pub fn ccw_sweep(start: f64, end: f64) -> f64 {
let s = norm_angle(end - start);
if s <= EPS { TAU } else { s }
}
/// True when angle `a` lies on the CCW sweep from `start` to `end` (inclusive, with tolerance).
pub fn angle_in_sweep(a: f64, start: f64, end: f64) -> bool {
let sweep = ccw_sweep(start, end);
let d = norm_angle(a - start);
d <= sweep + 1e-12 || (TAU - d) < 1e-12
}
pub fn deg(r: f64) -> f64 {
r.to_degrees()
}
pub fn rad(d: f64) -> f64 {
d.to_radians()
}
/// Number of segments needed to approximate an arc of `radius` and `sweep` within `tol`.
pub fn arc_segments(radius: f64, sweep: f64, tol: f64) -> usize {
let r = radius.abs();
if !(r.is_finite() && sweep.is_finite()) || r <= EPS {
return 1;
}
let tol = tol.max(r * 1e-6).min(r);
// chord error e = r(1 - cos(θ/2)) → θ = 2 acos(1 - e/r)
let step = 2.0 * (1.0 - tol / r).clamp(-1.0, 1.0).acos();
let n = if step > 1e-6 { (sweep.abs() / step).ceil() } else { 4096.0 };
(n as usize).clamp(1, 4096)
}
#[cfg(test)]
mod tests;
+149
View File
@@ -0,0 +1,149 @@
use serde::{Deserialize, Serialize};
use crate::{Vec2, Vec3};
/// A 2D affine transform `[a c e; b d f; 0 0 1]` (column vectors, like SVG/PDF).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Mat3 {
pub a: f64,
pub b: f64,
pub c: f64,
pub d: f64,
pub e: f64,
pub f: f64,
}
impl Default for Mat3 {
fn default() -> Self {
Mat3::IDENTITY
}
}
impl Mat3 {
pub const IDENTITY: Mat3 = Mat3 { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 };
pub fn translate(v: Vec2) -> Mat3 {
Mat3 { e: v.x, f: v.y, ..Mat3::IDENTITY }
}
pub fn scale(sx: f64, sy: f64) -> Mat3 {
Mat3 { a: sx, d: sy, ..Mat3::IDENTITY }
}
pub fn rotate(angle: f64) -> Mat3 {
let (s, c) = angle.sin_cos();
Mat3 { a: c, b: s, c: -s, d: c, e: 0.0, f: 0.0 }
}
/// Scale about `base`.
pub fn scale_about(base: Vec2, s: f64) -> Mat3 {
Mat3::translate(base).then_before(Mat3::scale(s, s)).then_before(Mat3::translate(-base))
}
pub fn rotate_about(base: Vec2, angle: f64) -> Mat3 {
Mat3::translate(base).then_before(Mat3::rotate(angle)).then_before(Mat3::translate(-base))
}
/// Reflection across the line through `p1`, `p2`.
pub fn mirror(p1: Vec2, p2: Vec2) -> Mat3 {
let d = (p2 - p1).normalized();
if d == Vec2::ZERO {
return Mat3::IDENTITY;
}
let (c2, s2) = (d.x * d.x - d.y * d.y, 2.0 * d.x * d.y);
let r = Mat3 { a: c2, b: s2, c: s2, d: -c2, e: 0.0, f: 0.0 };
Mat3::translate(p1).then_before(r).then_before(Mat3::translate(-p1))
}
/// `self * o`: apply `o` first, then `self`.
pub fn then_before(self, o: Mat3) -> Mat3 {
Mat3 {
a: self.a * o.a + self.c * o.b,
b: self.b * o.a + self.d * o.b,
c: self.a * o.c + self.c * o.d,
d: self.b * o.c + self.d * o.d,
e: self.a * o.e + self.c * o.f + self.e,
f: self.b * o.e + self.d * o.f + self.f,
}
}
/// Apply `self` first, then `o`.
pub fn then(self, o: Mat3) -> Mat3 {
o.then_before(self)
}
pub fn apply(&self, p: Vec2) -> Vec2 {
Vec2::new(self.a * p.x + self.c * p.y + self.e, self.b * p.x + self.d * p.y + self.f)
}
pub fn apply_vec(&self, v: Vec2) -> Vec2 {
Vec2::new(self.a * v.x + self.c * v.y, self.b * v.x + self.d * v.y)
}
pub fn det(&self) -> f64 {
self.a * self.d - self.b * self.c
}
pub fn inverse(&self) -> Option<Mat3> {
let det = self.det();
if det.abs() < 1e-300 || !det.is_finite() {
return None;
}
let id = 1.0 / det;
let a = self.d * id;
let b = -self.b * id;
let c = -self.c * id;
let d = self.a * id;
let e = -(a * self.e + c * self.f);
let f = -(b * self.e + d * self.f);
Some(Mat3 { a, b, c, d, e, f })
}
/// Uniform scale factor (geometric mean of the axis scales).
pub fn scale_factor(&self) -> f64 {
self.det().abs().sqrt()
}
/// Rotation angle of the transformed X axis.
pub fn rotation(&self) -> f64 {
crate::norm_angle(self.b.atan2(self.a))
}
pub fn is_mirroring(&self) -> bool {
self.det() < 0.0
}
}
/// A 4x4 transform, row-major, for 3D views and block transforms with elevation.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Mat4 {
pub m: [[f64; 4]; 4],
}
impl Default for Mat4 {
fn default() -> Self {
Mat4::IDENTITY
}
}
impl Mat4 {
pub const IDENTITY: Mat4 = Mat4 { m: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] };
pub fn mul(&self, o: &Mat4) -> Mat4 {
let mut r = [[0.0; 4]; 4];
for (i, row) in r.iter_mut().enumerate() {
for (j, cell) in row.iter_mut().enumerate() {
*cell = (0..4).map(|k| self.m[i][k] * o.m[k][j]).sum();
}
}
Mat4 { m: r }
}
pub fn apply(&self, p: Vec3) -> Vec3 {
let m = &self.m;
let w = m[3][0] * p.x + m[3][1] * p.y + m[3][2] * p.z + m[3][3];
let w = if w.abs() < 1e-300 { 1.0 } else { w };
Vec3::new(
(m[0][0] * p.x + m[0][1] * p.y + m[0][2] * p.z + m[0][3]) / w,
(m[1][0] * p.x + m[1][1] * p.y + m[1][2] * p.z + m[1][3]) / w,
(m[2][0] * p.x + m[2][1] * p.y + m[2][2] * p.z + m[2][3]) / w,
)
}
pub fn from_mat3(t: &Mat3) -> Mat4 {
Mat4 { m: [[t.a, t.c, 0.0, t.e], [t.b, t.d, 0.0, t.f], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] }
}
/// The "arbitrary axis algorithm" frame for an extrusion direction (DXF OCS → WCS).
pub fn ocs(normal: Vec3) -> Mat4 {
let n = normal.normalized();
if n == Vec3::ZERO || (n.x.abs() < 1e-12 && n.y.abs() < 1e-12 && n.z > 0.0) {
return Mat4::IDENTITY;
}
let ax = if n.x.abs() < 1.0 / 64.0 && n.y.abs() < 1.0 / 64.0 { Vec3::new(0.0, 1.0, 0.0).cross(n) } else { Vec3::Z.cross(n) }.normalized();
let ay = n.cross(ax).normalized();
Mat4 { m: [[ax.x, ay.x, n.x, 0.0], [ax.y, ay.y, n.y, 0.0], [ax.z, ay.z, n.z, 0.0], [0.0, 0.0, 0.0, 1.0]] }
}
}
+226
View File
@@ -0,0 +1,226 @@
use serde::{Deserialize, Serialize};
use crate::{Bounds2, Vec2};
/// A (possibly rational) B-spline curve, DXF SPLINE style.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Spline {
pub degree: usize,
pub knots: Vec<f64>,
pub control: Vec<Vec2>,
/// Empty = non-rational (all weights 1).
#[serde(default)]
pub weights: Vec<f64>,
#[serde(default)]
pub fit: Vec<Vec2>,
#[serde(default)]
pub closed: bool,
}
impl Spline {
/// A clamped uniform spline over control points.
pub fn from_control(control: Vec<Vec2>, degree: usize) -> Spline {
let n = control.len();
let degree = degree.clamp(1, n.saturating_sub(1).max(1));
let knots = clamped_uniform_knots(n, degree);
Spline { degree, knots, control, weights: Vec::new(), fit: Vec::new(), closed: false }
}
/// Cubic interpolation through fit points (chord-length parametrisation, natural-ish ends
/// via a clamped knot vector: solve the banded system for control points).
pub fn from_fit_points(fit: &[Vec2]) -> Spline {
let n = fit.len();
if n < 2 {
return Spline {
degree: 1,
knots: vec![0.0, 0.0, 1.0, 1.0],
control: fit.to_vec(),
weights: Vec::new(),
fit: fit.to_vec(),
closed: false,
};
}
if n == 2 {
let mut s = Spline::from_control(fit.to_vec(), 1);
s.fit = fit.to_vec();
return s;
}
let degree = 3.min(n - 1);
// Chord-length parameters.
let mut u = vec![0.0; n];
let mut total = 0.0;
for i in 1..n {
total += fit.get(i).zip(fit.get(i - 1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0).max(1e-12);
if let Some(x) = u.get_mut(i) {
*x = total;
}
}
for x in u.iter_mut() {
*x /= total.max(1e-300);
}
// Knots by averaging.
let mut knots = vec![0.0; degree + 1];
for j in 1..n.saturating_sub(degree) {
let s: f64 = (j..j + degree).filter_map(|i| u.get(i)).sum();
knots.push(s / degree as f64);
}
knots.extend(std::iter::repeat_n(1.0, degree + 1));
// Basis matrix N[i][j] = N_j(u_i).
let mut m = vec![vec![0.0; n]; n];
for (i, ui) in u.iter().enumerate() {
let span = find_span(n - 1, degree, *ui, &knots);
let b = basis(span, *ui, degree, &knots);
for (k, v) in b.iter().enumerate() {
if let Some(cell) = m.get_mut(i).and_then(|r| r.get_mut(span + k - degree)) {
*cell = *v;
}
}
}
let xs: Vec<f64> = fit.iter().map(|p| p.x).collect();
let ys: Vec<f64> = fit.iter().map(|p| p.y).collect();
let (Some(cx), Some(cy)) = (solve(m.clone(), xs), solve(m, ys)) else {
let mut s = Spline::from_control(fit.to_vec(), degree);
s.fit = fit.to_vec();
return s;
};
let control = cx.into_iter().zip(cy).map(|(x, y)| Vec2::new(x, y)).collect();
Spline { degree, knots, control, weights: Vec::new(), fit: fit.to_vec(), closed: false }
}
pub fn is_valid(&self) -> bool {
let n = self.control.len();
n > self.degree && self.degree >= 1 && self.knots.len() == n + self.degree + 1 && self.knots.windows(2).all(|w| w.first() <= w.get(1))
}
pub fn domain(&self) -> (f64, f64) {
let lo = self.knots.get(self.degree).copied().unwrap_or(0.0);
let hi = self.knots.get(self.control.len()).copied().unwrap_or(1.0);
(lo, hi)
}
/// Evaluate at parameter `t` (de Boor via basis functions).
pub fn eval(&self, t: f64) -> Vec2 {
if !self.is_valid() {
return self.control.first().copied().unwrap_or_default();
}
let n = self.control.len() - 1;
let (lo, hi) = self.domain();
let t = t.clamp(lo, hi);
let span = find_span(n, self.degree, t, &self.knots);
let b = basis(span, t, self.degree, &self.knots);
let mut p = Vec2::ZERO;
let mut wsum = 0.0;
for (k, nb) in b.iter().enumerate() {
let idx = span + k - self.degree;
let w = if self.weights.is_empty() { 1.0 } else { self.weights.get(idx).copied().unwrap_or(1.0) };
if let Some(c) = self.control.get(idx) {
p += *c * (nb * w);
wsum += nb * w;
}
}
if wsum.abs() > 1e-300 { p / wsum } else { p }
}
pub fn tessellate(&self, tol: f64) -> Vec<Vec2> {
if !self.is_valid() {
return self.control.clone();
}
let (lo, hi) = self.domain();
// Control-polygon length guides the sample count.
let poly: f64 = self.control.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum();
let n = ((poly / tol.max(1e-9)).sqrt() * 2.0).clamp(8.0, 2000.0) as usize * self.degree.max(1);
let n = n.min(4000);
(0..=n).map(|i| self.eval(lo + (hi - lo) * i as f64 / n as f64)).collect()
}
pub fn bounds(&self) -> Bounds2 {
Bounds2::from_points(self.tessellate(1e-3))
}
}
pub(crate) fn clamped_uniform_knots(n: usize, degree: usize) -> Vec<f64> {
let mut k = vec![0.0; degree + 1];
let inner = n.saturating_sub(degree + 1);
for i in 1..=inner {
k.push(i as f64 / (inner + 1) as f64);
}
k.extend(std::iter::repeat_n(1.0, degree + 1));
k
}
fn find_span(n: usize, p: usize, u: f64, knots: &[f64]) -> usize {
let kn = knots.get(n + 1).copied().unwrap_or(1.0);
if u >= kn {
return n;
}
let mut low = p;
let mut high = n + 1;
let mut mid = (low + high) / 2;
let mut guard = 0;
while guard < 200 {
guard += 1;
let km = knots.get(mid).copied().unwrap_or(0.0);
let km1 = knots.get(mid + 1).copied().unwrap_or(1.0);
if u < km {
high = mid;
} else if u >= km1 {
low = mid;
} else {
break;
}
mid = (low + high) / 2;
}
mid
}
fn basis(span: usize, u: f64, p: usize, knots: &[f64]) -> Vec<f64> {
let mut n = vec![0.0; p + 1];
let mut left = vec![0.0; p + 1];
let mut right = vec![0.0; p + 1];
if let Some(x) = n.get_mut(0) {
*x = 1.0;
}
for j in 1..=p {
let k = |i: isize| knots.get(i.max(0) as usize).copied().unwrap_or(0.0);
left[j] = u - k(span as isize + 1 - j as isize);
right[j] = k(span as isize + j as isize) - u;
let mut saved = 0.0;
for r in 0..j {
let den = right[r + 1] + left[j - r];
let tmp = if den.abs() > 1e-300 { n[r] / den } else { 0.0 };
n[r] = saved + right[r + 1] * tmp;
saved = left[j - r] * tmp;
}
n[j] = saved;
}
n
}
/// Gaussian elimination with partial pivoting.
#[allow(clippy::needless_range_loop)]
fn solve(mut a: Vec<Vec<f64>>, mut b: Vec<f64>) -> Option<Vec<f64>> {
let n = b.len();
for c in 0..n {
let piv = (c..n).max_by(|&i, &j| a[i][c].abs().total_cmp(&a[j][c].abs()))?;
if a[piv][c].abs() < 1e-14 {
return None;
}
a.swap(c, piv);
b.swap(c, piv);
for r in c + 1..n {
let f = a[r][c] / a[c][c];
if f != 0.0 {
for k in c..n {
a[r][k] -= f * a[c][k];
}
b[r] -= f * b[c];
}
}
}
let mut x = vec![0.0; n];
for r in (0..n).rev() {
let s: f64 = (r + 1..n).map(|k| a[r][k] * x[k]).sum();
x[r] = (b[r] - s) / a[r][r];
}
Some(x)
}
+159
View File
@@ -0,0 +1,159 @@
use crate::*;
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-6
}
#[test]
fn angles_normalize() {
assert!(close(norm_angle(-PI / 2.0), 3.0 * PI / 2.0));
assert!(close(ccw_sweep(0.0, 0.0), TAU));
assert!(angle_in_sweep(0.1, 6.0, 0.5));
assert!(!angle_in_sweep(3.0, 6.0, 0.5));
}
#[test]
fn mat_inverse_roundtrip() {
let m = Mat3::rotate_about(Vec2::new(3.0, 4.0), 0.7).then(Mat3::scale(2.0, 2.0));
let inv = m.inverse().unwrap();
let p = Vec2::new(10.0, -2.0);
let q = inv.apply(m.apply(p));
assert!(q.near(p, 1e-9));
}
#[test]
fn mirror_matrix() {
let m = Mat3::mirror(Vec2::ZERO, Vec2::new(1.0, 1.0));
assert!(m.apply(Vec2::new(1.0, 0.0)).near(Vec2::new(0.0, 1.0), 1e-12));
assert!(m.is_mirroring());
}
#[test]
fn circle_through_three_points() {
let c = Circle::from_3_points(Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(-1.0, 0.0)).unwrap();
assert!(c.center.near(Vec2::ZERO, 1e-9));
assert!(close(c.radius, 1.0));
assert!(Circle::from_3_points(Vec2::ZERO, Vec2::X, Vec2::X * 2.0).is_none());
}
#[test]
fn arc_three_points_direction() {
let a = Arc::from_3_points(Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(-1.0, 0.0)).unwrap();
assert!(close(a.sweep(), PI));
assert!(a.mid_point().near(Vec2::new(0.0, 1.0), 1e-9));
let b = Arc::from_3_points(Vec2::new(1.0, 0.0), Vec2::new(0.0, -1.0), Vec2::new(-1.0, 0.0)).unwrap();
assert!(b.mid_point().near(Vec2::new(0.0, -1.0), 1e-9));
}
#[test]
fn arc_bounds_include_quadrants() {
let a = Arc::new(Vec2::ZERO, 2.0, 0.0, PI);
let b = a.bounds();
assert!(close(b.max.y, 2.0));
assert!(close(b.min.y, 0.0));
}
#[test]
fn bulge_semicircle() {
let (arc, ccw) = bulge_to_arc(Vec2::new(0.0, 0.0), Vec2::new(2.0, 0.0), 1.0).unwrap();
assert!(ccw);
assert!(arc.center.near(Vec2::new(1.0, 0.0), 1e-9));
assert!(close(arc.radius, 1.0));
// CCW from (0,0) to (2,0) around (1,0) passes below.
assert!(arc.mid_point().near(Vec2::new(1.0, -1.0), 1e-9));
let (arc2, ccw2) = bulge_to_arc(Vec2::new(0.0, 0.0), Vec2::new(2.0, 0.0), -1.0).unwrap();
assert!(!ccw2);
assert!(arc2.mid_point().near(Vec2::new(1.0, 1.0), 1e-9));
}
#[test]
fn bulge_quarter_arc() {
let b = arc_to_bulge(PI / 2.0);
let (arc, _) = bulge_to_arc(Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), b).unwrap();
assert!(arc.center.near(Vec2::ZERO, 1e-9));
assert!(close(arc.sweep(), PI / 2.0));
}
#[test]
fn polyline_area_and_length() {
let p = Polyline::from_points(&[Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(4.0, 3.0), Vec2::new(0.0, 3.0)], true);
assert!(close(p.area(), 12.0));
assert!(close(p.len(), 14.0));
assert!(p.contains(Vec2::new(1.0, 1.0)));
assert!(!p.contains(Vec2::new(5.0, 1.0)));
}
#[test]
fn line_intersections() {
let a = Line::new(Vec2::new(0.0, 0.0), Vec2::new(10.0, 10.0));
let b = Line::new(Vec2::new(0.0, 10.0), Vec2::new(10.0, 0.0));
assert!(line_line(&a, &b).unwrap().near(Vec2::new(5.0, 5.0), 1e-9));
let c = Line::new(Vec2::new(20.0, 0.0), Vec2::new(30.0, -10.0));
assert!(line_line(&a, &c).is_none());
}
#[test]
fn line_circle_hits() {
let l = Line::new(Vec2::new(-5.0, 0.0), Vec2::new(5.0, 0.0));
let hits = line_circle(&l, &Circle::new(Vec2::ZERO, 2.0));
assert_eq!(hits.len(), 2);
let segs = intersect_segments(&Segment::Line(l), &Segment::Arc { arc: Arc::new(Vec2::ZERO, 2.0, 0.0, PI / 2.0), ccw: true });
assert_eq!(segs.len(), 1);
assert!(segs[0].near(Vec2::new(2.0, 0.0), 1e-9));
}
#[test]
fn circle_circle_hits() {
let h = circle_circle(&Circle::new(Vec2::ZERO, 5.0), &Circle::new(Vec2::new(8.0, 0.0), 5.0));
assert_eq!(h.len(), 2);
assert!(h.iter().all(|p| close(p.x, 4.0) && close(p.y.abs(), 3.0)));
}
#[test]
fn spline_interpolates_fit_points() {
let fit = [Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0), Vec2::new(3.0, 1.0), Vec2::new(4.0, 4.0), Vec2::new(6.0, 0.0)];
let s = Spline::from_fit_points(&fit);
assert!(s.is_valid());
let pts = s.tessellate(1e-4);
for f in fit {
let d = pts.iter().map(|p| p.dist(f)).fold(f64::INFINITY, f64::min);
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));
}
#[test]
fn ellipse_points() {
let e = Ellipse::full(Vec2::ZERO, Vec2::new(4.0, 0.0), 0.5);
assert!(e.at_param(PI / 2.0).near(Vec2::new(0.0, 2.0), 1e-9));
let b = e.bounds();
assert!((b.width() - 8.0).abs() < 1e-3);
}
#[test]
fn segment_offset() {
let s = Segment::Arc { arc: Arc::new(Vec2::ZERO, 5.0, 0.0, PI), ccw: true };
let o = s.offset(1.0).unwrap();
if let Segment::Arc { arc, .. } = o {
assert!(close(arc.radius, 4.0))
} else {
panic!()
}
assert!(s.offset(6.0).is_none());
}
#[test]
fn arc_segments_bounded() {
assert_eq!(arc_segments(0.0, 1.0, 0.1), 1);
assert!(arc_segments(1e9, TAU, 1e-12) <= 4096);
assert!(arc_segments(f64::NAN, TAU, 0.1) == 1);
}
#[test]
fn ocs_identity_for_z() {
assert_eq!(Mat4::ocs(Vec3::Z), Mat4::IDENTITY);
let m = Mat4::ocs(Vec3::new(0.0, 0.0, -1.0));
let p = m.apply(Vec3::new(1.0, 0.0, 0.0));
assert!((p.x + 1.0).abs() < 1e-9);
}
+199
View File
@@ -0,0 +1,199 @@
use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
use serde::{Deserialize, Serialize};
/// A 2D point or vector in drawing units.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Vec2 {
pub x: f64,
pub y: f64,
}
impl Vec2 {
pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };
pub const X: Vec2 = Vec2 { x: 1.0, y: 0.0 };
pub const Y: Vec2 = Vec2 { x: 0.0, y: 1.0 };
pub const fn new(x: f64, y: f64) -> Self {
Vec2 { x, y }
}
/// Unit vector at `angle` radians.
pub fn from_angle(angle: f64) -> Self {
Vec2::new(angle.cos(), angle.sin())
}
pub fn polar(center: Vec2, radius: f64, angle: f64) -> Self {
center + Vec2::from_angle(angle) * radius
}
pub fn dot(self, o: Vec2) -> f64 {
self.x * o.x + self.y * o.y
}
/// z of the 3D cross product.
pub fn cross(self, o: Vec2) -> f64 {
self.x * o.y - self.y * o.x
}
pub fn len(self) -> f64 {
self.x.hypot(self.y)
}
pub fn len2(self) -> f64 {
self.dot(self)
}
pub fn dist(self, o: Vec2) -> f64 {
(self - o).len()
}
pub fn angle(self) -> f64 {
crate::norm_angle(self.y.atan2(self.x))
}
pub fn angle_to(self, o: Vec2) -> f64 {
(o - self).angle()
}
/// Unit vector, or zero for a zero-length vector.
pub fn normalized(self) -> Vec2 {
let l = self.len();
if l > crate::EPS { self / l } else { Vec2::ZERO }
}
/// Rotated 90° counter-clockwise.
pub fn perp(self) -> Vec2 {
Vec2::new(-self.y, self.x)
}
pub fn rotate(self, a: f64) -> Vec2 {
let (s, c) = a.sin_cos();
Vec2::new(self.x * c - self.y * s, self.x * s + self.y * c)
}
pub fn rotate_about(self, center: Vec2, a: f64) -> Vec2 {
center + (self - center).rotate(a)
}
pub fn lerp(self, o: Vec2, t: f64) -> Vec2 {
self + (o - self) * t
}
pub fn mid(self, o: Vec2) -> Vec2 {
self.lerp(o, 0.5)
}
pub fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite()
}
pub fn near(self, o: Vec2, tol: f64) -> bool {
(self - o).len2() <= tol * tol
}
pub fn to3(self, z: f64) -> Vec3 {
Vec3::new(self.x, self.y, z)
}
pub fn min(self, o: Vec2) -> Vec2 {
Vec2::new(self.x.min(o.x), self.y.min(o.y))
}
pub fn max(self, o: Vec2) -> Vec2 {
Vec2::new(self.x.max(o.x), self.y.max(o.y))
}
/// Mirror across the infinite line through `a` and `b`.
pub fn mirror(self, a: Vec2, b: Vec2) -> Vec2 {
let d = (b - a).normalized();
if d == Vec2::ZERO {
return self;
}
let v = self - a;
let proj = d * v.dot(d);
a + proj * 2.0 - v
}
}
impl Add for Vec2 {
type Output = Vec2;
fn add(self, o: Vec2) -> Vec2 {
Vec2::new(self.x + o.x, self.y + o.y)
}
}
impl AddAssign for Vec2 {
fn add_assign(&mut self, o: Vec2) {
self.x += o.x;
self.y += o.y;
}
}
impl Sub for Vec2 {
type Output = Vec2;
fn sub(self, o: Vec2) -> Vec2 {
Vec2::new(self.x - o.x, self.y - o.y)
}
}
impl SubAssign for Vec2 {
fn sub_assign(&mut self, o: Vec2) {
self.x -= o.x;
self.y -= o.y;
}
}
impl Mul<f64> for Vec2 {
type Output = Vec2;
fn mul(self, s: f64) -> Vec2 {
Vec2::new(self.x * s, self.y * s)
}
}
impl Div<f64> for Vec2 {
type Output = Vec2;
fn div(self, s: f64) -> Vec2 {
if s == 0.0 { Vec2::ZERO } else { Vec2::new(self.x / s, self.y / s) }
}
}
impl Neg for Vec2 {
type Output = Vec2;
fn neg(self) -> Vec2 {
Vec2::new(-self.x, -self.y)
}
}
/// A 3D point or vector.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Vec3 {
pub x: f64,
pub y: f64,
pub z: f64,
}
impl Vec3 {
pub const ZERO: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 0.0 };
pub const Z: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 1.0 };
pub const fn new(x: f64, y: f64, z: f64) -> Self {
Vec3 { x, y, z }
}
pub fn xy(self) -> Vec2 {
Vec2::new(self.x, self.y)
}
pub fn dot(self, o: Vec3) -> f64 {
self.x * o.x + self.y * o.y + self.z * o.z
}
pub fn cross(self, o: Vec3) -> Vec3 {
Vec3::new(self.y * o.z - self.z * o.y, self.z * o.x - self.x * o.z, self.x * o.y - self.y * o.x)
}
pub fn len(self) -> f64 {
self.dot(self).sqrt()
}
pub fn normalized(self) -> Vec3 {
let l = self.len();
if l > crate::EPS { self * (1.0 / l) } else { Vec3::ZERO }
}
pub fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
}
}
impl Add for Vec3 {
type Output = Vec3;
fn add(self, o: Vec3) -> Vec3 {
Vec3::new(self.x + o.x, self.y + o.y, self.z + o.z)
}
}
impl Sub for Vec3 {
type Output = Vec3;
fn sub(self, o: Vec3) -> Vec3 {
Vec3::new(self.x - o.x, self.y - o.y, self.z - o.z)
}
}
impl Mul<f64> for Vec3 {
type Output = Vec3;
fn mul(self, s: f64) -> Vec3 {
Vec3::new(self.x * s, self.y * s, self.z * s)
}
}
impl Neg for Vec3 {
type Output = Vec3;
fn neg(self) -> Vec3 {
Vec3::new(-self.x, -self.y, -self.z)
}
}
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "cadcraft-io"
description = "CADCraft file formats: DXF read/write mapping, SVG and PNG export"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
cadcraft-geom = { workspace = true }
cadcraft-color = { workspace = true }
cadcraft-doc = { workspace = true }
cadcraft-dxf = { workspace = true }
cadcraft-render = { workspace = true }
thiserror = { workspace = true }
+791
View File
@@ -0,0 +1,791 @@
//! DXF → Drawing.
use std::collections::HashMap;
use cadcraft_color::{Color, Rgb};
use cadcraft_doc::*;
use cadcraft_dxf::{Tag, records, sections};
use cadcraft_geom::{PolyVertex, Spline, Vec2, Vec3};
use crate::{IoError, Result};
/// Value lookup helpers over an entity's tags.
struct T<'a>(&'a [Tag]);
impl T<'_> {
fn f(&self, code: i32) -> Option<f64> {
self.0.iter().find(|t| t.code == code).map(Tag::f64)
}
fn fd(&self, code: i32, d: f64) -> f64 {
self.f(code).unwrap_or(d)
}
fn i(&self, code: i32) -> Option<i64> {
self.0.iter().find(|t| t.code == code).map(Tag::i64)
}
fn s(&self, code: i32) -> Option<String> {
self.0.iter().find(|t| t.code == code).map(Tag::str)
}
fn p(&self, code: i32) -> Vec3 {
Vec3::new(self.fd(code, 0.0), self.fd(code + 10, 0.0), self.fd(code + 20, 0.0))
}
fn all_f(&self, code: i32) -> Vec<f64> {
self.0.iter().filter(|t| t.code == code).map(Tag::f64).collect()
}
fn pts(&self, code: i32) -> Vec<Vec2> {
let xs = self.all_f(code);
let ys = self.all_f(code + 10);
xs.into_iter().zip(ys).map(|(x, y)| Vec2::new(x, y)).collect()
}
}
fn common(t: &T) -> Common {
let mut c = Common { layer: t.s(8).unwrap_or_else(|| "0".into()), linetype: t.s(6).unwrap_or_else(|| "ByLayer".into()), ..Common::default() };
if let Some(v) = t.i(62) {
c.color = Color::from_aci(v as i16);
if v < 0 {
c.color = Color::ByLayer;
c.visible = true;
}
}
if let Some(tc) = t.i(420) {
c.color = Color::True(Rgb::from_u32(tc as u32));
}
if let Some(lw) = t.i(370) {
c.lineweight = Lineweight::from_dxf(lw as i16);
}
if let Some(s) = t.f(48) {
c.ltscale = if s > 0.0 { s } else { 1.0 };
}
if t.i(60) == Some(1) {
c.visible = false;
}
c.thickness = t.fd(39, 0.0);
c.extrusion = Vec3::new(t.fd(210, 0.0), t.fd(220, 0.0), t.fd(230, 1.0));
c
}
/// Apply the OCS → WCS transform for 2D entities with a non-default extrusion.
fn ocs(c: &Common, p: Vec3) -> Vec3 {
if (c.extrusion.z - 1.0).abs() < 1e-12 && c.extrusion.x.abs() < 1e-12 && c.extrusion.y.abs() < 1e-12 {
p
} else {
cadcraft_geom::Mat4::ocs(c.extrusion).apply(p)
}
}
fn text_from(t: &T) -> Text {
let h = match t.i(72).unwrap_or(0) {
1 => HAlign::Center,
2 => HAlign::Right,
3 => HAlign::Aligned,
4 => HAlign::Middle,
5 => HAlign::Fit,
_ => HAlign::Left,
};
let v = match t.i(73).or_else(|| t.i(74)).unwrap_or(0) {
1 => VAlign::Bottom,
2 => VAlign::Middle,
3 => VAlign::Top,
_ => VAlign::Baseline,
};
let align = if t.f(11).is_some() { Some(t.p(11)) } else { None };
Text {
insert: t.p(10),
align_pt: if h == HAlign::Left && v == VAlign::Baseline { None } else { align },
height: t.fd(40, 0.2).max(1e-9),
value: t.s(1).unwrap_or_default(),
rotation: t.fd(50, 0.0).to_radians(),
width_factor: t.fd(41, 1.0),
oblique: t.fd(51, 0.0).to_radians(),
style: t.s(7).unwrap_or_else(|| "Standard".into()),
halign: h,
valign: v,
}
}
/// Parse one entity record. POLYLINE/INSERT followers are handled by the caller.
fn entity(kind: &str, tags: &[Tag]) -> Option<(Common, EntityKind)> {
let t = T(tags);
let c = common(&t);
let k = match kind {
"LINE" => EntityKind::Line(Line { a: t.p(10), b: t.p(11) }),
"POINT" => EntityKind::Point(Point { p: t.p(10), angle: t.fd(50, 0.0).to_radians() }),
"CIRCLE" => EntityKind::Circle(Circle { center: ocs(&c, t.p(10)), radius: t.fd(40, 1.0).abs() }),
"ARC" => {
let mut a =
Arc { center: ocs(&c, t.p(10)), radius: t.fd(40, 1.0).abs(), start: t.fd(50, 0.0).to_radians(), end: t.fd(51, 360.0).to_radians() };
if c.extrusion.z < 0.0 {
// Mirrored OCS: angles run the other way.
let (s, e) = (std::f64::consts::PI - a.end, std::f64::consts::PI - a.start);
a.start = cadcraft_geom::norm_angle(s);
a.end = cadcraft_geom::norm_angle(e);
}
EntityKind::Arc(a)
}
"ELLIPSE" => EntityKind::Ellipse(Ellipse {
center: t.p(10),
major: t.p(11),
ratio: t.fd(40, 1.0).clamp(1e-9, 1.0),
start: t.fd(41, 0.0),
end: t.fd(42, std::f64::consts::TAU),
}),
"LWPOLYLINE" => {
let mut verts = Vec::new();
let mut cur: Option<PolyVertex> = None;
for tg in tags {
match tg.code {
10 => {
if let Some(v) = cur.take() {
verts.push(v);
}
cur = Some(PolyVertex { p: Vec2::new(tg.f64(), 0.0), ..Default::default() });
}
20 => {
if let Some(v) = cur.as_mut() {
v.p.y = tg.f64();
}
}
40 => {
if let Some(v) = cur.as_mut() {
v.start_width = tg.f64();
}
}
41 => {
if let Some(v) = cur.as_mut() {
v.end_width = tg.f64();
}
}
42 => {
if let Some(v) = cur.as_mut() {
v.bulge = tg.f64();
}
}
_ => {}
}
}
verts.extend(cur);
let flags = t.i(70).unwrap_or(0);
if c.extrusion.z < 0.0 {
for v in &mut verts {
v.p.x = -v.p.x;
v.bulge = -v.bulge;
}
}
EntityKind::LwPolyline(LwPolyline {
vertices: verts,
closed: flags & 1 != 0,
const_width: t.fd(43, 0.0),
elevation: t.fd(38, 0.0),
plinegen: flags & 128 != 0,
})
}
"SPLINE" => {
let degree = t.i(71).unwrap_or(3).clamp(1, 10) as usize;
let knots = t.all_f(40);
let control = t.pts(10);
let weights = t.all_f(41);
let fit = t.pts(11);
let mut sp = Spline { degree, knots, control, weights, fit: fit.clone(), closed: t.i(70).unwrap_or(0) & 1 != 0 };
if !sp.is_valid() && fit.len() >= 2 {
sp = Spline::from_fit_points(&fit);
} else if !sp.is_valid() && sp.control.len() >= 2 {
sp = Spline::from_control(sp.control.clone(), degree);
}
EntityKind::Spline(sp)
}
"RAY" => EntityKind::Ray(RayLine { base: t.p(10), dir: t.p(11) }),
"XLINE" => EntityKind::XLine(RayLine { base: t.p(10), dir: t.p(11) }),
"TEXT" => EntityKind::Text(text_from(&t)),
"MTEXT" => {
// Contents: code 3 chunks followed by code 1.
let mut contents = String::new();
for tg in tags.iter().filter(|x| x.code == 3) {
contents.push_str(&tg.str());
}
contents.push_str(&t.s(1).unwrap_or_default());
let rotation = match (t.f(11), t.f(21)) {
(Some(x), Some(y)) if x != 0.0 || y != 0.0 => Vec2::new(x, y).angle(),
_ => t.fd(50, 0.0).to_radians(),
};
EntityKind::MText(MText {
insert: t.p(10),
height: t.fd(40, 0.2).max(1e-9),
width: t.fd(41, 0.0).max(0.0),
attach: t.i(71).unwrap_or(1).clamp(1, 9) as u8,
rotation,
style: t.s(7).unwrap_or_else(|| "Standard".into()),
contents,
line_spacing: t.fd(44, 1.0),
})
}
"ATTDEF" => EntityKind::AttDef(Attrib {
tag: t.s(2).unwrap_or_default(),
text: text_from(&t),
invisible: t.i(70).unwrap_or(0) & 1 != 0,
constant: t.i(70).unwrap_or(0) & 2 != 0,
prompt: t.s(3).unwrap_or_default(),
}),
"INSERT" => EntityKind::Insert(Insert {
block: t.s(2).unwrap_or_default(),
insert: t.p(10),
scale: Vec3::new(t.fd(41, 1.0), t.fd(42, 1.0), t.fd(43, 1.0)),
rotation: t.fd(50, 0.0).to_radians(),
attribs: Vec::new(),
cols: t.i(70).unwrap_or(1).clamp(1, 10_000) as u32,
rows: t.i(71).unwrap_or(1).clamp(1, 10_000) as u32,
col_spacing: t.fd(44, 0.0),
row_spacing: t.fd(45, 0.0),
}),
"DIMENSION" => {
let ty = t.i(70).unwrap_or(0) & 0x0f;
let kind = match ty {
0 => DimKind::Linear { rotation: t.fd(50, 0.0).to_radians() },
1 => DimKind::Aligned,
2 => DimKind::Angular,
3 => DimKind::Diameter,
4 => DimKind::Radius,
5 => DimKind::Angular3P,
6 => DimKind::Ordinate { x_type: t.i(70).unwrap_or(0) & 64 != 0 },
_ => DimKind::Aligned,
};
EntityKind::Dimension(Dimension {
kind,
defpt: t.p(10),
text_mid: t.p(11),
p13: t.p(13),
p14: t.p(14),
p15: t.p(15),
p16: t.p(16),
text: t.s(1).unwrap_or_default(),
style: t.s(3).unwrap_or_else(|| "Standard".into()),
measurement: t.fd(42, 0.0),
text_rotation: t.fd(53, 0.0).to_radians(),
user_text_pos: t.i(70).unwrap_or(0) & 128 != 0,
block: t.s(2).filter(|s| !s.is_empty()),
})
}
"LEADER" => EntityKind::Leader(Leader {
vertices: t.pts(10).into_iter().map(|p| p.to3(0.0)).collect(),
arrow: t.i(71).unwrap_or(1) != 0,
spline: t.i(72).unwrap_or(0) != 0,
style: t.s(3).unwrap_or_else(|| "Standard".into()),
}),
"SOLID" | "TRACE" => {
let corners = [t.p(10), t.p(11), t.p(12), if t.f(13).is_some() { t.p(13) } else { t.p(12) }];
let corners = corners.map(|p| ocs(&c, p));
if kind == "SOLID" { EntityKind::Solid(Solid { corners }) } else { EntityKind::Trace(Solid { corners }) }
}
"3DFACE" => EntityKind::Face3d(Face3d { corners: [t.p(10), t.p(11), t.p(12), t.p(13)], hidden_edges: t.i(70).unwrap_or(0) as u8 }),
"HATCH" => hatch(tags, &t)?,
"VIEWPORT" => EntityKind::Viewport(Viewport {
center: t.p(10),
width: t.fd(40, 1.0),
height: t.fd(41, 1.0),
view_center: Vec2::new(t.fd(12, 0.0), t.fd(22, 0.0)),
view_height: t.fd(45, 1.0),
id: t.i(69).unwrap_or(0) as u32,
locked: t.i(90).unwrap_or(0) & 16384 != 0,
frozen_layers: Vec::new(),
}),
"WIPEOUT" => {
let o = t.p(10);
let u = t.p(11);
let v = t.p(12);
let pts: Vec<Vec2> = t.pts(14).into_iter().map(|q| o.xy() + u.xy() * (q.x + 0.5) + v.xy() * (q.y + 0.5)).collect();
EntityKind::Wipeout(Wipeout { boundary: pts })
}
"IMAGE" => {
EntityKind::Image(Image { insert: t.p(10), u: t.p(11), v: t.p(12), size: Vec2::new(t.fd(13, 1.0), t.fd(23, 1.0)), path: String::new() })
}
other => EntityKind::Unknown(Unknown {
dxf_type: other.to_string(),
tags: tags.iter().map(|tg| RawTag { code: tg.code, value: tg.str() }).collect(),
}),
};
Some((c, k))
}
fn hatch(tags: &[Tag], t: &T) -> Option<EntityKind> {
let pattern = t.s(2).unwrap_or_else(|| "SOLID".into());
let solid = t.i(70).unwrap_or(0) == 1;
let n_loops = t.i(91).unwrap_or(0).clamp(0, 100_000) as usize;
let mut loops = Vec::new();
// Walk the boundary data after the 91 tag.
let start = tags.iter().position(|x| x.code == 91).map(|i| i + 1)?;
let mut i = start;
let get = |i: usize| tags.get(i);
for _ in 0..n_loops {
// 92: loop type flags.
while get(i).is_some_and(|x| x.code != 92) {
i += 1;
}
let flags = get(i)?.i64();
i += 1;
let outer = flags & 1 != 0;
let mut verts: Vec<PolyVertex> = Vec::new();
if flags & 2 != 0 {
// Polyline boundary: 72 has-bulge, 73 closed, 93 count, then 10/20/42.
let has_bulge = get(i).filter(|x| x.code == 72).map(Tag::i64).unwrap_or(0) != 0;
while get(i).is_some_and(|x| x.code != 93) {
i += 1;
}
let n = get(i)?.i64().clamp(0, 1_000_000) as usize;
i += 1;
for _ in 0..n {
let x = get(i).filter(|t| t.code == 10)?.f64();
let y = get(i + 1).filter(|t| t.code == 20)?.f64();
i += 2;
let mut b = 0.0;
if has_bulge && get(i).is_some_and(|t| t.code == 42) {
b = get(i)?.f64();
i += 1;
}
verts.push(PolyVertex::with_bulge(Vec2::new(x, y), b));
}
} else {
// Edge boundary: 93 edge count, each 72 edge type.
while get(i).is_some_and(|x| x.code != 93) {
i += 1;
}
let n = get(i)?.i64().clamp(0, 1_000_000) as usize;
i += 1;
for _ in 0..n {
while get(i).is_some_and(|x| x.code != 72) {
i += 1;
}
let ty = get(i)?.i64();
i += 1;
let f = |i: usize| get(i).map(Tag::f64).unwrap_or(0.0);
match ty {
1 => {
let a = Vec2::new(f(i), f(i + 1));
let b = Vec2::new(f(i + 2), f(i + 3));
i += 4;
if verts.last().is_none_or(|l| !l.p.near(a, 1e-9)) {
verts.push(PolyVertex::new(a));
}
verts.push(PolyVertex::new(b));
}
2 => {
let c = Vec2::new(f(i), f(i + 1));
let r = f(i + 2);
let sa = f(i + 3).to_radians();
let ea = f(i + 4).to_radians();
let ccw = get(i + 5).map(Tag::i64).unwrap_or(1) != 0;
i += 6;
let (s, e) = if ccw { (sa, ea) } else { (-sa, -ea) };
let p0 = Vec2::polar(c, r, s);
let p1 = Vec2::polar(c, r, e);
let sweep = if ccw { cadcraft_geom::ccw_sweep(s, e) } else { -cadcraft_geom::ccw_sweep(e, s) };
if verts.last().is_none_or(|l| !l.p.near(p0, 1e-9)) {
verts.push(PolyVertex::new(p0));
}
if let Some(l) = verts.last_mut() {
l.bulge = cadcraft_geom::arc_to_bulge(sweep);
}
verts.push(PolyVertex::new(p1));
}
3 => {
// Elliptic arc: approximate with points.
let c = Vec2::new(f(i), f(i + 1));
let m = Vec2::new(f(i + 2), f(i + 3));
let ratio = f(i + 4);
let sa = f(i + 5).to_radians();
let ea = f(i + 6).to_radians();
i += 8;
let e = cadcraft_geom::Ellipse { center: c, major: m, ratio, start: sa, end: ea };
let mut pts = Vec::new();
e.tessellate(m.len() * 1e-3, &mut pts);
verts.extend(pts.into_iter().map(PolyVertex::new));
}
4 => {
// Spline edge: 94 degree, 73 rational, 74 periodic, 95 knots, 96 ctrl.
let _deg = get(i).map(Tag::i64).unwrap_or(3);
while get(i).is_some_and(|x| x.code != 96) {
i += 1;
}
let nc = get(i).map(Tag::i64).unwrap_or(0).clamp(0, 100_000) as usize;
i += 1;
let mut ctrl = Vec::new();
for _ in 0..nc {
if get(i).is_some_and(|t| t.code == 10) {
ctrl.push(Vec2::new(f(i), f(i + 1)));
i += 2;
if get(i).is_some_and(|t| t.code == 42) {
i += 1;
}
}
}
let sp = Spline::from_control(ctrl, 3);
verts.extend(sp.tessellate(1e-3).into_iter().map(PolyVertex::new));
}
_ => {}
}
}
}
if verts.len() > 1 && verts.first().map(|f| f.p).zip(verts.last().map(|l| l.p)).is_some_and(|(a, b)| a.near(b, 1e-9)) {
verts.pop();
}
loops.push(HatchLoop { vertices: verts, outer });
}
Some(EntityKind::Hatch(Hatch {
pattern: pattern.to_ascii_uppercase(),
solid: solid || pattern.eq_ignore_ascii_case("SOLID"),
loops,
scale: t.fd(41, 1.0),
angle: t.fd(52, 0.0).to_radians(),
associative: t.i(71).unwrap_or(0) != 0,
style: t.i(75).unwrap_or(0) as u8,
elevation: 0.0,
gradient: None,
origin: Vec2::ZERO,
background: None,
}))
}
/// Parse a run of entity records (ENTITIES section or a block's body) into entities.
fn parse_entities(recs: &[(String, Vec<Tag>)], d: &mut Drawing) -> Vec<(Option<String>, bool, Entity)> {
let mut out = Vec::new();
let mut i = 0;
while let Some((kind, tags)) = recs.get(i) {
let t = T(tags);
let owner = t.s(330);
let paper = t.i(67) == Some(1);
let handle = t.s(5).and_then(|h| Handle::parse_hex(&h));
let mut kindent = entity(kind, tags);
i += 1;
match kind.as_str() {
"POLYLINE" => {
let flags = t.i(70).unwrap_or(0);
let mut pts: Vec<(Vec3, f64, f64, f64)> = Vec::new();
while let Some((k2, t2)) = recs.get(i) {
if k2 == "VERTEX" {
let tt = T(t2);
if tt.i(70).unwrap_or(0) & 16 == 0 {
pts.push((tt.p(10), tt.fd(42, 0.0), tt.fd(40, 0.0), tt.fd(41, 0.0)));
}
i += 1;
} else {
if k2 == "SEQEND" {
i += 1;
}
break;
}
}
let c = common(&t);
let k = if flags & (8 | 16 | 64) != 0 {
EntityKind::Polyline3d(Polyline3d { points: pts.iter().map(|p| p.0).collect(), closed: flags & 1 != 0 })
} else {
EntityKind::LwPolyline(LwPolyline {
vertices: pts.iter().map(|p| PolyVertex { p: p.0.xy(), bulge: p.1, start_width: p.2, end_width: p.3 }).collect(),
closed: flags & 1 != 0,
const_width: t.fd(40, 0.0).min(t.fd(41, 0.0)).max(0.0),
elevation: t.p(10).z,
plinegen: flags & 128 != 0,
})
};
kindent = Some((c, k));
}
"INSERT" => {
if t.i(66) == Some(1) {
let mut attribs = Vec::new();
while let Some((k2, t2)) = recs.get(i) {
if k2 == "ATTRIB" {
let tt = T(t2);
attribs.push(Attrib {
tag: tt.s(2).unwrap_or_default(),
text: text_from(&tt),
invisible: tt.i(70).unwrap_or(0) & 1 != 0,
constant: false,
prompt: String::new(),
});
i += 1;
} else {
if k2 == "SEQEND" {
i += 1;
}
break;
}
}
if let Some((_, EntityKind::Insert(ins))) = kindent.as_mut() {
ins.attribs = attribs;
}
}
}
"SEQEND" | "VERTEX" | "ATTRIB" => continue,
_ => {}
}
if let Some((c, k)) = kindent {
let h = match handle {
Some(h) => {
d.bump_handseed(h);
h
}
None => d.new_handle(),
};
out.push((owner, paper, Entity { handle: h, common: c, kind: k }));
}
}
// Assign fresh handles to duplicates (hostile files).
let mut seen = std::collections::HashSet::new();
for (_, _, e) in &mut out {
if !seen.insert(e.handle) {
e.handle = d.new_handle();
seen.insert(e.handle);
}
}
out
}
fn header(tags: &[Tag], d: &mut Drawing) {
let mut i = 0;
while let Some(t) = tags.get(i) {
if t.code == 9 {
let name = t.str().trim_start_matches('$').to_ascii_uppercase();
i += 1;
let mut vals: Vec<&Tag> = Vec::new();
while let Some(v) = tags.get(i) {
if v.code == 9 {
break;
}
vals.push(v);
i += 1;
}
let hv = match vals.as_slice() {
[x, y, z] if x.code == 10 => HVal::Point(Vec3::new(x.f64(), y.f64(), z.f64())),
[x, y] if x.code == 10 => HVal::Point(Vec3::new(x.f64(), y.f64(), 0.0)),
[v] => match &v.value {
cadcraft_dxf::Value::Real(r) => HVal::Real(*r),
cadcraft_dxf::Value::Int(n) => HVal::Int(*n),
cadcraft_dxf::Value::Bool(b) => HVal::Int(i64::from(*b)),
other => HVal::Str(other.as_str()),
},
_ => continue,
};
d.header.set(&name, hv);
} else {
i += 1;
}
}
}
fn tables(tags: &[Tag], d: &mut Drawing, block_records: &mut HashMap<String, String>) {
for (kind, tg) in records(tags) {
let t = T(&tg);
match kind.as_str() {
"LAYER" => {
let name = t.s(2).unwrap_or_default();
if name.is_empty() {
continue;
}
let aci = t.i(62).unwrap_or(7);
let flags = t.i(70).unwrap_or(0);
let mut l = Layer {
name: name.clone(),
color: Color::Index(aci.unsigned_abs().clamp(1, 255) as u8),
linetype: t.s(6).unwrap_or_else(|| "Continuous".into()),
lineweight: t.i(370).map(|v| Lineweight::from_dxf(v as i16)).unwrap_or(Lineweight::Default),
on: aci >= 0,
frozen: flags & 1 != 0,
locked: flags & 4 != 0,
plot: t.i(290).unwrap_or(1) != 0,
..Layer::default()
};
if let Some(tc) = t.i(420) {
l.color = Color::True(Rgb::from_u32(tc as u32));
}
match d.layer_mut(&name) {
Some(x) => *x = l,
None => d.layers.push(l),
}
}
"LTYPE" => {
let name = t.s(2).unwrap_or_default();
if name.is_empty() || d.linetype(&name).is_some() {
continue;
}
let pattern = tg.iter().filter(|x| x.code == 49).map(|x| DashElement::dash(x.f64())).collect();
d.linetypes.push(Linetype { name, description: t.s(3).unwrap_or_default(), pattern });
}
"STYLE" => {
let name = t.s(2).unwrap_or_default();
if name.is_empty() {
continue;
}
let st = TextStyle {
name: name.clone(),
font: t.s(3).unwrap_or_default(),
big_font: t.s(4).unwrap_or_default(),
height: t.fd(40, 0.0),
width_factor: t.fd(41, 1.0),
oblique: t.fd(50, 0.0).to_radians(),
..Default::default()
};
match d.text_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case(&name)) {
Some(x) => *x = st,
None => d.text_styles.push(st),
}
}
"DIMSTYLE" => {
let name = t.s(2).unwrap_or_default();
if name.is_empty() {
continue;
}
let def = DimStyle::default();
let st = DimStyle {
name: name.clone(),
scale: t.fd(40, 1.0),
arrow_size: t.fd(41, def.arrow_size),
ext_offset: t.fd(42, def.ext_offset),
ext_extend: t.fd(44, def.ext_extend),
text_height: t.fd(140, def.text_height),
tick_size: t.fd(142, 0.0),
linear_factor: t.fd(144, 1.0),
text_gap: t.fd(147, def.text_gap),
text_above: t.i(77).unwrap_or(0) as u8,
decimals: t.i(271).unwrap_or(4).clamp(0, 8) as u8,
zero_suppression: t.i(78).unwrap_or(0) as u8,
post: t.s(3).unwrap_or_default(),
..def
};
match d.dim_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case(&name)) {
Some(x) => *x = st,
None => d.dim_styles.push(st),
}
}
"BLOCK_RECORD" => {
if let (Some(h), Some(n)) = (t.s(5), t.s(2)) {
block_records.insert(h.to_ascii_uppercase(), n);
}
}
_ => {}
}
}
}
/// Read a DXF file into a drawing.
pub fn read(bytes: &[u8]) -> Result<Drawing> {
let tags = cadcraft_dxf::parse(bytes).map_err(|e| IoError::Format(e.to_string()))?;
let secs = sections(&tags);
if secs.is_empty() {
return Err(IoError::Format("no sections found".into()));
}
let mut d = Drawing::new_imperial();
d.layouts.clear();
let mut block_records: HashMap<String, String> = HashMap::new();
let mut blocks: Vec<(String, Vec3, Vec<(Option<String>, bool, Entity)>, bool)> = Vec::new();
let mut layout_objs: Vec<(String, u32, String)> = Vec::new();
let mut entities = Vec::new();
for s in &secs {
match s.name.as_str() {
"HEADER" => header(&s.tags, &mut d),
"TABLES" => tables(&s.tags, &mut d, &mut block_records),
"BLOCKS" => {
let recs = records(&s.tags);
let mut i = 0;
while let Some((k, tg)) = recs.get(i) {
if k == "BLOCK" {
let t = T(tg);
let name = t.s(2).unwrap_or_default();
let base = t.p(10);
let xref = t.i(70).unwrap_or(0) & 4 != 0;
let mut j = i + 1;
while recs.get(j).is_some_and(|(k, _)| k != "ENDBLK") {
j += 1;
}
let body = recs.get(i + 1..j).unwrap_or(&[]);
let ents = parse_entities(body, &mut d);
blocks.push((name, base, ents, xref));
i = j + 1;
} else {
i += 1;
}
}
}
"ENTITIES" => entities = parse_entities(&records(&s.tags), &mut d),
"OBJECTS" => {
for (k, tg) in records(&s.tags) {
if k == "LAYOUT" {
// Fields after the AcDbLayout marker (AcDbPlotSettings also has a code 1).
let start = tg.iter().position(|x| x.code == 100 && x.str() == "AcDbLayout").unwrap_or(0);
let tail = tg.get(start..).unwrap_or(&[]);
let t = T(tail);
// LAYOUT has two 330s: owner dict and the block record; take the last.
let br = tg.iter().rfind(|x| x.code == 330).map(Tag::str).unwrap_or_default();
layout_objs.push((t.s(1).unwrap_or_default(), t.i(71).unwrap_or(0) as u32, br.to_ascii_uppercase()));
}
}
}
_ => {}
}
}
// Layouts.
let mut paper_block_for: HashMap<String, String> = HashMap::new();
layout_objs.sort_by_key(|l| l.1);
for (name, order, br) in &layout_objs {
if name.eq_ignore_ascii_case("Model") {
continue;
}
d.layouts.push(Layout::new(name, *order));
if let Some(bname) = block_records.get(br) {
paper_block_for.insert(bname.to_ascii_uppercase(), name.clone());
}
}
if d.layouts.is_empty() {
d.layouts.push(Layout::new("Layout1", 1));
paper_block_for.insert("*PAPER_SPACE".into(), "Layout1".into());
}
let first_layout = d.layouts.first().map(|l| l.name.clone()).unwrap_or_else(|| "Layout1".into());
// Blocks: model/paper space blocks hold entities in newer files.
for (name, base, ents, xref) in blocks {
let up = name.to_ascii_uppercase();
if up == "*MODEL_SPACE" {
for (_, _, e) in ents {
d.ensure_layer(&e.common.layer);
d.model.push(e);
}
continue;
}
if up.starts_with("*PAPER_SPACE") {
let lname = paper_block_for.get(&up).cloned().unwrap_or_else(|| first_layout.clone());
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) {
for (_, _, e) in ents {
l.entities.push(e);
}
}
continue;
}
let mut b = Block::new(&name);
b.base = base;
if xref {
b.xref_path = Some(String::new());
}
for (_, _, e) in ents {
b.entities.push(e);
}
d.blocks.insert(name, std::sync::Arc::new(b));
}
// ENTITIES section: model space, or paper space when flagged (67=1).
for (owner, paper, e) in entities {
d.ensure_layer(&e.common.layer);
let owner_name = owner.and_then(|o| block_records.get(&o.to_ascii_uppercase()).cloned()).map(|n| n.to_ascii_uppercase());
let to_paper = paper || owner_name.as_deref().is_some_and(|n| n.starts_with("*PAPER_SPACE"));
if to_paper {
let lname = owner_name.and_then(|n| paper_block_for.get(&n).cloned()).unwrap_or_else(|| first_layout.clone());
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) {
l.entities.push(e);
}
} else {
d.model.push(e);
}
}
// Keep handles unique against the header's seed.
let seed = d.header.str("HANDSEED", "");
if let Some(h) = Handle::parse_hex(&seed) {
d.bump_handseed(Handle(h.0.saturating_sub(1)));
}
if d.layer("0").is_none() {
d.layers.insert(0, Layer::default());
}
Ok(d)
}
+982
View File
@@ -0,0 +1,982 @@
//! Drawing → DXF (AC1015 / R2000 structure, readable by every DXF consumer since 2000).
use cadcraft_color::Color;
use cadcraft_doc::*;
use cadcraft_dxf::Tag;
use cadcraft_geom::{Vec2, Vec3};
struct W {
t: Vec<Tag>,
next: u64,
}
impl W {
fn s(&mut self, c: i32, v: impl Into<String>) {
self.t.push(Tag::s(c, v));
}
fn f(&mut self, c: i32, v: f64) {
self.t.push(Tag::f(c, v));
}
fn i(&mut self, c: i32, v: i64) {
self.t.push(Tag::i(c, v));
}
fn p(&mut self, c: i32, p: Vec3) {
self.f(c, p.x);
self.f(c + 10, p.y);
self.f(c + 20, p.z);
}
fn p2(&mut self, c: i32, p: Vec2) {
self.f(c, p.x);
self.f(c + 10, p.y);
}
fn h(&mut self) -> String {
let h = format!("{:X}", self.next);
self.next += 1;
h
}
}
/// Header variables we write, with their group codes (DXF Reference, HEADER section).
/// `P2`/`P3` = 2D/3D point.
const HEADER_VARS: &[(&str, i32)] = &[
("INSBASE", -3),
("LIMMIN", -2),
("LIMMAX", -2),
("ORTHOMODE", 70),
("FILLMODE", 70),
("MIRRTEXT", 70),
("LTSCALE", 40),
("ATTMODE", 70),
("TEXTSIZE", 40),
("TRACEWID", 40),
("TEXTSTYLE", 7),
("CLAYER", 8),
("CELTYPE", 6),
("CECOLOR", 62),
("CELTSCALE", 40),
("DIMSCALE", 40),
("DIMSTYLE", 2),
("LUNITS", 70),
("LUPREC", 70),
("AUNITS", 70),
("AUPREC", 70),
("ELEVATION", 40),
("THICKNESS", 40),
("FILLETRAD", 40),
("CHAMFERA", 40),
("CHAMFERB", 40),
("ANGBASE", 50),
("ANGDIR", 70),
("PDMODE", 70),
("PDSIZE", 40),
("PLINEWID", 40),
("CELWEIGHT", 370),
("LWDISPLAY", 290),
("INSUNITS", 70),
("MEASUREMENT", 70),
("PSLTSCALE", 70),
];
fn header_vars(w: &mut W, d: &Drawing) {
for (name, code) in HEADER_VARS {
let Some(v) = d.header.get(name) else { continue };
match (*code, v) {
(-2 | -3, HVal::Point(p)) => {
w.s(9, format!("${name}"));
w.f(10, p.x);
w.f(20, p.y);
if *code == -3 {
w.f(30, p.z);
}
}
(-2 | -3, _) => {}
(c @ (40 | 50), v) => {
if let Some(f) = v.as_f64() {
w.s(9, format!("${name}"));
w.f(c, f);
}
}
(c @ (62 | 70 | 290 | 370), v) => {
if let Some(i) = v.as_i64() {
w.s(9, format!("${name}"));
w.i(c, i);
}
}
(c, v) => {
if let Some(t) = v.as_str() {
w.s(9, format!("${name}"));
w.s(c, t);
}
}
}
}
}
fn common(w: &mut W, e: &Entity, owner: &str, paper: bool, subclass: &str) {
w.s(5, e.handle.hex());
w.s(330, owner);
w.s(100, "AcDbEntity");
if paper {
w.i(67, 1);
}
w.s(8, &e.common.layer);
if !e.common.linetype.eq_ignore_ascii_case("bylayer") {
w.s(6, &e.common.linetype);
}
match e.common.color {
Color::ByLayer => {}
Color::True(rgb) => {
w.i(62, i64::from(cadcraft_color::nearest_aci(rgb)));
w.i(420, i64::from(rgb.to_u32()));
}
c => w.i(62, i64::from(c.to_aci())),
}
if e.common.lineweight != Lineweight::ByLayer {
w.i(370, i64::from(e.common.lineweight.to_dxf()));
}
if (e.common.ltscale - 1.0).abs() > 1e-12 {
w.f(48, e.common.ltscale);
}
if !e.common.visible {
w.i(60, 1);
}
if !subclass.is_empty() {
w.s(100, subclass);
}
}
fn text_tags(w: &mut W, t: &Text, attrib_tag: Option<(&str, bool)>, attdef: bool) {
w.p(10, t.insert);
w.f(40, t.height);
w.s(1, &t.value);
if t.rotation != 0.0 {
w.f(50, t.rotation.to_degrees());
}
if (t.width_factor - 1.0).abs() > 1e-12 {
w.f(41, t.width_factor);
}
if t.oblique != 0.0 {
w.f(51, t.oblique.to_degrees());
}
w.s(7, &t.style);
let h = match t.halign {
HAlign::Left => 0,
HAlign::Center => 1,
HAlign::Right => 2,
HAlign::Aligned => 3,
HAlign::Middle => 4,
HAlign::Fit => 5,
};
let v = match t.valign {
VAlign::Baseline => 0,
VAlign::Bottom => 1,
VAlign::Middle => 2,
VAlign::Top => 3,
};
if h != 0 {
w.i(72, h);
}
if let Some(a) = t.align_pt {
w.p(11, a);
}
match attrib_tag {
Some((tag, invisible)) => {
w.s(100, if attdef { "AcDbAttributeDefinition" } else { "AcDbAttribute" });
if attdef {
w.s(3, "");
}
w.s(2, tag);
w.i(70, i64::from(invisible));
if v != 0 {
w.i(74, v);
}
}
None => {
w.s(100, "AcDbText");
if v != 0 {
w.i(73, v);
}
}
}
}
fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, dim_blocks: &std::collections::HashMap<Handle, String>) {
match &e.kind {
EntityKind::Line(l) => {
w.s(0, "LINE");
common(w, e, owner, paper, "AcDbLine");
w.p(10, l.a);
w.p(11, l.b);
}
EntityKind::Point(p) => {
w.s(0, "POINT");
common(w, e, owner, paper, "AcDbPoint");
w.p(10, p.p);
}
EntityKind::Circle(c) => {
w.s(0, "CIRCLE");
common(w, e, owner, paper, "AcDbCircle");
w.p(10, c.center);
w.f(40, c.radius);
}
EntityKind::Arc(a) => {
w.s(0, "ARC");
common(w, e, owner, paper, "AcDbCircle");
w.p(10, a.center);
w.f(40, a.radius);
w.s(100, "AcDbArc");
w.f(50, a.start.to_degrees());
w.f(51, a.end.to_degrees());
}
EntityKind::Ellipse(el) => {
w.s(0, "ELLIPSE");
common(w, e, owner, paper, "AcDbEllipse");
w.p(10, el.center);
w.p(11, el.major);
w.f(40, el.ratio);
w.f(41, el.start);
w.f(42, el.end);
}
EntityKind::LwPolyline(p) => {
w.s(0, "LWPOLYLINE");
common(w, e, owner, paper, "AcDbPolyline");
w.i(90, p.vertices.len() as i64);
w.i(70, i64::from(p.closed) | if p.plinegen { 128 } else { 0 });
if p.const_width > 0.0 {
w.f(43, p.const_width);
}
for v in &p.vertices {
w.p2(10, v.p);
if v.start_width != 0.0 || v.end_width != 0.0 {
w.f(40, v.start_width);
w.f(41, v.end_width);
}
if v.bulge != 0.0 {
w.f(42, v.bulge);
}
}
}
EntityKind::Polyline3d(p) => {
w.s(0, "POLYLINE");
common(w, e, owner, paper, "AcDb3dPolyline");
w.i(66, 1);
w.p(10, Vec3::ZERO);
w.i(70, 8 | i64::from(p.closed));
for q in &p.points {
let vh = w.h();
w.s(0, "VERTEX");
w.s(5, vh);
w.s(330, e.handle.hex());
w.s(100, "AcDbEntity");
w.s(8, &e.common.layer);
w.s(100, "AcDbVertex");
w.s(100, "AcDb3dPolylineVertex");
w.p(10, *q);
w.i(70, 32);
}
let sh = w.h();
w.s(0, "SEQEND");
w.s(5, sh);
w.s(330, e.handle.hex());
w.s(100, "AcDbEntity");
w.s(8, &e.common.layer);
}
EntityKind::Spline(s) => {
w.s(0, "SPLINE");
common(w, e, owner, paper, "AcDbSpline");
let flags = 8 | i64::from(s.closed) | if s.weights.is_empty() { 0 } else { 4 };
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);
for k in &s.knots {
w.f(40, *k);
}
for (i, c) in s.control.iter().enumerate() {
w.p(10, c.to3(0.0));
if let Some(wt) = s.weights.get(i) {
w.f(41, *wt);
}
}
for f in &s.fit {
w.p(11, f.to3(0.0));
}
}
EntityKind::Ray(r) | EntityKind::XLine(r) => {
let ray = matches!(e.kind, EntityKind::Ray(_));
w.s(0, if ray { "RAY" } else { "XLINE" });
common(w, e, owner, paper, if ray { "AcDbRay" } else { "AcDbXline" });
w.p(10, r.base);
w.p(11, r.dir);
}
EntityKind::Text(t) => {
w.s(0, "TEXT");
common(w, e, owner, paper, "AcDbText");
text_tags(w, t, None, false);
}
EntityKind::AttDef(a) => {
w.s(0, "ATTDEF");
common(w, e, owner, paper, "AcDbText");
text_tags(w, &a.text, Some((&a.tag, a.invisible)), true);
}
EntityKind::MText(t) => {
w.s(0, "MTEXT");
common(w, e, owner, paper, "AcDbMText");
w.p(10, t.insert);
w.f(40, t.height);
w.f(41, t.width);
w.i(71, i64::from(t.attach));
w.i(72, 1);
// Long contents go in 250-char 3-chunks, the remainder in 1.
let chars: Vec<char> = t.contents.chars().collect();
let chunks: Vec<String> = chars.chunks(250).map(|c| c.iter().collect()).collect();
let n = chunks.len();
for (i, c) in chunks.iter().enumerate() {
w.s(if i + 1 == n { 1 } else { 3 }, c.clone());
}
if n == 0 {
w.s(1, "");
}
w.s(7, &t.style);
if t.rotation != 0.0 {
w.f(50, t.rotation.to_degrees());
}
w.f(44, t.line_spacing);
}
EntityKind::Insert(i) => {
w.s(0, "INSERT");
common(w, e, owner, paper, "AcDbBlockReference");
if !i.attribs.is_empty() {
w.i(66, 1);
}
w.s(2, &i.block);
w.p(10, i.insert);
w.f(41, i.scale.x);
w.f(42, i.scale.y);
w.f(43, i.scale.z);
w.f(50, i.rotation.to_degrees());
if i.cols > 1 || i.rows > 1 {
w.i(70, i64::from(i.cols));
w.i(71, i64::from(i.rows));
w.f(44, i.col_spacing);
w.f(45, i.row_spacing);
}
if !i.attribs.is_empty() {
for a in &i.attribs {
let ah = w.h();
w.s(0, "ATTRIB");
w.s(5, ah);
w.s(330, e.handle.hex());
w.s(100, "AcDbEntity");
w.s(8, &e.common.layer);
w.s(100, "AcDbText");
text_tags(w, &a.text, Some((&a.tag, a.invisible)), false);
}
let sh = w.h();
w.s(0, "SEQEND");
w.s(5, sh);
w.s(330, e.handle.hex());
w.s(100, "AcDbEntity");
w.s(8, &e.common.layer);
}
}
EntityKind::Dimension(dm) => {
w.s(0, "DIMENSION");
common(w, e, owner, paper, "AcDbDimension");
let bname = dim_blocks.get(&e.handle).cloned().or_else(|| dm.block.clone()).unwrap_or_default();
w.s(2, bname);
w.p(10, dm.defpt);
let style = d.dim_style(&dm.style).cloned().unwrap_or_default();
let g = cadcraft_render::dimension_geometry(dm, &style, d.header.f64("DIMSCALE", 1.0));
w.p(11, if dm.user_text_pos { dm.text_mid } else { g.text_pos.to3(0.0) });
let ty: i64 = match dm.kind {
DimKind::Linear { .. } => 0,
DimKind::Aligned => 1,
DimKind::Angular => 2,
DimKind::Diameter => 3,
DimKind::Radius => 4,
DimKind::Angular3P => 5,
DimKind::Ordinate { x_type } => 6 | if x_type { 64 } else { 0 },
DimKind::ArcLength => 1,
};
w.i(70, ty | 32 | if dm.user_text_pos { 128 } else { 0 });
if !dm.text.is_empty() {
w.s(1, &dm.text);
}
w.s(3, &dm.style);
match dm.kind {
DimKind::Linear { rotation } => {
w.s(100, "AcDbAlignedDimension");
w.p(13, dm.p13);
w.p(14, dm.p14);
w.f(50, rotation.to_degrees());
w.s(100, "AcDbRotatedDimension");
}
DimKind::Aligned | DimKind::ArcLength => {
w.s(100, "AcDbAlignedDimension");
w.p(13, dm.p13);
w.p(14, dm.p14);
}
DimKind::Radius => {
w.s(100, "AcDbRadialDimension");
w.p(15, dm.p15);
w.f(40, 0.0);
}
DimKind::Diameter => {
w.s(100, "AcDbDiametricDimension");
w.p(15, dm.p15);
w.f(40, 0.0);
}
DimKind::Angular => {
w.s(100, "AcDb2LineAngularDimension");
w.p(13, dm.p13);
w.p(14, dm.p14);
w.p(15, dm.p15);
w.p(16, dm.p16);
}
DimKind::Angular3P => {
w.s(100, "AcDb3PointAngularDimension");
w.p(13, dm.p13);
w.p(14, dm.p14);
w.p(15, dm.p15);
}
DimKind::Ordinate { .. } => {
w.s(100, "AcDbOrdinateDimension");
w.p(13, dm.p13);
w.p(14, dm.p14);
}
}
}
EntityKind::Leader(l) => {
w.s(0, "LEADER");
common(w, e, owner, paper, "AcDbLeader");
w.s(3, &l.style);
w.i(71, i64::from(l.arrow));
w.i(72, i64::from(l.spline));
w.i(76, l.vertices.len() as i64);
for v in &l.vertices {
w.p(10, *v);
}
}
EntityKind::Solid(s) | EntityKind::Trace(s) => {
let solid = matches!(e.kind, EntityKind::Solid(_));
w.s(0, if solid { "SOLID" } else { "TRACE" });
common(w, e, owner, paper, "AcDbTrace");
w.p(10, s.corners[0]);
w.p(11, s.corners[1]);
w.p(12, s.corners[2]);
w.p(13, s.corners[3]);
}
EntityKind::Face3d(f) => {
w.s(0, "3DFACE");
common(w, e, owner, paper, "AcDbFace");
w.p(10, f.corners[0]);
w.p(11, f.corners[1]);
w.p(12, f.corners[2]);
w.p(13, f.corners[3]);
w.i(70, i64::from(f.hidden_edges));
}
EntityKind::Hatch(h) => {
w.s(0, "HATCH");
common(w, e, owner, paper, "AcDbHatch");
w.p(10, Vec3::new(0.0, 0.0, h.elevation));
w.p(210, Vec3::Z);
w.s(2, &h.pattern);
w.i(70, i64::from(h.solid));
w.i(71, i64::from(h.associative));
w.i(91, h.loops.len() as i64);
for l in &h.loops {
w.i(92, 2 | if l.outer { 1 } else { 0 });
let has_bulge = l.vertices.iter().any(|v| v.bulge != 0.0);
w.i(72, i64::from(has_bulge));
w.i(73, 1);
w.i(93, l.vertices.len() as i64);
for v in &l.vertices {
w.p2(10, v.p);
if has_bulge {
w.f(42, v.bulge);
}
}
w.i(97, 0);
}
w.i(75, i64::from(h.style));
w.i(76, 1);
if !h.solid {
w.f(52, h.angle.to_degrees());
w.f(41, h.scale);
w.i(77, 0);
let pat = cadcraft_doc::library::pattern(&h.pattern);
let lines = pat.map(|p| p.lines).unwrap_or_default();
w.i(78, lines.len() as i64);
for pl in lines {
let ang = pl.angle.to_radians() + h.angle;
w.f(53, ang.to_degrees());
let o = Vec2::new(pl.origin.0, pl.origin.1).rotate(h.angle) * h.scale;
w.f(43, o.x);
w.f(44, o.y);
let dl = Vec2::new(pl.delta.0, pl.delta.1).rotate(ang) * h.scale;
w.f(45, dl.x);
w.f(46, dl.y);
w.i(79, pl.dashes.len() as i64);
for dsh in pl.dashes {
w.f(49, dsh * h.scale);
}
}
}
w.i(98, 0);
}
EntityKind::Viewport(v) => {
w.s(0, "VIEWPORT");
common(w, e, owner, paper, "AcDbViewport");
w.p(10, v.center);
w.f(40, v.width);
w.f(41, v.height);
w.i(69, i64::from(v.id));
w.p2(12, v.view_center);
w.f(45, v.view_height);
}
// Not yet written: images, wipeouts, tables, multileaders, unknown objects.
_ => {}
}
}
/// Anonymous dimension blocks (`*D1`…) with the rendered geometry, as consumers expect.
fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Vec<Entity> {
let style = d.dim_style(&dm.style).cloned().unwrap_or_default();
let g = cadcraft_render::dimension_geometry(dm, &style, d.header.f64("DIMSCALE", 1.0));
let mut out = Vec::new();
let c = Common { layer: layer.into(), color: Color::ByBlock, ..Common::default() };
for l in &g.lines {
for seg in l.windows(2) {
if let [a, b] = seg {
out.push(Entity { handle: Handle(0), common: c.clone(), kind: EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) }) });
}
}
}
for t in &g.fills {
if let [a, b, cc] = t.as_slice() {
out.push(Entity {
handle: Handle(0),
common: c.clone(),
kind: EntityKind::Solid(Solid { corners: [a.to3(0.0), b.to3(0.0), cc.to3(0.0), cc.to3(0.0)] }),
});
}
}
if !g.value.is_empty() {
out.push(Entity {
handle: Handle(0),
common: c,
kind: EntityKind::MText(MText {
insert: g.text_pos.to3(0.0),
height: style.text_height * style.scale.max(1e-9),
width: 0.0,
attach: 5,
rotation: 0.0,
style: style.text_style.clone(),
contents: g.value.clone(),
line_spacing: 1.0,
}),
});
}
out
}
fn table_head(w: &mut W, name: &str, count: usize) -> String {
let h = w.h();
w.s(0, "TABLE");
w.s(2, name);
w.s(5, h.clone());
w.s(330, "0");
w.s(100, "AcDbSymbolTable");
w.i(70, count as i64);
h
}
fn record_head(w: &mut W, kind: &str, owner: &str, subclass: &str) -> String {
let h = w.h();
w.s(0, kind);
w.s(if kind == "DIMSTYLE" { 105 } else { 5 }, h.clone());
w.s(330, owner);
w.s(100, "AcDbSymbolTableRecord");
w.s(100, subclass);
h
}
/// Write a drawing as ASCII DXF.
pub fn write(d: &Drawing) -> String {
// Structural handles start above every entity handle.
let mut w = W { t: Vec::new(), next: d.handseed.max(0x100) + 0x1000 };
// Pre-allocate handles for block records.
let mut paper_layouts: Vec<&Layout> = d.layouts.iter().collect();
paper_layouts.sort_by_key(|l| l.tab_order);
let ms_br = w.h();
let ps_brs: Vec<(String, String, &Layout)> = paper_layouts
.iter()
.enumerate()
.map(|(i, l)| (if i == 0 { "*Paper_Space".to_string() } else { format!("*Paper_Space{}", i - 1) }, String::new(), *l))
.collect();
let ps_brs: Vec<(String, String, &Layout)> = ps_brs.into_iter().map(|(n, _, l)| (n, w.h(), l)).collect();
let mut user_blocks: Vec<(String, String, &Block)> = d.blocks.values().map(|b| (b.name.clone(), String::new(), b.as_ref())).collect();
user_blocks.iter_mut().for_each(|b| b.1 = format!("{:X}", 0));
let user_blocks: Vec<(String, String, &Block)> = user_blocks.into_iter().map(|(n, _, b)| (n, w.h(), b)).collect();
// Dimension blocks.
let mut dim_blocks: std::collections::HashMap<Handle, String> = std::collections::HashMap::new();
let mut dim_defs: Vec<(String, String, Vec<Entity>)> = Vec::new(); // filled below
let mut n = 1;
let all_spaces: Vec<&EntityStore> = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).collect();
for st in &all_spaces {
for e in st.iter() {
if let EntityKind::Dimension(dm) = &e.kind {
let mut name = format!("*D{n}");
while d.block(&name).is_some() {
n += 1;
name = format!("*D{n}");
}
n += 1;
let ents = dim_block_entities(d, dm, &e.common.layer);
let brh = w.h();
dim_blocks.insert(e.handle, name.clone());
dim_defs.push((name, brh, ents));
}
}
}
let root_dict = w.h();
let group_dict = w.h();
let layout_dict = w.h();
let model_layout = w.h();
let layout_handles: Vec<String> = ps_brs.iter().map(|_| w.h()).collect();
// ---------------- HEADER ----------------
w.s(0, "SECTION");
w.s(2, "HEADER");
w.s(9, "$ACADVER");
w.s(1, "AC1015");
w.s(9, "$DWGCODEPAGE");
w.s(3, "ANSI_1252");
let ext = d.extents(&Space::Model);
if !ext.is_empty() {
w.s(9, "$EXTMIN");
w.p(10, ext.min.to3(0.0));
w.s(9, "$EXTMAX");
w.p(10, ext.max.to3(0.0));
}
header_vars(&mut w, d);
let seed_pos = w.t.len();
w.s(9, "$HANDSEED");
w.s(5, "0");
w.s(0, "ENDSEC");
// ---------------- CLASSES ----------------
w.s(0, "SECTION");
w.s(2, "CLASSES");
w.s(0, "ENDSEC");
// ---------------- TABLES ----------------
w.s(0, "SECTION");
w.s(2, "TABLES");
// VPORT
let th = table_head(&mut w, "VPORT", 1);
record_head(&mut w, "VPORT", &th, "AcDbViewportTableRecord");
w.s(2, "*Active");
w.i(70, 0);
w.p2(10, Vec2::ZERO);
w.p2(11, Vec2::new(1.0, 1.0));
w.p2(12, if ext.is_empty() { Vec2::new(6.0, 4.5) } else { ext.center() });
w.p2(13, Vec2::ZERO);
w.p2(14, Vec2::new(0.5, 0.5));
w.p2(15, Vec2::new(0.5, 0.5));
w.p(16, Vec3::Z);
w.p(17, Vec3::ZERO);
w.f(40, if ext.is_empty() { 9.0 } else { (ext.height() * 1.1).max(1e-6) });
w.f(41, 1.6);
w.f(42, 50.0);
w.s(0, "ENDTAB");
// LTYPE
let th = table_head(&mut w, "LTYPE", d.linetypes.len());
for lt in &d.linetypes {
record_head(&mut w, "LTYPE", &th, "AcDbLinetypeTableRecord");
w.s(2, &lt.name);
w.i(70, 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.f(49, el.length);
w.i(74, 0);
}
}
w.s(0, "ENDTAB");
// LAYER
let th = table_head(&mut w, "LAYER", d.layers.len());
for l in &d.layers {
record_head(&mut w, "LAYER", &th, "AcDbLayerTableRecord");
w.s(2, &l.name);
w.i(70, i64::from(l.frozen) | if l.locked { 4 } else { 0 });
let aci = match l.color {
Color::True(rgb) => i64::from(cadcraft_color::nearest_aci(rgb)),
c => i64::from(c.to_aci()).clamp(1, 255),
};
w.i(62, if l.on { aci } else { -aci });
if let Color::True(rgb) = l.color {
w.i(420, i64::from(rgb.to_u32()));
}
w.s(6, &l.linetype);
if !l.plot {
w.i(290, 0);
}
w.i(370, i64::from(l.lineweight.to_dxf()));
}
w.s(0, "ENDTAB");
// STYLE
let th = table_head(&mut w, "STYLE", d.text_styles.len());
for s in &d.text_styles {
record_head(&mut w, "STYLE", &th, "AcDbTextStyleTableRecord");
w.s(2, &s.name);
w.i(70, 0);
w.f(40, s.height);
w.f(41, s.width_factor);
w.f(50, s.oblique.to_degrees());
w.i(71, 0);
w.f(42, 0.2);
w.s(3, if s.font == cadcraft_fonts_name() { "txt" } else { s.font.as_str() });
w.s(4, &s.big_font);
}
w.s(0, "ENDTAB");
for name in ["VIEW", "UCS"] {
table_head(&mut w, name, 0);
w.s(0, "ENDTAB");
}
let th = table_head(&mut w, "APPID", 1);
record_head(&mut w, "APPID", &th, "AcDbRegAppTableRecord");
w.s(2, "ACAD");
w.i(70, 0);
w.s(0, "ENDTAB");
// DIMSTYLE
let th = {
let h = w.h();
w.s(0, "TABLE");
w.s(2, "DIMSTYLE");
w.s(5, h.clone());
w.s(330, "0");
w.s(100, "AcDbSymbolTable");
w.i(70, d.dim_styles.len() as i64);
w.s(100, "AcDbDimStyleTable");
w.i(71, 0);
h
};
for s in &d.dim_styles {
record_head(&mut w, "DIMSTYLE", &th, "AcDbDimStyleTableRecord");
w.s(2, &s.name);
w.i(70, 0);
if !s.post.is_empty() {
w.s(3, &s.post);
}
w.f(40, s.scale);
w.f(41, s.arrow_size);
w.f(42, s.ext_offset);
w.f(43, s.baseline_spacing);
w.f(44, s.ext_extend);
w.f(140, s.text_height);
w.f(141, s.center_mark);
w.f(142, s.tick_size);
w.f(144, s.linear_factor);
w.f(147, s.text_gap);
w.i(73, i64::from(s.text_inside_horizontal));
w.i(74, i64::from(s.text_outside_horizontal));
w.i(77, i64::from(s.text_above));
w.i(78, i64::from(s.zero_suppression));
w.i(271, i64::from(s.decimals));
}
w.s(0, "ENDTAB");
// BLOCK_RECORD
let th = table_head(&mut w, "BLOCK_RECORD", 1 + ps_brs.len() + user_blocks.len() + dim_defs.len());
let br_rec = |w: &mut W, h: &str, name: &str, layout: Option<&str>| {
w.s(0, "BLOCK_RECORD");
w.s(5, h);
w.s(330, th.clone());
w.s(100, "AcDbSymbolTableRecord");
w.s(100, "AcDbBlockTableRecord");
w.s(2, name);
w.s(340, layout.unwrap_or("0"));
};
br_rec(&mut w, &ms_br, "*Model_Space", Some(&model_layout));
for (i, (n, h, _)) in ps_brs.iter().enumerate() {
br_rec(&mut w, h, n, layout_handles.get(i).map(String::as_str));
}
for (n, h, _) in &user_blocks {
br_rec(&mut w, h, n, None);
}
for (n, h, _) in &dim_defs {
br_rec(&mut w, h, n, None);
}
w.s(0, "ENDTAB");
w.s(0, "ENDSEC");
// ---------------- BLOCKS ----------------
w.s(0, "SECTION");
w.s(2, "BLOCKS");
let block = |w: &mut W, name: &str, brh: &str, base: Vec3, flags: i64, ents: &mut dyn Iterator<Item = &Entity>, paper: bool| {
let bh = w.h();
w.s(0, "BLOCK");
w.s(5, bh);
w.s(330, brh);
w.s(100, "AcDbEntity");
if paper {
w.i(67, 1);
}
w.s(8, "0");
w.s(100, "AcDbBlockBegin");
w.s(2, name);
w.i(70, flags);
w.p(10, base);
w.s(3, name);
w.s(1, "");
for e in ents {
entity(w, d, e, brh, false, &std::collections::HashMap::new());
}
let eh = w.h();
w.s(0, "ENDBLK");
w.s(5, eh);
w.s(330, brh);
w.s(100, "AcDbEntity");
if paper {
w.i(67, 1);
}
w.s(8, "0");
w.s(100, "AcDbBlockEnd");
};
block(&mut w, "*Model_Space", &ms_br, Vec3::ZERO, 0, &mut std::iter::empty(), false);
for (i, (n, h, l)) in ps_brs.iter().enumerate() {
if i == 0 {
block(&mut w, n, h, Vec3::ZERO, 0, &mut std::iter::empty(), true);
} else {
block(&mut w, n, h, Vec3::ZERO, 0, &mut l.entities.iter().map(|e| e.as_ref()), true);
}
}
for (n, h, b) in &user_blocks {
block(&mut w, n, h, b.base, if b.anonymous { 1 } else { 0 }, &mut b.entities.iter().map(|e| e.as_ref()), false);
}
// Dimension geometry entities need handles.
for (_, _, ents) in &mut dim_defs {
for e in ents.iter_mut() {
e.handle = Handle(w.next);
w.next += 1;
}
}
for (n, h, ents) in &dim_defs {
block(&mut w, n, h, Vec3::ZERO, 1, &mut ents.iter(), false);
}
w.s(0, "ENDSEC");
// ---------------- ENTITIES ----------------
w.s(0, "SECTION");
w.s(2, "ENTITIES");
for e in d.model.iter() {
entity(&mut w, d, e, &ms_br, false, &dim_blocks);
}
if let Some((_, h, l)) = ps_brs.first() {
for e in l.entities.iter() {
entity(&mut w, d, e, h, true, &dim_blocks);
}
}
w.s(0, "ENDSEC");
// ---------------- OBJECTS ----------------
w.s(0, "SECTION");
w.s(2, "OBJECTS");
w.s(0, "DICTIONARY");
w.s(5, root_dict.clone());
w.s(330, "0");
w.s(100, "AcDbDictionary");
w.i(281, 1);
w.s(3, "ACAD_GROUP");
w.s(350, group_dict.clone());
w.s(3, "ACAD_LAYOUT");
w.s(350, layout_dict.clone());
w.s(0, "DICTIONARY");
w.s(5, group_dict);
w.s(330, root_dict.clone());
w.s(100, "AcDbDictionary");
w.i(281, 1);
w.s(0, "DICTIONARY");
w.s(5, layout_dict.clone());
w.s(330, root_dict);
w.s(100, "AcDbDictionary");
w.i(281, 1);
w.s(3, "Model");
w.s(350, model_layout.clone());
for (i, (_, _, l)) in ps_brs.iter().enumerate() {
w.s(3, &l.name);
w.s(350, layout_handles.get(i).cloned().unwrap_or_default());
}
let layout_obj = |w: &mut W, h: &str, name: &str, tab: i64, brh: &str, flags: i64, page: &PageSetup| {
w.s(0, "LAYOUT");
w.s(5, h);
w.s(330, layout_dict.clone());
w.s(100, "AcDbPlotSettings");
w.s(1, "");
w.s(2, "none_device");
w.s(4, "");
w.s(6, "");
for (c, v) in [
(40, page.margins_mm[0]),
(41, page.margins_mm[1]),
(42, page.margins_mm[2]),
(43, page.margins_mm[3]),
(44, page.width_mm),
(45, page.height_mm),
(46, 0.0),
(47, 0.0),
(48, 0.0),
(49, 0.0),
(140, 0.0),
(141, 0.0),
(142, 1.0),
(143, 1.0),
] {
w.f(c, v);
}
w.i(70, 688);
w.i(72, 0);
w.i(73, i64::from(page.landscape));
w.i(74, 5);
w.s(7, "");
w.i(75, 16);
w.f(147, 1.0);
w.f(148, 0.0);
w.f(149, 0.0);
w.s(100, "AcDbLayout");
w.s(1, name);
w.i(70, flags);
w.i(71, tab);
w.p2(10, Vec2::ZERO);
w.p2(11, Vec2::new(12.0, 9.0));
w.p(12, Vec3::ZERO);
w.p(14, Vec3::ZERO);
w.p(15, Vec3::ZERO);
w.f(146, 0.0);
w.p(13, Vec3::ZERO);
w.p(16, Vec3::new(1.0, 0.0, 0.0));
w.p(17, Vec3::new(0.0, 1.0, 0.0));
w.i(76, 0);
w.s(330, brh);
};
layout_obj(&mut w, &model_layout, "Model", 0, &ms_br, 1, &PageSetup::default());
for (i, (_, brh, l)) in ps_brs.iter().enumerate() {
let h = layout_handles.get(i).cloned().unwrap_or_default();
layout_obj(&mut w, &h, &l.name, i64::from(l.tab_order.max(1)), brh, 1, &l.page);
}
w.s(0, "ENDSEC");
w.s(0, "EOF");
let seed = format!("{:X}", w.next);
if let Some(t) = w.t.get_mut(seed_pos + 1) {
*t = Tag::s(5, seed);
}
cadcraft_dxf::write_ascii(&w.t)
}
fn cadcraft_fonts_name() -> &'static str {
"CADCraft Stroke"
}
+63
View File
@@ -0,0 +1,63 @@
//! CADCraft file formats: DXF read/write, SVG and PNG export.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod dxf_read;
mod dxf_write;
pub mod svg;
use cadcraft_doc::{Drawing, Space};
#[derive(Debug, thiserror::Error)]
pub enum IoError {
#[error("{0}")]
Format(String),
#[error("unsupported file type `{0}`")]
Unsupported(String),
}
pub type Result<T> = std::result::Result<T, IoError>;
fn ext(name: &str) -> String {
std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default()
}
/// Read a drawing; the format comes from the content (DXF ASCII/binary) or the name.
pub fn read(bytes: &[u8], name: &str) -> Result<Drawing> {
if bytes.starts_with(b"AC10") {
return Err(IoError::Unsupported("DWG (reading .dwg is on the roadmap; save as DXF for now)".into()));
}
match ext(name).as_str() {
"dxf" | "" => dxf_read::read(bytes),
e if bytes.len() > 4 => dxf_read::read(bytes).map_err(|_| IoError::Unsupported(e.to_string())),
e => Err(IoError::Unsupported(e.to_string())),
}
}
/// Write a drawing in the format chosen by the name's extension.
pub fn write(d: &Drawing, name: &str) -> Result<Vec<u8>> {
match ext(name).as_str() {
"dxf" | "dwg" | "" => Ok(dxf_write::write(d).into_bytes()),
"svg" => Ok(svg::export(d, &Space::Model).into_bytes()),
"png" => png(d, &Space::Model, 2400, 1600),
e => Err(IoError::Unsupported(e.to_string())),
}
}
/// Render a space to PNG, fitted to its extents.
pub fn png(d: &Drawing, space: &Space, width: u32, height: u32) -> Result<Vec<u8>> {
let list = cadcraft_render::build(d, space, &cadcraft_render::Options::default());
let view = cadcraft_render::raster::View::fit(&list.bounds, width, height, 0.05);
cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default())
.ok_or_else(|| IoError::Format("render failed".into()))
}
pub fn read_dxf(bytes: &[u8]) -> Result<Drawing> {
dxf_read::read(bytes)
}
pub fn write_dxf(d: &Drawing) -> String {
dxf_write::write(d)
}
#[cfg(test)]
mod tests;
+76
View File
@@ -0,0 +1,76 @@
//! SVG export of a space (vector, for the web and documents).
use std::fmt::Write as _;
use cadcraft_color::{Rgb, display_rgb};
use cadcraft_doc::{Drawing, Space};
use cadcraft_render::Kind;
/// Export with a white background (colour 7 prints black).
pub fn export(d: &Drawing, space: &Space) -> String {
let list = cadcraft_render::build(d, space, &cadcraft_render::Options::default());
let b = list.bounds;
let (w, h) = if b.is_empty() { (1.0, 1.0) } else { (b.width().max(1e-9), b.height().max(1e-9)) };
let m = (w.max(h)) * 0.02;
let (x0, y1) = if b.is_empty() { (0.0, 1.0) } else { (b.min.x - m, b.max.y + m) };
let vw = w + 2.0 * m;
let vh = h + 2.0 * m;
let stroke = vw.max(vh) / 1500.0;
let mut s = String::new();
let _ = write!(
s,
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {vw:.6} {vh:.6}" width="{:.0}" height="{:.0}"><rect width="100%" height="100%" fill="white"/>"#,
1600.0,
1600.0 * vh / vw
);
let white = Rgb(255, 255, 255);
let tx = |x: f64| x - x0;
let ty = |y: f64| y1 - y;
for p in &list.prims {
let c = display_rgb(p.color, white).hex();
let pts = list.points(p);
match p.kind {
Kind::Polyline => {
let _ = write!(
s,
r#"<polyline fill="none" stroke="{c}" stroke-width="{stroke:.6}" stroke-linecap="round" stroke-linejoin="round" points=""#
);
for q in pts {
let _ = write!(s, "{:.6},{:.6} ", tx(q.x), ty(q.y));
}
s.push_str(r#""/>"#);
}
Kind::Tris => {
let _ = write!(s, r#"<path fill="{c}" d=""#);
for t in pts.chunks(3) {
if let [a, b2, cc] = t {
let _ = write!(s, "M{:.6} {:.6}L{:.6} {:.6}L{:.6} {:.6}Z", tx(a.x), ty(a.y), tx(b2.x), ty(b2.y), tx(cc.x), ty(cc.y));
}
}
s.push_str(r#""/>"#);
}
Kind::Point => {
if let Some(q) = pts.first() {
let _ = write!(s, r#"<circle cx="{:.6}" cy="{:.6}" r="{:.6}" fill="{c}"/>"#, tx(q.x), ty(q.y), stroke);
}
}
Kind::Infinite { ray } => {
if let (Some(bp), Some(dir)) = (pts.first(), pts.get(1)) {
let far = (vw + vh) * 2.0;
let a = if ray { *bp } else { *bp - *dir * far };
let e = *bp + *dir * far;
let _ = write!(
s,
r#"<line x1="{:.6}" y1="{:.6}" x2="{:.6}" y2="{:.6}" stroke="{c}" stroke-width="{stroke:.6}"/>"#,
tx(a.x),
ty(a.y),
tx(e.x),
ty(e.y)
);
}
}
}
}
s.push_str("</svg>");
s
}
+221
View File
@@ -0,0 +1,221 @@
use cadcraft_color::Color;
use cadcraft_doc::*;
use cadcraft_geom::{PolyVertex, Vec2, Vec3};
use crate::*;
fn sample() -> Drawing {
let mut d = Drawing::new_imperial();
d.layers.push(Layer { name: "Walls".into(), color: Color::Index(1), ..Layer::default() });
let c = |l: &str| Common { layer: l.into(), ..Common::default() };
d.add(&Space::Model, c("Walls"), EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 5.0, 0.0) })).unwrap();
d.add(&Space::Model, c("0"), EntityKind::Circle(Circle { center: Vec3::new(3.0, 4.0, 0.0), radius: 2.5 })).unwrap();
d.add(&Space::Model, c("0"), EntityKind::Arc(Arc { center: Vec3::ZERO, radius: 1.0, start: 0.5, end: 2.0 })).unwrap();
d.add(
&Space::Model,
c("0"),
EntityKind::LwPolyline(LwPolyline {
vertices: vec![PolyVertex::new(Vec2::ZERO), PolyVertex::with_bulge(Vec2::new(4.0, 0.0), 0.5), PolyVertex::new(Vec2::new(4.0, 3.0))],
closed: true,
const_width: 0.0,
elevation: 0.0,
plinegen: false,
}),
)
.unwrap();
d.add(
&Space::Model,
c("0"),
EntityKind::Text(Text {
insert: Vec3::new(1.0, 1.0, 0.0),
align_pt: None,
height: 0.25,
value: "Hello Café".into(),
rotation: 0.3,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: HAlign::Left,
valign: VAlign::Baseline,
}),
)
.unwrap();
d.add(
&Space::Model,
c("0"),
EntityKind::MText(MText {
insert: Vec3::new(5.0, 5.0, 0.0),
height: 0.2,
width: 3.0,
attach: 1,
rotation: 0.0,
style: "Standard".into(),
contents: "line one\\Pline two".into(),
line_spacing: 1.0,
}),
)
.unwrap();
d.add(
&Space::Model,
c("0"),
EntityKind::Ellipse(Ellipse {
center: Vec3::new(8.0, 8.0, 0.0),
major: Vec3::new(3.0, 0.0, 0.0),
ratio: 0.5,
start: 0.0,
end: std::f64::consts::TAU,
}),
)
.unwrap();
d.add(
&Space::Model,
c("0"),
EntityKind::Spline(cadcraft_geom::Spline::from_fit_points(&[Vec2::ZERO, Vec2::new(1.0, 2.0), Vec2::new(3.0, 1.0), Vec2::new(4.0, 3.0)])),
)
.unwrap();
d.add(
&Space::Model,
c("0"),
EntityKind::Dimension(Dimension {
kind: DimKind::Linear { rotation: 0.0 },
defpt: Vec3::new(0.0, -1.0, 0.0),
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(10.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 10.0,
text_rotation: 0.0,
user_text_pos: false,
block: None,
}),
)
.unwrap();
d.add(
&Space::Model,
c("0"),
EntityKind::Hatch(Hatch {
pattern: "ANSI31".into(),
solid: false,
loops: vec![HatchLoop {
vertices: vec![PolyVertex::new(Vec2::ZERO), PolyVertex::new(Vec2::new(2.0, 0.0)), PolyVertex::new(Vec2::new(2.0, 2.0))],
outer: true,
}],
scale: 1.0,
angle: 0.0,
associative: false,
style: 0,
elevation: 0.0,
gradient: None,
origin: Vec2::ZERO,
background: None,
}),
)
.unwrap();
let mut b = Block::new("Bolt");
b.entities.push(Entity::new(Handle(0x50), EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 0.25 })));
d.blocks.insert("Bolt".into(), std::sync::Arc::new(b));
d.add(
&Space::Model,
c("0"),
EntityKind::Insert(Insert {
block: "Bolt".into(),
insert: Vec3::new(2.0, 2.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: vec![],
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
}),
)
.unwrap();
d.add(&Space::Paper("Layout1".into()), c("0"), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 1.0, 0.0) })).unwrap();
d
}
#[test]
fn dxf_roundtrip_preserves_entities() {
let d = sample();
let text = write_dxf(&d);
let back = read_dxf(text.as_bytes()).unwrap();
let kinds = |d: &Drawing| d.model.iter().map(|e| e.kind.type_name()).collect::<Vec<_>>();
assert_eq!(kinds(&back), kinds(&d));
assert_eq!(back.layer("Walls").unwrap().color, Color::Index(1));
assert!(back.block("Bolt").is_some());
assert_eq!(back.layout("Layout1").unwrap().entities.len(), 1);
// Geometry survives.
for (a, b) in d.model.iter().zip(back.model.iter()) {
match (&a.kind, &b.kind) {
(EntityKind::Line(x), EntityKind::Line(y)) => assert_eq!(x, y),
(EntityKind::Circle(x), EntityKind::Circle(y)) => assert_eq!(x, y),
(EntityKind::LwPolyline(x), EntityKind::LwPolyline(y)) => assert_eq!(x.vertices, y.vertices),
(EntityKind::Text(x), EntityKind::Text(y)) => {
assert_eq!(x.value, y.value);
assert!((x.rotation - y.rotation).abs() < 1e-9);
}
(EntityKind::MText(x), EntityKind::MText(y)) => assert_eq!(x.contents, y.contents),
(EntityKind::Hatch(x), EntityKind::Hatch(y)) => assert_eq!(x.loops, y.loops),
_ => {}
}
assert_eq!(a.handle, b.handle);
assert_eq!(a.common.layer, b.common.layer);
}
// Handles stay unique after reading.
let mut back = back;
let h = back.new_handle();
assert!(back.entity(h).is_none());
}
#[test]
fn second_roundtrip_is_stable() {
let d = sample();
let t1 = write_dxf(&d);
let d2 = read_dxf(t1.as_bytes()).unwrap();
let d3 = read_dxf(write_dxf(&d2).as_bytes()).unwrap();
assert_eq!(d2.model.len(), d3.model.len());
}
#[test]
fn reads_r12_style_polyline_and_paper_flag() {
let text = "0\nSECTION\n2\nENTITIES\n0\nPOLYLINE\n8\n0\n66\n1\n70\n1\n0\nVERTEX\n8\n0\n10\n0\n20\n0\n0\nVERTEX\n8\n0\n10\n5\n20\n0\n42\n1\n0\nVERTEX\n8\n0\n10\n5\n20\n5\n0\nSEQEND\n0\nLINE\n67\n1\n8\n0\n10\n0\n20\n0\n11\n1\n21\n1\n0\nENDSEC\n0\nEOF\n";
let d = read(text.as_bytes(), "a.dxf").unwrap();
assert_eq!(d.model.len(), 1);
match &d.model.iter().next().unwrap().kind {
EntityKind::LwPolyline(p) => {
assert_eq!(p.vertices.len(), 3);
assert!(p.closed);
assert_eq!(p.vertices[1].bulge, 1.0);
}
_ => panic!(),
}
assert_eq!(d.layouts[0].entities.len(), 1);
}
#[test]
fn hostile_dxf_does_not_panic() {
for t in [
"0\nSECTION\n2\nENTITIES\n0\nHATCH\n91\n999999999\n92\n2\n93\n99999\n0\nENDSEC\n0\nEOF\n",
"0\nSECTION\n2\nENTITIES\n0\nSPLINE\n71\n99\n40\n1\n10\n0\n20\n0\n0\nENDSEC\n0\nEOF\n",
"0\nSECTION\n2\nENTITIES\n0\nINSERT\n66\n1\n2\nX\n0\nATTRIB\n0\nENDSEC\n",
"0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\nA\n0\nINSERT\n2\nA\n0\nENDBLK\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nINSERT\n2\nA\n0\nENDSEC\n0\nEOF\n",
"0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n42\n5\n20\n1\n0\nENDSEC\n0\nEOF\n",
] {
if let Ok(d) = read(t.as_bytes(), "x.dxf") {
let _ = cadcraft_render::build(&d, &Space::Model, &cadcraft_render::Options::default());
let _ = d.extents(&Space::Model);
}
}
}
#[test]
fn svg_and_png_export() {
let d = sample();
let svg = String::from_utf8(write(&d, "a.svg").unwrap()).unwrap();
assert!(svg.starts_with("<svg") && svg.contains("polyline"));
let png = write(&d, "a.png").unwrap();
assert_eq!(&png[1..4], b"PNG");
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "cadcraft-mcp"
description = "CADCraft MCP server: JSON-RPC 2.0 over stdio, driving a running app or a headless session"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
cadcraft-engine = { workspace = true }
cadcraft-render = { workspace = true }
cadcraft-io = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
+188
View File
@@ -0,0 +1,188 @@
//! Where MCP tool calls end up: a control-channel method call.
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;
use cadcraft_engine::Session;
use serde_json::{Value, json};
/// Something that answers control-channel methods (`engine.execute`, `cmdline.input`,
/// `drawing.inspect`, `ui.render`…). See `cadcraft_ui_egui::control` for the full list.
pub trait Backend {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String>;
/// True when a real UI is attached (`ui.screenshot` works).
fn has_ui(&self) -> bool;
fn describe(&self) -> String;
}
/// A running CADCraft app reached through its loopback control port.
pub struct Remote {
addr: String,
conn: Option<(BufReader<TcpStream>, TcpStream)>,
next_id: u64,
}
impl Remote {
pub fn connect(addr: &str) -> std::io::Result<Self> {
let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1 };
r.reconnect()?;
Ok(r)
}
fn reconnect(&mut self) -> std::io::Result<()> {
self.conn = None;
let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {}", self.addr));
for sa in self.addr.to_socket_addrs()? {
match TcpStream::connect_timeout(&sa, Duration::from_millis(800)) {
Ok(s) => {
s.set_nodelay(true).ok();
s.set_read_timeout(Some(Duration::from_secs(90))).ok();
let read = s.try_clone()?;
self.conn = Some((BufReader::new(read), s));
return Ok(());
}
Err(e) => last = e,
}
}
Err(last)
}
fn roundtrip(&mut self, line: &str) -> std::io::Result<String> {
if self.conn.is_none() {
self.reconnect()?;
}
let Some((reader, writer)) = self.conn.as_mut() else { return Err(std::io::Error::other("not connected")) };
writer.write_all(line.as_bytes())?;
writer.write_all(b"\n")?;
writer.flush()?;
let mut reply = String::new();
let n = reader.read_line(&mut reply)?;
if n == 0 {
self.conn = None;
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "connection closed"));
}
Ok(reply)
}
}
impl Backend for Remote {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
let id = self.next_id;
self.next_id += 1;
let line = json!({"id": id, "method": method, "params": params}).to_string();
let reply = match self.roundtrip(&line) {
Ok(r) => r,
Err(_) => self.roundtrip(&line).map_err(|e| format!("CADCraft at {}: {e}", self.addr))?,
};
let v: Value = serde_json::from_str(&reply).map_err(|e| format!("bad reply: {e}"))?;
if v.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(v.get("result").cloned().unwrap_or(Value::Null))
} else {
Err(v.get("error").and_then(Value::as_str).unwrap_or("error").to_string())
}
}
fn has_ui(&self) -> bool {
true
}
fn describe(&self) -> String {
format!("connected to CADCraft at {}", self.addr)
}
}
/// An in-process headless session (no window).
pub struct Headless {
pub session: Session,
}
impl Default for Headless {
fn default() -> Self {
Headless { session: Session::new() }
}
}
fn state(s: &Session) -> Value {
let p = s.current_prompt();
json!({
"prompt": s.prompt_text(),
"running": s.running.as_ref().map(|r| r.id.clone()),
"keywords": p.as_ref().map(|p| p.keywords.clone()).unwrap_or_default(),
"history": s.log.iter().rev().take(20).rev().cloned().collect::<Vec<_>>(),
})
}
impl Backend for Headless {
fn call(&mut self, method: &str, p: Value) -> Result<Value, String> {
let s = &mut self.session;
let str_p = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string);
match method {
"engine.execute" | "command" => {
let id = str_p("command").ok_or("missing `command`")?;
let params = p.get("params").cloned().filter(|v| !v.is_null()).unwrap_or(json!({}));
s.execute(&id, &params).map_err(|e| e.to_string())
}
"cmdline.input" => {
let before = s.log.len();
let r = s.cmdline(&str_p("text").unwrap_or_default());
let out: Vec<String> = s.log.iter().skip(before).cloned().collect();
let mut st = state(s);
if let Some(o) = st.as_object_mut() {
o.insert("output".into(), json!(out));
if let Err(e) = r {
o.insert("error".into(), json!(e.to_string()));
}
}
Ok(st)
}
"cmdline.script" => {
let before = s.log.len();
s.script(&str_p("text").unwrap_or_default()).map_err(|e| e.to_string())?;
let out: Vec<String> = s.log.iter().skip(before).cloned().collect();
Ok(json!({"output": out, "state": state(s)}))
}
"cmdline.key" => {
if str_p("key").is_some_and(|k| k.eq_ignore_ascii_case("escape") || k.eq_ignore_ascii_case("esc")) {
s.cancel();
} else {
s.input(cadcraft_engine::Input::Enter).map_err(|e| e.to_string())?;
}
Ok(state(s))
}
"cmdline.state" => Ok(state(s)),
"engine.commands" => {
Ok(Value::Array(cadcraft_engine::command_specs().iter().map(|c| serde_json::to_value(c.info(s)).unwrap_or_default()).collect()))
}
"drawing.inspect" | "document.inspect" => s.execute("drawing.inspect", &p).map_err(|e| e.to_string()),
"ui.render" => {
let w = p.get("width").and_then(Value::as_f64).unwrap_or(1600.0).clamp(16.0, 8192.0) as u32;
let h = p.get("height").and_then(Value::as_f64).unwrap_or(1000.0).clamp(16.0, 8192.0) as u32;
let st = s.state().map_err(|e| e.to_string())?;
let list = cadcraft_render::build(&st.doc, &st.space, &cadcraft_render::Options::default());
let fit = p.get("fit").and_then(Value::as_bool).unwrap_or(true);
let view = if fit {
cadcraft_render::raster::View::fit(&list.bounds, w, h, 0.05)
} else {
let v = st.view();
cadcraft_render::raster::View { center: v.center, scale: f64::from(h) / v.height.max(1e-12), width: w, height: h }
};
let png =
cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default()).ok_or("render failed")?;
if let Some(path) = str_p("path") {
std::fs::write(&path, &png).map_err(|e| format!("{path}: {e}"))?;
}
Ok(json!({"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h}))
}
"app.open" => s.execute("open", &json!({"path": str_p("path")})).map_err(|e| e.to_string()),
"app.save" => {
let id = if p.get("path").is_some() { "saveas" } else { "qsave" };
s.execute(id, &p).map_err(|e| e.to_string())
}
"ui.screenshot" => Err("no UI in headless mode; use render".into()),
other => Err(format!("unknown method `{other}`")),
}
}
fn has_ui(&self) -> bool {
false
}
fn describe(&self) -> String {
"headless CADCraft session".into()
}
}
+19
View File
@@ -0,0 +1,19 @@
//! CADCraft MCP server.
//!
//! JSON-RPC 2.0 over stdio (newline-delimited), implementing the MCP lifecycle, tools and
//! resources. Tools map onto the app's control-channel methods, served either by a headless
//! [`Headless`] session in-process or by a running app through its loopback control port
//! ([`Remote`]). Agents can type at the command line exactly like a user (`command_line`), call
//! any command with JSON (`execute`), inspect the drawing and render it to a PNG.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod backend;
mod server;
mod tools;
pub use backend::{Backend, Headless, Remote};
pub use server::{PROTOCOL_VERSION, Server};
#[cfg(test)]
mod tests;
+133
View File
@@ -0,0 +1,133 @@
//! JSON-RPC 2.0 framing and the MCP lifecycle / tools / resources methods.
use std::io::{BufRead, Write};
use serde_json::{Value, json};
use crate::backend::Backend;
use crate::tools::{call_tool, tool_definitions};
pub const PROTOCOL_VERSION: &str = "2025-06-18";
const SUPPORTED: &[&str] = &[PROTOCOL_VERSION, "2025-03-26", "2024-11-05"];
const PARSE_ERROR: i64 = -32700;
const INVALID_REQUEST: i64 = -32600;
const METHOD_NOT_FOUND: i64 = -32601;
const INVALID_PARAMS: i64 = -32602;
const INSTRUCTIONS: &str = "CADCraft is a 2D/3D CAD drafting app (an AutoCAD clone). Coordinates are drawing units, \
y up. Fastest path: command_line with AutoCAD syntax, e.g. `line 0,0 10,0 10,5 c`, `circle 5,2.5 1`, \
`rectang 0,0 4,3`, `offset 1` then pick, `zoom e`. Or execute with JSON (list_commands shows ids and params). \
Verify with inspect_drawing / query_entities and look with render.";
pub struct Server {
backend: Box<dyn Backend>,
initialized: bool,
}
fn response(id: Value, result: Value) -> Value {
json!({"jsonrpc": "2.0", "id": id, "result": result})
}
fn error(id: Value, code: i64, message: impl Into<String>) -> Value {
json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message.into()}})
}
impl Server {
pub fn new(backend: Box<dyn Backend>) -> Self {
Self { backend, initialized: false }
}
pub fn backend(&mut self) -> &mut dyn Backend {
self.backend.as_mut()
}
pub fn is_initialized(&self) -> bool {
self.initialized
}
/// Serve newline-delimited JSON-RPC until `input` closes (logs to stderr only).
pub fn serve(&mut self, input: impl BufRead, mut output: impl Write) -> std::io::Result<()> {
for line in input.lines() {
let line = line?;
if let Some(reply) = self.handle_line(&line) {
output.write_all(reply.as_bytes())?;
output.write_all(b"\n")?;
output.flush()?;
}
}
Ok(())
}
pub fn handle_line(&mut self, line: &str) -> Option<String> {
let line = line.trim();
if line.is_empty() {
return None;
}
let reply = match serde_json::from_str::<Value>(line) {
Ok(Value::Array(batch)) => {
let replies: Vec<Value> = batch.into_iter().filter_map(|m| self.handle(m)).collect();
(!replies.is_empty()).then_some(Value::Array(replies))
}
Ok(msg) => self.handle(msg),
Err(e) => Some(error(Value::Null, PARSE_ERROR, format!("parse error: {e}"))),
};
reply.map(|r| r.to_string())
}
pub fn handle(&mut self, msg: Value) -> Option<Value> {
let Value::Object(o) = &msg else { return Some(error(Value::Null, INVALID_REQUEST, "message must be an object")) };
let id = o.get("id").cloned();
let Some(method) = o.get("method").and_then(Value::as_str) else {
if o.contains_key("result") || o.contains_key("error") {
return None;
}
return Some(error(id.unwrap_or(Value::Null), INVALID_REQUEST, "missing `method`"));
};
let params = o.get("params").cloned().unwrap_or(Value::Null);
let Some(id) = id else {
if method == "notifications/initialized" {
self.initialized = true;
}
return None;
};
Some(match self.request(method, &params) {
Ok(r) => response(id, r),
Err((code, m)) => error(id, code, m),
})
}
fn request(&mut self, method: &str, params: &Value) -> Result<Value, (i64, String)> {
match method {
"initialize" => {
let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL_VERSION);
let version = if SUPPORTED.contains(&asked) { asked } else { PROTOCOL_VERSION };
Ok(json!({
"protocolVersion": version,
"capabilities": {"tools": {"listChanged": false}, "resources": {"listChanged": false}},
"serverInfo": {"name": "cadcraft", "title": "CADCraft", "version": env!("CARGO_PKG_VERSION")},
"instructions": format!("{INSTRUCTIONS} Backend: {}.", self.backend.describe()),
}))
}
"ping" => Ok(json!({})),
"tools/list" => Ok(tool_definitions(self.backend.has_ui())),
"tools/call" => {
let name = params.get("name").and_then(Value::as_str).ok_or((INVALID_PARAMS, "missing tool `name`".to_string()))?;
let args = params.get("arguments").cloned().unwrap_or(json!({}));
Ok(call_tool(self.backend.as_mut(), name, &args))
}
"resources/list" => Ok(json!({"resources": [
{"uri": "cadcraft://drawing", "name": "Active drawing", "mimeType": "application/json"},
{"uri": "cadcraft://commands", "name": "Command catalog", "mimeType": "application/json"},
]})),
"resources/read" => {
let uri = params.get("uri").and_then(Value::as_str).unwrap_or("");
let v = match uri {
"cadcraft://drawing" => self.backend.call("drawing.inspect", json!({})),
"cadcraft://commands" => self.backend.call("engine.commands", json!({})),
_ => return Err((-32002, format!("unknown resource `{uri}`"))),
}
.map_err(|e| (-32603, e))?;
Ok(json!({"contents": [{"uri": uri, "mimeType": "application/json", "text": v.to_string()}]}))
}
_ => Err((METHOD_NOT_FOUND, format!("method `{method}` not found"))),
}
}
}
+73
View File
@@ -0,0 +1,73 @@
//! An agent completes realistic drafting tasks through MCP only, and verifies through MCP only.
use serde_json::{Value, json};
use crate::{Headless, Server};
fn call(s: &mut Server, id: u64, method: &str, params: Value) -> Value {
let line = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}).to_string();
let r = s.handle_line(&line).expect("reply");
serde_json::from_str(&r).unwrap()
}
fn tool(s: &mut Server, name: &str, args: Value) -> Value {
let r = call(s, 99, "tools/call", json!({"name": name, "arguments": args}));
let c = &r["result"]["content"][0];
assert_ne!(r["result"]["isError"], json!(true), "{name} failed: {c}");
if c["type"] == "text" { serde_json::from_str(c["text"].as_str().unwrap()).unwrap_or(Value::Null) } else { c.clone() }
}
#[test]
fn lifecycle_and_tools() {
let mut s = Server::new(Box::new(Headless::default()));
let init = call(&mut s, 1, "initialize", json!({"protocolVersion": "2025-06-18"}));
assert_eq!(init["result"]["serverInfo"]["name"], "cadcraft");
assert!(s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#).is_none());
assert!(s.is_initialized());
let tools = call(&mut s, 2, "tools/list", json!({}));
assert!(tools["result"]["tools"].as_array().unwrap().iter().any(|t| t["name"] == "command_line"));
let bad = call(&mut s, 3, "nope", json!({}));
assert_eq!(bad["error"]["code"], -32601);
}
#[test]
fn agent_draws_a_plate_with_holes() {
let mut s = Server::new(Box::new(Headless::default()));
// Task 1: an outline via the command line, AutoCAD style.
tool(&mut s, "command_line", json!({"text": "rectang 0,0 100,60"}));
// Task 2: four holes with JSON.
for (x, y) in [(10, 10), (90, 10), (10, 50), (90, 50)] {
tool(&mut s, "execute", json!({"command": "circle", "params": {"center": [x, y], "radius": 4}}));
}
// Task 3: a layer and a centre line on it.
tool(&mut s, "execute", json!({"command": "layer.new", "params": {"name": "Center", "color": "red", "current": true}}));
tool(&mut s, "command_line", json!({"text": "line -5,30 105,30"}));
tool(&mut s, "command_line", json!({"text": ""}));
// Task 4: a script with text.
tool(&mut s, "script", json!({"text": "TEXT 0,-10 5 0 PLATE 100x60\n"}));
// Verify only through MCP.
let d = tool(&mut s, "inspect_drawing", json!({}));
assert_eq!(d["counts"]["Circle"], 4);
assert_eq!(d["counts"]["Polyline"], 1);
assert_eq!(d["counts"]["Line"], 1);
assert_eq!(d["counts"]["Text"], 1);
let lines = tool(&mut s, "query_entities", json!({"type": "Line", "layer": "Center"}));
assert_eq!(lines["count"], 1);
// Task 5: undo the text, check, then render.
tool(&mut s, "execute", json!({"command": "undo"}));
let d = tool(&mut s, "inspect_drawing", json!({"entities": false}));
assert!(d["counts"].get("Text").is_none());
let img = tool(&mut s, "render", json!({"width": 320, "height": 200}));
assert_eq!(img["type"], "image");
assert!(img["data"].as_str().unwrap().len() > 100);
}
#[test]
fn errors_are_tool_errors_not_crashes() {
let mut s = Server::new(Box::new(Headless::default()));
let r = call(&mut s, 1, "tools/call", json!({"name": "execute", "arguments": {"command": "circle", "params": {"center": "x"}}}));
assert_eq!(r["result"]["isError"], true);
let r = call(&mut s, 2, "tools/call", json!({"name": "screenshot", "arguments": {}}));
assert_eq!(r["result"]["isError"], true);
assert!(s.handle_line("{not json").unwrap().contains("-32700"));
}
+87
View File
@@ -0,0 +1,87 @@
//! MCP tool definitions and dispatch.
use serde_json::{Value, json};
use crate::backend::Backend;
pub fn tool_definitions(has_ui: bool) -> Value {
let mut tools = vec![
json!({"name": "command_line", "description": "Type one line at the CADCraft command line, exactly as a user would at an AutoCAD-style prompt. Starts commands by name or alias (LINE, L, CIRCLE, C, PLINE, RECTANG, MOVE, TRIM, OFFSET, ZOOM…) and answers the active prompt: points `x,y`, relative `@dx,dy`, polar `@dist<angle`, distances, keywords (e.g. `c` for Close), empty text = Enter. Spaces act as Enter, so `circle 0,0 5` works in one call. Returns the new prompt and command-line output.",
"inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}}),
json!({"name": "script", "description": "Run a multi-line script (like an AutoCAD .scr file): one or more inputs per line, blank line = Enter.",
"inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}}),
json!({"name": "execute", "description": "Run any command with JSON parameters (no prompts or dialogs). Use list_commands to find ids and parameter docs. Examples: line {points:[[0,0],[10,0]]}, circle {center:[0,0], radius:5}, layer.new {name:\"Walls\", color:\"red\", current:true}, move {handles:[\"10A\"], delta:[5,0]}, zoom {mode:\"extents\"}.",
"inputSchema": {"type": "object", "properties": {"command": {"type": "string"}, "params": {"type": "object"}}, "required": ["command"]}}),
json!({"name": "list_commands", "description": "List commands with ids, labels, menu paths, aliases and parameter docs. Optional substring filter.",
"inputSchema": {"type": "object", "properties": {"filter": {"type": "string"}}}}),
json!({"name": "inspect_drawing", "description": "Summary of the active drawing: entity counts, extents, layers, styles, blocks, layouts, selection, undo history and (optionally) entities with handles and geometry.",
"inputSchema": {"type": "object", "properties": {"entities": {"type": "boolean"}, "limit": {"type": "integer"}}}}),
json!({"name": "query_entities", "description": "Entities filtered by type (Line, Circle, Polyline…), layer and/or a window [[x0,y0],[x1,y1]].",
"inputSchema": {"type": "object", "properties": {"type": {"type": "string"}, "layer": {"type": "string"}, "window": {"type": "array"}, "limit": {"type": "integer"}}}}),
json!({"name": "render", "description": "Render the active drawing to a PNG (fitted to extents by default) and return it as an image.",
"inputSchema": {"type": "object", "properties": {"width": {"type": "integer"}, "height": {"type": "integer"}, "fit": {"type": "boolean"}, "path": {"type": "string"}}}}),
json!({"name": "new_drawing", "description": "Create a new drawing (imperial by default, or metric).",
"inputSchema": {"type": "object", "properties": {"metric": {"type": "boolean"}}}}),
json!({"name": "open", "description": "Open a DXF file.", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}),
json!({"name": "save", "description": "Save the drawing (DXF; .svg/.png export by extension).", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}}),
json!({"name": "cancel", "description": "Press Escape: cancel the running command (or clear the selection).", "inputSchema": {"type": "object", "properties": {}}}),
];
if has_ui {
tools.push(json!({"name": "screenshot", "description": "Screenshot the CADCraft window (PNG).", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}}));
tools.push(json!({"name": "ui_inspect", "description": "UI state: panels, canvas rect, view, cursor and snap, performance.", "inputSchema": {"type": "object", "properties": {}}}));
tools.push(json!({"name": "ui_click", "description": "Click in the drawing area at world coordinates (or screen with space:\"screen\"). Right button = Enter.", "inputSchema": {"type": "object", "properties": {"x": {"type": "number"}, "y": {"type": "number"}, "space": {"type": "string"}, "button": {"type": "string"}}, "required": ["x", "y"]}}));
}
json!({ "tools": tools })
}
fn text(v: &Value) -> Value {
json!({"content": [{"type": "text", "text": serde_json::to_string_pretty(v).unwrap_or_default()}]})
}
fn err_text(e: &str) -> Value {
json!({"content": [{"type": "text", "text": e}], "isError": true})
}
pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> Value {
let a = if args.is_object() { args.clone() } else { json!({}) };
let r = match name {
"command_line" => b.call("cmdline.input", a),
"script" => b.call("cmdline.script", a),
"execute" => b.call(
"engine.execute",
json!({"command": a.get("command").cloned().unwrap_or(Value::Null), "params": a.get("params").cloned().unwrap_or(json!({}))}),
),
"list_commands" => b.call("engine.commands", json!({})).map(|v| {
let f = a.get("filter").and_then(Value::as_str).map(str::to_ascii_lowercase);
match (v, f) {
(Value::Array(items), Some(f)) => {
Value::Array(items.into_iter().filter(|c| c.to_string().to_ascii_lowercase().contains(&f)).collect())
}
(v, _) => v,
}
}),
"inspect_drawing" => b.call("drawing.inspect", a),
"query_entities" => b.call("engine.execute", json!({"command": "entities", "params": a})),
"new_drawing" => b.call("engine.execute", json!({"command": "new", "params": a})),
"open" => b.call("app.open", a),
"save" => b.call("app.save", a),
"cancel" => b.call("cmdline.key", json!({"key": "escape"})),
"screenshot" => b.call("ui.screenshot", a),
"ui_inspect" => b.call("ui.inspect", json!({})),
"ui_click" => b.call("ui.pointer", a),
"render" => {
return match b.call("ui.render", a) {
Ok(v) => match v.get("pngBase64").and_then(Value::as_str) {
Some(data) => json!({"content": [{"type": "image", "data": data, "mimeType": "image/png"}]}),
None => text(&v),
},
Err(e) => err_text(&e),
};
}
other => return err_text(&format!("unknown tool `{other}`")),
};
match r {
Ok(v) => text(&v),
Err(e) => err_text(&e),
}
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "cadcraft-render"
description = "CADCraft rendering: display lists (linetypes, hatches, text, blocks, dimensions) and a CPU rasteriser"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
cadcraft-geom = { workspace = true }
cadcraft-color = { workspace = true }
cadcraft-doc = { workspace = true }
cadcraft-fonts = { workspace = true }
tiny-skia = { workspace = true }
+260
View File
@@ -0,0 +1,260 @@
//! Dimension geometry generation from definition points and a dimension style.
use cadcraft_doc::{DimKind, DimStyle, Dimension};
use cadcraft_geom::{Arc, Vec2, ccw_sweep};
#[derive(Clone, Debug, Default)]
pub struct DimGeometry {
pub lines: Vec<Vec<Vec2>>,
pub fills: Vec<Vec<Vec2>>,
pub text: Vec<Vec<Vec2>>,
pub text_pos: Vec2,
pub value: String,
}
/// A closed filled arrowhead at `tip` pointing along `dir` (unit), as two triangles' worth.
pub fn arrow(tip: Vec2, dir: Vec2, size: f64) -> Vec<Vec2> {
let back = tip - dir * size;
let n = dir.perp() * (size / 6.0);
vec![tip, back + n, back - n]
}
/// Format a linear measurement per the style (decimal units).
pub fn format_linear(v: f64, st: &DimStyle) -> String {
let v = v * st.linear_factor;
let mut s = format!("{:.*}", usize::from(st.decimals.min(8)), v);
// DIMZIN 8 suppresses trailing zeros.
if st.zero_suppression & 8 != 0 && s.contains('.') {
s = s.trim_end_matches('0').trim_end_matches('.').to_string();
}
if st.zero_suppression & 4 != 0 && s.starts_with("0.") {
s.remove(0);
}
s
}
fn apply_text(meas: String, d: &Dimension, st: &DimStyle) -> String {
let base = if st.post.contains("<>") { st.post.replace("<>", &meas) } else { format!("{meas}{}", st.post) };
if d.text.is_empty() {
base
} else if d.text.trim().is_empty() {
String::new()
} else {
d.text.replace("<>", &base)
}
}
fn ext_line(origin: Vec2, foot: Vec2, st: &DimStyle, k: f64) -> Option<Vec<Vec2>> {
let v = foot - origin;
let len = v.len();
if len < 1e-12 {
return None;
}
let u = v / len;
Some(vec![origin + u * (st.ext_offset * k), foot + u * (st.ext_extend * k)])
}
/// Generate the geometry of a dimension.
pub fn dimension_geometry(d: &Dimension, st: &DimStyle, dimscale: f64) -> DimGeometry {
let k = if st.scale > 0.0 { st.scale } else { dimscale.max(1e-9) };
let asz = st.arrow_size * k;
let th = st.text_height * k;
let gap = st.text_gap * k;
let mut g = DimGeometry::default();
let mut text_angle = 0.0;
let mut text_mid = d.text_mid.xy();
match d.kind {
DimKind::Linear { .. } | DimKind::Aligned => {
let p1 = d.p13.xy();
let p2 = d.p14.xy();
let on = d.defpt.xy();
let dir = match d.kind {
DimKind::Linear { rotation } => Vec2::from_angle(rotation),
_ => (p2 - p1).normalized(),
};
let dir = if dir == Vec2::ZERO { Vec2::X } else { dir };
// Feet on the dimension line through `on`.
let foot = |p: Vec2| on + dir * (p - on).dot(dir);
let f1 = foot(p1);
let f2 = foot(p2);
let meas = f1.dist(f2);
g.value = apply_text(format_linear(meas, st), d, st);
g.lines.extend(ext_line(p1, f1, st, k));
g.lines.extend(ext_line(p2, f2, st, k));
let inside = meas > 2.0 * asz + 1e-9;
let u = (f2 - f1).normalized();
let u = if u == Vec2::ZERO { dir } else { u };
if inside {
g.lines.push(vec![f1, f2]);
g.fills.push(arrow(f1, -u, asz));
g.fills.push(arrow(f2, u, asz));
} else {
g.lines.push(vec![f1 - u * (asz * 2.0), f2 + u * (asz * 2.0)]);
g.fills.push(arrow(f1, u, asz));
g.fills.push(arrow(f2, -u, asz));
}
text_angle = u.angle();
if text_angle > std::f64::consts::FRAC_PI_2 + 1e-9 && text_angle <= 3.0 * std::f64::consts::FRAC_PI_2 + 1e-9 {
text_angle -= std::f64::consts::PI;
}
if !d.user_text_pos {
let up = Vec2::from_angle(text_angle).perp();
text_mid = f1.mid(f2) + if st.text_above > 0 { up * (gap + th / 2.0) } else { Vec2::ZERO };
}
}
DimKind::Radius | DimKind::Diameter => {
let a = d.defpt.xy();
let b = d.p15.xy();
let (center, r, prefix) = if matches!(d.kind, DimKind::Radius) { (a, a.dist(b), "R") } else { (a.mid(b), a.dist(b) / 2.0, "⌀") };
let meas = if matches!(d.kind, DimKind::Radius) { r } else { 2.0 * r };
g.value = apply_text(format!("{prefix}{}", format_linear(meas, st)), d, st);
let u = (b - center).normalized();
let u = if u == Vec2::ZERO { Vec2::X } else { u };
let tip = center + u * r;
let tpos = if d.user_text_pos { text_mid } else { tip + u * (asz * 3.0) };
let start = if matches!(d.kind, DimKind::Diameter) { center - u * r } else { tip };
if matches!(d.kind, DimKind::Diameter) {
g.lines.push(vec![start, tip]);
g.fills.push(arrow(start, -u, asz));
}
g.lines.push(vec![tip, tpos]);
g.fills.push(arrow(tip, u, asz));
text_mid = tpos + Vec2::new(cadcraft_fonts::line_width(&g.value, th, 1.0) / 2.0 + gap, 0.0) * if u.x >= 0.0 { 1.0 } else { -1.0 };
if st.center_mark != 0.0 {
let c = st.center_mark.abs() * k;
g.lines.push(vec![center - Vec2::X * c, center + Vec2::X * c]);
g.lines.push(vec![center - Vec2::Y * c, center + Vec2::Y * c]);
}
}
DimKind::Angular | DimKind::Angular3P => {
// Angular3P: p15 vertex, p13/p14 on the legs, defpt on the arc.
// Angular (2 lines): lines p13-p14 and defpt-p15; p16 on the arc.
let (vertex, a1, a2, arc_pt) = if matches!(d.kind, DimKind::Angular3P) {
(d.p15.xy(), d.p13.xy(), d.p14.xy(), d.defpt.xy())
} else {
let v = cadcraft_geom::line_line_infinite(d.p13.xy(), d.p14.xy(), d.defpt.xy(), d.p15.xy()).map(|x| x.0).unwrap_or(d.p14.xy());
(v, d.p14.xy(), d.p15.xy(), d.p16.xy())
};
let r = vertex.dist(arc_pt).max(1e-9);
let s = vertex.angle_to(a1);
let e = vertex.angle_to(a2);
let arc =
if cadcraft_geom::angle_in_sweep(vertex.angle_to(arc_pt), s, e) { Arc::new(vertex, r, s, e) } else { Arc::new(vertex, r, e, s) };
let sweep = ccw_sweep(arc.start, arc.end);
let deg = sweep.to_degrees();
g.value = apply_text(format!("{:.*}°", usize::from(st.angular_decimals.min(8)), deg), d, st);
let mut pts = Vec::new();
arc.tessellate(r * 1e-3, &mut pts);
g.lines.push(pts);
let sp = arc.start_point();
let ep = arc.end_point();
g.lines.extend(ext_line(vertex + (sp - vertex).normalized() * vertex.dist(a1).min(r), sp, st, k));
g.lines.extend(ext_line(vertex + (ep - vertex).normalized() * vertex.dist(a2).min(r), ep, st, k));
g.fills.push(arrow(sp, -(sp - vertex).perp().normalized(), asz));
g.fills.push(arrow(ep, (ep - vertex).perp().normalized(), asz));
if !d.user_text_pos {
let mid = arc.mid_point();
text_mid = mid + (mid - vertex).normalized() * (gap + th / 2.0);
}
}
DimKind::Ordinate { x_type } => {
let feature = d.p13.xy();
let leader_end = d.p14.xy();
let origin = d.defpt.xy();
let meas = if x_type { (feature.x - origin.x).abs() } else { (feature.y - origin.y).abs() };
g.value = apply_text(format_linear(meas, st), d, st);
g.lines.push(vec![feature, leader_end]);
text_mid = leader_end + if x_type { Vec2::Y * (th * 0.7) } else { Vec2::X * (cadcraft_fonts::line_width(&g.value, th, 1.0) / 2.0 + gap) };
if x_type {
text_angle = std::f64::consts::FRAC_PI_2;
}
}
DimKind::ArcLength => {
let c = d.p15.xy();
let r = c.dist(d.p13.xy());
let arc = Arc::new(c, c.dist(d.defpt.xy()).max(1e-9), c.angle_to(d.p13.xy()), c.angle_to(d.p14.xy()));
let meas = r * arc.sweep();
g.value = apply_text(format!("⌒{}", format_linear(meas, st)), d, st);
let mut pts = Vec::new();
arc.tessellate(arc.radius * 1e-3, &mut pts);
g.lines.push(pts);
g.fills.push(arrow(arc.start_point(), -(arc.start_point() - c).perp().normalized(), asz));
g.fills.push(arrow(arc.end_point(), (arc.end_point() - c).perp().normalized(), asz));
if !d.user_text_pos {
let m = arc.mid_point();
text_mid = m + (m - c).normalized() * (gap + th / 2.0);
}
}
}
if !g.value.is_empty() {
let center_pt = text_mid;
let (strokes, _) = cadcraft_fonts::place_text(
&g.value,
center_pt,
Some(center_pt),
th,
if st.text_inside_horizontal && !matches!(d.kind, DimKind::Linear { .. } | DimKind::Aligned) { 0.0 } else { text_angle },
1.0,
0.0,
cadcraft_fonts::Align::Middle,
cadcraft_fonts::VAlign::Middle,
);
g.text = strokes;
}
g.text_pos = text_mid;
g
}
#[cfg(test)]
mod tests {
use super::*;
use cadcraft_geom::Vec3;
fn lin(p1: (f64, f64), p2: (f64, f64), on: (f64, f64), rot: f64) -> Dimension {
Dimension {
kind: DimKind::Linear { rotation: rot },
defpt: Vec3::new(on.0, on.1, 0.0),
text_mid: Vec3::ZERO,
p13: Vec3::new(p1.0, p1.1, 0.0),
p14: Vec3::new(p2.0, p2.1, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: None,
}
}
#[test]
fn horizontal_measures_dx() {
let g = dimension_geometry(&lin((0.0, 0.0), (10.0, 3.0), (0.0, 5.0), 0.0), &DimStyle::default(), 1.0);
assert_eq!(g.value, "10.0000");
assert!(!g.text.is_empty());
assert_eq!(g.fills.len(), 2);
}
#[test]
fn vertical_measures_dy() {
let g = dimension_geometry(&lin((0.0, 0.0), (10.0, 3.0), (15.0, 0.0), std::f64::consts::FRAC_PI_2), &DimStyle::default(), 1.0);
assert_eq!(g.value, "3.0000");
}
#[test]
fn override_text() {
let mut d = lin((0.0, 0.0), (10.0, 0.0), (0.0, 5.0), 0.0);
d.text = "<> TYP".into();
let g = dimension_geometry(&d, &DimStyle::default(), 1.0);
assert_eq!(g.value, "10.0000 TYP");
d.text = " ".into();
assert_eq!(dimension_geometry(&d, &DimStyle::default(), 1.0).value, "");
}
#[test]
fn iso_suppresses_zeros() {
let g = dimension_geometry(&lin((0.0, 0.0), (12.5, 0.0), (0.0, 5.0), 0.0), &DimStyle::iso25(), 1.0);
assert_eq!(g.value, "12.5");
}
}
+123
View File
@@ -0,0 +1,123 @@
//! Polygon filling: even-odd regions to triangles (slab decomposition), wide polylines.
use cadcraft_doc::LwPolyline;
use cadcraft_geom::{Polyline, Vec2};
/// Triangulate an even-odd region bounded by closed loops (holes allowed) by cutting it into
/// horizontal slabs at every vertex y and emitting trapezoids. Robust for any input; output
/// size is O(slabs × crossings), capped for hostile inputs.
pub fn triangulate_evenodd(loops: &[Vec<Vec2>]) -> Vec<Vec2> {
let mut edges: Vec<(Vec2, Vec2)> = Vec::new();
for l in loops {
let n = l.len();
if n < 3 {
continue;
}
for i in 0..n {
let (Some(&a), Some(&b)) = (l.get(i), l.get((i + 1) % n)) else { continue };
if (a.y - b.y).abs() > 1e-15 && a.is_finite() && b.is_finite() {
edges.push(if a.y < b.y { (a, b) } else { (b, a) });
}
}
}
if edges.is_empty() || edges.len() > 200_000 {
return Vec::new();
}
let mut ys: Vec<f64> = edges.iter().flat_map(|(a, b)| [a.y, b.y]).collect();
ys.sort_by(f64::total_cmp);
ys.dedup_by(|a, b| (*a - *b).abs() < 1e-12);
edges.sort_by(|a, b| a.0.y.total_cmp(&b.0.y));
let mut out = Vec::new();
let mut active: Vec<(Vec2, Vec2)> = Vec::new();
let mut next = 0usize;
for w in ys.windows(2) {
let (Some(&y0), Some(&y1)) = (w.first(), w.get(1)) else { continue };
let ym = (y0 + y1) / 2.0;
while let Some(e) = edges.get(next) {
if e.0.y <= ym {
active.push(*e);
next += 1;
} else {
break;
}
}
active.retain(|e| e.1.y > ym);
let xat = |e: &(Vec2, Vec2), y: f64| {
let t = (y - e.0.y) / (e.1.y - e.0.y);
e.0.x + (e.1.x - e.0.x) * t
};
let mut xs: Vec<(f64, f64, f64)> = active.iter().map(|e| (xat(e, ym), xat(e, y0), xat(e, y1))).collect();
xs.sort_by(|a, b| a.0.total_cmp(&b.0));
for pair in xs.chunks(2) {
if let [l, r] = pair {
let (a, b, c, d) = (Vec2::new(l.1, y0), Vec2::new(r.1, y0), Vec2::new(r.2, y1), Vec2::new(l.2, y1));
out.extend_from_slice(&[a, b, c, a, c, d]);
}
}
if out.len() > 6_000_000 {
break;
}
}
out
}
/// Triangles for a polyline with widths (constant or tapered per segment).
pub fn wide_polyline(p: &LwPolyline, tol: f64) -> Vec<Vec2> {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
let mut out = Vec::new();
let n = p.vertices.len();
for (i, seg) in pl.segments().iter().enumerate() {
let v = p.vertices.get(i % n.max(1)).copied().unwrap_or_default();
let (w0, w1) = if p.const_width > 0.0 { (p.const_width, p.const_width) } else { (v.start_width, v.end_width) };
let mut pts = Vec::new();
seg.tessellate(tol, &mut pts);
let m = pts.len();
if m < 2 {
continue;
}
let mut prev: Option<(Vec2, Vec2)> = None;
for (k, q) in pts.iter().enumerate() {
let t = k as f64 / (m - 1) as f64;
let w = (w0 + (w1 - w0) * t) / 2.0;
let dir = if k + 1 < m { pts.get(k + 1).map(|n| *n - *q) } else { pts.get(k.wrapping_sub(1)).map(|pv| *q - *pv) }
.unwrap_or(Vec2::X)
.normalized();
let nrm = dir.perp() * w;
let cur = (*q + nrm, *q - nrm);
if let Some((a, b)) = prev {
out.extend_from_slice(&[a, b, cur.1, a, cur.1, cur.0]);
}
prev = Some(cur);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn area(tris: &[Vec2]) -> f64 {
tris.chunks(3).map(|t| ((t[1] - t[0]).cross(t[2] - t[0]) / 2.0).abs()).sum()
}
#[test]
fn square_with_hole() {
let outer = vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)];
let hole = vec![Vec2::new(4.0, 4.0), Vec2::new(6.0, 4.0), Vec2::new(6.0, 6.0), Vec2::new(4.0, 6.0)];
let t = triangulate_evenodd(&[outer, hole]);
assert!((area(&t) - 96.0).abs() < 1e-9);
}
#[test]
fn triangle_area() {
let t = triangulate_evenodd(&[vec![Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 3.0)]]);
assert!((area(&t) - 6.0).abs() < 1e-9);
}
#[test]
fn degenerate_input() {
assert!(triangulate_evenodd(&[vec![Vec2::ZERO, Vec2::X]]).is_empty());
assert!(triangulate_evenodd(&[vec![Vec2::new(f64::NAN, 0.0), Vec2::X, Vec2::Y]]).is_empty() || true);
}
}
+95
View File
@@ -0,0 +1,95 @@
//! Pattern hatch line generation: each pattern line family is swept across the boundary
//! (even-odd clipped), then dashed.
use cadcraft_doc::Hatch;
use cadcraft_doc::library::{HatchPattern, pattern};
use cadcraft_geom::{Bounds2, Polyline, Vec2};
/// Hatch line runs in world coordinates (single-point runs are dots).
pub fn pattern_lines(h: &Hatch, tol: f64) -> Vec<Vec<Vec2>> {
let pat = pattern(&h.pattern).unwrap_or_else(|| pattern("ANSI31").unwrap_or(HatchPattern { name: "ANSI31", description: "", lines: vec![] }));
let loops: Vec<Vec<Vec2>> = h.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(tol)).collect();
let scale = if h.scale.is_finite() && h.scale > 1e-9 { h.scale } else { 1.0 };
let mut out = Vec::new();
for fam in &pat.lines {
let ang = fam.angle.to_radians() + h.angle;
let origin = h.origin + Vec2::new(fam.origin.0, fam.origin.1).rotate(h.angle) * scale;
let delta = Vec2::new(fam.delta.0, fam.delta.1).rotate(ang) * scale;
let spacing = (Vec2::new(fam.delta.0, fam.delta.1).y * scale).abs();
if spacing < 1e-9 {
continue;
}
let dashes: Vec<f64> = fam.dashes.iter().map(|d| d * scale).collect();
family(&loops, origin, ang, delta, spacing, &dashes, &mut out);
if out.len() > 500_000 {
break;
}
}
out
}
fn family(loops: &[Vec<Vec2>], origin: Vec2, ang: f64, delta: Vec2, spacing: f64, dashes: &[f64], out: &mut Vec<Vec<Vec2>>) {
// Work in a frame where the family's lines are horizontal.
let to_local = |p: Vec2| (p - origin).rotate(-ang);
let to_world = |p: Vec2| origin + p.rotate(ang);
let local: Vec<Vec<Vec2>> = loops.iter().map(|l| l.iter().map(|p| to_local(*p)).collect()).collect();
let bb = Bounds2::from_points(local.iter().flatten().copied());
if bb.is_empty() {
return;
}
let shift_per_line = delta.rotate(-ang).x;
let k0 = (bb.min.y / spacing).floor() as i64;
let k1 = (bb.max.y / spacing).ceil() as i64;
if k1.saturating_sub(k0) > 20_000 {
return;
}
let pat_len: f64 = dashes.iter().map(|d| d.abs()).sum();
for k in k0..=k1 {
let y = k as f64 * spacing;
let mut xs: Vec<f64> = Vec::new();
for l in &local {
let n = l.len();
for i in 0..n {
let (Some(a), Some(b)) = (l.get(i), l.get((i + 1) % n)) else { continue };
if (a.y > y) != (b.y > y) {
xs.push(a.x + (b.x - a.x) * (y - a.y) / (b.y - a.y));
}
}
}
xs.sort_by(f64::total_cmp);
let offset = shift_per_line * k as f64;
for span in xs.chunks(2) {
let [x0, x1] = span else { continue };
if dashes.is_empty() || pat_len < 1e-12 {
out.push(vec![to_world(Vec2::new(*x0, y)), to_world(Vec2::new(*x1, y))]);
continue;
}
// Dash phase anchored at x = offset.
let start_rep = ((x0 - offset) / pat_len).floor();
let mut x = offset + start_rep * pat_len;
let mut guard = 0;
'outer: while x < *x1 {
for d in dashes {
guard += 1;
if guard > 100_000 {
break 'outer;
}
let len = d.abs();
if *d > 0.0 {
let a = x.max(*x0);
let b = (x + len).min(*x1);
if b > a {
out.push(vec![to_world(Vec2::new(a, y)), to_world(Vec2::new(b, y))]);
}
} else if *d == 0.0 && x >= *x0 && x <= *x1 {
out.push(vec![to_world(Vec2::new(x, y))]);
}
x += len;
if x >= *x1 {
break 'outer;
}
}
}
}
}
}
+564
View File
@@ -0,0 +1,564 @@
//! CADCraft rendering.
//!
//! [`build`] turns a drawing space into a [`DisplayList`]: world-space polylines, filled
//! triangles and points, each tagged with its top-level entity handle and resolved colour.
//! Linetypes, hatches, text, block references and dimensions are expanded here. The UI uploads
//! the list to the GPU; [`raster`] draws it on the CPU (PNG export, plot preview, tests).
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod dim;
mod fill;
mod hatch;
mod linetype;
pub mod raster;
use cadcraft_color::{Color, Rgb};
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, Lineweight, Prim, Space};
use cadcraft_geom::{Bounds2, Mat3, Polyline, Vec2};
pub use dim::dimension_geometry;
pub use fill::triangulate_evenodd;
/// What a display-list primitive draws.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Kind {
/// `verts[start..start+len]` as a connected polyline.
Polyline,
/// `tris[start..start+len]`, three vertices per triangle.
Tris,
/// A single point marker at `verts[start]`.
Point,
/// An infinite line or ray: `verts[start]` = base, `verts[start+1]` = unit direction.
Infinite { ray: bool },
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DPrim {
pub handle: Handle,
pub color: Rgb,
/// Lineweight in mm (0 = thinnest).
pub lw: f32,
pub kind: Kind,
pub start: u32,
pub len: u32,
}
#[derive(Clone, Debug, Default)]
pub struct DisplayList {
pub prims: Vec<DPrim>,
pub verts: Vec<Vec2>,
pub tris: Vec<Vec2>,
pub bounds: Bounds2,
}
impl DisplayList {
pub fn segment_count(&self) -> usize {
self.prims.iter().filter(|p| p.kind == Kind::Polyline).map(|p| p.len.saturating_sub(1) as usize).sum()
}
/// The polyline points of a primitive.
pub fn points(&self, p: &DPrim) -> &[Vec2] {
match p.kind {
Kind::Tris => self.tris.get(p.start as usize..(p.start + p.len) as usize).unwrap_or(&[]),
_ => self.verts.get(p.start as usize..(p.start + p.len) as usize).unwrap_or(&[]),
}
}
}
/// Build options.
#[derive(Clone, Debug)]
pub struct Options {
/// Chord tolerance in world units (about half a pixel at the current zoom).
pub tolerance: f64,
/// Dashes shorter than this (world units) are drawn as continuous lines.
pub min_dash: f64,
/// Draw text (off for very coarse previews).
pub text: bool,
/// Highlighted (selected) handles are not special here; the canvas overlays them.
pub fill: bool,
pub lineweights: bool,
}
impl Default for Options {
fn default() -> Self {
Options { tolerance: 0.001, min_dash: 0.0, text: true, fill: true, lineweights: false }
}
}
/// Graphics state inherited through block references.
#[derive(Clone)]
struct Ctx<'a> {
d: &'a Drawing,
xf: Mat3,
block_color: Color,
block_layer: Option<String>,
block_lw: Lineweight,
block_ltype: String,
depth: usize,
top: Handle,
}
struct Builder<'a> {
list: DisplayList,
opts: &'a Options,
}
impl Builder<'_> {
fn polyline(&mut self, ctx: &Ctx, color: Rgb, lw: f32, pts: &[Vec2]) {
if pts.len() < 2 {
return;
}
let start = self.list.verts.len() as u32;
for p in pts {
let q = ctx.xf.apply(*p);
self.list.bounds.add(q);
self.list.verts.push(q);
}
self.list.prims.push(DPrim { handle: ctx.top, color, lw, kind: Kind::Polyline, start, len: pts.len() as u32 });
}
fn tris(&mut self, ctx: &Ctx, color: Rgb, tris: &[Vec2]) {
if tris.len() < 3 {
return;
}
let start = self.list.tris.len() as u32;
for p in tris {
let q = ctx.xf.apply(*p);
self.list.bounds.add(q);
self.list.tris.push(q);
}
self.list.prims.push(DPrim { handle: ctx.top, color, lw: 0.0, kind: Kind::Tris, start, len: tris.len() as u32 });
}
fn point(&mut self, ctx: &Ctx, color: Rgb, p: Vec2) {
let q = ctx.xf.apply(p);
self.list.bounds.add(q);
let start = self.list.verts.len() as u32;
self.list.verts.push(q);
self.list.prims.push(DPrim { handle: ctx.top, color, lw: 0.0, kind: Kind::Point, start, len: 1 });
}
fn infinite(&mut self, ctx: &Ctx, color: Rgb, base: Vec2, dir: Vec2, ray: bool) {
let start = self.list.verts.len() as u32;
self.list.verts.push(ctx.xf.apply(base));
self.list.verts.push(ctx.xf.apply_vec(dir).normalized());
self.list.prims.push(DPrim { handle: ctx.top, color, lw: 0.0, kind: Kind::Infinite { ray }, start, len: 2 });
}
}
/// Build the display list for a space.
pub fn build(d: &Drawing, space: &Space, opts: &Options) -> DisplayList {
let mut b = Builder { list: DisplayList::default(), opts };
if let Some(store) = d.space(space) {
for e in store.iter() {
let ctx = Ctx {
d,
xf: Mat3::IDENTITY,
block_color: Color::Index(7),
block_layer: None,
block_lw: Lineweight::Default,
block_ltype: "Continuous".into(),
depth: 0,
top: e.handle,
};
entity(&mut b, &ctx, e);
}
}
b.list
}
/// Build the display list for a set of loose entities (previews, rubber bands).
pub fn build_entities<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents: I, opts: &Options) -> DisplayList {
let mut b = Builder { list: DisplayList::default(), opts };
for e in ents {
let ctx = Ctx {
d,
xf: Mat3::IDENTITY,
block_color: Color::Index(7),
block_layer: None,
block_lw: Lineweight::Default,
block_ltype: "Continuous".into(),
depth: 0,
top: e.handle,
};
entity(&mut b, &ctx, e);
}
b.list
}
fn resolve(ctx: &Ctx, e: &Entity) -> (Rgb, f32, Option<cadcraft_doc::Linetype>, f64, bool) {
let d = ctx.d;
// Layer "0" inside a block takes the insert's layer.
let layer_name = if e.common.layer == "0" { ctx.block_layer.as_deref().unwrap_or("0") } else { e.common.layer.as_str() };
let layer = d.layer(layer_name);
let visible = e.common.visible && layer.is_none_or(|l| l.visible());
let layer_color = layer.map(|l| l.color).unwrap_or(Color::Index(7));
let rgb = e.common.color.resolve(layer_color, ctx.block_color);
let lw = match e.common.lineweight {
Lineweight::ByLayer => layer.map(|l| l.lineweight).unwrap_or(Lineweight::Default),
Lineweight::ByBlock => ctx.block_lw,
x => x,
};
let lw_mm = match lw {
Lineweight::Mm100(v) => f32::from(v) / 100.0,
_ => 0.25,
};
let lt_name = match e.common.linetype.to_ascii_lowercase().as_str() {
"bylayer" => layer.map(|l| l.linetype.clone()).unwrap_or_else(|| "Continuous".into()),
"byblock" => ctx.block_ltype.clone(),
_ => e.common.linetype.clone(),
};
let lt = d.linetype(&lt_name).filter(|l| !l.pattern.is_empty()).cloned();
let scale = d.header.f64("LTSCALE", 1.0) * e.common.ltscale;
(rgb, lw_mm, lt, scale, visible)
}
fn entity(b: &mut Builder, ctx: &Ctx, e: &Entity) {
let (rgb, lw, lt, ltscale, visible) = resolve(ctx, e);
if !visible {
return;
}
let tol = b.opts.tolerance / ctx.xf.scale_factor().max(1e-12);
let lw = if b.opts.lineweights { lw } else { 0.0 };
// Stroke a polyline with the entity's linetype.
let stroke = |b: &mut Builder, pts: &[Vec2]| match &lt {
Some(lt) => {
let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12);
for dash in linetype::apply(pts, lt, ltscale, min) {
if dash.len() == 1 {
if let Some(p) = dash.first() {
b.point(ctx, rgb, *p);
}
} else {
b.polyline(ctx, rgb, lw, &dash);
}
}
}
None => b.polyline(ctx, rgb, lw, pts),
};
match &e.kind {
EntityKind::Text(t) => {
if !b.opts.text {
return;
}
let (h, v) = align(t.halign, t.valign);
let oblique = t.oblique;
let (strokes, _) =
cadcraft_fonts::place_text(&t.value, t.insert.xy(), t.align_pt.map(|p| p.xy()), t.height, t.rotation, t.width_factor, oblique, h, v);
for s in strokes {
b.polyline(ctx, rgb, lw, &s);
}
}
EntityKind::AttDef(a) => {
let (h, v) = align(a.text.halign, a.text.valign);
let (strokes, _) = cadcraft_fonts::place_text(
&a.tag,
a.text.insert.xy(),
a.text.align_pt.map(|p| p.xy()),
a.text.height,
a.text.rotation,
a.text.width_factor,
a.text.oblique,
h,
v,
);
for s in strokes {
b.polyline(ctx, rgb, lw, &s);
}
}
EntityKind::MText(t) => {
if !b.opts.text {
return;
}
let l = cadcraft_fonts::layout_mtext(&t.contents, t.insert.xy(), t.height, t.width, t.attach, t.rotation, t.line_spacing);
for s in l.strokes {
b.polyline(ctx, rgb, lw, &s);
}
}
EntityKind::Insert(ins) => insert(b, ctx, e, ins, rgb),
EntityKind::Dimension(dm) => {
if let Some(blk) = dm.block.as_ref().and_then(|n| ctx.d.block(n))
&& ctx.depth < cadcraft_doc::MAX_BLOCK_DEPTH
{
let sub = sub_ctx(ctx, e, Mat3::IDENTITY);
for be in blk.entities.iter() {
entity(b, &sub, be);
}
} else {
let style = ctx.d.dim_style(&dm.style).cloned().unwrap_or_default();
let g = dim::dimension_geometry(dm, &style, ctx.d.header.f64("DIMSCALE", 1.0));
for l in &g.lines {
b.polyline(ctx, rgb, lw, l);
}
for t in &g.fills {
b.tris(ctx, rgb, t);
}
if b.opts.text {
for s in &g.text {
b.polyline(ctx, rgb, lw, s);
}
}
}
}
EntityKind::Hatch(h) => {
if h.solid || h.pattern.eq_ignore_ascii_case("SOLID") || h.gradient.is_some() {
if b.opts.fill {
let loops: Vec<Vec<Vec2>> =
h.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(tol)).collect();
let tris = fill::triangulate_evenodd(&loops);
let c = match &h.gradient {
Some(g) => g.color1.resolve(Color::Index(7), ctx.block_color),
None => rgb,
};
b.tris(ctx, c, &tris);
}
} else {
for seg in hatch::pattern_lines(h, tol) {
if seg.len() == 1 {
if let Some(p) = seg.first() {
b.point(ctx, rgb, *p);
}
} else {
b.polyline(ctx, rgb, lw, &seg);
}
}
}
}
EntityKind::LwPolyline(p) if p.const_width > 0.0 || p.vertices.iter().any(|v| v.start_width > 0.0 || v.end_width > 0.0) => {
if b.opts.fill && ctx.d.header.i64("FILLMODE", 1) != 0 {
let tris = fill::wide_polyline(p, tol);
b.tris(ctx, rgb, &tris);
} else {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
stroke(b, &pl.tessellate(tol));
}
}
EntityKind::LwPolyline(p) => {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
if p.plinegen || lt.is_none() {
stroke(b, &pl.tessellate(tol));
} else {
for s in pl.segments() {
let mut pts = Vec::new();
s.tessellate(tol, &mut pts);
stroke(b, &pts);
}
}
}
EntityKind::Solid(s) | EntityKind::Trace(s) => {
let c = &s.corners;
let q = [c[0].xy(), c[1].xy(), c[3].xy(), c[2].xy()];
if b.opts.fill && ctx.d.header.i64("FILLMODE", 1) != 0 {
b.tris(ctx, rgb, &[q[0], q[1], q[2], q[0], q[2], q[3]]);
} else {
b.polyline(ctx, rgb, lw, &[q[0], q[1], q[2], q[3], q[0]]);
}
}
EntityKind::Wipeout(w) => {
let mut pts = w.boundary.clone();
if let Some(f) = pts.first().copied() {
pts.push(f);
}
b.polyline(ctx, rgb, lw, &pts);
}
EntityKind::Image(i) => {
let o = i.insert.xy();
let u = i.u.xy() * i.size.x;
let v = i.v.xy() * i.size.y;
b.polyline(ctx, rgb, lw, &[o, o + u, o + u + v, o + v, o]);
b.polyline(ctx, rgb, lw, &[o, o + u + v]);
b.polyline(ctx, rgb, lw, &[o + u, o + v]);
}
EntityKind::Table(t) => {
let o = t.insert.xy();
let w: f64 = t.col_widths.iter().sum();
let mut y = 0.0;
b.polyline(ctx, rgb, lw, &[o, o + Vec2::new(w, 0.0)]);
for (r, rh) in t.row_heights.iter().enumerate() {
let mut x = 0.0;
for (c, cw) in t.col_widths.iter().enumerate() {
if let Some(cell) = t.cells.get(r).and_then(|row| row.get(c))
&& !cell.text.is_empty()
&& b.opts.text
{
let center = o + Vec2::new(x + cw / 2.0, -(y + rh / 2.0));
let (strokes, _) = cadcraft_fonts::place_text(
&cell.text,
center,
Some(center),
t.text_height,
0.0,
1.0,
0.0,
cadcraft_fonts::Align::Middle,
cadcraft_fonts::VAlign::Middle,
);
for s in strokes {
b.polyline(ctx, rgb, lw, &s);
}
}
x += cw;
}
y += rh;
b.polyline(ctx, rgb, lw, &[o + Vec2::new(0.0, -y), o + Vec2::new(w, -y)]);
}
let mut x = 0.0;
b.polyline(ctx, rgb, lw, &[o, o + Vec2::new(0.0, -y)]);
for cw in &t.col_widths {
x += cw;
b.polyline(ctx, rgb, lw, &[o + Vec2::new(x, 0.0), o + Vec2::new(x, -y)]);
}
}
EntityKind::Leader(l) => {
let pts: Vec<Vec2> = l.vertices.iter().map(|v| v.xy()).collect();
stroke(b, &pts);
if l.arrow
&& let (Some(a), Some(n)) = (pts.first(), pts.get(1))
{
let size = ctx.d.dim_style(&l.style).map(|s| s.arrow_size).unwrap_or(0.18) * ctx.d.header.f64("DIMSCALE", 1.0);
b.tris(ctx, rgb, &dim::arrow(*a, (*a - *n).normalized(), size));
}
}
EntityKind::MLeader(m) => {
for l in &m.leaders {
let pts: Vec<Vec2> = l.iter().map(|v| v.xy()).chain(std::iter::once(m.landing.xy())).collect();
b.polyline(ctx, rgb, lw, &pts);
if let (Some(a), Some(n)) = (pts.first(), pts.get(1)) {
b.tris(ctx, rgb, &dim::arrow(*a, (*a - *n).normalized(), m.arrow_size));
}
}
if let Some(t) = &m.text {
let land = m.landing.xy();
let dir = if t.insert.x >= land.x { 1.0 } else { -1.0 };
b.polyline(ctx, rgb, lw, &[land, land + Vec2::new(m.dogleg * dir, 0.0)]);
let l = cadcraft_fonts::layout_mtext(&t.contents, t.insert.xy(), t.height, t.width, t.attach, t.rotation, t.line_spacing);
for s in l.strokes {
b.polyline(ctx, rgb, lw, &s);
}
}
}
EntityKind::Point(p) => b.point(ctx, rgb, p.p.xy()),
kind => {
for prim in kind.prims() {
match prim {
Prim::Seg(s) => {
let mut pts = Vec::new();
s.tessellate(tol, &mut pts);
stroke(b, &pts);
}
Prim::Circle(c) => {
let mut pts = Vec::new();
c.tessellate(tol, &mut pts);
stroke(b, &pts);
}
Prim::Ellipse(el) => {
let mut pts = Vec::new();
el.tessellate(tol, &mut pts);
stroke(b, &pts);
}
Prim::Spline(s) => stroke(b, &s.tessellate(tol)),
Prim::Point(p) => b.point(ctx, rgb, p),
Prim::Infinite { base, dir, ray } => b.infinite(ctx, rgb, base, dir, ray),
Prim::Fill(pts) => {
let tris = fill::triangulate_evenodd(&[pts]);
b.tris(ctx, rgb, &tris);
}
}
}
}
}
}
fn align(h: cadcraft_doc::HAlign, v: cadcraft_doc::VAlign) -> (cadcraft_fonts::Align, cadcraft_fonts::VAlign) {
use cadcraft_fonts::{Align as A, VAlign as V};
let ha = match h {
cadcraft_doc::HAlign::Left => A::Left,
cadcraft_doc::HAlign::Center => A::Center,
cadcraft_doc::HAlign::Right => A::Right,
cadcraft_doc::HAlign::Aligned => A::Aligned,
cadcraft_doc::HAlign::Middle => A::Middle,
cadcraft_doc::HAlign::Fit => A::Fit,
};
let va = match v {
cadcraft_doc::VAlign::Baseline => V::Baseline,
cadcraft_doc::VAlign::Bottom => V::Bottom,
cadcraft_doc::VAlign::Middle => V::Middle,
cadcraft_doc::VAlign::Top => V::Top,
};
(ha, va)
}
fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> {
let layer = if e.common.layer == "0" { ctx.block_layer.clone() } else { Some(e.common.layer.clone()) };
let color = match e.common.color {
Color::ByBlock => ctx.block_color,
Color::ByLayer => ctx.d.layer(layer.as_deref().unwrap_or("0")).map(|l| l.color).unwrap_or(Color::Index(7)),
c => c,
};
let lw = match e.common.lineweight {
Lineweight::ByBlock => ctx.block_lw,
Lineweight::ByLayer => ctx.d.layer(layer.as_deref().unwrap_or("0")).map(|l| l.lineweight).unwrap_or(Lineweight::Default),
x => x,
};
let lt = match e.common.linetype.to_ascii_lowercase().as_str() {
"byblock" => ctx.block_ltype.clone(),
"bylayer" => ctx.d.layer(layer.as_deref().unwrap_or("0")).map(|l| l.linetype.clone()).unwrap_or_else(|| "Continuous".into()),
_ => e.common.linetype.clone(),
};
Ctx {
d: ctx.d,
xf: ctx.xf.then_before(m),
block_color: color,
block_layer: layer,
block_lw: lw,
block_ltype: lt,
depth: ctx.depth + 1,
top: ctx.top,
}
}
fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert, rgb: Rgb) {
if ctx.depth >= cadcraft_doc::MAX_BLOCK_DEPTH {
return;
}
if let Some(blk) = ctx.d.block(&ins.block) {
let cols = ins.cols.clamp(1, 10_000);
let rows = ins.rows.clamp(1, 10_000);
for r in 0..rows {
for c in 0..cols {
let off = Vec2::new(ins.col_spacing * f64::from(c), ins.row_spacing * f64::from(r)).rotate(ins.rotation);
let m = Mat3::translate(off).then_before(ins.transform(blk.base.xy()));
let sub = sub_ctx(ctx, e, m);
for be in blk.entities.iter() {
// Constant/visible attribute definitions inside blocks are not drawn; attribs are.
if matches!(be.kind, EntityKind::AttDef(_)) {
continue;
}
entity(b, &sub, be);
}
}
}
}
if b.opts.text {
for a in &ins.attribs {
if a.invisible {
continue;
}
let (h, v) = align(a.text.halign, a.text.valign);
let (strokes, _) = cadcraft_fonts::place_text(
&a.text.value,
a.text.insert.xy(),
a.text.align_pt.map(|p| p.xy()),
a.text.height,
a.text.rotation,
a.text.width_factor,
a.text.oblique,
h,
v,
);
for s in strokes {
b.polyline(ctx, rgb, 0.0, &s);
}
}
}
}
#[cfg(test)]
mod tests;
+121
View File
@@ -0,0 +1,121 @@
//! Apply a dash pattern along a polyline.
use cadcraft_doc::Linetype;
use cadcraft_geom::Vec2;
/// Split `pts` into dashes. Dots come back as single-point runs. When the scaled pattern is
/// shorter than `min_pattern` (sub-pixel), the polyline is returned whole.
pub fn apply(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64) -> Vec<Vec<Vec2>> {
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let total = lt.pattern_length() * scale;
if pts.len() < 2 || total <= 1e-12 || total < min_pattern {
return vec![pts.to_vec()];
}
// Guard against huge dash counts (zoomed out a lot): fall back to continuous.
let len: f64 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum();
if len / total > 50_000.0 {
return vec![pts.to_vec()];
}
let pattern: Vec<f64> = lt.pattern.iter().map(|d| d.length * scale).collect();
// AutoCAD centres the pattern so lines start and end with a dash: start at half the first dash.
let mut out: Vec<Vec<Vec2>> = Vec::new();
let mut cur: Vec<Vec2> = Vec::new();
let mut idx = 0usize;
let first = pattern.first().copied().unwrap_or(0.0);
let mut remaining = if first > 0.0 { first } else { first.abs() };
let mut on = first >= 0.0;
if on && first == 0.0 {
if let Some(p) = pts.first() {
out.push(vec![*p]);
}
idx = 1 % pattern.len();
let n = pattern.get(idx).copied().unwrap_or(0.0);
remaining = n.abs();
on = n > 0.0;
}
if on && let Some(p) = pts.first() {
cur.push(*p);
}
let mut guard = 0usize;
for w in pts.windows(2) {
let (Some(&a), Some(&b)) = (w.first(), w.get(1)) else { continue };
let seg = a.dist(b);
if seg <= 1e-15 {
continue;
}
let dir = (b - a) / seg;
let mut pos = 0.0;
while seg - pos > remaining {
guard += 1;
if guard > 2_000_000 {
return vec![pts.to_vec()];
}
pos += remaining;
let p = a + dir * pos;
if on {
cur.push(p);
out.push(std::mem::take(&mut cur));
}
idx = (idx + 1) % pattern.len();
let n = pattern.get(idx).copied().unwrap_or(0.0);
if n == 0.0 {
out.push(vec![p]);
idx = (idx + 1) % pattern.len();
let n2 = pattern.get(idx).copied().unwrap_or(0.0);
remaining = n2.abs();
on = n2 > 0.0;
} else {
remaining = n.abs();
on = n > 0.0;
}
if on {
cur.push(p);
}
}
remaining -= seg - pos;
if on {
cur.push(b);
}
}
if cur.len() >= 2 {
out.push(cur);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dashes_split_line() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(3.0, 0.0)], &lt, 1.0, 0.0);
// 3.0 / 0.75 = 4 patterns → 4 dashes.
assert_eq!(d.len(), 4);
assert!((d[0][1].x - 0.5).abs() < 1e-9);
assert!((d[1][0].x - 0.75).abs() < 1e-9);
}
#[test]
fn dots_are_single_points() {
let lt = Linetype::simple("DOT", "", &[0.0, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(1.0, 0.0)], &lt, 1.0, 0.0);
assert!(d.iter().all(|r| r.len() == 1));
assert!(d.len() >= 4);
}
#[test]
fn tiny_pattern_is_continuous() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(3.0, 0.0)], &lt, 1.0, 10.0);
assert_eq!(d.len(), 1);
}
#[test]
fn dash_continues_across_vertices() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(0.3, 0.0), Vec2::new(0.3, 1.0)], &lt, 1.0, 0.0);
assert_eq!(d[0].len(), 3); // the first dash turns the corner
}
}
+139
View File
@@ -0,0 +1,139 @@
//! CPU rasteriser: draws a display list with tiny-skia (PNG export, plot preview, tests).
use cadcraft_color::{Rgb, display_rgb};
use cadcraft_geom::{Bounds2, Vec2};
use tiny_skia::{FillRule, LineCap, LineJoin, Paint, PathBuilder, Pixmap, Stroke, Transform};
use crate::{DisplayList, Kind};
/// A 2D view: world point at the image centre and pixels per drawing unit.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct View {
pub center: Vec2,
pub scale: f64,
pub width: u32,
pub height: u32,
}
impl View {
pub fn to_screen(&self, p: Vec2) -> (f32, f32) {
let x = (p.x - self.center.x) * self.scale + f64::from(self.width) / 2.0;
let y = f64::from(self.height) / 2.0 - (p.y - self.center.y) * self.scale;
(x as f32, y as f32)
}
/// Fit `b` with a margin fraction.
pub fn fit(b: &Bounds2, width: u32, height: u32, margin: f64) -> View {
if b.is_empty() {
return View { center: Vec2::ZERO, scale: 1.0, width, height };
}
let w = b.width().max(1e-9);
let h = b.height().max(1e-9);
let s = (f64::from(width) / w).min(f64::from(height) / h) * (1.0 - margin);
View { center: b.center(), scale: if s.is_finite() && s > 0.0 { s } else { 1.0 }, width, height }
}
pub fn world_bounds(&self) -> Bounds2 {
let hw = f64::from(self.width) / 2.0 / self.scale;
let hh = f64::from(self.height) / 2.0 / self.scale;
Bounds2::new(self.center - Vec2::new(hw, hh), self.center + Vec2::new(hw, hh))
}
}
#[derive(Clone, Copy, Debug)]
pub struct RasterOptions {
pub background: Rgb,
/// Line width in pixels for zero-lineweight lines.
pub hairline: f32,
/// Pixels per mm for lineweights (0 = ignore lineweights).
pub px_per_mm: f32,
pub antialias: bool,
}
impl Default for RasterOptions {
fn default() -> Self {
RasterOptions { background: Rgb(33, 40, 48), hairline: 1.0, px_per_mm: 0.0, antialias: true }
}
}
/// Render to a pixmap. Returns `None` for zero or absurd sizes.
pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Pixmap> {
if view.width == 0 || view.height == 0 || view.width > 16384 || view.height > 16384 {
return None;
}
let mut pm = Pixmap::new(view.width, view.height)?;
pm.fill(tiny_skia::Color::from_rgba8(o.background.0, o.background.1, o.background.2, 255));
let vis = view.world_bounds();
for p in &list.prims {
let c = display_rgb(p.color, o.background);
let mut paint = Paint::default();
paint.set_color_rgba8(c.0, c.1, c.2, 255);
paint.anti_alias = o.antialias;
let pts = list.points(p);
match p.kind {
Kind::Polyline => {
let bb = Bounds2::from_points(pts.iter().copied());
if !bb.intersects(&vis) {
continue;
}
let mut pb = PathBuilder::new();
for (i, q) in pts.iter().enumerate() {
let (x, y) = view.to_screen(*q);
if i == 0 {
pb.move_to(x, y);
} else {
pb.line_to(x, y);
}
}
if let Some(path) = pb.finish() {
let w = if o.px_per_mm > 0.0 && p.lw > 0.0 { (p.lw * o.px_per_mm).max(o.hairline) } else { o.hairline };
let stroke = Stroke { width: w, line_cap: LineCap::Round, line_join: LineJoin::Round, ..Default::default() };
pm.stroke_path(&path, &paint, &stroke, Transform::identity(), None);
}
}
Kind::Tris => {
let mut pb = PathBuilder::new();
for t in pts.chunks(3) {
if let [a, b, c] = t {
let (ax, ay) = view.to_screen(*a);
let (bx, by) = view.to_screen(*b);
let (cx, cy) = view.to_screen(*c);
pb.move_to(ax, ay);
pb.line_to(bx, by);
pb.line_to(cx, cy);
pb.close();
}
}
if let Some(path) = pb.finish() {
pm.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None);
}
}
Kind::Point => {
if let Some(q) = pts.first() {
let (x, y) = view.to_screen(*q);
if let Some(r) = tiny_skia::Rect::from_xywh(x - 0.5, y - 0.5, 1.5, 1.5) {
pm.fill_rect(r, &paint, Transform::identity(), None);
}
}
}
Kind::Infinite { ray } => {
let (Some(base), Some(dir)) = (pts.first(), pts.get(1)) else { continue };
let far = (vis.width() + vis.height()) * 2.0 + base.dist(vis.center());
let a = if ray { *base } else { *base - *dir * far };
let b = *base + *dir * far;
let mut pb = PathBuilder::new();
let (ax, ay) = view.to_screen(a);
let (bx, by) = view.to_screen(b);
pb.move_to(ax, ay);
pb.line_to(bx, by);
if let Some(path) = pb.finish() {
pm.stroke_path(&path, &paint, &Stroke { width: o.hairline, ..Default::default() }, Transform::identity(), None);
}
}
}
}
Some(pm)
}
/// Render and encode as PNG.
pub fn render_png(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Vec<u8>> {
render(list, view, o)?.encode_png().ok()
}
+117
View File
@@ -0,0 +1,117 @@
use crate::raster::{RasterOptions, View, render};
use crate::*;
use cadcraft_doc::{Common, Drawing, EntityKind, Hatch, HatchLoop, Space};
use cadcraft_geom::{PolyVertex, Vec3};
fn sample() -> Drawing {
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) }))
.unwrap();
d.add(
&Space::Model,
Common { color: Color::Index(1), ..Default::default() },
EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::new(5.0, 5.0, 0.0), radius: 3.0 }),
)
.unwrap();
d
}
#[test]
fn builds_lines_and_circles() {
let d = sample();
let l = build(&d, &Space::Model, &Options { tolerance: 0.01, ..Default::default() });
assert_eq!(l.prims.len(), 2);
assert!(l.prims[1].len > 20);
assert_eq!(l.prims[1].color, Rgb(255, 0, 0));
}
#[test]
fn linetype_dashes_line() {
let mut d = sample();
d.linetypes.extend(cadcraft_doc::library::standard_linetypes());
d.layer_mut("0").unwrap().linetype = "DASHED".into();
let l = build(&d, &Space::Model, &Options::default());
assert!(l.prims.len() > 10);
}
#[test]
fn frozen_layer_hidden() {
let mut d = sample();
d.layer_mut("0").unwrap().frozen = true;
assert!(build(&d, &Space::Model, &Options::default()).prims.is_empty());
}
#[test]
fn text_produces_strokes() {
let mut d = Drawing::new_imperial();
d.add(
&Space::Model,
Common::default(),
EntityKind::Text(cadcraft_doc::Text {
insert: Vec3::ZERO,
align_pt: None,
height: 1.0,
value: "CAD".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
}),
)
.unwrap();
let l = build(&d, &Space::Model, &Options::default());
assert!(l.prims.len() >= 3);
}
#[test]
fn hatch_pattern_and_solid() {
let mut d = Drawing::new_imperial();
let sq = vec![
PolyVertex::new(Vec2::new(0.0, 0.0)),
PolyVertex::new(Vec2::new(4.0, 0.0)),
PolyVertex::new(Vec2::new(4.0, 4.0)),
PolyVertex::new(Vec2::new(0.0, 4.0)),
];
let h = Hatch {
pattern: "ANSI31".into(),
solid: false,
loops: vec![HatchLoop { vertices: sq.clone(), outer: true }],
scale: 1.0,
angle: 0.0,
associative: false,
style: 0,
elevation: 0.0,
gradient: None,
origin: Vec2::ZERO,
background: None,
};
d.add(&Space::Model, Common::default(), EntityKind::Hatch(h.clone())).unwrap();
let l = build(&d, &Space::Model, &Options::default());
// 45° lines at 0.125 spacing across a 4x4 square: about 4*sqrt(2)/0.125 ≈ 45 lines.
assert!(l.prims.len() > 35 && l.prims.len() < 60, "{}", l.prims.len());
let mut d2 = Drawing::new_imperial();
d2.add(&Space::Model, Common::default(), EntityKind::Hatch(Hatch { solid: true, pattern: "SOLID".into(), ..h })).unwrap();
let l2 = build(&d2, &Space::Model, &Options::default());
assert_eq!(l2.prims.len(), 1);
assert_eq!(l2.prims[0].kind, Kind::Tris);
}
#[test]
fn raster_draws_pixels() {
let d = sample();
let l = build(&d, &Space::Model, &Options::default());
let v = View::fit(&l.bounds, 200, 200, 0.1);
let pm = render(&l, &v, &RasterOptions::default()).unwrap();
let bg = pm.pixels().iter().filter(|p| p.red() == 33).count();
assert!(bg < 200 * 200);
// A red pixel exists from the circle.
assert!(pm.pixels().iter().any(|p| p.red() > 200 && p.green() < 60));
}
#[test]
fn raster_rejects_bad_size() {
let l = DisplayList::default();
assert!(render(&l, &View { center: Vec2::ZERO, scale: 1.0, width: 0, height: 10 }, &RasterOptions::default()).is_none());
}
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "cadcraft-ui-egui"
description = "CADCraft user interface (egui): the swappable front end"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
cadcraft-geom = { workspace = true }
cadcraft-color = { workspace = true }
cadcraft-doc = { workspace = true }
cadcraft-render = { workspace = true }
cadcraft-engine = { workspace = true }
egui = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
image = { workspace = true }

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