diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9ed4d52cd..1e6eb5806 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -407,6 +407,10 @@ jobs: # New UI text must reach every complete catalog; report it here, before review (#8542). - name: Translations in the complete catalogs run: cargo xtask i18n --check + - name: Model decisions use exact geometry, not meshes + run: | + cargo xtask mesh-decisions + cargo test -p xtask mesh_decisions --locked - name: Agent router and skills cite real files run: | cargo xtask skills diff --git a/AGENTS.md b/AGENTS.md index af4304973..aacf83c2d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,6 +10,7 @@ Work: ROADMAP.md, "Where help is wanted most" in CONTRIBUTING.md, issues labelle - No GPL/LGPL/AGPL code, not even reading it (OpenCASCADE, FreeCAD, SolveSpace, CadQuery, LibreCAD, QCAD): `cargo xtask licences --check`. - Every asset is original or openly licensed with a row in ATTRIBUTION.md; read `assets/AGENTS.md` before icon work: `cargo xtask assets`, `cargo xtask icons`. - Never crash: no unwrap/expect/panic/unsafe in non-test code (unsafe allowlist in crash-safety), errors are `Result`, input is hostile: clippy `-D warnings`, `hostile_params_never_panic`. +- Model decisions (what an operation does, which bodies it touches, which face or edge a point or name means, depths, nearness) use exact geometry; a mesh is for display, export, previews and mesh bodies (`xtask/mesh-decisions.txt` only shrinks): `cargo xtask mesh-decisions`. - Everything is a command and programmatic calls never open dialogs: `skills/solidcraft-commands/SKILL.md`. - Layering (geom, sketch/kernel/render, doc, io, engine, ui-egui, apps); only `crates/kernel` uses truck: `cargo xtask layers`. - One outer UI container, one camera path (`navigation::handle`), colours from theme tokens: `cargo xtask ui-containers`. diff --git a/Cargo.lock b/Cargo.lock index 444779db5..b4cb3c319 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4061,7 +4061,7 @@ dependencies = [ [[package]] name = "solidcraft" -version = "0.29.0" +version = "0.30.0" dependencies = [ "block2 0.6.2", "eframe", @@ -4098,11 +4098,11 @@ dependencies = [ [[package]] name = "solidcraft-3dx-client" -version = "0.29.0" +version = "0.30.0" [[package]] name = "solidcraft-cli" -version = "0.29.0" +version = "0.30.0" dependencies = [ "image", "log", @@ -4115,7 +4115,7 @@ dependencies = [ [[package]] name = "solidcraft-derive" -version = "0.29.0" +version = "0.30.0" dependencies = [ "proc-macro2", "quote", @@ -4124,7 +4124,7 @@ dependencies = [ [[package]] name = "solidcraft-doc" -version = "0.29.0" +version = "0.30.0" dependencies = [ "log", "serde", @@ -4142,7 +4142,7 @@ dependencies = [ [[package]] name = "solidcraft-engine" -version = "0.29.0" +version = "0.30.0" dependencies = [ "image", "log", @@ -4164,7 +4164,7 @@ dependencies = [ [[package]] name = "solidcraft-geom" -version = "0.29.0" +version = "0.30.0" dependencies = [ "serde", "serde_json", @@ -4173,7 +4173,7 @@ dependencies = [ [[package]] name = "solidcraft-gpu" -version = "0.29.0" +version = "0.30.0" dependencies = [ "image", "log", @@ -4193,7 +4193,7 @@ dependencies = [ [[package]] name = "solidcraft-io" -version = "0.29.0" +version = "0.30.0" dependencies = [ "cadmpeg-core", "cadmpeg-ir", @@ -4219,7 +4219,7 @@ dependencies = [ [[package]] name = "solidcraft-kernel" -version = "0.29.0" +version = "0.30.0" dependencies = [ "log", "proptest", @@ -4237,7 +4237,7 @@ dependencies = [ [[package]] name = "solidcraft-mcp" -version = "0.29.0" +version = "0.30.0" dependencies = [ "image", "serde_json", @@ -4247,7 +4247,7 @@ dependencies = [ [[package]] name = "solidcraft-profile" -version = "0.29.0" +version = "0.30.0" dependencies = [ "serde_json", "web-time", @@ -4255,7 +4255,7 @@ dependencies = [ [[package]] name = "solidcraft-render" -version = "0.29.0" +version = "0.30.0" dependencies = [ "image", "moxcms", @@ -4270,7 +4270,7 @@ dependencies = [ [[package]] name = "solidcraft-sketch" -version = "0.29.0" +version = "0.30.0" dependencies = [ "harfrust", "serde", @@ -4283,7 +4283,7 @@ dependencies = [ [[package]] name = "solidcraft-smlib" -version = "0.29.0" +version = "0.30.0" dependencies = [ "cc", "flate2", @@ -4297,14 +4297,14 @@ dependencies = [ [[package]] name = "solidcraft-space-mouse" -version = "0.29.0" +version = "0.30.0" dependencies = [ "serde", ] [[package]] name = "solidcraft-step" -version = "0.29.0" +version = "0.30.0" dependencies = [ "solidcraft-geom", "solidcraft-profile", @@ -4312,11 +4312,11 @@ dependencies = [ [[package]] name = "solidcraft-testkit" -version = "0.29.0" +version = "0.30.0" [[package]] name = "solidcraft-ui-egui" -version = "0.29.0" +version = "0.30.0" dependencies = [ "arboard", "egui", @@ -4347,7 +4347,7 @@ dependencies = [ [[package]] name = "solidcraft-web" -version = "0.29.0" +version = "0.30.0" dependencies = [ "eframe", "egui", @@ -5754,7 +5754,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.29.0" +version = "0.30.0" dependencies = [ "proc-macro2", "quick-xml", diff --git a/Cargo.toml b/Cargo.toml index b22c3adf8..10651f967 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ members = ["crates/*", "apps/*", "xtask"] exclude = ["vendor"] [workspace.package] -version = "0.29.0" +version = "0.30.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" diff --git a/ROADMAP.md b/ROADMAP.md index f6726e48f..0ee1e258e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -662,7 +662,9 @@ completed drawings publish atomically. The browser still exports synchronously. pieces survive unfold/refold as one logical sheet group, including split flanged sheets. Cut-outs made in the flat pattern cross bends at any angle or curved: their edges fold to helices and curves on the bend, their walls square to the sheet. Free-form bases use bounded - sampling. + sampling. A fold crosses the sheet's own outer edges the same way, slanted or on any curve, + with the outline exact in the flat pattern and its DXF, and flanges and other folds still go + on the panels. Parallel prismatic partial-depth cuts retain pocket side and depth through transfer and unfold/refold, with separate pocket contours in preview and DXF. Planar Intersect preserves exact holes and retained islands, including the union of multiple selected profiles, and diff --git a/SECURITY.md b/SECURITY.md index 00bd15049..23811aaeb 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -3,7 +3,7 @@ ## Supported versions SolidCraft is young and moves quickly, so only the latest release gets security fixes. Please -update to the [latest release](https://github.com/bherbruck/solidcraft/releases/latest) before +update to the [latest release](https://github.com/tangency-labs/solidcraft/releases/latest) before reporting, and check whether the problem is still on `main`. | Version | Supported | @@ -15,18 +15,46 @@ reporting, and check whether the problem is still on `main`. ## Reporting a vulnerability Please **don't open a public issue** for a security problem. Report it privately through GitHub: -open the repository's [Security tab](https://github.com/bherbruck/solidcraft/security) and choose +open the repository's [Security tab](https://github.com/tangency-labs/solidcraft/security) and choose **Report a vulnerability** -([direct link](https://github.com/bherbruck/solidcraft/security/advisories/new)). +([direct link](https://github.com/tangency-labs/solidcraft/security/advisories/new)). -Please include what you found, how to reproduce it (a design file, command or MCP request), the -version and platform, and the impact you expect. I'll acknowledge the report as soon as I can, -keep you updated in the advisory, and credit you when the fix is published unless you'd rather -stay anonymous. +Please include what you found, the steps you ran to reproduce it (a design file, command or MCP +request), the version and platform, and what an attacker gains. I'll acknowledge the report as soon +as I can, keep you updated in the advisory, and credit you when the fix is published unless you'd +rather stay anonymous. -Areas where reports are especially useful: +## What counts as a security issue -- opening untrusted design, STEP, STL or 3MF files (crashes, excessive memory or CPU, path tricks) -- the MCP server and the control API (file access outside the allowed folders, command injection) -- the web app (anything reaching beyond the page's own storage) -- release packages and the update paths (AppImage, Flatpak, MSI, deb, rpm, snap) +Advisories are for problems where someone gets something they shouldn't, without already having +access to your computer or your account. For example: + +- opening a design, STEP, STL or 3MF file from someone else runs code, or reads or overwrites files + it shouldn't +- a website or another computer can reach or control SolidCraft +- an agent gets past a prompt that promised to ask you first +- the web app reaches beyond the page's own storage +- a release package or an update can be tampered with +- an API key or token gets sent somewhere it shouldn't go + +## What to report as a normal bug + +Please [open an issue](https://github.com/tangency-labs/solidcraft/issues/new) for these. They're +still worth fixing, but they aren't security issues: + +- anything that needs a program already running on your computer, or the control token. A program + running as you can already do what you can. +- MCP's allowed folders. They guard against accidents, they aren't a security boundary, and an agent + with a shell of its own can already reach those files. Getting around them isn't a vulnerability. +- crashes, hangs, or heavy memory or CPU use, unless they also lead to something in the list above +- anything that only happens in an unusual setup you'd have to choose on purpose + +## Before you send it + +- **Run it.** Reproduce the problem on the latest release. If you only read the code, say so, and + expect it to wait. +- **Check it yourself.** If a scanner or an AI agent found it, read the code and confirm it first. + These tools tend to overrate what they find. +- **Say what's gained.** Name what the attacker needs and what they get. I set the final severity. + +Reports that don't fit will be closed with a short note, or moved to the issue tracker. diff --git a/apps/solidcraft-cli/tests/model_cache.rs b/apps/solidcraft-cli/tests/model_cache.rs index ceee4ec69..91011e67c 100644 --- a/apps/solidcraft-cli/tests/model_cache.rs +++ b/apps/solidcraft-cli/tests/model_cache.rs @@ -317,7 +317,8 @@ fn a_model_saved_under_another_check_mode_is_evaluated_again() { /// later round at the corner where they meet blends them again with it whether the design was /// opened from its model or evaluated anew. Two edges of a 20 mm box rounded r2 (a mitre at the /// corner (20, 0, 20)), saved; opened, the upright edge there rounded r3: the corner all three -/// rounded at once make, 10 faces and 7928.743041 mm³, the same body as the design evaluated anew. +/// rounded at once make (SMLib's setback corner, kernel `three_rounds_at_a_corner`), 15 faces and +/// 7928.142563938 mm³, the same body as the design evaluated anew. #[test] fn a_later_round_after_opening_blends_the_saved_rounds_again() { let mut built = Session::default(); @@ -334,8 +335,8 @@ fn a_later_round_after_opening_blends_the_saved_rounds_again() { let st = s.model.state(); let b = &st.body("Box").unwrap().body; let v = solidcraft_engine::kernel::measure(b).unwrap().volume; - assert_eq!(b.face_count(), 10); - assert!((v - 7928.743041).abs() < 1e-6, "{v}"); + assert_eq!(b.face_count(), 15); + assert!((v - 7928.142563938).abs() < 1e-6, "{v}"); } assert_eq!(model("later round", &cached), model("later round", &rebuilt)); let _ = std::fs::remove_file(&path); diff --git a/apps/solidcraft/src/control_server.rs b/apps/solidcraft/src/control_server.rs index b3a197edf..996d7c54a 100644 --- a/apps/solidcraft/src/control_server.rs +++ b/apps/solidcraft/src/control_server.rs @@ -22,6 +22,10 @@ const MAX_BAD_LINES: usize = 8; /// How long a subscribed connection waits after a `design.changed` line before the next: what /// changes meanwhile (a parameter dragged) goes out as one line, the latest (#6985). const EVENT_GAP: Duration = Duration::from_millis(100); +/// How long a new connection has to show the token. A client connects when it has a request to +/// send, so this is plenty; one that doesn't send it loses the connection, and its seat among +/// [`MAX_CONNECTIONS`] goes to someone else. +const TOKEN_WAIT: Duration = Duration::from_secs(5); static OPEN: AtomicUsize = AtomicUsize::new(0); /// The token files this launch wrote (its control port, the agent chat's endpoint) and the @@ -225,23 +229,53 @@ fn unauthorized() -> Value { /// Refuse the connection: the reply, then the end of what we send, then what the client had /// already sent read and dropped (a little, briefly). Closing a socket with unread input resets /// the connection, and a reset can reach the client before it has read the refusal. -fn refuse(out: &mut TcpStream, reader: &mut BufReader) { +fn refuse(out: &mut TcpStream, reader: &mut BufReader) { use std::io::Read; let _ = send(out, &unauthorized()); let _ = out.shutdown(std::net::Shutdown::Write); - let _ = reader.get_ref().set_read_timeout(Some(Duration::from_millis(500))); + reader.get_mut().deadline = Some(Instant::now() + Duration::from_millis(500)); let _ = std::io::copy(&mut reader.by_ref().take(64 * 1024), &mut std::io::sink()); } +/// What a client sends. Until it shows the token, all of its reads share one deadline, so neither +/// blank lines nor a line sent a byte at a time buy it more time. After that it may stay idle as +/// long as it likes. +struct ClientInput { + socket: TcpStream, + deadline: Option, +} + +impl ClientInput { + /// No deadline any more: the client showed the token. + fn admit(&mut self) -> std::io::Result<()> { + self.deadline = None; + self.socket.set_read_timeout(None) + } +} + +impl std::io::Read for ClientInput { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if let Some(deadline) = self.deadline { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + self.socket.set_read_timeout(Some(left))?; + } + self.socket.read(buf) + } +} + /// How long a request waits for the app's reply: most requests, and a batch (or every request, -/// on a patient connection). +/// on a patient connection); and how long a new connection has to show the token. #[derive(Clone, Copy)] struct Waits { short: Duration, long: Duration, + token: Duration, } -const WAITS: Waits = Waits { short: Duration::from_secs(60), long: Duration::from_secs(3600) }; +const WAITS: Waits = Waits { short: Duration::from_secs(60), long: Duration::from_secs(3600), token: TOKEN_WAIT }; /// A request that timed out but is still running in the app (#1618): its id and method, and where /// its reply will land. @@ -543,7 +577,7 @@ fn serve_with( let connection = running.connections.fetch_add(1, Ordering::Relaxed) + 1; let Ok(read) = stream.try_clone() else { return }; let mut out = stream; - let mut reader = BufReader::new(read); + let mut reader = BufReader::new(ClientInput { socket: read, deadline: Some(Instant::now() + waits.token) }); let mut bad = 0usize; let mut authenticated = false; let mut pending: Option = None; @@ -554,6 +588,10 @@ fn serve_with( let line = match read_line(&mut reader, MAX_LINE) { Ok(Some(l)) => String::from_utf8_lossy(&l).into_owned(), Ok(None) => break, + // Closed without a word: a client that connected early and only now sends its first + // request would read a line here as the reply to it. It finds the connection closed + // and opens another. + Err(e) if !authenticated && matches!(e.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock) => break, Err(e) => { let _ = answer(&mut out, events.as_ref(), &json!({"ok": false, "error": e.to_string()})); break; @@ -565,7 +603,12 @@ fn serve_with( // The first request must carry the token; later ones on the same connection may. if !authenticated { match token_of(&line) { - Some(t) if control_auth::tokens_match(&t, token) => authenticated = true, + Some(t) if control_auth::tokens_match(&t, token) => { + if reader.get_mut().admit().is_err() { + break; + } + authenticated = true; + } _ => { refuse(&mut out, &mut reader); break; @@ -675,6 +718,80 @@ fn serve_with( mod tests { use super::*; + /// A connection that doesn't show the token in time is closed without a word, however it fills + /// the time. One that does keeps working when it idles for longer than that. + #[test] + fn the_token_has_a_time_limit_and_an_authenticated_client_may_idle() { + use std::io::Read; + let token = "0123456789abcdef0123456789abcdef"; + let limit = Duration::from_millis(500); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + std::thread::spawn(move || { + for req in rx { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + }); + static RUNNING: Running = Running::new(); + let waits = Waits { short: Duration::from_secs(10), long: Duration::from_secs(10), token: limit }; + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let tx = tx.clone(); + std::thread::spawn(move || serve_with(stream, token, tx, egui::Context::default(), false, waits, &RUNNING, &DESIGN_WATCH)); + } + }); + let open = || { + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + s + }; + // Sends `drip` every 50 ms until the server closes; what it read, and when it closed. + let closed_after = |drip: &[u8]| { + let mut s = open(); + let start = Instant::now(); + s.set_read_timeout(Some(Duration::from_millis(50))).unwrap(); + let mut got = Vec::new(); + loop { + let mut buf = [0u8; 256]; + match s.read(&mut buf) { + Ok(0) => break, + Ok(n) => got.extend_from_slice(buf.get(..n).unwrap()), + Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => { + assert!(start.elapsed() < Duration::from_secs(20), "still open"); + let _ = s.write_all(drip); + } + Err(_) => break, + } + } + (got, start.elapsed()) + }; + for drip in [&b""[..], b"\n", b"\r\n \n", b" ", b"{"] { + let (got, took) = closed_after(drip); + assert!(got.is_empty(), "{drip:?} was answered: {}", String::from_utf8_lossy(&got)); + assert!(took >= limit.saturating_sub(Duration::from_millis(50)), "{drip:?} closed after {took:?}"); + } + + let mut s = open(); + let mut lines = BufReader::new(s.try_clone().unwrap()); + let mut ask = |line: Value| -> Value { + writeln!(s, "{line}").unwrap(); + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + serde_json::from_str(&l).unwrap() + }; + assert_eq!(ask(json!({"id": 1, "method": "ui.view", "token": token}))["ok"], true); + std::thread::sleep(limit * 3); + assert_eq!(ask(json!({"id": 2, "method": "ui.view"}))["ok"], true, "idle for longer than the limit"); + + // A wrong token is still answered, at once. + let mut wrong = open(); + writeln!(wrong, "{}", json!({"id": 1, "method": "ui.view", "token": "nope"})).unwrap(); + let mut l = String::new(); + BufReader::new(wrong).read_line(&mut l).unwrap(); + assert!(l.contains("unauthorized"), "{l}"); + } + /// #1618: a request that outlasts its wait says it is still running; the connection keeps its /// reply for `control.pending`, and refuses other requests as `busy` until it lands, so none /// is queued to run unseen behind it. @@ -698,7 +815,7 @@ mod tests { let _ = req.reply.send(json!({"ok": true, "result": req.method})); } }); - let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100) }; + let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100), token: TOKEN_WAIT }; static RUNNING: Running = Running::new(); std::thread::spawn(move || { if let Some(stream) = listener.incoming().flatten().next() { @@ -764,7 +881,7 @@ mod tests { let _ = req.reply.send(json!({"ok": true, "result": req.method})); } }); - let waits = Waits { short: Duration::from_millis(100), long: Duration::from_secs(60) }; + let waits = Waits { short: Duration::from_millis(100), long: Duration::from_secs(60), token: TOKEN_WAIT }; std::thread::spawn(move || { for stream in listener.incoming().flatten() { let tx = tx.clone(); diff --git a/assets/locales/ar.json b/assets/locales/ar.json index 884af24ff..5e342f006 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -477,6 +477,7 @@ "Rectangular": "مستطيلي", "Rectangular Tube": "أنبوب مستطيل", "Reference face": "الوجه المرجعي", + "Reference plane": "المستوى المرجعي", "Relief Depth": "عمق التفريغ", "Relief Width": "عرض التفريغ", "Remove Tools": "إزالة الأدوات", @@ -1216,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "منحنى شريحي بنقاط تحكم (الدرجة 5)", "cmd.sketch_spline_fit_point": "منحنى شريحي بنقاط ملاءمة", "cmd.sketch_spline_insert_point": "إضافة نقطة إلى المنحنى الشريحي", + "cmd.sketch_spline_remove_point": "إزالة نقطة من المنحنى الشريحي", "cmd.sketch_spline_reverse": "عكس اتجاه المنحنى الشريحي", "cmd.sketch_spun_profile": "مقطع دوراني", "cmd.sketch_toggle_diameter": "تبديل نصف القطر / القطر", @@ -1266,6 +1268,7 @@ "cmd.timeline_rollback": "نقل مؤشر الخط الزمني", "cmd.timeline_stop": "إيقاف السجل", "cmd.timeline_suppress": "تعطيل الميزة", + "cmd.ui.assistant": "إظهار المساعد أو إخفاؤه", "cmd.view.render_browser": "متصفح التصيير", "cmd.view.render_dock": "نقل لوحة التصيير", "cmd.view.render_focus": "عرض تركيز التصيير", @@ -1374,7 +1377,7 @@ "dialog.selection_external_curve": "{sketch} · منحنى {id}", "dialog.selection_guidance": "حدد مُدخلًا لتغييره. انقر على العناصر المحددة لإزالتها؛ Ctrl/Cmd مع النقر يبدّل تحديدها أيضًا. راجع المعاينة ثم اضغط موافق.", "dialog.selection_midpoint": "نقطة المنتصف · {id}", - "dialog.selection_profile": "{sketch} · المقطع {number}", + "dialog.selection_profile": "{sketch} · مقطع {number}", "dialog.selection_step": "{step} من {total}: حدد {input}", "dialog.step": "الخطوة", "document.changed_on_disk": "تغيّر {name} على القرص", @@ -2089,12 +2092,19 @@ "parts.family.button_head_cap_screw": "برغي برأس زرّي بتجويف سداسي", "parts.family.dowel_pin": "مسمار توجيه أسطواني", "parts.family.hex_bolt": "برغي سداسي الرأس", + "parts.family.hex_cap_screw_inch": "برغي سداسي الرأس (بوصة)", "parts.family.hex_nut": "صامولة سداسية", + "parts.family.hex_nut_inch": "صامولة سداسية (بوصة)", "parts.family.set_screw": "برغي تثبيت بتجويف سداسي، طرف مسطح", "parts.family.socket_head_cap_screw": "برغي برأس أسطواني بتجويف سداسي", "parts.family.washer": "حلقة مسطحة", + "parts.family.washer_sae": "حلقة مسطحة، SAE (ضيقة)", + "parts.family.washer_uss": "حلقة مسطحة، USS (عريضة)", "parts.holes": "الثقوب (اختياري)", "parts.placement_hint": "اختر ثقبًا أو أكثر لتثبيت قطعة في كل منها، أو اضغط موافق لوضعها عند نقطة الأصل", + "parts.system": "نظام الوحدات", + "parts.system.inch": "بوصة", + "parts.system.metric": "متري", "pattern.alignment_2": "المحاذاة 2", "pattern.alignment_hint": "العدد يشمل الأصل. «توسيط» يوازن النسخ؛ و«قلب» يختار الجانب الإضافي عندما يكون العدد زوجيًا.", "pattern.direction_1": "الاتجاه 1", @@ -4121,6 +4131,7 @@ "ui.agent_chat_auth_terminal": "شغّل هذا في الطرفية، ثم اضغط «اتصال» مرة أخرى:", "ui.agent_chat_auth_title": "تسجيل الدخول إلى الوكيل", "ui.agent_chat_cancel": "إلغاء", + "ui.agent_chat_cancel_timeout": "لم يستجب الوكيل لطلب الإيقاف، فتم قطع الاتصال به. أعد الاتصال للمتابعة.", "ui.agent_chat_cannot_start": "مثبّت، لكنه لا يبدأ: {error}", "ui.agent_chat_changes": "التغييرات: {n}، خطوة تراجع واحدة", "ui.agent_chat_changes_n": "{n} تغييرات", @@ -4130,6 +4141,7 @@ "ui.agent_chat_command": "أمر الوكيل", "ui.agent_chat_connect": "اتصال", "ui.agent_chat_copy": "نسخ", + "ui.agent_chat_copy_message": "نسخ الرسالة", "ui.agent_chat_ctx_bodies": "الأجسام", "ui.agent_chat_ctx_elements": "العناصر", "ui.agent_chat_ctx_features": "الميزات", @@ -4450,6 +4462,8 @@ "ui.coming_later": "قريبًا", "ui.command_done": "تم {command}", "ui.command_palette_hint": "اكتب أمرًا، مثل {example} — أو اضغط S للبحث", + "ui.components_from_bodies_hint": "أنشئ مكونًا لكل جسم محدد، باسم ذلك الجسم، ضمن المكون النشط.", + "ui.components_from_bodies_required": "حدد جسمًا واحدًا على الأقل.", "ui.concentric": "متحد المركز", "ui.cone": "مخروط", "ui.conic_curve": "منحنى مخروطي", @@ -4755,6 +4769,7 @@ "ui.history_sketch_listed_under": "مدرج تحت {feature}", "ui.history_title": "السجل", "ui.history_toggle_names": "إظهار أسماء الميزات أو إخفاؤها", + "ui.history_waits_for_editor": "ينتظر التراجع والإعادة والسجل حتى يكتمل فتح محرر الميزة", "ui.hole": "ثقب", "ui.hole_tap_type": "نوع لولبة الثقب", "ui.hole_type": "نوع الثقب", diff --git a/assets/locales/bs.json b/assets/locales/bs.json index 8bf268a8e..3d3964328 100644 --- a/assets/locales/bs.json +++ b/assets/locales/bs.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Splajn kontrolnih tačaka (stepen 5)", "cmd.sketch_spline_fit_point": "Splajn kroz tačke", "cmd.sketch_spline_insert_point": "Dodaj tačku splajna", + "cmd.sketch_spline_remove_point": "Ukloni tačku splajna", "cmd.sketch_spline_reverse": "Obrni smjer splajna", "cmd.sketch_spun_profile": "Rotirani profil", "cmd.sketch_toggle_diameter": "Prebaci poluprečnik / prečnik", diff --git a/assets/locales/cs.json b/assets/locales/cs.json index b0834d79e..d3dd2c979 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Splajn řídicími body (stupeň 5)", "cmd.sketch_spline_fit_point": "Splajn procházející body", "cmd.sketch_spline_insert_point": "Přidat bod splajnu", + "cmd.sketch_spline_remove_point": "Odebrat bod splajnu", "cmd.sketch_spline_reverse": "Obrátit směr splajnu", "cmd.sketch_spun_profile": "Rotační obrys", "cmd.sketch_toggle_diameter": "Přepnout poloměr / průměr", diff --git a/assets/locales/da.json b/assets/locales/da.json index 55696428f..755582ce5 100644 --- a/assets/locales/da.json +++ b/assets/locales/da.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Spline med kontrolpunkter (grad 5)", "cmd.sketch_spline_fit_point": "Spline gennem punkter", "cmd.sketch_spline_insert_point": "Tilføj splinepunkt", + "cmd.sketch_spline_remove_point": "Fjern splinepunkt", "cmd.sketch_spline_reverse": "Vend splinens retning", "cmd.sketch_spun_profile": "Omdrejningsprofil", "cmd.sketch_toggle_diameter": "Skift mellem radius og diameter", diff --git a/assets/locales/de.json b/assets/locales/de.json index cc740be5c..a9dc57d84 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -477,6 +477,7 @@ "Rectangular": "Rechteckig", "Rectangular Tube": "Rechteckrohr", "Reference face": "Referenzfläche", + "Reference plane": "Referenzebene", "Relief Depth": "Freistellungstiefe", "Relief Width": "Freistellungsbreite", "Remove Tools": "Werkzeuge entfernen", @@ -1213,6 +1214,7 @@ "cmd.sketch_spline_control_point_5": "Spline mit Kontrollpunkten (Grad 5)", "cmd.sketch_spline_fit_point": "Spline mit Fitpunkten", "cmd.sketch_spline_insert_point": "Splinepunkt hinzufügen", + "cmd.sketch_spline_remove_point": "Splinepunkt entfernen", "cmd.sketch_spline_reverse": "Splinerichtung umkehren", "cmd.sketch_spun_profile": "Gedrehtes Profil", "cmd.sketch_toggle_diameter": "Radius / Durchmesser umschalten", @@ -1263,6 +1265,7 @@ "cmd.timeline_rollback": "Zeitleistenmarkierung verschieben", "cmd.timeline_stop": "Verlauf anhalten", "cmd.timeline_suppress": "Merkmal unterdrücken", + "cmd.ui.assistant": "Assistenten ein-/ausblenden", "cmd.view.render_browser": "Render-Browser", "cmd.view.render_dock": "Render-Panel verschieben", "cmd.view.render_focus": "Render-Fokusansicht", @@ -2086,12 +2089,19 @@ "parts.family.button_head_cap_screw": "Linsenkopfschraube mit Innensechskant", "parts.family.dowel_pin": "Zylinderstift", "parts.family.hex_bolt": "Sechskantschraube", + "parts.family.hex_cap_screw_inch": "Sechskantschraube (Zoll)", "parts.family.hex_nut": "Sechskantmutter", + "parts.family.hex_nut_inch": "Sechskantmutter (Zoll)", "parts.family.set_screw": "Gewindestift mit Innensechskant und Kegelstumpf", "parts.family.socket_head_cap_screw": "Zylinderschraube mit Innensechskant", "parts.family.washer": "Unterlegscheibe", + "parts.family.washer_sae": "Unterlegscheibe, SAE (schmal)", + "parts.family.washer_uss": "Unterlegscheibe, USS (breit)", "parts.holes": "Bohrungen (optional)", "parts.placement_hint": "Wählen Sie eine oder mehrere Bohrungen, um in jede ein Teil einzusetzen, oder OK platziert es im Ursprung", + "parts.system": "Maßsystem", + "parts.system.inch": "Zoll", + "parts.system.metric": "Metrisch", "pattern.alignment_2": "Ausrichtung 2", "pattern.alignment_hint": "Die Anzahl enthält das Original. Die zentrierte Anordnung verteilt Kopien auf beide Seiten; bei gerader Anzahl legt die Richtungsumkehr die Seite mit der zusätzlichen Kopie fest.", "pattern.direction_1": "Richtung 1", @@ -4116,6 +4126,7 @@ "ui.agent_chat_auth_terminal": "Führen Sie dies in einem Terminal aus und klicken Sie dann erneut auf Verbinden:", "ui.agent_chat_auth_title": "Beim Agenten anmelden", "ui.agent_chat_cancel": "Abbrechen", + "ui.agent_chat_cancel_timeout": "Der Agent hat nicht auf Stopp reagiert und wurde getrennt. Zum Fortfahren erneut verbinden.", "ui.agent_chat_cannot_start": "Installiert, startet aber nicht: {error}", "ui.agent_chat_changes": "Änderungen: {n}, ein Rückgängig-Schritt", "ui.agent_chat_changes_n": "{n} Änderungen", @@ -4125,6 +4136,7 @@ "ui.agent_chat_command": "Agentenbefehl", "ui.agent_chat_connect": "Verbinden", "ui.agent_chat_copy": "Kopieren", + "ui.agent_chat_copy_message": "Nachricht kopieren", "ui.agent_chat_ctx_bodies": "Körper", "ui.agent_chat_ctx_elements": "Elemente", "ui.agent_chat_ctx_features": "Funktionen", @@ -4445,6 +4457,8 @@ "ui.coming_later": "bald verfügbar", "ui.command_done": "{command} fertig", "ui.command_palette_hint": "Befehl eingeben, z. B. {example} — oder S drücken, um zu suchen", + "ui.components_from_bodies_hint": "Für jeden ausgewählten Körper eine gleichnamige Komponente unter der aktiven Komponente erstellen.", + "ui.components_from_bodies_required": "Mindestens einen Körper auswählen.", "ui.concentric": "Konzentrisch", "ui.cone": "Kegel", "ui.conic_curve": "Kegelschnitt", @@ -4747,6 +4761,7 @@ "ui.history_sketch_listed_under": "Aufgeführt unter {feature}", "ui.history_title": "Verlauf", "ui.history_toggle_names": "Merkmalsnamen ein- oder ausblenden", + "ui.history_waits_for_editor": "Rückgängig, Wiederholen und Verlauf warten, bis der Feature-Editor geöffnet ist", "ui.hole": "Bohrung", "ui.hole_tap_type": "Gewindetyp", "ui.hole_type": "Bohrungstyp", diff --git a/assets/locales/en.json b/assets/locales/en.json index 07ededad6..472421ade 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -477,6 +477,7 @@ "Rectangular": "Rectangular", "Rectangular Tube": "Rectangular Tube", "Reference face": "Reference face", + "Reference plane": "Reference plane", "Relief Depth": "Relief Depth", "Relief Width": "Relief Width", "Remove Tools": "Remove Tools", @@ -1216,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Control Point Spline (Degree 5)", "cmd.sketch_spline_fit_point": "Fit Point Spline", "cmd.sketch_spline_insert_point": "Add Spline Point", + "cmd.sketch_spline_remove_point": "Remove Spline Point", "cmd.sketch_spline_reverse": "Reverse Spline Direction", "cmd.sketch_spun_profile": "Spun Profile", "cmd.sketch_toggle_diameter": "Toggle Radius / Diameter", @@ -1266,6 +1268,7 @@ "cmd.timeline_rollback": "Move Timeline Marker", "cmd.timeline_stop": "Stop History", "cmd.timeline_suppress": "Suppress Feature", + "cmd.ui.assistant": "Toggle Assistant", "cmd.view.render_browser": "Render Browser", "cmd.view.render_dock": "Move Render Dock", "cmd.view.render_focus": "Render Focus View", @@ -2089,12 +2092,19 @@ "parts.family.button_head_cap_screw": "Button head cap screw", "parts.family.dowel_pin": "Parallel pin (dowel)", "parts.family.hex_bolt": "Hex head bolt / screw", + "parts.family.hex_cap_screw_inch": "Hex cap screw (inch)", "parts.family.hex_nut": "Hex nut", + "parts.family.hex_nut_inch": "Hex nut (inch)", "parts.family.set_screw": "Hex socket set screw, flat point", "parts.family.socket_head_cap_screw": "Socket head cap screw", "parts.family.washer": "Plain washer", + "parts.family.washer_sae": "Plain washer, SAE (narrow)", + "parts.family.washer_uss": "Plain washer, USS (wide)", "parts.holes": "Holes (optional)", "parts.placement_hint": "pick one or more holes to seat a part in each, or OK places it at the origin", + "parts.system": "Unit system", + "parts.system.inch": "Inch", + "parts.system.metric": "Metric", "pattern.alignment_2": "Alignment 2", "pattern.alignment_hint": "Counts include the original. Center balances copies; Flip chooses the extra side for even totals.", "pattern.direction_1": "Direction 1", @@ -4121,6 +4131,7 @@ "ui.agent_chat_auth_terminal": "Run this in a terminal, then press Connect again:", "ui.agent_chat_auth_title": "Sign in to the agent", "ui.agent_chat_cancel": "Cancel", + "ui.agent_chat_cancel_timeout": "The agent did not respond to Stop and was disconnected. Reconnect to continue.", "ui.agent_chat_cannot_start": "Installed, but it does not start: {error}", "ui.agent_chat_changes": "Changes: {n}, one undo step", "ui.agent_chat_changes_n": "{n} changes", @@ -4130,6 +4141,7 @@ "ui.agent_chat_command": "Agent command", "ui.agent_chat_connect": "Connect", "ui.agent_chat_copy": "Copy", + "ui.agent_chat_copy_message": "Copy message", "ui.agent_chat_ctx_bodies": "Bodies", "ui.agent_chat_ctx_elements": "Elements", "ui.agent_chat_ctx_features": "Features", @@ -4450,6 +4462,8 @@ "ui.coming_later": "coming later", "ui.command_done": "{command} done", "ui.command_palette_hint": "Type a command, e.g. {example} — or press S to search", + "ui.components_from_bodies_hint": "Create one component per selected body, named after that body, under the active component.", + "ui.components_from_bodies_required": "Select at least one body.", "ui.concentric": "Concentric", "ui.cone": "Cone", "ui.conic_curve": "Conic Curve", @@ -4755,6 +4769,7 @@ "ui.history_sketch_listed_under": "Listed under {feature}", "ui.history_title": "History", "ui.history_toggle_names": "Show or hide feature names", + "ui.history_waits_for_editor": "Undo, Redo and History wait until the feature editor has opened", "ui.hole": "Hole", "ui.hole_tap_type": "Hole Tap Type", "ui.hole_type": "Hole Type", diff --git a/assets/locales/es.json b/assets/locales/es.json index 5ae4ea115..0f1d0ba0e 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -1195,6 +1195,7 @@ "cmd.sketch_spline_control_point_5": "Spline por puntos de control (grado 5)", "cmd.sketch_spline_fit_point": "Spline por puntos de ajuste", "cmd.sketch_spline_insert_point": "Añadir punto de spline", + "cmd.sketch_spline_remove_point": "Eliminar punto de spline", "cmd.sketch_spline_reverse": "Invertir dirección del spline", "cmd.sketch_spun_profile": "Perfil de revolución", "cmd.sketch_toggle_diameter": "Alternar radio / diámetro", @@ -1805,12 +1806,19 @@ "parts.family.button_head_cap_screw": "Tornillo cabeza botón", "parts.family.dowel_pin": "Pasador cilíndrico", "parts.family.hex_bolt": "Tornillo de cabeza hexagonal", + "parts.family.hex_cap_screw_inch": "Tornillo de cabeza hexagonal (pulgadas)", "parts.family.hex_nut": "Tuerca hexagonal", + "parts.family.hex_nut_inch": "Tuerca hexagonal (pulgadas)", "parts.family.set_screw": "Prisionero con hexágono interior, punta plana", "parts.family.socket_head_cap_screw": "Tornillo cilíndrico con hexágono interior", "parts.family.washer": "Arandela plana", + "parts.family.washer_sae": "Arandela plana, SAE (estrecha)", + "parts.family.washer_uss": "Arandela plana, USS (ancha)", "parts.holes": "Agujeros (opcional)", "parts.placement_hint": "elige uno o más agujeros para colocar una pieza en cada uno, o Aceptar la coloca en el origen", + "parts.system": "Sistema de unidades", + "parts.system.inch": "Pulgadas", + "parts.system.metric": "Métrico", "pattern.alignment_2": "Alineación 2", "pattern.alignment_hint": "Los recuentos incluyen el original. Centrar equilibra las copias; Invertir elige el lado adicional cuando el total es par.", "pattern.direction_1": "Dirección 1", diff --git a/assets/locales/fi.json b/assets/locales/fi.json index 3af298273..72995e5df 100644 --- a/assets/locales/fi.json +++ b/assets/locales/fi.json @@ -1191,6 +1191,7 @@ "cmd.sketch_spline_control_point_5": "Ohjauspistesplini (aste 5)", "cmd.sketch_spline_fit_point": "Sovituspistesplini", "cmd.sketch_spline_insert_point": "Lisää splinipiste", + "cmd.sketch_spline_remove_point": "Poista splinipiste", "cmd.sketch_spline_reverse": "Käännä splinin suunta", "cmd.sketch_spun_profile": "Pyöräytysprofiili", "cmd.sketch_toggle_diameter": "Vaihda säde / halkaisija", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 4da478259..e9094dff8 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -1195,6 +1195,7 @@ "cmd.sketch_spline_control_point_5": "Spline par points de contrôle (degré 5)", "cmd.sketch_spline_fit_point": "Spline par points", "cmd.sketch_spline_insert_point": "Ajouter un point de spline", + "cmd.sketch_spline_remove_point": "Supprimer un point de spline", "cmd.sketch_spline_reverse": "Inverser le sens de la spline", "cmd.sketch_spun_profile": "Profil de révolution", "cmd.sketch_toggle_diameter": "Basculer rayon / diamètre", @@ -2053,12 +2054,19 @@ "parts.family.button_head_cap_screw": "Vis à tête bombée à six pans creux", "parts.family.dowel_pin": "Goupille cylindrique", "parts.family.hex_bolt": "Vis à tête hexagonale", + "parts.family.hex_cap_screw_inch": "Vis à tête hexagonale (pouces)", "parts.family.hex_nut": "Écrou hexagonal", + "parts.family.hex_nut_inch": "Écrou hexagonal (pouces)", "parts.family.set_screw": "Vis sans tête à six pans creux, bout plat", "parts.family.socket_head_cap_screw": "Vis à tête cylindrique à six pans creux", "parts.family.washer": "Rondelle plate", + "parts.family.washer_sae": "Rondelle plate, SAE (étroite)", + "parts.family.washer_uss": "Rondelle plate, USS (large)", "parts.holes": "Trous (facultatif)", "parts.placement_hint": "choisissez un ou plusieurs trous pour y loger une pièce chacun, ou OK la place à l'origine", + "parts.system": "Système d'unités", + "parts.system.inch": "Pouces", + "parts.system.metric": "Métrique", "pattern.alignment_2": "Alignement 2", "pattern.alignment_hint": "La quantité inclut l’original. Le centrage répartit les copies de chaque côté ; si la quantité est paire, l’inversion choisit le côté qui reçoit la copie supplémentaire.", "pattern.direction_1": "Direction 1", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index 9ebf8ec29..816b09d11 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Spline por puntos de control (grao 5)", "cmd.sketch_spline_fit_point": "Spline por puntos de paso", "cmd.sketch_spline_insert_point": "Engadir punto ao spline", + "cmd.sketch_spline_remove_point": "Eliminar punto do spline", "cmd.sketch_spline_reverse": "Inverter a dirección do spline", "cmd.sketch_spun_profile": "Perfil de revolución", "cmd.sketch_toggle_diameter": "Alternar raio / diámetro", diff --git a/assets/locales/he.json b/assets/locales/he.json index 93fe01ff4..ce5bdece3 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -477,6 +477,7 @@ "Rectangular": "מלבני", "Rectangular Tube": "צינור מלבני", "Reference face": "פאת ייחוס", + "Reference plane": "מישור ייחוס", "Relief Depth": "עומק הקלה", "Relief Width": "רוחב הקלה", "Remove Tools": "הסרת הכלים", @@ -1216,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "ספליין נקודות בקרה (מעלה 5)", "cmd.sketch_spline_fit_point": "ספליין נקודות התאמה", "cmd.sketch_spline_insert_point": "הוספת נקודה לספליין", + "cmd.sketch_spline_remove_point": "הסרת נקודה מהספליין", "cmd.sketch_spline_reverse": "היפוך כיוון הספליין", "cmd.sketch_spun_profile": "פרופיל סיבובי", "cmd.sketch_toggle_diameter": "מעבר בין רדיוס לקוטר", @@ -1266,6 +1268,7 @@ "cmd.timeline_rollback": "הזזת סמן ציר הזמן", "cmd.timeline_stop": "עצירת ציר הזמן", "cmd.timeline_suppress": "השבתת פיצ'ר", + "cmd.ui.assistant": "הצגה או הסתרה של העוזר", "cmd.view.render_browser": "דפדפן רינדור", "cmd.view.render_dock": "הזז את עגינת הרינדור", "cmd.view.render_focus": "תצוגת מיקוד רינדור", @@ -2089,12 +2092,19 @@ "parts.family.button_head_cap_screw": "בורג ראש כפתור עם שקע משושה", "parts.family.dowel_pin": "פין גלילי", "parts.family.hex_bolt": "בורג ראש משושה", + "parts.family.hex_cap_screw_inch": "בורג ראש משושה (אינץ')", "parts.family.hex_nut": "אום משושה", + "parts.family.hex_nut_inch": "אום משושה (אינץ')", "parts.family.set_screw": "בורג אלן ללא ראש, קצה שטוח", "parts.family.socket_head_cap_screw": "בורג ראש גלילי עם משושה פנימי", "parts.family.washer": "דסקית שטוחה", + "parts.family.washer_sae": "דסקית שטוחה, SAE (צרה)", + "parts.family.washer_uss": "דסקית שטוחה, USS (רחבה)", "parts.holes": "חורים (אופציונלי)", "parts.placement_hint": "בחרו חור אחד או יותר כדי להושיב חלק בכל אחד, או לחצו אישור כדי למקם אותו בראשית", + "parts.system": "מערכת יחידות", + "parts.system.inch": "אינץ'", + "parts.system.metric": "מטרי", "pattern.alignment_2": "יישור 2", "pattern.alignment_hint": "הספירה כוללת את המקור. מרכוז מאזן את העותקים; היפוך בוחר את הצד שמקבל את העותק הנוסף כשהסך זוגי.", "pattern.direction_1": "כיוון 1", @@ -4121,6 +4131,7 @@ "ui.agent_chat_auth_terminal": "יש להריץ את זה במסוף ואז ללחוץ שוב על התחברות:", "ui.agent_chat_auth_title": "התחברות לסוכן", "ui.agent_chat_cancel": "ביטול", + "ui.agent_chat_cancel_timeout": "הסוכן לא הגיב לבקשת העצירה ונותק. יש להתחבר מחדש כדי להמשיך.", "ui.agent_chat_cannot_start": "מותקן, אך אינו מופעל: {error}", "ui.agent_chat_changes": "שינויים: {n}, צעד ביטול אחד", "ui.agent_chat_changes_n": "{n} שינויים", @@ -4130,6 +4141,7 @@ "ui.agent_chat_command": "פקודת הסוכן", "ui.agent_chat_connect": "התחברות", "ui.agent_chat_copy": "העתקה", + "ui.agent_chat_copy_message": "העתק הודעה", "ui.agent_chat_ctx_bodies": "גופים", "ui.agent_chat_ctx_elements": "אלמנטים", "ui.agent_chat_ctx_features": "פיצ'רים", @@ -4450,6 +4462,8 @@ "ui.coming_later": "בקרוב", "ui.command_done": "{command} הושלם", "ui.command_palette_hint": "יש להקליד פקודה, למשל {example} — או ללחוץ S לחיפוש", + "ui.components_from_bodies_hint": "יצירת רכיב לכל גוף שנבחר, בשם הגוף, תחת הרכיב הפעיל.", + "ui.components_from_bodies_required": "יש לבחור גוף אחד לפחות.", "ui.concentric": "משותף מרכז", "ui.cone": "חרוט", "ui.conic_curve": "עקום חרוטי", @@ -4755,6 +4769,7 @@ "ui.history_sketch_listed_under": "מופיעה תחת {feature}", "ui.history_title": "ציר הזמן", "ui.history_toggle_names": "הצגה או הסתרה של שמות הפיצ'רים", + "ui.history_waits_for_editor": "ביטול, ביצוע מחדש וציר הזמן ממתינים עד שעורך הפעולה ייפתח", "ui.hole": "חור", "ui.hole_tap_type": "סוג הברגת חור", "ui.hole_type": "סוג חור", diff --git a/assets/locales/hr.json b/assets/locales/hr.json index d34506684..859c7cfbd 100644 --- a/assets/locales/hr.json +++ b/assets/locales/hr.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Spline kontrolnih točaka (stupanj 5)", "cmd.sketch_spline_fit_point": "Spline kroz točke", "cmd.sketch_spline_insert_point": "Dodaj točku splinea", + "cmd.sketch_spline_remove_point": "Ukloni točku splinea", "cmd.sketch_spline_reverse": "Obrni smjer splinea", "cmd.sketch_spun_profile": "Rotirani profil", "cmd.sketch_toggle_diameter": "Prebaci polumjer / promjer", diff --git a/assets/locales/hu.json b/assets/locales/hu.json index a9adc2a86..72dc071e5 100644 --- a/assets/locales/hu.json +++ b/assets/locales/hu.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Vezérlőpontos spline (5. fokú)", "cmd.sketch_spline_fit_point": "Illesztőpontos spline", "cmd.sketch_spline_insert_point": "Splinepont hozzáadása", + "cmd.sketch_spline_remove_point": "Splinepont eltávolítása", "cmd.sketch_spline_reverse": "Spline irányának megfordítása", "cmd.sketch_spun_profile": "Forgatott profil", "cmd.sketch_toggle_diameter": "Sugár / átmérő váltása", diff --git a/assets/locales/id.json b/assets/locales/id.json index 3002ccec3..7f8a0d900 100644 --- a/assets/locales/id.json +++ b/assets/locales/id.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Spline Titik Kontrol (Derajat 5)", "cmd.sketch_spline_fit_point": "Spline Titik Fit", "cmd.sketch_spline_insert_point": "Tambah Titik Spline", + "cmd.sketch_spline_remove_point": "Hapus Titik Spline", "cmd.sketch_spline_reverse": "Balik Arah Spline", "cmd.sketch_spun_profile": "Profil Putar", "cmd.sketch_toggle_diameter": "Beralih Radius / Diameter", diff --git a/assets/locales/it.json b/assets/locales/it.json index 30c9e227b..4afa4e8d3 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Spline per punti di controllo (grado 5)", "cmd.sketch_spline_fit_point": "Spline interpolante", "cmd.sketch_spline_insert_point": "Aggiungi punto alla spline", + "cmd.sketch_spline_remove_point": "Rimuovi punto dalla spline", "cmd.sketch_spline_reverse": "Inverti direzione della spline", "cmd.sketch_spun_profile": "Profilo di tornitura", "cmd.sketch_toggle_diameter": "Alterna raggio / diametro", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 8ee6660fe..69a9723b0 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -477,6 +477,7 @@ "Rectangular": "長方形", "Rectangular Tube": "角形鋼管", "Reference face": "参照面", + "Reference plane": "参照平面", "Relief Depth": "リリーフ深さ", "Relief Width": "リリーフ幅", "Remove Tools": "ツールボディを削除", @@ -1216,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "制御点スプライン (次数 5)", "cmd.sketch_spline_fit_point": "通過点スプライン", "cmd.sketch_spline_insert_point": "スプライン点を追加", + "cmd.sketch_spline_remove_point": "スプライン点を削除", "cmd.sketch_spline_reverse": "スプラインの方向を反転", "cmd.sketch_spun_profile": "回転プロファイル", "cmd.sketch_toggle_diameter": "半径 / 直径の切り替え", @@ -1266,6 +1268,7 @@ "cmd.timeline_rollback": "タイムライン マーカーを移動", "cmd.timeline_stop": "履歴を停止", "cmd.timeline_suppress": "フィーチャーを抑制", + "cmd.ui.assistant": "アシスタントの表示切り替え", "cmd.view.render_browser": "Renderブラウザー", "cmd.view.render_dock": "レンダードックを移動", "cmd.view.render_focus": "Renderフォーカス表示", @@ -2089,12 +2092,19 @@ "parts.family.button_head_cap_screw": "ボタンヘッド六角穴付きボルト", "parts.family.dowel_pin": "平行ピン", "parts.family.hex_bolt": "六角ボルト", + "parts.family.hex_cap_screw_inch": "六角ボルト(インチ)", "parts.family.hex_nut": "六角ナット", + "parts.family.hex_nut_inch": "六角ナット(インチ)", "parts.family.set_screw": "六角穴付き止めねじ 平先", "parts.family.socket_head_cap_screw": "六角穴付きボルト", "parts.family.washer": "平座金", + "parts.family.washer_sae": "平座金、SAE(小形)", + "parts.family.washer_uss": "平座金、USS(大形)", "parts.holes": "穴 (省略可)", "parts.placement_hint": "1 つ以上の穴を選ぶとそれぞれに部品を取り付けます。選ばずに OK を押すと原点に配置します", + "parts.system": "単位系", + "parts.system.inch": "インチ", + "parts.system.metric": "メートル", "pattern.alignment_2": "配置 2", "pattern.alignment_hint": "個数には元の図形が含まれます。中央配置ではコピーを両側に配置し、反転で偶数個の場合に多く配置する側を切り替えます。", "pattern.direction_1": "方向 1", @@ -4121,6 +4131,7 @@ "ui.agent_chat_auth_terminal": "ターミナルでこれを実行してから、もう一度「接続」を押してください:", "ui.agent_chat_auth_title": "エージェントにサインイン", "ui.agent_chat_cancel": "キャンセル", + "ui.agent_chat_cancel_timeout": "エージェントが停止要求に応答しなかったため、接続を切断しました。続行するには再接続してください。", "ui.agent_chat_cannot_start": "インストールされていますが、起動しません: {error}", "ui.agent_chat_changes": "{n} 件の変更(元に戻すは1回)", "ui.agent_chat_changes_n": "{n} 件の変更", @@ -4130,6 +4141,7 @@ "ui.agent_chat_command": "エージェントのコマンド", "ui.agent_chat_connect": "接続", "ui.agent_chat_copy": "コピー", + "ui.agent_chat_copy_message": "メッセージをコピー", "ui.agent_chat_ctx_bodies": "ボディ", "ui.agent_chat_ctx_elements": "要素", "ui.agent_chat_ctx_features": "フィーチャ", @@ -4450,6 +4462,8 @@ "ui.coming_later": "準備中", "ui.command_done": "{command} 完了", "ui.command_palette_hint": "コマンドを入力(例: {example})— または S キーで検索", + "ui.components_from_bodies_hint": "選択した各ボディと同じ名前のコンポーネントを、アクティブなコンポーネントの下に作成します。", + "ui.components_from_bodies_required": "ボディを1つ以上選択してください。", "ui.concentric": "同心", "ui.cone": "円錐", "ui.conic_curve": "円錐曲線", @@ -4755,6 +4769,7 @@ "ui.history_sketch_listed_under": "{feature} の下に表示", "ui.history_title": "履歴", "ui.history_toggle_names": "フィーチャー名を表示・非表示", + "ui.history_waits_for_editor": "元に戻す、やり直す、履歴は、フィーチャーエディターが開くまで待機します", "ui.hole": "穴", "ui.hole_tap_type": "ねじ穴タイプ", "ui.hole_type": "穴タイプ", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 3f6b3ecbc..70b4d0920 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -407,6 +407,7 @@ "Recover unsaved design?": "저장되지 않은 디자인을 복구할까요?", "Rectangular": "직사각형", "Reference face": "참조 면", + "Reference plane": "참조 평면", "Relief Depth": "릴리프 깊이", "Relief Width": "릴리프 너비", "Remove Tools": "공구 제거", @@ -1097,6 +1098,7 @@ "cmd.timeline_rollback": "타임라인 마커 이동", "cmd.timeline_stop": "기록 재생 중지", "cmd.timeline_suppress": "특성 비활성화", + "cmd.ui.assistant": "도우미 표시 전환", "cmd.view.render_browser": "렌더 브라우저", "cmd.view.render_dock": "렌더 도크 이동", "cmd.view.render_focus": "렌더 집중 보기", @@ -2960,6 +2962,7 @@ "ui.agent_chat_auth_terminal": "터미널에서 이것을 실행한 뒤 다시 연결을 누르세요:", "ui.agent_chat_auth_title": "에이전트에 로그인", "ui.agent_chat_cancel": "취소", + "ui.agent_chat_cancel_timeout": "에이전트가 중지 요청에 응답하지 않아 연결이 끊어졌습니다. 계속하려면 다시 연결하세요.", "ui.agent_chat_cannot_start": "설치되어 있지만 시작되지 않습니다: {error}", "ui.agent_chat_changes": "변경 {n}개, 실행 취소 한 번", "ui.agent_chat_changes_of": "변경 {n}/{limit}", @@ -3235,6 +3238,8 @@ "ui.coming_later": "추후 지원 예정", "ui.command_done": "{command} 완료", "ui.command_palette_hint": "명령 입력(예: {example}) — 또는 S 키를 눌러 검색", + "ui.components_from_bodies_hint": "활성 구성요소 아래에 선택한 각 바디와 같은 이름의 구성요소를 만듭니다.", + "ui.components_from_bodies_required": "바디를 하나 이상 선택하세요.", "ui.concentric": "동심", "ui.cone": "원뿔", "ui.conic_curve": "원뿔 곡선", diff --git a/assets/locales/ms.json b/assets/locales/ms.json index bd71861f7..d5f37dc83 100644 --- a/assets/locales/ms.json +++ b/assets/locales/ms.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Splin Titik Kawalan (Darjah 5)", "cmd.sketch_spline_fit_point": "Splin Titik Padanan", "cmd.sketch_spline_insert_point": "Tambah Titik Splin", + "cmd.sketch_spline_remove_point": "Buang Titik Splin", "cmd.sketch_spline_reverse": "Songsangkan Arah Splin", "cmd.sketch_spun_profile": "Profil Putaran", "cmd.sketch_toggle_diameter": "Togol Jejari / Diameter", diff --git a/assets/locales/nb.json b/assets/locales/nb.json index 43a212b37..ef2b4d68a 100644 --- a/assets/locales/nb.json +++ b/assets/locales/nb.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Spline med kontrollpunkter (grad 5)", "cmd.sketch_spline_fit_point": "Spline gjennom punkter", "cmd.sketch_spline_insert_point": "Legg til splinepunkt", + "cmd.sketch_spline_remove_point": "Fjern splinepunkt", "cmd.sketch_spline_reverse": "Reverser splineretning", "cmd.sketch_spun_profile": "Dreid profil", "cmd.sketch_toggle_diameter": "Veksle mellom radius / diameter", diff --git a/assets/locales/nl.json b/assets/locales/nl.json index 22f2b541d..2df6ec9a1 100644 --- a/assets/locales/nl.json +++ b/assets/locales/nl.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Spline met controlepunten (graad 5)", "cmd.sketch_spline_fit_point": "Spline door punten", "cmd.sketch_spline_insert_point": "Splinepunt toevoegen", + "cmd.sketch_spline_remove_point": "Splinepunt verwijderen", "cmd.sketch_spline_reverse": "Splinerichting omkeren", "cmd.sketch_spun_profile": "Gedraaid profiel", "cmd.sketch_toggle_diameter": "Straal/diameter omschakelen", diff --git a/assets/locales/pending/agent-chat-copy-message.json b/assets/locales/pending/agent-chat-copy-message.json deleted file mode 100644 index cb724aa67..000000000 --- a/assets/locales/pending/agent-chat-copy-message.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "en": { "ui.agent_chat_copy_message": "Copy message" }, - "de": { "ui.agent_chat_copy_message": "Nachricht kopieren" }, - "ar": { "ui.agent_chat_copy_message": "نسخ الرسالة" }, - "he": { "ui.agent_chat_copy_message": "העתק הודעה" }, - "ja": { "ui.agent_chat_copy_message": "メッセージをコピー" }, - "vi": { "ui.agent_chat_copy_message": "Sao chép tin nhắn" }, - "zh": { "ui.agent_chat_copy_message": "复制消息" } -} diff --git a/assets/locales/pending/assistant-shortcut.json b/assets/locales/pending/assistant-shortcut.json deleted file mode 100644 index 888dcf986..000000000 --- a/assets/locales/pending/assistant-shortcut.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "ar": { - "cmd.ui.assistant": "إظهار المساعد أو إخفاؤه" - }, - "de": { - "cmd.ui.assistant": "Assistenten ein-/ausblenden" - }, - "en": { - "cmd.ui.assistant": "Toggle Assistant" - }, - "he": { - "cmd.ui.assistant": "הצגה או הסתרה של העוזר" - }, - "ja": { - "cmd.ui.assistant": "アシスタントの表示切り替え" - }, - "ko": { - "cmd.ui.assistant": "도우미 표시 전환" - }, - "vi": { - "cmd.ui.assistant": "Bật/tắt trợ lý" - }, - "zh": { - "cmd.ui.assistant": "切换助手显示" - } -} diff --git a/assets/locales/pending/fillet-setback-at-least.json b/assets/locales/pending/fillet-setback-at-least.json new file mode 100644 index 000000000..e3728e4a5 --- /dev/null +++ b/assets/locales/pending/fillet-setback-at-least.json @@ -0,0 +1,26 @@ +{ + "en": { + "ui.fillet_error_setback_short": "The setback is too short for this corner's patch: it builds from {least} on. Try a longer Setback." + }, + "ar": { + "ui.fillet_error_setback_short": "مسافة الإرجاع قصيرة جدًا على رقعة هذه الزاوية: تُبنى ابتداءً من {least}. جرّب مسافة إرجاع أطول." + }, + "de": { + "ui.fillet_error_setback_short": "Der Rücksprung ist für das Eckstück zu kurz: Es lässt sich ab {least} bauen. Versuchen Sie einen längeren Rücksprung." + }, + "he": { + "ui.fillet_error_setback_short": "הנסיגה קצרה מדי עבור הטלאי של פינה זו: הוא נבנה החל מ-{least}. נסו נסיגה ארוכה יותר." + }, + "ja": { + "ui.fillet_error_setback_short": "このコーナーのパッチにはセットバックが短すぎます。{least} 以上で作れます。より長いセットバックを試してください。" + }, + "ko": { + "ui.fillet_error_setback_short": "이 코너의 패치에 비해 셋백이 너무 짧습니다. {least}부터 만들 수 있습니다. 더 긴 셋백을 시도해 보세요." + }, + "vi": { + "ui.fillet_error_setback_short": "Khoảng Lùi quá ngắn cho mảng của góc này: mảng được tạo từ {least} trở lên. Hãy thử khoảng Lùi dài hơn." + }, + "zh": { + "ui.fillet_error_setback_short": "对于此角点的面片,后退距离太短:从 {least} 起可以构建。请尝试更长的后退距离。" + } +} diff --git a/assets/locales/pending/spline-remove-point.json b/assets/locales/pending/spline-remove-point.json deleted file mode 100644 index 17e7511b4..000000000 --- a/assets/locales/pending/spline-remove-point.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "en": { "cmd.sketch_spline_remove_point": "Remove Spline Point" }, - "ar": { "cmd.sketch_spline_remove_point": "إزالة نقطة من المنحنى الشريحي" }, - "bs": { "cmd.sketch_spline_remove_point": "Ukloni tačku splajna" }, - "cs": { "cmd.sketch_spline_remove_point": "Odebrat bod splajnu" }, - "da": { "cmd.sketch_spline_remove_point": "Fjern splinepunkt" }, - "de": { "cmd.sketch_spline_remove_point": "Splinepunkt entfernen" }, - "es": { "cmd.sketch_spline_remove_point": "Eliminar punto de spline" }, - "fi": { "cmd.sketch_spline_remove_point": "Poista splinipiste" }, - "fr": { "cmd.sketch_spline_remove_point": "Supprimer un point de spline" }, - "gl": { "cmd.sketch_spline_remove_point": "Eliminar punto do spline" }, - "he": { "cmd.sketch_spline_remove_point": "הסרת נקודה מהספליין" }, - "hr": { "cmd.sketch_spline_remove_point": "Ukloni točku splinea" }, - "hu": { "cmd.sketch_spline_remove_point": "Splinepont eltávolítása" }, - "id": { "cmd.sketch_spline_remove_point": "Hapus Titik Spline" }, - "it": { "cmd.sketch_spline_remove_point": "Rimuovi punto dalla spline" }, - "ja": { "cmd.sketch_spline_remove_point": "スプライン点を削除" }, - "ms": { "cmd.sketch_spline_remove_point": "Buang Titik Splin" }, - "nb": { "cmd.sketch_spline_remove_point": "Fjern splinepunkt" }, - "nl": { "cmd.sketch_spline_remove_point": "Splinepunt verwijderen" }, - "pl": { "cmd.sketch_spline_remove_point": "Usuń punkt splajnu" }, - "ro": { "cmd.sketch_spline_remove_point": "Elimină punct din spline" }, - "ru": { "cmd.sketch_spline_remove_point": "Удалить точку сплайна" }, - "sr": { "cmd.sketch_spline_remove_point": "Уклони тачку сплајна" }, - "sv": { "cmd.sketch_spline_remove_point": "Ta bort splinepunkt" }, - "tr": { "cmd.sketch_spline_remove_point": "Spline Noktasını Kaldır" }, - "uk": { "cmd.sketch_spline_remove_point": "Видалити точку сплайна" }, - "vi": { "cmd.sketch_spline_remove_point": "Xóa điểm khỏi đường cong Spline" }, - "zh": { "cmd.sketch_spline_remove_point": "删除样条曲线点" }, - "zh-TW": { "cmd.sketch_spline_remove_point": "刪除雲形線點" } -} diff --git a/assets/locales/pl.json b/assets/locales/pl.json index f2873bceb..0d7924305 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -1190,6 +1190,7 @@ "cmd.sketch_spline_control_point_5": "Splajn z punktów kontrolnych (stopień 5)", "cmd.sketch_spline_fit_point": "Splajn przez punkty", "cmd.sketch_spline_insert_point": "Dodaj punkt splajnu", + "cmd.sketch_spline_remove_point": "Usuń punkt splajnu", "cmd.sketch_spline_reverse": "Odwróć kierunek splajnu", "cmd.sketch_spun_profile": "Profil obrotowy", "cmd.sketch_toggle_diameter": "Przełącz promień / średnicę", diff --git a/assets/locales/ro.json b/assets/locales/ro.json index 4944a5675..9d16781b4 100644 --- a/assets/locales/ro.json +++ b/assets/locales/ro.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Spline cu puncte de control (grad 5)", "cmd.sketch_spline_fit_point": "Spline cu puncte de potrivire", "cmd.sketch_spline_insert_point": "Adaugă punct la spline", + "cmd.sketch_spline_remove_point": "Elimină punct din spline", "cmd.sketch_spline_reverse": "Inversează direcția spline-ului", "cmd.sketch_spun_profile": "Profil rotit", "cmd.sketch_toggle_diameter": "Comută rază / diametru", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 8640bb9c5..3d2211604 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -115,7 +115,7 @@ "Circular": "Круговой", "Circumference": "Окружность", "Clockwise": "По часовой стрелке", - "Close draft": "Закрыть анализ уклонов", + "Close draft": "Закрыть черновик", "Collapse": "Свернуть", "Collisions": "Столкновения", "Colour": "Цвет", @@ -775,6 +775,8 @@ "at the face": "у грани", "bom.group_children": "Вложенные детали в строке своей детали", "browser.body_name": "Тело{number}", + "browser.calibrate_click_a": "Щёлкните по изображению, чтобы задать точку A, или введите её координаты.", + "browser.calibrate_click_b": "Щёлкните по изображению, чтобы задать точку B, или введите её координаты.", "browser.calibrate_title": "Калибровка: {name}", "browser.capture_many": "Компоненты ({count}) перемещены, но их положения не зафиксированы.", "browser.capture_note": "«Зафиксировать положение» сохраняет новое положение; «Вернуть положение» восстанавливает прежнее.", @@ -1188,6 +1190,7 @@ "cmd.sketch_spline_control_point_5": "Сплайн по контрольным точкам (степень 5)", "cmd.sketch_spline_fit_point": "Сплайн по точкам сглаживания", "cmd.sketch_spline_insert_point": "Добавить точку сплайна", + "cmd.sketch_spline_remove_point": "Удалить точку сплайна", "cmd.sketch_spline_reverse": "Обратить направление сплайна", "cmd.sketch_spun_profile": "Профиль вращения", "cmd.sketch_toggle_diameter": "Переключить радиус / диаметр", @@ -1552,6 +1555,16 @@ "help.sketch.constraint.symmetry": "Делает две точки или кривые зеркальными друг для друга относительно линии или центральной точки. Используйте, чтобы профиль оставался симметричным при изменении одной стороны.", "help.sketch.constraint.tangent": "Заставляет две кривые касаться, например линию и дугу. Используйте для плавных стыков без излома.", "help.sketch.construction": "Переключает кривые между обычной и вспомогательной геометрией, которую профили не учитывают. Используйте вспомогательные кривые как помощники для разметки, ориентиры и размеры.", + "help.sketch.construction_line": "Создайте бесконечную вспомогательную прямую через две точки. С её помощью можно разметить эскиз, не разделяя профили.", + "help.sketch.construction_line.angle": "Создайте бесконечную вспомогательную прямую под углом к оси X эскиза. Укажите точку и введите угол либо задайте направление.", + "help.sketch.construction_line.bisector": "Выберите две пересекающиеся прямые эскиза, затем одну из двух биссектрис. Результат изменяется вместе с исходными прямыми.", + "help.sketch.construction_line.horizontal": "Создайте бесконечную горизонтальную вспомогательную прямую через точку. Её горизонтальное ограничение сохраняется при последующих изменениях.", + "help.sketch.construction_line.parallel": "Выберите прямую эскиза, затем разместите параллельную бесконечную вспомогательную прямую. Щелчок правой кнопкой — выбрать другую исходную прямую.", + "help.sketch.construction_line.perpendicular": "Выберите прямую эскиза, затем разместите перпендикулярную бесконечную вспомогательную прямую. Щелчок правой кнопкой — выбрать другую исходную прямую.", + "help.sketch.construction_line.tangent_at": "Создайте касательную в точке окружности или дуги окружности либо в конечной точке открытого сплайна или коники. Выберите кривую, затем точку касания.", + "help.sketch.construction_line.tangent_external": "Выберите окружность или дугу, затем внешнюю точку и решение для касательной. В предпросмотре показаны только точки касания на нарисованной дуге.", + "help.sketch.construction_line.tangent_two": "Выберите две окружности или дуги, затем в предпросмотре выберите общую касательную. Точки касания должны лежать на нарисованных кривых.", + "help.sketch.construction_line.vertical": "Создайте бесконечную вертикальную вспомогательную прямую через точку. Её вертикальное ограничение сохраняется при последующих изменениях.", "help.sketch.copy": "Копирует выбранные кривые и точки эскиза вместе с ограничениями и размерами между ними. Вставьте их в этот эскиз или в другой.", "help.sketch.create": "Начинает новый 2D-эскиз на плоскости или плоской грани модели. Каждое «Выдавливание», «Вращение» и «Сдвиг» начинается с эскиза.", "help.sketch.cut": "Копирует выбранную геометрию эскиза и удаляет её из эскиза одним шагом отмены. Вставьте её в другое место этого эскиза или в другой эскиз.", @@ -2218,6 +2231,8 @@ "prefs.overall_speed": "Общая скорость", "prefs.parameter_list_rows": "Строк в списке параметров", "prefs.parameter_list_rows_tip": "Стрелка вниз в пустом поле значения открывает список параметров, сначала избранные, не больше этого числа. Меньшее число делает список лёгким в большом дизайне.", + "prefs.persistent_ribbon_pressed": "Подсвечивать активные команды на ленте", + "prefs.persistent_ribbon_pressed_help": "Подсвечивает команды на ленте, пока их действие включено. Отключите, чтобы сохранить прежний нейтральный вид и справку по командам.", "prefs.perspective_fov": "Угол обзора", "prefs.placement": "Размещение", "prefs.prefer_free_sketch_points": "Предпочитать подвижные точки эскиза, когда точки перекрываются", @@ -2281,6 +2296,8 @@ "prefs.sketch_exit_view_note": "Куда переходит вид после «Завершить эскиз», «Отмена» или двойного Esc.", "prefs.sketch_face_activates_part": "Эскиз на грани детали делает эту деталь активной", "prefs.sketch_face_activates_part_note": "Эскиз, начатый на грани тела другого компонента, сначала активирует этот компонент, поэтому эскиз принадлежит ему и в браузере остаётся с этой деталью. После этого деталь остаётся активной. Выкл.: эскиз принадлежит активному компоненту.", + "prefs.sketch_open_look_at": "Поворачивать камеру к эскизу при его открытии", + "prefs.sketch_open_look_at_note": "Выкл.: при создании или редактировании эскиза вид не меняется. «Взгляд на» поворачивает вид к эскизу, когда это нужно.", "prefs.sketch_recent_snap": "Автопривязка к недавним центрам и серединам", "prefs.sketch_recent_snap_note": "При рисовании курсор привязывается к месту пересечения направляющих двух последних центров окружностей или середин прямых отрезков. Выкл.: эти направляющие остаются только визуальными, а курсор не смещается.", "prefs.sketch_selection": "Эскиз и выделение", @@ -2388,6 +2405,10 @@ "properties.title": "Свойства: {name}", "recovery.days_ago": "{count} дн. назад", "recovery.detail": "{file} · операций: {features} · автосохранение {when}", + "recovery.discard_all": "Отбросить все", + "recovery.discard_all_detail": "Это действие нельзя отменить.", + "recovery.discard_all_title": "Отбросить автосохранения ({count})?", + "recovery.discard_all_title_one": "Отбросить 1 автосохранение?", "recovery.hours_ago": "{count} ч назад", "recovery.just_now": "только что", "recovery.min_ago": "{count} мин назад", diff --git a/assets/locales/sr.json b/assets/locales/sr.json index 089e76bcd..07b0a787c 100644 --- a/assets/locales/sr.json +++ b/assets/locales/sr.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Сплајн контролних тачака (степен 5)", "cmd.sketch_spline_fit_point": "Сплајн кроз тачке", "cmd.sketch_spline_insert_point": "Додај тачку сплајна", + "cmd.sketch_spline_remove_point": "Уклони тачку сплајна", "cmd.sketch_spline_reverse": "Обрни смер сплајна", "cmd.sketch_spun_profile": "Ротирани профил", "cmd.sketch_toggle_diameter": "Пребаци полупречник / пречник", diff --git a/assets/locales/sv.json b/assets/locales/sv.json index 6696743ea..359663936 100644 --- a/assets/locales/sv.json +++ b/assets/locales/sv.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Spline med kontrollpunkter (grad 5)", "cmd.sketch_spline_fit_point": "Spline med passpunkter", "cmd.sketch_spline_insert_point": "Lägg till splinepunkt", + "cmd.sketch_spline_remove_point": "Ta bort splinepunkt", "cmd.sketch_spline_reverse": "Vänd splinens riktning", "cmd.sketch_spun_profile": "Roterad profil", "cmd.sketch_toggle_diameter": "Växla radie / diameter", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 8863f5123..4639202a3 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Kontrol noktalı spline (derece 5)", "cmd.sketch_spline_fit_point": "Uydurma noktalı spline", "cmd.sketch_spline_insert_point": "Spline Noktası Ekle", + "cmd.sketch_spline_remove_point": "Spline Noktasını Kaldır", "cmd.sketch_spline_reverse": "Spline yönünü ters çevir", "cmd.sketch_spun_profile": "Döndürülmüş profil", "cmd.sketch_toggle_diameter": "Yarıçap / Çap Arasında Geçiş Yap", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index f2fe74478..b4ea5922b 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "Сплайн за контрольними точками (5-й степінь)", "cmd.sketch_spline_fit_point": "Сплайн за точками проходження", "cmd.sketch_spline_insert_point": "Додати точку сплайна", + "cmd.sketch_spline_remove_point": "Видалити точку сплайна", "cmd.sketch_spline_reverse": "Обернути напрямок сплайна", "cmd.sketch_spun_profile": "Профіль обертання", "cmd.sketch_toggle_diameter": "Перемкнути радіус / діаметр", diff --git a/assets/locales/vi.json b/assets/locales/vi.json index c6dde61c4..77104b6b7 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -477,6 +477,7 @@ "Rectangular": "Hình chữ nhật", "Rectangular Tube": "Thép hộp chữ nhật", "Reference face": "Bề mặt tham chiếu", + "Reference plane": "Mặt phẳng tham chiếu", "Relief Depth": "Độ sâu rãnh thoát", "Relief Width": "Chiều rộng rãnh thoát", "Remove Tools": "Loại bỏ công cụ cắt", @@ -1216,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "Đường cong Spline qua điểm điều khiển (Bậc 5)", "cmd.sketch_spline_fit_point": "Đường cong Spline qua các điểm", "cmd.sketch_spline_insert_point": "Thêm điểm vào đường cong Spline", + "cmd.sketch_spline_remove_point": "Xóa điểm khỏi đường cong Spline", "cmd.sketch_spline_reverse": "Đảo ngược hướng đường cong Spline", "cmd.sketch_spun_profile": "Biên dạng xoay tròn (Spun Profile)", "cmd.sketch_toggle_diameter": "Chuyển đổi bán kính / đường kính", @@ -1266,6 +1268,7 @@ "cmd.timeline_rollback": "Di chuyển con trỏ lịch sử thiết kế", "cmd.timeline_stop": "Dừng lịch sử", "cmd.timeline_suppress": "Tạm nén tính năng", + "cmd.ui.assistant": "Bật/tắt trợ lý", "cmd.view.render_browser": "Trình duyệt kết xuất", "cmd.view.render_dock": "Di chuyển neo kết xuất", "cmd.view.render_focus": "Chế độ xem tập trung kết xuất", @@ -2089,12 +2092,19 @@ "parts.family.button_head_cap_screw": "Vít đầu tròn lục giác chìm", "parts.family.dowel_pin": "Chốt trụ", "parts.family.hex_bolt": "Bu lông đầu lục giác", + "parts.family.hex_cap_screw_inch": "Bu lông đầu lục giác (inch)", "parts.family.hex_nut": "Đai ốc lục giác", + "parts.family.hex_nut_inch": "Đai ốc lục giác (inch)", "parts.family.set_screw": "Vít trí lục giác chìm, đầu bằng", "parts.family.socket_head_cap_screw": "Bu lông lục giác chìm đầu trụ", "parts.family.washer": "Vòng đệm phẳng", + "parts.family.washer_sae": "Vòng đệm phẳng, SAE (hẹp)", + "parts.family.washer_uss": "Vòng đệm phẳng, USS (rộng)", "parts.holes": "Lỗ (tùy chọn)", "parts.placement_hint": "chọn một hoặc nhiều lỗ để lắp một chi tiết vào mỗi lỗ, hoặc nhấn OK để đặt tại gốc tọa độ", + "parts.system": "Hệ đơn vị", + "parts.system.inch": "Inch", + "parts.system.metric": "Hệ mét", "pattern.alignment_2": "Căn chỉnh 2", "pattern.alignment_hint": "Số lượng bao gồm cả bản gốc. Căn giữa sẽ cân bằng các bản sao; Đổi hướng sẽ chọn phía bổ sung cho tổng số chẵn.", "pattern.direction_1": "Hướng 1", @@ -4121,6 +4131,7 @@ "ui.agent_chat_auth_terminal": "Chạy lệnh này trong cửa sổ dòng lệnh, sau đó nhấp Kết nối lại:", "ui.agent_chat_auth_title": "Đăng nhập vào AI Agent", "ui.agent_chat_cancel": "Hủy bỏ", + "ui.agent_chat_cancel_timeout": "Tác nhân không phản hồi yêu cầu Dừng nên đã bị ngắt kết nối. Hãy kết nối lại để tiếp tục.", "ui.agent_chat_cannot_start": "Đã cài đặt nhưng không khởi động được: {error}", "ui.agent_chat_changes": "Thay đổi: {n}, trong 1 bước hoàn tác", "ui.agent_chat_changes_n": "{n} thay đổi", @@ -4130,6 +4141,7 @@ "ui.agent_chat_command": "Lệnh của AI Agent", "ui.agent_chat_connect": "Kết nối", "ui.agent_chat_copy": "Sao chép", + "ui.agent_chat_copy_message": "Sao chép tin nhắn", "ui.agent_chat_ctx_bodies": "Khối", "ui.agent_chat_ctx_elements": "Phần tử", "ui.agent_chat_ctx_features": "Tính năng", @@ -4450,6 +4462,8 @@ "ui.coming_later": "sắp ra mắt", "ui.command_done": "Hoàn tất lệnh {command}", "ui.command_palette_hint": "Nhập một lệnh, ví dụ: {example} — hoặc nhấn S để tìm kiếm", + "ui.components_from_bodies_hint": "Tạo một thành phần cho mỗi vật thể đã chọn, đặt tên theo vật thể đó, bên dưới thành phần đang hoạt động.", + "ui.components_from_bodies_required": "Chọn ít nhất một vật thể.", "ui.concentric": "Đồng tâm", "ui.cone": "Hình nón", "ui.conic_curve": "Đường cong Conic", @@ -4755,6 +4769,7 @@ "ui.history_sketch_listed_under": "Được liệt kê dưới {feature}", "ui.history_title": "Lịch sử", "ui.history_toggle_names": "Hiện hoặc ẩn tên tính năng", + "ui.history_waits_for_editor": "Hoàn tác, Làm lại và Lịch sử sẽ chờ cho đến khi trình chỉnh sửa tính năng mở xong", "ui.hole": "Tạo lỗ", "ui.hole_tap_type": "Kiểu ta-rô ren lỗ", "ui.hole_type": "Loại lỗ", diff --git a/assets/locales/zh-TW.json b/assets/locales/zh-TW.json index efa82f87d..ec056da6c 100644 --- a/assets/locales/zh-TW.json +++ b/assets/locales/zh-TW.json @@ -1203,6 +1203,7 @@ "cmd.sketch_spline_control_point_5": "控制點雲形線(5 次)", "cmd.sketch_spline_fit_point": "擬合點雲形線", "cmd.sketch_spline_insert_point": "新增雲形線點", + "cmd.sketch_spline_remove_point": "刪除雲形線點", "cmd.sketch_spline_reverse": "反向雲形線方向", "cmd.sketch_spun_profile": "旋轉輪廓", "cmd.sketch_toggle_diameter": "切換半徑 / 直徑", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 4599dd401..7616304d3 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -477,6 +477,7 @@ "Rectangular": "矩形", "Rectangular Tube": "矩形管", "Reference face": "参考面", + "Reference plane": "参考平面", "Relief Depth": "止裂槽深度", "Relief Width": "止裂槽宽度", "Remove Tools": "移除工具", @@ -1216,6 +1217,7 @@ "cmd.sketch_spline_control_point_5": "控制点样条曲线(5 次)", "cmd.sketch_spline_fit_point": "拟合点样条曲线", "cmd.sketch_spline_insert_point": "添加样条曲线点", + "cmd.sketch_spline_remove_point": "删除样条曲线点", "cmd.sketch_spline_reverse": "反向样条曲线方向", "cmd.sketch_spun_profile": "旋转轮廓", "cmd.sketch_toggle_diameter": "切换半径 / 直径", @@ -1266,6 +1268,7 @@ "cmd.timeline_rollback": "移动时间线标记", "cmd.timeline_stop": "停止历史播放", "cmd.timeline_suppress": "抑制特征", + "cmd.ui.assistant": "切换助手显示", "cmd.view.render_browser": "渲染浏览器", "cmd.view.render_dock": "移动渲染停靠面板", "cmd.view.render_focus": "渲染专注视图", @@ -2089,12 +2092,19 @@ "parts.family.button_head_cap_screw": "圆头内六角螺钉", "parts.family.dowel_pin": "圆柱销", "parts.family.hex_bolt": "六角头螺栓", + "parts.family.hex_cap_screw_inch": "六角头螺栓(英制)", "parts.family.hex_nut": "六角螺母", + "parts.family.hex_nut_inch": "六角螺母(英制)", "parts.family.set_screw": "内六角平端紧定螺钉", "parts.family.socket_head_cap_screw": "内六角圆柱头螺钉", "parts.family.washer": "平垫圈", + "parts.family.washer_sae": "平垫圈,SAE(窄型)", + "parts.family.washer_uss": "平垫圈,USS(宽型)", "parts.holes": "孔(可选)", "parts.placement_hint": "选择一个或多个孔,在每个孔中各装一个零件;或按确定将其放在原点", + "parts.system": "单位制", + "parts.system.inch": "英制", + "parts.system.metric": "公制", "pattern.alignment_2": "对齐 2", "pattern.alignment_hint": "数量包含原始图形。居中时副本分布在两侧;数量为偶数时,反转可切换多一个副本的一侧。", "pattern.direction_1": "方向 1", @@ -4121,6 +4131,7 @@ "ui.agent_chat_auth_terminal": "在终端中运行以下命令,然后再次点击连接:", "ui.agent_chat_auth_title": "登录智能体", "ui.agent_chat_cancel": "取消", + "ui.agent_chat_cancel_timeout": "代理未响应停止请求,已断开连接。请重新连接以继续。", "ui.agent_chat_cannot_start": "已安装,但无法启动:{error}", "ui.agent_chat_changes": "{n} 项更改,一步撤销", "ui.agent_chat_changes_n": "{n} 项更改", @@ -4130,6 +4141,7 @@ "ui.agent_chat_command": "智能体命令", "ui.agent_chat_connect": "连接", "ui.agent_chat_copy": "复制", + "ui.agent_chat_copy_message": "复制消息", "ui.agent_chat_ctx_bodies": "实体", "ui.agent_chat_ctx_elements": "元素", "ui.agent_chat_ctx_features": "特征", @@ -4450,6 +4462,8 @@ "ui.coming_later": "即将推出", "ui.command_done": "{command} 完成", "ui.command_palette_hint": "输入命令,例如 {example} — 或按 S 搜索", + "ui.components_from_bodies_hint": "在活动组件下,为每个选定实体创建一个以该实体命名的组件。", + "ui.components_from_bodies_required": "请至少选择一个实体。", "ui.concentric": "同心", "ui.cone": "圆锥体", "ui.conic_curve": "圆锥曲线", @@ -4755,6 +4769,7 @@ "ui.history_sketch_listed_under": "列在 {feature} 下", "ui.history_title": "历史", "ui.history_toggle_names": "显示或隐藏特征名称", + "ui.history_waits_for_editor": "撤销、重做和历史将等待特征编辑器打开", "ui.hole": "孔", "ui.hole_tap_type": "孔攻丝类型", "ui.hole_type": "孔类型", diff --git a/assets/shaders/viewport.wgsl b/assets/shaders/viewport.wgsl index 4ce7ee127..87a722295 100644 --- a/assets/shaders/viewport.wgsl +++ b/assets/shaders/viewport.wgsl @@ -37,6 +37,7 @@ fn near_z(c: vec4) -> f32 { @group(1) @binding(2) var acc_t: texture_2d; @group(2) @binding(0) var ao_depth: texture_2d; +@group(2) @binding(1) var ao_map: texture_2d; fn clipped(p: vec3) -> bool { return length(u.clip.xyz) > 0.5 && dot(u.clip.xyz, p) > u.clip.w; @@ -73,7 +74,7 @@ fn out_color(c: vec4) -> vec4 { } struct TOut { - @builtin(position) pos: vec4, + @invariant @builtin(position) pos: vec4, @location(0) n: vec3, @location(1) c: vec4, @location(2) wp: vec3, @@ -124,7 +125,7 @@ fn vs_tri_inst( /// stores every vertex's outputs: more of them cost more than the triangles' shared vertices /// save). struct FOut { - @builtin(position) pos: vec4, + @invariant @builtin(position) pos: vec4, @location(0) rp: vec3, @location(1) c: vec4, @location(2) @interpolate(flat) h: u32, @@ -230,6 +231,12 @@ fn fs_ao_depth_flat(i: FOut, @builtin(front_facing) front: bool) -> AoDepth { return opaque_depth(t, front); } +@fragment +fn fs_ao_term_flat(i: FOut, @builtin(front_facing) front: bool) -> @location(0) vec4 { + let t = flat_fragment(i, front); + return ao_term(t, front); +} + /// Opaque model surfaces: cut by the section plane/// Opaque model surfaces: cut by the section plane, the inside shows as a flat cap colour. @fragment fn fs_solid(i: TOut, @builtin(front_facing) front: bool) -> @location(0) vec4 { @@ -367,11 +374,88 @@ fn opaque_depth(i: TOut, front: bool) -> AoDepth { return AoDepth(depth, bitcast(depth)); } +/// The term for an opaque surface's fragment, on the prepass's depth. A section's cut face has none. +fn ao_term(i: TOut, front: bool) -> vec4 { + if (clipped(i.wp) || length(i.n) < 0.5) { discard; } + if (!front && length(u.clip.xyz) > 0.5) { return vec4(1.0); } + return vec4(occlusion_term(i)); +} + +@fragment +fn fs_ao_term(i: TOut, @builtin(front_facing) front: bool) -> @location(0) vec4 { + return ao_term(i, front); +} + +@vertex +fn vs_ao_blur(@builtin(vertex_index) v: u32) -> @builtin(position) vec4 { + let p = vec2(f32((v << 1u) & 2u), f32(v & 2u)); + return vec4(p * 2.0 - 1.0, 0.0, 1.0); +} + +/// The depth map at `p`, reading 0 near and 1 far whichever way the buffer runs. +fn map_depth(p: vec2) -> f32 { + let at = clamp(p, vec2(0), vec2(textureDimensions(ao_depth)) - vec2(1)); + let d = bitcast(textureLoad(ao_depth, at, 0).x); + return select(d, 1.0 - d, reversed()); +} + +/// The raw term (`ao_map` in this pass) averaged over a 4 x 4 window, which holds every turn of +/// [`ao_turn`]'s pattern once. A neighbour counts when it lies on this pixel's plane, the slope +/// taken from the nearer side across each axis, so no surface's shade crosses an edge. +@fragment +fn fs_ao_blur(@builtin(position) pos: vec4) -> @location(0) vec4 { + let c = vec2(pos.xy); + let d = map_depth(c); + if (d >= 1.0) { return vec4(1.0); } + let left = d - map_depth(c + vec2(-1, 0)); + let right = map_depth(c + vec2(1, 0)) - d; + let above = d - map_depth(c + vec2(0, -1)); + let below = map_depth(c + vec2(0, 1)) - d; + let dx = select(right, left, abs(left) < abs(right)); + let dy = select(below, above, abs(above) < abs(below)); + let tolerance = 1.5 * (abs(dx) + abs(dy)) + 1e-6; + let last = vec2(textureDimensions(ao_map)) - vec2(1); + var sum = 0.0; + var weight = 0.0; + for (var y = -2; y < 2; y = y + 1) { + for (var x = -2; x < 2; x = x + 1) { + let p = c + vec2(x, y); + let s = map_depth(p); + if (s < 1.0 && abs(s - (d + dx * f32(x) + dy * f32(y))) <= tolerance) { + sum = sum + textureLoad(ao_map, clamp(p, vec2(0), last), 0).x; + weight = weight + 1.0; + } + } + } + return vec4(sum / max(weight, 1.0)); +} + +/// A pixel's turn of the sample pattern: every 4 x 4 window holds each of 16 turns once. +fn ao_turn(pos: vec2) -> f32 { + let x = u32(pos.x) & 3u; + let y = u32(pos.y) & 3u; + let v = ((x ^ y) & 1u) << 3u | (y & 1u) << 2u | ((x ^ y) >> 1u) << 1u | (y >> 1u); + return (f32(v) + 0.5) / 16.0; +} + +/// The lit pass's occlusion: the blurred term where this point falls in the map, whatever the +/// window's viewport offset and supersampling. +fn occlusion(i: TOut) -> f32 { + let size = vec2(textureDimensions(ao_map)); + // The maps are 1 × 1 stand-ins until a frame draws into them (the product preview draws no + // prepass, and AO off releases them): they tell nothing, so leave the surface unoccluded. + if (u.ao.x <= 0.0 || length(i.n) < 0.5 || size.x < 2 || size.y < 2) { return 1.0; } + let q = u.vp * vec4(i.wp, 1.0); + if (q.w <= 0.0) { return 1.0; } + let uv = vec2(q.x / q.w * 0.5 + 0.5, 0.5 - q.y / q.w * 0.5); + return textureLoad(ao_map, clamp(vec2(uv * vec2(size)), vec2(0), size - vec2(1)), 0).x; +} + // Cosine-weighted hemisphere samples, the pattern turned by a different angle at each pixel. // Projecting the sample and a point one radius toward the eye supplies a depth range in both // orthographic and perspective views; distant foreground geometry cannot cast a dark halo onto // a background surface. -fn occlusion(i: TOut) -> f32 { +fn occlusion_term(i: TOut) -> f32 { let radius = u.ao.x; if (radius <= 0.0 || length(i.n) < 0.5) { return 1.0; } var n = normalize(i.n); @@ -385,10 +469,9 @@ fn occlusion(i: TOut) -> f32 { if (size.x < 2 || size.y < 2) { return 1.0; } // The same offsets at every pixel made each sample darken its own shifted copy of a nearby // part's outline: faint ghosts of the part where the radius is large on screen (#4167), - // stepped bands along contacts where it is small (#3407). Turned by interleaved gradient - // noise (Jimenez 2014), neighbouring pixels sample different points and the copies break up - // into an even grain. - let turn = fract(52.9829189 * fract(dot(i.pos.xy, vec2(0.06711056, 0.00583715)))); + // stepped bands along contacts where it is small (#3407). Turned, neighbouring pixels sample + // different points, the copies break up into grain, and the blur takes the grain out (#9327). + let turn = ao_turn(i.pos.xy); let t = tangent * cos(turn * 6.28318531) + bitangent * sin(turn * 6.28318531); let b = cross(n, t); // One comparison for both depth directions: depths read as 0 near / 1 far (mirrored when diff --git a/crates/doc/src/assembly.rs b/crates/doc/src/assembly.rs index d962850f7..0e82f2185 100644 --- a/crates/doc/src/assembly.rs +++ b/crates/doc/src/assembly.rs @@ -219,9 +219,12 @@ fn map_plane_ref(m: &Mat, p: &mut PlaneRef) { } // Named origin planes and construction planes are the component's own. PlaneRef::Origin { .. } | PlaneRef::Construction { .. } => {} - PlaneRef::Tangent { face, at } => { + PlaneRef::Tangent { face, at, reference, .. } => { *at = apply_point(m, *at); map_geo_ref(m, face); + if let Some(r) = reference { + map_geo_ref(m, r); + } } PlaneRef::Midplane { .. } | PlaneRef::TwoEdges { .. } diff --git a/crates/doc/src/clipboard.rs b/crates/doc/src/clipboard.rs index 8ad156356..3d8311181 100644 --- a/crates/doc/src/clipboard.rs +++ b/crates/doc/src/clipboard.rs @@ -335,7 +335,12 @@ fn checked_plane(p: &PlaneRef, depth: usize) -> crate::Result<()> { checked_geo(b, depth + 1)?; checked_geo(c, depth + 1)?; } - PlaneRef::Tangent { face, .. } => checked_geo(face, depth + 1)?, + PlaneRef::Tangent { face, reference, .. } => { + checked_geo(face, depth + 1)?; + if let Some(r) = reference { + checked_geo(r, depth + 1)?; + } + } PlaneRef::AlongPath { path, .. } => checked_geo(path, depth + 1)?, _ => {} } diff --git a/crates/doc/src/construct.rs b/crates/doc/src/construct.rs index 08aec0f8c..8ea542be5 100644 --- a/crates/doc/src/construct.rs +++ b/crates/doc/src/construct.rs @@ -116,6 +116,11 @@ pub struct Construct { pub feature: u64, pub name: String, pub geom: ConstructGeom, + /// The bodies it was built from, when every pick it reads lies on a body + /// ([`source_bodies`]): a later Move of all of them carries it along (#10127). Empty when + /// it also reads something fixed (a point, a plane, a sketch), which keeps it in place. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub bodies: Vec, } /// Everything a reference needs to be resolved. @@ -529,6 +534,48 @@ fn surface_normal(s: FaceSurface, p: Vec3) -> Option<(Vec3, Vec3)> { } } +/// A point over `s` where the face turns towards `towards` (a reference plane's normal): around +/// the axis of a cylinder, cone or torus, turned `angle` about it; straight at it on a sphere. Of +/// the two sides, the one `at` is on (#8822). +fn facing(s: FaceSurface, at: Vec3, towards: Vec3, angle: f64) -> Result { + let side = |d: Vec3, w: Vec3| if d.dot(w) < 0.0 { d * -1.0 } else { d }; + let around = |axis: Vec3, w: Vec3| -> Result<(Vec3, f64)> { + let d = (towards - axis * towards.dot(axis)) + .normalized() + .ok_or_else(|| bad("the reference is square to the face's axis: every plane tangent to the face meets it at a right angle"))?; + let d = d * angle.cos() + axis.cross(d) * angle.sin(); + let r = w - axis * w.dot(axis); + Ok((side(d, r), r.len())) + }; + if !angle.is_finite() { + return Err(bad("the angle is not a number")); + } + Ok(match s { + FaceSurface::Plane { .. } => at, + FaceSurface::Cylinder { origin, axis, radius } => { + let w = at - origin; + let (d, _) = around(axis.into(), w)?; + origin + axis * w.dot(axis) + d * radius + } + FaceSurface::Cone { apex, axis, .. } => { + let w = at - apex; + let (d, r) = around(axis.into(), w)?; + apex + axis * w.dot(axis) + d * r.max(1e-6) + } + // On the outer equator, where the tube faces away from the axis. + FaceSurface::Torus { center, axis, major, minor } => { + let (d, _) = around(axis.into(), at - center)?; + center + d * (major + minor) + } + FaceSurface::Sphere { center, radius } => { + if angle.abs() > 1e-12 { + return Err(bad("a sphere has no axis to turn the plane about: leave the angle out")); + } + center + side(towards, at - center) * radius + } + }) +} + fn face_surface_at(ctx: &Ctx, g: &GeoRef) -> Result<(FaceSurface, Vec3)> { match g { GeoRef::Face { at, name } => { @@ -570,6 +617,46 @@ fn line_line(a: (Vec3, Vec3), b: (Vec3, Vec3)) -> Option { Some(((p + u * s) + (q + v * t)) * 0.5) } +/// The bodies a construction built from `refs` lies on: each face, edge and vertex pick's body, +/// and the bodies of the constructions it is built from. Empty when any pick is not on a body +/// (a fixed point, the origin, a plane, a world axis, a sketch) or is not found: such a +/// construction is held by something a move of the bodies leaves where it is, so it stays. +pub(crate) fn source_bodies(ctx: &Ctx, refs: &[&GeoRef]) -> Vec { + let mut out: Vec = Vec::new(); + for g in refs { + let found: Vec = match g { + GeoRef::Face { at, name } => face_of(ctx.st, *at, name).map(|(b, ..)| vec![b.definition_name().to_string()]).unwrap_or_default(), + GeoRef::Edge { at, name } => edge_pick(ctx.st, *at, name).map(|(b, ..)| vec![b.definition_name().to_string()]).unwrap_or_default(), + GeoRef::Vertex { .. } => { + point(ctx, g).ok().and_then(|p| vertex_body(ctx.st, p)).map(|b| vec![b.definition_name().to_string()]).unwrap_or_default() + } + GeoRef::Axis { name } | GeoRef::ConstructPoint { name } => { + ctx.st.construct.iter().find(|c| c.name.as_str() == AsRef::::as_ref(name)).map(|c| c.bodies.clone()).unwrap_or_default() + } + _ => Vec::new(), + }; + if found.is_empty() { + return Vec::new(); + } + for b in found { + if !out.contains(&b) { + out.push(b); + } + } + } + out +} + +/// The body with a vertex (an end of one of its edges) at `p`. +fn vertex_body(st: &ModelState, p: Vec3) -> Option<&ModelBody> { + bodies(st).find(|b| { + let tol = (b.body.size() * 1e-3).max(1e-3); + b.body + .edges(tol) + .is_ok_and(|edges| edges.iter().flat_map(|e| [e.points.first(), e.points.last()]).flatten().any(|v| v.dist(p) <= 1e-6 * (1.0 + p.len()))) + }) +} + pub(crate) fn resolve_axis(ctx: &Ctx, d: &AxisDef) -> Result<(Vec3, Vec3)> { match d { AxisDef::ThroughFace { face } => line(ctx, face), @@ -669,9 +756,17 @@ pub(crate) fn resolve_geo_plane(ctx: &Ctx, p: &PlaneRef) -> Result { } Plane::new(pa, pb - pa, pc - pa).ok_or_else(degenerate) } - PlaneRef::Tangent { face, at } => { + PlaneRef::Tangent { face, at, reference, angle } => { let (s, _) = face_surface_at(ctx, face)?; - let (on, n) = surface_normal(s, *at).ok_or_else(|| bad("the point is on the face's axis"))?; + let at = match reference { + Some(r) => { + let towards = plane(ctx, r)?.normal().normalized().ok_or_else(degenerate)?; + let angle = angle.as_ref().map(|a| Document::eval_in(ctx.vals, a, Kind::Angle)).transpose()?.unwrap_or(0.0); + facing(s, *at, towards, angle)? + } + None => *at, + }; + let (on, n) = surface_normal(s, at).ok_or_else(|| bad("the point is on the face's axis"))?; Plane::from_normal(on, n).ok_or_else(degenerate) } PlaneRef::Perpendicular { plane: base, line: l } => { @@ -816,7 +911,11 @@ impl PlaneRef { PlaneRef::Midplane { a, b } | PlaneRef::TwoEdges { a, b } | PlaneRef::AxisPoint { axis: a, point: b } => vec![a.as_mut(), b.as_mut()], PlaneRef::Perpendicular { plane, line } => vec![plane.as_mut(), line.as_mut()], PlaneRef::ThreePoints { a, b, c } => vec![a.as_mut(), b.as_mut(), c.as_mut()], - PlaneRef::Tangent { face, .. } => vec![face.as_mut()], + PlaneRef::Tangent { face, reference, .. } => { + let mut v = vec![face.as_mut()]; + v.extend(reference.as_deref_mut()); + v + } PlaneRef::AlongPath { path, .. } => vec![path.as_mut()], PlaneRef::ThroughPoint { base, point } => { let mut refs = base.refs_mut(); diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 05c17aca3..e231bed3a 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -86,8 +86,17 @@ pub enum PlaneRef { AxisPoint { axis: Box, point: Box }, /// Through three points. ThreePoints { a: Box, b: Box, c: Box }, - /// Tangent to a face (cylinder, cone, sphere, torus) where the point `at` lies over it. - Tangent { face: Box, at: Vec3 }, + /// Tangent to a face (cylinder, cone, sphere, torus) where the point `at` lies over it. With + /// a `reference` (a plane or planar face), it touches where the face turns towards the + /// reference instead, turned by `angle` about the face's axis, on the side of `at` (#8822). + Tangent { + face: Box, + at: Vec3, + #[serde(default, skip_serializing_if = "Option::is_none")] + reference: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + angle: Option, + }, /// Square to an edge or sketch curve, a fraction `t` (expression, 0…1) of the way along it. AlongPath { path: Box, t: Expr }, /// Through a straight edge (or line, axis) and square to a plane (or planar face). @@ -1275,9 +1284,10 @@ pub enum FeatureKind { body: Option, }, /// A perforation field (#732): round holes of `diameter` on a staggered (60°) or square grid of `pitch` over the - /// whole flat sheet, kept `margin` (default: the diameter) clear of its edges, cut-outs and bend zones. Stored like - /// a cosmetic thread: the holes go to the flat pattern, the DXF and the measured volume, not into the B-rep, so a - /// panel can carry tens of thousands of them. + /// whole flat sheet, or inside the closed profiles of `sketch` when it is given, kept `margin` (default: the + /// diameter) clear of its edges, cut-outs, bend zones and the outline. Stored like a cosmetic thread: the holes go + /// to the flat pattern, the DXF and the measured volume, not into the B-rep, so a panel can carry tens of thousands + /// of them. SheetPerforate { #[walk(length = "Diameter")] diameter: Expr, @@ -1290,6 +1300,13 @@ pub enum FeatureKind { pattern: Option, #[serde(default, skip_serializing_if = "Option::is_none")] body: Option, + /// The field's outline: a sketch on a face of the sheet. None: the whole sheet. + #[serde(default, skip_serializing_if = "Option::is_none")] + sketch: Option, + /// Which of the outline sketch's profiles bound the field. None: all of them. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[walk(profiles_of = sketch)] + profiles: Option, }, /// Fold a sheet along a line on its base face: a sketch line (followed when the sketch /// changes), else the points `a`, `b`. @@ -2339,7 +2356,11 @@ pub enum PatternKind { reversed2: bool, }, Circular { - origin: Position, + /// A point on the axis the copies turn about: numbers, or length expressions it follows + /// as the parameters change (#10852). + #[serde(with = "point_expr")] + #[walk(placement)] + origin: PointExpr, axis: Dir, #[walk(unitless = "Quantity")] count: Expr, diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index f48c619b1..4b62ed175 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -45,6 +45,11 @@ pub struct ModelBody { joint_faces: Arc>, /// Lazy canonical reference triangles for a proper rigid occurrence placement. mesh_placement: Option>, + /// For a mirrored copy: its faces as a world state shows them, a rigid move of the source's + /// [`placed_mesh::OppositeHand`]. Display only: the model reads the copy's own triangles. + mirrored_mesh: Option>, + /// The first mirrored copy made of this body, shared by its clones. + opposite_hand: Arc>, /// The display plan (none when the body has no plan: a mesh body, or one the planner /// refuses), shared like the mesh. A GPU viewport draws it. plan: Arc<[OnceLock>>; 4]>, @@ -94,6 +99,8 @@ impl ModelBody { mesh: Arc::new(OnceLock::new()), joint_faces: Arc::new(OnceLock::new()), mesh_placement: None, + mirrored_mesh: None, + opposite_hand: Arc::new(OnceLock::new()), plan: Arc::new(Default::default()), plan_mesh: Arc::new(Default::default()), key: 0, @@ -744,6 +751,7 @@ impl ModelState { && let Some(lines) = olds.first().and_then(|x| x.body.split_lines()) { b.body = b.body.clone().with_split_lines(Some(lines.clone())); + b.mirrored_mesh = None; } // An imported look outlives the operations on the body. if b.body.paint().is_none() @@ -1606,6 +1614,8 @@ fn hash_placement(m: &Mat, h: &mut impl Hasher) { fn mirror_placements_digest(doc: &Document, f: &Feature, placements: &[Vec], bodies: &[crate::BodyName]) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); doc.component_transform(f.component).iter().flatten().for_each(|x| x.to_bits().hash(&mut h)); + // A feature added after the mirror that builds on its copies needs them made for that. + placement_reuse::copies_only_shown(doc, f).hash(&mut h); for placed in placements.iter().map(|path| mirror_copy_frame(doc, path)) { placed.is_some().hash(&mut h); if let Some((component, frame, picked)) = placed { @@ -2248,6 +2258,16 @@ impl Model { _ => mats, }; next.stamp(doc, &state, f, key, mats); + // Evaluated again only for what came before it (a mirror moved by a drag). + if let Some(old) = self.results.get(i).filter(|old| old.id == f.id) { + let made = old.state.bodies.iter().filter(|b| b.feature == f.id).map(|b| (b.name.as_str(), b)); + let made: std::collections::HashMap<&str, &ModelBody> = made.collect(); + for b in next.bodies.iter_mut().filter(|b| b.feature == f.id) { + if let Some(old) = made.get(b.name.as_str()) { + b.keep_meshes_of(old); + } + } + } for b in &mut next.bodies { if !b.transferred { b.component = match doc.body_components.get(&b.name) { @@ -3059,10 +3079,29 @@ fn apply_traced_with( let affected: std::collections::BTreeMap = target_idx.iter().filter_map(|i| state.bodies.get(*i)).map(|b| (b.name.clone(), b.body.lumps().map_or(1, |l| l.len()))).collect(); let mut remove = Vec::new(); + // A cut hands a body its tools cannot reach back as it was, but only after a whole + // boolean: in a design of many bodies that was most of a hole's time (#10225). Such a + // body is left as it is. Its box and the tools' are their meshes' grown past how far + // the exact faces can curve out from them (a dome rises above the outline of its + // edges), so a tool that touches a body, or only comes near it, still meets it in the + // boolean. A body shown in another frame, and a mesh body, are cut as before; an + // intersect removes the bodies it misses, and is left as it was. + let reach: Option>> = + (op == Operation::Cut && !tools.iter().any(|t| t.body.is_mesh())).then(|| tools.iter().map(|t| more::body_box(&t.body)).collect()); for &ti in &target_idx { let Some(mut acc) = state.bodies.get(ti).map(|b| Some(b.traced())) else { continue }; // The tools meet the target where it is shown: in its frame (#3383). let into = state.bodies.get(ti).and_then(|b| tool_frame(&b.name)); + if let (Some(reach), None, Some(mb)) = (&reach, into, state.bodies.get(ti)) + && !reach.is_empty() + && !mb.body.is_mesh() + && let Some(target) = more::mesh_box(mb) + && reach.iter().all(|tool| more::boxes_apart(&Some(target), tool)) + { + continue; + } + #[cfg(test)] + cost_tests::count(|c| c.cut += 1); for t in &tools { let t = &tool_in(t, into)?; acc = match acc { @@ -3440,8 +3479,9 @@ fn body_at(st: &ModelState, body: &Option, points: &[Vec3]) -> /// A hole stays on its face when the model changes: a position now inside a body moves back /// against the drilling direction to the surface, one now above it moves down onto it. Only the -/// bodies in `scope` count (every body when it is empty, see [`hole_scope`]). -fn hole_on_surface(st: &ModelState, p: Vec3, dir: Vec3, scope: &[String]) -> Vec3 { +/// bodies in `scope` count (every body when it is empty, see [`hole_scope`]). Edit Hole seeds from +/// this point so the dialog's face pick matches where evaluation drills (#10689). +pub fn hole_on_surface(st: &ModelState, p: Vec3, dir: Vec3, scope: &[String]) -> Vec3 { let size = st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max); let eps = size * 1e-6; let mut best: Option = None; @@ -4923,7 +4963,26 @@ fn feature_tools_with_constructor( let (mut lo, mut hi) = if a <= b { (a, b) } else { (b, a) }; // To a curved (or slanted) face: run right through the target body, then keep what // lies before its surface (the tool less the body, the piece at the start). - let curved = curved_face(&tst, to_face, Some(n)); + let mut curved = curved_face(&tst, to_face, Some(n)); + // A Cut to the far side of a curved wall (a window through a duct's side): ending the + // tool on that face leaves it lying in the wall's face, where the boolean fails, and + // the tool less the body keeps only the air before the wall, which cuts nothing. Where + // the target's material ends at the face under the whole profile, the tool ends flat + // in the gap beyond it instead: it takes what lies before the face and meets no face. + if *operation == Operation::Cut + && off == 0.0 + && let (Some(bi), Some((_, fi))) = (curved, to_face) + && let Some(tb) = tst.bodies.get(bi) + && let Some(end) = cut_end_past_face(tb, fi, &ss.plane, ®ions, if hi > 0.0 { 1.0 } else { -1.0 }) + && (if hi > 0.0 { end > lo } else { end < hi }) + { + if hi > 0.0 { + hi = end; + } else { + lo = end; + } + curved = None; + } if let Some(bi) = curved && let Some(tb) = tst.bodies.get(bi) { @@ -5873,11 +5932,19 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model } } crate::PatternKind::Circular { origin, axis, count: c, angle, alignment, reversed, axis_ref, axis_feature } => { - // On an edge or round face: about it as it is now; on a construction axis: where it is. + // On an edge or round face: about it as it is now; on a construction axis: where it is; + // else through its origin, whose expressions follow the parameters (#10852). let (origin, axis) = match (axis_ref, axis_feature) { (Some(g), _) => crate::construct::model_axis(&*construction_state(doc, st, component)?, g)?, (None, Some(name)) => construction_axis_in(Some(doc), st, name, component)?, - (None, None) => (origin.0, axis.0), + (None, None) => { + let [x, y, z] = origin; + let o = Vec3::new(val(vals, x, Kind::Length)?, val(vals, y, Kind::Length)?, val(vals, z, Kind::Length)?); + if ![o.x, o.y, o.z].iter().all(|c| c.is_finite() && c.abs() < 1e9) { + return Err(DocError::Invalid("the pattern's axis origin is out of range".into())); + } + (o, axis.0) + } }; let n = count(c)?; let total = val(vals, angle, Kind::Angle)?; @@ -5952,6 +6019,35 @@ fn path_at(segs: &[kernel::PathSeg], d: f64) -> (Vec3, Vec3) { } /// Whether a copy has no material to cut in any of its eligible targets. +/// The bodies a hole cuts: those its feature names, else its component's and its own (as +/// `apply_traced` picks a cut's targets). +fn hole_targets<'a>(st: &'a ModelState, f: &Feature) -> Vec<&'a ModelBody> { + let all = f.participants.len() == 1 && f.participants.first().is_some_and(|t| t == "*"); + st.bodies + .iter() + .filter(|b| all || if f.participants.is_empty() { b.component == f.component || b.feature == f.id } else { f.participants.contains(&b.name) }) + .collect() +} + +/// Whether hole tool `tool` is clear of every body the hole cuts, by their boxes (#10701). Boxes +/// only: a probe boolean for every hole of a large hole pattern would double its work, and the +/// bodies' meshes are there already (the hole found its face on them). A body of another +/// component is in another frame: the hole is then not known to miss. +fn hole_misses(st: &ModelState, f: &Feature, tool: &Body) -> bool { + let targets = hole_targets(st, f); + let bounds = tool.outline_bounds(); + if targets.is_empty() + || targets.iter().any(|b| b.component != f.component) + || bounds.is_empty() + || !bounds.min.is_finite() + || !bounds.max.is_finite() + { + return false; + } + let tool_box = Some(bounds.inflated(1e-6)); + targets.iter().all(|b| more::boxes_apart(&tool_box, &more::mesh_box(b))) +} + fn copy_misses(st: &ModelState, f: &Feature, targets: &[String], tools: &[Traced]) -> bool { let targets = if targets.is_empty() { &f.participants } else { targets }; let all = targets.len() == 1 && targets.first().is_some_and(|t| t == "*"); @@ -6454,6 +6550,74 @@ fn trim_to_body(tools: Vec, target: &ModelBody, dist_to_start: impl Fn(V Ok(out) } +/// For a Cut To the curved face `fi` of `target`: the height above `plane` (along its normal) at +/// which a flat-ended tool over `regions`, travelling along `travel` × the normal (±1), stops in +/// the gap beyond that face. Rays over the profiles must each cross the face ahead of the profile, +/// with material just before the first such crossing and none just after; the end is halfway across the narrowest gap to the next +/// material (at most the usual run past a curved target). `None` when that does not hold. +fn cut_end_past_face(target: &ModelBody, fi: usize, plane: &Plane, regions: &[Region2], travel: f64) -> Option { + let m = target.mesh(); + let n = plane.normal(); + let dir = n * travel; + let size = target.body.size(); + let eps = (size * 1e-4).max(1e-6); + let margin = size * 0.05 + 1.0; + // Sample points: the outline of each profile and a grid over its inside. + let mut samples: Vec = Vec::new(); + for r in regions { + let ring: Vec = r.outer.polyline(1e-2).into_iter().collect(); + let step = (ring.len() / 64).max(1); + samples.extend(ring.iter().step_by(step).copied()); + let (mut lo, mut hi) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)); + for q in &ring { + lo = Vec2::new(lo.x.min(q.x), lo.y.min(q.y)); + hi = Vec2::new(hi.x.max(q.x), hi.y.max(q.y)); + } + for i in 0..12 { + for j in 0..12 { + let q = Vec2::new(lo.x + (hi.x - lo.x) * (i as f64 + 0.5) / 12.0, lo.y + (hi.y - lo.y) * (j as f64 + 0.5) / 12.0); + if r.contains(q) { + samples.push(q); + } + } + } + } + let height = |q: Vec3| (q - plane.origin).dot(n); + let reach = size * 4.0 + 1.0; + let (mut face_end, mut gap_end) = (f64::MIN, f64::MAX); + for q2 in samples { + let q = plane.to_world(q2); + // Every crossing of the line through `q`, in travel order, from well before the body. + let back = travel * height(q) + reach + size; + let mut o = q - dir * back; + let mut hits: Vec<(f64, usize)> = Vec::new(); + while let Some((t, tri)) = m.raycast(o, dir) { + let at = o + dir * t; + hits.push((travel * height(at), *m.tri_face.get(tri)? as usize)); + o = at + dir * eps; + if hits.len() > 256 { + return None; + } + } + // The first crossing of the face ahead of the profile: an exact kernel's whole cylinder is + // one face, which a line through it crosses twice. + let k = (0..hits.len()).filter(|&k| hits[k].1 == fi && hits[k].0 > -eps).min_by(|a, b| hits[*a].0.total_cmp(&hits[*b].0))?; + let e = hits[k].0; + let at = |t: f64| plane.origin + n * (travel * t) + (q - plane.origin - n * height(q)); + if !m.contains(at(e - eps * 10.0)) || m.contains(at(e + eps * 10.0)) { + return None; + } + face_end = face_end.max(e); + let next = hits.iter().map(|h| h.0).filter(|&t| t > e + eps * 10.0).fold(f64::MAX, f64::min); + gap_end = gap_end.min(next); + } + if face_end == f64::MIN || gap_end - face_end < eps * 100.0 { + return None; + } + let end = face_end + ((gap_end - face_end) * 0.5).min(margin); + Some(travel * end) +} + /// One point on each face of a body (a triangle centre, so it lies on the face). fn face_samples(b: &ModelBody) -> Vec { let m = b.mesh(); @@ -6797,7 +6961,23 @@ fn eval_feature( let handled = sheet_hole_cut(st, f, &tools, warning)?; let tools: Vec = tools.into_iter().map(|(tool, _)| tool).collect(); if handled.is_empty() { + // A hole moved off the material (a changed position, parameter or sketch point) + // cuts nothing: it says so, as a pattern does of its copies (#10701). + let missed = tools.iter().filter(|tool| hole_misses(st, f, &tool.body)).count(); + let total = tools.len(); + let targets: Vec = hole_targets(st, f).iter().map(|b| b.name.clone()).collect(); apply_traced(doc, st, f, tools, Operation::Cut, &[])?; + match (missed, total) { + (0, _) => {} + (_, 1) => append_warning(warning, "the hole removes no material".into()), + _ => append_warning(warning, format!("{missed} of {total} holes remove no material")), + } + // A hole wider than the part takes all of it away (#10702): almost never what a + // hole means, so it says which bodies are gone. + let gone: Vec<&str> = targets.iter().map(String::as_str).filter(|n| st.body(n).is_none()).collect(); + if !gone.is_empty() { + append_warning(warning, format!("the hole removes all of {}", gone.join(", "))); + } } else { apply_beside_sheet_cut(doc, st, f, tools, Operation::Cut, &[], &handled)?; } @@ -6946,25 +7126,38 @@ fn eval_feature( // Picks on bodies of other (moved) components are where those bodies are shown. None => doc.resolve_plane_in(vals, plane, 0, Some(&*construction_state(doc, st, f.component)?))?, }; - st.construct.push(crate::construct::Construct { feature: f.id, name: f.name.clone(), geom: crate::construct::ConstructGeom::Plane(pl) }); + st.construct.push(crate::construct::Construct { + feature: f.id, + name: f.name.clone(), + geom: crate::construct::ConstructGeom::Plane(pl), + bodies: Vec::new(), + }); Ok(()) } FeatureKind::ConstructionAxis { def } => { - let (origin, dir) = - crate::construct::resolve_axis(&crate::construct::Ctx { doc, vals, st: &*construction_state(doc, st, f.component)?, depth: 0 }, def)?; + let cst = construction_state(doc, st, f.component)?; + let ctx = crate::construct::Ctx { doc, vals, st: &cst, depth: 0 }; + let (origin, dir) = crate::construct::resolve_axis(&ctx, def)?; + let bodies = crate::construct::source_bodies(&ctx, &def.refs()); st.construct.push(crate::construct::Construct { feature: f.id, name: f.name.clone(), geom: crate::construct::ConstructGeom::Axis { origin, dir }, + bodies, }); Ok(()) } FeatureKind::ConstructionPoint { def } => { - let p = crate::construct::resolve_point( - &crate::construct::Ctx { doc, vals, st: &*construction_state(doc, st, f.component)?, depth: 0 }, - def, - )?; - st.construct.push(crate::construct::Construct { feature: f.id, name: f.name.clone(), geom: crate::construct::ConstructGeom::Point(p) }); + let cst = construction_state(doc, st, f.component)?; + let ctx = crate::construct::Ctx { doc, vals, st: &cst, depth: 0 }; + let p = crate::construct::resolve_point(&ctx, def)?; + let bodies = crate::construct::source_bodies(&ctx, &def.refs()); + st.construct.push(crate::construct::Construct { + feature: f.id, + name: f.name.clone(), + geom: crate::construct::ConstructGeom::Point(p), + bodies, + }); Ok(()) } FeatureKind::BoundaryFill { tools, cells, operation, remove_tools } => { @@ -7137,6 +7330,9 @@ fn eval_feature( } let m = mirror_matrix(&pl); let mut output = 0; + // Copies evaluated on each frame a placement is dragged, which nothing cuts or joins: + // searching their revolved faces again was nearly all that took. + let shown_only = !*combine && !placements.is_empty() && placement_reuse::copies_only_shown(doc, f); for (k, n) in bodies.iter().enumerate() { let i = st.bodies.iter().position(|b| &b.name == n).ok_or_else(|| DocError::Unknown(format!("body `{n}`")))?; let Some(mb) = st.bodies.get(i).cloned() else { continue }; @@ -7153,7 +7349,12 @@ fn eval_feature( } None => (None, m, m), }; - let mirrored = moved_copy(&mb, kernel::transform_matrix(&mb.body, if *combine { own } else { copy })?, 1); + let copied = if shown_only { + kernel::place_matrix(&mb.body, copy) + } else { + kernel::transform_matrix(&mb.body, if *combine { own } else { copy }) + }; + let mirrored = moved_copy(&mb, copied?, 1); if *combine { let joined = kernel::boolean(&mb.body, &mirrored.body, BoolOp::Union)? .ok_or_else(|| DocError::Invalid("the mirror join produced nothing".into()))?; @@ -7175,6 +7376,9 @@ fn eval_feature( let name = copy_body_name(st, f, output, &mb.name); copy_sheet(st, &mb.name, &name, ©); let mut body = ModelBody::traced_new(name, mirrored, f.id); + if !placements.is_empty() { + body.mirrored_mesh = placed_mesh::PlacedMesh::mirrored(&mb, &body.body, ©).map(Arc::new); + } if let Some(c) = component.filter(|c| *c != f.component) { // Kept in that component as a moved body is (and through later features). body.component = c; @@ -7454,6 +7658,9 @@ fn eval_feature( *slot = ModelBody::traced_new(mb.name.clone(), Traced::step(nb, &[&mb.traced()]), mb.feature); } } + if !*copy { + move_constructions_with(doc, st, bodies, &crate::rigid(t, Vec3::ZERO, axis, ang)); + } Ok(()) } FeatureKind::MeshConvert { body, tolerance } => { @@ -7614,6 +7821,36 @@ fn construction_state<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> Resu state_in_frame(doc, st, comp) } +/// Construction axes and points built on bodies a Move moves go with them (#10127): an axis +/// through a cylinder turns with the cylinder, as its faces do. Only those built from the moved +/// bodies alone (`Construct::bodies`) follow; one also held by a fixed point, a plane or another +/// body stays. `m` is the move in the bodies' own frame; each construction is kept in its +/// component's frame (`construction_state`), so the move is carried over into that frame. +fn move_constructions_with(doc: &Document, st: &mut ModelState, moved: &[crate::BodyName], m: &Mat) { + let frame_of = |feature: u64| { + let comp = doc.feature(feature).map(|f| f.component).unwrap_or(0); + if comp == 0 && !doc.occurrences.is_empty() { crate::IDENTITY } else { doc.component_transform(comp) } + }; + let world: BTreeMap<&str, Mat> = + st.bodies.iter().filter(|b| moved.iter().any(|n| *n == b.name)).map(|b| (b.name.as_str(), body_world(doc, b))).collect(); + let mut placed = Vec::new(); + for (k, c) in st.construct.iter().enumerate() { + let Some(body) = c.bodies.first().and_then(|b| world.get(b.as_str())) else { continue }; + if !c.bodies.iter().all(|b| world.contains_key(b.as_str())) { + continue; + } + let frame = frame_of(c.feature); + let (Some(body_inv), Some(frame_inv)) = (crate::mat_inverse(body), crate::mat_inverse(&frame)) else { continue }; + let in_frame = crate::mat_mul(&crate::mat_mul(&frame_inv, body), &crate::mat_mul(m, &crate::mat_mul(&body_inv, &frame))); + placed.push((k, c.geom.placed(&in_frame))); + } + for (k, geom) in placed { + if let Some(c) = st.construct.get_mut(k) { + c.geom = geom; + } + } +} + /// Whether `plane` is given by the origin planes and numbers alone. fn plane_is_fixed(plane: &PlaneRef) -> bool { match plane { @@ -7906,7 +8143,8 @@ impl PlacedBodies { if let Some(placed) = self.taken(b, m, &name) { return Ok(placed); } - let body = kernel::place_matrix(&b.body, *m).map_err(|e| DocError::Invalid(format!("body `{}` cannot be placed: {e}", b.name)))?; + let body = if crate::is_identity(m) { Ok(b.body.clone()) } else { kernel::place_matrix(&b.body, *m) }; + let body = body.map_err(|e| DocError::Invalid(format!("body `{}` cannot be placed: {e}", b.name)))?; let mut fresh = ModelBody::new(name, body, b.feature); fresh.mesh_placement = placed_mesh::PlacedMesh::new(b, m).map(Arc::new); Ok(fresh) @@ -8008,6 +8246,12 @@ fn placed_key(b: &ModelBody, m: &crate::Mat) -> (usize, [u64; 16]) { (Arc::as_ptr(&b.mesh) as usize, bits) } +/// Whether a world state shows `b`, placed by `m`, apart from the model's body. A mirrored copy +/// always is: it is drawn from its source's opposite hand, and the model keeps its own triangles. +fn placed_apart(b: &ModelBody, m: &crate::Mat) -> bool { + !crate::is_identity(m) || b.mirrored_mesh.is_some() +} + /// [`world_state`], reusing the bodies `placed` holds from an earlier call and leaving it holding /// this call's. pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut PlacedBodies) -> Result { @@ -8062,7 +8306,7 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut for (comp, path, m) in &placements { for b in bodies_of(*comp) { let bm = body_matrix(b, m); - if !crate::is_identity(&bm) { + if placed_apart(b, &bm) { jobs.push((b, bm, names.name(&b.name, *comp, path))); } } @@ -8083,7 +8327,7 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut let bm = body_matrix(b, &m); // Identical geometry also shares its display mesh cell with the definition. // A changed placement keeps a distinct mesh, at that placement's coordinates. - let mut placed = if crate::is_identity(&bm) { + let mut placed = if !placed_apart(b, &bm) { let mut placed = b.clone(); placed.name = names.name(&b.name, comp, &path); placed diff --git a/crates/doc/src/eval_cost_tests.rs b/crates/doc/src/eval_cost_tests.rs index a6cd5c9a0..12a9442a7 100644 --- a/crates/doc/src/eval_cost_tests.rs +++ b/crates/doc/src/eval_cost_tests.rs @@ -16,7 +16,8 @@ use crate::eval::{PlacementReads, body_world, hash_placement, placement_digest}; use crate::*; /// Work counted on this thread: bodies moved, STEP texts digested, joint faces and bodies -/// measured, bodies searched for by name, features searched for by id. +/// measured, bodies searched for by name, features searched for by id, bodies a cut (or +/// intersect) ran its booleans on, and bodies searched for the cylinder a tap marking lies on. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub(super) struct Counts { pub moved: usize, @@ -25,11 +26,23 @@ pub(super) struct Counts { pub measures: usize, pub body_searches: usize, pub feature_searches: usize, + pub cut: usize, + pub cylinder_search: usize, } thread_local! { - static COUNTS: Cell = - const { Cell::new(Counts { moved: 0, digested: 0, joint_faces: 0, measures: 0, body_searches: 0, feature_searches: 0 }) }; + static COUNTS: Cell = const { + Cell::new(Counts { + moved: 0, + digested: 0, + joint_faces: 0, + measures: 0, + body_searches: 0, + feature_searches: 0, + cut: 0, + cylinder_search: 0, + }) + }; } pub(super) fn count(f: impl FnOnce(&mut Counts)) { @@ -1085,3 +1098,268 @@ fn a_placed_tap_follows_its_body_offset() { apply_point(&mat_mul(&doc.component_transform(comp), &rigid(Vec3::new(0.0, 0.0, 7.0), Vec3::ZERO, Vec3::Z, 0.0)), Vec3::new(1.0, 1.0, 0.0)); assert!(tap.axis_point.dist(expected) < 1e-9, "{:?} {expected:?}", tap.axis_point); } + +/// What adding a feature of `kind` at the end of `doc` did to the bodies already there: how many +/// its cut ran booleans on, and which it left exactly as they were (the same geometry, its name, +/// key and face names carried over). A cut that cannot reach a body hands it back as it was, and +/// must not pay a whole boolean to find that out (#10225); the sheet metal hole (#10226) and the +/// cosmetic thread (#10227) check their own shortcuts with it too. +pub(super) struct CutWork { + pub cut: usize, + pub kept: Vec, + pub model: Model, +} + +pub(super) fn cut_work(doc: &mut Document, kind: FeatureKind) -> CutWork { + let mut model = Model::new(); + model.evaluate(doc); + let id = doc.add_feature(kind, None).unwrap(); + let work = counted(|| model.evaluate(doc)); + let result = model.result(id).unwrap(); + assert_eq!(result.error, None, "the feature builds"); + let before = model.state_before(id); + let kept = result + .state + .bodies + .iter() + .filter(|b| { + before + .body(&b.name) + .is_some_and(|old| old.body.same(&b.body) && old.key == b.key && crate::naming::face_names(old) == crate::naming::face_names(b)) + }) + .map(|b| b.name.clone()) + .collect(); + CutWork { cut: work.cut, kept, model } +} + +/// A box body named `name`, `size` long on each side from `corner`. +fn block(doc: &mut Document, name: &str, corner: Vec3, size: [f64; 3]) { + let id = doc + .add_feature( + FeatureKind::Box { + corner: point_expr(corner), + length: size[0].to_string().into(), + width: size[1].to_string().into(), + height: size[2].to_string().into(), + operation: Operation::NewBody, + }, + None, + ) + .unwrap(); + doc.feature_mut(id).unwrap().body_names = vec![name.into()]; +} + +/// A cylinder that cuts, standing on `base` along Z. +fn cutter(base: Vec3, radius: f64, height: f64) -> FeatureKind { + FeatureKind::Cylinder { + base: point_expr(base), + axis: Dir(Vec3::Z), + radius: radius.to_string().into(), + height: height.to_string().into(), + operation: Operation::Cut, + references: Vec::new(), + } +} + +/// A cut leaves the bodies its tool cannot reach as they were, without a boolean on each: in a +/// design of many bodies those booleans were most of a hole's time (#10225). +#[test] +fn a_cut_leaves_bodies_it_cannot_reach_as_they_were() { + let mut doc = Document::new("far"); + block(&mut doc, "Near", Vec3::ZERO, [50.0, 40.0, 30.0]); + // 0.5 mm clear of the tool, and far off. + block(&mut doc, "Beside", Vec3::new(13.5, 0.0, 0.0), [20.0, 40.0, 30.0]); + for i in 0..5 { + block(&mut doc, &format!("Far{i}"), Vec3::new(200.0 * (i + 1) as f64, 0.0, 0.0), [50.0, 40.0, 30.0]); + } + // Near and Beside overlap; the hole goes through Near only, beside Beside. + let work = cut_work(&mut doc, cutter(Vec3::new(10.0, 20.0, -5.0), 3.0, 40.0)); + assert_eq!(work.cut, 1, "only the body the tool reaches goes through the boolean"); + assert_eq!(work.kept, ["Beside", "Far0", "Far1", "Far2", "Far3", "Far4"]); + assert!(volume(&work.model, "Near") < 60_000.0 - 800.0, "and it is cut"); +} + +/// A cut still goes through the boolean wherever its tool reaches a body or comes close: on a +/// face, along a line, a hair beside it, into a dome above its edge circle. (Bodies its tool +/// cannot reach are left out of it: `a_cut_leaves_bodies_it_cannot_reach_as_they_were`.) +#[test] +fn a_cut_still_runs_where_its_tool_touches_grazes_or_meets_a_curved_face() { + // A cylinder whose side is tangent to the face x = 50, one a hair clear of it, one 0.1 mm in. + for (x, cuts) in [(53.0, false), (53.0005, false), (52.9, true)] { + let mut doc = Document::new("graze"); + block(&mut doc, "A", Vec3::ZERO, [50.0, 40.0, 30.0]); + let work = cut_work(&mut doc, cutter(Vec3::new(x, 20.0, 0.0), 3.0, 30.0)); + assert_eq!(work.cut, 1, "the tool at x = {x} goes through the boolean"); + let v = volume(&work.model, "A"); + assert_eq!(v < 60_000.0 - 1.0, cuts, "the tool at x = {x} cuts material: {v}"); + assert!(!cuts || work.kept.is_empty(), "a body cut is a new body"); + } + // A box meeting the block only along its top edge. + let mut doc = Document::new("edge"); + block(&mut doc, "A", Vec3::ZERO, [50.0, 40.0, 30.0]); + let along = FeatureKind::Box { + corner: point_expr(Vec3::new(50.0, 0.0, 30.0)), + length: "10".into(), + width: "40".into(), + height: "10".into(), + operation: Operation::Cut, + }; + assert_eq!(cut_work(&mut doc, along).cut, 1); + // A dome: a sphere's cap rising 10 mm above the circle it stands on. A thin tool drilled into + // its top near the apex, well above that circle, cuts it. + let mut doc = Document::new("dome"); + doc.add_feature(FeatureKind::Sphere { center: point_expr(Vec3::new(0.0, 0.0, -10.0)), radius: "20".into(), operation: Operation::NewBody }, None) + .unwrap(); + let below = FeatureKind::Box { + corner: point_expr(Vec3::new(-30.0, -30.0, -40.0)), + length: "60".into(), + width: "60".into(), + height: "40".into(), + operation: Operation::Cut, + }; + doc.add_feature(below, None).unwrap(); + let mut model = Model::new(); + model.evaluate(&doc); + let dome = model.state().bodies[0].name.clone(); + let whole = volume(&model, &dome); + let work = cut_work(&mut doc, cutter(Vec3::new(2.0, 1.0, 8.0), 1.0, 5.0)); + assert_eq!(work.cut, 1); + assert!(volume(&work.model, &dome) < whole - 1.0, "the drill cuts into the dome"); + assert!(work.kept.is_empty()); +} + +/// A cylinder body named `name` standing on `base` along Z. +fn shaft(doc: &mut Document, name: &str, base: Vec3, radius: f64, height: f64) { + let id = doc + .add_feature( + FeatureKind::Cylinder { + base: point_expr(base), + axis: Dir(Vec3::Z), + radius: radius.to_string().into(), + height: height.to_string().into(), + operation: Operation::NewBody, + references: Vec::new(), + }, + None, + ) + .unwrap(); + doc.feature_mut(id).unwrap().body_names = vec![name.into()]; +} + +/// The work of adding `kind` at the end of `doc`, and the tap markings the design then has. +fn marking_work(doc: &mut Document, kind: FeatureKind) -> (Counts, Vec) { + let mut model = Model::new(); + model.evaluate(doc); + let id = doc.add_feature(kind, None).unwrap(); + let work = counted(|| model.evaluate(doc)); + assert_eq!(model.result(id).unwrap().error, None, "the feature builds"); + (work, model.state().threads.clone()) +} + +/// A cosmetic tap marking at `p`. +fn marking(p: Vec3) -> FeatureKind { + FeatureKind::Thread { + face: FacePick(p), + designation: Some("M6".into()), + length: None, + modeled: false, + from: None, + up_to: None, + form: Default::default(), + hand: Default::default(), + starts: 1, + ease_out: None, + tip: Default::default(), + chamfer_angle: None, + chamfer_depth: None, + steep_flank: Default::default(), + } +} + +/// A tap marking looks for its cylinder in the bodies near it only: each body searched was +/// tessellated again, so many markings in a design of many bodies took quadratic time (#10227). +#[test] +fn a_tap_marking_searches_only_the_bodies_near_it() { + let mut doc = Document::new("far"); + shaft(&mut doc, "Shaft", Vec3::ZERO, 3.0, 6.0); + for i in 0..5 { + block(&mut doc, &format!("Far{i}"), Vec3::new(200.0 * (i + 1) as f64, 0.0, 0.0), [50.0, 40.0, 30.0]); + } + let (work, threads) = marking_work(&mut doc, marking(Vec3::new(3.0, 0.0, 3.0))); + assert_eq!(work.cylinder_search, 1, "only the shaft is searched"); + assert_eq!(threads.len(), 1); + assert_eq!(threads[0].body, "Shaft"); + assert_eq!(threads[0].designation, "M6"); + assert!((threads[0].radius - 3.0).abs() < 1e-6 && !threads[0].internal); + + // A tapped hole in a plate among far bodies: only the plate is searched for its wall. + let mut doc = Document::new("tapped"); + block(&mut doc, "Plate", Vec3::ZERO, [60.0, 60.0, 12.0]); + for i in 0..5 { + block(&mut doc, &format!("Far{i}"), Vec3::new(200.0 * (i + 1) as f64, 0.0, 0.0), [50.0, 40.0, 30.0]); + } + let hole = FeatureKind::Hole { + position: FacePick(Vec3::new(30.0, 30.0, 12.0)), + at: None, + direction: Dir(-Vec3::Z), + diameter: "5".into(), + depth: Some("10".into()), + hole: HoleKind::default(), + points: None, + thread: Some("M6".into()), + thread_depth: None, + hand: Default::default(), + modeled: false, + ease_out: None, + to: None, + references: Vec::new(), + }; + let (work, threads) = marking_work(&mut doc, hole); + assert_eq!(work.cylinder_search, 1, "only the plate is searched"); + assert_eq!(threads.len(), 1); + assert_eq!(threads[0].body, "Plate"); + assert!(threads[0].internal && (threads[0].radius - 2.5).abs() < 1e-6); +} + +/// Bodies within reach of a tap marking are still searched: the shaft it lies on, a block 3 mm +/// off (within a twentieth of the block's size, where the cylinder search itself looks), and one +/// 3.6 mm off (just past it, but within the margin the boxes keep); a block 4.5 mm off is not. +/// The marking stays on the shaft. +#[test] +fn a_tap_marking_still_searches_the_bodies_within_its_reach() { + let mut doc = Document::new("near"); + shaft(&mut doc, "Shaft", Vec3::ZERO, 3.0, 6.0); + // Each block is 50 x 40 x 30 (a twentieth of its size is 3.54 mm), its face x = 3 + gap. + for (name, gap) in [("Close", 3.0), ("Edge", 3.6), ("Clear", 4.5)] { + block(&mut doc, name, Vec3::new(3.0 + gap, -20.0, 0.0), [50.0, 40.0, 30.0]); + } + let (work, threads) = marking_work(&mut doc, marking(Vec3::new(3.0, 0.0, 3.0))); + assert_eq!(work.cylinder_search, 3, "the shaft, Close and Edge are searched"); + assert_eq!(threads.len(), 1); + assert_eq!(threads[0].body, "Shaft"); + + // A pin in a hole a hair wider: a marking on the pin, and one on the hole's wall. + for (p, body, internal) in [(Vec3::new(2.0, 0.0, 5.0), "Pin", false), (Vec3::new(2.5, 0.0, 5.0), "Plate", true)] { + let mut doc = Document::new("pin"); + block(&mut doc, "Plate", Vec3::new(-20.0, -20.0, 0.0), [40.0, 40.0, 10.0]); + let bore = FeatureKind::Cylinder { + base: point_expr(Vec3::new(0.0, 0.0, -1.0)), + axis: Dir(Vec3::Z), + radius: "2.5".into(), + height: "12".into(), + operation: Operation::Cut, + references: Vec::new(), + }; + doc.add_feature(bore, None).unwrap(); + shaft(&mut doc, "Pin", Vec3::ZERO, 2.0, 10.0); + let mut kind = marking(p); + if let FeatureKind::Thread { designation, .. } = &mut kind { + *designation = None; + } + let (work, threads) = marking_work(&mut doc, kind); + assert_eq!(work.cylinder_search, 2, "both bodies are searched for {body}"); + assert_eq!(threads.len(), 1); + assert_eq!(threads[0].body, body); + assert_eq!(threads[0].internal, internal); + } +} diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs index 079778e9d..e4e04f223 100644 --- a/crates/doc/src/eval_more.rs +++ b/crates/doc/src/eval_more.rs @@ -672,7 +672,7 @@ pub(super) fn sheet_eval( tag_flanges(sh, n0, f.id); rebuild_sheet(st, i) } - FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body } => { + FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body, sketch, profiles } => { // Without a body name the field goes on the newest sheet, as the command's own body lookup does. let i = match body { Some(_) => sheet_for(st, body, None)?, @@ -694,8 +694,18 @@ pub(super) fn sheet_eval( "perforation needs diameter > 0, pitch > diameter and margin >= 0 (diameter {d}, pitch {pitch}, margin {margin})" ))); } + // The outline sketch's profiles, where they lie on the sheet now. + let outline = match sketch { + Some(sk) => { + let ss = st.sketch(sk.0).ok_or_else(|| DocError::Unknown(format!("sketch {sk}")))?; + let regions = select_profiles(ss, profiles.as_ref().unwrap_or(&ProfileSel::All))?; + let sh = st.sheets.get(i).ok_or_else(|| DocError::Invalid("sheet".into()))?; + Some(sh.perforation_outline(&ss.plane, ®ions)?) + } + None => None, + }; let sh = st.sheets.get_mut(i).ok_or_else(|| DocError::Invalid("sheet".into()))?; - sh.perforations.push(crate::sheet::SheetPerforation { feature: f.id, diameter: d, pitch, margin, square, from_right: false }); + sh.perforations.push(crate::sheet::SheetPerforation { feature: f.id, diameter: d, pitch, margin, square, from_right: false, outline }); Ok(()) } FeatureKind::SheetHem { edges, length, gap, flip, body } => { @@ -1047,15 +1057,17 @@ pub(super) fn sheet_primitive_cut( return Ok(Vec::new()); } // The first sheet the primitive meets decides the machining direction. Sheets clear of it - // by their boxes are passed over; the one sheet left needs no boolean to show it is met (that - // boolean came out empty against a sheet carrying a label's cut-outs, and the hole was then - // cut into the solid without a place in the flat pattern). - let tool_box = body_box(tool); - let near: Vec<&sheet::SheetBody> = st - .sheets - .iter() - .filter(|sh| sheet_eligible(f, st, &[], sh) && st.body(&sh.body).is_some_and(|mb| !boxes_apart(&mesh_box(mb), &tool_box))) - .collect(); + // by their exact boxes ([`kernel::apart`]) are passed over; the one sheet left needs no + // boolean to show it is met (that boolean came out empty against a sheet carrying a label's + // cut-outs, and the hole was then cut into the solid without a place in the flat pattern). + let mut near: Vec<&sheet::SheetBody> = Vec::new(); + for sh in st.sheets.iter().filter(|sh| sheet_eligible(f, st, &[], sh)) { + if let Some(mb) = st.body(&sh.body) + && !kernel::apart(&mb.body, tool)? + { + near.push(sh); + } + } let mut normal = None; for sh in &near { if let Some(mb) = st.body(&sh.body) @@ -1366,9 +1378,6 @@ fn sheet_prism_cut( } else { Vec::new() }; - // Boxes around the tools: a tool clear of a bend by its box needs no boolean to show it (a - // label's letters against every bend and flange of a tray). - let tool_boxes: Vec> = tools.iter().map(body_box).collect(); let mut plans = Vec::new(); let mut notes = Vec::new(); 'sheets: for original in &st.sheets { @@ -1388,12 +1397,10 @@ fn sheet_prism_cut( // is exact, and a cut that machines nothing there is checked against the solid after it. // (That boolean cost each label hundreds of milliseconds, and against a sheet already // carrying a label's cut-outs it came out empty: the next cut was dropped.) + // A tool clear of a bend by its exact box (a label's letters against every bend and + // flange of a tray) costs no intersection work: the boolean answers it from the boxes. for bends in sh.unmodeled_solids(plane)? { - let bends_box = body_box(&bends); - for (tool, tool_box) in tools.iter().zip(&tool_boxes) { - if boxes_apart(&bends_box, tool_box) { - continue; - } + for tool in tools { if kernel::boolean(&bends, tool, kernel::BoolOp::Intersect)?.is_some() { return Err(DocError::Invalid( "this machining intersects a folded bend or a nonparallel panel; unfold the sheet before machining that material".into(), @@ -1580,13 +1587,13 @@ fn sheet_prism_cut( /// A box around `body`, grown past its mesh's deflection from the exact faces (and a hair /// more): bodies whose boxes are apart do not meet. None when it can't be worked out. -fn body_box(body: &Body) -> Option { +pub(super) fn body_box(body: &Body) -> Option { let tol = (body.size() * 1e-3).max(1e-4); padded_box(&body.mesh(&solidcraft_kernel::MeshTolerance::chord(tol)).ok()?, tol) } /// [`body_box`] of a model body, from the mesh it keeps. -fn mesh_box(mb: &ModelBody) -> Option { +pub(super) fn mesh_box(mb: &ModelBody) -> Option { padded_box(&mb.mesh(), mb.display_tol()) } @@ -1595,8 +1602,25 @@ fn padded_box(mesh: &solidcraft_geom::Mesh, tol: f64) -> Option { (!b.is_empty() && b.min.is_finite() && b.max.is_finite()).then(|| b.inflated(2.0 * tol + 1e-6)) } +/// Whether [`kernel::cylinder_face_at`] is known to find no face of `mb` at `p`. It takes a +/// face only when its own mesh of the body comes within a twentieth of the body's size of the +/// point. That mesh lies in the body's box ([`mesh_box`]) give or take its own deflection, which +/// the reach allows for, so a box farther away than that holds no face for it. Working that out from the mesh the body keeps +/// spares a tessellation of every body in the design for each tap marking (#10227). A mesh +/// body, and a body whose box is unknown, are searched as before. +pub(super) fn beyond_cylinder_reach(mb: &ModelBody, p: Vec3) -> bool { + if mb.body.is_mesh() { + return false; + } + let Some(b) = mesh_box(mb) else { return false }; + let size = mb.body.size(); + let reach = size * 0.05 + 2.0 * (size * 1e-3).max(1e-3); + let off = (b.min - p).max(p - b.max).max(Vec3::ZERO); + off.len() > reach +} + /// Whether two boxes are known to be apart (an unknown box is never apart). -fn boxes_apart(a: &Option, b: &Option) -> bool { +pub(super) fn boxes_apart(a: &Option, b: &Option) -> bool { let (Some(a), Some(b)) = (a, b) else { return false }; a.max.x < b.min.x || b.max.x < a.min.x || a.max.y < b.min.y || b.max.y < a.min.y || a.max.z < b.min.z || b.max.z < a.min.z } diff --git a/crates/doc/src/eval_thread.rs b/crates/doc/src/eval_thread.rs index c9a24d9f2..4d0570a06 100644 --- a/crates/doc/src/eval_thread.rs +++ b/crates/doc/src/eval_thread.rs @@ -162,7 +162,12 @@ pub(super) fn thread_on(st: &ModelState, feature: u64, p: Vec3, ask: &ThreadAsk) .bodies .iter() .enumerate() - .filter_map(|(i, b)| kernel::cylinder_face_at(&b.body, p).map(|c| (i, c))) + .filter(|(_, b)| !more::beyond_cylinder_reach(b, p)) + .filter_map(|(i, b)| { + #[cfg(test)] + cost_tests::count(|c| c.cylinder_search += 1); + kernel::cylinder_face_at(&b.body, p).map(|c| (i, c)) + }) .min_by(|a, b| { let dist = |c: &kernel::CylinderFace| ((p - c.axis_point - c.axis * (p - c.axis_point).dot(c.axis)).len() - c.radius).abs(); dist(&a.1).total_cmp(&dist(&b.1)) diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rs index 0df50741a..c166586a6 100644 --- a/crates/doc/src/feature_walk_tests/fixtures.rs +++ b/crates/doc/src/feature_walk_tests/fixtures.rs @@ -148,7 +148,10 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> { ("sheet_hem", json!({"type": "sheet_hem", "edges": [o], "length": "hem.length", "gap": "hem.gap"})), ( "sheet_perforate", - json!({"type": "sheet_perforate", "diameter": "perforate.diameter", "pitch": "perforate.pitch", "margin": "perforate.margin"}), + json!({ + "type": "sheet_perforate", "diameter": "perforate.diameter", "pitch": "perforate.pitch", "margin": "perforate.margin", + "sketch": 1, "profiles": {"type": "all"} + }), ), ( "sheet_fold", diff --git a/crates/doc/src/feature_walk_tests/golden_exprs.txt b/crates/doc/src/feature_walk_tests/golden_exprs.txt index 0f39e2f3f..c940c102b 100644 --- a/crates/doc/src/feature_walk_tests/golden_exprs.txt +++ b/crates/doc/src/feature_walk_tests/golden_exprs.txt @@ -107,7 +107,7 @@ pattern_circular inputs: Quantity = circ.count (Unitless) Total angle = circ.angle (Angle) - expressions: circ.count, circ.angle + expressions: circ.count, circ.angle, 0, 0, 0 pattern_path inputs: Quantity = path.count (Unitless) diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txt index 55163f67f..1c41447e0 100644 --- a/crates/doc/src/feature_walk_tests/golden_geometry.txt +++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt @@ -47,6 +47,7 @@ pattern_rectangular moves: pattern.dir1[0], pattern.dir1[1], pattern.dir2[1], pattern.dir2[2] pattern_circular moves: pattern.axis[0], pattern.axis[2], pattern.origin[0], pattern.origin[1], pattern.origin[2] + placement: 0, 0, 0 pattern_path mirror moves: plane.axis_dir[0], plane.axis_dir[1], plane.axis_origin[0], plane.axis_origin[1], plane.axis_origin[2] @@ -133,6 +134,7 @@ sheet_flange sheet_hem moves: edges[0][0], edges[0][1], edges[0][2] sheet_perforate + profiles: 1 all sheet_fold moves: a[0], a[1], a[2], b[1], b[2], fixed[0], fixed[1], fixed[2] sheet_path diff --git a/crates/doc/src/feature_walk_tests/golden_refs.txt b/crates/doc/src/feature_walk_tests/golden_refs.txt index 9b27d0083..ca57f8315 100644 --- a/crates/doc/src/feature_walk_tests/golden_refs.txt +++ b/crates/doc/src/feature_walk_tests/golden_refs.txt @@ -143,6 +143,8 @@ sheet_flange sheet_hem remap_bodies: body sheet_perforate + sketches: [1] + remap_refs: sketch remap_bodies: body sheet_fold sketches: [7] diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index 020ecc1fa..bf996d17b 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -724,6 +724,13 @@ pub fn read(s: &str) -> Result { let mut grouped_features = std::collections::BTreeSet::new(); let joint_ids: std::collections::BTreeSet<_> = d.assembly.joints.iter().map(|joint| joint.id).collect(); let mut grouped_joints = std::collections::BTreeSet::new(); + // A folder entry naming a feature or joint the design doesn't have, or one a folder already + // holds, is dropped, and the design opens: folders only group the timeline, so nothing else + // is lost. Editing a feature inside a folder used to leave such entries (#9373). + for group in &mut d.timeline_groups { + group.joints.retain(|joint| joint_ids.contains(joint) && grouped_joints.insert(*joint)); + group.features.retain(|feature| feature_ids.contains(feature) && grouped_features.insert(*feature)); + } for group in &d.timeline_groups { if group.name.trim().is_empty() || group.name.len() > 128 || !group_ids.insert(group.id) { return Err(DocError::Invalid("damaged design: invalid timeline folder".into())); @@ -731,12 +738,6 @@ pub fn read(s: &str) -> Result { if group.parent.is_some_and(|parent| parent == group.id) { return Err(DocError::Invalid("damaged design: timeline folder cannot contain itself".into())); } - if group.joints.iter().any(|joint| !joint_ids.contains(joint) || !grouped_joints.insert(*joint)) { - return Err(DocError::Invalid("damaged design: invalid joint in a timeline folder".into())); - } - if group.features.iter().any(|feature| !feature_ids.contains(feature) || !grouped_features.insert(*feature)) { - return Err(DocError::Invalid("damaged design: invalid feature in a timeline folder".into())); - } } for group in &d.timeline_groups { if let Some(parent) = group.parent { diff --git a/crates/doc/src/format/pending/circular-pattern-origin-expressions.rs b/crates/doc/src/format/pending/circular-pattern-origin-expressions.rs new file mode 100644 index 000000000..7919fbe64 --- /dev/null +++ b/crates/doc/src/format/pending/circular-pattern-origin-expressions.rs @@ -0,0 +1,4 @@ +//! A circular pattern's axis `origin` can hold length expressions (strings) as well as numbers, +//! so a pattern about a parameter-driven point follows the parameter (#10852). An origin of +//! plain numbers is saved as before, and older designs need no transformation. The last release +//! refuses this newer format and asks for an update instead of failing to read the origin. diff --git a/crates/doc/src/format/pending/sheet-perforation-outline.rs b/crates/doc/src/format/pending/sheet-perforation-outline.rs new file mode 100644 index 000000000..423133a3b --- /dev/null +++ b/crates/doc/src/format/pending/sheet-perforation-outline.rs @@ -0,0 +1,4 @@ +//! A perforation field can be bounded by a sketch: a `sheet_perforate` feature saves an optional `sketch` and +//! `profiles` (its outline), and a sheet's perforation the outline in flat coordinates (`outline`). Holes go only +//! inside the outline. Older designs need no transformation: a field without an outline covers the whole sheet as +//! before. The last release refuses a design saved with this (the newer format number). diff --git a/crates/doc/src/format/pending/tangent-plane-reference.rs b/crates/doc/src/format/pending/tangent-plane-reference.rs new file mode 100644 index 000000000..5f8ce101b --- /dev/null +++ b/crates/doc/src/format/pending/tangent-plane-reference.rs @@ -0,0 +1,5 @@ +//! A tangent construction plane can save a `reference` (a plane or planar face) and an `angle` +//! (#8822): the plane touches the face where it turns towards the reference, turned by the angle +//! about the face's axis. An older design has neither, and its tangent planes touch where they +//! were picked, as before. The last release refuses a design that has them (it asks for an +//! update) instead of opening those planes at the picked point, away from their reference. diff --git a/crates/doc/src/format/pending/component-history-hidden.rs b/crates/doc/src/format/v47/component-history-hidden.rs similarity index 100% rename from crates/doc/src/format/pending/component-history-hidden.rs rename to crates/doc/src/format/v47/component-history-hidden.rs diff --git a/crates/doc/src/format/pending/face-anchor-placement.rs b/crates/doc/src/format/v47/face-anchor-placement.rs similarity index 100% rename from crates/doc/src/format/pending/face-anchor-placement.rs rename to crates/doc/src/format/v47/face-anchor-placement.rs diff --git a/crates/doc/src/format/pending/plane-axis-point.rs b/crates/doc/src/format/v47/plane-axis-point.rs similarity index 100% rename from crates/doc/src/format/pending/plane-axis-point.rs rename to crates/doc/src/format/v47/plane-axis-point.rs diff --git a/crates/doc/src/joints_relations.rs b/crates/doc/src/joints_relations.rs index cd3f5fe0f..c3c0f1a0c 100644 --- a/crates/doc/src/joints_relations.rs +++ b/crates/doc/src/joints_relations.rs @@ -16,14 +16,11 @@ const TURNS: [f64; 4] = [0.0, std::f64::consts::FRAC_PI_2, std::f64::consts::PI, /// Starts tried at most (angle values beyond the first three start at 0). const MAX_STARTS: usize = 64; -/// The values of relation `j` that move B least from where it is now: B's joint frame as it sits -/// in A's, met as nearly as the relation allows (its origin as near as it can be to where it is, -/// and its axes, each weighed as a point a part's size along it). `None` for a joint that is not a relation, or whose -/// origins can't be found. +/// The values of joint `j` that move B least from where it is now: B's joint frame as it sits +/// in A's, met as nearly as the joint allows (its origin as near as it can be to where it is, +/// and its axes, each weighed as a point a part's size along it). Used for relations and for +/// typed joints that close a loop. `None` when the origins or finite values can't be found. pub fn relation_values(doc: &Document, st: &ModelState, j: &Joint) -> Option> { - if !j.kind.is_relation() { - return None; - } let world = |occ: u64| if occ == 0 { IDENTITY } else { occurrence_world(doc, occ) }; let fa = mat_mul(&world(j.a.occurrence), &resolve_origin(doc, st, &j.a).ok()?); let fb = mat_mul(&world(j.b.occurrence), &resolve_origin(doc, st, &j.b).ok()?); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 6aee6b626..87c1bcb3f 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -90,9 +90,10 @@ pub use document::*; pub use eval::{ EdgeRef, FeatureResult, KeptSeparate, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo, blend_target, curve_pick_error, draft_corner_options, edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, - import_body_names, join_pieces_added, map_wire, metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices, revolve_extent, - revolve_extent_for_handle, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, state_in_frame, - state_in_frame_at, suggested_thread, suggested_thread_in, tangent_face_chain, through_all_distance, world_state, world_state_reusing, + hole_on_surface, import_body_names, join_pieces_added, map_wire, metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices, + revolve_extent, revolve_extent_for_handle, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, + state_in_frame, state_in_frame_at, suggested_thread, suggested_thread_in, tangent_face_chain, through_all_distance, world_state, + world_state_reusing, }; pub use eval::{EvalCache, KeptResults}; pub use expr::Expr; diff --git a/crates/doc/src/placed_mesh.rs b/crates/doc/src/placed_mesh.rs index c6d877c53..54eeb4132 100644 --- a/crates/doc/src/placed_mesh.rs +++ b/crates/doc/src/placed_mesh.rs @@ -16,23 +16,57 @@ pub(super) struct PlacedMesh { /// each placement draws them moved, so a part is planned once however often it is placed. plans: Arc<[OnceLock>>; 4]>, plan_meshes: Arc<[OnceLock>>; 4]>, + /// The definition's own opposite hand: a copy of a copy is a rigid move of that. + opposite_hand: Arc>, transform: crate::Mat, pub(super) tolerance: f64, } +/// A body's opposite hand: the first mirrored copy made of it, and the matrix that made it. A +/// reflection reverses each face's edge walk, so a copy can't be drawn from its source's triangles. +/// Two reflections do cancel, though: every later mirrored copy of the body, wherever dragging a +/// placement puts it, is a proper rigid move of this one, whose triangles are made once. +#[derive(Debug)] +pub(super) struct OppositeHand { + /// The body it mirrors, to tell a holder whose body was replaced. + source: Body, + definition: ModelBody, + matrix: crate::Mat, +} + impl PlacedMesh { + /// Where `copy` (`source` transformed by `matrix`) stands relative to `source`'s opposite + /// hand. `None` shows it from its own mesh: a matrix that isn't a reflection of the first. + /// A copy of a copy goes by what its source is drawn from, which outlives that source. + pub(super) fn mirrored(source: &ModelBody, copy: &Body, matrix: &crate::Mat) -> Option { + let (cell, body, matrix) = match source.mirrored_mesh.as_deref() { + Some(drawn) => (&drawn.opposite_hand, &drawn.body, crate::mat_mul(matrix, &drawn.transform)), + None => (&source.opposite_hand, &source.body, *matrix), + }; + let hand = cell.get_or_init(|| OppositeHand { + source: body.clone(), + definition: ModelBody::new(String::new(), copy.clone(), source.feature), + matrix, + }); + if !same_triangles(&hand.source, body) { + return None; + } + Self::new(&hand.definition, &crate::mat_mul(&matrix, &crate::mat_inverse(&hand.matrix)?)) + } + /// Share the original definition, never a chain of previously placed meshes. A source's /// OnceLock lives with its immutable geometry, so edits get a new source automatically. pub(super) fn new(source: &ModelBody, transform: &crate::Mat) -> Option { if !proper_rigid(transform) { return None; } - Some(match source.mesh_placement.as_deref() { + Some(match source.mesh_placement.as_deref().or(source.mirrored_mesh.as_deref()) { Some(original) => Self { body: original.body.clone(), mesh: original.mesh.clone(), plans: original.plans.clone(), plan_meshes: original.plan_meshes.clone(), + opposite_hand: original.opposite_hand.clone(), transform: crate::mat_mul(transform, &original.transform), tolerance: original.tolerance, }, @@ -41,6 +75,7 @@ impl PlacedMesh { mesh: source.mesh.clone(), plans: source.plan.clone(), plan_meshes: source.plan_mesh.clone(), + opposite_hand: source.opposite_hand.clone(), transform: *transform, tolerance: source.display_tol(), }, @@ -98,6 +133,29 @@ impl PlacedMesh { } } +/// Whether two bodies mesh to the same triangles: the same shape, split along the same lines. +fn same_triangles(a: &Body, b: &Body) -> bool { + a.same_shape(b) + && match (a.split_lines(), b.split_lines()) { + (Some(x), Some(y)) => Arc::ptr_eq(x, y), + (None, None) => true, + _ => false, + } +} + +impl ModelBody { + /// Keep the meshes `old` holds when this body is the same shape: a feature evaluated again + /// that gives the same solids (an import, from its shared file) doesn't mesh them again. + pub(super) fn keep_meshes_of(&mut self, old: &ModelBody) { + if same_triangles(&self.body, &old.body) { + self.mesh = old.mesh.clone(); + self.plan = old.plan.clone(); + self.plan_mesh = old.plan_mesh.clone(); + self.opposite_hand = old.opposite_hand.clone(); + } + } +} + /// The display plan of a definition `body` at quality `q`, made once in `cell`. pub(super) fn definition_plan( body: &Body, diff --git a/crates/doc/src/placement_reuse.rs b/crates/doc/src/placement_reuse.rs index 11ea1a394..4e3778b77 100644 --- a/crates/doc/src/placement_reuse.rs +++ b/crates/doc/src/placement_reuse.rs @@ -68,6 +68,21 @@ fn local_plane(plane: &PlaneRef, depth: usize) -> bool { } } +/// Whether no feature after the mirror `f` can cut, join or otherwise build on bodies: only +/// features that read none, and further mirrors, which copy them. A boolean depends on how a +/// copy's revolved faces are turned, so a copy it may reach is made with +/// [`solidcraft_kernel::transform_matrix`]; one that is only shown needs no search for that. It +/// depends on the design alone, so a design evaluates the same however it was reached. +pub(super) fn copies_only_shown(doc: &Document, f: &Feature) -> bool { + let mut later = doc.features.iter().skip_while(|g| g.id != f.id).skip(1); + let mut components = std::collections::HashMap::with_capacity(doc.features.len()); + for g in &doc.features { + components.entry(g.id).or_insert(g.component); + } + let copies = |g: &Feature| matches!(&g.kind, FeatureKind::Mirror { features, combine: false, .. } if features.is_empty()); + later.all(|g| copies(g) || local_geometry(g, &components)) +} + pub(super) fn local_geometry(f: &Feature, components: &std::collections::HashMap) -> bool { // Persistent picked-face/edge attachments can move an otherwise literal input. if !f.face_names.is_empty() || !f.edge_names.is_empty() || !f.edge_refs.is_empty() { diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs index 5165a5758..1dc0cab7f 100644 --- a/crates/doc/src/project.rs +++ b/crates/doc/src/project.rs @@ -228,7 +228,7 @@ fn resolve_uncached( let (ba, fa) = crate::project3d::part_of(st, a).ok_or_else(|| lost(&a.describe()))?; let (bb, fb) = crate::project3d::part_of(st, b).ok_or_else(|| lost(&b.describe()))?; let chord = (ba.body.size().max(bb.body.size()) * 1e-3).max(1e-3); - for e in crate::kernel::meeting_edges(&ba.body, fa, &bb.body, fb, chord)? { + for e in crate::kernel::meeting_edges(&ba.body, fa.as_deref(), &bb.body, fb.as_deref(), chord)? { wires.push(e.points); exact.push(vec![WireCurve { curve: e.curve, interval: e.interval }]); } diff --git a/crates/doc/src/project3d.rs b/crates/doc/src/project3d.rs index 6542c12fa..bc970dd63 100644 --- a/crates/doc/src/project3d.rs +++ b/crates/doc/src/project3d.rs @@ -6,15 +6,18 @@ use solidcraft_sketch::LinkSource; use crate::eval::ModelState; -/// The body of a body or face reference, and the face (its index in the body's face order) for a -/// face reference: the face nearest its point, on the named body or else the nearest body. -pub(crate) fn part_of<'a>(st: &'a ModelState, src: &LinkSource) -> Option<(&'a crate::ModelBody, Option)> { +/// The body of a body or face reference and, for a face reference, the faces (indices in the +/// body's face order) of the surface patch of the face nearest its point, on the named body or +/// else the nearest body: the B-rep pieces joined across hidden seams, as the viewport picks and +/// highlights it (#9009). +pub(crate) fn part_of<'a>(st: &'a ModelState, src: &LinkSource) -> Option<(&'a crate::ModelBody, Option>)> { match src { LinkSource::Body { body } => Some((st.body(body)?, None)), LinkSource::Face { body, at } => { let b = st.body(body).or_else(|| st.bodies.iter().min_by(|x, y| dist_to(&x.mesh(), *at).total_cmp(&dist_to(&y.mesh(), *at))))?; - let (f, _, _) = crate::project::nearest_face(&b.mesh(), *at)?; - Some((b, usize::try_from(f).ok())) + let m = b.mesh(); + let (f, _, _) = crate::project::nearest_face(&m, *at)?; + Some((b, Some(m.surface_patch(usize::try_from(f).ok()?)))) } _ => None, } @@ -24,8 +27,9 @@ fn dist_to(m: &Mesh, p: Vec3) -> f64 { crate::project::nearest_face(m, p).map(|x| x.2).unwrap_or(f64::INFINITY) } -fn tris(m: &Mesh, face: Option) -> Vec<[Vec3; 3]> { - m.triangles.iter().zip(&m.tri_face).filter(|(_, f)| face.is_none_or(|x| x == **f)).filter_map(|(t, _)| m.tri(t)).collect() +/// The triangles of the faces in `faces` (sorted ascending), or of the whole mesh for `None`. +fn tris(m: &Mesh, faces: Option<&[u32]>) -> Vec<[Vec3; 3]> { + m.triangles.iter().zip(&m.tri_face).filter(|(_, f)| faces.is_none_or(|fs| fs.binary_search(f).is_ok())).filter_map(|(t, _)| m.tri(t)).collect() } /// Ray–triangle hit parameter (Möller–Trumbore), any sign. @@ -54,7 +58,7 @@ fn ray_hit(o: Vec3, d: Vec3, t: &[Vec3; 3]) -> Option { /// miss the face split the result. pub(crate) fn onto_face(m: &Mesh, f: u32, pts: &[Vec3], dir: Vec3) -> Vec> { let Some(d) = dir.normalized() else { return Vec::new() }; - let ts = tris(m, Some(f)); + let ts = tris(m, Some(std::slice::from_ref(&f))); let size = m.bounds().diagonal().max(1e-9); // Resample so the projected curve follows the surface. let step = size / 200.0; diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index a01b7698f..780a6a076 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -538,6 +538,10 @@ pub struct SheetFlange { /// (flat coordinates, counter-clockwise). #[serde(default, skip_serializing_if = "Option::is_none")] pub exact: Option, + /// A fold's bend zone as drawn, when a curved edge of the sheet crosses it (flat coordinates, + /// counter-clockwise): `zone` is this instead of straight ends. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub zone_shape: Option, /// Which feature made it: `F.` (persistent edge names). #[serde(default, skip_serializing_if = "String::is_empty")] pub tag: String, @@ -697,6 +701,10 @@ pub struct SheetPerforation { /// copy, whose holes are the mirror image of its source's. #[serde(skip_serializing_if = "std::ops::Not::not")] pub from_right: bool, + /// The field's outline in flat coordinates (see [`SheetBody::perforation_outline`]): holes only inside these + /// regions, margin clear of their edges, on a grid that starts from their bounding box. None: the whole flat. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outline: Option>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -839,6 +847,205 @@ fn rect(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> Region2 { Region2 { outer: lp, holes: Vec::new() } } +/// How a fold's bend runs along its line `d`: where its start line starts and ends, how far its far +/// edge runs on past those ends, and which ends are cut askew (`SheetFlange::ext`, `tear`). +type FoldEnds = (f64, f64, (f64, f64), (bool, bool)); + +/// The ends of a fold's zone (`strip`, between the lines at `s0` and `s0 + ba` along `n`) when +/// straight edges of the sheet slant across it, so that it folds as a bend with torn ends. Every +/// corner must lie on one of the two lines: a curved edge has corners in between, and an S of the +/// same area as a straight end would pass on area alone. +fn slanted_zone(strip: &[Vec2], n: Vec2, d: Vec2, s0: f64, ba: f64) -> Option { + let on_line = |q: &Vec2, s: f64| (q.dot(n) - s).abs() <= ZONE_SQUARE_TOL; + if !strip.iter().all(|q| on_line(q, s0) || on_line(q, s0 + ba)) { + return None; + } + let span = |s: f64| { + let mut along = strip.iter().filter(|q| on_line(q, s)).map(|q| q.dot(d)); + let first = along.next()?; + Some(along.fold((first, first), |(lo, hi), u| (lo.min(u), hi.max(u)))) + }; + let ((a0, a1), (e0, e1)) = (span(s0)?, span(s0 + ba)?); + let (start, far) = (a1 - a0, e1 - e0); + let trapezoid = (start + far) / 2.0 * ba; + if start <= ZONE_SQUARE_TOL + || far <= ZONE_SQUARE_TOL + || (trapezoid - signed_area(strip).abs()).abs() > 1e-6 * start.max(far).max(1.0) * ba.max(1.0) + { + return None; + } + let end = |on: f64| if on.abs() > ZONE_SQUARE_TOL { (on, true) } else { (0.0, false) }; + let ((on0, torn0), (on1, torn1)) = (end(a0 - e0), end(e1 - a1)); + Some((a0, a1, (on0, on1), (torn0, torn1))) +} + +/// A turn sharper than this (its sine) between two edges of an outline is a corner. Smooth curves +/// and their chords turn less: a chord at the sheet's 0.001 mm tolerance turns about 5° on a 1 mm +/// radius. +const CORNER_TURN: f64 = 0.17; + +/// Where two edges of an outline meet at a corner. +fn outline_corners(outline: &Loop2) -> Vec { + let segs = &outline.segs; + let mut corners = Vec::new(); + for (i, next) in segs.iter().enumerate() { + let Some(prev) = segs.get((i + segs.len() - 1) % segs.len()) else { continue }; + let (t0, t1) = (prev.end_tangent(), next.start_tangent()); + if t0.cross(t1).abs() > CORNER_TURN || t0.dot(t1) < 0.0 { + corners.push(next.start()); + } + } + corners +} + +/// `seg` in pieces, cut where it crosses the line `level` along `n`, into `out`. A curve that only +/// touches the line stays whole. +fn cut_at_level(seg: &Seg2, n: Vec2, level: f64, out: &mut Vec) { + const SAMPLES: usize = 64; + const MAX_CROSSINGS: usize = 16; + const ON_LINE: f64 = 1e-9; + let off = |s: &Seg2, t: f64| s.point_at(t).dot(n) - level; + let mut rest = *seg; + for _ in 0..MAX_CROSSINGS { + // The first change of side, skipping samples on the line itself. + let (mut last, mut crossing) = (None::<(f64, f64)>, None); + for k in 0..=SAMPLES { + let t = k as f64 / SAMPLES as f64; + let v = off(&rest, t); + if v.abs() <= ON_LINE { + continue; + } + match last { + Some((was, before)) if before * v < 0.0 => { + crossing = Some((was, t, before)); + break; + } + _ => last = Some((t, v)), + } + } + let Some((mut lo, mut hi, before)) = crossing else { break }; + // On the distance itself: the cut lands on the line, and what's left starts on it. + for _ in 0..60 { + let mid = (lo + hi) / 2.0; + if off(&rest, mid) * before > 0.0 { + lo = mid; + } else { + hi = mid; + } + } + let (first, second) = rest.split_at((lo + hi) / 2.0); + out.push(first); + rest = second; + } + out.push(rest); +} + +/// A panel's outline cut exactly across a fold whose zone a curved edge crosses, each piece +/// keeping its exact curves. +#[derive(Clone, Debug, PartialEq)] +struct CurvedFold { + fixed: Loop2, + zone: Loop2, + moving: Loop2, + ends: FoldEnds, +} + +/// `outline` cut into the side short of the zone between the lines at `s0` and `s0 + ba` along `n`, +/// the zone, and the side past it. It must run from one side through the zone to the other and +/// back through the zone, once: a notch, several tabs on the line or a zone that reaches the +/// outline's tip is `None`. Both of the zone's ends count as torn: their edges aren't square across. +fn curved_fold(outline: &Loop2, n: Vec2, d: Vec2, s0: f64, ba: f64) -> Option { + const ON_LINE: f64 = 1e-6; + if outline.segs.len() > MAX_FLAT_POINTS { + return None; + } + let outline = outline.ccw(); + let mut pieces = Vec::new(); + for seg in &outline.segs { + let mut near = Vec::new(); + cut_at_level(seg, n, s0, &mut near); + for piece in &near { + cut_at_level(piece, n, s0 + ba, &mut pieces); + } + } + // The band each piece lies in: 0 short of the zone, 1 in it, 2 past it. A piece along either + // line is an edge square across the bend, not one crossing it. + let mut bands = Vec::with_capacity(pieces.len()); + for piece in &pieces { + let v = piece.mid().dot(n); + if !v.is_finite() || (v - s0).abs() <= ON_LINE || (v - s0 - ba).abs() <= ON_LINE { + return None; + } + bands.push(if v < s0 { + 0 + } else if v > s0 + ba { + 2 + } else { + 1 + }); + } + // Round the outline from where it enters the side short of the zone. + let count = pieces.len(); + let first = (0..count).find(|&i| bands.get(i) == Some(&0) && bands.get((i + count - 1) % count) != Some(&0))?; + let mut runs: Vec<(i32, Vec)> = Vec::new(); + for k in 0..count { + let i = (first + k) % count; + let (band, piece) = (*bands.get(i)?, *pieces.get(i)?); + match runs.last_mut() { + Some((b, run)) if *b == band => run.push(piece), + _ => runs.push((band, vec![piece])), + } + } + let [(0, near), (1, there), (2, far), (1, back)] = runs.as_slice() else { return None }; + let ends_of = |run: &[Seg2]| Some((run.first()?.start(), run.last()?.end())); + let ((near0, near1), (there0, there1), (far0, far1), (back0, back1)) = (ends_of(near)?, ends_of(there)?, ends_of(far)?, ends_of(back)?); + let on = |q: Vec2, s: f64| (q.dot(n) - s).abs() <= ON_LINE; + if !(on(near0, s0) && on(near1, s0) && on(far0, s0 + ba) && on(far1, s0 + ba)) { + return None; + } + let closed = |run: &[Seg2], to: Vec2, from: Vec2| { + let mut segs = run.to_vec(); + segs.push(Seg2::Line { a: to, b: from }); + segs + }; + let mut zone = closed(there, there1, back0); + zone.extend_from_slice(back); + zone.push(Seg2::Line { a: back1, b: there0 }); + let span = |p: Vec2, q: Vec2| (p.dot(d).min(q.dot(d)), p.dot(d).max(q.dot(d))); + let ((a0, a1), (e0, e1)) = (span(near0, near1), span(far0, far1)); + if a1 - a0 <= ON_LINE || e1 - e0 <= ON_LINE { + return None; + } + Some(CurvedFold { + fixed: Loop2 { segs: closed(near, near1, near0) }, + zone: Loop2 { segs: zone }, + moving: Loop2 { segs: closed(far, far1, far0) }, + ends: (a0, a1, (a0 - e0, e1 - a1), (true, true)), + }) +} + +/// Two counter-clockwise loops joined along a straight edge they share, running opposite ways: +/// every curve of both exactly as it was, which the planar booleans wouldn't hand back. +fn join_along_seam(a: &Loop2, b: &Loop2) -> Option { + const SAME: f64 = 1e-6; + if a.segs.len().saturating_mul(b.segs.len()) > MAX_FLAT_POINTS { + return None; + } + for (i, ea) in a.segs.iter().enumerate() { + let Seg2::Line { a: p, b: q } = *ea else { continue }; + for (j, eb) in b.segs.iter().enumerate() { + let Seg2::Line { a: r, b: s } = *eb else { continue }; + if p.dist(s) <= SAME && q.dist(r) <= SAME { + let mut segs = Vec::with_capacity(a.segs.len() + b.segs.len()); + segs.extend(a.segs.iter().skip(i + 1).chain(a.segs.iter().take(i)).cloned()); + segs.extend(b.segs.iter().skip(j + 1).chain(b.segs.iter().take(j)).cloned()); + return Some(Loop2 { segs }); + } + } + } + None +} + /// Round to a 1e-9 mm grid (keeps trimmed edges exactly where the kernel expects them). fn snap(v: Vec2) -> Vec2 { let r = |x: f64| (x * 1e9).round() / 1e9; @@ -1096,6 +1303,9 @@ impl SheetBody { /// Flat region of a flange's bend zone: square across the bend at both ends, but at a torn /// end its far edge ends where the panel's does. pub fn zone(&self, f: &SheetFlange) -> Region2 { + if let Some(lp) = &f.zone_shape { + return Region2 { outer: lp.ccw(), holes: Vec::new() }; + } let ba = self.allowance(f); let (u0, u1) = self.zone_span(f); let (a, b) = (f.p + f.d * u0, f.p + f.d * u1); @@ -1112,6 +1322,32 @@ impl SheetBody { (if f.tear.0 { -f.ext.0 } else { u0 }, if f.tear.1 { f.len + f.ext.1 } else { u1 }) } + /// How far a bend's zone reaches along the bend from `p`: a torn end runs askew, and a curved + /// edge may bulge past both of its ends. + pub(crate) fn zone_reach(&self, f: &SheetFlange) -> (f64, f64) { + if let Some(lp) = &f.zone_shape { + return lp.polyline(1e-3).iter().map(|q| (*q - f.p).dot(f.d)).fold((f64::MAX, f64::MIN), |(lo, hi), u| (lo.min(u), hi.max(u))); + } + let ((u0, u1), (e0, e1)) = (self.zone_span(f), self.zone_ends(f)); + (u0.min(e0), u1.max(e1)) + } + + /// Where a bend's centre line starts and ends, along the bend from `p`: between the middles + /// of the bend's two ends (a torn end is askew), or where a curved edge crosses it. + fn centre_line(&self, f: &SheetFlange) -> (f64, f64) { + if let Some(lp) = &f.zone_shape { + let mut at = Vec::new(); + for e in &lp.segs { + line_hits(f.p + f.n * (self.allowance(f) / 2.0), f.d, e, &mut at); + } + if let (Some(lo), Some(hi)) = (at.iter().copied().reduce(f64::min), at.iter().copied().reduce(f64::max)) { + return (lo, hi); + } + } + let ((u0, u1), (e0, e1)) = (self.zone_span(f), self.zone_ends(f)); + ((u0 + e0) / 2.0, (u1 + e1) / 2.0) + } + /// Folded (in the flat frame, as `fold`), the point of a bend's end (the one at `p`, or the /// other one when `at_end`) at the turn `phi` of the bend and the height `z` in the sheet. A /// torn end runs evenly along the bend while the bend turns, from its start line's end to @@ -1150,7 +1386,9 @@ impl SheetBody { if let Some(shape) = &f.shape && let Some((lo, hi)) = edge_span(shape, f.p + f.n * self.allowance(f)) { - return (span.0.max(lo), span.1.min(hi)); + // A torn end runs askew to where the panel's end starts, so the panel's root doesn't + // limit the bend there. + return (if f.tear.0 { span.0 } else { span.0.max(lo) }, if f.tear.1 { span.1 } else { span.1.min(hi) }); } span } @@ -1931,6 +2169,60 @@ impl SheetBody { Ok(regions) } + /// The sheet's panels and bend zones. Where a free-form edge crosses a fold, the zone and the + /// panels either side are already joined along their seams, so the edge stays the curve it + /// was drawn as: merged by the planar booleans it would come back as fitted arcs. A seam + /// another feature changed is left to them. + fn flat_pieces(&self) -> Result> { + let mut owners: Vec> = Vec::new(); + let mut slots: Vec> = Vec::new(); + for (pi, r) in self.panels() { + owners.push(pi); + slots.push(Some(planar_region(&r)?)); + } + let panel_slot = |pi: Option| owners.iter().position(|o| *o == pi); + let panels = slots.len(); + for f in &self.flanges { + slots.push(Some(planar_region(&self.zone(f))?)); + } + // Which slot now holds each: joined pieces live in the one they joined. + let mut held_by: Vec = (0..slots.len()).collect(); + let free_form = |slots: &[Option], at: usize| slots.get(at).and_then(Option::as_ref).is_some_and(|r| !r.outer.is_line_arc()); + for (i, f) in self.flanges.iter().enumerate() { + // A fold's pieces share whole seams; an edge flange's bend needn't span its edge. + if f.shape.is_none() { + continue; + } + let zone = panels + i; + let sides = [panel_slot(f.parent), panel_slot(Some(i))]; + if !free_form(&slots, zone) && !sides.iter().flatten().any(|&p| free_form(&slots, held_by.get(p).copied().unwrap_or(p))) { + continue; + } + for side in sides.into_iter().flatten() { + let at = |held_by: &[usize], k: usize| held_by.get(k).copied().unwrap_or(k); + let (a, b) = (at(&held_by, zone), at(&held_by, side)); + if a == b { + continue; + } + let (Some(Some(ra)), Some(Some(rb))) = (slots.get(a), slots.get(b)) else { continue }; + let Some(joined) = join_along_seam(&ra.outer, &rb.outer) else { continue }; + let holes = ra.holes.iter().chain(&rb.holes).cloned().collect(); + if let Some(slot) = slots.get_mut(a) { + *slot = Some(Region2 { outer: joined, holes }); + } + if let Some(slot) = slots.get_mut(b) { + *slot = None; + } + for k in &mut held_by { + if *k == b { + *k = a; + } + } + } + } + Ok(slots.into_iter().flatten().collect()) + } + pub(crate) fn flat_material(&self) -> Result> { let mut work = FlatWork::new(); // Merge structural pieces before cutting: clipping each panel first introduces @@ -1944,16 +2236,12 @@ impl SheetBody { } let mut regions = Vec::new(); let mut panel_points = 0usize; - for (_, r) in self.panels() { - let r = planar_region(&r)?; + for r in self.flat_pieces()? { panel_points = panel_points.saturating_add(region_complexity(std::slice::from_ref(&r))?.1); if panel_points > MAX_FLAT_POINTS { return Err(flat_budget_error()); } regions.push(r); - } - for f in &self.flanges { - regions.push(planar_region(&self.zone(f))?); region_complexity(®ions)?; } let regions = material_union(regions, &mut work)?; @@ -2085,9 +2373,7 @@ impl SheetBody { let mut out = Vec::new(); for (i, f) in self.flanges.iter().enumerate() { let ba = self.allowance(f); - // The centre line runs between the middles of the bend's two ends (a torn end is askew). - let ((u0, u1), (e0, e1)) = (self.zone_span(f), self.zone_ends(f)); - let (u0, u1) = ((u0 + e0) / 2.0, (u1 + e1) / 2.0); + let (u0, u1) = self.centre_line(f); let a = f.p + f.n * (ba / 2.0) + f.d * u0; for (s0, s1) in clear_of(a, f.d, u1 - u0, &cuts) { out.push(BendInfo { @@ -2110,9 +2396,45 @@ impl SheetBody { self.flanges.iter().map(|f| self.zone(f)).collect() } + /// A perforation field's outline (#732) in flat coordinates: closed regions of a sketch in `plane` (world). An + /// unfolded sheet takes them as drawn on the flat; a folded one through each panel whose material the plane lies + /// in, clipped to that panel, so an outline on one face never reaches a flange in the flat. Refused when the + /// plane lies in no panel. + pub fn perforation_outline(&self, plane: &Plane, regions: &[Region2]) -> Result> { + let on = |pi: Option| { + let w = self.world(pi); + let n = apply_vector(&w, Vec3::Z); + let z = (plane.origin - apply_point(&w, Vec3::ZERO)).dot(n); + n.cross(plane.normal()).len() < 1e-6 && (-LINEAR_TOL..=self.t + LINEAR_TOL).contains(&z) + }; + if self.flat { + if !on(None) { + return Err(DocError::Invalid("the perforation's outline sketch must lie on the flat sheet".into())); + } + return regions.iter().map(|r| self.region_to_flat(None, plane, r)).collect(); + } + let mut work = FlatWork::new(); + let mut out = Vec::new(); + let mut found = false; + for (pi, panel) in self.parallel_panels(plane) { + if !on(pi) { + continue; + } + found = true; + let mapped = regions.iter().map(|r| self.region_to_flat(pi, plane, r)).collect::>>()?; + out.extend(material_boolean(std::slice::from_ref(&panel), &mapped, kernel::BoolOp::Intersect, &mut work)?); + } + if !found { + return Err(DocError::Invalid("the perforation's outline sketch must lie on a face of the sheet".into())); + } + Ok(out) + } + /// Hole centres of a perforation field (#732), flat coordinates: a staggered (60°, odd rows shifted half a pitch) /// or square grid from the flat bounding box's lower-left corner plus margin + radius; a hole is kept where it is - /// at least margin clear of the material's edges and cut-outs and of every bend zone. + /// at least margin clear of the material's edges and cut-outs and of every bend zone. A field with an outline + /// keeps its holes inside the outline and margin clear of its edges too, on a grid from the lower-left corner of + /// the outline's bounding box (within the flat's). pub fn perforation_holes(&self, p: &SheetPerforation) -> Result> { let regions = self.flat_regions()?; let zones = self.bend_zones(); @@ -2133,6 +2455,20 @@ impl SheetBody { if !(lo.x <= hi.x) || !(p.pitch > 0.0) { return Ok(Vec::new()); } + // The rows and columns span the flat, or the outline's part of it; the bucket grid below stays the flat's. + let mut field = Aabb2 { min: lo, max: hi }; + if let Some(outline) = &p.outline { + let n = segs.len(); + for r in outline { + for l in std::iter::once(&r.outer).chain(&r.holes) { + segs.extend(l.polyline(1e-3).edges().map(|(&a, &b)| (a, b))); + } + } + field = field.intersection(&segs.get(n..).unwrap_or(&[]).iter().map(|(a, _)| *a).collect::()); + if !(field.min.x <= field.max.x && field.min.y <= field.max.y) { + return Ok(Vec::new()); + } + } // Segments bucketed in a grid, so each hole only checks the edges near it. let cell = (2.0 * clear).max(p.pitch).max(1.0); let (nx, ny) = (((hi.x - lo.x) / cell) as usize + 1, ((hi.y - lo.y) / cell) as usize + 1); @@ -2159,20 +2495,22 @@ impl SheetBody { let dy = if p.square { p.pitch } else { p.pitch * 3f64.sqrt() / 2.0 }; let mut out = Vec::new(); let mut row = 0usize; + let Aabb2 { min: flo, max: fhi } = field; loop { - let y = lo.y + clear + row as f64 * dy; - if y > hi.y - clear + 1e-9 { + let y = flo.y + clear + row as f64 * dy; + if y > fhi.y - clear + 1e-9 { break; } let shift = if !p.square && row % 2 == 1 { p.pitch / 2.0 } else { 0.0 }; // Steps across the row from its first hole; a mirrored field counts from the right. let mut step = 0.0; - while lo.x + clear + shift + step <= hi.x - clear + 1e-9 { - let x = if p.from_right { hi.x - clear - shift - step } else { lo.x + clear + shift + step }; + while flo.x + clear + shift + step <= fhi.x - clear + 1e-9 { + let x = if p.from_right { fhi.x - clear - shift - step } else { flo.x + clear + shift + step }; let c = Vec2::new(x, y); let (i, j) = idx(x, y); let near = grid.get(j * nx + i).map(Vec::as_slice).unwrap_or(&[]); if regions.iter().any(|r| r.contains(c)) + && p.outline.as_ref().is_none_or(|o| o.iter().any(|r| r.contains(c))) && !zones.iter().any(|z| z.contains(c)) && near.iter().all(|&k| segs.get(k).is_none_or(|&s| dist(c, s) >= clear - 1e-9)) { @@ -2446,10 +2784,8 @@ impl SheetBody { return Err(DocError::Invalid("not supported yet: a partial side-edge flange beside a cut-out".into())); } let clipped = if side || original.shape.is_some() || original.exact.is_some() { + // A panel with curves gives way to its 0.001 mm chords here. let region = self.panel(original); - if !region.outer.segs.iter().all(|s| matches!(s, Seg2::Line { .. })) { - return Err(DocError::Invalid("not supported yet: a flange setback on a curved flange panel".into())); - } let points = clip(®ion.outer.ccw().polyline(1e-3), a + inward * by, inward); if points.len() < 3 { return Err(DocError::Invalid("the flange's setback removes the whole panel".into())); @@ -2792,6 +3128,7 @@ impl SheetBody { leg: leg.max(0.0), shape: None, exact: None, + zone_shape: None, tag: String::new(), ext: (0.0, 0.0), slope: (0.0, 0.0), @@ -3690,6 +4027,7 @@ impl SheetBody { tear: (false, false), shape: None, exact: None, + zone_shape: None, tag: String::new(), }); Ok(self.flanges.len() - 1) @@ -3703,7 +4041,8 @@ impl SheetBody { /// flat). On the base the side holding `fixed` (default: the larger side) stays put; on a /// flange the side toward its own bend does. `flip` folds the other way. A `fixed` point that /// touches no material still picks the side it lies on, and sets `warning` (see - /// [`FOLD_FIXED_OFF_SHEET`]). + /// [`FOLD_FIXED_OFF_SHEET`]). The outline may cross the zone on straight slanted edges or on + /// any curve; a sharp corner in the zone is refused, by name. #[allow(clippy::too_many_arguments)] pub fn add_fold( &mut self, @@ -3758,11 +4097,12 @@ impl SheetBody { let pts = dedup(&r.outer.ccw().polyline(1e-3)); let (a2, b2) = (Vec2::new(fa.x, fa.y), Vec2::new(fb.x, fb.y)); if pts.contains((a2 + b2) * 0.5) || polys_cross(&pts, &[a2, b2, (a2 + b2) * 0.5]) { - found = Some((pi, inv, a2, b2, pts)); + found = Some((pi, inv, a2, b2, pts, r.outer)); break; } } - let (panel, inv, a2, b2, pts) = found.ok_or_else(|| DocError::Invalid("the fold line must lie on a flat face of the sheet".into()))?; + let (panel, inv, a2, b2, pts, outline) = + found.ok_or_else(|| DocError::Invalid("the fold line must lie on a flat face of the sheet".into()))?; let d = (b2 - a2).normalized().ok_or_else(|| DocError::Invalid("the fold line has no length".into()))?; let mut n = Vec2::new(-d.y, d.x); let l0 = a2.dot(n); @@ -3815,6 +4155,7 @@ impl SheetBody { tear: (false, false), shape: None, exact: None, + zone_shape: None, tag: String::new(), }; let ba = self.allowance(&probe); @@ -3845,26 +4186,46 @@ impl SheetBody { let angle = if flip { -angle } else { angle }; return self.fold_tabs(panel, &pts, (n, d), (s0, ba), span, (angle, radius), &strips); } - // The bend zone must be a rectangle across the panel (a slanted or curved edge would - // run across the bend as a helix, which the sheet's faces can't carry yet). + // The bend zone is a rectangle across the panel, or straight edges of the sheet slant + // across it, or curved ones do. Those ends fold to helices and curves, as torn ends and + // cut-outs across a bend do. let us: Vec = strip.iter().map(|q| q.dot(d)).collect(); let (u0, u1) = (us.iter().cloned().fold(f64::MAX, f64::min), us.iter().cloned().fold(f64::MIN, f64::max)); + let mut ends: FoldEnds = (u0, u1, (0.0, 0.0), (false, false)); + let mut zone_shape = None; + // An outline with curves is cut exactly, wherever the curves are, so they stay as drawn in + // the flat pattern; a cut that doesn't come out whole falls back on the chords. + let cut = if outline.segs.iter().all(|e| matches!(e, Seg2::Line { .. })) { None } else { curved_fold(&outline, n, d, s0, ba) }; if ((u1 - u0) * ba - signed_area(&strip).abs()).abs() > 1e-6 * (u1 - u0).max(1.0) * ba.max(1.0) { - // A corner of the outline inside the zone (e.g. a fold right at a tab's root): name - // it and how far the line has to move to clear it. - let corners: Vec<(Vec2, f64)> = pts.iter().map(|q| (*q, q.dot(n) - s0)).filter(|(_, s)| *s > 1e-6 && *s < ba - 1e-6).collect(); - if let Some(&(c, _)) = corners.first() { - let on = corners.iter().fold(0.0_f64, |m, (_, s)| m.max(*s)); - let back = corners.iter().fold(0.0_f64, |m, (_, s)| m.max(ba - *s)); - let w = apply_point(&self.world(panel), Vec3::new(c.x, c.y, self.t)); - return Err(DocError::Invalid(format!( - "the bend zone ({ba:.3} mm wide) reaches a corner of the sheet's outline at ({:.3}, {:.3}, {:.3}): \ - move the fold line at least {on:.3} mm toward the side that folds or {back:.3} mm toward the side that stays", - w.x, w.y, w.z - ))); + if let Some(slanted) = slanted_zone(&strip, n, d, s0, ba) { + ends = slanted; + } else { + // A corner of the outline inside the zone (e.g. a fold right at a tab's root): name + // it and how far the line has to move to clear it. + let corners: Vec<(Vec2, f64)> = + outline_corners(&outline).into_iter().map(|q| (q, q.dot(n) - s0)).filter(|(_, s)| *s > 1e-6 && *s < ba - 1e-6).collect(); + if let Some(&(c, _)) = corners.first() { + let on = corners.iter().fold(0.0_f64, |m, (_, s)| m.max(*s)); + let back = corners.iter().fold(0.0_f64, |m, (_, s)| m.max(ba - *s)); + let w = apply_point(&self.world(panel), Vec3::new(c.x, c.y, self.t)); + return Err(DocError::Invalid(format!( + "the bend zone ({ba:.3} mm wide) reaches a corner of the sheet's outline at ({:.3}, {:.3}, {:.3}): \ + move the fold line at least {on:.3} mm toward the side that folds or {back:.3} mm toward the side that stays", + w.x, w.y, w.z + ))); + } + let Some(curved) = &cut else { + return Err(DocError::Invalid("not supported yet: folds whose bend zone crosses a slanted or curved edge of the sheet".into())); + }; + ends = curved.ends; + zone_shape = Some(curved.zone.clone()); } - return Err(DocError::Invalid("not supported yet: folds whose bend zone crosses a slanted or curved edge of the sheet".into())); } + let (u0, u1, ext, tear) = ends; + let (fixed_exact, moving_exact) = match cut { + Some(cut) => (Some(cut.fixed), Some(cut.moving)), + None => (None, None), + }; let up = !flip; let leg = moving.iter().map(|q| q.dot(n) - s0 - ba).fold(0.0, f64::max); let p0 = n * s0 + d * u0; @@ -3875,11 +4236,14 @@ impl SheetBody { v.into_iter().map(snap).collect::>() }; match panel { - None => self.base = Region2 { outer: Loop2::polygon(&fixed_part).ccw(), holes: self.base.holes.clone() }, + None => { + self.base = + Region2 { outer: fixed_exact.clone().unwrap_or_else(|| Loop2::polygon(&fixed_part)).ccw(), holes: self.base.holes.clone() } + } Some(j) => { if let Some(f) = self.flanges.get_mut(j) { f.shape = Some(ccw(fixed_part.clone())); - f.exact = None; + f.exact = fixed_exact; } } } @@ -3892,11 +4256,12 @@ impl SheetBody { angle: if up { angle } else { -angle }, radius, leg, - ext: (0.0, 0.0), + ext, slope: (0.0, 0.0), - tear: (false, false), + tear, shape: Some(ccw(moving)), - exact: None, + exact: moving_exact, + zone_shape, tag: String::new(), }); let i = self.flanges.len() - 1; @@ -4041,6 +4406,7 @@ impl SheetBody { tear: (false, false), shape: Some(ccw(moving)), exact: None, + zone_shape: None, tag: String::new(), }); } @@ -4801,6 +5167,9 @@ impl SheetBody { if let Some(exact) = &mut f.exact { *exact = flip_x_loop(exact); } + if let Some(zone) = &mut f.zone_shape { + *zone = flip_x_loop(zone); + } } for r in self.holes.iter_mut().chain(self.labels.iter_mut()).chain(self.pockets.iter_mut().map(|p| &mut p.region)) { *r = flip_x_region(r); @@ -4811,6 +5180,9 @@ impl SheetBody { } for p in &mut self.perforations { p.from_right = !p.from_right; + for r in p.outline.iter_mut().flatten() { + *r = flip_x_region(r); + } } for (_, a, b) in &mut self.base_curves { (*a, *b) = (flip_x(*b), flip_x(*a)); @@ -4942,6 +5314,7 @@ pub fn contour_flange(body: &str, rule: &str, rv: &RuleValues, plane: &Plane, pt tear: (false, false), shape: None, exact: None, + zone_shape: None, tag: String::new(), }; let ba = sheet.allowance(&f); @@ -5623,6 +5996,145 @@ mod tests { } } + /// Any closed curve the sheet's outlines can hold: a circle, conics, cubics, and a mix. + fn curved_outlines() -> Vec<(&'static str, Loop2)> { + let w = std::f64::consts::FRAC_1_SQRT_2; + let v = |x: f64, y: f64| Vec2::new(x, y); + let conic = |a: Vec2, apex: Vec2, b: Vec2| Seg2::Conic { a, apex, b, w }; + let ellipse = vec![ + conic(v(80.0, 0.0), v(80.0, 40.0), v(0.0, 40.0)), + conic(v(0.0, 40.0), v(-80.0, 40.0), v(-80.0, 0.0)), + conic(v(-80.0, 0.0), v(-80.0, -40.0), v(0.0, -40.0)), + conic(v(0.0, -40.0), v(80.0, -40.0), v(80.0, 0.0)), + ]; + let cubic = |p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2| Seg2::Cubic { p0, p1, p2, p3 }; + // An uneven blob: its sides aren't symmetric about the fold or each other. + let spline = vec![ + cubic(v(70.0, -5.0), v(75.0, 30.0), v(30.0, 55.0), v(0.0, 40.0)), + cubic(v(0.0, 40.0), v(-30.0, 25.0), v(-90.0, 45.0), v(-85.0, 0.0)), + cubic(v(-85.0, 0.0), v(-80.0, -45.0), v(-20.0, -60.0), v(0.0, -35.0)), + cubic(v(0.0, -35.0), v(20.0, -10.0), v(65.0, -40.0), v(70.0, -5.0)), + ]; + // A D: a straight side the fold runs across, and an arc it also crosses. + let d_shape = vec![ + Seg2::Line { a: v(-50.0, -50.0), b: v(0.0, -50.0) }, + Seg2::Arc { center: v(0.0, 0.0), radius: 50.0, start: -std::f64::consts::FRAC_PI_2, sweep: std::f64::consts::PI }, + Seg2::Line { a: v(0.0, 50.0), b: v(-50.0, 50.0) }, + Seg2::Line { a: v(-50.0, 50.0), b: v(-50.0, -50.0) }, + ]; + vec![ + ("circle", Loop2::circle(v(0.0, 0.0), 50.0)), + ("ellipse", Loop2 { segs: ellipse }), + ("spline", Loop2 { segs: spline }), + ("D", Loop2 { segs: d_shape }), + ] + } + + #[test] + fn a_curved_outline_is_cut_exactly_across_a_fold_whatever_the_curve() { + let (n, d) = (Vec2::new(1.0, 0.0), Vec2::new(0.0, -1.0)); + for (name, lp) in curved_outlines() { + for (s0, ba) in [(-2.8, 5.6), (-30.0, 12.0), (10.0, 1.5)] { + let cut = curved_fold(&lp, n, d, s0, ba).unwrap_or_else(|| panic!("{name} at {s0}")); + // The pieces are the outline: nothing lost, nothing doubled, and all closed. + let area = |l: &Loop2| l.signed_area(); + let sum = area(&cut.fixed) + area(&cut.zone) + area(&cut.moving); + assert!((sum - lp.signed_area().abs()).abs() < 1e-6, "{name} at {s0}: {sum} vs {}", lp.signed_area()); + for piece in [&cut.fixed, &cut.zone, &cut.moving] { + assert!(piece.is_closed(1e-9) && piece.is_ccw(), "{name} at {s0}: {piece:?}"); + } + // Each lies wholly in its band, on the outline's own curves: sampled densely. + let band = |l: &Loop2, lo: f64, hi: f64| l.polyline(1e-3).iter().all(|q| q.dot(n) >= lo - 1e-6 && q.dot(n) <= hi + 1e-6); + assert!(band(&cut.fixed, f64::MIN, s0) && band(&cut.zone, s0, s0 + ba) && band(&cut.moving, s0 + ba, f64::MAX), "{name} at {s0}"); + // A curve is cut, not replaced by chords: the same kind of segment comes back. + let curves = |l: &Loop2| l.segs.iter().filter(|e| !matches!(e, Seg2::Line { .. })).count(); + assert!(curves(&cut.fixed) + curves(&cut.zone) + curves(&cut.moving) >= curves(&lp), "{name} at {s0}"); + assert!(cut.ends.3 == (true, true), "{name}: both ends are torn"); + } + } + } + + /// What keeps a flat pattern true: unrolling a bend keeps lengths on its neutral surface, so + /// a curved edge is as long folded as in the flat there, and only there. + #[test] + fn a_curved_edge_keeps_its_length_on_the_neutral_surface() { + for (name, lp) in curved_outlines() { + let mut s = plate(10.0, 10.0); + s.base = Region2 { outer: lp, holes: Vec::new() }; + let t = s.t; + let mut warning = None; + let (a, b) = (Vec3::new(5.0, -200.0, t), Vec3::new(5.0, 200.0, t)); + let i = + s.add_fold(a, b, std::f64::consts::FRAC_PI_2, 3.0, "centerline", false, None, &mut warning).unwrap_or_else(|e| panic!("{name}: {e}")); + let zone = s.flanges[i].zone_shape.clone().unwrap_or_else(|| panic!("{name}: no exact zone")); + let neutral = t - s.k * t; + let mut edges = 0; + for e in zone.segs.iter().filter(|e| !matches!(zone_edge_kind(&s.flanges[i], e), ZoneEdge::Along)) { + edges += 1; + const N: usize = 400; + let at = |k: usize| e.point_at(k as f64 / N as f64); + let flat: f64 = (0..N).map(|k| at(k).dist(at(k + 1))).sum(); + let folded = |z: f64| -> f64 { (0..N).map(|k| s.map3(Piece::Zone(i), at(k), z).dist(s.map3(Piece::Zone(i), at(k + 1), z))).sum() }; + assert!((folded(neutral) - flat).abs() < 1e-3, "{name}: {} folded vs {flat} flat", folded(neutral)); + // The test can tell: on the inside of the bend the edge is shorter. + assert!(flat - folded(t) > 0.05, "{name}: {} on the inside vs {flat} flat", folded(t)); + } + assert!(edges >= 2, "{name}: {zone:?}"); + } + } + + #[test] + fn a_fold_across_an_outline_that_doesnt_pass_through_once_is_refused() { + let (n, d) = (Vec2::new(1.0, 0.0), Vec2::new(0.0, -1.0)); + let v = |x: f64, y: f64| Vec2::new(x, y); + let circle = Loop2::circle(v(0.0, 0.0), 50.0); + // The zone reaches the tip: nothing lies past it, or short of it. + assert!(curved_fold(&circle, n, d, 49.0, 5.0).is_none()); + assert!(curved_fold(&circle, n, d, -54.0, 5.0).is_none()); + // Wholly off the sheet. + assert!(curved_fold(&circle, n, d, 60.0, 5.0).is_none()); + // Two tabs on the line: the outline crosses the zone four times. + let tabs = Loop2::polygon(&[ + v(-10.0, -30.0), + v(10.0, -30.0), + v(10.0, -5.0), + v(-10.0, -5.0), + v(-10.0, 5.0), + v(10.0, 5.0), + v(10.0, 30.0), + v(-10.0, 30.0), + v(-20.0, 30.0), + v(-20.0, -30.0), + ]); + assert!(curved_fold(&tabs, n, d, -2.0, 4.0).is_none()); + // An edge square across the bend, along the zone's line. + let along = Loop2::polygon(&[v(-10.0, -10.0), v(2.0, -10.0), v(2.0, 10.0), v(-10.0, 10.0)]); + assert!(curved_fold(&along, n, d, -2.0, 4.0).is_none()); + // Numbers that aren't. + assert!(curved_fold(&circle, n, d, f64::NAN, 5.0).is_none()); + assert!(curved_fold(&Loop2 { segs: Vec::new() }, n, d, 0.0, 5.0).is_none()); + } + + #[test] + fn a_fold_zone_with_straight_ends_is_told_from_a_curved_or_cornered_one() { + let (n, d) = (Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)); + let zone = |pts: &[(f64, f64)]| slanted_zone(&pts.iter().map(|&(x, y)| Vec2::new(x, y)).collect::>(), n, d, 0.0, 4.0); + // Narrowing, widening, leaning one way, and square at one end. + assert_eq!(zone(&[(0.0, 0.0), (4.0, 1.0), (4.0, 9.0), (0.0, 10.0)]), Some((0.0, 10.0, (-1.0, -1.0), (true, true)))); + assert_eq!(zone(&[(0.0, 1.0), (4.0, 0.0), (4.0, 10.0), (0.0, 9.0)]), Some((1.0, 9.0, (1.0, 1.0), (true, true)))); + assert_eq!(zone(&[(0.0, 0.0), (4.0, 2.0), (4.0, 12.0), (0.0, 10.0)]), Some((0.0, 10.0, (-2.0, 2.0), (true, true)))); + assert_eq!(zone(&[(0.0, 0.0), (4.0, 0.0), (4.0, 9.0), (0.0, 10.0)]), Some((0.0, 10.0, (0.0, -1.0), (false, true)))); + // An S across the zone encloses what the straight end would: its corners give it away. + assert_eq!(zone(&[(0.0, 0.0), (4.0, 1.0), (4.0, 9.0), (2.0, 10.0), (2.0, 9.0), (0.0, 10.0)]), None); + // A curved end, as a polyline. + assert_eq!(zone(&[(0.0, 0.0), (4.0, 0.0), (4.0, 9.0), (3.0, 9.8), (1.0, 9.8), (0.0, 9.0)]), None); + // Nothing to bend across: the zone comes to a point on either line, or isn't there. + assert_eq!(zone(&[(0.0, 0.0), (4.0, 5.0), (0.0, 10.0)]), None); + assert_eq!(zone(&[(0.0, 5.0), (4.0, 0.0), (4.0, 10.0)]), None); + assert_eq!(zone(&[]), None); + assert_eq!(zone(&[(f64::NAN, 0.0), (4.0, 0.0), (4.0, 10.0), (0.0, 10.0)]), None); + } + #[test] fn a_slanted_flat_edge_folds_to_its_exact_helix() { // A 72° flange, inside: the bend's axis runs along x through y = setback, z = T + R, diff --git a/crates/doc/src/sheet_convert.rs b/crates/doc/src/sheet_convert.rs index ba60eaa23..0cd53463d 100644 --- a/crates/doc/src/sheet_convert.rs +++ b/crates/doc/src/sheet_convert.rs @@ -1026,6 +1026,7 @@ pub fn convert_body( slope: (0.0, 0.0), shape: None, exact: None, + zone_shape: None, tag: String::new(), tear: (false, false), }); diff --git a/crates/doc/src/sheet_face_names.rs b/crates/doc/src/sheet_face_names.rs index 8d42e849c..c23149f15 100644 --- a/crates/doc/src/sheet_face_names.rs +++ b/crates/doc/src/sheet_face_names.rs @@ -89,8 +89,8 @@ impl SheetBody { let Some(inverse) = mat_inverse(&world) else { continue }; let q = apply_point(&inverse, p) - o; let u = q.dot(d); - let (u0, u1) = self.zone_span(f); - if u < u0 - tol || u > u1 + tol { + let (lo, hi) = self.zone_reach(f); + if u < lo - tol || u > hi + tol { continue; } let radial = q - d * u; diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 544986ad9..244d50363 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -602,6 +602,33 @@ fn feature_inserted_at_a_marker_inside_a_timeline_folder_joins_it() { assert!(Document::from_json(&doc.to_json()).is_ok(), "the inserted feature must leave a reopenable design"); } +/// #9373: a timeline folder that names a feature or joint the design doesn't have, or a feature +/// a folder already lists, no longer stops the design opening. Those entries are dropped and +/// everything else is kept. Editing a feature inside a folder used to save such entries. +#[test] +fn a_folder_naming_missing_or_repeated_features_still_opens() { + let mut doc = Document::new("stale folder entries"); + let sketch = || FeatureKind::Sketch { plane: PlaneRef::Origin { name: "XY".into() }, sketch: Sketch::new() }; + let a = doc.add_feature(sketch(), Some("A")).unwrap(); + let b = doc.add_feature(sketch(), Some("B")).unwrap(); + let c = doc.add_feature(sketch(), Some("C")).unwrap(); + let missing = doc.next_id + 10; + doc.timeline_groups.push(TimelineGroup { id: 100, name: "Repeats".into(), parent: None, features: vec![a, b, b], joints: vec![] }); + doc.timeline_groups.push(TimelineGroup { + id: 101, + name: "Stale".into(), + parent: None, + features: vec![b, c, missing, missing, missing], + joints: vec![missing, missing], + }); + let opened = Document::from_json(&doc.to_json()).expect("the design opens"); + assert_eq!(opened.features.iter().map(|f| f.id).collect::>(), vec![a, b, c]); + assert_eq!(opened.timeline_groups[0].features, vec![a, b], "listed once"); + assert_eq!(opened.timeline_groups[1].features, vec![c], "no missing feature, nor one the first folder holds"); + assert!(opened.timeline_groups[1].joints.is_empty()); + assert_eq!(opened.timeline_groups.iter().map(|g| g.name.as_str()).collect::>(), ["Repeats", "Stale"], "both folders are kept"); +} + /// A marker after the last feature leaves every feature active, as no marker does, so a feature /// added then is active too, not added rolled back (#7741: editing the last feature from the /// History runs its command with the marker there). diff --git a/crates/doc/src/walk.rs b/crates/doc/src/walk.rs index 981734078..4677bbcd1 100644 --- a/crates/doc/src/walk.rs +++ b/crates/doc/src/walk.rs @@ -340,6 +340,7 @@ impl Walk for PlaneRef { p = base; } PlaneRef::AlongPath { t, .. } => return f(("Distance (0 to 1)", t, Kind::Unitless, ExprRole::Input)), + PlaneRef::Tangent { angle: Some(angle), .. } => return f(("Angle", angle, Kind::Angle, ExprRole::Input)), // A plane seen from behind keeps its base's expressions (a sketch made with // `flip` on an offset plane did not follow the offset's parameter). PlaneRef::Flipped { base, .. } | PlaneRef::ThroughPoint { base, .. } => p = base, @@ -366,6 +367,7 @@ impl Walk for PlaneRef { p = base; } PlaneRef::AlongPath { t, .. } => return f(("Distance (0 to 1)", t, Kind::Unitless, ExprRole::Input)), + PlaneRef::Tangent { angle: Some(angle), .. } => return f(("Angle", angle, Kind::Angle, ExprRole::Input)), // A plane seen from behind keeps its base's expressions (a sketch made with // `flip` on an offset plane did not follow the offset's parameter). PlaneRef::Flipped { base, .. } | PlaneRef::ThroughPoint { base, .. } => p = base, @@ -420,7 +422,13 @@ impl PlaneRef { b.walk_feature_refs(f, depth + 1); c.walk_feature_refs(f, depth + 1); } - Self::Tangent { face, .. } | Self::AlongPath { path: face, .. } => face.walk_feature_refs(f, depth + 1), + Self::Tangent { face, reference, .. } => { + face.walk_feature_refs(f, depth + 1); + if let Some(r) = reference { + r.walk_feature_refs(f, depth + 1); + } + } + Self::AlongPath { path, .. } => path.walk_feature_refs(f, depth + 1), Self::Origin { .. } | Self::Custom { .. } | Self::Placed { .. } | Self::Face { .. } => {} } } @@ -451,7 +459,13 @@ impl PlaneRef { b.walk_feature_refs_mut(f, depth + 1); c.walk_feature_refs_mut(f, depth + 1); } - Self::Tangent { face, .. } | Self::AlongPath { path: face, .. } => face.walk_feature_refs_mut(f, depth + 1), + Self::Tangent { face, reference, .. } => { + face.walk_feature_refs_mut(f, depth + 1); + if let Some(r) = reference { + r.walk_feature_refs_mut(f, depth + 1); + } + } + Self::AlongPath { path, .. } => path.walk_feature_refs_mut(f, depth + 1), Self::Origin { .. } | Self::Custom { .. } | Self::Placed { .. } | Self::Face { .. } => {} } } diff --git a/crates/engine/src/cmd/construct.rs b/crates/engine/src/cmd/construct.rs index c6c14b89c..26c4b8354 100644 --- a/crates/engine/src/cmd/construct.rs +++ b/crates/engine/src/cmd/construct.rs @@ -141,7 +141,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("plane_tangent") .contract(&PLANE_TANGENT_CONTRACT) .output(output_schema_for::) - .params("face: ref (cylinder, cone, sphere or torus); at?: [x,y,z] where it touches (default: the face pick); name?"), + .params("face: ref (cylinder, cone, sphere or torus); at?: [x,y,z] where it touches (default: the face pick); reference?: plane or planar face ref (the plane touches where the face turns towards it: parallel to it, on the side of `at`); angle?: expr (with reference, default 0 deg: turned that far about the face's axis; not on a sphere); name?"), CommandSpec::new("construct.plane.along_path", "Plane Along Path", crate::checked!("construct.plane.along_path", plane_along)) .at("SOLID", "CONSTRUCT") .icon("plane_along_path") @@ -408,7 +408,20 @@ fn plane_tangent(s: &mut Session, p: &Value) -> Result { (None, GeoRef::Face { at, .. }) => *at, _ => return Err(bad(cmd, "`at` is required: where the plane touches the face")), }; - plane(s, p, PlaneRef::Tangent { face: Box::new(face), at }) + let reference = match p.get("reference").filter(|v| !v.is_null()) { + Some(_) => Some(Box::new(geo(s, p.get("reference"), cmd, "reference")?)), + None => None, + }; + let angle = match p.get("angle").filter(|v| !v.is_null()) { + Some(_) if reference.is_none() => return Err(bad(cmd, "`angle` turns the plane from a `reference`: give one")), + Some(_) => { + let angle = req_expr(cmd, p, "angle")?; + check_expr(s, &angle, solidcraft_doc::expr::Kind::Angle, cmd, "angle")?; + Some(angle) + } + None => None, + }; + plane(s, p, PlaneRef::Tangent { face: Box::new(face), at, reference, angle }) } fn plane_along(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e30c1c298..d51fc4516 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1334,7 +1334,7 @@ fn select_set(s: &mut Session, p: &Value) -> Result { s.selection.push(x); } } - s.revision += 1; + s.refresh_display(); Ok(json!({"selected": s.selection.len()})) } @@ -1391,7 +1391,7 @@ fn select_same_look(s: &mut Session, p: &Value) -> Result { fn select_clear(s: &mut Session, _p: &Value) -> Result { s.selection.clear(); - s.revision += 1; + s.refresh_display(); Ok(json!({"selected": 0})) } @@ -1771,6 +1771,15 @@ fn redefine(s: &mut Session, p: &Value) -> Result { { *after = before.clone(); } + // A perforation keeps its outline through an edit that names no sketch (the Perforate dialog has no outline). + if let (FeatureKind::SheetPerforate { sketch: Some(before), profiles: picked, .. }, FeatureKind::SheetPerforate { sketch, profiles, .. }) = + (&old.kind, &mut new.kind) + && sketch.is_none() + && params.get("sketch").is_none() + { + *sketch = Some(*before); + *profiles = picked.clone(); + } // A boundary surface's loop of sketch curves and its curve network are one command's two // forms: an edit may turn one into the other. let boundary = |k: &FeatureKind| matches!(k, FeatureKind::SurfaceBoundary { .. } | FeatureKind::SurfaceNetwork { .. }); @@ -1798,6 +1807,11 @@ fn redefine(s: &mut Session, p: &Value) -> Result { }) .collect(); trial.doc_mut().features.retain(|f| f.id != made); + // Made right after the edited feature, the trial joined the timeline folder holding both: + // it leaves it too, or its id stays there, and is given out again below (#9373). + for group in &mut trial.doc_mut().timeline_groups { + group.features.retain(|f| *f != made); + } let added = trial.doc.features.len().saturating_sub(s.doc.features.len()); trial.doc_mut().marker = s.doc.marker.map(|marker| if marker > idx { marker.saturating_add(added) } else { marker }); if made == s.doc.next_id && trial.doc.next_id == made.saturating_add(1) { diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index 05c950810..f129a957a 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -645,6 +645,29 @@ fn timeline_folders_are_command_backed_saved_undoable_and_follow_feature_ids() { assert!(s.doc.timeline_groups.is_empty()); } +/// #9373: editing a feature inside a timeline folder left the id of the edit's trial feature in +/// the folder and gave that id out again, so every edit there added it once more, and a feature +/// made later took it and was listed twice: the saved design then would not open. Edited, the +/// folder keeps its own features, once each, and the design opens again. +#[test] +fn editing_a_feature_inside_a_folder_leaves_the_folder_as_it_was() { + let mut s = Session::default(); + for (name, height) in [("Base", 10), ("Post", 20), ("Pin", 30)] { + run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": height, "operation": "new", "name": name})); + } + let ids: Vec = s.doc.features.iter().map(|f| f.id).collect(); + run(&mut s, "timeline.group", json!({"name": "Parts", "features": ids})); + for width in [5, 6, 7] { + run(&mut s, "timeline.redefine", json!({"feature": "Post", "command": "solid.box", "params": {"length": 4, "width": width, "height": 20}})); + } + assert_eq!(s.doc.timeline_groups[0].features, ids, "no trial feature is left in the folder"); + let made = + run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "operation": "new", "name": "Later"}))["feature"].as_u64().unwrap(); + assert!(!s.doc.timeline_groups[0].features.contains(&made), "a feature made after the folder is not in it"); + let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + assert_eq!(reopened.timeline_groups, s.doc.timeline_groups); +} + #[test] fn timeline_reorders_selected_features_as_one_block_and_removes_folders_in_one_step() { let mut s = Session::default(); @@ -1561,11 +1584,13 @@ fn timeline_joint_folders_are_mixed_saved_and_undoable() { let saved = s.doc.to_json(); let reopened = solidcraft_doc::Document::from_json(&saved).unwrap(); assert_eq!(reopened.to_json(), saved); + // A folder naming a joint the design doesn't have, or one twice, opens without that entry + // (#9373). let mut damaged: Value = serde_json::from_str(&saved).unwrap(); damaged["timeline_groups"][0]["joints"] = json!([u64::MAX]); - assert!(solidcraft_doc::Document::from_json(&damaged.to_string()).is_err()); + assert!(solidcraft_doc::Document::from_json(&damaged.to_string()).unwrap().timeline_groups[0].joints.is_empty()); damaged["timeline_groups"][0]["joints"] = json!([joint, joint]); - assert!(solidcraft_doc::Document::from_json(&damaged.to_string()).is_err()); + assert_eq!(solidcraft_doc::Document::from_json(&damaged.to_string()).unwrap().timeline_groups[0].joints, [joint]); let destination = run(&mut s, "timeline.group", json!({"name":"Destination"}))["group"].as_u64().unwrap(); run(&mut s, "timeline.move_to_group", json!({"joints":[joint], "group":destination})); assert!(s.doc.timeline_groups[0].joints.is_empty()); diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 4bb751233..a9ec0f759 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -91,7 +91,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.pattern.circular", "Circular Pattern", pattern_circ) .at("SOLID", "CREATE") .icon("pattern_circ") - .params("features: [names] | bodies: [names] | components: [names]; axis: X|Y|Z | construction axis name (followed when edited) | {origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); count; angle? (default 360 deg; partial arcs include both ends); alignment?: left|center|right (default right; original stays fixed); reversed?: bool (Flip; selects the extra side for even centered counts)"), + .params("features: [names] | bodies: [names] | components: [names]; axis: X|Y|Z | construction axis name (followed when edited) | {origin, dir} (origin coordinates may be length expressions; the pattern follows them) | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); count; angle? (default 360 deg; partial arcs include both ends); alignment?: left|center|right (default right; original stays fixed); reversed?: bool (Flip; selects the extra side for even centered counts)"), CommandSpec::new("solid.pattern.path", "Pattern on Path", pattern_path) .at("SOLID", "CREATE") .icon("pattern_path") @@ -167,7 +167,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("presspull") .key("Q") .params("face: [x,y,z] and distance: expr (positive adds material, negative cuts), or edges: [[x,y,z]…] and distance (a fillet)"), - CommandSpec::new("solid.move", "Move/Copy", move_bodies).at("SOLID", "MODIFY").icon("move").key("M").enabled(not_in_sketch).params("bodies: [names]; translate?: [x,y,z] (exprs or numbers); axis?: [x,y,z]; angle?: expr; copy?: bool (default false: keeps the original bodies and transforms a new copy instead of moving them in place)"), + CommandSpec::new("solid.move", "Move/Copy", move_bodies).at("SOLID", "MODIFY").icon("move").key("M").enabled(not_in_sketch).params("bodies: [names]; translate?: [x,y,z] (exprs or numbers); axis?: [x,y,z]; angle?: expr; copy?: bool (default false: keeps the original bodies and transforms a new copy instead of moving them in place); occurrences?: [occurrence paths, root first] (only with copy: each component is copied as an independent component, as Paste New copies it, and the copy moves by the same translate, axis and angle in the world; the reply lists the copies in occurrences)"), ]; /// Where an extrude starts and which way is positive: a point inside the (first) profile or @@ -1874,16 +1874,73 @@ fn combine(s: &mut Session, p: &Value) -> Result { } fn move_bodies(s: &mut Session, p: &Value) -> Result { + if let Some(paths) = copied_components(p)? { + return copy_components(s, p, paths); + } if let Some(plan) = crate::frames::placements_moved(s, p) { return move_placements(s, p, plan); } + // Bodies in differently placed frames: one Move feature per frame, each moving its bodies + // by the world vector and turn mapped into that frame (#9660). + if let Some(moves) = crate::frames::split_move(s, p) { + return move_split(s, &moves); + } move_body_feature(s, p) } -/// A move of several placements of one part (`frames::placements_moved`, #4768): each placement -/// moved in the world by the move's translation and turn (about the world origin, as the Move -/// feature turns bodies), and the root component's bodies listed moved as bodies, in one step. -fn move_placements(s: &mut Session, p: &Value, plan: crate::frames::PlacementMove) -> Result { +/// The moves of `frames::split_move`, in one step, with one reply: the features made, and the +/// bodies made, changed and removed by any of them. +fn move_split(s: &mut Session, moves: &[Value]) -> Result { + let mut features = Vec::new(); + let mut lists: [(&str, Vec); 3] = [("created_bodies", Vec::new()), ("changed_bodies", Vec::new()), ("removed_bodies", Vec::new())]; + let mut last = Value::Null; + for p in moves { + let reply = move_body_feature(s, p)?; + features.push(reply.get("feature").cloned().unwrap_or(Value::Null)); + for (key, list) in &mut lists { + for name in reply.get(*key).and_then(Value::as_array).into_iter().flatten() { + if !list.contains(name) { + list.push(name.clone()); + } + } + } + last = reply; + } + if let Some(out) = last.as_object_mut() { + if let Some(first) = features.first() { + out.insert("feature".into(), first.clone()); + } + out.insert("features".into(), Value::Array(features)); + for (key, list) in lists { + out.insert(key.into(), Value::Array(list)); + } + } + Ok(last) +} + +/// The occurrence paths a copying move copies (`occurrences`, root first), `None` when it names +/// none. A component is only ever copied, so the move must set `copy`. +fn copied_components(p: &Value) -> Result>>> { + let cmd = "solid.move"; + let Some(list) = p.get("occurrences") else { return Ok(None) }; + let paths: Vec> = list + .as_array() + .into_iter() + .flatten() + .map(|path| path.as_array().and_then(|ids| ids.iter().map(Value::as_u64).collect::>>()).filter(|ids| !ids.is_empty())) + .collect::>() + .ok_or_else(|| bad(cmd, "`occurrences` must list occurrence paths, each a list of occurrence ids"))?; + if paths.is_empty() || paths.len() > 1000 { + return Err(bad(cmd, "`occurrences` must list 1…1000 occurrence paths")); + } + if p.get("copy").and_then(Value::as_bool) != Some(true) { + return Err(bad(cmd, "`occurrences` are copied: set `copy` to true")); + } + Ok(Some(paths)) +} + +/// The translation (mm) and turn (radians, if any) of a move in the world. +fn world_move(s: &Session, p: &Value) -> Result<(Vec, Option)> { let cmd = "solid.move"; let length = |v: &Value| -> Result { match v { @@ -1901,6 +1958,79 @@ fn move_placements(s: &mut Session, p: &Value, plan: crate::frames::PlacementMov Some(a) => Some(s.doc.eval(&a, Kind::Angle).map_err(|e| bad(cmd, format!("angle: {e}")))?), None => None, }; + Ok((translate, angle)) +} + +/// A copying move of components (`occurrences`, with `copy`): each picked placement's component is +/// copied as an independent component, as Paste New copies it (`component.paste_new`), placed where +/// the placement is; the copy then moves by the move's translation and turn in the world, as +/// `occurrence.move` moves a placement. The bodies listed are copied as bodies (see +/// `move_body_feature`) in the same command, so the whole move is one undo step. +fn copy_components(s: &mut Session, p: &Value, paths: Vec>) -> Result { + let cmd = "solid.move"; + let (translate, angle) = world_move(s, p)?; + let paste = super::find_command("component.paste_new").ok_or_else(|| EngineError::UnknownCommand("component.paste_new".into()))?; + let mover = super::find_command("occurrence.move").ok_or_else(|| EngineError::UnknownCommand("occurrence.move".into()))?; + // A component inside another one copied here comes with its parent's copy. + let mut paths: Vec> = paths.into_iter().fold(Vec::new(), |mut out, path| { + if !out.contains(&path) { + out.push(path); + } + out + }); + let all = paths.clone(); + paths.retain(|p| !all.iter().any(|q| q.len() < p.len() && p.starts_with(q))); + // The bodies are given in the world; their own component's frame turns them, as a move of bodies + // alone is turned, so they are mapped the same way, before any copy is made. + let has_bodies = match p.get("bodies") { + None => false, + Some(Value::Array(bodies)) => !bodies.is_empty(), + Some(_) => return Err(bad(cmd, "`bodies` must list bodies")), + }; + let mut rest = p.clone(); + if let Some(object) = rest.as_object_mut() { + object.remove("occurrences"); + } + // Bodies in differently placed frames split by frame (`frames::split_move`, #9660), as a move of them alone does. + let split = crate::frames::split_move(s, &rest); + let bodies = if has_bodies && split.is_none() { Some(crate::frames::to_local(s, cmd, &rest)?.unwrap_or_else(|| rest.clone())) } else { None }; + let mut copies = Vec::new(); + for path in &paths { + let Some(&source) = path.last() else { continue }; + let component = + s.doc.occurrences.iter().find(|o| o.id == source).map(|o| o.component).ok_or_else(|| bad(cmd, "`occurrences` names no occurrence"))?; + let made = paste.run_nested(s, &json!({"component": component, "occurrence": source, "path": path}))?; + let copy = made.get("occurrence").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "the copy has no occurrence"))?; + // The copy is placed by the same parent placement as its source. + let mut at = path[..path.len() - 1].to_vec(); + at.push(copy); + let mut q = json!({"occurrence": copy, "path": at, "space": "world", "translate": translate}); + if let Some(axis) = p.get("axis") { + q["axis"] = axis.clone(); + } + if let Some(angle) = angle { + q["angle"] = json!(angle); + } + mover.run_nested(s, &q)?; + copies.push(copy); + } + // The reply is a solid.move reply: the bodies' feature reply, with the copies made alongside. + let mut out = match (split, bodies) { + (Some(moves), _) => move_split(s, &moves)?, + (None, Some(local)) => move_body_feature(s, &local)?, + (None, None) => json!({}), + }; + if let Some(object) = out.as_object_mut() { + object.insert("occurrences".into(), json!(copies)); + } + Ok(out) +} + +/// A move of several placements of one part (`frames::placements_moved`, #4768): each placement +/// moved in the world by the move's translation and turn (about the world origin, as the Move +/// feature turns bodies), and the root component's bodies listed moved as bodies, in one step. +fn move_placements(s: &mut Session, p: &Value, plan: crate::frames::PlacementMove) -> Result { + let (translate, angle) = world_move(s, p)?; let spec = super::find_command("occurrence.move").ok_or_else(|| EngineError::UnknownCommand("occurrence.move".into()))?; let mut moved = Vec::new(); for path in &plan.paths { @@ -2116,16 +2246,32 @@ fn pattern_rect(s: &mut Session, p: &Value) -> Result { finish_pattern(s, p, features, pattern, bodies) } +/// The line a circular pattern turns about, as [`axis_line`] reads it, except that the origin of +/// `{origin, dir}` may be length expressions, kept so the pattern follows them (#10852). +fn pattern_axis(s: &Session, p: &Value, cmd: &str) -> Result<(PointExpr, Vec3, Option, Option)> { + if let Some(a @ Value::Object(o)) = p.get("axis") + && o.contains_key("origin") + && !super::is_model_axis(a) + { + // Read under its full name, so a refusal says which origin it means. + let origin = point_param(s, &json!({ "axis.origin": o.get("origin") }), "axis.origin", cmd)?; + let dir = a.get("dir").and_then(vec3).and_then(|d| d.normalized()).ok_or_else(|| bad(cmd, "axis needs a non-zero `dir`"))?; + return Ok((origin.unwrap_or_else(|| solidcraft_doc::point_expr(Vec3::ZERO)), dir, None, None)); + } + let (origin, dir, axis_ref, axis_feature) = axis_line(s, p, cmd)?; + Ok((solidcraft_doc::point_expr(origin), dir, axis_ref, axis_feature)) +} + fn pattern_circ(s: &mut Session, p: &Value) -> Result { let cmd = "solid.pattern.circular"; let (features, bodies) = pattern_sources(s, p, cmd)?; - let (origin, axis, axis_ref, axis_feature) = axis_line(s, p, cmd)?; + let (origin, axis, axis_ref, axis_feature) = pattern_axis(s, p, cmd)?; let count = req_expr(cmd, p, "count")?; check_count(s, &count, cmd, "count")?; let angle = expr(p, "angle").unwrap_or_else(|| "360 deg".into()); check_expr(s, &angle, Kind::Angle, cmd, "angle")?; let pattern = solidcraft_doc::PatternKind::Circular { - origin: Position(origin), + origin, axis: Dir(axis), count, angle, diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index eb846efd3..79552bf01 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -44,12 +44,12 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("save") .key("Ctrl+S") .noundo() - .params("path? (default: current file); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false); overwrite?: bool (replace the design's file even though another program or computer changed it since it was opened or saved; without it that save is refused)"), + .params("path? (default: current file; a name that opens as another kind of file, such as .step, .stl or .dxf, is refused: file.export writes those); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false); overwrite?: bool (replace the design's file even though another program or computer changed it since it was opened or saved; without it that save is refused)"), CommandSpec::new("file.save_as", "Save As", save_as) .icon("save") .key("Ctrl+Shift+S") .noundo() - .params("path; format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false); overwrite?: bool (as file.save, when `path` is the design's own file)"), + .params("path (a design file name, .sc as a rule; one that opens as another kind of file, such as .step, .stl or .dxf, is refused: file.export writes those); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false); overwrite?: bool (as file.save, when `path` is the design's own file)"), CommandSpec::new("doc.recovery_list", "Recoverable Designs", recovery_list).icon("restore") .noundo() .params("dir? (default: the recovery folder) → designs autosaved by apps that crashed or closed with unsaved changes"), @@ -488,8 +488,38 @@ fn rename_design(s: &mut Session, from: &str, to: &str) { } } -fn write(s: &mut Session, path: &str, format: &str, compression: &str, preview: bool, cache: bool, overwrite: bool) -> Result { +/// The kind of file `doc.open` reads `path` as when that is not a design, by its extension. A +/// design saved under such a name would not open again as the design (#9745). +fn other_file_kind(path: &str) -> Option<&'static str> { + if solidcraft_io::is_step_path(path) { + Some("a STEP or other CAD exchange file") + } else if solidcraft_io::is_mesh_path(path) { + Some("a mesh") + } else if super::drawing_import_command(path).is_some() { + Some("a 2D drawing") + } else if solidcraft_io::is_point_cloud_path(path) { + Some("a point cloud") + } else if solidcraft_io::is_drawing_path(path) { + Some("a SolidCraft drawing") + } else { + None + } +} + +/// Refuse to save a design under a name [`other_file_kind`] opens as another kind of file, +/// pointing to `file.export` when that writes the format. +fn check_design_name(cmd: &str, path: &str) -> Result<()> { + let Some(kind) = other_file_kind(path) else { return Ok(()) }; + let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_string()).unwrap_or_default(); + let export = if solidcraft_io::Format::from_name(&ext).is_ok() { format!(", or write a .{ext} file with file.export") } else { String::new() }; + Err(bad(cmd, format!("{path}: a .{ext} file opens as {kind}, not as a design; save the design as .{}{export}", solidcraft_io::DESIGN_EXT))) +} + +#[allow(clippy::too_many_arguments)] +fn write(s: &mut Session, cmd: &str, path: &str, format: &str, compression: &str, preview: bool, cache: bool, overwrite: bool) -> Result { + // A path outside the agent's folders says so first, whatever its name. solidcraft_io::vfs::check(path).map_err(|e| EngineError::Other(e.to_string()))?; + check_design_name(cmd, path)?; if s.path.as_deref() == Some(path) { if s.read_only { return Err(EngineError::Other(format!("{path}: the design was opened read-only; save it to another file with file.save_as"))); @@ -688,6 +718,7 @@ fn save(s: &mut Session, p: &Value) -> Result { }; write( s, + "file.save", &path, str_(p, "format").unwrap_or(default_design_format(&path)), str_(p, "compression").unwrap_or("fast"), @@ -705,6 +736,7 @@ fn save_as(s: &mut Session, p: &Value) -> Result { let path = path_arg(p, "file.save_as")?.to_string(); write( s, + "file.save_as", &path, str_(p, "format").unwrap_or(default_design_format(&path)), str_(p, "compression").unwrap_or("fast"), @@ -1917,6 +1949,36 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn a_design_is_not_saved_under_a_name_that_opens_as_another_file() { + // #9745: a design saved as `part.step` or `part.stl` was refused or opened as a broken mesh. + let dir = name_dir("other-kind"); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + for name in + ["part.step", "part.STP", "part.igs", "part.stl", "part.obj", "part.3mf", "part.glb", "part.dxf", "part.svg", "part.ply", "part.scdwg"] + { + let path = dir.join(name); + for command in ["file.save_as", "file.save"] { + let e = s.execute(command, &json!({"path":path})).unwrap_err().to_string(); + assert!(e.contains("not as a design") && e.contains(".sc"), "{command} {name}: {e}"); + assert!(!path.exists(), "{command} {name} wrote the file"); + } + } + let e = s.execute("file.save_as", &json!({"path":dir.join("part.stl")})).unwrap_err().to_string(); + assert!(e.contains("file.export"), "STL is an export format: {e}"); + assert!(s.path.is_none() && s.is_dirty(), "a refused save changes nothing"); + // Names that open again as the design still save, and what they write opens as it. + for name in ["part.sc", "part.json", "part.txt", "part"] { + let path = dir.join(name); + s.execute("file.save_as", &json!({"path":path})).unwrap(); + let mut reopened = Session::default(); + reopened.execute("doc.open", &json!({"path":path})).unwrap(); + assert_eq!(reopened.doc.features.len(), 1, "{name} reopens as the design"); + } + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn save_as_keeps_a_name_the_user_chose() { let dir = name_dir("named"); diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index fca5fcfc4..e86c7aca9 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -697,11 +697,47 @@ fn check_sides(a: &JointOrigin, b: &JointOrigin, cmd: &str) -> Result<()> { Ok(()) } +/// A path already joins the two sides, including paths through grounded occurrences. +fn closes_loop(s: &Session, j: &Joint) -> bool { + let mut at: BTreeMap> = BTreeMap::new(); + for joint in s.doc.assembly.joints.iter().filter(|j| !j.suppressed).take(joints::MAX_JOINTS) { + at.entry(joint.a.occurrence).or_default().push(joint.b.occurrence); + at.entry(joint.b.occurrence).or_default().push(joint.a.occurrence); + } + // The solver fixes the root and every grounded occurrence in the same world frame. + for o in s.doc.occurrences.iter().filter(|o| o.grounded) { + at.entry(0).or_default().push(o.id); + at.entry(o.id).or_default().push(0); + } + let mut seen = BTreeSet::from([j.a.occurrence]); + let mut pending = vec![j.a.occurrence]; + while let Some(occ) = pending.pop() { + if occ == j.b.occurrence { + return true; + } + for other in at.get(&occ).into_iter().flatten() { + if seen.insert(*other) { + pending.push(*other); + } + } + } + false +} + fn add_joint(s: &mut Session, mut j: Joint, p: &Value) -> Result { if s.doc.assembly.joints.len() >= 10_000 { return Err(EngineError::Other("too many joints".into())); } check_sides(&j.a, &j.b, "joint.create")?; + // Relations and loop-closing typed joints start where their parts are. A typed joint in + // an open chain keeps its usual initial values; explicitly supplied values also keep theirs. + if p.get("values").is_none() + && p.get("value").is_none() + && (j.kind.is_relation() || closes_loop(s, &j)) + && let Some(q) = joints::relation_values(&s.doc, &s.model.state(), &j) + { + j.values = q; + } // It starts at its values inside its limits. A value moved to a limit moves the part as it // is joined, which the answer says. let mut q = j.values.clone(); @@ -731,7 +767,10 @@ fn add_joint(s: &mut Session, mut j: Joint, p: &Value) -> Result { // A new joint starts shown, even if a stale visibility entry came from an older design. s.visibility.hidden_joints.retain(|h| *h != id); s.doc_mut().assembly.joints.push(j); - let sol = resolve(s); + let mut sol = resolve(s); + if sol.conflicts.iter().any(|(c, ..)| *c == id) && close_by_half_turn(s, id, &sol) { + sol = resolve(s); + } let mut out = sol_json(&sol, p); out["joint"] = json!(id); out["name"] = json!(name); @@ -741,6 +780,95 @@ fn add_joint(s: &mut Session, mut j: Joint, p: &Value) -> Result { Ok(out) } +/// Sets of angle values a new loop-closing joint tries a half turn round, at most. +const HALF_TURN_TRIALS: usize = 16; + +/// A new joint that closes a loop is met from where the loop's parts sit. Where its parts only +/// meet with one of them turned a half turn about a joint on the way between them (a second +/// planar joint mating two faces that point the same way, #10331), the loop solve starts at a +/// pose turned exactly away and sees no way round, and the joint is left as a conflict. As the +/// first joint of a chain moves its part into place, turn the new joint's own angle, each angle +/// on the shortest joint path between its two parts, or one of each, a half turn, and keep the +/// first that meets it with no new conflict or error elsewhere than `before` had (stored, for +/// the caller's resolve). False, and nothing changed, when none does. Values a motion link or an +/// expression sets, and turns their limits stop short, are left alone. +fn close_by_half_turn(s: &mut Session, id: u64, before: &joints::Solution) -> bool { + let asm = &s.doc.assembly; + let Some(new) = asm.joints.iter().find(|j| j.id == id) else { return false }; + let (from, to) = (new.a.occurrence, new.b.occurrence); + // Breadth first over the other joints, from A's occurrence to B's. + let mut reached: BTreeMap> = BTreeMap::from([(from, None)]); + let mut frontier = vec![from]; + while !frontier.is_empty() && !reached.contains_key(&to) { + let mut next = Vec::new(); + for at in frontier { + for (k, j) in asm.joints.iter().enumerate().filter(|(_, j)| j.id != id && !j.suppressed) { + let other = if j.a.occurrence == at { + j.b.occurrence + } else if j.b.occurrence == at { + j.a.occurrence + } else { + continue; + }; + if let std::collections::btree_map::Entry::Vacant(e) = reached.entry(other) { + e.insert(Some(k)); + next.push(other); + } + } + } + frontier = next; + } + let mut path = Vec::new(); + let mut at = to; + while let Some(Some(k)) = reached.get(&at).copied() { + let Some(j) = asm.joints.get(k) else { break }; + path.push(k); + at = if j.a.occurrence == at { j.b.occurrence } else { j.a.occurrence }; + } + let linked: BTreeSet<(u64, usize)> = asm.links.iter().map(|l| (l.b, l.ib)).collect(); + // The angle values that may turn: on the path, and the new joint's own (turned exactly + // away about its axis, its own value sees no way round either). + let angles = |ks: &[usize]| -> Vec<(usize, usize)> { + ks.iter() + .filter_map(|k| asm.joints.get(*k).map(|j| (*k, j))) + .flat_map(|(k, j)| (0..j.kind.dofs().len()).filter(move |i| j.kind.is_angle(*i)).map(move |i| (k, j, i))) + .filter(|(_, j, i)| j.exprs.value(*i).is_none() && !linked.contains(&(j.id, *i))) + .map(|(k, _, i)| (k, i)) + .collect() + }; + let own = asm.joints.iter().position(|j| j.id == id).map(|k| angles(&[k])).unwrap_or_default(); + let mut trials: Vec> = own.iter().map(|v| vec![*v]).collect(); + for v in angles(&path) { + trials.push(vec![v]); + trials.extend(own.iter().map(|w| vec![v, *w])); + } + trials.truncate(HALF_TURN_TRIALS); + let st = s.model.state(); + 'trial: for turns in trials { + let mut doc = (*s.doc).clone(); + for (k, i) in turns { + let Some(j) = doc.assembly.joints.get_mut(k) else { continue 'trial }; + j.values.resize(j.kind.dofs().len(), 0.0); + let Some(q) = j.values.get(i).copied() else { continue 'trial }; + let mut turned = j.values.clone(); + if let Some(slot) = turned.get_mut(i) { + *slot = q + std::f64::consts::PI; + } + joints::clamp(j, &mut turned); + if turned.get(i).is_none_or(|v| (v - q - std::f64::consts::PI).abs() > 1e-9) { + continue 'trial; + } + j.values = turned; + } + let sol = joints::solve_holding_with_analysis(&doc, &st, &BTreeMap::new(), joints::Analysis::Placement); + if sol.conflicts.len() < before.conflicts.len() && !sol.conflicts.iter().any(|(c, ..)| *c == id) && sol.errors.len() <= before.errors.len() { + s.doc_mut().assembly.joints = doc.assembly.joints; + return true; + } + } + false +} + fn joint_origin(s: &mut Session, p: &Value) -> Result { let cmd = "joint.origin"; let origin = origin_param(s, Some(p), cmd)?; @@ -798,13 +926,6 @@ fn joint(s: &mut Session, p: &Value) -> Result { suppressed: false, exprs: JointExprs { offset: typed(p.get("offset")), angle: typed(p.get("angle")), values: value_exprs(p) }, }; - // A relation given no values starts from where its parts are: B moves no further than it must. - if p.get("values").is_none() - && p.get("value").is_none() - && let Some(q) = joints::relation_values(&s.doc, &s.model.state(), &j) - { - j.values = q; - } // No angle given: B keeps its turn about the joint's axis where a half turn would otherwise // come only from how its origin's x was chosen. (An angle relation's angle is its tilt.) if angle.is_none() && !j.kind.is_relation() { @@ -1515,7 +1636,7 @@ fn edit(s: &mut Session, p: &Value) -> Result { // A relation whose type, offset, tilt or flip changes starts again from where its parts are. let reseat = kind.is_some() || offset.is_some() || angle.is_some() || p.get("flip").is_some() || sides; if reseat { - let edited = s.doc.assembly.joints.iter().find(|j| j.id == id).cloned(); + let edited = s.doc.assembly.joints.iter().find(|j| j.id == id).filter(|j| j.kind.is_relation()).cloned(); if let Some(q) = edited.and_then(|j| joints::relation_values(&s.doc, &s.model.state(), &j)) && let Some(j) = s.doc_mut().assembly.joints.iter_mut().find(|j| j.id == id) { diff --git a/crates/engine/src/cmd/joints_relations_tests.rs b/crates/engine/src/cmd/joints_relations_tests.rs index e858ea0f2..2c09d1eae 100644 --- a/crates/engine/src/cmd/joints_relations_tests.rs +++ b/crates/engine/src/cmd/joints_relations_tests.rs @@ -60,6 +60,43 @@ fn clean(r: &Value) -> bool { r["conflicts"] == json!([]) && r["errors"] == json!([]) } +#[test] +fn closing_planar_joint_starts_from_the_current_placement() { + let mut s = Session::default(); + for name in ["Base", "Part"] { + run(&mut s, "component.create", json!({"name": name})); + run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 6})); + run(&mut s, "component.activate", json!({"component": "root"})); + } + let base = occ(&s, "Base"); + run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true})); + let r = run( + &mut s, + "joint.create", + json!({"type": "planar", "name": "First", "flip": true, "angle": 0, + "a": {"occurrence": "Base", "point": [0, 0, 0], "x": [1, 0, 0]}, + "b": {"occurrence": "Part", "point": [0, 0, 0], "x": [1, 0, 0]}, "values": [50, 30, 120]}), + ); + assert!(clean(&r), "{r}"); + // Check a frame, so a turn as well as a translation is observable. + let points = [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z]; + let before = points.map(|p| place(&s, "Part", p)); + let at = before[0]; + let x = before[1] - at; + let r = run( + &mut s, + "joint.create", + json!({"type": "planar", "name": "Closing", "flip": true, "angle": 0, + "a": {"occurrence": "Base", "point": [0, 0, 0], "x": [1, 0, 0]}, + "b": {"occurrence": "Part", "point": [at.x, at.y, at.z], "x": [x.x, x.y, x.z]}}), + ); + assert!(clean(&r), "{r}"); + for (p, want) in points.into_iter().zip(before) { + let got = place(&s, "Part", p); + assert!(near(got, want, 1e-6), "{p:?}: {got:?}, expected {want:?}"); + } +} + #[test] fn stacked_relations_place_a_part_and_follow_the_panel() { let mut s = panel(); diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rs index 8ae8c6652..86af4b579 100644 --- a/crates/engine/src/cmd/joints_tests.rs +++ b/crates/engine/src/cmd/joints_tests.rs @@ -699,6 +699,104 @@ fn values_left_out_of_a_drive_follow_the_loop() { assert!(near(place(&s, "Plate", Vec3::ZERO), Vec3::new(10.0, 10.0, 0.0)), "{:?}", place(&s, "Plate", Vec3::ZERO)); } +/// Two boards 400 x 100 x 20 for #10331: yellow at the origin, grounded, and red 300 mm along Y. +fn boards() -> Session { + let mut s = Session::default(); + for (name, corner) in [("Yellow", [0.0, 0.0, 0.0]), ("Red", [0.0, 300.0, 0.0])] { + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": name, "grounded": false})); + run(&mut s, "solid.box", json!({"length": 400, "width": 100, "height": 20, "corner": corner})); + } + let y = occ(&s, "Yellow"); + run(&mut s, "occurrence.ground", json!({"occurrence": y, "grounded": true})); + s +} + +/// #10331: a board on a planar joint, mated by a second planar joint at a face that points the +/// same way as the face it meets. It meets it turned a half turn on the first joint, the way the +/// first joint moves its part into place, in either pick order, and still slides along the +/// line the two planes share. Faces that can never meet stay a conflict, and nothing moves. +#[test] +fn a_second_planar_joint_turns_its_part_a_half_turn_to_meet() { + // Each case: the yellow face, the red face (world points once red lies on yellow, at + // x 0..400, y 0..100, z 20..40), and where red's origin ends up. + let cases = [ + ("fronts", [200.0, 0.0, 10.0], [200.0, 0.0, 30.0], Some(Vec3::new(400.0, 300.0, 20.0))), + ("ends", [0.0, 50.0, 10.0], [0.0, 50.0, 30.0], Some(Vec3::new(0.0, 400.0, 20.0))), + ("top against front", [200.0, 0.0, 10.0], [200.0, 50.0, 40.0], None), + ]; + for red_first in [false, true] { + for (case, yellow_face, red_face, expected) in cases { + let mut s = boards(); + let planar = |s: &mut Session, name: &str, yellow: [f64; 3], red: [f64; 3]| { + let (yellow, red) = (json!({"occurrence": "Yellow", "face": yellow}), json!({"occurrence": "Red", "face": red})); + let (a, b) = if red_first { (red, yellow) } else { (yellow, red) }; + run(s, "joint.create", json!({"type": "planar", "a": a, "b": b, "name": name})) + }; + let r = planar(&mut s, "Top", [200.0, 50.0, 20.0], [200.0, 350.0, 0.0]); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{case}: {r}"); + let on_top = place(&s, "Red", Vec3::ZERO); + let r = planar(&mut s, "Side", yellow_face, red_face); + let label = format!("{case}, red picked first: {red_first}"); + let Some(expected) = expected else { + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(1), "{label}: {r}"); + assert!(near(place(&s, "Red", Vec3::ZERO), on_top), "{label}: {:?}", place(&s, "Red", Vec3::ZERO)); + continue; + }; + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{label}: {r}"); + assert!(place(&s, "Red", Vec3::ZERO).dist(expected) < 1e-6, "{label}: {:?}", place(&s, "Red", Vec3::ZERO)); + assert_eq!(dof_of(&mut s, "Red"), 1, "{label}"); + let axes = solidcraft_doc::joints::motion_axes(&s.doc, &s.model.state(), occ(&s, "Red")); + assert!(axes.len() == 1 && !axes.iter().any(|a| a.angular), "{label}: {axes:?}"); + } + } +} + +/// #10331, with the board turned on the table first (the report's board was turned 40 degrees): +/// a second planar joint between any side of the yellow board and any side of the red one meets, +/// whichever turn the red board needs on the first joint to get there. +#[test] +fn any_two_sides_of_turned_boards_meet_on_a_second_planar_joint() { + // The sides' centres, the red ones where the red board was made. + let reds = [ + ("red front", Vec3::new(200.0, 300.0, 10.0)), + ("red back", Vec3::new(200.0, 400.0, 10.0)), + ("red left end", Vec3::new(0.0, 350.0, 10.0)), + ("red right end", Vec3::new(400.0, 350.0, 10.0)), + ]; + let yellows = [ + ("yellow front", [200.0, 0.0, 10.0]), + ("yellow back", [200.0, 100.0, 10.0]), + ("yellow left end", [0.0, 50.0, 10.0]), + ("yellow right end", [400.0, 50.0, 10.0]), + ]; + for turn in [40.0f64, 0.0, 137.0] { + for (yn, yp) in yellows { + for (rn, rl) in reds { + let mut s = boards(); + run( + &mut s, + "occurrence.move", + json!({"occurrence": "Red:1", "space": "world", "axis": [0, 0, 1], "angle": format!("{turn} deg"), "origin": [200, 350, 0]}), + ); + let top = place(&s, "Red", Vec3::new(200.0, 350.0, 0.0)); + run( + &mut s, + "joint.create", + json!({"type": "planar", "a": {"occurrence": "Yellow", "face": [200, 50, 20]}, "b": {"occurrence": "Red", "face": [top.x, top.y, top.z]}, "name": "Top"}), + ); + let rp = place(&s, "Red", rl); + let r = run( + &mut s, + "joint.create", + json!({"type": "planar", "a": {"occurrence": "Yellow", "face": yp}, "b": {"occurrence": "Red", "face": [rp.x, rp.y, rp.z]}, "name": "Side"}), + ); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "turned {turn} degrees, {yn} against {rn}: {r}"); + } + } + } +} + /// A slider-crank: crank 15 about the origin, rod 40, a piston sliding along X. Returns the crank /// pin and the wrist pin. fn slider_crank() -> (Session, Vec3, Vec3) { diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index e1c635fff..075b4db3f 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -47,13 +47,14 @@ pub(crate) use features::{EdgeRefForm, PLANE_FORMS, axis_dir_form, axis_line_obj pub use features::{auto_operation, extrude_reach, shown_scope}; pub use file::open_steps::OpenSteps; pub use join_pieces::{Addition, addition}; +pub use parts::part_length_label; pub use sketch::dimension_roles; pub(crate) use sketch::face::face_pick_form; pub use sketch_construction::{ ConstructionLine, construction_line_choice, construction_line_mode, construction_line_solutions, construction_line_takes_length, construction_segment, }; -pub use sketch_create::tangent_arc_preview; +pub use sketch_create::{tangent_arc_preview, tangent_arc_starts_at}; pub use sketch_import::drawing_import_command; pub use sketch_modify::{extend_arc_preview, extend_preview, trim_piece}; pub use view_dxf::sketch::exportable as view_dxf_exportable; @@ -249,6 +250,12 @@ impl CommandSpec { other => other, } } + /// The refusal this command gives when it is not available in this session: none when it + /// is. It is the engine's own wording (`EngineError::Disabled`), so a caller that only has + /// the message can tell it from a failure of the command itself. + pub fn disabled_refusal(&self, s: &Session) -> Option { + (self.enabled)(s).err().map(|why| crate::EngineError::Disabled(self.id.to_string(), why).to_string()) + } pub fn info(&self, s: &Session) -> CommandInfo { let e = (self.enabled)(s); let (label, icon) = match self.id { diff --git a/crates/engine/src/cmd/parts.rs b/crates/engine/src/cmd/parts.rs index 14021f555..4bbf8917c 100644 --- a/crates/engine/src/cmd/parts.rs +++ b/crates/engine/src/cmd/parts.rs @@ -1,5 +1,6 @@ -//! Standard parts: ISO metric fasteners, dowel pins and ball bearings, generated in code from -//! the dimensions in the public standards tables (no vendor geometry). Each part is inserted as +//! Standard parts: ISO metric and ASME/ANSI inch fasteners, dowel pins and ball bearings, +//! generated in code from the dimensions in the public standards tables (no vendor geometry). +//! Inch parts are tabled in inches and built in millimetres like the rest. Each part is inserted as //! its own component, built by ordinary features (so it stays parametric and editable), with a //! cosmetic thread where it has one; at a hole it gets a rigid joint that puts its axis on the //! hole's and seats it on the face. Inserted at several holes it is still one component, placed @@ -16,20 +17,24 @@ use crate::params::{bad, num, str_, vec3}; use crate::{EngineError, Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("parts.library", "Standard Parts", library).icon("library") + CommandSpec::new("parts.library", "Standard Parts", library) + .icon("library") .noundo() - .params("family? → families (name, standard, sizes, lengths) and, with family, each size's dimensions (mm)"), - CommandSpec::new("parts.fastener", "Insert Fastener", insert_atomic).at("SOLID", "INSERT").icon("fastener").params( - "the Insert Part dialog's command (same as parts.insert): family, size, length?, at?|point?+direction?, name?", - ), + .params("family? → families (name, standard, system: metric|inch, sizes, lengths) and, with family, each size's dimensions (mm)"), + CommandSpec::new("parts.fastener", "Insert Fastener", insert_atomic) + .at("SOLID", "INSERT") + .icon("fastener") + .params("the Insert Part dialog's command (same as parts.insert): family, size, length?, at?|point?+direction?, name?"), CommandSpec::new("parts.insert", "Insert Part", insert_atomic).icon("fastener").params( - "family (socket_head_cap_screw | button_head_cap_screw | hex_bolt | hex_nut | washer | set_screw | dowel_pin | bearing); size (\"M6\", or \"608\" for bearings); \ - length? (mm; screws, bolts, set screws, pins; default a standard length near 2.5 d); \ + "family (socket_head_cap_screw | button_head_cap_screw | hex_bolt | hex_nut | washer | set_screw | dowel_pin | bearing | \ + hex_cap_screw_inch | hex_nut_inch | washer_sae | washer_uss); size (\"M6\", \"608\" for bearings, \"1/2-13 UNC\" for inch screws and nuts, \ + \"1/2\" for inch washers); length? (mm, inch parts too; screws, bolts, set screws, pins; default a standard length near 2.5 d); \ at?: [x,y,z] on a hole's rim or wall (the part seats on the hole's face with a rigid joint), or a list of them (one component, \ placed and seated once per hole) | point?: [x,y,z] with direction?: [x,y,z] (no joint); name? → component, occurrence, joint?, \ and with at: occurrences, joints (one per hole, in pick order)", ), - CommandSpec::new("parts.resize", "Change Part Size", resize_atomic).icon("scale") + CommandSpec::new("parts.resize", "Change Part Size", resize_atomic) + .icon("scale") .params("component: id|name of an inserted part; size?; length? — rebuilds it (joints keep it seated)"), ]; @@ -43,6 +48,10 @@ const FAMILIES: &[(&str, &str, &str)] = &[ ("set_screw", "Hex socket set screw, flat point", "ISO 4026"), ("dowel_pin", "Parallel pin (dowel)", "ISO 8734"), ("bearing", "Deep groove ball bearing (envelope)", "ISO 15 (6000/6200/600 series)"), + ("hex_cap_screw_inch", "Hex cap screw (inch)", "ASME B18.2.1"), + ("hex_nut_inch", "Hex nut (inch)", "ASME B18.2.2"), + ("washer_sae", "Plain washer, SAE (narrow)", "ANSI B18.22.1 Type A"), + ("washer_uss", "Plain washer, USS (wide)", "ANSI B18.22.1 Type A"), ]; /// ISO metric coarse: (size, d, pitch). @@ -190,6 +199,127 @@ const BEARINGS: [(&str, f64, f64, f64); 13] = [ const LENGTHS: [f64; 22] = [4.0, 5.0, 6.0, 8.0, 10.0, 12.0, 16.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0, 55.0, 60.0, 65.0, 70.0, 80.0, 90.0, 100.0, 120.0]; +/// Millimetres per inch. +const INCH: f64 = 25.4; + +/// ASME B18.2.1 hex cap screw, in inches: (nominal size, width across flats F, head height H). +/// 9/16 is left out until the thread catalogue has its UNC and UNF threads. +const INCH_HEX_CAP: [(&str, f64, f64); 9] = [ + ("1/4", 0.4375, 0.156), + ("5/16", 0.5, 0.203), + ("3/8", 0.5625, 0.234), + ("7/16", 0.625, 0.281), + ("1/2", 0.75, 0.312), + ("5/8", 0.9375, 0.391), + ("3/4", 1.125, 0.469), + ("7/8", 1.3125, 0.547), + ("1", 1.5, 0.609), +]; + +/// ASME B18.2.2 hex nut, in inches: (nominal size, width across flats F, thickness H). +const INCH_HEX_NUT: [(&str, f64, f64); 9] = [ + ("1/4", 0.4375, 0.219), + ("5/16", 0.5, 0.266), + ("3/8", 0.5625, 0.328), + ("7/16", 0.6875, 0.375), + ("1/2", 0.75, 0.438), + ("5/8", 0.9375, 0.547), + ("3/4", 1.125, 0.641), + ("7/8", 1.3125, 0.75), + ("1", 1.5, 0.859), +]; + +/// ANSI B18.22.1 Type A plain washers, in inches: (nominal size, inside diameter, outside +/// diameter, thickness). SAE is the standard's narrow (N) series, USS its wide (W) one. +const WASHER_SAE: [(&str, f64, f64, f64); 9] = [ + ("1/4", 0.281, 0.625, 0.065), + ("5/16", 0.344, 0.688, 0.065), + ("3/8", 0.406, 0.812, 0.065), + ("7/16", 0.469, 0.922, 0.065), + ("1/2", 0.531, 1.062, 0.095), + ("5/8", 0.656, 1.312, 0.095), + ("3/4", 0.812, 1.469, 0.134), + ("7/8", 0.938, 1.75, 0.134), + ("1", 1.062, 2.0, 0.134), +]; +const WASHER_USS: [(&str, f64, f64, f64); 9] = [ + ("1/4", 0.312, 0.734, 0.065), + ("5/16", 0.375, 0.875, 0.083), + ("3/8", 0.438, 1.0, 0.083), + ("7/16", 0.5, 1.25, 0.083), + ("1/2", 0.562, 1.375, 0.109), + ("5/8", 0.688, 1.75, 0.134), + ("3/4", 0.812, 2.0, 0.148), + ("7/8", 0.938, 2.25, 0.165), + ("1", 1.062, 2.5, 0.165), +]; + +/// Standard lengths for inch cap screws (inches). +const INCH_LENGTHS: [f64; 19] = [0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 7.0, 8.0]; + +fn inch_lengths() -> Vec { + INCH_LENGTHS.iter().map(|l| l * INCH).collect() +} + +/// The first standard length at or above 2.5 d. Both sides are inches turned into mm, so the +/// comparison allows for rounding: a 1/2 screw's 2.5 d is exactly 1-1/4. +fn default_inch_length(d: f64) -> f64 { + inch_lengths().into_iter().find(|l| *l >= 2.5 * d - 1e-9).unwrap_or(8.0 * INCH) +} + +fn is_inch(family: &str) -> bool { + matches!(family, "hex_cap_screw_inch" | "hex_nut_inch" | "washer_sae" | "washer_uss") +} + +/// A unified inch thread from the catalogue (`1/2-13 UNC`): its nominal size (`1/2`), and its +/// major diameter and pitch (mm). +fn unified(size: &str) -> Option<(String, f64, f64)> { + use solidcraft_doc::TappedThreadFamily::{Unc, Unf}; + let t = solidcraft_doc::parse_tapped_thread(size).filter(|t| matches!(t.family, Unc | Unf))?; + let nominal = t.designation.split('-').next()?.to_string(); + Some((nominal, t.major_diameter, t.pitch)) +} + +/// The catalogue's threads for a nominal inch size, UNC before UNF. +fn unified_sizes(nominal: &str) -> Vec { + use solidcraft_doc::TappedThreadFamily::{Unc, Unf}; + [Unc, Unf].into_iter().flat_map(solidcraft_doc::tapped_thread_sizes).filter(|t| t.designation.split('-').next() == Some(nominal)).collect() +} + +/// A length (mm) in fractional inches to the nearest 1/64 (`1-1/2`), or none off that grid. +fn inch_fraction(mm: f64) -> Option { + let n = mm / INCH * 64.0; + let r = n.round(); + if !r.is_finite() || r <= 0.0 || r > 1e6 || (n - r).abs() > 1e-6 { + return None; + } + let r = r as u64; + let (whole, mut num, mut den) = (r / 64, r % 64, 64); + while num > 0 && num % 2 == 0 { + num /= 2; + den /= 2; + } + Some(match (whole, num) { + (w, 0) => w.to_string(), + (0, n) => format!("{n}/{den}"), + (w, n) => format!("{w}-{n}/{den}"), + }) +} + +/// How a part's length (mm) is shown where its family has a unit of its own: `1-1/2 in` for an +/// inch family, none for a metric one (shown in the design's units). +pub fn part_length_label(family: &str, mm: f64) -> Option { + is_inch(family).then(|| inch_fraction(mm)).flatten().map(|f| format!("{f} in")) +} + +/// A part's size with its length, as names and part numbers write it: `M6x20`, `1/2-13 UNC x 2`. +fn size_with_length(family: &str, size: &str, len: f64) -> String { + match is_inch(family).then(|| inch_fraction(len)).flatten() { + Some(l) => format!("{size} x {l}"), + None => format!("{size}x{len}"), + } +} + fn metric(size: &str) -> Option<(f64, f64)> { METRIC.iter().find(|(s, _, _)| s.eq_ignore_ascii_case(size)).map(|(_, d, p)| (*d, *p)) } @@ -202,9 +332,11 @@ fn default_length(d: f64) -> f64 { #[derive(Clone, Debug, PartialEq)] enum Shape { /// A head (round, domed or hex), a shank down −z, an optional hex socket in the head's top. - Screw { d: f64, pitch: f64, len: f64, head: Head, socket: Option<(f64, f64)> }, + /// `pitch` is that of a metric cosmetic thread; inch parts have none, as `solid.thread` takes + /// only metric designations (#9571). + Screw { d: f64, pitch: Option, len: f64, head: Head, socket: Option<(f64, f64)> }, /// A hex prism with a through hole (nut), z 0…m. - Nut { d: f64, pitch: f64, s: f64, m: f64 }, + Nut { d: f64, pitch: Option, s: f64, m: f64 }, /// A ring (washer, bearing envelope), z 0…h. Ring { d_in: f64, d_out: f64, h: f64 }, /// A cylinder down −z with a socket in its top (set screw), or plain (pin). @@ -237,22 +369,43 @@ fn shape(family: &str, size: &str, length: Option) -> std::result::Result { let (d, pitch) = metric(size).ok_or_else(|| need("metric"))?; let (_, dk, k, s, t) = SHCS.iter().find(|r| r.0.eq_ignore_ascii_case(size)).copied().ok_or_else(|| need("ISO 4762"))?; - Shape::Screw { d, pitch, len: len(d), head: Head::Round { dk, k }, socket: Some((s, t)) } + Shape::Screw { d, pitch: Some(pitch), len: len(d), head: Head::Round { dk, k }, socket: Some((s, t)) } } "button_head_cap_screw" => { let (d, pitch) = metric(size).ok_or_else(|| need("metric"))?; let (_, dk, k, s, t) = BHCS.iter().find(|r| r.0.eq_ignore_ascii_case(size)).copied().ok_or_else(|| need("ISO 7380-1"))?; - Shape::Screw { d, pitch, len: len(d), head: Head::Dome { dk, k, flat: BUTTON_FLAT * s }, socket: Some((s, t)) } + Shape::Screw { d, pitch: Some(pitch), len: len(d), head: Head::Dome { dk, k, flat: BUTTON_FLAT * s }, socket: Some((s, t)) } } "hex_bolt" => { let (d, pitch) = metric(size).ok_or_else(|| need("metric"))?; let (_, s, k) = HEX_BOLT.iter().find(|r| r.0.eq_ignore_ascii_case(size)).copied().ok_or_else(|| need("ISO 4014"))?; - Shape::Screw { d, pitch, len: len(d), head: Head::Hex { s, k }, socket: None } + Shape::Screw { d, pitch: Some(pitch), len: len(d), head: Head::Hex { s, k }, socket: None } } "hex_nut" => { let (d, pitch) = metric(size).ok_or_else(|| need("metric"))?; let (_, s, m) = HEX_NUT.iter().find(|r| r.0.eq_ignore_ascii_case(size)).copied().ok_or_else(|| need("ISO 4032"))?; - Shape::Nut { d, pitch, s, m } + Shape::Nut { d, pitch: Some(pitch), s, m } + } + "hex_cap_screw_inch" => { + let (nominal, d, _) = unified(size).ok_or_else(|| need("UNC/UNF"))?; + let (_, f, h) = INCH_HEX_CAP.iter().find(|r| r.0 == nominal).copied().ok_or_else(|| need("ASME B18.2.1"))?; + Shape::Screw { + d, + pitch: None, + len: length.unwrap_or_else(|| default_inch_length(d)), + head: Head::Hex { s: f * INCH, k: h * INCH }, + socket: None, + } + } + "hex_nut_inch" => { + let (nominal, d, _) = unified(size).ok_or_else(|| need("UNC/UNF"))?; + let (_, f, h) = INCH_HEX_NUT.iter().find(|r| r.0 == nominal).copied().ok_or_else(|| need("ASME B18.2.2"))?; + Shape::Nut { d, pitch: None, s: f * INCH, m: h * INCH } + } + "washer_sae" | "washer_uss" => { + let table = if family == "washer_sae" { &WASHER_SAE } else { &WASHER_USS }; + let (_, d1, d2, h) = table.iter().find(|r| r.0 == size.trim()).copied().ok_or_else(|| need("ANSI B18.22.1"))?; + Shape::Ring { d_in: d1 * INCH, d_out: d2 * INCH, h: h * INCH } } "washer" => { let (_, d1, d2, h) = WASHER.iter().find(|r| r.0.eq_ignore_ascii_case(size)).copied().ok_or_else(|| need("ISO 7089"))?; @@ -390,12 +543,16 @@ fn build(s: &mut Session, sh: &Shape) -> Result<()> { if let Some((af, t)) = socket { hex(s, af, k, k - t, "cut")?; } - thread(s, d, pitch, Vec3::new(d / 2.0, 0.0, -len / 2.0)); + if let Some(p) = pitch { + thread(s, d, p, Vec3::new(d / 2.0, 0.0, -len / 2.0)); + } } Shape::Nut { d, pitch, s: af, m } => { hex(s, af, 0.0, m, "new")?; cyl(s, d, -1.0, m + 1.0, "cut")?; - thread(s, d, pitch, Vec3::new(d / 2.0, 0.0, m / 2.0)); + if let Some(p) = pitch { + thread(s, d, p, Vec3::new(d / 2.0, 0.0, m / 2.0)); + } } Shape::Ring { d_in, d_out, h } => { revolve(s, &[(d_in / 2.0, 0.0), (d_out / 2.0, 0.0), (d_out / 2.0, h), (d_in / 2.0, h)], "new")?; @@ -424,11 +581,26 @@ fn library(_s: &mut Session, p: &Value) -> Result { "set_screw" => SET_SCREW.iter().map(|r| json!({"size": r.0, "d": metric(r.0).map(|m| m.0), "pitch": metric(r.0).map(|m| m.1), "socket": r.1, "socket_depth": r.2})).collect(), "dowel_pin" => DOWEL.iter().map(|d| json!({"size": format!("{d}"), "d": d})).collect(), "bearing" => BEARINGS.iter().map(|r| json!({"size": r.0, "bore": r.1, "outer": r.2, "width": r.3})).collect(), + "hex_cap_screw_inch" => INCH_HEX_CAP + .iter() + .flat_map(|r| unified_sizes(r.0).into_iter().map(move |t| json!({"size": t.designation, "d": t.major_diameter, "pitch": t.pitch, "across_flats": r.1 * INCH, "head_height": r.2 * INCH}))) + .collect(), + "hex_nut_inch" => INCH_HEX_NUT + .iter() + .flat_map(|r| unified_sizes(r.0).into_iter().map(move |t| json!({"size": t.designation, "d": t.major_diameter, "pitch": t.pitch, "across_flats": r.1 * INCH, "height": r.2 * INCH}))) + .collect(), + "washer_sae" | "washer_uss" => { + let table = if id == "washer_sae" { &WASHER_SAE } else { &WASHER_USS }; + table.iter().map(|r| json!({"size": r.0, "inner": r.1 * INCH, "outer": r.2 * INCH, "thickness": r.3 * INCH})).collect() + } _ => Vec::new(), }; let (_, name, standard) = FAMILIES.iter().find(|f| f.0 == id).copied().unwrap_or(("", "", "")); - let lengths = - matches!(id, "socket_head_cap_screw" | "button_head_cap_screw" | "hex_bolt" | "set_screw" | "dowel_pin").then_some(LENGTHS.to_vec()); + let lengths = match id { + "socket_head_cap_screw" | "button_head_cap_screw" | "hex_bolt" | "set_screw" | "dowel_pin" => Some(LENGTHS.to_vec()), + "hex_cap_screw_inch" => Some(inch_lengths()), + _ => None, + }; if lengths.is_some() { for row in &mut sizes { let Some(size) = row.get("size").and_then(Value::as_str).map(str::to_string) else { continue }; @@ -438,7 +610,8 @@ fn library(_s: &mut Session, p: &Value) -> Result { } } } - json!({"family": id, "name": name, "standard": standard, "sizes": sizes, "lengths": lengths}) + let system = if is_inch(id) { "inch" } else { "metric" }; + json!({"family": id, "name": name, "standard": standard, "system": system, "sizes": sizes, "lengths": lengths}) }; match str_(p, "family") { Some(f) if FAMILIES.iter().any(|x| x.0 == f) => Ok(fam(f)), @@ -449,16 +622,17 @@ fn library(_s: &mut Session, p: &Value) -> Result { fn part_name(family: &str, size: &str, sh: &Shape) -> String { match sh { - Shape::Screw { len, .. } | Shape::Rod { len, .. } => format!("{} {size}x{len}", label(family)), + Shape::Screw { len, .. } | Shape::Rod { len, .. } => format!("{} {}", label(family), size_with_length(family, size, *len)), _ => format!("{} {size}", label(family)), } } -/// A standard part's part number and description: its standard and size (`ISO 4762 M6x20`), or -/// a bearing's designation, and the family's name with the size. +/// A standard part's part number and description: its standard and size (`ISO 4762 M6x20`, +/// `ASME B18.2.1 1/2-13 UNC x 2`, an inch washer with its series: `ANSI B18.22.1 1/2 N`), or a +/// bearing's designation, and the family's name with the size. fn identity(family: &str, size: &str, sh: &Shape) -> (String, String) { let size = match sh { - Shape::Screw { len, .. } | Shape::Rod { len, .. } => format!("{size}x{len}"), + Shape::Screw { len, .. } | Shape::Rod { len, .. } => size_with_length(family, size, *len), _ => size.to_string(), }; let standard = match family { @@ -469,10 +643,18 @@ fn identity(family: &str, size: &str, sh: &Shape) -> (String, String) { "washer" => "ISO 7089", "set_screw" => "ISO 4026", "dowel_pin" => "ISO 8734", + "hex_cap_screw_inch" => "ASME B18.2.1", + "hex_nut_inch" => "ASME B18.2.2", + "washer_sae" | "washer_uss" => "ANSI B18.22.1", + _ => "", + }; + let series = match family { + "washer_sae" => " N", + "washer_uss" => " W", _ => "", }; let name = FAMILIES.iter().find(|f| f.0 == family).map_or("Part", |f| f.1); - let part_number = if standard.is_empty() { size.clone() } else { format!("{standard} {size}") }; + let part_number = if standard.is_empty() { size.clone() } else { format!("{standard} {size}{series}") }; (part_number, format!("{name} {size}")) } @@ -503,6 +685,10 @@ fn label(family: &str) -> &'static str { "washer" => "Washer", "set_screw" => "Set Screw", "dowel_pin" => "Dowel Pin", + "hex_cap_screw_inch" => "Hex Cap Screw", + "hex_nut_inch" => "Hex Nut", + "washer_sae" => "SAE Washer", + "washer_uss" => "USS Washer", _ => "Bearing", } } @@ -780,6 +966,93 @@ mod tests { } } + /// #10316: ASME/ANSI inch hex cap screws, hex nuts and SAE/USS washers, tabled in inches and + /// built in millimetres, with sizes from the UNC/UNF thread catalogue and fractional-inch names. + #[test] + fn inch_parts_follow_the_asme_and_ansi_tables() { + const IN: f64 = 25.4; + let across_corners = |af: f64| af / (std::f64::consts::PI / 6.0).cos(); + let part_number = |s: &Session, out: &Value| { + let comp = out["component"].as_u64().unwrap_or(0); + s.doc.components.iter().find(|c| c.id == comp).and_then(|c| c.metadata.text(solidcraft_doc::metadata::PART_NUMBER)).map(str::to_string) + }; + // Every nominal size 1/4 to 1 but 9/16, coarse and fine. + let l = run(&mut Session::default(), "parts.library", json!({"family": "hex_cap_screw_inch"})); + let sizes: Vec<&str> = l["sizes"].as_array().map(|a| a.iter().filter_map(|x| x["size"].as_str()).collect()).unwrap_or_default(); + assert_eq!(sizes.len(), 18, "{sizes:?}"); + assert_eq!(sizes[..2], ["1/4-20 UNC", "1/4-28 UNF"]); + assert_eq!(sizes[16..], ["1-8 UNC", "1-12 UNF"]); + assert_eq!((l["standard"].as_str(), l["system"].as_str()), (Some("ASME B18.2.1"), Some("inch"))); + let all = run(&mut Session::default(), "parts.library", json!({})); + let inch: Vec<&str> = all["families"] + .as_array() + .map(|a| a.iter().filter(|f| f["system"] == "inch").filter_map(|f| f["family"].as_str()).collect()) + .unwrap_or_default(); + assert_eq!(inch, ["hex_cap_screw_inch", "hex_nut_inch", "washer_sae", "washer_uss"]); + let lengths: Vec = l["lengths"].as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default(); + assert_eq!((lengths.first().copied(), lengths.last().copied(), lengths.len()), (Some(0.5 * IN), Some(8.0 * IN), 19)); + // A 1/2-13 x 2 cap screw: 3/4 across flats, head 0.312 high, shank 2 in long, no thread mark. + let mut s = Session::default(); + let out = run(&mut s, "parts.insert", json!({"family": "hex_cap_screw_inch", "size": "1/2-13 UNC", "length": 2.0 * IN})); + assert_eq!(out["name"], "Hex Cap Screw 1/2-13 UNC x 2"); + assert_eq!(part_number(&s, &out).as_deref(), Some("ASME B18.2.1 1/2-13 UNC x 2")); + let (lo, hi) = bbox(&s, "Hex Cap Screw 1/2-13 UNC x 2"); + let w = (hi.x - lo.x).max(hi.y - lo.y); + assert!((w - across_corners(0.75 * IN)).abs() < 1e-6 && (lo.z + 2.0 * IN).abs() < 1e-6 && (hi.z - 0.312 * IN).abs() < 1e-6, "{lo:?} {hi:?}"); + assert!(s.model.state().threads.is_empty(), "solid.thread takes only metric designations (#9571)"); + // Its default length is the first standard length at or above 2.5 d: 1-1/4 for a 1/2. + let mut d = Session::default(); + assert_eq!( + run(&mut d, "parts.insert", json!({"family": "hex_cap_screw_inch", "size": "1/2-20 UNF"}))["name"], + "Hex Cap Screw 1/2-20 UNF x 1-1/4" + ); + // A 1/2-13 nut: 3/4 across flats, 0.438 thick, with the 1/2 in hole through it. + let mut n = Session::default(); + let out = run(&mut n, "parts.insert", json!({"family": "hex_nut_inch", "size": "1/2-13 UNC"})); + assert_eq!(part_number(&n, &out).as_deref(), Some("ASME B18.2.2 1/2-13 UNC")); + let (lo, hi) = bbox(&n, "Hex Nut 1/2-13 UNC"); + let (w, h) = ((hi.x - lo.x).max(hi.y - lo.y), hi.z - lo.z); + assert!((w - across_corners(0.75 * IN)).abs() < 1e-6 && (h - 0.438 * IN).abs() < 1e-6, "{w} {h}"); + // 1/2 washers: SAE 1.062 x 0.095, USS 1.375 x 0.109, the series in the part number. + for (family, label, od, t, number) in [ + ("washer_sae", "SAE Washer 1/2", 1.062, 0.095, "ANSI B18.22.1 1/2 N"), + ("washer_uss", "USS Washer 1/2", 1.375, 0.109, "ANSI B18.22.1 1/2 W"), + ] { + let mut w = Session::default(); + let out = run(&mut w, "parts.insert", json!({"family": family, "size": "1/2"})); + assert_eq!(part_number(&w, &out).as_deref(), Some(number)); + let (lo, hi) = bbox(&w, label); + assert!((hi.x - lo.x - od * IN).abs() < 1e-6 && (hi.z - lo.z - t * IN).abs() < 1e-6, "{family}: {lo:?} {hi:?}"); + } + // Resizing keeps it inch, and sizes the tables don't have are refused. + let r = run(&mut s, "parts.resize", json!({"component": "Hex Cap Screw 1/2-13 UNC x 2", "size": "3/8-16 UNC", "length": 1.0 * IN})); + assert_eq!(r["name"], "Hex Cap Screw 3/8-16 UNC x 1"); + for (family, size) in [ + ("hex_cap_screw_inch", "9/16-12 UNC"), + ("hex_cap_screw_inch", "#10-24 UNC"), + ("hex_cap_screw_inch", "M12"), + ("hex_cap_screw_inch", "1/2-20 UNC"), + ("hex_nut_inch", "1/2"), + ("washer_sae", "9/16"), + ("washer_uss", "1/2-13 UNC"), + ] { + assert!(Session::default().execute("parts.insert", &json!({"family": family, "size": size})).is_err(), "{family} {size}"); + } + } + + #[test] + fn inch_lengths_read_as_fractions() { + assert_eq!(super::part_length_label("hex_cap_screw_inch", 1.5 * 25.4).as_deref(), Some("1-1/2 in")); + assert_eq!(super::part_length_label("hex_cap_screw_inch", 0.75 * 25.4).as_deref(), Some("3/4 in")); + assert_eq!(super::part_length_label("hex_cap_screw_inch", 8.0 * 25.4).as_deref(), Some("8 in")); + // Off the 1/64 grid, or a metric family: shown as millimetres in the design's units. + assert_eq!(super::part_length_label("hex_cap_screw_inch", 20.0), None); + assert_eq!(super::part_length_label("socket_head_cap_screw", 25.4), None); + for bad in [f64::NAN, f64::INFINITY, -25.4, 0.0, 1e300] { + assert_eq!(super::part_length_label("hex_cap_screw_inch", bad), None, "{bad}"); + } + } + /// #7692: a button head cap screw (ISO 7380-1) takes the same parameters as a socket head /// cap screw, with a domed crown in place of the cylindrical head. #[test] @@ -958,6 +1231,10 @@ mod tests { ("set_screw", "M6", "M8"), ("dowel_pin", "6", "8"), ("bearing", "608", "6200"), + ("hex_cap_screw_inch", "1/2-13 UNC", "5/8-11 UNC"), + ("hex_nut_inch", "1/2-13 UNC", "5/8-18 UNF"), + ("washer_sae", "1/2", "5/8"), + ("washer_uss", "1/2", "5/8"), ] { let mut s = Session::default(); let part = run(&mut s, "parts.insert", json!({"family": family, "size": size})); diff --git a/crates/engine/src/cmd/patterns_tests.rs b/crates/engine/src/cmd/patterns_tests.rs index 9839dbcb3..42e458d22 100644 --- a/crates/engine/src/cmd/patterns_tests.rs +++ b/crates/engine/src/cmd/patterns_tests.rs @@ -246,27 +246,79 @@ fn circular_axis_origin_rejects_invalid_values_atomically() { run(&mut s, "parameters.add", json!({"name":"cy","expression":"25 mm"})); let before = s.doc.to_json(); let undo = s.undo.len(); - for origin in [ - json!(["cx", "cy", 0]), - json!(["50", 25, 0]), - json!([0, 0]), - json!([0, 0, 0, 0]), - json!(null), - json!(false), - json!({"x":0,"y":0}), - json!([1e9, 0, 0]), - json!([0, 1e100, 0]), - ] { - for (cmd, params) in [ - ("solid.pattern.circular", json!({"features":["Hole1"],"axis":{"origin":origin,"dir":[0,0,1]},"count":4})), - ("construct.plane.at_angle", json!({"base":"XY","axis":{"origin":origin,"dir":[1,0,0]},"angle":45})), - ] { - let error = s.execute(cmd, ¶ms).unwrap_err().to_string(); - assert!(error.contains("axis.origin") && error.contains("expressions are not supported"), "{error}"); - assert_eq!(s.doc.to_json(), before); - assert_eq!(s.undo.len(), undo); - } + let invalid = [json!([0, 0]), json!([0, 0, 0, 0]), json!(null), json!(false), json!({"x":0,"y":0}), json!([1e9, 0, 0]), json!([0, 1e100, 0])]; + // A circular pattern's origin takes length expressions (#10852); an angled plane's doesn't. + for origin in invalid.iter().chain(&[json!(["nope", 0, 0]), json!(["2 deg", 0, 0])]) { + let params = json!({"features":["Hole1"],"axis":{"origin":origin,"dir":[0,0,1]},"count":4}); + let error = s.execute("solid.pattern.circular", ¶ms).unwrap_err().to_string(); + assert!(error.contains("axis.origin"), "{origin}: {error}"); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.undo.len(), undo); } + for origin in invalid.iter().chain(&[json!(["cx", "cy", 0]), json!(["50", 25, 0])]) { + let params = json!({"base":"XY","axis":{"origin":origin,"dir":[1,0,0]},"angle":45}); + let error = s.execute("construct.plane.at_angle", ¶ms).unwrap_err().to_string(); + assert!(error.contains("axis.origin") && error.contains("expressions are not supported"), "{error}"); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.undo.len(), undo); + } +} + +/// #10852: a circular pattern about `{origin, dir}` with length expressions in the origin turns +/// about the point they give now, so the copies follow the parameters as the seed does. The +/// expressions are saved, renamed with their parameter, and can be set by `timeline.edit`. +#[test] +fn circular_axis_origin_expressions_follow_their_parameters() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name":"cx","expression":"50 mm"})); + run(&mut s, "parameters.add", json!({"name":"cy","expression":"40 mm"})); + // A 2 mm cube 20 mm from (cx, cy), turned about the vertical line there. + run(&mut s, "solid.box", json!({"length":2,"width":2,"height":2,"corner":["cx + 20 mm","cy",0],"body_name":"Cube"})); + run(&mut s, "solid.pattern.circular", json!({"bodies":["Cube"],"axis":{"origin":["cx","cy",0],"dir":[0,0,1]},"count":4})); + // The x and y extent of the four cubes: 22 mm either side of the axis while it is 20 mm away. + let span = |s: &Session| { + let st = s.model.state(); + assert_eq!(st.bodies.len(), 4); + let mut out = [f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY]; + for b in st.bodies.iter().filter_map(|mb| solidcraft_kernel::measure(&mb.body).ok()).map(|m| m.bbox) { + out = [out[0].min(b.min.x), out[1].max(b.max.x), out[2].min(b.min.y), out[3].max(b.max.y)]; + } + out + }; + let about_at = |s: &Session, x: f64, y: f64, half: f64| { + for (got, want) in span(s).into_iter().zip([x - half, x + half, y - half, y + half]) { + assert!((got - want).abs() < 1e-6, "{:?} is not {half} mm either side of ({x}, {y})", span(s)); + } + }; + let about = |s: &Session, x: f64, y: f64| about_at(s, x, y, 22.0); + // The origin as the pattern saves it. + let saved_origin = |s: &Session| match s.doc.features.last().map(|f| &f.kind) { + Some(solidcraft_doc::FeatureKind::Pattern { pattern, .. }) => serde_json::to_value(pattern).unwrap_or_default()["origin"].clone(), + other => panic!("not a pattern: {other:?}"), + }; + about(&s, 50.0, 40.0); + assert_eq!(saved_origin(&s), json!(["cx", "cy", 0.0]), "the expressions are saved"); + run(&mut s, "parameters.change", json!({"name":"cx","expression":"60 mm"})); + about(&s, 60.0, 40.0); + // Renaming a parameter renames it in the origin, and the pattern still follows it. + run(&mut s, "parameters.rename", json!({"name":"cy","new_name":"py"})); + run(&mut s, "parameters.change", json!({"name":"py","expression":"45 mm"})); + about(&s, 60.0, 45.0); + assert_eq!(saved_origin(&s), json!(["cx", "py", 0.0])); + let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap_or_else(|e| panic!("{e}"))); + about(&reopened, 60.0, 45.0); + // timeline.edit sets the origin as expressions too: 10 mm back, so the cube is 30 mm away. + let pattern = s.doc.features.last().map(|f| f.id).unwrap_or_default(); + run(&mut s, "timeline.edit", json!({"feature":pattern,"set":{"pattern.origin":["cx - 10 mm","py","0 mm"]}})); + about_at(&s, 50.0, 45.0, 32.0); + run(&mut s, "edit.undo", json!({})); + about(&s, 60.0, 45.0); + // Plain numbers are saved as numbers, as before. + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":2,"width":2,"height":2,"corner":[70,40,0],"body_name":"Cube"})); + run(&mut s, "solid.pattern.circular", json!({"bodies":["Cube"],"axis":{"origin":[50,40,0],"dir":[0,0,1]},"count":4})); + about(&s, 50.0, 40.0); + assert_eq!(saved_origin(&s), json!([50.0, 40.0, 0.0])); } #[test] diff --git a/crates/engine/src/cmd/section.rs b/crates/engine/src/cmd/section.rs index ebae74fa2..15fb8d92a 100644 --- a/crates/engine/src/cmd/section.rs +++ b/crates/engine/src/cmd/section.rs @@ -24,7 +24,7 @@ fn section(s: &mut Session, p: &Value) -> Result { if bool_(p, "clear").unwrap_or(false) { s.section = None; s.status_slot(crate::status_items::StatusId::Section, false); - s.revision += 1; + s.refresh_display(); return serde_json::to_value(contract::SectionResult { section: None, param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string())); } // A named plane's world axis: which component of a point lies along its normal. @@ -82,7 +82,7 @@ fn section(s: &mut Session, p: &Value) -> Result { s.section_hatch = bool_(p, "hatch").unwrap_or(true); s.status_slot(crate::status_items::StatusId::Section, true); s.status_activated(crate::status_items::StatusId::Section); - s.revision += 1; + s.refresh_display(); let section = contract::Section { origin: [origin.x, origin.y, origin.z], normal: [normal.x, normal.y, normal.z], diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs index dcb986257..ce74fff2c 100644 --- a/crates/engine/src/cmd/sheet.rs +++ b/crates/engine/src/cmd/sheet.rs @@ -56,7 +56,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .contract(&PERFORATE_CONTRACT) .output(output_schema_for::) .params( - "diameter, pitch: expr; margin?: expr (clear of edges, cut-outs and bends; default: the diameter); pattern?: staggered (60°, default) | square; body? - a perforation field over the whole flat sheet: holes in the flat pattern (perforations), the DXF (layer PERFORATION) and the measured volume, not cut into the B-rep (#732)", + "diameter, pitch: expr; margin?: expr (clear of edges, cut-outs, bends and the outline; default: the diameter); pattern?: staggered (60°, default) | square; body?; sketch? + profiles? (the outline: closed profiles of a sketch on a face of the sheet; holes only inside them, out of their inner loops) - a perforation field over the whole flat sheet or inside the outline: holes in the flat pattern (perforations), the DXF (layer PERFORATION) and the measured volume, not cut into the B-rep (#732)", ), CommandSpec::new("sheet.hem", "Hem", crate::checked!("sheet.hem", hem)) .at("SHEET METAL", "CREATE") @@ -472,7 +472,14 @@ fn perforate(s: &mut Session, p: &Value) -> Result { check_expr(s, m, Kind::Length, cmd, "margin")?; } let pattern = str_(p, "pattern").map(|t| perforation_pattern(t).map(str::to_string).map_err(|why| bad(cmd, why))).transpose()?; - add_feature(s, p, FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body: str_(p, "body").map(BodyName::from) }) + // The outline: only a sketch named here, never the active one. + let sketch = match p.get("sketch") { + Some(_) => Some(SketchId(feature_sketch(s, p, cmd)?)), + None if p.get("profiles").is_some() => return Err(bad(cmd, "`profiles` picks the outline's profiles: it needs `sketch`")), + None => None, + }; + let profiles = p.get("profiles").map(|_| profiles(p, cmd)).transpose()?; + add_feature(s, p, FeatureKind::SheetPerforate { diameter, pitch, margin, pattern, body: str_(p, "body").map(BodyName::from), sketch, profiles }) } fn hem(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/sheet_dxf_tests.rs b/crates/engine/src/cmd/sheet_dxf_tests.rs index 8a99ce6eb..26a736054 100644 --- a/crates/engine/src/cmd/sheet_dxf_tests.rs +++ b/crates/engine/src/cmd/sheet_dxf_tests.rs @@ -614,3 +614,59 @@ fn bend_lines_can_be_left_out_and_everything_put_on_layer_0() { assert!(s.execute("sheet.export_dxf", &bad).is_err(), "{bad}"); } } + +/// The DXF of a sheet folded across a curved outer outline has the curve as drawn, not arcs fitted +/// to it, and no seams where the fold cut it: the blank, with its bend line where the bend is. +#[test] +fn a_curved_outline_folded_across_stays_its_curve_in_the_dxf() { + let blanks: [(&str, &str, Value, &str); 3] = [ + ("circle", "sketch.circle.center", json!({"center": [0, 0], "radius": 50}), "CIRCLE"), + ("ellipse", "sketch.ellipse", json!({"center": [0, 0], "major": [80, 0], "minor_radius": 40}), "ELLIPSE"), + ( + "spline", + "sketch.spline.fit_point", + json!({"points": [[70, -5], [40, 40], [0, 40], [-50, 35], [-85, 0], [-40, -50], [0, -35], [35, -25]], "periodic": true}), + "SPLINE", + ), + ]; + for (name, id, p, kind) in blanks { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Blank"})); + run(&mut s, id, p); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sheet.flange", json!({"sketch": "Blank"})); + let flat_loops = loops(&s); + let area: f64 = flat_loops.iter().map(|l| l.signed_area().abs()).sum(); + run(&mut s, "sheet.fold", json!({"points": [[10, -200, 2.5], [10, 200, 2.5]]})); + let dxf = export(&mut s, json!({})); + let es = entities(&dxf); + assert!(count(&es, kind) >= 1, "{name}: no {kind}: {:?}", es.iter().map(|e| e.0.as_str()).collect::>()); + if kind != "CIRCLE" { + assert_eq!(count(&es, "ARC"), 0, "{name}: curves came back as fitted arcs"); + } + // The only straight line is the bend line, across the sheet on the zone's centre line. + let lines: Vec<&Entity> = es.iter().filter(|e| e.0 == "LINE").collect(); + assert_eq!(lines.len(), 1, "{name}: seams left in the outline"); + let (a, b) = (point(lines[0], 10), point(lines[0], 11)); + assert!((a.x - 10.0).abs() < 1e-6 && (b.x - 10.0).abs() < 1e-6, "{name}: bend line {a:?} to {b:?}"); + // The blank is the blank: as much of it as was drawn, exactly. + let after: f64 = loops(&s).iter().map(|l| l.signed_area().abs()).sum(); + assert!((after - area).abs() < 1e-6 * area, "{name}: {after} vs {area}"); + } +} + +/// A fold across the straight part of a curved outline keeps the curve as drawn as well: an arc +/// stays one arc, not the 0.001 mm chords a fold used to leave. +#[test] +fn a_curve_away_from_a_fold_stays_its_curve_in_the_dxf() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Blank"})); + run(&mut s, "sketch.line", json!({"points": [[0, 50], [-60, 50], [-60, -50], [0, -50]]})); + run(&mut s, "sketch.arc.three_point", json!({"start": [0, -50], "through": [50, 0], "end": [0, 50]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sheet.flange", json!({"sketch": "Blank"})); + run(&mut s, "sheet.fold", json!({"points": [[-20, -200, 2.5], [-20, 200, 2.5]]})); + let es = entities(&export(&mut s, json!({}))); + assert_eq!(count(&es, "ARC"), 1, "{:?}", es.iter().map(|e| e.0.as_str()).collect::>()); + assert!(count(&es, "LINE") < 12, "the arc went to chords: {} lines", count(&es, "LINE")); +} diff --git a/crates/engine/src/cmd/sheet_face_names_tests.rs b/crates/engine/src/cmd/sheet_face_names_tests.rs index 206c676d2..6b6500fed 100644 --- a/crates/engine/src/cmd/sheet_face_names_tests.rs +++ b/crates/engine/src/cmd/sheet_face_names_tests.rs @@ -115,3 +115,23 @@ fn a_flanges_sheet_names_hold_when_another_flange_goes() { assert!(solidcraft_doc::naming::named_face_point(&s.model.state(), None, &gone).is_err()); assert!(solidcraft_doc::naming::named_face_point(&s.model.state(), Some("Body2"), &right).is_err()); } + +/// A fold at 45° across a strip, with a bend zone wide for the strip: about a third of the bend's +/// faces lies beyond the ends of its start line, along the bend, and they still take its names. +#[test] +fn a_bend_askew_across_a_sheet_keeps_its_names() { + let mut s = Session::default(); + run(&mut s, "sheet.manage_rules", json!({"name": "R10", "thickness": "1 mm", "bend_radius": "10 mm", "active": true})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Strip"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [200, 20]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sheet.flange", json!({"sketch": "Strip"})); + run(&mut s, "sheet.fold", json!({"points": [[90, -5, 1], [115, 20, 1]], "fixed": [10, 10, 1]})); + let fold = s.doc.features.last().map_or(0, |f| f.id); + let all = faces(&mut s); + for (side, radius) in [("inner", 10.0), ("outer", 11.0)] { + let name = format!("sheet:Body1:F{fold}.0:bend.{side}"); + let f = named(&all, &name); + assert!(f.len() == 1 && f[0].2.is_some_and(|r| (r - radius).abs() < 1e-6), "{name}: {all:?}"); + } +} diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rs index 842d1f068..6eddeb7c4 100644 --- a/crates/engine/src/cmd/sheet_tests.rs +++ b/crates/engine/src/cmd/sheet_tests.rs @@ -3171,6 +3171,397 @@ fn fold_at_a_tab_root_names_the_real_cause() { run(&mut ok, "sheet.fold", json!({"points": [[40, 51, 0.8], [60, 51, 0.8]], "fixed": [50, 25, 0.8]})); } +/// The sheet of the folds across slanted edges below: 2 mm thick, R 1, K 0.4. +fn t2_blank(s: &mut Session, outline: Value) { + run(s, "sheet.manage_rules", json!({"name": "T2", "thickness": "2 mm", "bend_radius": "1 mm", "k_factor": "0.4", "active": true})); + run(s, "sketch.create", json!({"plane": "XY", "name": "Blank"})); + run(s, "sketch.line", json!({"points": outline, "closed": true})); + run(s, "sketch.finish", json!({})); + run(s, "sheet.flange", json!({"sketch": "Blank"})); +} + +/// 160 long, 50 wide at x = 0 and 100 wide at x = 160: 12000 mm², and 75 wide at its midline. +fn t2_trapezoid(s: &mut Session) { + t2_blank(s, json!([[0, -25], [160, -50], [160, 50], [0, 25]])); +} + +/// A point on `t2_trapezoid`'s lower slanted side, on the sheet's top. +fn t2_slant(x: f64) -> [f64; 3] { + [x, -25.0 - 25.0 * x / 160.0, 2.0] +} + +/// What the T2 sheet's flat pattern says it weighs. A bend of turn θ takes θ·(R + K·T) of the flat +/// and has θ·T·(R + T/2) of section, so it adds θ·T²·(½ − K) per mm across it; ruled ends keep the +/// zone's mean width at its centre line's length, however askew they are. +fn t2_volume_from_flat(f: &Value) -> f64 { + let area = |loops: &Value| -> f64 { + let ring = |l: &Value| { + let p: Vec<(f64, f64)> = + l.as_array().into_iter().flatten().map(|q| (q[0].as_f64().unwrap_or(f64::NAN), q[1].as_f64().unwrap_or(f64::NAN))).collect(); + (0..p.len()).map(|i| p[i].0 * p[(i + 1) % p.len()].1 - p[(i + 1) % p.len()].0 * p[i].1).sum::().abs() / 2.0 + }; + loops.as_array().into_iter().flatten().map(ring).sum() + }; + let bends: f64 = f["bends"] + .as_array() + .into_iter() + .flatten() + .map(|b| b["angle_deg"].as_f64().unwrap_or(f64::NAN).to_radians() * 0.4 * b["length"].as_f64().unwrap_or(f64::NAN)) + .sum(); + (area(&f["outline"]) - area(&f["cutouts"])) * 2.0 + bends +} + +/// The midline of a trapezoid crosses its slanted sides: the bend zone isn't square across, and +/// the sheet keeps its real outline (#10621). +#[test] +fn a_fold_across_slanted_edges_keeps_the_sheets_outline() { + let zone = FRAC_PI_2 * 1.8; + let flat_volume = 12000.0 * 2.0; + let want = flat_volume + 75.0 * FRAC_PI_2 * 0.4; + // Both legs are as long, R + T + 80 - BA / 2 high when folded. + let (wide, narrow) = ([80.0 + zone / 2.0 - 3.0, 160.0], [0.0, 80.0 - zone / 2.0 + 3.0]); + for (name, fixed, x) in + [("no side named: the larger stays", None, wide), ("the wide end", Some([150, 0, 0]), wide), ("the narrow end", Some([10, 0, 0]), narrow)] + { + let mut s = Session::default(); + t2_trapezoid(&mut s); + let mut fold = json!({"points": [[80, -60, 2], [80, 60, 2]]}); + if let Some(p) = fixed { + fold["fixed"] = json!(p); + } + run(&mut s, "sheet.fold", fold); + let v = volume(&mut s); + assert!(rel(v, want) < 1e-5, "{name}: volume {v} vs {want}"); + let b = bbox(&mut s); + let at = |v: &Value| v.as_f64().unwrap_or(f64::NAN); + assert!((at(&b["min"][0]) - x[0]).abs() < 1e-6 && (at(&b["max"][0]) - x[1]).abs() < 1e-6, "{name}: {b}"); + assert!((at(&b["max"][2]) - (3.0 + 80.0 - zone / 2.0)).abs() < 1e-6, "{name}: {b}"); + let f = flat(&mut s); + assert!((at(&f["flat_size_mm"][0]) - 160.0).abs() < 1e-6 && (at(&f["flat_size_mm"][1]) - 100.0).abs() < 1e-6, "{name}: {f}"); + assert_eq!(f["cutouts"].as_array().map(Vec::len), Some(0), "{name}: the outline is the sheet's, not a trimmed rectangle: {f}"); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(1), "{name}: {f}"); + assert!((at(&f["bends"][0]["length"]) - 75.0).abs() < 1e-6 && (at(&f["bends"][0]["allowance"]) - zone).abs() < 1e-9, "{name}: {f}"); + assert!(rel(t2_volume_from_flat(&f), want) < 1e-9, "{name}: {f}"); + // Flat again it weighs the sheet it was, and it folds back the same. + run(&mut s, "sheet.unfold", json!({})); + let unfolded = volume(&mut s); + assert!(rel(unfolded, flat_volume) < 1e-9, "{name}: unfolded {unfolded}"); + run(&mut s, "sheet.refold", json!({})); + let refolded = volume(&mut s); + assert!(rel(refolded, v) < 1e-9, "{name}: refolded {refolded} vs {v}"); + } +} + +/// A fold across slanted edges leaves panels with their real outlines, so flanges and other folds +/// go on it as on any fold, before or after it. +#[test] +fn flanges_and_folds_go_on_a_sheet_folded_across_slanted_edges() { + let mid = json!({"points": [[80, -60, 2], [80, 60, 2]], "fixed": [150, 0, 0]}); + let wide = json!({"edges": [[160, 0, 2]], "height": 20}); + let slanted = json!({"edges": [t2_slant(120.0)], "height": 20}); + let flange = "sheet.flange"; + let fold = "sheet.fold"; + let cases: [(&str, Vec<(&str, &Value)>); 3] = [ + ("flange on the wide end after", vec![(fold, &mid), (flange, &wide)]), + ("flange on the wide end before", vec![(flange, &wide), (fold, &mid)]), + ("flange on the slanted side after", vec![(fold, &mid), (flange, &slanted)]), + ]; + let mut volumes = Vec::new(); + for (name, steps) in cases { + let mut s = Session::default(); + t2_trapezoid(&mut s); + for (id, p) in steps { + run(&mut s, id, p.clone()); + } + let (v, f) = (volume(&mut s), flat(&mut s)); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{name}: {f}"); + assert!(rel(v, t2_volume_from_flat(&f)) < 2e-5, "{name}: volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f)); + volumes.push(v); + } + // A flange beside the fold: the order doesn't matter. + assert!(rel(volumes[0], volumes[1]) < 1e-6, "{volumes:?}"); + + // A flange along the whole slanted side has its bend where the fold would cross: refused, + // for that reason, as on a rectangle. + let mut s = Session::default(); + t2_trapezoid(&mut s); + run(&mut s, flange, slanted.clone()); + match s.execute(fold, &mid) { + Ok(v) => panic!("the fold goes through the flange's bend: {v}"), + Err(e) => assert!(e.to_string().contains("a fold through a flange's bend"), "{e}"), + } + + // A second fold, 87.5 wide at x = 120 and square to the first, or askew across the same sides. + let mut s = Session::default(); + t2_trapezoid(&mut s); + run(&mut s, fold, mid.clone()); + run(&mut s, fold, json!({"points": [[120, -60, 2], [120, 60, 2]], "fixed": [150, 0, 0]})); + let want = 24000.0 + (75.0 + 87.5) * FRAC_PI_2 * 0.4; + let v = volume(&mut s); + assert!(rel(v, want) < 1e-5, "volume {v} vs {want}"); + let mut s = Session::default(); + t2_trapezoid(&mut s); + run(&mut s, fold, mid.clone()); + run(&mut s, fold, json!({"points": [[100, 60, 2], [140, -60, 2]], "fixed": [155, 0, 0]})); + let (v, f) = (volume(&mut s), flat(&mut s)); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{f}"); + assert!(rel(v, t2_volume_from_flat(&f)) < 2e-5, "volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f)); + + // Askew on the blank itself. + let mut s = Session::default(); + t2_trapezoid(&mut s); + run(&mut s, fold, json!({"points": [[60, 60, 2], [100, -60, 2]], "fixed": [155, 0, 0]})); + let (v, f) = (volume(&mut s), flat(&mut s)); + assert!(rel(v, t2_volume_from_flat(&f)) < 2e-5, "volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f)); +} + +/// Walls leaning at 70° close the trapezoid's corner on a slanted line, so a fold across the wide +/// end's wall crosses a slanted edge of a flange: the wall widens evenly up to its top, and the +/// bend with it (#10621). +#[test] +fn a_fold_across_a_flanges_slanted_end_folds() { + let lean = 70f64.to_radians(); + let walls = json!({"edges": [[160, 0, 2], t2_slant(120.0)], "height": 40, "angle": "70 deg"}); + // The wall's outer face, from where the wall alone reaches: its top's outer corner is the + // farthest out, its inner corner the highest. + let mut one = Session::default(); + t2_trapezoid(&mut one); + run(&mut one, "sheet.flange", json!({"edges": [[160, 0, 2]], "height": 40, "angle": "70 deg"})); + let b = bbox(&mut one); + let (x_out, z_in) = (b["max"][0].as_f64().unwrap_or(f64::NAN), b["max"][2].as_f64().unwrap_or(f64::NAN)); + let z_out = z_in - 2.0 * lean.cos(); + let mut lengths = Vec::new(); + for z in [14.0, 22.0, 30.0] { + let mut s = Session::default(); + t2_trapezoid(&mut s); + run(&mut s, "sheet.flange", walls.clone()); + let x = x_out - (z_out - z) / lean.tan(); + run(&mut s, "sheet.fold", json!({"points": [[x, -90.0, z], [x, 90.0, z]], "angle": "30 deg"})); + let (v, f) = (volume(&mut s), flat(&mut s)); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(3), "z {z}: {f}"); + assert!(rel(v, t2_volume_from_flat(&f)) < 2e-5, "z {z}: volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f)); + lengths.push(f["bends"][2]["length"].as_f64().unwrap_or(f64::NAN)); + } + let (rise, more) = (lengths[1] - lengths[0], lengths[2] - lengths[1]); + assert!(rise > 1e-3 && (rise - more).abs() < 1e-6, "{lengths:?}"); +} + +/// A blank whose outer outline is curved: `draw` makes it in a sketch, on the T2 sheet. +fn t2_curved_blank(s: &mut Session, draw: &[(&str, Value)], k: &str) { + run(s, "sheet.manage_rules", json!({"name": "T2", "thickness": "2 mm", "bend_radius": "1 mm", "k_factor": k, "active": true})); + run(s, "sketch.create", json!({"plane": "XY", "name": "Blank"})); + for (id, p) in draw { + run(s, id, p.clone()); + } + run(s, "sketch.finish", json!({})); + run(s, "sheet.flange", json!({"sketch": "Blank"})); +} + +/// A circle or an ellipse as the sheet's outer outline, folded at `x` off its centre. The bend +/// adds θ·T²·(½ − K) per mm of the zone's mean width, which is the material in the zone over BA: +/// for semi-axes a (across the fold) and b, the chord (b / a)·2√(a² − s²) over the zone. The bend +/// allowance sets how high the part that folds stands, so K shows there: compensation. +#[test] +fn a_fold_across_a_round_outer_outline_is_compensated() { + let circle = ("sketch.circle.center", json!({"center": [0, 0], "radius": 50})); + let ellipse = ("sketch.ellipse", json!({"center": [0, 0], "major": [80, 0], "minor_radius": 40})); + for (name, draw, a, b) in [("circle", circle, 50.0_f64, 50.0_f64), ("ellipse", ellipse, 80.0_f64, 40.0_f64)] { + for (x, k) in [(10.0_f64, 0.4_f64), (-20.0, 0.3), (10.0, 0.5)] { + let zone = FRAC_PI_2 * (1.0 + k * 2.0); + let integral = |s: f64| s * (a * a - s * s).sqrt() + a * a * (s / a).asin(); + let in_zone = (b / a) * (integral(x + zone / 2.0) - integral(x - zone / 2.0)); + let want = PI * a * b * 2.0 + FRAC_PI_2 * 4.0 * (0.5 - k) * in_zone / zone; + let mut s = Session::default(); + t2_curved_blank(&mut s, std::slice::from_ref(&draw), &k.to_string()); + run(&mut s, "sheet.fold", json!({"points": [[x, -200, 2], [x, 200, 2]], "fixed": [-(a - 1.0) * x.signum(), 0, 2]})); + let name = format!("{name} at x = {x}, K {k}"); + // The volume measure works on facets: a flat ellipse reads about 1e-4 low on its own. + let v = volume(&mut s); + assert!(rel(v, want) < 3e-4, "{name}: volume {v} vs {want}"); + // The part past the bend stands R + T + its flat length past the zone. + let leg = a - x.abs() - zone / 2.0; + let high = bbox(&mut s)["max"][2].as_f64().unwrap_or(f64::NAN); + assert!((high - (3.0 + leg)).abs() < 1e-3, "{name}: {high} high vs {}", 3.0 + leg); + // The flat pattern is the blank as drawn, the bend line on the zone's centre line. + let f = flat(&mut s); + let at = |v: &Value| v.as_f64().unwrap_or(f64::NAN); + // (The size is measured on 0.001 mm chords, so up to that short on each side.) + assert!((at(&f["flat_size_mm"][0]) - 2.0 * a).abs() < 2.5e-3 && (at(&f["flat_size_mm"][1]) - 2.0 * b).abs() < 2.5e-3, "{name}: {f}"); + let chord = 2.0 * b * (1.0 - (x / a).powi(2)).sqrt(); + assert!((at(&f["bends"][0]["length"]) - chord).abs() < 1e-3 && (at(&f["bends"][0]["allowance"]) - zone).abs() < 1e-9, "{name}: {f}"); + assert_eq!(f["cutouts"].as_array().map(Vec::len), Some(0), "{name}: {f}"); + run(&mut s, "sheet.unfold", json!({})); + let unfolded = volume(&mut s); + assert!(rel(unfolded, PI * a * b * 2.0) < 3e-4, "{name}: unfolded {unfolded}"); + run(&mut s, "sheet.refold", json!({})); + let refolded = volume(&mut s); + assert!(rel(refolded, v) < 1e-9, "{name}: refolded {refolded} vs {v}"); + } + } +} + +/// Any curve, not only conics: a closed spline, an open spline closed by a line, an arc with lines, +/// each folded where its curves cross the zone, then folded again. +#[test] +fn a_fold_crosses_any_curve_of_the_outer_outline() { + let spline = vec![( + "sketch.spline.fit_point", + json!({"points": [[70, -5], [40, 40], [0, 40], [-50, 35], [-85, 0], [-40, -50], [0, -35], [35, -25]], "periodic": true}), + )]; + let open = vec![ + ("sketch.spline.fit_point", json!({"points": [[-60, 0], [-30, 45], [10, 30], [60, 50]]})), + ("sketch.line", json!({"points": [[60, 50], [60, -30], [-60, -30], [-60, 0]]})), + ]; + let d_shape = vec![ + ("sketch.line", json!({"points": [[0, 50], [-60, 50], [-60, -50], [0, -50]]})), + ("sketch.arc.three_point", json!({"start": [0, -50], "through": [50, 0], "end": [0, 50]})), + ]; + for (name, draw, line_at) in [("closed spline", spline, 5.0), ("open spline and lines", open, 7.0), ("arc and lines", d_shape, 20.0)] { + let mut s = Session::default(); + t2_curved_blank(&mut s, &draw, "0.4"); + let flat_volume = volume(&mut s); + run(&mut s, "sheet.fold", json!({"points": [[line_at, -200, 2], [line_at, 200, 2]]})); + let (v, f) = (volume(&mut s), flat(&mut s)); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(1), "{name}: {f}"); + // The bend adds what it adds to the flat sheet, here on a centre line that varies little. + let gain = v - flat_volume; + let want = f["bends"][0]["length"].as_f64().unwrap_or(f64::NAN) * FRAC_PI_2 * 0.4; + assert!((gain - want).abs() < 0.03 * want + 1.5, "{name}: gained {gain} vs {want}"); + // Flat again it weighs what it did, and it folds back the same. + run(&mut s, "sheet.unfold", json!({})); + let unfolded = volume(&mut s); + assert!(rel(unfolded, flat_volume) < 3e-4, "{name}: unfolded {unfolded} vs {flat_volume}"); + run(&mut s, "sheet.refold", json!({})); + let refolded = volume(&mut s); + assert!(rel(refolded, v) < 1e-9, "{name}: refolded {refolded} vs {v}"); + // A second fold across the part that stayed, where the curves cross it too. + run(&mut s, "sheet.fold", json!({"points": [[line_at - 30.0, -200, 2], [line_at - 30.0, 200, 2]], "fixed": [line_at - 50.0, 0, 2]})); + let f = flat(&mut s); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{name}: second fold: {f}"); + } +} + +/// A curved outline with a hole across the zone: the bend adds what the material in the zone +/// holds, between the outline's chord and the hole's. +#[test] +fn a_cut_out_crosses_a_fold_across_a_round_outer_outline() { + let (r, hole, x, k) = (50.0_f64, 15.0_f64, 10.0_f64, 0.4_f64); + let zone = FRAC_PI_2 * (1.0 + k * 2.0); + let integral = |a: f64, s: f64| { + let s = s.clamp(-a, a); + s * (a * a - s * s).sqrt() + a * a * (s / a).asin() + }; + let in_zone = integral(r, x + zone / 2.0) - integral(r, x - zone / 2.0) - (integral(hole, zone / 2.0) - integral(hole, -zone / 2.0)); + let want = PI * (r * r - hole * hole) * 2.0 + FRAC_PI_2 * 4.0 * (0.5 - k) * in_zone / zone; + let mut s = Session::default(); + t2_curved_blank(&mut s, &[("sketch.circle.center", json!({"center": [0, 0], "radius": r}))], "0.4"); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Hole"})); + run(&mut s, "sketch.circle.center", json!({"center": [x, 0], "radius": hole})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Hole", "distance": 20, "direction": "symmetric", "operation": "cut", "targets": ["Body1"]})); + run(&mut s, "sheet.fold", json!({"points": [[x, -200, 2], [x, 200, 2]], "fixed": [-49, 0, 2]})); + let v = volume(&mut s); + assert!(rel(v, want) < 3e-4, "volume {v} vs {want}"); + let f = flat(&mut s); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "the hole parts the bend line: {f}"); +} + +/// Curves away from the zone stay curves too, and a flange still goes on either side of a fold +/// across the straight part of a curved outline (the side with the arc gives way to chords). +#[test] +fn flanges_go_on_a_curved_outline_folded_across_its_straight_part() { + let d_shape = vec![ + ("sketch.line", json!({"points": [[0, 50], [-60, 50], [-60, -50], [0, -50]]})), + ("sketch.arc.three_point", json!({"start": [0, -50], "through": [50, 0], "end": [0, 50]})), + ]; + let fold = json!({"points": [[-20, -200, 2], [-20, 200, 2]], "fixed": [-50, 0, 2]}); + // The side that stays is square; the arc goes up with the side that folds. + let mut s = Session::default(); + t2_curved_blank(&mut s, &d_shape, "0.4"); + run(&mut s, "sheet.fold", fold.clone()); + run(&mut s, "sheet.flange", json!({"edges": [[-60, 0, 2]], "height": 20})); + let (v, f) = (volume(&mut s), flat(&mut s)); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{f}"); + assert!(rel(v, t2_volume_from_flat(&f)) < 3e-4, "volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f)); + // The side with the arc stays; the flange goes on the square side that folded. + let mut s = Session::default(); + t2_curved_blank(&mut s, &d_shape, "0.4"); + run(&mut s, "sheet.fold", json!({"points": [[-20, -200, 2], [-20, 200, 2]], "fixed": [40, 0, 2]})); + let high = bbox(&mut s)["max"][2].as_f64().unwrap_or(f64::NAN); + run(&mut s, "sheet.flange", json!({"edges": [[-20.0 + FRAC_PI_2 * 0.9 - 3.0, 0, high]], "height": 20})); + let (v, f) = (volume(&mut s), flat(&mut s)); + assert_eq!(f["bends"].as_array().map(Vec::len), Some(2), "{f}"); + assert!(rel(v, t2_volume_from_flat(&f)) < 3e-4, "volume {v} vs the flat's {}: {f}", t2_volume_from_flat(&f)); +} + +/// A sharp corner in the zone stays refused, by name: the material beside it wouldn't hang from +/// anything. A fold clear of it, on the same outline, folds. Where the lines run smoothly into the +/// arc is no corner. +#[test] +fn a_corner_of_a_curved_outline_in_the_zone_is_named() { + let stepped = vec![ + ("sketch.line", json!({"points": [[0, 50], [-20, 50], [-20, 30], [-60, 30], [-60, -30], [-20, -30], [-20, -50], [0, -50]]})), + ("sketch.arc.three_point", json!({"start": [0, -50], "through": [50, 0], "end": [0, 50]})), + ]; + let mut s = Session::default(); + t2_curved_blank(&mut s, &stepped, "0.4"); + match s.execute("sheet.fold", &json!({"points": [[-20, -200, 2], [-20, 200, 2]], "fixed": [40, 0, 2]})) { + Ok(v) => panic!("the zone holds the corners at x = -20: {v}"), + Err(e) => assert!(e.to_string().contains("corner of the sheet's outline"), "{e}"), + } + run(&mut s, "sheet.fold", json!({"points": [[0, -200, 2], [0, 200, 2]], "fixed": [40, 0, 2]})); +} + +/// A circle or an ellipse cut out across a fold that crosses slanted edges, before the fold or in +/// the flat after it: the outline's edges and the cut-out's both cross the bend. +#[test] +fn round_cut_outs_cross_a_fold_across_slanted_edges() { + let zone = FRAC_PI_2 * 1.8; + let fold = json!({"points": [[80, -60, 2], [80, 60, 2]], "fixed": [150, 0, 0]}); + let cut = |s: &mut Session, draw: &(&str, Value)| { + run(s, "sketch.create", json!({"plane": "XY", "name": "Hole"})); + run(s, draw.0, draw.1.clone()); + run(s, "sketch.finish", json!({})); + run(s, "solid.extrude", json!({"sketch": "Hole", "distance": 20, "direction": "symmetric", "operation": "cut", "targets": ["Body1"]})); + }; + let circle = ("sketch.circle.center", json!({"center": [80, 0], "radius": 15})); + let ellipse = ("sketch.ellipse", json!({"center": [80, 0], "major": [100, 0], "minor_radius": 10})); + for (name, draw, a, b) in [("circle", circle, 15.0_f64, 15.0_f64), ("ellipse", ellipse, 20.0_f64, 10.0_f64)] { + // What it takes out of the zone: its chord (b / a)·2√(a² − s²) across s in ±BA / 2. + let h = zone / 2.0; + let in_zone = 2.0 * (b / a) * (h * (a * a - h * h).sqrt() + a * a * (h / a).asin()); + let flat_volume = (12000.0 - PI * a * b) * 2.0; + let want = flat_volume + (75.0 - in_zone / zone) * FRAC_PI_2 * 0.4; + + let mut before = Session::default(); + t2_trapezoid(&mut before); + cut(&mut before, &draw); + run(&mut before, "sheet.fold", fold.clone()); + let v = volume(&mut before); + assert!(rel(v, want) < 1e-5, "{name}: volume {v} vs {want}"); + // One cut-out, and the centre line in two pieces either side of it. + let f = flat(&mut before); + assert_eq!(f["cutouts"].as_array().map(Vec::len), Some(1), "{name}: {f}"); + let bends = f["bends"].as_array().cloned().unwrap_or_default(); + let length: f64 = bends.iter().map(|b| b["length"].as_f64().unwrap_or(f64::NAN)).sum(); + assert!(bends.len() == 2 && (length - (75.0 - 2.0 * b)).abs() < 1e-3, "{name}: {f}"); + run(&mut before, "sheet.unfold", json!({})); + // A round hole's volume is measured on its facets: 0.235 mm³ over for this circle, as on + // a plain rectangle. + let unfolded = volume(&mut before); + assert!(rel(unfolded, flat_volume) < 2e-5, "{name}: unfolded {unfolded} vs {flat_volume}"); + + let mut after = Session::default(); + t2_trapezoid(&mut after); + run(&mut after, "sheet.fold", fold.clone()); + run(&mut after, "sheet.unfold", json!({})); + cut(&mut after, &draw); + run(&mut after, "sheet.refold", json!({})); + let refolded = volume(&mut after); + assert!(rel(refolded, want) < 1e-5, "{name}: refolded {refolded} vs {want}"); + } +} + /// #296: two bends meeting at an open corner relief touch only along an edge, so the folded /// material the machining guard checks must not be sewn into one solid. #[test] @@ -5302,6 +5693,102 @@ fn perforate_supports_a_square_pattern_and_refuses_impossible_values() { } } +/// The hole centres `staggered_count` counts, over the box (x0, y0)..(x1, y1). +fn staggered_centres(x0: f64, y0: f64, x1: f64, y1: f64, d: f64, pitch: f64, margin: f64) -> Vec<(f64, f64)> { + let (clear, dy) = (d / 2.0 + margin, pitch * 3f64.sqrt() / 2.0); + let mut out = Vec::new(); + let mut row = 0; + while y0 + clear + row as f64 * dy <= y1 - clear + 1e-9 { + let mut x = x0 + clear + if row % 2 == 1 { pitch / 2.0 } else { 0.0 }; + while x <= x1 - clear + 1e-9 { + out.push((x, y0 + clear + row as f64 * dy)); + x += pitch; + } + row += 1; + } + out +} + +/// A 100 x 60 x 0.8 sheet with a sketch on its face: a 50 x 30 rectangle at (10, 10) with a Ø10 circle at (35, 25). +fn sheet_with_a_field_outline(s: &mut Session) { + outline_blank(s, json!([[0, 0], [100, 0], [100, 60], [0, 60]])); + run(s, "sketch.create", json!({"plane": "XY", "name": "Field"})); + run(s, "sketch.rectangle.two_point", json!({"p0": [10, 10], "p1": [60, 40]})); + run(s, "sketch.circle.center", json!({"center": [35, 25], "radius": 5})); + run(s, "sketch.finish", json!({})); +} + +/// #732: a sketch bounds the field. The ring of the rectangle less the circle takes Rv 1.0-1.5 only inside it, margin +/// clear of both its loops, on the grid from the outline's lower-left corner; an edit without a sketch keeps it. +#[test] +fn perforation_outline_bounds_the_field_and_keeps_out_its_inner_loops() { + let mut s = Session::default(); + sheet_with_a_field_outline(&mut s); + let made = + run(&mut s, "sheet.perforate", json!({"diameter": "1", "pitch": "1.5", "margin": "1", "sketch": "Field", "profiles": [{"point": [15, 15]}]})); + let expected: Vec<(f64, f64)> = + staggered_centres(10.0, 10.0, 60.0, 40.0, 1.0, 1.5, 1.0).into_iter().filter(|&(x, y)| (x - 35.0).hypot(y - 25.0) >= 6.5).collect(); + assert_eq!(flat(&mut s)["perforations"][0]["count"].as_u64(), Some(expected.len() as u64)); + let dxf = run(&mut s, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap_or_default().to_string(); + let holes = perforation_circles(&dxf); + assert_eq!(holes.len(), expected.len()); + assert!((holes[0].0 - 11.5).abs() < 1e-9 && (holes[0].1 - 11.5).abs() < 1e-9, "first hole at the outline's corner: {:?}", holes[0]); + assert!(holes.iter().all(|&(x, y, _)| (11.5 - 1e-9..=58.5 + 1e-9).contains(&x) && (11.5 - 1e-9..=38.5 + 1e-9).contains(&y))); + assert!(holes.iter().all(|&(x, y, _)| (x - 35.0).hypot(y - 25.0) >= 6.5 - 1e-9), "no hole in or near the inner loop"); + let n = holes.len(); + run( + &mut s, + "timeline.redefine", + json!({"feature": made["feature"], "command": "sheet.perforate", "params": {"diameter": "1", "pitch": "1.5", "margin": "1"}}), + ); + assert_eq!(flat(&mut s)["perforations"][0]["count"].as_u64(), Some(n as u64), "the edit keeps the outline"); +} + +/// #732: on a folded sheet the outline goes through the panel its sketch lies on and stops there: an outline that +/// reaches past the bend puts no hole in the flange. A sketch on no face of the sheet is refused. +#[test] +fn perforation_outline_on_a_folded_sheet_stays_in_its_panel() { + let mut s = Session::default(); + outline_blank(&mut s, json!([[0, 0], [100, 0], [100, 60], [0, 60]])); + run(&mut s, "sheet.flange", json!({"edges": [[50, 0, 0.8]], "height": 20})); + for (name, z) in [("Top", 0.8), ("Above", 10.0)] { + run(&mut s, "sketch.create", json!({"plane": {"origin": [0, 0, z], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "name": name})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-50, -50], "p1": [150, 110]})); + run(&mut s, "sketch.finish", json!({})); + } + run(&mut s, "sheet.perforate", json!({"diameter": "1", "pitch": "1.5", "margin": "1", "sketch": "Top"})); + let zone = &flat(&mut s)["bend_zones"][0]; // [min x, max x, min y, max y] of the bend zone, flat coordinates + let top = zone[3].as_f64().unwrap_or(f64::NAN); + let dxf = run(&mut s, "sheet.export_dxf", json!({}))["dxf"].as_str().unwrap_or_default().to_string(); + let holes = perforation_circles(&dxf); + assert!(!holes.is_empty()); + assert!(holes.iter().all(|&(_, y, r)| y - r - 1.0 >= top - 1e-9), "every hole is in the base, beyond the bend zone's y {top}"); + let refused = s.execute("sheet.perforate", &json!({"diameter": "1", "pitch": "1.5", "sketch": "Above"})); + assert!(refused.is_err_and(|e| e.to_string().contains("must lie on a face of the sheet"))); +} + +/// #732: a mirrored copy's bounded field is the mirror image of its source's. +#[test] +fn a_mirrored_sheet_copy_mirrors_its_perforation_outline() { + let mut s = Session::default(); + sheet_with_a_field_outline(&mut s); + run(&mut s, "sheet.perforate", json!({"diameter": "1", "pitch": "1.5", "margin": "1", "sketch": "Field", "profiles": [{"point": [15, 15]}]})); + run(&mut s, "solid.mirror", json!({"bodies": ["Body1"], "plane": "YZ"})); + let holes = |s: &mut Session, body: &str, sx: f64| -> Vec<(i64, i64)> { + let dxf = run(s, "sheet.export_dxf", json!({"body": body}))["dxf"].as_str().unwrap_or_default().to_string(); + let c = perforation_circles(&dxf); + // Relative to the field's own lower-left hole, x scaled by sx, rounded to 1e-6 mm. + let x0 = c.iter().map(|h| h.0 * sx).fold(f64::INFINITY, f64::min); + let y0 = c.iter().map(|h| h.1).fold(f64::INFINITY, f64::min); + let mut v: Vec<(i64, i64)> = c.iter().map(|h| (((h.0 * sx - x0) * 1e6).round() as i64, ((h.1 - y0) * 1e6).round() as i64)).collect(); + v.sort_unstable(); + v + }; + let original = holes(&mut s, "Body1", -1.0); + assert!(!original.is_empty()); + assert_eq!(holes(&mut s, "Body1 (2)", 1.0), original); +} + /// A 100 x 60 tray with one 45° flange 40 high on its y = 0 edge (2.5 mm, R 2.5, K 0.44), and on /// it a return 10 high when asked. Returns the far edge of the last panel in the flat pattern: /// the base starts at the setback s = (t + R)·tan 22.5°, each bend's zone is (π/4)·(R + K·t) long, @@ -5770,3 +6257,51 @@ fn an_unfolded_sheets_flat_face_is_named_after_its_base_at_every_size() { } } } + +/// A primitive cut passes over a sheet its exact box is clear of: that sheet comes back the very +/// same body, and the sheet the cut meets gets the hole. +#[test] +fn a_primitive_cut_passes_over_a_sheet_clear_of_it_by_its_exact_box() { + let mut s = Session::default(); + for (name, x) in [("Left", 0.0), ("Right", 100.2)] { + run(&mut s, "solid.box", json!({"corner": [x, 0, 0], "length": 100, "width": 60, "height": 2.5, "body_name": name})); + run(&mut s, "sheet.convert", json!({"body": name, "face": [x + 50.0, 30, 2.5]})); + } + let body = |s: &Session, name: &str| s.model.state().bodies.iter().find(|b| b.name == name).map(|b| b.body.clone()).unwrap(); + let left = body(&s, "Left"); + let right_volume = body_volume(&mut s, "Right"); + // 0.2 mm from the Left sheet's end: within the display mesh's tolerance of it, clear of its exact box. + run(&mut s, "solid.cylinder", json!({"base": [102.9, 30, -1], "radius": 2.5, "height": 5, "operation": "cut"})); + assert!(body(&s, "Left").same(&left), "the sheet clear of the cut is passed over"); + let holes = |s: &Session, name: &str| s.model.state().sheets.iter().find(|sh| sh.body == name).map(|sh| sh.holes.len()); + assert_eq!(holes(&s, "Left"), Some(0)); + assert_eq!(holes(&s, "Right"), Some(1)); + assert!((right_volume - body_volume(&mut s, "Right") - PI * 6.25 * 2.5).abs() < 1e-3); +} + +/// A cut that only grazes a bend's curved faces near the edge where the bend meets the base is +/// checked against the bend and refused (the sheet is unchanged); one clear of the bend's exact +/// box cuts the base. +#[test] +fn a_cut_grazing_a_bend_near_its_edge_is_refused_and_one_clear_of_its_exact_box_cuts() { + // `plate_with_flange`: the bend (R 2.5, T 2.5) runs from y = 0 to y = 5, where the base + // panel starts. + for (y0, grazes) in [(4.9, true), (5.1, false)] { + let mut s = Session::default(); + plate_with_flange(&mut s); + let v0 = volume(&mut s); + rectangle_tool(&mut s, "Slot", [40.0, y0], [60.0, 15.0]); + let cut = json!({"sketch": "Slot", "through_all": true, "direction": "symmetric", "operation": "cut"}); + if grazes { + let before = s.doc.to_json(); + let e = s.execute("solid.extrude", &cut).unwrap_err().to_string(); + assert!(e.contains("intersects a folded bend"), "{e}"); + assert_eq!(s.doc.to_json(), before); + assert_eq!(volume(&mut s), v0); + } else { + run(&mut s, "solid.extrude", cut); + assert!((v0 - volume(&mut s) - 20.0 * (15.0 - y0) * 2.5).abs() < 1e-3, "{}", v0 - volume(&mut s)); + assert_eq!(flat(&mut s)["cutouts"].as_array().map(Vec::len), Some(1)); + } + } +} diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index a67e905b1..5ac98bceb 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -867,6 +867,27 @@ pub fn tangent_arc_preview(sk: &Sketch, curve: &str, start: &str, end: Vec2) -> Some(out) } +/// The picked point, then any other point at the same place: a trimmed arc's end is its own +/// point, lying on the end of the curve that trimmed it, which is the one a click picks (#1485). +fn tangent_start_candidates(sk: &Sketch, picked: usize) -> Vec { + let at = sk.point(picked).unwrap_or_default(); + let tol = 1e-6 * at.len().max(1.0); + std::iter::once(picked).chain((0..sk.points.len()).filter(|&q| q != picked && sk.point(q).is_some_and(|x| x.dist(at) <= tol))).collect() +} + +/// The first drawn curve (and which of the candidate points) a tangent arc can leave from. +fn tangent_start_curve(sk: &Sketch, candidates: &[usize]) -> Option<(usize, usize)> { + candidates + .iter() + .find_map(|&q| sk.curves.iter().enumerate().find(|(i, c)| !c.construction && leaving_dir(sk, *i, q).is_some()).map(|(i, _)| (i, q))) +} + +/// Whether `sketch.arc.tangent` can start at sketch point `start` (an id such as `l1.end`): the +/// end of a drawn line, arc or spline there. A tool asks before taking the click (#10653). +pub fn tangent_arc_starts_at(sk: &Sketch, start: &str) -> bool { + sk.resolve_point(start).is_some_and(|picked| tangent_start_curve(sk, &tangent_start_candidates(sk, picked)).is_some()) +} + fn arc_tangent(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.arc.tangent"; // An id ends the arc on that point, so a chain can close; coordinates make a new point. @@ -881,14 +902,16 @@ fn arc_tangent(s: &mut Session, p: &Value) -> Result { (None, Some(at)) => (at, None), (None, None) => return Err(bad(cmd, "missing `end`")), }; + // A snapped place that is no point yet (`on:l3:…` on a line, `mid:l1` at its middle: a + // click between a line's ends) is no end to start from: said so, not as an unknown point + // (#10653). Point ids (`l1.end`, `p3`, `origin`) have no colon. + let not_an_end = || bad(cmd, "`start` must be the end point of a line or arc"); + if str_(p, "start").is_some_and(|start| start.contains(':')) { + return Err(not_an_end()); + } let st = req_parg(sk, doc, p, "start", cmd)?; - let picked = st.idx().ok_or_else(|| bad(cmd, "`start` must be the end point of a line or arc"))?; - // The picked point, then any other point at the same place: a trimmed arc's end is its own - // point, lying on the end of the curve that trimmed it, which is the one a click picks (#1485). - let at = st.pos(); - let tol = 1e-6 * at.len().max(1.0); - let candidates: Vec = - std::iter::once(picked).chain((0..sk.points.len()).filter(|&q| q != picked && sk.point(q).is_some_and(|x| x.dist(at) <= tol))).collect(); + let picked = st.idx().ok_or_else(not_an_end)?; + let candidates = tangent_start_candidates(sk, picked); let (ci, pi) = match str_(p, "curve") { Some(id) => { let ci = sk.curve_index(id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))?; @@ -899,10 +922,7 @@ fn arc_tangent(s: &mut Session, p: &Value) -> Result { .ok_or_else(|| bad(cmd, "`start` is not an end of that curve"))?; (ci, pi) } - None => candidates - .iter() - .find_map(|&q| sk.curves.iter().enumerate().find(|(i, c)| !c.construction && leaving_dir(sk, *i, q).is_some()).map(|(i, _)| (i, q))) - .ok_or_else(|| bad(cmd, "no line or arc ends at `start`"))?, + None => tangent_start_curve(sk, &candidates).ok_or_else(|| bad(cmd, "no line or arc ends at `start`"))?, }; let t = leaving_dir(sk, ci, pi).ok_or_else(|| bad(cmd, "`start` is not an end of that curve"))?; let s0 = st.pos(); diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index 27c18df96..f2484ae8b 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -60,7 +60,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("trim") .key("T") .enabled(in_sketch) - .params(concat!("curve: id, at: [x,y] (the piece to remove: between the nearest intersections around it)", created_doc!())), + .params(concat!("curve: id, at: [x,y] (the piece to remove: between the nearest intersections around it). Trimming a line source releases its dependent straight offsets' linked extents (offset_released: curve ids), retaining their driving normal-distance dimensions and parallel relations", created_doc!())), CommandSpec::new("sketch.trim.path", "Trim Along Path", trim_path) .icon("trim") .enabled(in_sketch) @@ -409,13 +409,103 @@ fn trim(s: &mut Session, p: &Value) -> Result { let at = req_vec2(cmd, p, "at")?; let (out, info) = edit(s, p, cmd, false, |sk, doc| { let ci = curve_arg(sk, p, cmd)?; - let (out, _) = remove_piece(sk, ci, at, cmd)?; + let released = release_source_line_offsets(sk, doc, ci, cmd)?; + let (mut out, _) = remove_piece(sk, ci, at, cmd)?; + if !released.is_empty() { + out["offset_released"] = json!(released); + } doc.prune_model_params(); Ok(out) })?; Ok(json!({"result": out, "sketch": info})) } +/// A source line's endpoints may change independently of its parallel offsets. Materialize +/// the affected line chains before Trim, retaining their original driving distance parameters +/// as point-line dimensions. Directly trimming an associated output remains a separate command policy. +fn release_source_line_offsets(sk: &mut Sketch, doc: &solidcraft_doc::Document, ci: usize, cmd: &str) -> Result> { + let Some(curve) = sk.curves.get(ci) else { return Ok(Vec::new()) }; + if curve.infinite || sk.is_linked_curve(ci) || !matches!(curve.kind, CurveKind::Line { .. }) { + return Ok(Vec::new()); + } + let id = curve.id.clone(); + let affected: Vec = sk + .offsets + .iter() + .enumerate() + .filter_map(|(i, offset)| { + (offset.topology.is_none() + && offset.sources.iter().any(|(source, _)| source == &id) + && offset.sources.len() == offset.outputs.len() + && offset.sources.iter().zip(&offset.outputs).all(|((source, _), output)| { + [source, output] + .iter() + .all(|id| sk.curve_index(id).and_then(|ci| sk.curves.get(ci)).is_some_and(|c| matches!(c.kind, CurveKind::Line { .. }))) + })) + .then_some(i) + }) + .collect(); + if affected.is_empty() { + return Ok(Vec::new()); + } + let report = solve_current(sk, doc)?; + if !report.keeps_orientation() { + return Err(bad(cmd, report.failure(|_| "cannot trim a source with conflicting offset dimensions".into()))); + } + let mut released = Vec::new(); + for index in affected.into_iter().rev() { + let record = sk.offsets.remove(index); + let dimension = sk + .constraints + .iter() + .find(|c| { + matches!(&c.kind, + ConstraintKind::OffsetDistance { output, .. } if record.outputs.contains(output)) + }) + .cloned() + .ok_or_else(|| bad(cmd, "missing offset distance dimension"))?; + let value = match dimension.kind { + ConstraintKind::OffsetDistance { value, .. } => value, + _ => record.distance.abs(), + }; + sk.constraints.retain(|c| !matches!(&c.kind, ConstraintKind::OffsetDistance { output, .. } if record.outputs.contains(output))); + for output in &record.outputs { + let target = sk.curve_index(output).ok_or_else(|| bad(cmd, "missing offset line"))?; + let points = sk.curves.get(target).map(|c| c.kind.point_ids()).unwrap_or_default(); + for i in points { + if i != 0 + && sk.curves.iter().all(|c| !c.kind.uses(i) || record.outputs.contains(&c.id)) + && let Some(point) = sk.points.get_mut(i) + { + point.fixed = false; + } + } + } + for (index, ((source, _), output)) in record.sources.iter().zip(&record.outputs).enumerate() { + let source = sk.curve_index(source).ok_or_else(|| bad(cmd, "missing offset source"))?; + let target = sk.curve_index(output).ok_or_else(|| bad(cmd, "missing offset line"))?; + if !sk.constraints.iter().any(|c| { + matches!(c.kind, + ConstraintKind::Parallel { a, b } if (a == source && b == target) || (a == target && b == source)) + }) { + add_c(sk, ConstraintKind::Parallel { a: source, b: target })?; + } + let p = sk.curves.get(target).and_then(|c| c.kind.ends()).map(|ends| ends.0).ok_or_else(|| bad(cmd, "missing offset line endpoint"))?; + let kind = ConstraintKind::PointLineDistance { p, l: source, value }; + let id = sk.add_constraint(kind.clone(), dimension.param.clone())?; + if let Some(added) = sk.constraints.iter_mut().find(|c| c.id == id) { + let mut kept = dimension.clone(); + kept.id = if index == 0 { dimension.id.clone() } else { id }; + kept.kind = kind; + *added = kept; + } + } + released.extend(record.outputs); + } + released.sort(); + Ok(released) +} + /// Remove the piece of curve `ci` around `at`: between the nearest intersections on either /// side, or the whole curve when nothing crosses it. Returns what `sketch.trim` reports and the /// removed piece as a polyline. @@ -443,6 +533,21 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu return Ok((json!({"deleted": id}), removed)); } refuse_offset_ends(sk, ci, "trim", cmd)?; + // For parallel lines, any point on the output measures the same normal distance. + // Move an endpoint witness to the surviving piece before removing its old endpoint. + let witnesses: Vec = sk + .constraints + .iter() + .filter_map(|dimension| { + let ConstraintKind::PointLineDistance { p, l, .. } = dimension.kind else { return None }; + let ends = sk.curves.get(ci).and_then(|c| c.kind.ends())?; + let line = matches!(sk.curves.get(ci)?.kind, CurveKind::Line { .. }); + (line + && (p == ends.0 || p == ends.1) + && sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Parallel { a, b } if (a == ci && b == l) || (a == l && b == ci)))) + .then(|| dimension.id.clone()) + }) + .collect(); release_extent(sk, ci); let ts: Vec = cuts.iter().map(|c| c.0).collect(); let (pieces, pts) = split_at(sk, ci, &ts)?; @@ -477,6 +582,15 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu }; let keep: Vec = pieces.iter().copied().filter(|x| *x != gone).collect(); tie(sk, &keep)?; + if let Some((a, _)) = sk.curves.get(ci).and_then(|c| c.kind.ends()) { + for dimension in &mut sk.constraints { + if witnesses.contains(&dimension.id) + && let ConstraintKind::PointLineDistance { p, .. } = &mut dimension.kind + { + *p = a; + } + } + } let removed = sk.polyline(gone); sk.remove_curves(&[gone]); Ok((json!({"trimmed": id}), removed)) @@ -575,7 +689,14 @@ fn trim_path(s: &mut Session, p: &Value) -> Result { after = (si, t); // A piece trim refuses (a closed spline crossed once) stays as it was. let before = sk.clone(); - match remove_piece(sk, ci, q, cmd) { + let cut = release_source_line_offsets(sk, doc, ci, cmd).and_then(|released| { + let (mut out, gone) = remove_piece(sk, ci, q, cmd)?; + if !released.is_empty() { + out["offset_released"] = json!(released); + } + Ok((out, gone)) + }); + match cut { Ok((out, gone)) => { trimmed.push(out); removed.push(json!(gone.iter().map(|v| [v.x, v.y]).collect::>())); diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index 55c898cf9..9fa34117a 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -4151,6 +4151,27 @@ fn corner_tools_refuse_all_spatial_curves_with_an_unsupported_message() { } } +/// #10653: a tangent arc started on a line between its ends (`on:l1:…`, which a click there +/// gives) is refused as no end to start from, not as an unknown point; `tangent_arc_starts_at` +/// tells a tool which points it can start at. +#[test] +fn a_tangent_arc_starts_only_at_a_curves_end() { + let mut s = new_sketch(); + let line = ids(&run(&mut s, "sketch.line", json!({"points": [[5, 0], [15, 0]], "connect": false, "infer": false}))["curves"])[0].clone(); + let before = s.doc.to_json(); + let on = format!("on:{line}:10,0"); + for start in [on.clone(), format!("mid:{line}")] { + let err = s.execute("sketch.arc.tangent", &json!({"start": start, "end": [20, 10]})).map(|v| v.to_string()).unwrap_err().to_string(); + assert!(err.contains("`start` must be the end point of a line or arc") && !err.contains("unknown sketch point"), "{start}: {err}"); + assert_eq!(s.doc.to_json(), before); + } + let sk = sketch(&s); + assert!(crate::cmd::tangent_arc_starts_at(&sk, &format!("{line}.end"))); + assert!(crate::cmd::tangent_arc_starts_at(&sk, &format!("{line}.start"))); + assert!(!crate::cmd::tangent_arc_starts_at(&sk, &on)); + assert!(!crate::cmd::tangent_arc_starts_at(&sk, "origin"), "no curve ends at the origin here"); +} + /// `sketch.arc.tangent` ends on an existing point when `end` names it, so a chain can close, and /// makes a new point for coordinates as before (#9489). The preview is the arc the command draws. #[test] @@ -4482,3 +4503,148 @@ fn move_copy_drawn_wire_failures_leave_the_design_and_history_unchanged() { assert_eq!(s.doc.to_json(), original); assert_eq!((s.undo.len(), s.redo.len()), history); } + +/// A construction line and its two offsets each stop at their own crossing. Trimming one +/// must never shorten the others, whatever order the three curves are picked in. +#[test] +fn trim_source_then_two_offsets_independently_in_either_order() { + for order in [[0, 1, 2], [0, 2, 1]] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0,0],[40,40]], "construction": true, "connect": false, "infer": false, "ids": ["source"]})); + let out = run(&mut s, "sketch.offset", json!({"curves": ["source"], "distance": 2, "symmetric": true, "chain": false})); + let mut curves = vec!["source".to_string()]; + curves.extend(ids(&out["curves"])); + assert_eq!(curves.len(), 3); + run(&mut s, "sketch.line", json!({"points": [[-20,20],[60,20]], "connect": false, "infer": false})); + for picked in order { + let before = sketch(&s); + let geometry = |sk: &solidcraft_sketch::Sketch, id: &str| sk.shape(sk.curve_index(id).unwrap()).unwrap(); + let solidcraft_sketch::Shape::Line { a, b } = geometry(&before, &curves[picked]) else { panic!("line") }; + let r = run(&mut s, "sketch.trim", json!({"curve": curves[picked], "at": [a.x + 1.0, a.y + 1.0]})); + assert_eq!(r["sketch"]["solved"], true, "{order:?}: {r}"); + let after = sketch(&s); + let solidcraft_sketch::Shape::Line { a: start, b: end } = geometry(&after, &curves[picked]) else { panic!("line") }; + assert!((start.y - 20.0).abs() < 1e-6 && (start.x - (20.0 + a.x - a.y)).abs() < 1e-6, "{order:?}: {start:?}"); + assert!(end.dist(b) < 1e-6, "the far end stays put: {order:?}: {end:?} {b:?}"); + for (i, id) in curves.iter().enumerate().filter(|(i, _)| *i != picked) { + let solidcraft_sketch::Shape::Line { a: old_a, b: old_b } = geometry(&before, id) else { panic!("line") }; + let solidcraft_sketch::Shape::Line { a: new_a, b: new_b } = geometry(&after, id) else { panic!("line") }; + assert!(new_a.dist(old_a) < 1e-6 && new_b.dist(old_b) < 1e-6, "unpicked {i} changed in {order:?}: {old_a:?} -> {new_a:?}"); + } + run(&mut s, "edit.undo", json!({})); + assert_eq!( + serde_json::to_value(sketch(&s)).unwrap(), + serde_json::to_value(before).unwrap(), + "one undo restores the complete association" + ); + run(&mut s, "edit.redo", json!({})); + assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), serde_json::to_value(after).unwrap()); + } + } +} + +#[test] +fn trim_path_cuts_source_and_two_offsets_at_their_own_crossings() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0,0],[40,40]], "construction": true, "connect": false, "infer": false, "ids": ["source"]})); + let out = run(&mut s, "sketch.offset", json!({"curves": ["source"], "distance": 2, "symmetric": true, "chain": false})); + let mut curves = vec!["source".to_string()]; + curves.extend(ids(&out["curves"])); + run(&mut s, "sketch.line", json!({"points": [[-20,20],[60,20]], "connect": false, "infer": false})); + let before = s.doc.to_json(); + let path = json!({"points": [[4,5],[15,5],[-10,5]], "dry_run": true}); + let preview = run(&mut s, "sketch.trim.path", path); + assert_eq!(preview["trimmed"].as_array().unwrap().len(), 3, "{preview}"); + assert_eq!(s.doc.to_json(), before, "preview releases no stored associations or parameters"); + let r = run(&mut s, "sketch.trim.path", json!({"points": [[4,5],[15,5],[-10,5]]})); + assert_eq!(r["trimmed"], preview["trimmed"]); + assert!(r["skipped"].as_array().unwrap().is_empty(), "{r}"); + let sk = sketch(&s); + assert!(sk.offsets.is_empty()); + for id in curves { + let solidcraft_sketch::Shape::Line { a, .. } = sk.shape(sk.curve_index(&id).unwrap()).unwrap() else { panic!("line") }; + assert!((a.y - 20.0).abs() < 1e-6, "{id}: {a:?}"); + } + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before, "one undo restores all three lines and their associations"); +} + +#[test] +fn trim_whole_source_keeps_its_offsets_and_unrelated_associations() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0,0],[40,40]], "connect": false, "infer": false, "ids": ["source"]})); + let out = run(&mut s, "sketch.offset", json!({"curves": ["source"], "distance": 2, "symmetric": true, "chain": false})); + let outputs = ids(&out["curves"]); + run(&mut s, "sketch.line", json!({"points": [[100,100],[120,100]], "connect": false, "infer": false, "ids": ["unrelated"]})); + let other = run(&mut s, "sketch.offset", json!({"curves": ["unrelated"], "distance": 3, "chain": false})); + let before = sketch(&s); + let doc_before = s.doc.to_json(); + let r = run(&mut s, "sketch.trim", json!({"curve": "source", "at": [10,10]})); + assert_eq!(r["result"]["deleted"], "source"); + assert_eq!(r["sketch"]["solved"], true); + let sk = sketch(&s); + assert!(sk.curve_index("source").is_none()); + assert_eq!(sk.offsets.len(), 1); + for id in outputs { + assert_eq!(sk.polyline(sk.curve_index(&id).unwrap()), before.polyline(before.curve_index(&id).unwrap()), "{id}"); + } + let other_output = other["curves"][0].as_str().unwrap(); + assert_eq!(sk.offset_distance(other_output), Some(3.0)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), doc_before); +} + +#[test] +fn trim_keeps_offset_distances_driving_after_trims_drag_and_reopen() { + let verify = |s: &Session, distance: f64, parameter: &str| { + let state = s.world_state().unwrap(); + let sk = &state.sketch(1).unwrap().sketch; + let solidcraft_sketch::Shape::Line { a, b } = sk.shape(sk.curve_index("source").unwrap()).unwrap() else { panic!("source line") }; + let dir = (b - a).normalized().unwrap(); + for (id, sign) in [("l1", 1.0), ("l2", -1.0)] { + let solidcraft_sketch::Shape::Line { a: p, b: q } = sk.shape(sk.curve_index(id).unwrap()).unwrap() else { panic!("offset line") }; + assert!(dir.cross((q - p).normalized().unwrap()).abs() < 1e-6, "{id} is parallel"); + for point in [p, q] { + assert!((dir.cross(point - a) - sign * distance).abs() < 1e-6, "{id}: {point:?}, distance {distance}"); + } + } + assert!(s.doc.param(parameter).is_some(), "the original driving offset parameter remains"); + assert_eq!(sk.constraints.iter().filter(|c| c.param.as_deref() == Some(parameter)).count(), 2, "both sides retain their dimensions"); + assert!(state.sketch(1).unwrap().report.ok()); + }; + for reverse_outputs in [true, false] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points":[[0,0],[40,40]],"construction":true,"connect":false,"infer":false,"ids":["source"]})); + let out = run(&mut s, "sketch.offset", json!({"curves":["source"],"distance":2,"symmetric":true,"chain":false})); + let parameter = out["param"].as_str().unwrap().to_string(); + let cutter = + run(&mut s, "sketch.line", json!({"points":[[-20,20],[60,20]],"connect":false,"infer":false}))["curves"][0].as_str().unwrap().to_string(); + let order = if reverse_outputs { ["source", "l2", "l1"] } else { ["source", "l1", "l2"] }; + for id in order { + let sk = sketch(&s); + let solidcraft_sketch::Shape::Line { a, .. } = sk.shape(sk.curve_index(id).unwrap()).unwrap() else { panic!("line") }; + run(&mut s, "sketch.trim", json!({"curve":id,"at":[a.x+1.0,a.y+1.0]})); + verify(&s, 2.0, ¶meter); + } + // A second end trim must reattach the existing distance witness to the retained line. + let second_cutter = + run(&mut s, "sketch.line", json!({"points":[[-20,25],[60,25]],"connect":false,"infer":false}))["curves"][0].as_str().unwrap().to_string(); + for id in order { + let sk = sketch(&s); + let solidcraft_sketch::Shape::Line { a, .. } = sk.shape(sk.curve_index(id).unwrap()).unwrap() else { panic!("line") }; + run(&mut s, "sketch.trim", json!({"curve":id,"at":[a.x+1.0,a.y+1.0]})); + verify(&s, 2.0, ¶meter); + } + run(&mut s, "sketch.constraint.fix", json!({"entities":["source",cutter,second_cutter]})); + run(&mut s, "sketch.move_point", json!({"point":"l1.end","to":[55,25]})); + verify(&s, 2.0, ¶meter); + run(&mut s, "parameters.change", json!({"name":parameter,"expression":"3 mm"})); + verify(&s, 3.0, ¶meter); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + verify(&reopened, 3.0, ¶meter); + run(&mut reopened, "parameters.change", json!({"name":parameter,"expression":"4 mm"})); + verify(&reopened, 4.0, ¶meter); + run(&mut reopened, "edit.undo", json!({})); + verify(&reopened, 3.0, ¶meter); + } +} diff --git a/crates/engine/src/cmd/sketch_project_tests.rs b/crates/engine/src/cmd/sketch_project_tests.rs index 7ae27da8f..1ee11a9cd 100644 --- a/crates/engine/src/cmd/sketch_project_tests.rs +++ b/crates/engine/src/cmd/sketch_project_tests.rs @@ -513,6 +513,77 @@ fn three_d_sketch_curves() { assert!((c["start_at"][0].as_f64().unwrap().abs() - 6.0).abs() < 1e-3, "{c}"); } +/// #9009: picked faces intersect as the viewport picks them, the whole surface patch, not just the +/// B-rep piece under the pick; a fit-point spline's wall is one face per span joined by hidden seams. +#[test] +fn intersection_curve_of_picked_faces_spans_the_whole_surface() { + use solidcraft_doc::project::resolve; + use solidcraft_geom::Plane; + use solidcraft_sketch::{LinkKind, LinkSource}; + use std::collections::BTreeMap; + + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "wall_h", "expression": "20 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Wave"})); + let wave = ids(&run(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 0], [9.5, 12], [30.5, 7], [52, 15]]}))["curves"])[0].clone(); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "surface.extrude", json!({"sketch": "Wave", "curves": [wave], "distance": "wall_h", "body_name": "Wall"})); + run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Roof"})); + // XZ sketch y is world -Z, so the arc peaks at world z = 15. + let arc = run(&mut s, "sketch.arc.three_point", json!({"start": [0, 0], "end": [50, 0], "through": [25, -15]}))["created"]["curves"][0] + .as_str() + .unwrap() + .to_string(); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "surface.extrude", json!({"sketch": "Roof", "curves": [arc], "distance": 30, "body_name": "Roof"})); + + let st = s.model.state(); + let wall = st.body("Wall").unwrap(); + let m = wall.mesh(); + assert!(wall.body.face_count() > 1, "premise of #9009: one face per spline span"); + assert_eq!(m.surface_patch(m.tri_face[0] as usize).len(), wall.body.face_count(), "premise: the spans are one surface patch (hidden seams)"); + // A pick on the middle span, away from the joins at x = 9.5 and x = 30.5. + let pick = + *m.positions.iter().min_by(|a, b| ((a.x - 20.).abs() + (a.z - 10.).abs()).total_cmp(&((b.x - 20.).abs() + (b.z - 10.).abs()))).unwrap(); + + let check = |s: &Session, id: u64| { + let st = s.model.state(); + let sk = &st.sketch(id).unwrap().sketch; + assert!(sk.links.iter().all(|l| !l.lost), "no link lost"); + let pts: Vec<_> = sk.wires.iter().flat_map(|w| w.pts.iter().copied()).collect(); + assert!(!pts.is_empty()); + let (lo, hi) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), p| (l.min(p.x), h.max(p.x))); + assert!(lo < 1.0 && hi > 49.0, "the whole crossing, not one span: x {lo}..{hi}"); + for p in &pts { + assert!((((p.x - 25.).powi(2) + (p.z + 40. / 3.).powi(2)).sqrt() - 85. / 3.).abs() < 0.1, "{p:?}"); + assert!(p.y > -1e-6 && p.y < 30. + 1e-6, "{p:?}"); + } + }; + + run(&mut s, "sketch.create", json!({"plane": "XY"})); + let id = s.active_sketch.unwrap(); + let r = run( + &mut s, + "sketch.intersection_curve", + json!({"a": {"face": [pick.x, pick.y, pick.z], "body": "Wall"}, "b": {"face": [25, 15, 15], "body": "Roof"}}), + ); + assert!(!r["wires"].as_array().unwrap().is_empty(), "{r}"); + check(&s, id); + + // The same as giving the two bodies. + let st = s.model.state(); + let body = |n: &str| Box::new(LinkSource::Body { body: n.to_string() }); + let whole = resolve(&s.doc, &BTreeMap::new(), &st, &Plane::XY, LinkKind::Include, &LinkSource::Intersection { a: body("Wall"), b: body("Roof") }) + .unwrap(); + let sk = &st.sketch(id).unwrap().sketch; + assert_eq!(sk.wires.len(), whole.wires.len()); + + // Editing the wall re-resolves the stored pick to the same patch. + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "parameters.change", json!({"name": "wall_h", "expression": "25 mm"})); + check(&s, id); +} + #[test] fn isoparametric_curves_of_a_cylinder() { let mut s = Session::default(); diff --git a/crates/engine/src/cmd/solid_move_copy_tests.rs b/crates/engine/src/cmd/solid_move_copy_tests.rs index 793817540..c9f5da037 100644 --- a/crates/engine/src/cmd/solid_move_copy_tests.rs +++ b/crates/engine/src/cmd/solid_move_copy_tests.rs @@ -181,3 +181,160 @@ fn an_older_design_with_no_copy_key_at_all_still_loads_and_moves_in_place() { let moved = state.body("Cube").unwrap(); assert!(moved.mesh().bounds().min.dist(Vec3::new(5.0, 0.0, 0.0)) < 1e-6); } + +/// A component `Part` holding a 20 mm cube at the origin, placed once at the root. +fn part_with_cube(s: &mut Session) -> (u64, u64) { + let made = run(s, "component.create", json!({"name": "Part", "grounded": false})); + cube20(s, "Peg"); + run(s, "component.activate", json!({"component": "root"})); + (made["component"].as_u64().unwrap(), made["occurrence"].as_u64().unwrap()) +} + +/// The component an occurrence is an instance of. +fn component_of(s: &Session, occurrence: u64) -> u64 { + s.doc.occurrences.iter().find(|o| o.id == occurrence).expect("the occurrence exists").component +} + +/// The lowest corner of the first body a placement shows, in the world. +fn world_min(s: &Session, path: &[u64]) -> Vec3 { + let names = s.occurrence_bodies(path, true).unwrap(); + s.world_state().unwrap().body(&names[0]).unwrap().mesh().bounds().min +} + +#[test] +fn copying_a_picked_component_makes_an_independent_component_at_the_moved_place() { + let mut s = Session::default(); + let (part, occurrence) = part_with_cube(&mut s); + let before = s.doc.clone(); + let source = world_min(&s, &[occurrence]); + let reply = run(&mut s, "solid.move", json!({"bodies": [], "occurrences": [[occurrence]], "copy": true, "translate": [50, 0, 0]})); + let copy = reply["occurrences"][0].as_u64().expect("the move reports the copy it made"); + let copied = component_of(&s, copy); + assert_ne!(copied, part, "an independent copy of the component, not another instance of it"); + let name = &s.doc.components.iter().find(|c| c.id == copied).expect("the copy is a component").name; + assert_eq!(name, "Part (2)", "named the way Paste New names its copies"); + assert!(world_min(&s, &[copy]).dist(Vec3::new(source.x + 50.0, source.y, source.z)) < 1e-6, "the copy lands at the moved place"); + assert!(world_min(&s, &[occurrence]).dist(source) < 1e-6, "the original component stays where it was"); + assert_eq!(s.occurrence_bodies(&[occurrence], true).unwrap().len(), 1, "the original keeps its body"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, before, "one undo removes the copy"); +} + +#[test] +fn a_copied_component_turns_with_the_move() { + let mut s = Session::default(); + let (_, occurrence) = part_with_cube(&mut s); + let reply = run( + &mut s, + "solid.move", + json!({"bodies": [], "occurrences": [[occurrence]], "copy": true, "translate": [0, 0, 0], "axis": [0, 0, 1], "angle": "90 deg"}), + ); + let copy = reply["occurrences"][0].as_u64().unwrap(); + // A quarter turn about the origin takes the cube's x from 0..20 to -20..0 and y to 0..20. + assert!(world_min(&s, &[copy]).dist(Vec3::new(-20.0, 0.0, 0.0)) < 1e-6, "the copy turns with the move"); + assert!(world_min(&s, &[occurrence]).dist(Vec3::ZERO) < 1e-6, "the original does not turn"); +} + +#[test] +fn bodies_and_a_component_copied_together_are_one_undo_step() { + let mut s = Session::default(); + let (_, occurrence) = part_with_cube(&mut s); + cube20_at(&mut s, "Top", [0, 0, 50]); + let before = s.doc.clone(); + let count = s.model.state().bodies.len(); + let reply = run(&mut s, "solid.move", json!({"bodies": ["Top"], "occurrences": [[occurrence]], "copy": true, "translate": [50, 0, 0]})); + assert_eq!(reply["occurrences"].as_array().map(Vec::len), Some(1)); + assert!(reply.get("feature").is_some(), "the reply is a solid.move reply: the body feature's, with the copies alongside"); + assert_eq!(s.model.state().bodies.len(), count + 2, "a copy of the body and of the component"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, before, "one undo removes both copies"); +} + +/// A copying move of a component and of bodies in differently turned frames (a block in the root +/// and a screw inserted lying down) is one move: the component's copy turns with it, the bodies +/// split into one feature per frame as a move of them alone does (#9660), in one undo step. +#[test] +fn a_copied_component_and_bodies_in_differently_turned_frames_are_one_undo_step() { + let mut s = Session::default(); + let (_, occurrence) = part_with_cube(&mut s); + run(&mut s, "solid.box", json!({"length": 30, "width": 30, "height": 10, "center": [0, 0, 5], "body_name": "Block"})); + run( + &mut s, + "parts.insert", + json!({"family": "socket_head_cap_screw", "size": "M3", "length": 12, "point": [0, 0, 10], "direction": [1, 0, 0], "name": "screw"}), + ); + let before = s.doc.clone(); + let reply = run( + &mut s, + "solid.move", + json!({"bodies": ["Block", "Body1"], "occurrences": [[occurrence]], "copy": true, "axis": [0, 0, 1], "angle": "90 deg"}), + ); + assert_eq!(reply["features"].as_array().map(Vec::len), Some(2), "one Move feature per frame"); + let copy = reply["occurrences"][0].as_u64().expect("the move reports the copy it made"); + assert!(world_min(&s, &[copy]).dist(Vec3::new(-20.0, 0.0, 0.0)) < 1e-6, "the copy turns with the move"); + assert!(world_min(&s, &[occurrence]).dist(Vec3::ZERO) < 1e-6, "the original does not turn"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc, before, "one undo removes the copies of the component and of the bodies"); +} + +#[test] +fn a_component_picked_with_its_parent_is_copied_once_inside_the_parents_copy() { + let mut s = Session::default(); + // `Outer` at the root holds `Inner`, which holds a 20 mm cube. + let outer = run(&mut s, "component.create", json!({"name": "Outer", "grounded": false}))["occurrence"].as_u64().unwrap(); + let inner = run(&mut s, "component.create", json!({"name": "Inner", "parent": "Outer"}))["occurrence"].as_u64().unwrap(); + cube20(&mut s, "Peg"); + run(&mut s, "component.activate", json!({"component": "root"})); + let counts = |s: &Session| (s.doc.components.len(), s.doc.occurrences.len(), s.model.state().bodies.len()); + assert_eq!(counts(&s), (2, 2, 1), "components, occurrences and bodies before the move"); + let before = s.doc.clone(); + let source = world_min(&s, &[outer, inner]); + + // Both are picked, Inner inside Outer: Inner comes with its parent's copy, so one copy is made. + let reply = run(&mut s, "solid.move", json!({"bodies": [], "occurrences": [[outer], [outer, inner]], "copy": true, "translate": [50, 0, 0]})); + assert_eq!(reply["occurrences"].as_array().map(Vec::len), Some(1), "one copy: Inner is copied inside Outer's copy"); + let copy = reply["occurrences"][0].as_u64().unwrap(); + assert_eq!(counts(&s), (4, 4, 2), "the copy of Outer and its own Inner, with the cube copied once"); + assert!( + world_min(&s, &[copy]).dist(Vec3::new(source.x + 50.0, source.y, source.z)) < 1e-6, + "the copied cube sits 50 mm along X from the original" + ); + assert!(world_min(&s, &[outer, inner]).dist(source) < 1e-6, "the original cube stays where it was"); + + run(&mut s, "edit.undo", json!({})); + assert_eq!(counts(&s), (2, 2, 1), "one undo puts back the two components, two occurrences and one body"); + assert_eq!(s.doc, before, "one undo removes the whole copy"); +} + +#[test] +fn a_copy_that_fails_part_way_changes_nothing() { + let mut s = Session::default(); + let (_, occurrence) = part_with_cube(&mut s); + let before = s.doc.clone(); + let undo = s.undo.len(); + // The first component copies; the second names no occurrence, so the whole move is refused. + let error = s.execute("solid.move", &json!({"bodies": [], "occurrences": [[occurrence], [999_999]], "copy": true, "translate": [50, 0, 0]})); + assert!(error.is_err()); + assert_eq!(s.doc, before, "the first copy is rolled back with the rest"); + assert_eq!(s.undo.len(), undo, "a refused move leaves no undo step"); +} + +#[test] +fn components_move_only_as_copies() { + let mut s = Session::default(); + let (_, occurrence) = part_with_cube(&mut s); + let before = s.doc.clone(); + let error = s.execute("solid.move", &json!({"bodies": [], "occurrences": [[occurrence]], "translate": [50, 0, 0]})).unwrap_err(); + assert!(error.to_string().contains("copy"), "{error}"); + assert_eq!(s.doc, before, "a refused move changes nothing"); +} + +#[test] +fn bodies_that_are_not_a_list_are_refused_with_components() { + let mut s = Session::default(); + let (_, occurrence) = part_with_cube(&mut s); + let before = s.doc.clone(); + let error = s.execute("solid.move", &json!({"bodies": "Peg", "occurrences": [[occurrence]], "copy": true, "translate": [50, 0, 0]})).unwrap_err(); + assert!(error.to_string().contains("bodies"), "{error}"); + assert_eq!(s.doc, before, "a refused move changes nothing"); +} diff --git a/crates/engine/src/cmd/surface_analysis.rs b/crates/engine/src/cmd/surface_analysis.rs index b5c257bb7..7a562e614 100644 --- a/crates/engine/src/cmd/surface_analysis.rs +++ b/crates/engine/src/cmd/surface_analysis.rs @@ -129,7 +129,7 @@ impl Session { self.continuity.clear(); } self.status_analysis_changed(None); - self.revision += 1; + self.refresh_display(); } } @@ -172,7 +172,7 @@ fn set(s: &mut Session, p: &Value, a: SurfaceAnalysis) -> Result { s.analyses_off(Some(a.command())); } s.status_analysis_changed((!bool_(p, "clear").unwrap_or(false)).then_some(crate::status_items::StatusId::SurfaceAnalysis)); - s.revision += 1; + s.refresh_display(); let vector = |v: Vec3| [v.x, v.y, v.z]; let analysis = s.analysis.map(|a| match a { SurfaceAnalysis::Zebra { stripes } => contract::Analysis::Zebra { stripes }, @@ -236,7 +236,7 @@ fn continuity(s: &mut Session, p: &Value) -> Result { if bool_(p, "clear").unwrap_or(false) { s.continuity.clear(); s.status_analysis_changed(None); - s.revision += 1; + s.refresh_display(); return serde_json::to_value(contract::ContinuityResult::Cleared { analysis: "continuity".into(), cleared: true, @@ -364,7 +364,7 @@ fn continuity(s: &mut Session, p: &Value) -> Result { s.analyses_off(Some("inspect.continuity")); } s.status_analysis_changed(Some(crate::status_items::StatusId::Continuity)); - s.revision += 1; + s.refresh_display(); serde_json::to_value(contract::ContinuityResult::Measured { analysis: "continuity".into(), samples, diff --git a/crates/engine/src/cmd/view_navigation.rs b/crates/engine/src/cmd/view_navigation.rs index 93a94aa95..69b848674 100644 --- a/crates/engine/src/cmd/view_navigation.rs +++ b/crates/engine/src/cmd/view_navigation.rs @@ -321,7 +321,7 @@ fn render_select(s: &mut Session, p: &Value) -> Result { let result = serde_json::to_value(request).map_err(|e| bad("view.render_select", e.to_string()))?; if !s.selection.is_empty() { s.selection.clear(); - s.revision += 1; + s.refresh_display(); } Ok(result) } diff --git a/crates/engine/src/computed_commands_tests.rs b/crates/engine/src/computed_commands_tests.rs index 903489312..04b6d7df2 100644 --- a/crates/engine/src/computed_commands_tests.rs +++ b/crates/engine/src/computed_commands_tests.rs @@ -149,6 +149,35 @@ fn editor_visibility_changes_allow_apply_and_preserve_separate_undo_steps() { } } +/// A section, an analysis or the selection changed while an editor is open changes only what is +/// shown: OK still applies the edit and Cancel puts the design back (#10687). +#[test] +fn editor_display_changes_allow_apply_and_cancel() { + let cases: [&[(&str, serde_json::Value)]; 5] = [ + &[("inspect.section", json!({"plane":"XZ","offset":1}))], + &[("inspect.section", json!({"plane":"XZ","offset":1})), ("inspect.section", json!({"clear":true}))], + &[("inspect.zebra", json!({"stripes":14.5}))], + &[("select.set", json!({"items":[{"type":"body","name":"Other"}]}))], + &[("select.clear", json!({}))], + ]; + for display in cases { + let (mut session, source, original, commands) = extrusion_editor(); + for (id, params) in display { + session.execute(id, params).unwrap(); + } + let prepared = + session.scratch().compute_editor_commands(&commands, &source, original).unwrap_or_else(|e| panic!("OK after {display:?}: {e}")); + session.accept_commands(prepared).unwrap(); + assert_editor_volume(&mut session, 12024.0); + let (mut session, source, original, _) = extrusion_editor(); + for (id, params) in display { + session.execute(id, params).unwrap(); + } + session.restore_editor(&source, original).unwrap_or_else(|e| panic!("Cancel after {display:?}: {e}")); + assert_editor_volume(&mut session, 6024.0); + } +} + #[test] fn editor_visibility_changes_allow_cancel_and_keep_undo_and_redo_at_the_original_marker() { for undo_hide in [false, true] { diff --git a/crates/engine/src/construct_tests.rs b/crates/engine/src/construct_tests.rs index 5d32dd222..8af12922a 100644 --- a/crates/engine/src/construct_tests.rs +++ b/crates/engine/src/construct_tests.rs @@ -410,6 +410,57 @@ fn plane_tangent_to_a_cylinder() { assert!(parallel(u.normal(), Vec3::Z) && on_plane(&u, Vec3::new(3.0, 3.0, 65.0)), "{u:?}"); } +/// #8822: with a reference plane or planar face, the plane touches where the face turns towards +/// the reference (parallel to it, on the side of the pick), turned by an angle about the axis, +/// and follows the reference when it moves. +#[test] +fn plane_tangent_lined_up_with_a_reference() { + let mut s = part(); + // Picked 60° round the cylinder (axis Z through (60, 0)); the XZ plane faces ±Y. + let pick = json!([62.5, 4.330127, 5]); + run(&mut s, "construct.plane.tangent", json!({"face": {"face": pick}, "reference": {"plane": "XZ"}, "name": "T"})); + let t = plane(&s, "T"); + assert!(parallel(t.normal(), Vec3::Y) && on_plane(&t, Vec3::new(60.0, 5.0, 9.0)), "{t:?}"); + // Turned 30° about the axis: still on the pick's side. + run(&mut s, "construct.plane.tangent", json!({"face": {"face": pick}, "reference": {"plane": "XZ"}, "angle": "30 deg", "name": "A"})); + let a = plane(&s, "A"); + let d = Vec3::new(-0.5, 3f64.sqrt() / 2.0, 0.0); + assert!(parallel(a.normal(), d) && on_plane(&a, Vec3::new(60.0, 0.0, 2.0) + d * 5.0), "{a:?}"); + // A planar face of the box (x = 40, facing X) as the reference. + run(&mut s, "construct.plane.tangent", json!({"face": {"face": pick}, "reference": {"face": [40, 15, 10]}, "name": "F"})); + let f = plane(&s, "F"); + assert!(parallel(f.normal(), Vec3::X) && on_plane(&f, Vec3::new(65.0, 1.0, 1.0)), "{f:?}"); + // The torus (axis Z through (0, 60)): on its outer equator. + run(&mut s, "construct.plane.tangent", json!({"face": {"face": [0, 72, 0]}, "reference": {"plane": "XZ"}, "name": "R"})); + let r = plane(&s, "R"); + assert!(parallel(r.normal(), Vec3::Y) && on_plane(&r, Vec3::new(3.0, 72.0, 1.0)), "{r:?}"); + // The sphere (centre (0, 0, 60)), picked below its middle: under it, parallel to XY. + run(&mut s, "construct.plane.tangent", json!({"face": {"face": [3, 0, 56]}, "reference": {"plane": "XY"}, "name": "U"})); + let u = plane(&s, "U"); + assert!(parallel(u.normal(), Vec3::Z) && on_plane(&u, Vec3::new(1.0, 1.0, 55.0)), "{u:?}"); + + // A reference built on a parameter: the tangent plane follows it. + run(&mut s, "parameters.add", json!({"name": "turn", "expression": "0 deg"})); + run(&mut s, "construct.plane.at_angle", json!({"base": "XZ", "axis": "Z", "angle": "turn", "name": "Ref"})); + run(&mut s, "construct.plane.tangent", json!({"face": {"face": pick}, "reference": {"plane": "Ref"}, "name": "M"})); + assert!(on_plane(&plane(&s, "M"), Vec3::new(60.0, 5.0, 1.0))); + run(&mut s, "parameters.change", json!({"name": "turn", "expression": "-90 deg"})); + let m = plane(&s, "M"); + assert!(parallel(m.normal(), Vec3::X) && on_plane(&m, Vec3::new(65.0, 2.0, 1.0)), "{m:?}"); + + // What has no answer is refused and adds nothing. + let count = construction_planes(&s).len(); + for (p, why) in [ + (json!({"face": {"face": pick}, "reference": {"plane": "XY"}}), "a reference square to the axis"), + (json!({"face": {"face": [3, 0, 56]}, "reference": {"plane": "XY"}, "angle": "10 deg"}), "an angle on a sphere"), + (json!({"face": {"face": pick}, "angle": "10 deg"}), "an angle without a reference"), + (json!({"face": {"face": pick}, "reference": {"plane": "XZ"}, "angle": "2 mm"}), "a length for the angle"), + ] { + assert!(s.execute("construct.plane.tangent", &p).is_err(), "{why}"); + } + assert_eq!(construction_planes(&s).len(), count); +} + #[test] fn plane_along_a_path() { let mut s = part(); @@ -756,3 +807,27 @@ fn hiding_an_occurrence_hides_its_construction_geometry() { assert!(!s.construction_visible(name), "{name} shows in a hidden placement"); } } + +/// #10127: an axis and a point built on a component's cylinder turn with it when Move/Copy +/// turns the cylinder, as its faces do. One also pinned to a fixed point stays where it is. +#[test] +fn construction_on_a_moved_body_moves_with_it() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 20, "body_name": "Pin"})); + run(&mut s, "component.create", json!({"name": "Part", "parent": "root", "activate": false})); + run(&mut s, "component.move_bodies", json!({"bodies": ["Pin"], "component": "Part"})); + run(&mut s, "construct.axis.through_cylinder", json!({"face": {"face": [5, 0, 10]}, "name": "PinAxis"})); + run(&mut s, "construct.point.center", json!({"of": {"edge": [5, 0, 20]}, "name": "PinTop"})); + run(&mut s, "construct.axis.two_points", json!({"a": {"construct_point": "PinTop"}, "b": {"point": [0, 50, 20]}, "name": "Tether"})); + let body = s.model.state().bodies.first().map(|b| b.name.clone()).unwrap(); + // A quarter turn about Y through the origin, then 10 mm along X: the top centre (0, 0, 20) + // goes to (30, 0, 0), and the cylinder's axis lies along X. + run(&mut s, "solid.move", json!({"bodies": [body], "translate": [10, 0, 0], "axis": [0, 1, 0], "angle": "90 deg"})); + let errors: Vec = s.model.results.iter().filter_map(|r| r.error.clone()).collect(); + assert!(errors.is_empty(), "{errors:?}"); + let (o, d) = axis(&s, "PinAxis"); + assert!(parallel(d, Vec3::X) && on_line(o, d, Vec3::new(30.0, 0.0, 0.0)), "{o:?} {d:?}"); + assert!(near(point(&s, "PinTop"), Vec3::new(30.0, 0.0, 0.0)), "{:?}", point(&s, "PinTop")); + let (o, d) = axis(&s, "Tether"); + assert!(on_line(o, d, Vec3::new(0.0, 0.0, 20.0)) && on_line(o, d, Vec3::new(0.0, 50.0, 20.0)), "{o:?} {d:?}"); +} diff --git a/crates/engine/src/control_auth.rs b/crates/engine/src/control_auth.rs index c93541923..6645a1cfb 100644 --- a/crates/engine/src/control_auth.rs +++ b/crates/engine/src/control_auth.rs @@ -57,12 +57,17 @@ pub fn bind_with_fallback(first: u16, tries: u16) -> Result/control` (`SOLIDCRAFT_CONTROL_DIR` replaces it). fn control_dir() -> Option { - match solidcraft_geom::env::var_os("CONTROL_DIR").filter(|d| !d.is_empty()) { + match custom_control_dir() { Some(d) => Some(PathBuf::from(d)), None => Some(crate::recovery::data_dir()?.join("control")), } } +/// The folder `SOLIDCRAFT_CONTROL_DIR` names in place of the default one. +fn custom_control_dir() -> Option { + solidcraft_geom::env::var_os("CONTROL_DIR").filter(|d| !d.is_empty()) +} + /// The token file of the app listening on `port`: `/control/.token` /// (`SOLIDCRAFT_CONTROL_DIR` replaces the folder). pub fn token_path(port: u16) -> Option { @@ -276,9 +281,19 @@ pub fn tokens_match(a: &str, b: &str) -> bool { /// Write `token` to `path`, readable and writable only by the user: the folder is made `0700` /// and the file `0600` on Unix; on Windows the file's inherited permissions are replaced by one -/// entry for the user (`icacls`) before the token goes in. A file left by an earlier launch is -/// replaced. The process file beside it ([`pid_path`]) records this process, best effort. +/// entry for the user (`icacls`) before the token goes in; when that fails, the still empty file +/// is removed and no token is written. A file left by an earlier launch is replaced. The process +/// file beside it ([`pid_path`]) records this process, best effort. pub fn write_token_file(path: &Path, token: &str) -> Result<()> { + #[cfg(windows)] + let restrict = restrict_to_user; + #[cfg(not(windows))] + let restrict = |_: &Path| Ok(()); + write_token_file_with(path, token, restrict) +} + +/// [`write_token_file`], with `restrict` limiting the new file to the user (Windows). +fn write_token_file_with(path: &Path, token: &str, restrict: impl FnOnce(&Path) -> Result<()>) -> Result<()> { let dir = path.parent().ok_or_else(|| Error::new(ErrorKind::InvalidInput, "no folder"))?; std::fs::create_dir_all(dir)?; let _ = std::fs::remove_file(path); @@ -291,8 +306,11 @@ pub fn write_token_file(path: &Path, token: &str) -> Result<()> { opts.mode(0o600); } let mut f = opts.open(path)?; - #[cfg(windows)] - restrict_to_user(path)?; + if let Err(e) = restrict(path) { + drop(f); + let _ = std::fs::remove_file(path); + return Err(e); + } f.write_all(token.as_bytes())?; f.write_all(b"\n")?; f.sync_all()?; @@ -332,9 +350,32 @@ fn held_by_another(path: &Path, token: &str) -> bool { #[cfg(windows)] const ICACLS_LIMIT: std::time::Duration = std::time::Duration::from_secs(5); +/// How a run of `icacls` ended. +#[cfg(any(windows, test))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum IcaclsEnd { + Succeeded, + Failed, + /// It didn't finish within [`ICACLS_LIMIT`] and was ended. + TimedOut, +} + +/// Whether a token may go into a file after `icacls` ended this way. `custom_folder`: the file is +/// in the folder `SOLIDCRAFT_CONTROL_DIR` names. A timeout is accepted only in the default folder, +/// the user's own local app data, which other users can't read by default; nothing is known about +/// the permissions of any other folder. +#[cfg(any(windows, test))] +fn restriction_result(end: IcaclsEnd, custom_folder: bool, path: &Path) -> Result<()> { + match end { + IcaclsEnd::Succeeded => Ok(()), + IcaclsEnd::TimedOut if !custom_folder => Ok(()), + IcaclsEnd::TimedOut => Err(Error::new(ErrorKind::TimedOut, format!("icacls did not finish in time to restrict {}", path.display()))), + IcaclsEnd::Failed => Err(Error::other(format!("icacls failed to restrict {}", path.display()))), + } +} + /// Windows: drop inherited entries and grant only the current user full access. An `icacls` -/// that doesn't finish in time is ended and the file kept as made: it is in the user's own -/// local app data folder, which other users can't read by default. +/// that doesn't finish in time is ended, and [`restriction_result`] decides what that means. #[cfg(windows)] fn restrict_to_user(path: &Path) -> Result<()> { use std::os::windows::process::CommandExt; @@ -348,10 +389,12 @@ fn restrict_to_user(path: &Path) -> Result<()> { .stderr(std::process::Stdio::null()) .creation_flags(0x0800_0000) .spawn()?; - match wait_within(child, ICACLS_LIMIT)? { - Some(status) if !status.success() => Err(Error::other(format!("icacls failed to restrict {}", path.display()))), - _ => Ok(()), - } + let end = match wait_within(child, ICACLS_LIMIT)? { + Some(status) if status.success() => IcaclsEnd::Succeeded, + Some(_) => IcaclsEnd::Failed, + None => IcaclsEnd::TimedOut, + }; + restriction_result(end, custom_control_dir().is_some(), path) } /// Wait for `child` at most `limit`: its exit status, or `None` (and the child ended) when it @@ -400,6 +443,39 @@ mod tests { assert!(wait_within(failing, Duration::from_secs(5)).unwrap().is_some_and(|s| !s.success())); } + /// #6145's freeze fix stays in the default folder, the user's own; a folder picked with + /// `SOLIDCRAFT_CONTROL_DIR` gets no token unless the file was really restricted. + #[test] + fn only_the_default_folder_accepts_an_icacls_that_timed_out() { + let path = Path::new("control/7878.token"); + for custom in [false, true] { + assert!(restriction_result(IcaclsEnd::Succeeded, custom, path).is_ok()); + assert!(restriction_result(IcaclsEnd::Failed, custom, path).is_err()); + } + assert!(restriction_result(IcaclsEnd::TimedOut, false, path).is_ok()); + let e = restriction_result(IcaclsEnd::TimedOut, true, path).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::TimedOut); + assert!(e.to_string().contains("7878.token"), "{e}"); + } + + /// A file that couldn't be restricted is removed, empty and with no process file beside it, and + /// the error goes to the caller. A restricted one gets its token. + #[test] + fn a_token_file_that_could_not_be_restricted_is_removed() { + let dir = std::env::temp_dir().join(format!("solidcraft-control-restrict-{}", std::process::id())); + let path = dir.join("7879.token"); + let e = write_token_file_with(&path, "secret-token", |p| { + assert_eq!(std::fs::read(p).unwrap(), b"", "restricted before the token goes in"); + restriction_result(IcaclsEnd::TimedOut, true, p) + }) + .unwrap_err(); + assert_eq!(e.kind(), ErrorKind::TimedOut); + assert!(!path.exists() && !pid_path(&path).exists()); + write_token_file_with(&path, "secret-token", |p| restriction_result(IcaclsEnd::TimedOut, false, p)).unwrap(); + assert_eq!(read_token(&path).as_deref(), Some("secret-token")); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn tokens_compare_whole() { assert!(tokens_match("abc123", "abc123")); diff --git a/crates/engine/src/extent_tests.rs b/crates/engine/src/extent_tests.rs index 852a271ef..8a836ce2d 100644 --- a/crates/engine/src/extent_tests.rs +++ b/crates/engine/src/extent_tests.rs @@ -181,3 +181,56 @@ fn extrude_to_a_cylinder_beside_another_body() { assert!((end + (2.75f64 * 2.75 - 1.5 * 1.5).sqrt()).abs() < 1e-3, "{b}"); assert!((b["bbox"]["min"][0].as_f64().unwrap_or(0.0) + 98.0).abs() < 1e-6, "{b}"); } + +/// A window cut To Object through the side of a tube (r 20 outside, 18 inside), up to the inside +/// face: it takes the wall under the profile and nothing else. Before, the tool ended in the +/// curved inner face: the tool less the tube kept only the air before the wall and cut nothing, +/// or the boolean failed on the coincident curved faces. Picking the outside face from inside +/// the wall cuts back to it. +#[test] +fn cut_to_the_far_side_of_a_curved_wall() { + let tube = || { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 20, "height": 20, "body_name": "Tube"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Bore"})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 18})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Bore", "distance": 20, "operation": "cut"})); + s + }; + let volume = |s: &mut Session| body(s, "Tube")["volume_mm3"].as_f64().unwrap_or(0.0); + let wall = |x: f64, r: f64| (r * r - x * x).sqrt(); + let n = 2000; + let between = |r0: f64, r1: f64| -> f64 { + (0..n).map(|i| -3.0 + 6.0 * (i as f64 + 0.5) / n as f64).map(|x| (wall(x, r1) - wall(x, r0)) * 4.0 * 6.0 / n as f64).sum() + }; + // From outside the tube, through the wall, to its inside face. + let mut s = tube(); + let whole = volume(&mut s); + run(&mut s, "sketch.create", json!({"plane": {"origin": [0, -30, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}, "name": "Window"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-3, 8], "p1": [3, 12]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Window", "to": [0, -18, 10], "operation": "cut"})); + let removed = whole - volume(&mut s); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); + // The same window cut 20 mm, ending in the bore: the tube's own facets set its volume. + let mut plain = tube(); + run(&mut plain, "sketch.create", json!({"plane": {"origin": [0, -30, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}, "name": "Window"})); + run(&mut plain, "sketch.rectangle.two_point", json!({"p0": [-3, 8], "p1": [3, 12]})); + run(&mut plain, "sketch.finish", json!({})); + run(&mut plain, "solid.extrude", json!({"sketch": "Window", "distance": -20, "operation": "cut"})); + let reference = whole - volume(&mut plain); + assert!((removed - reference).abs() < reference * 1e-6, "removed {removed}, a 20 mm cut {reference}"); + let want = between(18.0, 20.0); + assert!((removed - want).abs() < want * 2e-2, "removed {removed}, want {want}"); + // From inside the wall (y = -19) back out to the outside face. + let mut s = tube(); + run(&mut s, "sketch.create", json!({"plane": {"origin": [0, -19, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}, "name": "Window"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [-3, 8], "p1": [3, 12]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Window", "to": [0, -20, 10], "operation": "cut"})); + let removed = whole - volume(&mut s); + let want: f64 = (0..n).map(|i| -3.0 + 6.0 * (i as f64 + 0.5) / n as f64).map(|x| (wall(x, 20.0) - 19.0) * 4.0 * 6.0 / n as f64).sum(); + assert!((removed - want).abs() < want * 2e-2, "removed {removed}, want {want}"); + assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); +} diff --git a/crates/engine/src/frames.rs b/crates/engine/src/frames.rs index 3b1c19a37..140926f09 100644 --- a/crates/engine/src/frames.rs +++ b/crates/engine/src/frames.rs @@ -347,6 +347,9 @@ thread_local! { static DEPTH: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The outermost command's coordinates were mapped here (its table lists them). static MAPPED: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// The outermost command is `solid.move`, whose parameters stay in the world when its bodies + /// lie in differently turned frames (`split_move`). + static OUTER_MOVE: std::cell::Cell = const { std::cell::Cell::new(false) }; /// The picks of the running command: the point it sees and the bodies whose faces meet /// there (the first is the body under it; more than one means the pick is ambiguous). static PICKS: std::cell::RefCell)>> = const { std::cell::RefCell::new(Vec::new()) }; @@ -413,6 +416,7 @@ impl Nested { if outer { let inner = if id == "timeline.redefine" { None } else { Some(id) }; MAPPED.with(|m| m.set(inner.is_none_or(|i| !table(i).is_empty() || i == "construct.plane.axis_point"))); + OUTER_MOVE.with(|m| m.set(id == "solid.move")); } (Nested, outer) } @@ -427,6 +431,11 @@ impl Drop for Nested { /// `params` with world picks mapped into component frames (`None`: nothing to change). A model /// that cannot be placed is the error. pub fn to_local(s: &Session, id: &str, params: &Value) -> crate::Result> { + // A move of bodies in differently turned frames keeps its world vectors: `solid.move` splits + // it by frame and maps each part itself (`split_move`). + if id == "solid.move" && split_move(s, params).is_some() { + return Ok(None); + } // A command with no world picks has nothing to map, and may not need the bodies placed. let picks = !table(id).is_empty() || matches!(id, "library.apply" | "timeline.redefine" | "sketch.redefine"); if !picks || !placed(s) { @@ -436,6 +445,59 @@ pub fn to_local(s: &Session, id: &str, params: &Value) -> crate::Result Option> { + let outermost_move = DEPTH.with(std::cell::Cell::get) == 1 && OUTER_MOVE.with(std::cell::Cell::get); + if !outermost_move || !placed(s) || placements_moved(s, params).is_some() { + return None; + } + let names = params.get("bodies")?.as_array()?; + let turns = params.get("axis").is_some() || params.get("angle").is_some(); + let alike = |a: &Mat, b: &Mat| { + let columns = if turns { 4 } else { 3 }; + a.iter().zip(b).take(columns).all(|(x, y)| x.iter().zip(y).take(3).all(|(u, v)| (u - v).abs() <= 1e-9 * (1.0 + u.abs().max(v.abs())))) + }; + let frames = s.body_frames(); + let mut groups: Vec<(Mat, Vec)> = Vec::new(); + for name in names { + // An unknown body is the command's to refuse. + let b = name.as_str()?; + let m = frames.iter().find(|(world, own, _)| world == b || own == b).map(|(.., m)| *m)?; + match groups.iter_mut().find(|(g, _)| alike(g, &m)) { + Some((_, bodies)) => bodies.push(name.clone()), + None => groups.push((m, vec![name.clone()])), + } + } + if groups.len() < 2 { + return None; + } + // An unplaceable model is `to_local`'s error to report. + let world = s.world_state().ok()?; + let given = params.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()); + let moves = groups + .into_iter() + .enumerate() + .map(|(k, (_, bodies))| { + let mut p = params.clone(); + p["bodies"] = Value::Array(bodies); + // Each move is its own feature: a name given is numbered after the first. + if let Some(name) = given.filter(|_| k > 0) { + p["name"] = Value::String(format!("{name} ({})", k + 1)); + } + map_local(s, &world, "solid.move", &p).unwrap_or(p) + }) + .collect(); + Some(moves) +} + /// [`to_local`] on the placed model `world`. fn map_local(s: &Session, world: &solidcraft_doc::ModelState, id: &str, params: &Value) -> Option { if id == "library.apply" { @@ -448,8 +510,9 @@ fn map_local(s: &Session, world: &solidcraft_doc::ModelState, id: &str, params: return Some(out); } // Several placements of one part moved together are moved as placements, in the world - // (`placements_moved`): their names and vectors stay as given. - if id == "solid.move" && placements_moved(s, params).is_some() { + // (`placements_moved`), and components copied (`occurrences`) likewise: their names and vectors + // stay as given. Bodies listed with them are mapped by `copy_components`. + if id == "solid.move" && (params.get("occurrences").is_some() || placements_moved(s, params).is_some()) { return None; } if id == "timeline.redefine" { diff --git a/crates/engine/src/frames_tests.rs b/crates/engine/src/frames_tests.rs index f0a3410f5..303828680 100644 --- a/crates/engine/src/frames_tests.rs +++ b/crates/engine/src/frames_tests.rs @@ -274,6 +274,65 @@ fn move_expression_distances_keep_parameters_through_rebuild_and_reopen() { } } +/// One `solid.move` of bodies placed in differently turned frames (a block in the root and a +/// screw inserted lying down) moves and turns each of them in the world, whichever is listed +/// first (#9660). +#[test] +fn one_move_of_bodies_in_differently_turned_frames_moves_each_in_the_world() { + let corners = |(lo, hi): (Vec3, Vec3)| { + let mut out = Vec::new(); + for x in [lo.x, hi.x] { + for y in [lo.y, hi.y] { + for z in [lo.z, hi.z] { + out.push(Vec3::new(x, y, z)); + } + } + } + out + }; + let bounds = |points: Vec| { + let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY); + let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for p in points { + lo = Vec3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z)); + hi = Vec3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z)); + } + (lo, hi) + }; + let close = |a: (Vec3, Vec3), b: (Vec3, Vec3)| a.0.dist(b.0) < 1e-4 && a.1.dist(b.1) < 1e-4; + // The quarter turn is about the world z axis, which passes through the screw's own origin + // (where it was inserted): a Move feature turns about that origin. + let moves: [(Value, &dyn Fn(Vec3) -> Vec3); 3] = [ + (json!({"translate": [0, 0, 3]}), &|p| p + Vec3::new(0.0, 0.0, 3.0)), + (json!({"translate": [0, "2 mm", 0]}), &|p| p + Vec3::new(0.0, 2.0, 0.0)), + (json!({"axis": [0, 0, 1], "angle": "90 deg"}), &|p| Vec3::new(-p.y, p.x, p.z)), + ]; + for direction in [[1, 0, 0], [0, 0, -1], [0, 1, 0]] { + for order in [["Block", "Body1"], ["Body1", "Block"]] { + for (params, expected) in &moves { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 30, "width": 30, "height": 10, "center": [0, 0, 5], "body_name": "Block"})); + let screw = json!({"family": "socket_head_cap_screw", "size": "M3", "length": 12, "point": [0, 0, 10], "direction": direction, "name": "screw"}); + run(&mut s, "parts.insert", screw); + let before: Vec<_> = order.iter().map(|b| world_bbox(&s, b)).collect(); + let mut p = params.clone(); + p["bodies"] = json!(order); + run(&mut s, "solid.move", p.clone()); + for (body, was) in order.iter().zip(&before) { + let want = bounds(corners(*was).into_iter().map(expected).collect()); + let got = world_bbox(&s, body); + assert!(close(got, want), "{body} after {p} (screw along {direction:?}): {got:?}, want {want:?}"); + } + // One step: a single undo puts both back. + run(&mut s, "edit.undo", json!({})); + for (body, was) in order.iter().zip(&before) { + assert!(close(world_bbox(&s, body), *was), "{body} after undoing {p}"); + } + } + } + } +} + /// Edit Feature passes a primitive's placement through as saved, so changing the radius of /// Leaf B's rod in the Hinge Assembly leaves the leaf where it was (#2926). #[test] diff --git a/crates/engine/src/hole_face_tests.rs b/crates/engine/src/hole_face_tests.rs index f165a224b..1a88882cf 100644 --- a/crates/engine/src/hole_face_tests.rs +++ b/crates/engine/src/hole_face_tests.rs @@ -449,3 +449,47 @@ fn a_hole_may_start_over_the_mouth_of_an_existing_bore() { let e = s.execute("solid.hole", &json!({"position": [-1, 15, 20], "diameter": 8})).unwrap_err().to_string(); assert!(e.contains("is not on a face of a body"), "{e}"); } + +/// A hole moved off the part cuts nothing and says so (#10701), as a pattern's copies do: by a +/// parameter of its position or a sketch point moved away. Back on the part it is silent. +#[test] +fn a_hole_moved_off_the_part_says_it_removes_no_material() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "hx", "expression": "10 mm"})); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "name": "Plate"})); + run(&mut s, "solid.hole", json!({"position": ["hx", "10 mm", "10 mm"], "diameter": 5, "name": "H1"})); + assert_eq!(said(&s, "H1"), ""); + change(&mut s, "hx", "100 mm"); + assert!((volume(&mut s) - 12_000.0).abs() < 1e-6, "nothing is cut"); + assert!(said(&s, "H1").contains("the hole removes no material"), "{}", said(&s, "H1")); + change(&mut s, "hx", "30 mm"); + assert_eq!(said(&s, "H1"), ""); + // Holes at two sketch points, one of them moved off the plate. + run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 10, "name": "HP"})); + run(&mut s, "sketch.point", json!({"point": [10, 20], "id": "a"})); + run(&mut s, "sketch.point", json!({"point": [20, 20], "id": "b"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.hole", json!({"sketch": "HP", "points": ["a", "b"], "diameter": 4, "name": "H2"})); + assert_eq!(said(&s, "H2"), ""); + run(&mut s, "sketch.edit", json!({"sketch": "HP"})); + run(&mut s, "sketch.move_point", json!({"point": "a", "to": [100, 100]})); + run(&mut s, "sketch.finish", json!({})); + assert!(said(&s, "H2").contains("1 of 2 holes remove no material"), "{}", said(&s, "H2")); +} + +/// A hole wider than the part takes all of it away and says so (#10702): at creation, and when +/// a parameter widens it later. A hole across the part's width keeps the rest, silently. +#[test] +fn a_hole_wider_than_the_part_says_it_removes_all_of_it() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "hd", "expression": "40 mm"})); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "name": "Plate"})); + run(&mut s, "solid.hole", json!({"position": [10, 10, 10], "diameter": "hd", "name": "H1"})); + assert_eq!(said(&s, "H1"), ""); + assert_eq!(s.model.state().bodies.len(), 1); + change(&mut s, "hd", "100 mm"); + assert!(s.model.state().bodies.is_empty()); + assert!(said(&s, "H1").contains("the hole removes all of Body1"), "{}", said(&s, "H1")); + change(&mut s, "hd", "5 mm"); + assert_eq!(said(&s, "H1"), ""); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 411f55111..7a32ee31e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -477,8 +477,9 @@ pub struct Session { pub log: Vec, /// Increments on every document change (views use it to refresh). pub revision: u64, - /// Revision increments caused only by visibility. Comparing both counters proves that - /// every intervening increment left an editor's document and model untouched. + /// Revision increments caused only by what is shown ([`Session::refresh_display`]). + /// Comparing both counters proves that every intervening increment left an editor's + /// document and model untouched. visibility_revision: u64, /// [`Document::browser_stamp`] when the browser's groups and order were last checked. browser_stamp: [u64; 6], @@ -1472,8 +1473,9 @@ impl Session { } } - /// Only what is hidden or shown changed: the model is untouched, so only the view revision - /// moves (the visibility caches are keyed on it) and the viewport redraws. + /// Only what is shown changed (hidden or shown items, a section or analysis, the selection): + /// the design and model are untouched, so only the view revision moves and the viewport + /// redraws. An open feature editor stays valid across it (#10687). pub(crate) fn refresh_display(&mut self) { self.revision += 1; self.visibility_revision += 1; diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 59b349935..e05c079fb 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -283,6 +283,14 @@ impl Autosaver { Ok(true) } + /// Whether the last autosave holds `s` as it is now, with no write still running: what a + /// crash now would leave for the next launch to offer. A finished write counts once a + /// [`Self::tick`] has taken its outcome. + pub fn caught_up(&self, s: &Session) -> bool { + self.writing.is_none() + && self.last.as_ref().is_some_and(|(doc, visibility)| (Arc::ptr_eq(doc, &s.doc) || **doc == *s.doc) && *visibility == s.visibility) + } + /// Autosave when the interval has passed, or right away after a big operation. The design /// is written on a worker thread; true when this call started a write. pub fn tick(&mut self, s: &Session, big: bool) -> Result { diff --git a/crates/engine/src/schema/construct.rs b/crates/engine/src/schema/construct.rs index 0e138867c..a670fcf0e 100644 --- a/crates/engine/src/schema/construct.rs +++ b/crates/engine/src/schema/construct.rs @@ -8,7 +8,7 @@ use schemars::JsonSchema; use serde::Deserialize; -use super::types::{ConstructionCommon, GeoRefParam, NumberExpr, PlaneCommon, Point3, feature_common, present}; +use super::types::{AngleExpr, ConstructionCommon, GeoRefParam, NumberExpr, PlaneCommon, Point3, feature_common, present}; /// Add a construction axis along the axis of a cylinder, cone or torus face, or of a circular /// edge. @@ -214,6 +214,14 @@ pub struct PlaneTangentParams { /// otherwise. #[serde(default)] pub at: Option, + /// A plane or planar face to line the plane up with: it touches where the face turns + /// towards the reference, parallel to it, on the side of `at`. + #[serde(default)] + pub reference: Option, + /// With `reference`, how far the plane is turned from it about the face's axis. Not on a + /// sphere. Default: 0 deg. + #[serde(default)] + pub angle: Option, #[serde(flatten, deserialize_with = "feature_common")] pub common: PlaneCommon, } diff --git a/crates/engine/src/schema/construct_tests.rs b/crates/engine/src/schema/construct_tests.rs index 106b985f4..f2d7a56ba 100644 --- a/crates/engine/src/schema/construct_tests.rs +++ b/crates/engine/src/schema/construct_tests.rs @@ -27,7 +27,7 @@ fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &["axis", "name", "participants", "point"]); assert_keys(input_schema_for::(), &["a", "b", "name", "participants"]); assert_keys(input_schema_for::(), &["a", "b", "c", "name", "participants"]); - assert_keys(input_schema_for::(), &["at", "face", "name", "participants"]); + assert_keys(input_schema_for::(), &["angle", "at", "face", "name", "participants", "reference"]); assert_keys(input_schema_for::(), &["name", "participants", "path", "t"]); assert_keys(input_schema_for::(), &["line", "name", "participants", "plane"]); } diff --git a/crates/engine/src/schema/sheet.rs b/crates/engine/src/schema/sheet.rs index 8e3cbf573..da76fcba1 100644 --- a/crates/engine/src/schema/sheet.rs +++ b/crates/engine/src/schema/sheet.rs @@ -417,9 +417,9 @@ pub struct FlangeParams { pub common: FeatureCommon, } -/// Add a field of round perforations over a whole flat sheet: holes in the flat pattern, the DXF -/// (layer PERFORATION) and the measured volume, not cut into the solid. `participants` changes -/// nothing. +/// Add a field of round perforations over a whole flat sheet, or inside a sketch's outline: holes +/// in the flat pattern, the DXF (layer PERFORATION) and the measured volume, not cut into the +/// solid. `participants` changes nothing. #[derive(Debug, Deserialize, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct PerforateParams { @@ -427,8 +427,8 @@ pub struct PerforateParams { pub diameter: LengthExpr, /// The distance between hole centres, more than the diameter. pub pitch: LengthExpr, - /// How far the holes stay clear of the sheet's edges, cut-outs and bends, at least 0. - /// Default: the diameter. + /// How far the holes stay clear of the sheet's edges, cut-outs and bends, and of the outline, + /// at least 0. Default: the diameter. #[serde(default)] pub margin: Option, /// How the holes are laid out. Default: staggered. @@ -437,6 +437,18 @@ pub struct PerforateParams { /// The sheet metal body. Default: the newest sheet. #[serde(default)] pub body: Option, + /// The field's outline: a sketch, by id or name, on a face of the sheet (or on the flat sheet + /// while it is unfolded). Holes go only inside its closed profiles, out of their inner loops, + /// on a grid from the outline's lower-left corner; on a folded sheet only in the panels the + /// sketch lies on. Default: the whole sheet. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "IdOrName")] + pub sketch: Option, + /// Which of the outline sketch's profiles bound the field. Needs `sketch`. Default: all of + /// them. + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "ProfilesParam")] + pub profiles: Option, #[serde(flatten, deserialize_with = "feature_common")] pub common: FeatureCommon, } diff --git a/crates/engine/src/schema/sheet_tests.rs b/crates/engine/src/schema/sheet_tests.rs index 069904a05..1e1d50d3a 100644 --- a/crates/engine/src/schema/sheet_tests.rs +++ b/crates/engine/src/schema/sheet_tests.rs @@ -64,7 +64,7 @@ fn schemas_and_the_key_check_agree() { "type", ]), ); - assert_keys(input_schema_for::(), &keys(&["body", "diameter", "margin", "pattern", "pitch"])); + assert_keys(input_schema_for::(), &keys(&["body", "diameter", "margin", "pattern", "pitch", "profiles", "sketch"])); assert_keys(input_schema_for::(), &keys(&["body", "edges", "flip", "gap", "length"])); assert_keys(input_schema_for::(), &keys(&["angle", "body", "curve", "fixed", "flip", "points", "position", "radius", "sketch"])); assert_keys(input_schema_for::(), &keys(&["body"])); diff --git a/crates/engine/src/status_items.rs b/crates/engine/src/status_items.rs index 5dff8791c..d6e333edb 100644 --- a/crates/engine/src/status_items.rs +++ b/crates/engine/src/status_items.rs @@ -144,7 +144,7 @@ impl Session { self.status_slot(id, active); } if self.status_items() != before { - self.revision += 1; + self.refresh_display(); } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 345c67df9..402905920 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -109,10 +109,10 @@ fn fillet_as_wide_as_a_face_rounds_it_off() { /// The owner's ruling of 2026-10-30: two edges of a 20 mm box rounded r2 in one fillet (they /// meet in a mitre at the corner (20, 0, 20), the upright edge there sharp), then the upright edge -/// r3 in a second fillet, whose tangent chain takes the mitre's seam with it. The corner is one -/// smooth patch, the body rounding all three at once makes (kernel `fillet_radii` of the box with -/// each edge's radius: 10 faces, 7928.743041 mm³); the r2 rounds keep their names, and the r3 -/// round and the corner patch are the second fillet's. +/// r3 in a second fillet, whose tangent chain takes the mitre's seam with it. The corner is the +/// body rounding all three at once makes (kernel `fillet_radii` of the box with each edge's +/// radius, `three_rounds_at_a_corner`: SMLib's setback corner, 15 faces, 7928.142563938 mm³); the +/// r2 rounds keep their names, and the r3 round and the corner's patches are the second fillet's. #[test] fn a_later_round_at_a_mitred_corner_is_blended_with_the_rounds_there() { let mut s = Session::default(); @@ -134,16 +134,17 @@ fn a_later_round_at_a_mitred_corner_is_blended_with_the_rounds_there() { let second = run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 3}))["feature"].as_u64().unwrap(); assert!(s.model.results.iter().all(|r| r.error.is_none()), "{:?}", s.model.results); let v = volume(&mut s); - assert!((v - 7928.743041).abs() < 1e-5, "{v}"); + assert!((v - 7928.142563938).abs() < 1e-6, "{v}"); let faces = run(&mut s, "model.faces", json!({"body": "Box"}))["faces"].as_array().cloned().unwrap_or_default(); - assert_eq!(faces.len(), 10); + assert_eq!(faces.len(), 15); let after: Vec = rounds.iter().map(|p| named(&mut s, *p)).collect(); assert_eq!(after, before); - // The r3 round (halfway up, at 45°) and the corner patch: the two faces the second fillet made. + // The r3 round (halfway up, at 45°) and the corner's patches: the faces the second fillet made. let k3 = 3.0 - 4.5_f64.sqrt(); assert!(named(&mut s, solidcraft_geom::Vec3::new(20.0 - k3, k3, 10.0)).starts_with(&format!("F{second}:blend:"))); let made = faces.iter().filter(|f| f["name"].as_str().is_some_and(|n| n.starts_with(&format!("F{second}:")))).count(); - assert_eq!(made, 2, "{faces:?}"); + // the r3 round and the corner's six patches (a setback patch per round, three in the triangle) + assert_eq!(made, 7, "{faces:?}"); } #[test] @@ -1930,8 +1931,10 @@ fn section_analysis() { assert_eq!(s.undo.len(), undo); } -/// A section index finds the same cut segments, in the same order, as cutting every triangle: -/// tilted and axis normals, cuts through vertices, at the ends and beyond the part. +/// A section index finds the same cut segments, in the same order and to the bit, as cutting +/// every triangle: one index for every normal (tilting a Section Analysis turns it every frame, +/// #10373), axis and tilted, cuts through vertices, at the ends and beyond the part, and a +/// triangle with a corner that is not a number. #[test] fn section_index_cuts_like_every_triangle() { let mut s = Session::default(); @@ -1939,18 +1942,30 @@ fn section_index_cuts_like_every_triangle() { run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 8, "operation": "join"})); let st = s.model.state(); let m = st.bodies.first().unwrap().mesh(); - assert!(m.triangles.len() > 64, "enough triangles for several slabs: {}", m.triangles.len()); - for n in [Vec3::Z, -Vec3::Y, Vec3::new(1.0, 2.0, 3.0).normalized().unwrap(), Vec3::new(-0.3, 0.1, 0.9).normalized().unwrap()] { - let index = view::SectionIndex::new(&m, n); - let heights: Vec = m.positions.iter().map(|p| n.dot(*p)).collect(); - let (lo, hi) = heights.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), h| (a.min(*h), b.max(*h))); - let mut cuts: Vec = (0..=40).map(|k| lo - 1.0 + (hi - lo + 2.0) * k as f64 / 40.0).collect(); - cuts.extend(heights.iter().step_by(7).copied()); - cuts.extend([lo, hi]); - for at in cuts { - let o = n * at; - let segments = view::section_segments(&m, o, n); - assert_eq!(index.segments(&m, o), segments, "{n:?} at {at}"); + assert!(m.triangles.len() > 64, "enough triangles for several cells: {}", m.triangles.len()); + let bits = |v: Vec<(Vec3, Vec3)>| v.iter().flat_map(|(a, b)| [a.x, a.y, a.z, b.x, b.y, b.z].map(f64::to_bits)).collect::>(); + let mut hostile = (*m).clone(); + hostile.positions.push(Vec3::new(f64::NAN, 0.0, 0.0)); + let nan = u32::try_from(hostile.positions.len() - 1).unwrap(); + hostile.triangles.extend([[0, 1, nan], [0, 1, u32::MAX]]); + for m in [&*m, &hostile] { + let index = view::SectionIndex::new(m); + let mut normals = vec![Vec3::Z, -Vec3::Y, Vec3::new(1.0, 2.0, 3.0).normalized().unwrap(), Vec3::new(-0.3, 0.1, 0.9).normalized().unwrap()]; + // A tilt drag: the normal turns a little every frame. + normals.extend((0..30).map(|k| { + let a = (5.0 + 3.0 * k as f64).to_radians(); + Vec3::new(0.1, a.sin(), a.cos()).normalized().unwrap() + })); + for n in normals { + let heights: Vec = m.positions.iter().map(|p| n.dot(*p)).filter(|h| h.is_finite()).collect(); + let (lo, hi) = heights.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), h| (a.min(*h), b.max(*h))); + let mut cuts: Vec = (0..=40).map(|k| lo - 1.0 + (hi - lo + 2.0) * k as f64 / 40.0).collect(); + cuts.extend(heights.iter().step_by(7).copied()); + cuts.extend([lo, hi]); + for at in cuts { + let o = n * at; + assert_eq!(bits(index.segments(m, o, n)), bits(view::section_segments(m, o, n)), "{n:?} at {at}"); + } } } } diff --git a/crates/engine/src/tests/mirror_placed.rs b/crates/engine/src/tests/mirror_placed.rs index 5afa7362f..396d8abee 100644 --- a/crates/engine/src/tests/mirror_placed.rs +++ b/crates/engine/src/tests/mirror_placed.rs @@ -232,3 +232,171 @@ fn a_placement_leading_to_another_component_is_reported_lost() { assert!(e.contains("no longer exists"), "{e}"); assert!(s.world_state().unwrap().body(©).is_none()); } + +/// A carriage-like part (a bored block and a ring) placed once, free to move: its occurrence and +/// body names. +fn curved_part(s: &mut Session) -> (u64, Vec) { + let c = run(s, "component.create", json!({"name": "Carriage", "grounded": false})); + run(s, "solid.box", json!({"length": 20, "width": 10, "height": 10, "corner": [10, 5, 0], "body_name": "Block"})); + run(s, "solid.cylinder", json!({"base": [20, 10, -1], "radius": 3, "height": 12, "operation": "cut", "targets": ["Block"]})); + run(s, "solid.torus", json!({"center": [20, 10, 20], "major": 6, "minor": 2, "operation": "new", "body_name": "Ring"})); + run(s, "component.activate", json!({"component": 0})); + run(s, "occurrence.move", json!({"occurrence": c["occurrence"], "translate": [0, 7, 3]})); + (c["occurrence"].as_u64().unwrap(), vec!["Block".into(), "Ring".into()]) +} + +/// The shown bodies drawn, as a viewport does, and the tessellation that took. +fn drawn(s: &Session) -> f64 { + let world = s.world_state().unwrap(); + let (_, work) = solidcraft_kernel::profile::capture(|| { + for b in &world.bodies { + b.mesh_in_place(); + b.display_plan(); + b.mesh(); + } + }); + work.tessellate_ms +} + +/// What the viewport shows is what a fresh evaluation of the design shows: where the triangles +/// are, which way they face and which faces and edges they belong to. +fn assert_as_evaluated_afresh(s: &Session) { + let mut fresh = solidcraft_doc::Model::new(); + fresh.no_cache = true; + fresh.evaluate(&s.doc); + assert!(fresh.results.iter().all(|r| r.error.is_none())); + let (shown, want) = (s.world_state().unwrap(), solidcraft_doc::world_state(&s.doc, &fresh.state()).unwrap()); + assert_eq!(shown.bodies.len(), want.bodies.len()); + for (a, b) in shown.bodies.iter().zip(&want.bodies) { + assert_eq!(a.name, b.name); + let (x, y) = (a.mesh(), b.mesh()); + assert_eq!(x.triangles, y.triangles, "{}", a.name); + assert_eq!(x.tri_face, y.tri_face, "{}", a.name); + assert_eq!(x.edge_faces, y.edge_faces, "{}", a.name); + assert_eq!(x.seams, y.seams, "{}", a.name); + assert_eq!(x.positions.len(), y.positions.len(), "{}", a.name); + assert!(x.edges.iter().flatten().zip(y.edges.iter().flatten()).all(|(p, q)| p.dist(*q) < 1e-7), "{}: edges", a.name); + assert_same_surface(&x, &y, &a.name); + // A plan's ties fall by the pose it was made at. + let (x, y) = (a.display_plan().unwrap().evaluate(), b.display_plan().unwrap().evaluate()); + assert_eq!(x.triangles.len(), y.triangles.len(), "{}: plan", a.name); + assert_same_surface(&x, &y, &a.name); + } +} + +/// Two meshes of one surface, facing the same way. Their points can differ: a revolved face is +/// turned by where it stands when it is made, which only moves where the surface is sampled. +fn assert_same_surface(x: &solidcraft_geom::Mesh, y: &solidcraft_geom::Mesh, name: &str) { + let enclosed = |m: &solidcraft_geom::Mesh| { + m.triangles.iter().fold((0.0, 0.0), |(v, s), t| { + let [a, b, c] = t.map(|i| m.positions[i as usize]); + (v + a.dot(b.cross(c)) / 6.0, s + (b - a).cross(c - a).len() / 2.0) + }) + }; + let ((v, s), (w, t)) = (enclosed(x), enclosed(y)); + assert!(v > 0.0 && (v - w).abs() < 1e-4 * w && (s - t).abs() < 1e-4 * t, "{name}: encloses {v}, {s} against {w}, {t}"); + let (a, b) = (x.bounds(), y.bounds()); + assert!(a.min.dist(b.min) < 0.05 && a.max.dist(b.max) < 0.05, "{name}: {a:?} against {b:?}"); +} + +/// Dragging a part with a mirrored copy moved the copy too, and every frame meshed the copy from +/// nothing: a design with a few dozen curved mirrored bodies dragged at a frame or two a second. +#[test] +fn dragging_a_mirrored_part_meshes_its_copies_once() { + let mut s = Session::default(); + let (occurrence, bodies) = curved_part(&mut s); + let first = run(&mut s, "solid.mirror", json!({"bodies": bodies, "plane": "XZ"})); + // Mirrored again, as four carriages from one are: the source of these copies moves as well. + run(&mut s, "solid.mirror", json!({"bodies": first["created_bodies"], "plane": "YZ"})); + drawn(&s); + for k in 1..=4 { + let at = f64::from(k) * 3.5; + run(&mut s, "occurrence.drag", json!({"occurrence": occurrence, "at": [0, 0, 0], "point": [1, at, 2], "continuous": true})); + assert!(s.model.last_recomputed > 0, "the copies follow the part"); + assert_eq!(drawn(&s), 0.0, "frame {k}: the copies are drawn from triangles already made"); + } + assert_as_evaluated_afresh(&s); + run(&mut s, "edit.undo", json!({})); + assert_as_evaluated_afresh(&s); +} + +/// What the viewport draws of a copy doesn't reach what the model reads: a later feature finds +/// the copy's own triangles, as it does in a design opened afresh. +#[test] +fn a_mirrored_copys_shared_triangles_are_display_only() { + let mut s = Session::default(); + let (occurrence, bodies) = curved_part(&mut s); + let r = run(&mut s, "solid.mirror", json!({"bodies": bodies, "plane": "XZ"})); + run(&mut s, "occurrence.drag", json!({"occurrence": occurrence, "at": [0, 0, 0], "point": [0, 3, 0], "continuous": true})); + drawn(&s); + let (state, world) = (s.model.state(), s.world_state().unwrap()); + for copy in r["created_bodies"].as_array().unwrap().iter().map(|n| n.as_str().unwrap()) { + assert!(world.body(copy).is_some_and(|b| b.cached_mesh().is_some()), "{copy} was drawn"); + assert!(state.body(copy).unwrap().cached_mesh().is_none(), "{copy}: the model's own mesh is its own"); + } +} + +/// A source changed is mirrored from what it is now, not from the triangles of what it was. +#[test] +fn a_changed_source_gives_its_copy_new_triangles() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "side", "expression": "10 mm"})); + let c = run(&mut s, "component.create", json!({"name": "Part", "grounded": false})); + run(&mut s, "solid.box", json!({"length": "side", "width": 10, "height": 10, "corner": [10, 0, 0], "body_name": "Block"})); + run(&mut s, "component.activate", json!({"component": 0})); + run(&mut s, "occurrence.move", json!({"occurrence": c["occurrence"], "translate": [0, 20, 0]})); + let copy = created(&run(&mut s, "solid.mirror", json!({"bodies": ["Block"], "plane": "XZ"}))); + assert_box(world_box(&s, ©), (Vec3::new(10.0, -30.0, 0.0), Vec3::new(20.0, -20.0, 10.0))); + run(&mut s, "parameters.change", json!({"name": "side", "expression": "15 mm"})); + assert_box(world_box(&s, ©), (Vec3::new(10.0, -30.0, 0.0), Vec3::new(25.0, -20.0, 10.0))); + assert_as_evaluated_afresh(&s); +} + +/// Copies nothing builds on skip the search that readies their revolved faces for a boolean. +/// A feature added later that does build on them gets them readied, as a design opened with that +/// feature has them, whether or not they were mirrored first. +#[test] +fn a_cut_added_after_a_mirror_finds_its_copies_readied() { + let cut = |s: &mut Session, copy: &str| { + run(s, "solid.cylinder", json!({"base": [20, -17, 15], "radius": 3, "height": 12, "operation": "cut", "targets": [copy]})); + }; + let mut s = Session::default(); + let (_, bodies) = curved_part(&mut s); + let copies = run(&mut s, "solid.mirror", json!({"bodies": bodies, "plane": "XZ"})); + let ring = copies["created_bodies"][1].as_str().unwrap().to_string(); + let evaluated = s.model.recomputed; + cut(&mut s, &ring); + assert!(s.model.results.iter().all(|r| r.error.is_none())); + assert!(s.model.recomputed - evaluated >= 2, "the mirror is evaluated again with the cut"); + let measured = |s: &Session| { + let v = run(&mut s.scratch(), "inspect.measure", json!({"bodies": [ring]})); + v["total"]["volume_mm3"].as_f64().unwrap() + }; + let volume = measured(&s); + let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + assert_eq!(measured(&reopened), volume, "what evaluates here is what opens"); +} + +/// A part inserted after the mirror keeps its meshes while the mirror moves: evaluating the +/// insert again gives the same solids, and meshing them was as slow as meshing the copies. +#[test] +fn an_insert_after_a_mirror_keeps_its_meshes_through_a_drag() { + let dir = std::env::temp_dir().join(format!("solidcraft-mirror-insert-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("insert.step").to_string_lossy().replace('\\', "/"); + let mut part = Session::default(); + run(&mut part, "solid.sphere", json!({"radius": 5})); + run(&mut part, "file.export", json!({"path": file})); + let mut s = Session::default(); + let (occurrence, bodies) = curved_part(&mut s); + run(&mut s, "solid.mirror", json!({"bodies": bodies, "plane": "XZ"})); + run(&mut s, "file.insert_step", json!({"path": file, "name": "After"})); + let _ = std::fs::remove_dir_all(&dir); + run(&mut s, "component.activate", json!({"component": 0})); + drawn(&s); + for k in 1..=3 { + run(&mut s, "occurrence.drag", json!({"occurrence": occurrence, "at": [0, 0, 0], "point": [0, f64::from(k), 0], "continuous": true})); + assert_eq!(drawn(&s), 0.0, "frame {k}"); + } + assert_as_evaluated_afresh(&s); +} diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index ddedb22c6..94d3d2b52 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -967,72 +967,143 @@ fn cut_triangle(m: &solidcraft_geom::Mesh, t: &[u32; 3], o: Vec3, n: Vec3, eps: } } -/// A mesh's triangles sorted into slabs along one normal, so cuts with that normal at any -/// height look only at the triangles of one slab: dragging a Section Analysis keeps the normal -/// and moves the cut, and an imported part can have millions of triangles. The same segments -/// as [`section_segments`]. +/// A mesh's triangles sorted into the cells of a grid by where their boxes sit, each cell +/// keeping the box around its triangles, so a cut with any plane looks only at the triangles of +/// the cells the plane crosses: an imported part can have millions of triangles, and dragging a +/// Section Analysis moves the cut and, when tilted, turns its normal every frame (#10373). The +/// same segments, in the same order, as [`section_segments`]. pub struct SectionIndex { - normal: Vec3, - /// The lowest height (`normal · p`) of the mesh, and the slab thickness. - start: f64, - step: f64, - /// Per slab, the triangles whose heights reach into it. - slabs: Vec>, + /// Per cell holding triangles, the centre and half size of the box around them, and where + /// they are in `tris` (in mesh order). + cells: Vec<(Vec3, Vec3, u32, u32)>, + tris: Vec, + /// Triangles with a corner that is not finite: cut on every plane, as `section_segments` + /// does. + always: Vec, + /// The largest coordinate of the mesh, for the cell test's rounding margin. + reach: f64, eps: f64, } -/// Slabs a [`SectionIndex`] makes, at most. -const SECTION_SLABS: usize = 4096; +/// How many mean triangle widths a [`SectionIndex`] cell is wide, and most cells of its grid. +const SECTION_CELL_WIDTHS: f64 = 4.0; +const SECTION_GRID: usize = 1 << 22; impl SectionIndex { - pub fn new(m: &solidcraft_geom::Mesh, normal: Vec3) -> SectionIndex { - let heights: Vec> = m + pub fn new(m: &solidcraft_geom::Mesh) -> SectionIndex { + let finite_tri = |t: &[u32; 3]| m.tri(t).filter(|p| p.iter().all(|q| q.is_finite())); + let mut always = Vec::new(); + let mut centres = Aabb3::EMPTY; + let (mut widths, mut count) = (0.0, 0usize); + for (i, t) in m.triangles.iter().enumerate() { + match finite_tri(t) { + Some([a, b, c]) => { + let (lo, hi) = (a.min(b).min(c), a.max(b).max(c)); + centres.add((lo + hi) * 0.5); + widths += (hi - lo).len(); + count += 1; + } + None if m.tri(t).is_some() => always.extend(u32::try_from(i)), + None => {} + } + } + // Cells as wide as a few triangles, on the axes the part spans: a part's triangles lie + // on its surface, so cells sized from the part's volume would hold far more. + let size = if centres.is_empty() { Vec3::ZERO } else { centres.size() }; + let ext = [size.x, size.y, size.z]; + let dims_for = |side: f64| ext.map(|e| if e > 0.0 && side > 0.0 { (e / side).ceil().clamp(1.0, SECTION_GRID as f64) as usize } else { 1 }); + let cells_of = |d: [usize; 3]| d.iter().fold(1usize, |p, k| p.saturating_mul(*k)); + let mut side = widths / count.max(1) as f64 * SECTION_CELL_WIDTHS; + while cells_of(dims_for(side)) > SECTION_GRID && side.is_finite() { + side *= 1.25; + } + let dims = dims_for(side); + let cells = cells_of(dims).min(SECTION_GRID); + let at = |v: f64, lo: f64, e: f64, d: usize| { + let k = if e > 0.0 { ((v - lo) / e * d as f64).floor() } else { 0.0 }; + if k.is_finite() { (k.max(0.0) as usize).min(d.saturating_sub(1)) } else { 0 } + }; + let of: Vec> = m .triangles .iter() .map(|t| { - let d = m.tri(t)?.map(|q| normal.dot(q)); - Some((d[0].min(d[1]).min(d[2]), d[0].max(d[1]).max(d[2]))) + let [a, b, c] = finite_tri(t)?; + let p = (a.min(b).min(c) + a.max(b).max(c)) * 0.5; + let [x, y, z] = + [at(p.x, centres.min.x, ext[0], dims[0]), at(p.y, centres.min.y, ext[1], dims[1]), at(p.z, centres.min.z, ext[2], dims[2])]; + Some(((z * dims[1] + y) * dims[0] + x).min(cells.saturating_sub(1))) }) .collect(); - let (lo, hi) = heights.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), (l, h)| (a.min(*l), b.max(*h))); - let count = if lo.is_finite() && hi.is_finite() { (m.triangles.len() / 64).clamp(1, SECTION_SLABS) } else { 0 }; - let step = if count > 0 && hi > lo { (hi - lo) / count as f64 } else { 1.0 }; - let mut index = SectionIndex { normal, start: lo, step, slabs: vec![Vec::new(); count], eps: section_nudge(m) }; - for (i, h) in heights.iter().enumerate() { - let (Some((l, h)), Ok(i)) = (h, u32::try_from(i)) else { continue }; - for k in index.slab(*l)..=index.slab(*h) { - if let Some(slab) = index.slabs.get_mut(k) { - slab.push(i); - } + // Counted per cell, then each cell's first slot (the last entry: the total). + let mut starts = vec![0u32; cells + 1]; + for c in of.iter().flatten() { + if let Some(s) = starts.get_mut(*c) { + *s += 1; } } - index - } - - /// The normal this index was made for. - pub fn normal(&self) -> Vec3 { - self.normal - } - - fn slab(&self, height: f64) -> usize { - let k = ((height - self.start) / self.step).floor(); - if k.is_finite() { (k.max(0.0) as usize).min(self.slabs.len().saturating_sub(1)) } else { 0 } + let mut total = 0u32; + for s in &mut starts { + (*s, total) = (total, total.saturating_add(*s)); + } + let mut fill = starts.clone(); + let mut tris = vec![0u32; total as usize]; + for (i, c) in of.iter().enumerate() { + let (Some(c), Ok(i)) = (c, u32::try_from(i)) else { continue }; + if let Some(at) = fill.get_mut(*c) { + if let Some(slot) = tris.get_mut(*at as usize) { + *slot = i; + } + *at += 1; + } + } + let mut reach: f64 = 0.0; + let cells = starts + .windows(2) + .filter_map(|w| match *w { + [a, e] if e > a => { + let mut b = Aabb3::EMPTY; + for i in tris.get(a as usize..e as usize).unwrap_or(&[]) { + for p in m.triangles.get(*i as usize).and_then(|t| m.tri(t)).into_iter().flatten() { + b.add(p); + } + } + reach = reach.max(b.min.x.abs().max(b.min.y.abs()).max(b.min.z.abs()).max(b.max.x.abs()).max(b.max.y.abs()).max(b.max.z.abs())); + Some((b.center(), b.size() * 0.5, a, e)) + } + _ => None, + }) + .collect(); + SectionIndex { cells, tris, always, reach, eps: section_nudge(m) } } /// [`section_segments`] of `m` (the mesh this index was made from) at the plane through - /// `o` with this index's normal. - pub fn segments(&self, m: &solidcraft_geom::Mesh, o: Vec3) -> Vec<(Vec3, Vec3)> { - let mut out = Vec::new(); - let at = self.normal.dot(o); - if self.slabs.is_empty() || !at.is_finite() || at < self.start { - return out; + /// `o` with normal `n`; nothing for a plane that is not finite. + pub fn segments(&self, m: &solidcraft_geom::Mesh, o: Vec3, n: Vec3) -> Vec<(Vec3, Vec3)> { + if !(o.is_finite() && n.is_finite()) { + return Vec::new(); } - for i in self.slabs.get(self.slab(at)).into_iter().flatten() { - if let Some(t) = m.triangles.get(*i as usize) { - cut_triangle(m, t, o, self.normal, self.eps, &mut out); + let an = Vec3::new(n.x.abs(), n.y.abs(), n.z.abs()); + // Rounding in `cut_triangle`'s heights is far below this margin, so a cell left out + // holds no triangle it would cut. + let margin = 1e-9 * (an.x + an.y + an.z) * (self.reach + o.x.abs().max(o.y.abs()).max(o.z.abs()) + 1.0); + let at = n.dot(o); + // The cut triangles' segments, by triangle, then in mesh order. + let mut found: Vec<(u32, (Vec3, Vec3))> = Vec::new(); + let mut out = Vec::with_capacity(1); + let mut cut = |i: u32| { + if let Some(t) = m.triangles.get(i as usize) { + cut_triangle(m, t, o, n, self.eps, &mut out); + found.extend(out.pop().map(|seg| (i, seg))); + } + }; + self.always.iter().for_each(|i| cut(*i)); + for (centre, half, first, end) in &self.cells { + if (n.dot(*centre) - at).abs() <= an.dot(*half) + margin { + self.tris.get(*first as usize..*end as usize).unwrap_or(&[]).iter().for_each(|i| cut(*i)); } } - out + found.sort_unstable_by_key(|(i, _)| *i); + found.into_iter().map(|(_, seg)| seg).collect() } } @@ -1062,12 +1133,12 @@ pub fn sketch_shown(s: &Session, id: u64) -> bool { v.shown_sketches.contains(&id) || !sketch_consumed(s, id) } -/// Is a sketch used by a later feature? A sheet metal base or contour flange uses its sketch as -/// an Extrude does: shown, its lines lie on the sheet's edges and take the clicks meant for -/// them (#6804). So does a Hole at sketch points: shown, its points are drawn in the holes -/// (#9082). A Single hole snapped to one point (#2110) does not: it was placed on a face, not -/// built from the sketch, and hiding the sketch would take its other points from the next -/// Single hole's snap. +/// Is a sketch used by a later feature? A sheet metal base or contour flange, or a perforation's +/// outline, uses its sketch as an Extrude does: shown, its lines lie on the sheet's edges and +/// faces and take the clicks meant for them (#6804). So does a Hole at sketch points: shown, its +/// points are drawn in the holes (#9082). A Single hole snapped to one point (#2110) does not: it +/// was placed on a face, not built from the sketch, and hiding the sketch would take its other +/// points from the next Single hole's snap. pub fn sketch_consumed(s: &Session, id: u64) -> bool { if let Ok(mut cache) = s.consumed_sketches_cache.lock() { if cache.as_ref().is_none_or(|c| !std::ptr::eq(c.doc.as_ptr(), Arc::as_ptr(&s.doc))) { @@ -1097,7 +1168,8 @@ fn consumed_sketches(doc: &solidcraft_doc::Document) -> impl Iterator Some(sketch.0), + | FeatureKind::Hole { points: Some(SketchPoints { sketch, single: false, .. }), .. } + | FeatureKind::SheetPerforate { sketch: Some(sketch), .. } => Some(sketch.0), _ => None, }) } diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs index bedca130d..f2001d488 100644 --- a/crates/gpu/src/view.rs +++ b/crates/gpu/src/view.rs @@ -3666,7 +3666,7 @@ impl Renderer { }; if phase == Phase::AfterSeeThrough { pass.set_bind_group(1, &res.access_bind, &[]); - pass.set_bind_group(2, &res.ao.bind, &[]); + pass.set_bind_group(2, &res.ao.maps.bind, &[]); Self::draw_over(res, pass, sk, h, pv, m, &tris, &lines); return; } @@ -3675,7 +3675,7 @@ impl Renderer { pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]); lines(pass, &res.overlay, &sk.under); pass.set_bind_group(1, &res.access_bind, &[]); - pass.set_bind_group(2, &res.ao.bind, &[]); + pass.set_bind_group(2, &res.ao.maps.bind, &[]); pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); // `counting`: only closed bodies, for a section's crossing count ([`Cut::count`]). let planned = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, counting: bool| { diff --git a/crates/gpu/src/view/ao.rs b/crates/gpu/src/view/ao.rs index f0aab0487..2449e6e58 100644 --- a/crates/gpu/src/view/ao.rs +++ b/crates/gpu/src/view/ao.rs @@ -1,68 +1,134 @@ -//! The optional AO depth prepass. Only opaque model and preview triangles participate: their -//! depth is drawn once into a single-sample depth map the lit fragment samples for occlusion. -//! The map is independent of the window's MSAA, and the depth runs the same way as the -//! viewport's own buffer (see [`super::depth_compare`] and [`super::far_depth`]). +//! The optional AO passes. Only opaque model and preview triangles participate: their depth is +//! drawn once into a single-sample depth map, and the occlusion term of the surface that depth +//! holds is drawn into a texture of the same size and blurred by depth (#9327), which the lit +//! fragment reads. The maps are independent of the window's MSAA, and the depth runs the same way +//! as the viewport's own buffer (see [`super::depth_compare`] and [`super::far_depth`]). //! Depth testing chooses the nearest surface; an R32Uint colour attachment stores that depth's //! bits for portable integer texel reads. GLSL cannot load from a depth texture, and float //! colour attachments are not available on every GL adapter. use super::{Batches, TriSource, color_layout, depth_compare, far_depth, instance_layout, planned_layout, shared_layout, tri_layout}; -pub(super) struct Resources { - pub layout: wgpu::BindGroupLayout, - pub bind: wgpu::BindGroup, - depth: wgpu::TextureView, - values: wgpu::TextureView, - size: [u32; 2], - pipeline: wgpu::RenderPipeline, - planned_pipeline: wgpu::RenderPipeline, - instanced_pipeline: wgpu::RenderPipeline, - instanced_flat_pipeline: wgpu::RenderPipeline, +const TERM_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R8Unorm; + +/// What the opaque triangles are drawn with in one pass, by where they come from. +struct OpaquePipelines { + built: wgpu::RenderPipeline, + planned: wgpu::RenderPipeline, + instanced: wgpu::RenderPipeline, + instanced_flat: wgpu::RenderPipeline, } -fn texture(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, size: [u32; 2]) -> (wgpu::TextureView, wgpu::TextureView, wgpu::BindGroup) { - let texture = |label, format, usage| { - device.create_texture(&wgpu::TextureDescriptor { +/// The maps at their current size. Group 2 of the shader is the depth map and a term: `bind` has +/// the blurred one for the lit pass, `blur_bind` the raw one for the blur. +pub(super) struct Maps { + pub bind: wgpu::BindGroup, + blur_bind: wgpu::BindGroup, + depth: wgpu::TextureView, + values: wgpu::TextureView, + raw: wgpu::TextureView, + smooth: wgpu::TextureView, +} + +pub(super) struct Resources { + pub layout: wgpu::BindGroupLayout, + pub maps: Maps, + size: [u32; 2], + prepass: OpaquePipelines, + term: OpaquePipelines, + blur: wgpu::RenderPipeline, +} + +fn maps(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, size: [u32; 2]) -> Maps { + let view = |label, format, usage| { + device + .create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + .create_view(&Default::default()) + }; + let drawn_and_read = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING; + let depth = view("sc_ao_depth", wgpu::TextureFormat::Depth32Float, wgpu::TextureUsages::RENDER_ATTACHMENT); + let values = view("sc_ao_values", wgpu::TextureFormat::R32Uint, drawn_and_read); + let raw = view("sc_ao_raw", TERM_FORMAT, drawn_and_read); + let smooth = view("sc_ao_smooth", TERM_FORMAT, drawn_and_read); + let group = |label, term| { + device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some(label), - size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format, - usage, - view_formats: &[], + layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&values) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(term) }, + ], }) }; - let depth = texture("sc_ao_depth", wgpu::TextureFormat::Depth32Float, wgpu::TextureUsages::RENDER_ATTACHMENT).create_view(&Default::default()); - let values = texture("sc_ao_values", wgpu::TextureFormat::R32Uint, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING) - .create_view(&Default::default()); - let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("sc_ao_depth"), - layout, - entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&values) }], - }); - (depth, values, bind) + Maps { bind: group("sc_ao_lit", &smooth), blur_bind: group("sc_ao_blur", &raw), depth, values, raw, smooth } +} + +/// A term map as a pass's target, cleared to no occlusion. +fn term_target(view: &wgpu::TextureView) -> Option> { + Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::WHITE), store: wgpu::StoreOp::Store }, + }) +} + +/// The opaque triangles of `batches`, as neither pass counts them in the performance overlay. +fn draw_opaque(pass: &mut wgpu::RenderPass<'_>, pipelines: &OpaquePipelines, binds: [&wgpu::BindGroup; 2], batches: [&Batches; 2]) { + for (batch, bind) in batches.into_iter().zip(binds) { + pass.set_bind_group(0, bind, &[]); + pass.set_pipeline(&pipelines.built); + for tris in [&batch.tris, &batch.open_tris].into_iter().flatten() { + for (buffer, count) in &tris.parts { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw(0..*count, 0..1); + } + } + let uncounted = super::Tally::default(); + // The blocks' opaque triangles, for the same depth. + for key in &batch.block_order { + if let Some(block) = batch.blocks.get(key) { + block.draw(pass, super::TriClass::Opaque, &uncounted); + } + } + pass.set_pipeline(&pipelines.planned); + for draw in batch.planned.iter().filter(|d| d.class == super::TriClass::Opaque) { + pass.set_vertex_buffer(0, draw.mesh.vertices.slice(..)); + pass.set_vertex_buffer(1, draw.colors.slice(..)); + pass.set_index_buffer(draw.mesh.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..draw.mesh.index_count, 0, 0..1); + } + for draw in batch.instanced.iter().filter(|d| d.look == super::InstanceLook::Opaque) { + draw.draw(pass, &pipelines.instanced, &pipelines.instanced_flat, &uncounted); + } + } } impl Resources { - /// The layout of the depth map's bind group, which the lit pipelines' layout includes. + /// The layout of the maps' bind groups, which the lit pipelines' layout includes. pub fn layout(device: &wgpu::Device) -> wgpu::BindGroupLayout { + let entry = |binding, sample_type| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { sample_type, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }, + count: None, + }; device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("sc_ao_depth"), - entries: &[wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Uint, - view_dimension: wgpu::TextureViewDimension::D2, - multisampled: false, - }, - count: None, - }], + label: Some("sc_ao_maps"), + entries: &[entry(0, wgpu::TextureSampleType::Uint), entry(1, wgpu::TextureSampleType::Float { filterable: false })], }) } - /// The prepass's pipelines and a 1 x 1 stand-in map, bound with `layout` ([`Resources::layout`]). + /// The passes' pipelines and 1 x 1 stand-in maps, bound with `layout` ([`Resources::layout`]). pub fn new( device: &wgpu::Device, layout: &wgpu::BindGroupLayout, @@ -71,57 +137,82 @@ impl Resources { reversed: bool, ) -> Self { let layout = layout.clone(); - let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + let prepass_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("sc_ao_prepass"), bind_group_layouts: &[Some(uniform)], immediate_size: 0, }); + let term_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("sc_ao_term"), + bind_group_layouts: &[Some(uniform), None, Some(&layout)], + immediate_size: 0, + }); let built = [Some(tri_layout())]; let evaluated = [Some(planned_layout()), Some(color_layout())]; let placed = [Some(shared_layout()), Some(instance_layout())]; - let pipeline = |source: TriSource| { - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("sc_ao_prepass"), - layout: Some(&pipeline_layout), - vertex: wgpu::VertexState { - module, - entry_point: Some(source.entry()), - buffers: match source { - TriSource::Built => &built[..], - TriSource::Planned => &evaluated[..], - TriSource::Instanced | TriSource::InstancedFlat => &placed[..], + let target = |format| [Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::RED })]; + let opaque = |label, layout: &wgpu::PipelineLayout, fragment: &str, format, depth_write_enabled, compare| { + let pipeline = |source: TriSource| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(layout), + vertex: wgpu::VertexState { + module, + entry_point: Some(source.entry()), + buffers: match source { + TriSource::Built => &built[..], + TriSource::Planned => &evaluated[..], + TriSource::Instanced | TriSource::InstancedFlat => &placed[..], + }, + compilation_options: Default::default(), }, - compilation_options: Default::default(), - }, - primitive: wgpu::PrimitiveState::default(), - depth_stencil: Some(wgpu::DepthStencilState { - format: wgpu::TextureFormat::Depth32Float, - depth_write_enabled: Some(true), - depth_compare: Some(depth_compare(reversed, wgpu::CompareFunction::Less)), - stencil: Default::default(), - bias: Default::default(), - }), - multisample: wgpu::MultisampleState::default(), - fragment: Some(wgpu::FragmentState { - module, - entry_point: Some(&source.fragment("fs_ao_depth")), - targets: &[Some(wgpu::ColorTargetState { - format: wgpu::TextureFormat::R32Uint, - blend: None, - write_mask: wgpu::ColorWrites::RED, - })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - }) + primitive: wgpu::PrimitiveState::default(), + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(depth_write_enabled), + depth_compare: Some(depth_compare(reversed, compare)), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module, + entry_point: Some(&source.fragment(fragment)), + targets: &target(format), + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }; + OpaquePipelines { + built: pipeline(TriSource::Built), + planned: pipeline(TriSource::Planned), + instanced: pipeline(TriSource::Instanced), + instanced_flat: pipeline(TriSource::InstancedFlat), + } }; - let planned_pipeline = pipeline(TriSource::Planned); - let instanced_pipeline = pipeline(TriSource::Instanced); - let instanced_flat_pipeline = pipeline(TriSource::InstancedFlat); - let pipeline = pipeline(TriSource::Built); - let (depth, values, bind) = texture(device, &layout, [1, 1]); - Self { layout, bind, depth, values, size: [1, 1], pipeline, planned_pipeline, instanced_pipeline, instanced_flat_pipeline } + let prepass = opaque("sc_ao_prepass", &prepass_layout, "fs_ao_depth", wgpu::TextureFormat::R32Uint, true, wgpu::CompareFunction::Less); + // The term only where the prepass's depth is, so each pixel's term is worked out once. + let term = opaque("sc_ao_term", &term_layout, "fs_ao_term", TERM_FORMAT, false, wgpu::CompareFunction::LessEqual); + let blur = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("sc_ao_blur"), + layout: Some(&term_layout), + vertex: wgpu::VertexState { module, entry_point: Some("vs_ao_blur"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module, + entry_point: Some("fs_ao_blur"), + targets: &target(TERM_FORMAT), + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }); + let maps = maps(device, &layout, [1, 1]); + Self { layout, maps, size: [1, 1], prepass, term, blur } } pub fn prepare( @@ -138,7 +229,7 @@ impl Resources { // Bound memory at large window sizes; normalized coordinates also handle downsampling. let size = target_size(enabled, size_px, device.limits().max_texture_dimension_2d); if size != self.size { - (self.depth, self.values, self.bind) = texture(device, &self.layout, size); + self.maps = maps(device, &self.layout, size); self.size = size; } if !enabled { @@ -147,7 +238,7 @@ impl Resources { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("sc_ao_prepass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &self.values, + view: &self.maps.values, depth_slice: None, resolve_target: None, ops: wgpu::Operations { @@ -156,7 +247,7 @@ impl Resources { }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &self.depth, + view: &self.maps.depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(far_depth(reversed)), store: wgpu::StoreOp::Store }), stencil_ops: None, }), @@ -164,34 +255,35 @@ impl Resources { occlusion_query_set: None, multiview_mask: None, }); - for (batch, bind) in batches.into_iter().zip(binds) { - pass.set_bind_group(0, bind, &[]); - pass.set_pipeline(&self.pipeline); - for tris in [&batch.tris, &batch.open_tris].into_iter().flatten() { - for (buffer, count) in &tris.parts { - pass.set_vertex_buffer(0, buffer.slice(..)); - pass.draw(0..*count, 0..1); - } - } - // The depth prepass is left out of the performance overlay's counts, as before. - let uncounted = super::Tally::default(); - // The blocks' opaque triangles, for the same depth. - for key in &batch.block_order { - if let Some(block) = batch.blocks.get(key) { - block.draw(&mut pass, super::TriClass::Opaque, &uncounted); - } - } - pass.set_pipeline(&self.planned_pipeline); - for draw in batch.planned.iter().filter(|d| d.class == super::TriClass::Opaque) { - pass.set_vertex_buffer(0, draw.mesh.vertices.slice(..)); - pass.set_vertex_buffer(1, draw.colors.slice(..)); - pass.set_index_buffer(draw.mesh.indices.slice(..), wgpu::IndexFormat::Uint32); - pass.draw_indexed(0..draw.mesh.index_count, 0, 0..1); - } - for draw in batch.instanced.iter().filter(|d| d.look == super::InstanceLook::Opaque) { - draw.draw(&mut pass, &self.instanced_pipeline, &self.instanced_flat_pipeline, &uncounted); - } - } + draw_opaque(&mut pass, &self.prepass, binds, batches); + drop(pass); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("sc_ao_term"), + color_attachments: &[term_target(&self.maps.raw)], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &self.maps.depth, + depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Discard }), + stencil_ops: None, + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_bind_group(2, &self.maps.bind, &[]); + draw_opaque(&mut pass, &self.term, binds, batches); + drop(pass); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("sc_ao_blur"), + color_attachments: &[term_target(&self.maps.smooth)], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&self.blur); + pass.set_bind_group(0, binds[0], &[]); + pass.set_bind_group(2, &self.maps.blur_bind, &[]); + pass.draw(0..3, 0..1); } } diff --git a/crates/io/src/design_lock.rs b/crates/io/src/design_lock.rs index 6a4daf361..f8376d308 100644 --- a/crates/io/src/design_lock.rs +++ b/crates/io/src/design_lock.rs @@ -15,6 +15,7 @@ //! The browser build keeps neither: it has no shared folders, and no clock in `std`. use serde::{Deserialize, Serialize}; +use std::io::Read; use std::path::{Path, PathBuf}; /// How often an open design's lock is written again. @@ -109,16 +110,29 @@ fn user_name() -> String { ["USER", "USERNAME", "LOGNAME"].iter().find_map(|k| std::env::var(k).ok().filter(|v| !v.trim().is_empty())).unwrap_or_default() } -/// The lock next to the design at `path`, if there is a readable one. +/// The lock next to the design at `path`, if there is a readable one. Anything at the lock's path +/// but a regular file (a symbolic link, a device, a FIFO) is no lock and is not opened, and no +/// more than a lock's size is ever read. pub fn read(path: &Path) -> Option { if cfg!(target_arch = "wasm32") { return None; } let file = lock_path(path); - if std::fs::metadata(&file).ok()?.len() > MAX_LOCK_BYTES { + let meta = std::fs::symlink_metadata(&file).ok().filter(std::fs::Metadata::is_file)?; + if meta.len() > MAX_LOCK_BYTES { return None; } - serde_json::from_slice(&std::fs::read(&file).ok()?).ok() + let opened = std::fs::File::open(&file).ok()?; + // The path may have been swapped between the two calls; the handle decides. + if !opened.metadata().ok()?.is_file() { + return None; + } + let mut bytes = Vec::new(); + opened.take(MAX_LOCK_BYTES + 1).read_to_end(&mut bytes).ok()?; + if bytes.len() as u64 > MAX_LOCK_BYTES { + return None; + } + serde_json::from_slice(&bytes).ok() } /// Another app's fresh lock on the design at `path` at `now`: it is open elsewhere. @@ -126,10 +140,12 @@ pub fn held_elsewhere(path: &Path, now: u64) -> Option { read(path).filter(|l| !l.is_mine() && !l.is_stale(now)) } -/// Write `lock` next to the design at `path` (replacing whatever lock is there). +/// Write `lock` next to the design at `path`, replacing whatever lock is there. A symbolic link +/// at the lock's path is refused and never followed, unlike a save, which follows a link to where +/// the design really lives: the file a link there points to is not this app's to replace. pub fn write(path: &Path, lock: &Lock) -> std::io::Result<()> { let bytes = serde_json::to_vec_pretty(lock).map_err(std::io::Error::other)?; - crate::safe_write::write_atomic(&lock_path(path), &bytes, false) + crate::safe_write::write_atomic_no_follow(&lock_path(path), &bytes) } /// Remove this process's lock on the design at `path`; another app's lock is left alone. diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index f26cfe4c9..0cce0c892 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -423,9 +423,14 @@ pub fn export_mesh_at(b: &solidcraft_kernel::Body, quality: MeshQuality) -> Resu Ok(b.mesh(&solidcraft_kernel::MeshTolerance::chord((b.size() * quality.share()).max(1e-3)))?) } -/// Distance within which an exported mesh's vertices are welded (STL and 3MF alike). +/// Distance within which an exported mesh's vertices are welded (STL, 3MF and OBJ alike). fn weld_eps(b: &solidcraft_kernel::Body) -> f64 { - (b.size() * 1e-6).max(1e-7) + weld_distance(b.size()) +} + +/// [`weld_eps`] for a body of characteristic size (bounding box diagonal) `size`. +fn weld_distance(size: f64) -> f64 { + (size * 1e-6).max(1e-7) } /// Unit-density [`MassProperties`] of a body from its welded [`export_mesh`], the mesh URDF links @@ -540,49 +545,81 @@ pub fn obj_files(bodies: &[ObjBody<'_>], mtl_name: &str) -> ObjFiles { ObjFiles { obj, mtl } } -/// The mesh of a body: its vertices and normals, each written once per distinct value, and the -/// faces that use them. Returns the text and the bases the next body carries on from. +/// The mesh of a body, welded as STL and 3MF are ([`weld`]: vertices closer than +/// [`weld_distance`] merged, and sides split where another face's vertex lies on them), so +/// neighbouring faces share their edge points and the file opens again as a closed solid +/// (#9074). Each corner keeps the normal it had ([`corner_normals`]), so edges between faces +/// stay sharp. Vertices and normals are each written once per distinct value. Returns the text +/// and the bases the next body carries on from. fn mesh_text(mesh: &Mesh, vbase: usize, nbase: usize) -> (String, usize, usize) { use std::collections::HashMap; - let mut s = String::new(); - // `+ 0.0` turns -0 into 0, so both merge. - let key = |x: f64, y: f64, z: f64| [x + 0.0, y + 0.0, z + 0.0].map(f64::to_bits); - let mut vmap: HashMap<[u64; 3], usize> = HashMap::new(); - let mut nmap: HashMap<[u64; 3], usize> = HashMap::new(); - let vi: Vec = mesh - .positions - .iter() - .map(|p| { - let next = vmap.len(); - *vmap.entry(key(p.x, p.y, p.z)).or_insert_with(|| { - s += &format!("v {} {} {}\n", p.x, p.y, p.z); - next - }) - }) - .collect(); - let ni: Vec = mesh - .normals - .iter() - .map(|n| { - let next = nmap.len(); - *nmap.entry(key(n.x, n.y, n.z)).or_insert_with(|| { - s += &format!("vn {} {} {}\n", n.x, n.y, n.z); - next - }) - }) - .collect(); - for t in &mesh.triangles { - let (Some(a), Some(b), Some(c)) = (vi.get(t[0] as usize), vi.get(t[1] as usize), vi.get(t[2] as usize)) else { continue }; - let (a, b, c) = (a + vbase, b + vbase, c + vbase); - match (ni.get(t[0] as usize), ni.get(t[1] as usize), ni.get(t[2] as usize)) { - (Some(na), Some(nb), Some(nc)) => { - let (na, nb, nc) = (na + nbase, nb + nbase, nc + nbase); - s += &format!("f {a}//{na} {b}//{nb} {c}//{nc}\n"); - } - _ => s += &format!("f {a} {b} {c}\n"), - } + let mut bounds = solidcraft_geom::Aabb3::EMPTY; + for p in &mesh.positions { + bounds.add(*p); } - (s, vbase + vmap.len(), nbase + nmap.len()) + let eps = weld_distance(bounds.diagonal()); + // Each welded triangle is tagged with the triangle it came from, for its normals. + let source: Vec = (0..mesh.triangles.len()).map(|k| u32::try_from(k).unwrap_or(u32::MAX)).collect(); + let (positions, triangles, from) = threemf::weld_tagged(&mesh.positions, &mesh.triangles, &source, eps); + let mut s = String::new(); + for p in &positions { + s += &format!("v {} {} {}\n", p.x, p.y, p.z); + } + // `+ 0.0` turns -0 into 0, so both merge. + let key = |n: Vec3| [n.x + 0.0, n.y + 0.0, n.z + 0.0].map(f64::to_bits); + let mut nmap: HashMap<[u64; 3], usize> = HashMap::new(); + let mut faces = String::new(); + for (t, k) in triangles.iter().zip(&from) { + let (a, b, c) = (t[0] as usize + vbase, t[1] as usize + vbase, t[2] as usize + vbase); + let at = t.map(|i| positions.get(i as usize).copied()); + let normals = match (mesh.triangles.get(*k as usize), at) { + (Some(o), [Some(pa), Some(pb), Some(pc)]) => corner_normals(mesh, *o, [pa, pb, pc], eps), + _ => None, + }; + let Some(normals) = normals else { + faces += &format!("f {a} {b} {c}\n"); + continue; + }; + let [na, nb, nc] = normals.map(|n| { + let next = nmap.len(); + nbase + + *nmap.entry(key(n)).or_insert_with(|| { + s += &format!("vn {} {} {}\n", n.x, n.y, n.z); + next + }) + }); + faces += &format!("f {a}//{na} {b}//{nb} {c}//{nc}\n"); + } + s += &faces; + (s, vbase + positions.len(), nbase + nmap.len()) +} + +/// The normals at the corners `at` of a welded piece of triangle `t` of `mesh` (the whole +/// triangle, or a piece of it split where another face's vertex lies on a side): a corner +/// within `eps` of one of `t`'s own corners takes that corner's normal; a point a side was split +/// at takes the normal between the side's ends. `None` when the mesh has no normals there. +fn corner_normals(mesh: &Mesh, t: [u32; 3], at: [Vec3; 3], eps: f64) -> Option<[Vec3; 3]> { + let p = t.map(|i| mesh.positions.get(i as usize).copied()); + let n = t.map(|i| mesh.normals.get(i as usize).copied()); + let ([Some(p0), Some(p1), Some(p2)], [Some(n0), Some(n1), Some(n2)]) = (p, n) else { return None }; + let (p, n) = ([p0, p1, p2], [n0, n1, n2]); + Some(at.map(|q| p.iter().zip(n).find(|(c, _)| c.dist(q) <= eps).map_or_else(|| normal_at(p, n, q), |(_, n)| n))) +} + +/// The normal at `q` on the triangle with corners `p` and corner normals `n`: the corners' +/// normals weighted by where `q` lies (barycentric), of unit length. The first corner's when +/// the triangle has no area. +fn normal_at(p: [Vec3; 3], n: [Vec3; 3], q: Vec3) -> Vec3 { + let [p0, p1, p2] = p; + let [n0, n1, n2] = n; + let (e1, e2, d) = (p1 - p0, p2 - p0, q - p0); + let (d11, d12, d22, d1, d2) = (e1.dot(e1), e1.dot(e2), e2.dot(e2), d.dot(e1), d.dot(e2)); + let den = d11 * d22 - d12 * d12; + if !(den.abs() > 0.0) { + return n0; + } + let (v, w) = ((d22 * d1 - d12 * d2) / den, (d11 * d2 - d12 * d1) / den); + (n0 * (1.0 - v - w) + n1 * v + n2 * w).normalized().unwrap_or(n0) } /// The material of each body: its name, safe to write in a material library and unique among @@ -1234,9 +1271,8 @@ mod tests { .sum() } - /// Build → export 3MF → import → the same volume as the STL export, closed meshes, names. - #[test] - fn threemf_round_trip() { + /// A filleted box, a cylinder and a torus: bodies whose faces are curved and meshed apart. + fn curved_bodies() -> Model { let mut doc = Document::new("t"); doc.add_feature( FeatureKind::Box { @@ -1287,6 +1323,40 @@ mod tests { .unwrap(); let mut m = Model::new(); m.evaluate(&doc); + m + } + + /// OBJ is welded as STL and 3MF are: a filleted box, a cylinder and a torus written as OBJ + /// open again closed, with their STL export's volume, every face keeping its normals + /// (#9074). Before, each face wrote its edge points again, a few ulps apart, and the file + /// opened as an open mesh with no volume. + #[test] + fn obj_round_trip_of_curved_bodies_is_closed() { + let m = curved_bodies(); + let st = m.state(); + let bytes = export(&st, &[], Format::Obj, "t").unwrap(); + let text = String::from_utf8(bytes.clone()).unwrap(); + assert!(text.lines().filter(|l| l.starts_with("f ")).all(|l| l.matches("//").count() == 3), "every corner has a normal"); + let f = mesh_import_feature(&bytes, "parts.obj").unwrap(); + let mut d2 = Document::new("m"); + let id = d2.add_feature(f.kind, Some(&f.name)).unwrap(); + let mut m2 = Model::new(); + m2.evaluate(&d2); + assert!(m2.result(id).unwrap().error.is_none()); + let st2 = m2.state(); + assert_eq!(st2.bodies.len(), 3); + for (a, b) in st.bodies.iter().zip(&st2.bodies) { + assert!(b.body.is_mesh() && b.body.is_closed_mesh(), "{} is not watertight", a.name); + let v_stl = stl_volume(&export(&st, std::slice::from_ref(&a.name), Format::StlBinary, "t").unwrap()); + let v = solidcraft_kernel::measure(&b.body).unwrap().volume; + assert!((v - v_stl).abs() <= 1e-6 * v_stl.abs(), "{}: {v} vs {v_stl}", a.name); + } + } + + /// Build → export 3MF → import → the same volume as the STL export, closed meshes, names. + #[test] + fn threemf_round_trip() { + let m = curved_bodies(); let st = m.state(); assert_eq!(st.bodies.len(), 3); let bytes = export(&st, &[], Format::ThreeMf, "t").unwrap(); diff --git a/crates/io/src/safe_write.rs b/crates/io/src/safe_write.rs index ebe9184a2..baf309ea0 100644 --- a/crates/io/src/safe_write.rs +++ b/crates/io/src/safe_write.rs @@ -226,13 +226,17 @@ fn write_steps(path: &Path, bytes: &[u8], backup: bool, stop: Option) -> s return Err(e); } sync_dir(path); - // Temporary files of saves that crashed part way (a minute old or more) go. - for t in stale_temps(path) { - if fs::metadata(&t).and_then(|m| m.modified()).ok().and_then(|m| m.elapsed().ok()).is_some_and(|age| age.as_secs() >= 60) { + remove_old_temps(path); + Ok(()) +} + +/// Temporary files of saves that crashed part way (a minute old or more) go. +fn remove_old_temps(path: &Path) { + for t in temps_beside(path) { + if fs::symlink_metadata(&t).and_then(|m| m.modified()).ok().and_then(|m| m.elapsed().ok()).is_some_and(|age| age.as_secs() >= 60) { let _ = fs::remove_file(t); } } - Ok(()) } /// Write `bytes` to `path` atomically; with `backup`, the file being replaced is kept as @@ -249,6 +253,34 @@ pub fn write_atomic(path: &Path, bytes: &[u8], backup: bool) -> std::io::Result< write_steps(&resolve_links(path)?, bytes, backup, None) } +/// Write `bytes` to the file named `path` itself, atomically: a link at `path` is never followed, +/// and what it points to is never touched. Anything there that isn't a regular file is refused. For +/// the app's own small files beside a design, which never live anywhere else. +pub fn write_atomic_no_follow(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + if cfg!(target_arch = "wasm32") { + return crate::vfs::write(&path.to_string_lossy(), bytes); + } + let there = fs::symlink_metadata(path).ok(); + if there.as_ref().is_some_and(|m| !m.is_file()) { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{}: not a regular file", path.display()))); + } + let tmp = temp_beside(path, "new"); + if let Err(e) = write_synced(&tmp, bytes) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + keep_permissions(&there.map(|m| m.permissions()), &tmp); + // A rename replaces the name itself, so a link put there since the check above goes, and the + // file it pointed to stays as it was. + if let Err(e) = replace_synced(&tmp, path) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + sync_dir(path); + remove_old_temps(path); + Ok(()) +} + /// Publish a complete new file without replacing an existing destination, even if another /// writer creates it after this call starts. Unsupported filesystems return an error. pub fn create_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { @@ -275,8 +307,11 @@ pub fn create_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { /// Leftover temporary files of saves that never finished (a crash part way), next to `path` /// (next to the file a link at `path` points to, where a save puts them). pub fn stale_temps(path: &Path) -> Vec { - let resolved = resolve_links(path).unwrap_or_else(|_| path.to_path_buf()); - let path = resolved.as_path(); + temps_beside(&resolve_links(path).unwrap_or_else(|_| path.to_path_buf())) +} + +/// The leftover temporary files of the file named `path` itself. +fn temps_beside(path: &Path) -> Vec { let Some(name) = path.file_name().map(|n| n.to_string_lossy().to_string()) else { return Vec::new() }; let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); let prefix = format!(".{name}."); @@ -407,6 +442,104 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A link at the lock's path is neither written through nor read through, and closing the + /// design leaves it alone. A save still follows a link at the design's own path. + #[cfg(unix)] + #[test] + fn a_link_at_the_lock_path_is_never_followed() { + use crate::design_lock as lock; + use std::os::unix::fs::symlink; + let d = dir("design-lock-link"); + let design = d.join("Bracket.solidcraft"); + std::fs::write(&design, b"one").unwrap(); + let lock_file = lock::lock_path(&design); + let now = lock::now_secs(); + let mine = lock::Lock::mine(now); + + let victim = d.join("victim.txt"); + std::fs::write(&victim, b"keep me").unwrap(); + symlink(&victim, &lock_file).unwrap(); + assert!(lock::write(&design, &mine).is_err()); + assert_eq!(std::fs::read(&victim).unwrap(), b"keep me"); + assert!(std::fs::symlink_metadata(&lock_file).unwrap().file_type().is_symlink(), "the link is refused, not replaced"); + std::fs::remove_file(&lock_file).unwrap(); + + // A link to a place with nothing there doesn't make the file either. + let missing = d.join("made-by-the-link.txt"); + symlink(&missing, &lock_file).unwrap(); + assert!(lock::write(&design, &mine).is_err()); + assert!(!missing.exists()); + std::fs::remove_file(&lock_file).unwrap(); + + // A link to a real lock is no lock: nothing is read through it, and closing leaves it. + let elsewhere = d.join("elsewhere.lock"); + std::fs::write(&elsewhere, serde_json::to_vec(&mine).unwrap()).unwrap(); + symlink(&elsewhere, &lock_file).unwrap(); + assert!(lock::read(&design).is_none()); + lock::remove(&design); + assert!(std::fs::symlink_metadata(&lock_file).is_ok() && elsewhere.exists()); + std::fs::remove_file(&lock_file).unwrap(); + + // A hard link is a regular file: its name is replaced, the other name keeps its content. + let other_name = d.join("other-name.txt"); + std::fs::write(&other_name, b"keep me too").unwrap(); + std::fs::hard_link(&other_name, &lock_file).unwrap(); + lock::write(&design, &mine).unwrap(); + assert_eq!(std::fs::read(&other_name).unwrap(), b"keep me too"); + assert!(lock::read(&design).is_some_and(|l| l.is_mine())); + std::fs::remove_file(&lock_file).unwrap(); + + // Nothing there, and no temporary file left: a plain lock is still written. + lock::write(&design, &mine).unwrap(); + assert_eq!(lock::read(&design), Some(mine)); + assert!(stale_temps(&lock_file).is_empty()); + + // The design's own link is still followed by a save. + let real = d.join("real.solidcraft"); + std::fs::write(&real, b"old").unwrap(); + let linked = d.join("linked.solidcraft"); + symlink(&real, &linked).unwrap(); + write_atomic(&linked, b"new", false).unwrap(); + assert_eq!(std::fs::read(&real).unwrap(), b"new"); + assert!(std::fs::symlink_metadata(&linked).unwrap().file_type().is_symlink()); + let _ = std::fs::remove_dir_all(&d); + } + + /// A lock path that isn't a regular file is ignored at once. Read on a thread, so a regression + /// fails here rather than holding up the test run. + #[cfg(unix)] + #[test] + fn a_lock_path_that_is_not_a_regular_file_is_ignored_at_once() { + use crate::design_lock as lock; + use std::os::unix::fs::symlink; + let d = dir("design-lock-special"); + let design = d.join("Bracket.solidcraft"); + let lock_file = lock::lock_path(&design); + let read_soon = |design: &Path| { + let (tx, rx) = std::sync::mpsc::channel(); + let design = design.to_path_buf(); + std::thread::spawn(move || { + let _ = tx.send(lock::read(&design)); + }); + rx.recv_timeout(std::time::Duration::from_secs(10)).expect("read returned") + }; + let cases: [&dyn Fn(&Path); 3] = [&|p| symlink("/dev/zero", p).unwrap(), &|p| std::fs::create_dir(p).unwrap(), &|p| { + assert!(std::process::Command::new("mkfifo").arg(p).status().unwrap().success()) + }]; + for make in cases { + make(&lock_file); + assert!(read_soon(&design).is_none()); + assert!(lock::held_elsewhere(&design, lock::now_secs()).is_none()); + assert!(lock::write(&design, &lock::Lock::mine(lock::now_secs())).is_err()); + assert!(std::fs::symlink_metadata(&lock_file).is_ok(), "left where it is"); + let _ = std::fs::remove_file(&lock_file).or_else(|_| std::fs::remove_dir(&lock_file)); + } + // A regular file too large to be a lock is not read either. + std::fs::write(&lock_file, vec![b' '; 4097]).unwrap(); + assert!(read_soon(&design).is_none()); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn create_does_not_replace_an_existing_destination() { let d = dir("create"); diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 9dc8e3960..3627436f7 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -224,6 +224,10 @@ pub fn fillet_removing(body: &Body, edges: &[Vec3], radius: f64) -> Result<(Body Ok((closed(body, b)?, gone)) } +/// What a refusal of a setback too short for its corner says before the least that builds (in +/// mm): SMLib certifies the corner's fill convex only from that setback on ([`fillet_setback`]). +pub const SETBACK_AT_LEAST: &str = "the smallest setback that builds is "; + /// [`fillet`] with corner setbacks: each `(at, distance)` sets back the corner at the vertex /// nearest `at`, a vertex where every edge is rounded, so its patch starts `distance` along /// each of its edges from the vertex (one distance for all of a corner's edges: SMLib keeps one diff --git a/crates/kernel/src/blend_corner.rs b/crates/kernel/src/blend_corner.rs index a6fbaf575..544e2a2ef 100644 --- a/crates/kernel/src/blend_corner.rs +++ b/crates/kernel/src/blend_corner.rs @@ -305,30 +305,6 @@ mod tests { 8000.0 - full + (sum - union) * hh * hh } - /// What the strips leave of the corner block where a patch over the corner of rounds `ra`, - /// `rb`, `rc` on a, b, c lies: beyond a's end section (y < rc), b's (x > 20 − rc) and c's end - /// (z > 20 − max(ra, rb), where c's rails meet a's and b's), the box's material that no - /// strip removes, by columns along z. Outside that block such a body is the strips' (its - /// rounds are the strips' cylinders up to those ends), so its patch takes at most this - /// beyond them. - fn corner_block(ra: f64, rb: f64, rc: f64) -> f64 { - let len = |d: f64, r: f64| if d < r { r - (r * r - (r - d) * (r - d)).max(0.0).sqrt() } else { 0.0 }; - let (n, depth) = (2000, ra.max(rb)); - let h = rc / n as f64; - let mut kept = 0.0; - for i in 0..n { - let dx = (i as f64 + 0.5) * h; - for j in 0..n { - let dy = (j as f64 + 0.5) * h; - if (rc - dx).powi(2) + (rc - dy).powi(2) > rc * rc && dx < rc && dy < rc { - continue; - } - kept += depth - len(dx, ra).max(len(dy, rb)).min(depth); - } - } - kept * h * h - } - /// Largest angle (degrees) between the two faces' normals along edges between curved faces. fn kink(b: &Body) -> f64 { let rec = Faces::of(b).unwrap(); @@ -515,29 +491,41 @@ mod tests { assert!(r.validity().is_empty(), "{:?}", r.validity()); assert!((vol(&r) - sphere).abs() < 1e-11 * sphere, "{} vs {sphere}", vol(&r)); assert!(kink(&r) < 0.01); - // Different radii: a smooth patch over the corner, more than the strips take, and no more - // than they leave in the block it lies in: its rounds end at a's section y = rc, b's - // x = 20 − rc, and c's rails where they meet a's and b's (z = 20 − ra, z = 20 − rb), the - // patch's four corners. (2, 2, 3): 1.168 beyond the strips, of the 11.86 the block keeps; - // (2, 3, 4): 3.099 of 32.69. + // Different radii: SMLib's setback corner (SmBlendSetback.h). Each round runs whole up to + // its section square to its edge at its setback, the owner's rule's (at least 1.5 r, more + // where the rails beside it cross later, scaled to the least at which the corner's G1 fill + // is certified convex), and the hole between the three sections is filled by the setback + // split: one setback patch per round and the triangle between them in three + // quadrilaterals, so 6 planes, 3 rounds and 6 patches (15 faces), G1 across every seam. + // Outside the box the sections span ([20 - d_b, 20] x [0, d_a] x [20 - d_c, 20], d each + // edge's setback) the body is the three strips', so its volume is theirs within that box's. + // The rounds a and b of one radius lie mirrored about the plane x + y = 20 with c: one + // setback. (2, 2, 3): 3.6155, 3.6155, 4.6485; (2, 3, 4): 4.7745, 5.03975, 6.366 (a, b, c). for (rs, sel) in [((2.0, 2.0, 3.0), fillet(&ab, &[c], 3.0)), ((2.0, 3.0, 4.0), fillet_radii(&bx, &[(a, 2.0), (b, 3.0), (c, 4.0)]))] { let r = sel.unwrap(); - assert_eq!(r.face_count(), 10); + assert_eq!(r.face_count(), 15); assert_eq!(r.unmeshed_faces(), 0); + assert!(r.validity().is_empty(), "{:?}", r.validity()); let k = kink(&r); - assert!(k < 0.05, "kink {k}°"); + assert!(k < 0.01, "kink {k}°"); let (ra, rb, rc) = rs; - let ends = [ - Vec3::new(20.0 - ra, rc, 20.0), - Vec3::new(20.0, rc, 20.0 - ra), - Vec3::new(20.0 - rc, rb, 20.0), - Vec3::new(20.0 - rc, 0.0, 20.0 - rb), - ]; - for p in ends { - assert!(vertices(&r).iter().any(|q| q.dist(p) < 1e-9), "{rs:?}: no patch corner at {p:?}"); + let vs = vertices(&r); + // An edge's setback: where its round's section meets both faces, at two vertices. + let setback = |at: &dyn Fn(f64) -> [Vec3; 2], r: f64| -> Option { + vs.iter() + .flat_map(|p| [p.y, 20.0 - p.x, 20.0 - p.z]) + .find(|d| *d >= 1.5 * r - 1e-9 && *d < 20.0 && at(*d).iter().all(|q| vs.iter().any(|p| p.dist(*q) < 1e-9))) + }; + let da = setback(&|d| [Vec3::new(20.0 - ra, d, 20.0), Vec3::new(20.0, d, 20.0 - ra)], ra); + let db = setback(&|d| [Vec3::new(20.0 - d, 0.0, 20.0 - rb), Vec3::new(20.0 - d, rb, 20.0)], rb); + let dc = setback(&|d| [Vec3::new(20.0 - rc, 0.0, 20.0 - d), Vec3::new(20.0, rc, 20.0 - d)], rc); + eprintln!("{rs:?}: setbacks {da:?} {db:?} {dc:?}"); + let (Some(da), Some(db), Some(dc)) = (da, db, dc) else { panic!("{rs:?}: a round's setback section is missing: {da:?} {db:?} {dc:?}") }; + if ra == rb { + assert!((da - db).abs() < 1e-9, "{da} vs {db}"); } let (v, s) = (vol(&r), strips(ra, rb, rc)); - assert!(v < s + 0.05 && v > s - corner_block(ra, rb, rc), "{v} vs {s}"); + assert!((v - s).abs() < db * da * dc, "{v} vs {s}"); } } diff --git a/crates/kernel/src/blend_smlib.rs b/crates/kernel/src/blend_smlib.rs index 77b62d9cc..46615328c 100644 --- a/crates/kernel/src/blend_smlib.rs +++ b/crates/kernel/src/blend_smlib.rs @@ -444,7 +444,15 @@ mod imp { "not supported yet: the {what} meets a corner of this kind, which SMLib's blends do not handle yet (where its edges \ run on tangentially into each other, or meet in a way no blend corner builds)" )), - SmError::NoRoom => KernelError::TooLarge(format!("the {what} is larger than the faces beside its edges allow")), + // A setback too short for its corner's fill (SMLib certifies it convex only from + // its least on) names that least; any other is a blend too large for its room. + SmError::NoRoom => match solidcraft_smlib::blend_fit() { + Some(solidcraft_smlib::Fit::SetbackAtLeast(least)) => KernelError::Invalid(format!( + "the setback is too short for its corner: {}{least:.4} mm (the corner's patch is convex only from there)", + crate::SETBACK_AT_LEAST + )), + _ => KernelError::TooLarge(format!("the {what} is larger than the faces beside its edges allow")), + }, SmError::Unported(why) => KernelError::Invalid(format!("not supported yet: {why}")), e => failed(what, "operation", e), })?; diff --git a/crates/kernel/src/corner_g2_tests.rs b/crates/kernel/src/corner_g2_tests.rs index 88125bc27..325741826 100644 --- a/crates/kernel/src/corner_g2_tests.rs +++ b/crates/kernel/src/corner_g2_tests.rs @@ -344,10 +344,11 @@ fn a_mixed_convexity_corner_is_refused() { } /// Curvature-continuous rounds (`fillet_g2`, equivalent radius 5) of the three edges at the box -/// corner: SMLib's own corner patch between them is only tangent to the rounds, its curvature -/// jumping across their seams (it showed as a dome on the corner), so the corner is the G2 patch -/// instead, filled between the curvature rounds' setback sections: one closed valid solid, the -/// patch curvature-continuous to every round and face round it clear of the hole's corners. +/// corner: SMLib's own corner between them is its setback corner, whose fill for curvature +/// sections meets the rounds and faces curvature-continuously (SmBlendSetback.h: G2 for an order +/// 2 section), as the G2 patch filled between the curvature rounds' setback sections does: each +/// one closed valid solid, curvature-continuous across every seam round the corner clear of the +/// hole's corners. #[test] fn curvature_rounds_meet_at_a_g2_corner() { let (body, edges) = box_corner(); @@ -357,9 +358,9 @@ fn curvature_rounds_meet_at_a_g2_corner() { let v = crate::validity::validity(&g2); assert!(v.ok(), "{:?}", v); let (_, clear, n) = corner_seams(&g2, 0.15); - let (_, smlib_clear, _) = corner_seams(&smlib_corner, 0.15); + let (_, smlib_clear, smlib_n) = corner_seams(&smlib_corner, 0.15); assert!(n > 0 && clear <= CURVATURE_SHARE / 5.0, "{clear} over {n} stations"); - assert!(smlib_clear > 10.0 * CURVATURE_SHARE / 5.0, "SMLib's own corner patch: {smlib_clear}"); + assert!(smlib_n > 0 && smlib_clear <= CURVATURE_SHARE / 5.0, "SMLib's own corner: {smlib_clear} over {smlib_n} stations"); // Both differ only within the setback cube (side 1.5 r = 7.5) at the corner. let (a, b) = (measure(&g2).unwrap().volume, measure(&smlib_corner).unwrap().volume); assert!((a - b).abs() < 7.5f64.powi(3), "{a} vs {b}"); diff --git a/crates/kernel/src/fillet_setback_tests.rs b/crates/kernel/src/fillet_setback_tests.rs index 5c9166099..04a92776e 100644 --- a/crates/kernel/src/fillet_setback_tests.rs +++ b/crates/kernel/src/fillet_setback_tests.rs @@ -44,8 +44,10 @@ fn a_setback_off_the_rounded_corner_is_refused() { } /// A setback that does not reach past where the corner's rounds meet without one (on faces square -/// to each other, the radius) is refused before SMLib runs, naming that least setback; a setback -/// just past it builds. +/// to each other, the radius) is refused before SMLib runs, naming that least setback. Past it, a +/// setback still too short for SMLib's corner fill (certified convex only from a setback on, +/// smlib_blend_fit_size's SMLIB_FIT_SETBACK_AT_LEAST) is refused naming the smallest that builds, +/// at most twice the one asked for (the certificate scales the setbacks up to 2); that one builds. #[test] fn a_setback_not_past_the_radius_is_refused_naming_the_least() { for s in [2.0, 5.0] { @@ -54,7 +56,16 @@ fn a_setback_not_past_the_radius_is_refused_naming_the_least() { other => panic!("setback {s}: {:?}", other.map(|b| b.face_count())), } } - let out = corner_case(Some(5.5)).unwrap(); + let least = match corner_case(Some(5.5)) { + Err(KernelError::Invalid(why)) => { + let named = why.split_once(SETBACK_AT_LEAST).and_then(|(_, rest)| rest.split_once(" mm")).and_then(|(n, _)| n.parse::().ok()); + named.unwrap_or_else(|| panic!("no least setback named: {why}")) + } + other => panic!("setback 5.5: {:?}", other.map(|b| b.face_count())), + }; + eprintln!("setback 5.5 refused: the smallest that builds is {least}"); + assert!(least > 5.5 && least <= 11.0, "{least}"); + let out = corner_case(Some(least)).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); // The least the refusal names, for a form to show before it runs; none at no vertex. let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(60.0, 40.0, 20.0)).unwrap(); diff --git a/crates/kernel/src/intersection.rs b/crates/kernel/src/intersection.rs index bdaaf5e3d..93aec0bdb 100644 --- a/crates/kernel/src/intersection.rs +++ b/crates/kernel/src/intersection.rs @@ -26,18 +26,23 @@ fn failed(what: &str, e: impl std::fmt::Display) -> KernelError { KernelError::Failed(format!("SMLib intersection curve: {what}: {e}")) } -/// `body` itself, or its face `face` (in its face order) alone as a surface body. -fn part(body: &Body, face: Option) -> Result { - match face { - None => Ok(body.clone()), - Some(f) if f < body.record().faces.len() => crate::surfaces::taken(body, body.record(), &[(f, false)]), - Some(f) => Err(KernelError::Invalid(format!("the body has no face {f}"))), +/// `body` itself, or its faces `faces` (in its face order) alone as a surface body. +fn part(body: &Body, faces: Option<&[usize]>) -> Result { + let Some(faces) = faces else { return Ok(body.clone()) }; + let count = body.record().faces.len(); + if let Some(f) = faces.iter().find(|f| **f >= count) { + return Err(KernelError::Invalid(format!("the body has no face {f}"))); } + if faces.is_empty() { + return Err(KernelError::Invalid("no face given".into())); + } + let taken: Vec<(usize, bool)> = faces.iter().map(|f| (*f, false)).collect(); + crate::surfaces::taken(body, body.record(), &taken) } -/// Where `a` (or its face `a_face`) meets `b` (or its face `b_face`): every edge SMLib's imprint +/// Where `a` (or its faces `a_face`) meets `b` (or its faces `b_face`): every edge SMLib's imprint /// of the one by the other makes, its points at `chord` mm. Empty where they do not meet. -pub fn meeting_edges(a: &Body, a_face: Option, b: &Body, b_face: Option, chord: f64) -> Result> { +pub fn meeting_edges(a: &Body, a_face: Option<&[usize]>, b: &Body, b_face: Option<&[usize]>, chord: f64) -> Result> { let (a, b) = (part(a, a_face)?, part(b, b_face)?); let ta = a.smlib()?.tagged(0).map_err(|e| failed("tag", e))?; let tb = b.smlib()?.tagged(1).map_err(|e| failed("tag", e))?; diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 9bc396657..993e0af63 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -156,8 +156,8 @@ mod validity; pub mod watch; pub use blend::{ - ChamferSide, blend_edges, chamfer, chamfer_max, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, fillet_g2_with_g2_corners, - fillet_least_setback, fillet_max, fillet_max_each, fillet_removing, fillet_setback, tangent_chain, + ChamferSide, SETBACK_AT_LEAST, blend_edges, chamfer, chamfer_max, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, + fillet_g2_with_g2_corners, fillet_least_setback, fillet_max, fillet_max_each, fillet_removing, fillet_setback, tangent_chain, }; pub use blend_corner::fillet_radii; pub use blend_variable::{RadiusSpline, Taper, fillet_chord, fillet_tapered, fillet_variable, fillet_variable_points, fillet_variable_spline, taper}; @@ -202,7 +202,7 @@ pub use meshbody::{MAX_TRIANGLES, mesh_body}; pub use native::{body_from_smlib, smlib_body}; pub use native::{brep_record, decode_native_body, encode_native_body, native_preview_mesh}; pub use offset::with_same_surface; -pub use ops::{BoolOp, boolean, half_space, join_apart, place_matrix, split_by_plane, transform, transform_matrix, union_all, union_apart}; +pub use ops::{BoolOp, apart, boolean, half_space, join_apart, place_matrix, split_by_plane, transform, transform_matrix, union_all, union_apart}; pub use point_path::{ PathPiece, PointPath, SpaceBezier, along_path, curve_path, edge_path, face_section_along, project_onto_face, sketch_record_curve, sweep_point_path_with, diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 5913e7366..ad550dd97 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -56,8 +56,9 @@ pub fn union_all(bodies: &[&Body]) -> Result { } /// Whether B-rep bodies `a` and `b` are apart: their exact boxes, each grown by twice its -/// record's tolerance (as [`union_apart`] takes them), do not meet. -fn apart(a: &Body, b: &Body) -> Result { +/// record's tolerance (as [`union_apart`] takes them), do not meet. Never for a mesh body. The +/// way to skip work on bodies that cannot meet: a mesh's box is not the body's. +pub fn apart(a: &Body, b: &Body) -> Result { if a.is_mesh() || b.is_mesh() { return Ok(false); } diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 38f92633b..dde907c35 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -212,9 +212,13 @@ impl Remote { } } - /// Connect now, if the app is there (`new` does not); the error says why not. + /// See whether the app is there now (`new` does not); the error says why not. The connection + /// doesn't stay open: the app closes one that shows no token within a few seconds, and the + /// first call may be long away. That call connects again. pub fn try_connect(&mut self) -> std::io::Result<()> { - self.reconnect() + self.reconnect()?; + self.drop_conn(); + Ok(()) } /// Failing to reach the app at all is `NotConnected`, so [`Remote::explain`] can tell it from diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 4a0e6cc0a..86832a329 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1754,6 +1754,39 @@ fn a_bridged_request_carries_the_agents_folders() { echo.join().unwrap(); } +/// A server started before its first tool call keeps no connection waiting (the app closes one +/// that shows no token in time), and a call on a connection the app has closed meanwhile goes out +/// on a new one without an error. +#[test] +fn a_bridge_holds_no_idle_connection_and_survives_one_closed_before_its_first_call() { + use std::io::{BufRead, Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + let app = std::thread::spawn(move || { + let (mut probe, _) = listener.accept().unwrap(); + probe.set_read_timeout(Some(std::time::Duration::from_secs(10))).unwrap(); + assert_eq!(probe.read(&mut [0u8; 1]).unwrap(), 0, "the probe closes at once and sends nothing"); + // The connection the second bridge makes first: closed unanswered, as a timed-out one is. + drop(listener.accept().unwrap()); + for _ in 0..2 { + let (stream, _) = listener.accept().unwrap(); + let mut line = String::new(); + std::io::BufReader::new(stream.try_clone().unwrap()).read_line(&mut line).unwrap(); + let req: Value = serde_json::from_str(&line).unwrap(); + writeln!(&stream, "{}", json!({"id": req["id"], "ok": true, "result": {"method": req["method"]}})).unwrap(); + } + }); + let token = "0123456789abcdef0123456789abcdef"; + let mut early = crate::Remote::new(&addr, Some(token)); + early.try_connect().unwrap(); + let mut idle = crate::Remote::connect_with_token(&addr, Some(token)).unwrap(); + let got = crate::Backend::call(&mut early, "ui.view", json!({})).unwrap(); + assert_eq!(got["method"], "ui.view", "{got}"); + let got = crate::Backend::call(&mut idle, "ui.view", json!({})).unwrap(); + assert_eq!(got["method"], "ui.view", "{got}"); + app.join().unwrap(); +} + /// #7181, bridged: once the agent has saved a design through the app, that file's folder goes /// with every later request as `design_folders`, so the app counts it after the design moves on. /// Not before the save succeeded, not for one the app refused, not for a relative path (the app diff --git a/crates/sketch/src/link.rs b/crates/sketch/src/link.rs index f22912eb8..178d0c2f1 100644 --- a/crates/sketch/src/link.rs +++ b/crates/sketch/src/link.rs @@ -1218,11 +1218,31 @@ impl Sketch { let keep = self.links.clone(); self.remove_curves(&curves); let pts = self.link_points(id); + self.free_own_curves(&pts); self.remove_points(&pts); // Removal prunes empty links; this one stays. self.links = keep; } + /// The sketch's own curves that use one of `pts` (a circle drawn on a projected hole's + /// centre) move onto a free point of their own at the same place, so removing `pts` doesn't + /// delete them with the link (#5388). Constraints on `pts` still go with them. + fn free_own_curves(&mut self, pts: &[usize]) { + for &p in pts { + let own: Vec = self.curves.iter().enumerate().filter(|(_, c)| c.link.is_none() && c.kind.uses(p)).map(|(i, _)| i).collect(); + if own.is_empty() { + continue; + } + let Some(pos) = self.points.get(p).map(|q| q.pos) else { continue }; + let Ok(free) = self.add_point(pos, None) else { continue }; + for ci in own { + if let Some(c) = self.curves.get_mut(ci) { + c.kind.map_points(&|q| if q == p { free } else { q }); + } + } + } + } + /// Mark a link as lost (its reference was not found); its geometry stays as it was. pub fn set_link_lost(&mut self, id: &str, lost: bool) { if let Some(l) = self.links.iter_mut().find(|l| l.id == id) { diff --git a/crates/sketch/src/link_identity_tests.rs b/crates/sketch/src/link_identity_tests.rs index bfa511854..31c91d229 100644 --- a/crates/sketch/src/link_identity_tests.rs +++ b/crates/sketch/src/link_identity_tests.rs @@ -423,3 +423,38 @@ fn edge_on_face_saved_as_a_line_pair_keeps_the_line_an_offset_follows() { let end = sk.points[sk.link_points(&link)[1]].pos; assert_eq!(end, Vec2::new(17.0, 5.0), "the line moved to the new geometry"); } + +/// #5388: a circle the user drew on a projected hole's centre survives when the face changes +/// shape and its projection is rebuilt (a second hole added to the face). +#[test] +fn rebuilt_face_keeps_a_users_circle_on_its_projected_centre() { + let mut sk = Sketch::new(); + let hole = |c: Vec2| LinkGeom::Circle(c, 2.1); + let face_with = |holes: &[Vec2]| square(15.0).into_iter().chain(holes.iter().map(|c| hole(*c))).collect::>(); + let link = sk.add_link(LinkKind::Project, face(), &face_with(&[Vec2::ZERO])).unwrap(); + // The projected hole's centre point. + let centre = sk + .link_curves(&link) + .into_iter() + .find_map(|i| match sk.curves[i].kind { + CurveKind::Circle { c, .. } => Some(c), + _ => None, + }) + .unwrap(); + let mine = sk.add_curve(CurveKind::Circle { c: centre, r: 5.25 }, Some("c_mine")).unwrap(); + assert!(sk.curves[mine].link.is_none()); + // The face gains two more holes: the projection's shape changes, so it is rebuilt. + assert!(sk.update_link(&link, &face_with(&[Vec2::ZERO, Vec2::new(-10.0, 0.0), Vec2::new(10.0, 0.0)])).unwrap()); + let kept = sk.curves.iter().find(|c| c.id == "c_mine").expect("the user's circle survives the rebuild"); + assert!(kept.link.is_none()); + match kept.kind { + CurveKind::Circle { c, r } => { + assert_eq!(r, 5.25); + let p = &sk.points[c]; + assert!(p.link.is_none(), "it sits on a point of its own, not a projected one"); + assert!(p.pos.len() < 1e-9, "still at the hole's centre: {:?}", p.pos); + } + ref k => panic!("not a circle: {k:?}"), + } + assert_eq!(sk.link_curves(&link).len(), 4 + 3, "the projection is the new outline and holes"); +} diff --git a/crates/smlib/SMLIB_PREBUILT b/crates/smlib/SMLIB_PREBUILT index 1811dc299..e32b5afb3 100644 --- a/crates/smlib/SMLIB_PREBUILT +++ b/crates/smlib/SMLIB_PREBUILT @@ -1,10 +1,10 @@ # Rust target, SHA-256 of smlib-.tar.gz in the release prebuilt- of # tangency-labs/smlib. Written by scripts/fetch-smlib.sh --pin; never edited by hand. -aarch64-apple-darwin 48461900e6d041389bb3736f2772f7bb21f2d202a1e1f4d27d6c6915c298bb8a -aarch64-pc-windows-msvc 2ba752b4bf8a3f18b47cbc6773763d7d9a3a0393be27c3d4e98a6d5ca9cf0b4d -aarch64-unknown-linux-gnu 8c66c2a113a64e574d945772965f7cc0de46ff8bbb3ce450e95bf57abe6058c0 -i686-pc-windows-msvc dd771c1dede08a3bdfe012ef509d99a16087872790792b44bb8b26cc1015a671 -wasm32-unknown-unknown 7bb1507b9d474d9ee19f2a61d22c9167fdf360672897d9d8dfeb4647a1993fd5 -x86_64-apple-darwin 7ad19f0b30c4c0787f0d3459e2263906fa290db2247afab9efd068feb185fa26 -x86_64-pc-windows-msvc 0dcc44829efa70e19b739b06a19d3cbbc2101c0cc9fb0cc44f28fb97066ce20d -x86_64-unknown-linux-gnu 8d009ebf182f04c95c6a64f9b0b13b355796b62fef60d81665341915136c5851 +aarch64-apple-darwin b1d0e36c05090ab89e96601079b156a656024d0b209a0ac1973443494ed814ba +aarch64-pc-windows-msvc 5c02e2a884acd2de419867392bac497eae7bcd258e90a7de50d8a6c8eaaf7a89 +aarch64-unknown-linux-gnu 52a9d8c58747bc86495be8e81bb7b352faf85bc35b87fd4340e8eab7f4a9d988 +i686-pc-windows-msvc a071be49f30fea979d5972c35542bbcbef04794cbb9891c1a1a78e12720836bd +wasm32-unknown-unknown 6bd987227bc707cdc4f287c1a70fc01e53437a9657e05901fa3a7904ec920351 +x86_64-apple-darwin 8d3fd575337059e345a6b5e7f7e9be94fae7f5a9edc66989f6e1e033eec0ab2e +x86_64-pc-windows-msvc 158fb9fa89cf44bffa44452b2b4829e9a54586d86c0b8c7e5c2d640ac8b45515 +x86_64-unknown-linux-gnu 2a9560c23ad693e89a48d1491d2a75ecfe8e0575d07cfff29ec61cb712429299 diff --git a/crates/smlib/SMLIB_REV b/crates/smlib/SMLIB_REV index 33fcdb90f..57e5be618 100644 --- a/crates/smlib/SMLIB_REV +++ b/crates/smlib/SMLIB_REV @@ -1 +1 @@ -5e8c9c19bb2cff6b5ae321ecda577496955fe037 +f916a8d628a063333a39b2e303849e584dcc9f26 diff --git a/crates/smlib/src/ffi/ops.rs b/crates/smlib/src/ffi/ops.rs index 9d2ba3bfd..6cdc07c44 100644 --- a/crates/smlib/src/ffi/ops.rs +++ b/crates/smlib/src/ffi/ops.rs @@ -1,5 +1,5 @@ //! The operations block of `capi/include/smlib.h` (`smlib_boolean`, `smlib_boolean_union_all`, `smlib_boolean2d`, `smlib_fillet`, -//! `smlib_chamfer`, `smlib_blend`, `smlib_blend_dropping`, `smlib_blend_setback`, `smlib_blend_setback_open`, `smlib_fillet_variable`, `smlib_chamfer_sides`, `smlib_shell`, `smlib_offset_faces`, +//! `smlib_chamfer`, `smlib_blend`, `smlib_blend_dropping`, `smlib_blend_setback`, `smlib_blend_setback_open`, `smlib_blend_fit_size`, `smlib_fillet_variable`, `smlib_chamfer_sides`, `smlib_shell`, `smlib_offset_faces`, //! `smlib_thicken`, `smlib_draft`, `smlib_merge_faces`, `smlib_brep_solid_count`, `smlib_imprint`; the fork's `capi/src/smlib_ops.cpp`), declared by //! hand. Part of the FFI boundary, like its parent: called only through //! [`crate::ops`]. @@ -31,6 +31,11 @@ pub const BLEND_CURVATURE: i32 = 1; pub const BLEND_CHORD: i32 = 2; pub const BLEND_CHAMFER: i32 = 3; +pub const FIT_SIZE: i32 = 0; +pub const FIT_SETBACK: i32 = 1; +pub const FIT_SCALE: i32 = 2; +pub const FIT_SETBACK_AT_LEAST: i32 = 3; + /// Which selection operation: the C functions share one signature. #[derive(Clone, Copy)] pub enum Pick { @@ -95,6 +100,7 @@ unsafe extern "C" { out: *mut *mut RawBrep, out_failed_point: *mut i64, ) -> i32; + fn smlib_blend_fit_size(out_size: *mut f64, out_what: *mut i32) -> i32; fn smlib_blend_dropping( brep: *const RawBrep, kind: i32, @@ -251,6 +257,19 @@ pub fn pick_op(kind: Pick, b: &Handle, points: &[[f64; 3]], tolerance: f64, size }) } +/// `smlib_blend_fit_size`: the size that builds, and what it sizes (`FIT_*`), for the last blend +/// call SMLib refused as too large or a setback as too short; `None` where it names none. +#[cfg(feature = "native")] +pub fn blend_fit_size() -> Option<(f64, i32)> { + let (mut size, mut what) = (0.0f64, -1i32); + (unsafe { smlib_blend_fit_size(&mut size, &mut what) } == OK).then_some((size, what)) +} + +#[cfg(not(feature = "native"))] +pub fn blend_fit_size() -> Option<(f64, i32)> { + None +} + #[cfg(feature = "native")] pub fn thicken(b: &Handle, thickness: f64, symmetric: bool) -> Result { new_brep(|out| unsafe { smlib_thicken(b.raw(), thickness, i32::from(symmetric), out) }) diff --git a/crates/smlib/src/lib.rs b/crates/smlib/src/lib.rs index 8f2fb1160..82d2a872f 100644 --- a/crates/smlib/src/lib.rs +++ b/crates/smlib/src/lib.rs @@ -34,7 +34,7 @@ pub mod trim; pub use check::{CheckLevel, CheckReport}; pub use measure::{MEASURE_ACCURACY, MassProperties, PointClass}; -pub use ops::{Blend, BooleanOp, ChamferSecond, Hole, HoleEdge, MAX_POINTS, MAX_UNION_BREPS}; +pub use ops::{Blend, BooleanOp, ChamferSecond, Fit, Hole, HoleEdge, MAX_POINTS, MAX_UNION_BREPS, blend_fit}; /// Why an SMLib call failed. #[derive(Clone, Debug, PartialEq)] diff --git a/crates/smlib/src/ops.rs b/crates/smlib/src/ops.rs index 7f70ff03d..f782ee659 100644 --- a/crates/smlib/src/ops.rs +++ b/crates/smlib/src/ops.rs @@ -8,6 +8,40 @@ use crate::{Brep, Error, Result, core, error, ffi, init, route}; +/// What size builds a blend SMLib refused ([`blend_fit`]): from the refusal's own cause, never by +/// building again. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Fit { + /// The largest size (a round's radius, a chamfer's distance, a chord's width) that builds. + Size(f64), + /// The largest setback of a set-back corner that fits (the one asked for is too long). + Setback(f64), + /// The factor (< 1) a two-distance chamfer's distances are both scaled by to build. + Scale(f64), + /// The smallest setback that builds the corner (the one asked for is too short: its fill is + /// certified convex only from there). + SetbackAtLeast(f64), +} + +/// The size that builds the last blend this process's SMLib refused as too large +/// ([`Error::NoRoom`]) or whose setback it refused as too short; `None` where it names no single +/// size. Read it right after the refused call: SMLib keeps only the last one. +pub fn blend_fit() -> Option { + // solidcore names no size that builds yet: its refusals keep their own words, and the C++ + // kernel's last refusal is never read for one of solidcore's. + if route::backend() == route::Backend::Solidcore { + return None; + } + let (size, what) = ffi::ops::blend_fit_size()?; + match what { + ffi::ops::FIT_SIZE => Some(Fit::Size(size)), + ffi::ops::FIT_SETBACK => Some(Fit::Setback(size)), + ffi::ops::FIT_SCALE => Some(Fit::Scale(size)), + ffi::ops::FIT_SETBACK_AT_LEAST => Some(Fit::SetbackAtLeast(size)), + _ => None, + } +} + /// How [`Brep::boolean`] combines two bodies. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BooleanOp { diff --git a/crates/ui-egui/examples/acp_test_agent.rs b/crates/ui-egui/examples/acp_test_agent.rs index 95c625e7f..58b48bd0d 100644 --- a/crates/ui-egui/examples/acp_test_agent.rs +++ b/crates/ui-egui/examples/acp_test_agent.rs @@ -177,7 +177,7 @@ fn main() { send(&json!({"jsonrpc": "2.0", "id": 900, "method": "session/request_permission", "params": { "sessionId": session, // Named as the Claude Code adapter names an MCP tool. - "toolCall": {"toolCallId": "t1", "title": "mcp__solidcraft__batch"}, + "toolCall": {"toolCallId": "t1", "title": "mcp__solidcraft-app__batch", "kind": "other"}, "options": [{"optionId": "allow", "name": "Allow", "kind": "allow_once"}, {"optionId": "reject", "name": "Reject", "kind": "reject_once"}], }})); // Wait for the answer (other lines are not expected meanwhile). diff --git a/crates/ui-egui/src/agent_chat/acp.rs b/crates/ui-egui/src/agent_chat/acp.rs index 2f5e4d49f..efffaf331 100644 --- a/crates/ui-egui/src/agent_chat/acp.rs +++ b/crates/ui-egui/src/agent_chat/acp.rs @@ -160,6 +160,19 @@ pub fn initialize_params(version: &str) -> Value { /// keeps its own entry on a clash) can't shadow the bridge with a headless session. pub const BRIDGE_NAME: &str = "solidcraft-app"; +/// Whether a permission question is about a tool of the chat's own MCP server, whose calls +/// SolidCraft's gate checks. The agent writes both values and ACP has nothing better to go on, so +/// the test is strict: the whole title is the tool's name as the Claude adapter forms it +/// (`mcp__solidcraft-app__batch`), one word with no room for a command line, a path or other free +/// text, and the kind is `other` (the kind an MCP tool has) or not given. Any other title goes +/// through the user's mode and remembered answers: agents that word their MCP tools differently, +/// and a user's own MCP server, which the gate doesn't see. +pub fn is_bridge_tool(title: &str, kind: Option<&str>) -> bool { + let tool = title.strip_prefix("mcp__").and_then(|t| t.strip_prefix(BRIDGE_NAME)).and_then(|t| t.strip_prefix("__")); + let named = tool.is_some_and(|t| !t.is_empty() && t.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')); + named && matches!(kind, None | Some("other")) +} + /// The MCP server the agent starts to reach the design: `solidcraft-cli mcp --connect` bridged to /// this app's control port. The server finds the port's token in the token file the app wrote /// (docs/control-protocol.md), so the token never travels through the agent, and it keeps its @@ -473,6 +486,8 @@ pub enum Incoming { Permission { rpc: Value, title: String, + /// The tool call's kind (`execute`, `edit`, `other`, …), as the agent gives it. + kind: Option, options: Vec, }, /// The agent says whether it is logged in (an extension both adapters send). @@ -546,6 +561,7 @@ pub fn parse(line: &str) -> Option { (Some("session/request_permission"), Some(id)) => { let call = params.get("toolCall"); let title = call.and_then(|c| c.get("title")).and_then(Value::as_str).unwrap_or("").to_string(); + let kind = call.and_then(|c| c.get("kind")).and_then(Value::as_str).map(str::to_string); let options = params .get("options") .and_then(Value::as_array) @@ -562,7 +578,7 @@ pub fn parse(line: &str) -> Option { .collect() }) .unwrap_or_default(); - Some(Incoming::Permission { rpc: id.clone(), title, options }) + Some(Incoming::Permission { rpc: id.clone(), title, kind, options }) } (Some(m), Some(id)) => Some(Incoming::Unsupported { rpc: id.clone(), method: m.to_string() }), (Some("session/update"), None) => Some(update(params.get("update")?, params.get("sessionId").and_then(Value::as_str).unwrap_or(""))), @@ -700,6 +716,48 @@ mod tests { // The panel still recognises the bridge's tools as SolidCraft's (agents name them after // their server, e.g. `mcp__solidcraft-app__batch`). assert!(BRIDGE_NAME.contains("solidcraft")); + assert!(is_bridge_tool(&format!("mcp__{BRIDGE_NAME}__batch"), Some("other"))); + } + + /// Only the whole name of a tool of the chat's own server counts, whatever else a title holds. + #[test] + fn only_the_bridges_exact_tool_names_are_its_tools() { + for tool in ["batch", "inspect_design", "set_parameter"] { + assert!(is_bridge_tool(&format!("mcp__solidcraft-app__{tool}"), None), "{tool}"); + assert!(is_bridge_tool(&format!("mcp__solidcraft-app__{tool}"), Some("other")), "{tool}"); + } + for title in [ + "", + "solidcraft", + "SolidCraft", + "run solidcraft-cli; ls", + "solidcraft-cli --version", + "Edit ~/.local/share/solidcraft/agent-chat/work/notes.txt", + // A user's own MCP server (docs/mcp.md), which SolidCraft's gate doesn't see. + "mcp__solidcraft__batch", + "mcp__solidcraft-live__batch", + "mcp__other__solidcraft-app", + "mcp__solidcraft-app__", + "mcp__solidcraft-app", + "solidcraft-app__batch", + "solidcraft-app: batch", + "Tool: solidcraft-app/batch", + "mcp.solidcraft-app.batch", + " mcp__solidcraft-app__batch", + "mcp__solidcraft-app__batch ", + "mcp__solidcraft-app__batch; ls", + "mcp__solidcraft-app__batch && ls", + "mcp__solidcraft-app__batch\nls", + "mcp__solidcraft-app__../../tool", + "mcp__SOLIDCRAFT-APP__batch", + "MCP__solidcraft-app__batch", + "mcp__solidcraft-app__Batch", + ] { + assert!(!is_bridge_tool(title, None), "{title:?}"); + } + for kind in ["execute", "edit", "delete", "move", "read", "search", "fetch", "think", ""] { + assert!(!is_bridge_tool("mcp__solidcraft-app__batch", Some(kind)), "{kind:?}"); + } } #[test] @@ -813,8 +871,9 @@ mod tests { }) ); let perm = r#"{"jsonrpc":"2.0","id":7,"method":"session/request_permission","params":{"sessionId":"s","toolCall":{"toolCallId":"t1","title":"batch"},"options":[{"optionId":"allow","name":"Allow","kind":"allow_once"},{"optionId":"reject","name":"Reject","kind":"reject_once"}]}}"#; - let Some(Incoming::Permission { rpc, title, options }) = parse(perm) else { panic!() }; + let Some(Incoming::Permission { rpc, title, kind, options }) = parse(perm) else { panic!() }; assert_eq!((title.as_str(), options.len(), options[1].kind.as_str()), ("batch", 2, "reject_once")); + assert_eq!(kind, None); assert_eq!(permission_reply(rpc.clone(), Some("allow"))["result"]["outcome"], json!({"outcome": "selected", "optionId": "allow"})); assert_eq!(permission_reply(rpc, None)["result"]["outcome"]["outcome"], "cancelled"); let fs = r#"{"jsonrpc":"2.0","id":8,"method":"fs/read_text_file","params":{}}"#; diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rs index 6b453964c..7255dab25 100644 --- a/crates/ui-egui/src/agent_chat/acp_client.rs +++ b/crates/ui-egui/src/agent_chat/acp_client.rs @@ -3,6 +3,7 @@ //! sign-in). The panel sees only [`Event`]s. use std::collections::HashMap; +use std::time::{Duration, Instant}; use serde_json::{Value, json}; @@ -21,6 +22,9 @@ enum Pending { SetConfig, } +/// Give a cancelled prompt time to finish before disconnecting an unresponsive agent. +const CANCEL_GRACE: Duration = Duration::from_secs(5); + /// Variables the agent doesn't inherit: a control token set for the app's own `--control` port /// would otherwise reach the agent and outrank the chat endpoint's own token file. const ENV_REMOVE: &[&str] = &["SOLIDCRAFT_CONTROL_TOKEN"]; @@ -41,6 +45,7 @@ pub struct AcpBackend { /// Open permission questions: our key → the agent's request id. permissions: HashMap, next_key: u64, + cancelling: Option<(u64, Instant)>, exited: bool, config_pending: Option<(u64, String)>, modern_config: bool, @@ -68,6 +73,7 @@ impl AcpBackend { auth: Vec::new(), permissions: HashMap::new(), next_key: 0, + cancelling: None, exited: false, config_pending: None, modern_config: false, @@ -93,6 +99,9 @@ impl AcpBackend { match msg { Incoming::Reply { id, result } => { let Some(what) = self.pending.remove(&id) else { return }; + if self.cancelling.is_some_and(|(request, _)| request == id) { + self.cancelling = None; + } match (what, result) { (Pending::Initialize, Ok(v)) => { self.agent = acp::agent_info(&v); @@ -104,6 +113,12 @@ impl AcpBackend { } (Pending::SessionNew, Ok(v)) => match v.get("sessionId").and_then(Value::as_str) { Some(s) => { + // New chat has opened successfully: retire the old turn before Ready. + // Its late reply and cancellation deadline must not end the new turn. + if let Some((request, _)) = self.cancelling.take() { + self.pending.remove(&request); + out.push(Event::TurnEnded { reason: "cancelled".into() }); + } self.session = Some(s.to_string()); match acp::config_options(&v) { acp::ConfigParse::Snapshot(options) => { @@ -180,10 +195,10 @@ impl AcpBackend { Incoming::Text { thought, text } => out.push(Event::Text { thought, text }), Incoming::Tool { id, title, kind, status, input, output } => out.push(Event::Tool { id, title, kind, status, input, output }), Incoming::Plan(p) => out.push(Event::Plan(p)), - Incoming::Permission { rpc, title, options } => { + Incoming::Permission { rpc, title, kind, options } => { self.next_key += 1; self.permissions.insert(self.next_key, rpc); - out.push(Event::Permission { key: self.next_key, title, options }); + out.push(Event::Permission { key: self.next_key, title, kind, options }); } Incoming::AuthStatus(s) => out.push(Event::AuthStatus(s)), Incoming::ModeChanged(m) if !self.modern_config => out.push(Event::Modes { current: m, available: Vec::new() }), @@ -198,10 +213,17 @@ impl AcpBackend { Incoming::Ignored => {} } } -} -impl ChatBackend for AcpBackend { - fn poll(&mut self) -> Vec { + fn finish_exit(&mut self, tail: Vec) -> Event { + self.exited = true; + self.session = None; + self.pending.clear(); + self.cancelling = None; + self.config_pending = None; + Event::Exited { tail } + } + + fn poll_at(&mut self, now: Instant) -> Vec { let mut out = Vec::new(); if self.exited { return out; @@ -214,18 +236,25 @@ impl ChatBackend for AcpBackend { } } Ok(FromAgent::Exited(tail)) => { - self.exited = true; - self.session = None; - self.pending.clear(); - self.config_pending = None; - out.push(Event::Exited { tail }); + out.push(self.finish_exit(tail)); break; } Err(_) => break, } } + // Drain replies first: an acknowledgement already waiting must keep the connection. + if self.cancelling.is_some_and(|(_, started)| now.saturating_duration_since(started) >= CANCEL_GRACE) { + self.proc.shutdown(false); + out.push(self.finish_exit(vec![crate::i18n::tr("ui.agent_chat_cancel_timeout").to_string()])); + } out } +} + +impl ChatBackend for AcpBackend { + fn poll(&mut self) -> Vec { + self.poll_at(Instant::now()) + } fn prompt(&mut self, parts: &[PromptPart]) { if let Some(s) = self.session.clone() { @@ -240,6 +269,11 @@ impl ChatBackend for AcpBackend { } if let Some(s) = &self.session { self.proc.send(&acp::notification("session/cancel", json!({"sessionId": s}))); + // Repeated Stop presses must not postpone the fallback. An idle session needs none. + if self.cancelling.is_none() { + self.cancelling = + self.pending.iter().find_map(|(&id, request)| (*request == Pending::Prompt).then_some(id)).map(|id| (id, Instant::now())); + } } } @@ -343,6 +377,75 @@ mod tests { use super::*; use crate::agent_chat::backend::StartContext; + fn ready_backend() -> Result { + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut backend = AcpBackend::start(&["sh".into(), "-c".into(), "cat >/dev/null".into()], ctx)?; + let mut events = Vec::new(); + backend.handle(Incoming::Reply { id: 1, result: Ok(json!({"agentInfo":{"name":"fake"}})) }, &mut events); + backend.handle(Incoming::Reply { id: 2, result: Ok(json!({"sessionId":"s1"})) }, &mut events); + Ok(backend) + } + + #[test] + fn an_unresponsive_cancel_disconnects_the_agent() { + let mut backend = ready_backend().unwrap(); + backend.prompt(&[PromptPart::Text("stalled search".into())]); + backend.cancel(); + let started = backend.cancelling.unwrap().1; + assert!(backend.poll_at(started + CANCEL_GRACE - Duration::from_millis(1)).is_empty()); + backend.cancel(); + let events = backend.poll_at(started + CANCEL_GRACE); + assert!(matches!(events.as_slice(), [Event::Exited { .. }]), "Stop must not wait indefinitely: {events:?}"); + assert!(backend.pid().is_none()); + assert!(backend.session.is_none() && backend.pending.is_empty()); + assert!(backend.poll().is_empty(), "the exit is reported only once"); + } + + #[test] + fn a_cancelled_prompt_reply_keeps_the_connection() { + for reply in [Ok(json!({"stopReason":"cancelled"})), Err((-32603, "operation aborted".into()))] { + let mut backend = ready_backend().unwrap(); + backend.prompt(&[PromptPart::Text("search".into())]); + let request = backend.next_id; + backend.cancel(); + let mut events = Vec::new(); + backend.handle(Incoming::Reply { id: request, result: reply }, &mut events); + assert!(events.iter().any(|e| matches!(e, Event::TurnEnded { .. }))); + assert!(backend.poll_at(Instant::now() + CANCEL_GRACE).is_empty()); + assert!(backend.pid().is_some() && !backend.exited); + backend.shutdown(true); + } + } + + #[test] + fn cancelling_an_idle_session_does_not_disconnect_it() { + let mut backend = ready_backend().unwrap(); + backend.cancel(); + assert!(backend.poll_at(Instant::now() + CANCEL_GRACE).is_empty()); + assert!(backend.pid().is_some() && !backend.exited); + backend.shutdown(true); + } + + #[test] + fn a_new_session_retires_the_old_cancelled_prompt() { + let mut backend = ready_backend().unwrap(); + backend.prompt(&[PromptPart::Text("old search".into())]); + let old_prompt = backend.next_id; + backend.cancel(); + ChatBackend::new_session(&mut backend); + let mut events = Vec::new(); + backend.handle(Incoming::Reply { id: backend.next_id, result: Ok(json!({"sessionId":"s2"})) }, &mut events); + assert!(matches!(events.first(), Some(Event::TurnEnded { reason }) if reason == "cancelled")); + assert!(matches!(events.last(), Some(Event::Ready { .. }))); + backend.prompt(&[PromptPart::Text("new search".into())]); + assert!(backend.poll_at(Instant::now() + CANCEL_GRACE).is_empty(), "a new session has no stale cancellation deadline"); + backend.cancel(); + events.clear(); + backend.handle(Incoming::Reply { id: old_prompt, result: Ok(json!({"stopReason":"cancelled"})) }, &mut events); + assert!(events.is_empty(), "an old reply must not end the new turn or clear its cancellation deadline"); + assert!(matches!(backend.poll_at(Instant::now() + CANCEL_GRACE).as_slice(), [Event::Exited { .. }])); + } + fn snapshot(session: &str, value: &str) -> Value { json!({"sessionId":session,"configOptions":[{"id":"provider.model","category":"model","name":"Model","type":"select","currentValue":value,"options":[{"value":"fast","name":"Fast"},{"value":"smart","name":"Smart"}]}]}) } diff --git a/crates/ui-egui/src/agent_chat/backend.rs b/crates/ui-egui/src/agent_chat/backend.rs index ccd404c09..51d88f0e4 100644 --- a/crates/ui-egui/src/agent_chat/backend.rs +++ b/crates/ui-egui/src/agent_chat/backend.rs @@ -78,6 +78,8 @@ pub enum Event { Permission { key: u64, title: String, + /// The tool call's kind, as the agent gives it. + kind: Option, options: Vec, }, /// It needs the user to sign in; `methods` are its own ways to do so. diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index 952fd63cc..24966a753 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -49,7 +49,7 @@ use crate::i18n::{format as trf, tr}; use crate::{ControlRequest, SolveApp}; use backend::{ChatBackend, Event, PermissionOption, PromptPart, ToolStatus}; -pub(crate) use panel::{left_inset, tool_space}; +pub(crate) use panel::{left_inset, owns_keyboard_input, tool_space}; pub use panel::{show, tip as panel_tip, toggle, toggle_shortcut}; /// Most entries kept in the conversation; older ones are dropped. @@ -375,6 +375,8 @@ pub struct AgentChat { pub confirm_new: bool, /// Where the panel was drawn last (for its shortcuts). pub panel_rect: Option, + /// A pointer press in the transcript owns keys just like a focused text editor. + keyboard_owned: bool, /// Unreserved sheet space, shared by the actual dock and its drag preview. pub(crate) dock_space: Option, /// The last message sent, kept to send again after a sign-in (its files too). @@ -477,6 +479,7 @@ impl AgentChat { } // Hit regions must be measured again for the incoming conversation. self.panel_rect = None; + self.keyboard_owned = false; self.dock_space = None; self.drop_rect = None; } @@ -729,7 +732,7 @@ impl AgentChat { self.push(Item::Plan(entries)); } } - Event::Permission { key, title, options } => return Some(Outcome::Permission { key, title, options }), + Event::Permission { key, title, kind, options } => return Some(Outcome::Permission { key, title, kind, options }), Event::Modes { current, available } => { if self.config_options.is_none() && !available.is_empty() { self.modes = available; @@ -834,6 +837,13 @@ impl AgentChat { self.clear_config(); self.state = Some(if matches!(self.state(), State::Starting | State::Failed) { State::Failed } else { State::Exited }); self.steering = false; + for item in &mut self.items { + if let Item::Tool { status, .. } = item + && !matches!(status, Some(ToolStatus::Completed | ToolStatus::Failed)) + { + *status = Some(ToolStatus::Failed); + } + } let last: Vec = tail.into_iter().rev().take(6).collect::>().into_iter().rev().collect(); let detail = if last.is_empty() { String::new() } else { format!("\n{}", last.join("\n")) }; self.notice(format!("{}{detail}", tr("ui.agent_chat_exited")), true); @@ -850,7 +860,7 @@ enum Outcome { /// A message was answered (or the agent stopped): the turn's bookkeeping ends. TurnEnd, /// The agent asks before running something of its own: answered by the mode, or asked. - Permission { key: u64, title: String, options: Vec }, + Permission { key: u64, title: String, kind: Option, options: Vec }, } /// The AI features are on (the master switch in Settings → AI) and this is the desktop app. @@ -923,12 +933,6 @@ pub(crate) fn assistant_tip(app: &SolveApp, mark: AssistantMark) -> String { format!("{name} — {state}") } -/// Whether a permission question is about one of SolidCraft's own tools (which SolidCraft's own -/// gate checks): the agents name MCP tools after their server. -fn solidcraft_tool(title: &str) -> bool { - title.to_ascii_lowercase().contains("solidcraft") -} - /// `solidcraft-cli` next to this program, else on the search path. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn find_cli() -> Option { @@ -1658,14 +1662,15 @@ pub fn answer_permission(app: &mut SolveApp, index: usize, option: Option<&str>) app.agent_chat.answer(index, option); } -/// The agent asks before running something of its own. SolidCraft's own tools are checked by -/// SolidCraft's gate, so they're allowed here (no double question); otherwise the mode or an -/// earlier "always allow" may answer, and the chat says so; otherwise the user is asked. -fn on_permission(app: &mut SolveApp, key: u64, title: String, options: Vec) { +/// The agent asks before running something of its own. The chat's own MCP tools are checked by +/// SolidCraft's gate, so they're allowed here (no double question, see [`acp::is_bridge_tool`]); +/// otherwise the mode or an earlier "always allow" may answer, and the chat says so; otherwise the +/// user is asked. +fn on_permission(app: &mut SolveApp, key: u64, title: String, kind: Option<&str>, options: Vec) { let agent = app.agent_chat.running_id.clone(); let mode = agents::mode_for(&app.preferences, &agent); let remembered = agents::always_allowed(&app.preferences, &agent, &title); - let why = if solidcraft_tool(&title) { + let why = if acp::is_bridge_tool(&title, kind) { Some("ui.ai_auto_ours") } else if remembered { Some("ui.ai_auto_remembered") @@ -1949,7 +1954,7 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { b.answer_permission(key, None); } } - Some(Outcome::Permission { key, title, options }) => on_permission(app, key, title, options), + Some(Outcome::Permission { key, title, kind, options }) => on_permission(app, key, title, kind.as_deref(), options), None => {} } if let Some(model) = confirmed_model { diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 201b2f8b8..b7388ca0c 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -83,6 +83,26 @@ pub fn tip(app: &SolveApp) -> String { } } +/// Selectable transcript labels do not take egui keyboard focus. Keep their keys out of +/// CAD until a pointer press outside the chat, not merely a move of the pointer. Use the +/// panel in this window, never label selections belonging to another native viewport. +/// Called before layout so even a click and a shortcut in the same frame are routed here. +pub(crate) fn owns_keyboard_input(app: &mut SolveApp, ctx: &egui::Context) -> bool { + let rect = app.agent_chat.panel_rect.filter(|_| shown(app) && app.agent_chat.open && !app.preferences.agent_chat_minimized); + let Some(rect) = rect else { + app.agent_chat.keyboard_owned = false; + return false; + }; + ctx.input(|input| { + for event in &input.events { + if let egui::Event::PointerButton { pos, pressed: true, .. } = event { + app.agent_chat.keyboard_owned = rect.contains(*pos); + } + } + }); + app.agent_chat.keyboard_owned +} + /// The panel, when the chat is turned on and open. Call before the central viewport is laid out. pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index be1652902..0d151563f 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -1,6 +1,126 @@ use super::*; use std::sync::mpsc::channel; +fn transcript_clipboard_harness(layout: crate::shell::LayoutMode) -> crate::scenario::Harness { + let mut h = narrow_chat(); + h.app.ui.layout = layout; + h.app.preferences.agent_chat_width = 500.0; + h.app.agent_chat.items.push(Item::Agent { thought: false, text: "Transcript clipboard sentinel".into() }); + h.app.run("solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Cube"})).unwrap(); + h.app.run("select.set", json!({"items": [{"type": "body", "name": "Cube"}]})).unwrap(); + h.frames(4); + h +} + +fn transcript_text_position(h: &crate::scenario::Harness) -> egui::Pos2 { + let mut at = None; + for clipped in &h.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if let egui::Shape::Text(text) = shape + && text.galley.text() == "Transcript clipboard sentinel" + { + at = Some(text.pos + egui::vec2(15.0, 7.0)); + } + }); + } + at.expect("the assistant message is visible") +} + +fn transcript_click(h: &mut crate::scenario::Harness, pos: egui::Pos2) { + h.frame_with(vec![ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, + ]); + h.frame_with(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }]); +} + +#[test] +fn transcript_copy_and_cut_do_not_touch_the_cad_clipboard() { + for layout in [crate::shell::LayoutMode::Docked, crate::shell::LayoutMode::Floating] { + let mut h = transcript_clipboard_harness(layout); + let at = transcript_text_position(&h); + transcript_click(&mut h, at); + transcript_click(&mut h, at); + assert!(h.ctx.plugin::().lock().has_selection(), "select real label text"); + assert!(!h.ctx.egui_wants_keyboard_input(), "a selectable label is not a text editor"); + // Moving the mouse away does not transfer the keyboard back to the model. + h.frame_with(vec![egui::Event::PointerMoved(egui::pos2(500.0, 500.0))]); + let undo = h.app.session.undo.len(); + h.frame_with(vec![egui::Event::Copy]); + assert!(h.output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(text) if text == "Transcript")), "copy selected text"); + assert!(h.app.copied_bodies.is_empty(), "{layout:?}: copying text must not copy a CAD body"); + h.frame_with(vec![egui::Event::Cut]); + assert!(h.app.cut.is_empty(), "{layout:?}: cutting read-only text must not cut a CAD body"); + assert_eq!(h.app.session.undo.len(), undo); + } +} + +#[test] +fn transcript_paste_does_not_insert_a_previously_copied_body() { + for layout in [crate::shell::LayoutMode::Docked, crate::shell::LayoutMode::Floating] { + let mut h = transcript_clipboard_harness(layout); + h.frame_with(vec![egui::Event::Copy]); + assert!(!h.app.copied_bodies.is_empty(), "prime the real CAD clipboard"); + let at = transcript_text_position(&h); + transcript_click(&mut h, at); + transcript_click(&mut h, at); + let undo = h.app.session.undo.len(); + h.frame_with(vec![egui::Event::Paste("text from another app".into())]); + assert_eq!(h.app.session.model.state().bodies.len(), 1, "{layout:?}: text paste must not paste CAD geometry"); + assert_eq!(h.app.session.undo.len(), undo); + // A deliberate click outside the panel returns ownership to CAD. + transcript_click(&mut h, egui::pos2(700.0, 500.0)); + h.frame_with(vec![egui::Event::Paste("SolidCraft bodies".into())]); + assert_eq!(h.app.session.model.state().bodies.len(), 2, "{layout:?}: CAD paste still works after returning to the model"); + } +} + +#[test] +fn transcript_key_events_do_not_run_cad_shortcuts() { + for layout in [crate::shell::LayoutMode::Docked, crate::shell::LayoutMode::Floating] { + let mut h = transcript_clipboard_harness(layout); + let at = transcript_text_position(&h); + transcript_click(&mut h, at); + transcript_click(&mut h, at); + let key = |key| egui::Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::CTRL | egui::Modifiers::COMMAND, + }; + h.frame_with(vec![key(egui::Key::C)]); + assert!(h.app.copied_bodies.is_empty(), "{layout:?}: key-event copy also belongs to the chat"); + h.frame_with(vec![key(egui::Key::X)]); + assert!(h.app.cut.is_empty(), "{layout:?}: key-event cut also belongs to the chat"); + assert!(crate::edit_clipboard::copy(&mut h.app)); + h.frame_with(vec![key(egui::Key::V)]); + assert_eq!(h.app.session.model.state().bodies.len(), 1, "{layout:?}: key-event paste stays out of CAD"); + // A quick tap can have no modifiers held by the end of the frame. It must not + // fall through to the plain A (Appearance) shortcut while selecting chat text. + h.frame_with(vec![key(egui::Key::A)]); + assert!(h.app.dialog.is_none(), "{layout:?}: selecting text must not open Appearance"); + } +} + +#[test] +fn transcript_shortcut_ownership_ends_when_the_panel_is_hidden() { + for hidden in ["closed", "minimized", "disabled"] { + let mut h = transcript_clipboard_harness(crate::shell::LayoutMode::Floating); + h.frame_with(vec![egui::Event::Copy]); + let at = transcript_text_position(&h); + transcript_click(&mut h, at); + transcript_click(&mut h, at); + match hidden { + "closed" => h.app.agent_chat.open = false, + "minimized" => h.app.preferences.agent_chat_minimized = true, + _ => h.app.preferences.ai_features = false, + } + h.frame_with(vec![egui::Event::Paste("SolidCraft bodies".into())]); + assert_eq!(h.app.session.model.state().bodies.len(), 2, "{hidden}: the invisible panel must not retain CAD keys"); + } +} + fn chat() -> AgentChat { let mut c = AgentChat::default(); c.state = Some(State::Ready); @@ -532,17 +652,48 @@ fn the_agents_own_questions_are_answered_by_the_mode_or_asked() { PermissionOption { id: "no".into(), name: "Reject".into(), kind: "reject_once".into() }, ] }; - on_permission(&mut app, 1, "mcp__solidcraft__batch".into(), opts()); - assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { text, .. }) if text.contains("mcp__solidcraft__batch"))); - on_permission(&mut app, 2, "Run ls".into(), opts()); + on_permission(&mut app, 1, "mcp__solidcraft-app__batch".into(), Some("other"), opts()); + assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { text, .. }) if text.contains("mcp__solidcraft-app__batch"))); + on_permission(&mut app, 2, "Run ls".into(), None, opts()); assert!(matches!(app.agent_chat.items.last(), Some(Item::Permission { answer: None, .. }))); let n = app.agent_chat.items.len() - 1; answer_permission(&mut app, n, Some("always")); assert!(agents::always_allowed(&app.preferences, "claude", "Run ls")); - on_permission(&mut app, 3, "Run ls".into(), opts()); + on_permission(&mut app, 3, "Run ls".into(), None, opts()); assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "remembered"); } +/// A title that only mentions SolidCraft is no tool of SolidCraft's: in every mode but Allow +/// everything the user is asked, and the mode still answers when it says to. +#[test] +fn a_title_that_mentions_solidcraft_goes_through_the_users_mode() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.agent_chat.running_id = "codex".into(); + let opts = || vec![PermissionOption { id: "allow".into(), name: "Allow".into(), kind: "allow_once".into() }]; + let titles = [ + ("run solidcraft-cli; ls", Some("execute")), + ("run solidcraft-cli; ls", None), + ("Edit ~/.local/share/solidcraft/agent-chat/work/notes.txt", Some("edit")), + ("mcp__solidcraft__batch", Some("other")), + ("mcp__solidcraft-app__batch", Some("execute")), + ]; + for mode in [agents::Mode::Ask, agents::Mode::Edits] { + app.preferences.agent_permissions.insert("codex".into(), mode); + for (title, kind) in titles { + on_permission(&mut app, 1, title.into(), kind, opts()); + assert!(matches!(app.agent_chat.items.last(), Some(Item::Permission { answer: None, .. })), "{mode:?}: {title}"); + app.agent_chat.items.clear(); + } + // The chat's own tool stays a single question, the gate's. + on_permission(&mut app, 2, "mcp__solidcraft-app__batch".into(), Some("other"), opts()); + assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "{mode:?}"); + app.agent_chat.items.clear(); + } + app.preferences.agent_permissions.insert("codex".into(), agents::Mode::All); + on_permission(&mut app, 3, titles[0].0.into(), titles[0].1, opts()); + assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "Allow everything answers it"); +} + // ---- Messages typed while the agent works ---- use std::sync::Mutex; @@ -698,7 +849,8 @@ fn a_late_sign_in_retry_or_permission_cannot_restart_a_departed_turn() { crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap(); script.report(Event::Permission { key: 7, - title: "mcp__solidcraft__batch".into(), + title: "mcp__solidcraft-app__batch".into(), + kind: None, options: vec![PermissionOption { id: "allow".into(), name: "Allow".into(), kind: "allow_once".into() }], }); ended(&script, "auth"); @@ -1127,6 +1279,51 @@ fn stop_keeps_the_queue() { assert!(app.agent_chat.pending.is_empty()); } +#[test] +fn an_unresponsive_cancel_exit_keeps_the_queue_and_completed_changes() { + let (mut app, script, ctx) = app_with_script(); + let (tx, rx) = channel(); + app.agent_chat.tools_rx = Some(rx); + let before = app.session.doc.clone(); + send(&mut app, &ctx, "two boxes".into()); + let replies: Vec<_> = [0.0, 20.0].into_iter().map(|x| ask(&tx, "engine.execute", boxed(x))).collect(); + frame(&mut app); + for reply in replies { + assert_eq!(reply.recv_timeout(std::time::Duration::from_secs(30)).unwrap()["ok"], true); + } + let completed = app.session.doc.clone(); + let statuses = [Some(ToolStatus::Completed), Some(ToolStatus::Failed), Some(ToolStatus::Pending), Some(ToolStatus::InProgress), None]; + for (id, status) in statuses.into_iter().enumerate() { + script.report(Event::Tool { id: id.to_string(), title: Some("search".into()), kind: None, status, input: None, output: None }); + } + poll(&mut app, &ctx); + send(&mut app, &ctx, "later".into()); + cancel(&mut app); + script.report(Event::Exited { tail: vec![tr("ui.agent_chat_cancel_timeout").to_string()] }); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.state(), State::Exited); + assert!(app.agent_chat.backend.is_none() && app.agent_chat.turn.is_none()); + assert_eq!(texts(&app), ["later"]); + assert_eq!(script.prompts().len(), 1, "disconnect must not send the queue"); + assert!(Arc::ptr_eq(&app.session.doc, &completed), "completed changes stay in the design"); + let statuses: Vec<_> = app + .agent_chat + .items + .iter() + .filter_map(|item| match item { + Item::Tool { status, .. } => Some(*status), + _ => None, + }) + .collect(); + assert_eq!( + statuses, + [Some(ToolStatus::Completed), Some(ToolStatus::Failed), Some(ToolStatus::Failed), Some(ToolStatus::Failed), Some(ToolStatus::Failed)] + ); + let changes = app.agent_chat.items.iter().rposition(|i| matches!(i, Item::Changes { steps: 2, .. })).expect("the completed changes are grouped"); + undo_changes(&mut app, changes); + assert!(Arc::ptr_eq(&app.session.doc, &before), "the completed changes still undo together"); +} + /// Send now: cancel first, the prompt only after the agent has ended the cancelled turn, with a /// note that the previous step was interrupted (shown without it in the conversation). #[test] diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 0e4fe053a..bcc5453a4 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -1703,7 +1703,7 @@ fn occurrence_rows_inner( if r.double && !takes_components && app.session.doc.parts.contains_key(&placement.component) { crate::dialogs_part_size::open(app, placement.component); } - if r.clicked && takes_components { + if r.clicked && (takes_components || crate::dialogs_move::picks_components(app)) { if let Some(mut d) = app.dialog.take() { d.pick(&app.session, Sel::Occurrence { path: path.to_vec() }); app.dialog = Some(d); diff --git a/crates/ui-egui/src/browser_model_tests.rs b/crates/ui-egui/src/browser_model_tests.rs index 860cad349..499e8a3af 100644 --- a/crates/ui-egui/src/browser_model_tests.rs +++ b/crates/ui-egui/src/browser_model_tests.rs @@ -237,6 +237,15 @@ fn body_names(app: &crate::SolveApp) -> Vec { .unwrap_or_default() } +/// The bodies the open Move/Copy would move, a picked component's bodies included. +fn move_bodies(app: &crate::SolveApp) -> Vec { + let Some(d) = app.dialog.as_ref() else { return Vec::new() }; + crate::dialogs_move::params(app, d) + .ok() + .and_then(|p| p["bodies"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())) + .unwrap_or_default() +} + fn two_bodies(h: &mut crate::scenario::Harness) { h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Left"})).unwrap(); h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [30, 0, 0], "body_name": "Right"})).unwrap(); @@ -309,7 +318,7 @@ fn browser_move_copy_takes_a_component_clicked_in_the_tree() { open_move(&mut h); h.frames(2); click(&mut h, &format!("row:occurrence:{occurrence}")); - assert_eq!(body_names(&h.app), owned, "the component's bodies are the Move/Copy selection"); + assert_eq!(move_bodies(&h.app), owned, "the component's bodies are the Move/Copy selection"); assert!(h.app.tree.occurrence_move.is_none(), "the open body dialog stays; this click does not switch to component Move"); h.app.dialog = None; @@ -318,7 +327,7 @@ fn browser_move_copy_takes_a_component_clicked_in_the_tree() { click(&mut h, "row:Untitled"); assert_eq!(h.app.tree.picked_components, vec![0]); h.app.start("solid.move"); - let names = body_names(&h.app); + let names = move_bodies(&h.app); assert!(names.iter().any(|n| owned.contains(n)), "Move/Copy starts from the component picked in the tree: {names:?}"); } diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 074693b40..fcbd40cf2 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -734,11 +734,11 @@ fn viewport_items(app: &SolveApp) -> Vec { v.push(act("ui.fit", "Fit", "fit")); v.push(act("ui.home", "Home View", "home")); v.push(Item::sep()); - let anything_hidden = !app.session.visibility.hidden_bodies.is_empty() - || !app.session.visibility.hidden_sketches.is_empty() - || !app.session.visibility.hidden_folders.is_empty(); + let can_unisolate = !app.session.visibility.hidden_bodies.is_empty() || !app.session.visibility.hidden_occurrences.is_empty(); + let anything_hidden = + can_unisolate || !app.session.visibility.hidden_sketches.is_empty() || !app.session.visibility.hidden_folders.is_empty(); v.push(act("ui.showAll", "Show All", "eye").on(anything_hidden)); - v.push(act("ui.showAll", "Unisolate", "eye").on(!app.session.visibility.hidden_bodies.is_empty())); + v.push(act("ui.showAll", "Unisolate", "eye").on(can_unisolate)); v.push(Item::sep()); v.push(cmd(app, "solid.extrude", "Extrude")); v.push(cmd(app, "solid.fillet", "Fillet")); diff --git a/crates/ui-egui/src/deferred.rs b/crates/ui-egui/src/deferred.rs index 30991ac8b..8f451575f 100644 --- a/crates/ui-egui/src/deferred.rs +++ b/crates/ui-egui/src/deferred.rs @@ -140,6 +140,9 @@ impl SolveApp { if id == "timeline.play" { return self.run(id, params); } + if matches!(id, "edit.undo" | "edit.redo" | "timeline.roll_to") { + self.close_editor_for_history()?; + } // A manual history action takes over from playback. Playback takes its state out // while submitting its own next step, then puts it back to wait for that step. crate::timeline::stop_playback(self); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0d476a3ac..4018769b4 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -123,6 +123,11 @@ crate::dialog_descriptor::dialog_descriptors! { FeatureKind::ConstructionPlane { plane: PlaneRef::AtAngle { angle, .. } }) { angle: String = "45 deg".into() => shown_expr(angle, ValueKind::Angle), } => json!({"angle": angle}); + // With a reference plane, the plane touches where the face turns towards it (#8822). + TangentPlane("construct.plane.tangent", "TANGENT PLANE", [("Face", FACES, false), ("Reference plane", PLANES | PLANAR_FACES, false)], + FeatureKind::ConstructionPlane { plane: PlaneRef::Tangent { angle, .. } }) { + angle: String = "0 deg".into() => angle.as_ref().map_or_else(|| "0 deg".to_string(), ToString::to_string), + } => json!({"angle": angle}); Scale("solid.scale", "SCALE", [("Bodies", BODIES, true)], FeatureKind::Scale { factor, .. }) { factor: String = "2".into() => factor.to_string(), @@ -1127,6 +1132,19 @@ impl Dialog { continue; } } + // Move/Copy keeps a selected component as the component, so Create Copy can still be + // ticked after it (the bodies are what a move without a copy moves). + if matches!(d.kind, Kind::Move { .. }) + && let Sel::Occurrence { path } = sel + && !path.is_empty() + && let Some(inp) = d.inputs.first_mut() + && inp.accept == BODIES + { + if !inp.items.contains(sel) { + inp.items.push(sel.clone()); + } + continue; + } let as_body = match sel { Sel::Face { body, .. } | Sel::Edge { body, .. } | Sel::Vertex { body, .. } => Some(Sel::Body { name: body.to_string() }), _ => None, @@ -1318,6 +1336,7 @@ impl Dialog { | Kind::Loft { .. } | Kind::Sweep { .. } | Kind::AnglePlane { .. } + | Kind::TangentPlane { .. } | Kind::PathPlane { .. } | Kind::Midplane | Kind::Construct { .. } @@ -2960,6 +2979,16 @@ fn missing_pick(error: &str) -> bool { awaiting_selection(error) || error.get(..5).is_some_and(|start| start.eq_ignore_ascii_case("pick ")) } +/// A refusal that says the command is not available in this context ("`sketch.project` is not +/// available right now: no sketch is being edited"): the engine's own `Disabled` refusal for the +/// command this dialog runs, so the sketch ended or the mode changed under it. Guidance, not a +/// failure of the design: there is nothing to report (#10181). +fn context_refusal(app: &SolveApp, d: &Dialog, error: &str) -> bool { + let Some(id) = d.command() else { return false }; + let Some(spec) = solidcraft_engine::find_command(id) else { return false }; + spec.disabled_refusal(&app.session).is_some_and(|refusal| refusal == error) +} + fn error_rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut egui::Ui) { if matches!(d.kind, Kind::SketchModify(_)) && d.previews() @@ -3010,8 +3039,13 @@ fn error_rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut }); return; } + // A command that is not available in this context ("`sketch.project` is not available + // right now: no sketch is being edited") is guidance too: the context went away, not the + // design, so there is nothing to report (#10181). let rect = if missing_pick(&error) { crate::ui_kit::text(ui, &shown_error(&error), crate::ui_kit::Text::Hint("missing_pick")).rect + } else if context_refusal(app, d, &error) { + crate::ui_kit::text(ui, &shown_error(&error), crate::ui_kit::Text::Hint("context")).rect } else { // A fillet's refusal reads in plain words, or not at all where its Setback field already // says what is wrong; the kernel's own text stays in the hover text, Copy Details and the @@ -3066,7 +3100,7 @@ fn error_rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut #[derive(Debug, PartialEq)] pub(crate) enum FilletRefusal { /// In these plain words. - Plain(&'static str), + Plain(String), /// Not again: the Setback field already flags the value and names the least it takes. InField, } @@ -3081,6 +3115,12 @@ pub(crate) fn fillet_plain_error(error: &str, setback_in_field: bool) -> Option< if setback_in_field && error.contains("the setback must be more than") { return Some(FilletRefusal::InField); } + // A setback too short for its corner's patch: the least that builds, as the kernel names it + if let Some((_, rest)) = error.split_once(solidcraft_engine::kernel::SETBACK_AT_LEAST) + && let Some(least) = rest.split_once(" mm").map(|(n, _)| n.trim()).filter(|n| n.parse::().is_ok()) + { + return Some(FilletRefusal::Plain(crate::i18n::format("ui.fillet_error_setback_short", &[("least", &format!("{least} mm"))]))); + } let too_large = error.contains("larger than the faces beside its edges allow"); let corner = error.contains("setback") || error.contains("G2 corner") || error.contains("corner patch"); let kernel = error.contains("SMLib") @@ -3089,11 +3129,11 @@ pub(crate) fn fillet_plain_error(error: &str, setback_in_field: bool) -> Option< || error.contains("kernel internal error") || error.contains("the rounds would leave openings"); if too_large { - Some(FilletRefusal::Plain(tr("ui.fillet_error_too_large"))) + Some(FilletRefusal::Plain(tr("ui.fillet_error_too_large").to_string())) } else if corner && kernel { - Some(FilletRefusal::Plain(tr("ui.fillet_error_corner"))) + Some(FilletRefusal::Plain(tr("ui.fillet_error_corner").to_string())) } else if kernel { - Some(FilletRefusal::Plain(tr("ui.fillet_error_failed"))) + Some(FilletRefusal::Plain(tr("ui.fillet_error_failed").to_string())) } else { None } @@ -4984,6 +5024,15 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S }; ("construct.plane.along_path", json!({"path": path, "t": t})) } + Kind::TangentPlane { .. } => { + need(0, "a curved face")?; + let face = construct_ref(app, sels(d, 0).first().ok_or("pick a curved face")?)?; + match sels(d, 1).first() { + Some(reference) => ("construct.plane.tangent", json!({"face": face, "reference": plane_arg(app, Some(reference))?})), + // A null `angle` keeps the descriptor's angle out: it turns the plane from a reference. + None => ("construct.plane.tangent", json!({"face": face, "angle": null})), + } + } Kind::AnglePlane { .. } => { need(0, "a plane")?; let base = plane_arg(app, sels(d, 0).first())?; @@ -5857,7 +5906,6 @@ fn construct_picks(id: &str) -> Option<(&'static str, &'static str, &'static [(& "PLANE THROUGH THREE POINTS", &[("First point", POINT, "a"), ("Second point", POINT, "b"), ("Third point", POINT, "c")], ), - "construct.plane.tangent" => ("construct.plane.tangent", "TANGENT PLANE", &[("Face", FACES, "face")]), "construct.plane.perpendicular" => { ("construct.plane.perpendicular", "PERPENDICULAR PLANE", &[("Plane", PLANE, "plane"), ("Line", LINE, "line")]) } @@ -6324,14 +6372,19 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + // Evaluation projects the stored point onto the face along the drill + // direction when the body moves; seed the Face pick there too (#10689). + // Keep `position_exprs.point` as the stored value so expressions stay only + // when the pick is still that point (a moved face drops them for numbers). + let on_face = solidcraft_engine::doc::hole_on_surface(&crate::open_meshing::session_world(s), position.0, direction.0, &[]); if let Some(inp) = d.inputs.first_mut() { - inp.items = vec![face_sel(s, position.0).unwrap_or(Sel::Face { body: String::new(), index: 0, point: position.0 })]; + inp.items = vec![face_sel(s, on_face).unwrap_or(Sel::Face { body: String::new(), index: 0, point: on_face })]; } d.extra.insert("direction".into(), pt3(direction.0)); // A position given as expressions (#1678) is sent again while the pick // stays where the hole is; a new pick places it by the point picked. - if let Some(at) = at { - let exprs: Vec<&str> = at.iter().map(|e| e.as_str()).collect(); + if let Some(exprs) = at { + let exprs: Vec<&str> = exprs.iter().map(|e| e.as_str()).collect(); d.extra.insert("position_exprs".into(), json!({"at": exprs, "point": pt3(position.0)})); } crate::hole_refs::restore(s, &mut d, references, &f.edge_names, app.preferences.length_decimals); @@ -6598,11 +6651,15 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option().is_ok_and(|v| v.abs() < 1e-9)); + let origin: Vec = + origin.iter().map(|e| e.trim().parse::().map_or_else(|_| json!(e.to_string()), |v| json!(v))).collect(); let pick = match (axis_ref, axis_feature) { (Some(g), _) => model_axis_sel(s, g), (None, Some(name)) => Some(Sel::Axis { name: name.to_string() }), - (None, None) => world_axis(axis.0).filter(|_| origin.len() < 1e-9).map(|name| Sel::Axis { name }), + (None, None) => world_axis(axis.0).filter(|_| at_zero).map(|name| Sel::Axis { name }), }; match (pick, axis_ref) { (Some(pick), _) => { @@ -6615,7 +6672,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { - d.extra.insert("axis".into(), json!({"origin": pt3(origin.0), "dir": pt3(axis.0)})); + d.extra.insert("axis".into(), json!({"origin": origin, "dir": pt3(axis.0)})); } } d @@ -6755,6 +6812,17 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + let mut d = start("construct.plane.tangent")?; + d.kind = Kind::simple_restore(&f.kind)?; + if let Some(inp) = d.inputs.first_mut() { + inp.items = geo_sel(s, face).into_iter().collect(); + } + if let Some(inp) = d.inputs.get_mut(1) { + inp.items = reference.as_deref().and_then(|r| geo_sel(s, r)).into_iter().collect(); + } + d + } FeatureKind::ConstructionPlane { plane: PlaneRef::Midplane { a, b } } => { let mut d = start("construct.plane.midplane")?; if let Some(inp) = d.inputs.first_mut() { @@ -7319,6 +7387,42 @@ mod refused_ok_tests { let bore = h.app.session.execute("timeline.inspect", &json!({"feature": "Bore"})).unwrap(); assert!(bore.to_string().contains("\"depth\":\"5\""), "{bore}"); } + + /// After a parameter moves the drilled face, Edit Hole seeds the face where the hole is + /// now — not the stored raw position above or inside the body (#10689). + #[test] + fn editing_a_hole_after_its_face_moves_seeds_the_face() { + let mut h = Harness::new(); + steps( + &mut h, + &[ + json!({"call": "engine.execute", "params": {"command": "parameters.add", "params": {"name": "t", "expression": "10 mm"}}}), + json!({"call": "engine.execute", "params": {"command": "solid.box", "params": {"name": "Base", "body_name": "Base", "length": 40, "width": 30, "height": "t"}}}), + json!({"call": "engine.execute", "params": {"command": "solid.hole", "params": {"name": "Hole1", "position": [30, 15, 10], "diameter": 5, "depth": 4}}}), + json!({"call": "engine.execute", "params": {"command": "parameters.change", "params": {"name": "t", "expression": "8 mm"}}}), + json!({"call": "ui.editFeature", "params": {"feature": "Hole1"}}), + ], + ); + assert!(h.app.dialog.as_ref().is_some_and(|d| d.editing.is_some())); + let face = h.app.dialog.as_ref().and_then(|d| d.inputs.first()).and_then(|i| i.items.first()); + let Some(Sel::Face { point, body, .. }) = face else { + panic!("Edit Hole seeds a face pick, got {face:?}"); + }; + assert!(!body.is_empty(), "the face has a body name"); + assert!((point.z - 8.0).abs() < 1e-3, "seeded on the face at z=8, got {point:?}"); + h.frames(2); + assert_eq!(shown(&mut h), None, "no off-face refusal"); + if let Some(Kind::Hole { diameter, .. }) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + *diameter = "6 mm".into(); + } + h.frames(2); + assert_eq!(shown(&mut h), None); + steps(&mut h, &[json!({"key": "Enter"})]); + assert!(h.app.dialog.is_none()); + let vol = h.app.session.execute("inspect.measure", &json!({})).unwrap(); + let volume = vol["total"]["volume_mm3"].as_f64().expect("volume"); + assert!((volume - 9486.90).abs() < 0.1, "Ø6 hole on the moved face: {volume}"); + } } /// Whether two picks are the same face of the same body (wherever on it they were made). @@ -7599,6 +7703,34 @@ mod construct_ask_tests { assert!(status_error(&h.app).is_none(), "{:?}", status_error(&h.app)); assert!(!solidcraft_engine::view::construction_planes(&h.app.session).is_empty(), "the tangent plane is created"); } + + /// #8822: a reference plane and an angle place the tangent plane, and editing it brings both back. + #[test] + fn tangent_plane_lines_up_with_a_reference_plane() { + let mut h = Harness::new(); + cylinder(&mut h); + h.step(&json!({"click": {"world": [10, 0, 10]}})).unwrap(); // the outer cylindrical face + h.step(&json!({"start": "construct.plane.tangent"})).unwrap(); + h.frames(2); + let d = h.app.dialog.as_mut().expect("the dialog opens"); + assert_eq!(d.inputs.iter().map(|i| i.label).collect::>(), ["Face", "Reference plane"]); + d.inputs[1].items = vec![Sel::Plane { name: "XZ".into() }]; + if let Kind::TangentPlane { angle } = &mut d.kind { + *angle = "30 deg".into(); + } + h.step(&json!({"key": "Enter"})).unwrap(); + h.frames(2); + assert!(h.app.dialog.is_none(), "Create closes the dialog: {:?}", status_error(&h.app)); + let planes = solidcraft_engine::view::construction_planes(&h.app.session); + let (id, _, pl) = planes.last().expect("the tangent plane is created"); + // XZ faces ±Y; turned 30° about the axis (Z), on the side of the pick (+X). + let n = Vec3::new(0.5, -(3f64.sqrt()) / 2.0, 0.0); + assert!(pl.normal().cross(n).len() < 1e-6 && (pl.origin - n * 10.0).dot(n).abs() < 1e-6, "{pl:?}"); + let reopened = for_feature(&h.app, *id, None).expect("the plane opens for editing"); + assert!(matches!(&reopened.kind, Kind::TangentPlane { angle } if angle == "30 deg"), "{:?}", reopened.kind); + assert_eq!(reopened.inputs[1].items, vec![Sel::Plane { name: "XZ".into() }]); + assert_eq!(reopened.inputs[0].items.len(), 1, "the face is picked again"); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs_all_tests.rs b/crates/ui-egui/src/dialogs_all_tests.rs index f40267e84..d1ca57206 100644 --- a/crates/ui-egui/src/dialogs_all_tests.rs +++ b/crates/ui-egui/src/dialogs_all_tests.rs @@ -1254,6 +1254,30 @@ fn ok_on_a_rolled_back_pattern_editor_says_it_is_not_built() { assert!(text.starts_with("Pattern changed, but it is after the history marker"), "{text}"); } +/// #10852: the editor of a circular pattern whose axis origin is length expressions sends them +/// back as they are, so applying it unchanged keeps the pattern following its parameters. +#[test] +fn editing_a_circular_pattern_keeps_its_origin_expressions() { + let mut h = Harness::new(); + h.app.home.open = false; + for (id, params) in [ + ("parameters.add", json!({"name":"cx","expression":"20 mm"})), + ("solid.box", json!({"length":40,"width":30,"height":10,"corner":[0,0,0],"body_name":"Plate"})), + ("solid.cylinder", json!({"radius":2,"height":20,"base":["cx - 10 mm",15,-5],"operation":"cut","targets":["Plate"],"name":"Cut"})), + ("solid.pattern.circular", json!({"features":["Cut"],"axis":{"origin":["cx",15,0],"dir":[0,0,1]},"count":2,"name":"Pattern"})), + ] { + h.app.run(id, params).unwrap(); + } + let pattern = h.app.session.doc.features.last().unwrap().id; + let origin = |h: &Harness| serde_json::to_value(&h.app.session.doc.feature(pattern).unwrap().kind).unwrap()["pattern"]["origin"].clone(); + assert_eq!(origin(&h), json!(["cx", 15.0, 0.0])); + let d = crate::dialogs::for_feature(&h.app, pattern, None).unwrap(); + for (command, params) in crate::dialogs::apply_commands(&h.app, &d).unwrap() { + h.app.run(&command, params).unwrap(); + } + assert_eq!(origin(&h), json!(["cx", 15.0, 0.0]), "the expression is kept, not its value now"); +} + /// The Circular Pattern dialog must show only one field active at a time (#10066): the pick /// field's accent ring yields while a text field holds the keyboard, and clicking a pick field /// takes the keyboard back. diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 750fc7b8b..967480116 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -90,6 +90,7 @@ const MOVES: &[&str] = &[ #[derive(Clone, Debug)] pub enum Asm { + FromBodies, NewComponent { name: String, activate: bool, @@ -196,6 +197,7 @@ impl JointForm { impl Asm { pub fn title(&self) -> &'static str { match self { + Asm::FromBodies => "cmd.component_from_bodies", Asm::NewComponent { .. } => "NEW COMPONENT", Asm::Joint(j) if j.editing.is_some() => "EDIT JOINT", Asm::Joint(j) if j.as_built => "AS-BUILT JOINT", @@ -224,6 +226,7 @@ impl Asm { pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { let s = &app.session; let (asm, inputs) = match id { + "component.from_bodies" => (Asm::FromBodies, vec![SelInput::new("Bodies", BODIES, true)]), "component.create" => (Asm::NewComponent { name: String::new(), activate: true }, vec![SelInput::new("Bodies (optional)", BODIES, true)]), "joint.create" => (Asm::Joint(Box::new(JointForm::new(false, &app.session.doc))), side_inputs()), "joint.as_built" => ( @@ -669,6 +672,16 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se let mut enter = false; let problem = joint_problem(app, k, inputs); match k { + Asm::FromBodies => { + ui.add(egui::Label::new(app.tr("ui.components_from_bodies_hint")).wrap()); + if crate::ui_kit::button(ui, app.tr("ui.select_all"), crate::ui_kit::Button::Normal).clicked() + && let Some(input) = inputs.first_mut() + { + // Transfers take definition names, rather than the names of repeated placements. + input.items = app.session.model.state().bodies.iter().map(|body| Sel::Body { name: body.name.clone() }).collect(); + *active = 0; + } + } Asm::NewComponent { name, activate } => { enter |= text_row(ui, "Name", name, crate::i18n::tr_label("Component1")).0; crate::ui_kit::options(ui, "component_options", &mut [("Activate", activate)]); @@ -1073,6 +1086,13 @@ pub fn commands(app: &SolveApp, k: &Asm, inputs: &[SelInput]) -> Result { + let bodies = sel_items(inputs, 0).body_names(); + if bodies.is_empty() { + return Err(crate::i18n::tr("ui.components_from_bodies_required").into()); + } + cmd("component.from_bodies", json!({ "bodies": bodies })) + } Asm::NewComponent { name, activate } => { let bodies: Vec = sel_items(inputs, 0).body_names(); if bodies.is_empty() { diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs index fdbf4f11a..1ece845b6 100644 --- a/crates/ui-egui/src/dialogs_assembly_tests.rs +++ b/crates/ui-egui/src/dialogs_assembly_tests.rs @@ -1188,3 +1188,55 @@ fn inch_joint_offsets_limits_and_drive_values_keep_their_units() { let Kind::Assembly(Asm::Joint(f)) = edit.kind else { panic!("no edit") }; assert_eq!((f.limits[0].1.as_str(), f.limits[0].2.as_str()), ("0 in", "0.5 in")); } + +/// The Assemble ribbon must open a body picker, without executing the JSON command yet. +#[test] +fn components_from_bodies_dialog_select_all_cancel_and_ok() { + let mut h = crate::scenario::Harness::new(); + for x in [0, 30] { + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"corner":[x,0,0]})).unwrap(); + } + let before = h.app.session.doc.clone(); + let names: Vec<_> = h.app.session.model.state().bodies.iter().map(|body| body.name.to_string()).collect(); + h.step(&json!({"start":"component.from_bodies"})).unwrap(); + let d = h.app.dialog.as_ref().expect("From Bodies opens a dialog"); + assert!(matches!(d.kind, Kind::Assembly(Asm::FromBodies))); + assert!(apply_commands(&h.app, d).is_err(), "OK requires at least one body"); + assert_eq!(h.app.session.doc, before); + h.step(&json!({"widget":crate::i18n::tr("ui.select_all")})).unwrap(); + let commands = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands, vec![("component.from_bodies".into(), json!({"bodies":names}))]); + if let Ok(path) = std::env::var("SOLIDCRAFT_COMPONENTS_DIALOG_EVIDENCE") { + let ctx = crate::fonts::test_context(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0)); + let mut textures = Default::default(); + for frame in 0..6 { + let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(bounds), ..Default::default() }, |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }); + crate::ui_kit::test_textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + if frame == 5 { + crate::ui_kit::test_raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures).save(&path).unwrap(); + } + } + } + h.step(&json!({"widget":"Cancel"})).unwrap(); + assert!(h.app.dialog.is_none()); + assert_eq!(h.app.session.doc, before, "Cancel makes no components"); + // Existing body picks seed the same standard multi-selection input. + h.app.session.selection = vec![Sel::Body { name: names[0].clone() }]; + h.step(&json!({"start":"component.from_bodies"})).unwrap(); + let d = h.app.dialog.as_ref().unwrap(); + assert_eq!(d.inputs[0].items.body_names(), vec![names[0].clone()]); + h.step(&json!({"widget":crate::i18n::tr("ui.select_all")})).unwrap(); + h.step(&json!({"widget":"OK"})).unwrap(); + assert!(h.app.dialog.is_none()); + for name in &names { + let component = h.app.session.doc.find_component(name).expect("one component per body"); + assert_eq!(h.app.session.doc.model_body_component(h.app.session.model.state().body(name).unwrap()), component); + } + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before, "the dialog applies one undoable command"); +} diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 556f02975..6b27fec97 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -87,6 +87,7 @@ pub(super) fn command(kind: &Kind) -> Option<&'static str> { _ => k.simple_metadata().map(|(command, _)| command), }, Kind::Assembly(k) => match k { + crate::dialogs_assembly::Asm::FromBodies => Some("component.from_bodies"), crate::dialogs_assembly::Asm::NewComponent { .. } => Some("component.create"), crate::dialogs_assembly::Asm::Joint(f) => Some(if f.as_built { "joint.as_built" } else { "joint.create" }), crate::dialogs_assembly::Asm::JointOrigin { .. } => Some("joint.origin"), @@ -860,6 +861,12 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo Kind::AnglePlane { angle } => { enter |= expr_row(ui, "Angle", angle); } + // The angle turns the plane from its reference, so it shows once one is picked. + Kind::TangentPlane { angle } => { + if d.inputs.get(1).is_some_and(|inp| !inp.items.is_empty()) { + enter |= expr_row(ui, "Angle", angle); + } + } Kind::PathPlane { t, .. } => { enter |= expr_row(ui, "Position (0 to 1)", t); } @@ -1470,6 +1477,26 @@ mod tests { /// A smooth-patch fillet reopens with its corner and setback, and OK writes them as saved; a /// setback list the dialog cannot show as one distance is kept as it is. + /// A setback too short for SMLib's corner fill (past the least the field flags) is refused by + /// the kernel naming the smallest that builds; the dialog says it in plain words, that length + /// in them. + #[test] + fn a_setback_too_short_for_the_corner_says_the_least_that_builds() { + let refused = format!( + "invalid parameters for `solid.fillet`: the setback is too short for its corner: {}5.9620 mm (the corner's patch is convex only from there)", + solidcraft_engine::kernel::SETBACK_AT_LEAST + ); + match crate::dialogs::fillet_plain_error(&refused, true) { + Some(crate::dialogs::FilletRefusal::Plain(plain)) => assert!(plain.contains("5.9620 mm"), "{plain}"), + other => panic!("{other:?}"), + } + // A blend too large for its faces keeps its own words. + assert_eq!( + crate::dialogs::fillet_plain_error("the fillet is larger than the faces beside its edges allow", true), + Some(crate::dialogs::FilletRefusal::Plain(crate::i18n::tr("ui.fillet_error_too_large").to_string())) + ); + } + #[test] fn a_saved_smooth_patch_reopens_with_its_setback() { for (setbacks, field) in [ diff --git a/crates/ui-egui/src/dialogs_move.rs b/crates/ui-egui/src/dialogs_move.rs index bb74dc9ae..327a6771d 100644 --- a/crates/ui-egui/src/dialogs_move.rs +++ b/crates/ui-egui/src/dialogs_move.rs @@ -98,7 +98,7 @@ pub(crate) fn chained(app: &SolveApp) -> Option<(Vec, Mat)> { (Some(s), None) => s, (None, c) => c?, }; - (!is_identity(&m)).then(|| (items(d, 0).body_names(), m)) + (!is_identity(&m)).then(|| (bodies_of(app, d), m)) } /// Whether the triad is being dragged in a Move dialog (`drag` keeps the values it began from). @@ -117,7 +117,7 @@ fn made(app: &SolveApp, d: &Dialog) -> Option { /// Where a point a pick keeps on moved body `body` (see [`from_shown`]) shows: moved on by the /// current type's own move. pub(crate) fn shown_point(app: &SolveApp, body: &str, p: Vec3) -> Vec3 { - let Some(d) = app.dialog.as_ref().filter(|d| matches!(d.kind, Kind::Move { .. }) && items(d, 0).body_names().iter().any(|n| n == body)) else { + let Some(d) = app.dialog.as_ref().filter(|d| matches!(d.kind, Kind::Move { .. }) && bodies_of(app, d).iter().any(|n| n == body)) else { return p; }; made(app, d).map_or(p, |m| apply_point(&m, p)) @@ -128,7 +128,7 @@ pub(crate) fn shown_point(app: &SolveApp, body: &str, p: Vec3) -> Vec3 { /// own move. Kept there, a pivot or From point picked mid-move doesn't move with the move it /// sets. pub(crate) fn from_shown(app: &SolveApp, sel: Sel) -> Sel { - let Some(d) = app.dialog.as_ref().filter(|d| matches!(d.kind, Kind::Move { .. }) && on_moved(d, &sel)) else { return sel }; + let Some(d) = app.dialog.as_ref().filter(|d| matches!(d.kind, Kind::Move { .. }) && on_moved(&bodies_of(app, d), &sel)) else { return sel }; let Some(back) = made(app, d).and_then(|m| mat_inverse(&m)) else { return sel }; match sel { Sel::Edge { body, index, point } => Sel::Edge { body, index, point: apply_point(&back, point) }, @@ -138,14 +138,86 @@ pub(crate) fn from_shown(app: &SolveApp, sel: Sel) -> Sel { } } -/// Whether a pick is on one of the bodies being moved. -fn on_moved(d: &Dialog, s: &Sel) -> bool { +/// Whether a pick is on one of the bodies being moved (`moved`, see [`bodies_of`]). +fn on_moved(moved: &[String], s: &Sel) -> bool { match s { - Sel::Edge { body, .. } | Sel::Face { body, .. } | Sel::Vertex { body, .. } => items(d, 0).body_names().contains(body), + Sel::Edge { body, .. } | Sel::Face { body, .. } | Sel::Vertex { body, .. } => moved.contains(body), _ => false, } } +/// The bodies the picks stand for: the bodies picked, and the bodies of each picked component +/// (the bodies its placement shows, as a Browser row lists them). +fn bodies_of(app: &SolveApp, d: &Dialog) -> Vec { + let mut out: Vec = Vec::new(); + for sel in items(d, 0) { + let names = match sel { + Sel::Body { name } => vec![name.clone()], + Sel::Occurrence { path } => app.session.occurrence_bodies(path, true).unwrap_or_default(), + _ => Vec::new(), + }; + for name in names { + if !out.contains(&name) { + out.push(name); + } + } + } + out +} + +/// Whether Create Copy is ticked. +fn copies(d: &Dialog) -> bool { + d.extra.get("copy").and_then(Value::as_bool).unwrap_or(false) +} + +/// Whether a Move dialog takes the components picked (not their bodies) into its bodies input: a +/// click on a component in the component pick mode, or a Browser row. Not when it edits a move +/// that is already a feature (its picks stay bodies). Without Create Copy the components still +/// move their bodies (`targets`). +pub(crate) fn picks_components(app: &SolveApp) -> bool { + app.dialog.as_ref().is_some_and(|d| matches!(d.kind, Kind::Move { .. }) && d.active == 0 && d.editing.is_none()) +} + +/// What a click picks in a Move dialog: with the component pick mode on, the component a body +/// belongs to (copied as a component with Create Copy, see `targets`), otherwise the pick as it was. +pub(crate) fn component_pick(app: &SolveApp, hit: &crate::viewport::Hit, sel: Sel) -> Sel { + let (crate::viewport::Hit::Face { body, .. }, Sel::Body { .. }) = (hit, &sel) else { return sel }; + if app.ui.pick_components && picks_components(app) { + let occurrence = crate::viewport::component_selection(app, body); + if matches!(occurrence, Sel::Occurrence { .. }) { + return occurrence; + } + } + sel +} + +/// What the move moves and copies, as solid.move takes them: the bodies, and with Create Copy the +/// components picked (copied as components, see `occurrences`). +fn targets(app: &SolveApp, d: &Dialog) -> (Vec, Vec>) { + if !copies(d) { + return (bodies_of(app, d), Vec::new()); + } + let components = items(d, 0) + .iter() + .filter_map(|s| match s { + Sel::Occurrence { path } => Some(path.clone()), + _ => None, + }) + .collect(); + (items(d, 0).body_names(), components) +} + +/// The solid.move parameters that name what the move moves (`bodies`, and `occurrences` when +/// there are components to copy). +fn targets_json(app: &SolveApp, d: &Dialog) -> Value { + let (bodies, components) = targets(app, d); + let mut p = json!({ "bodies": bodies }); + if !components.is_empty() { + p["occurrences"] = json!(components); + } + p +} + /// A point of the model before this move where the earlier types' move puts it: on a moved body /// (`moved`) or, for the bodies' centre, always. fn carried(d: &Dialog, moved: bool, p: Vec3) -> Vec3 { @@ -196,7 +268,7 @@ fn sel_point(app: &SolveApp, d: &Dialog, s: Option<&Sel>) -> Option { None => crate::open_meshing::session_world(&app.session), }; // The centre is found where the body was modelled; the picked point is where it stands. - Some(crate::dialogs::edge_circle_in(&st, body, *index).map_or(*point, |(c, ..)| carried(d, on_moved(d, s), c))) + Some(crate::dialogs::edge_circle_in(&st, body, *index).map_or(*point, |(c, ..)| carried(d, on_moved(&bodies_of(app, d), s), c))) } Sel::Vertex { point, .. } | Sel::Face { point, .. } => Some(*point), _ => None, @@ -214,7 +286,7 @@ fn bodies_center(app: &SolveApp, d: &Dialog) -> Option { None => app.session.model.state(), }; let mut bb: Option<(Vec3, Vec3)> = None; - for n in items(d, 0).body_names() { + for n in bodies_of(app, d) { let Some(b) = st.body(&n) else { continue }; let x = b.mesh().bounds(); bb = Some(match bb { @@ -274,7 +346,7 @@ pub fn params(app: &SolveApp, d: &Dialog) -> Result { let made = transform(app, &p)?; with_transform(p, &mat_mul(&made, &c)) } - (Step::Needs(_), Some(c)) => with_transform(json!({ "bodies": items(d, 0).body_names() }), &c), + (Step::Needs(_), Some(c)) => with_transform(targets_json(app, d), &c), }; if d.extra.get("copy").and_then(Value::as_bool).unwrap_or(false) { p["copy"] = json!(true); @@ -326,13 +398,13 @@ fn with_transform(mut p: Value, m: &Mat) -> Value { /// The current type's own move, from where the earlier types leave the bodies. fn step(app: &SolveApp, d: &Dialog) -> Result { let Kind::Move { mode, x, y, z, rx, ry, rz, angle } = &d.kind else { return Err("not a move".into()) }; - let bodies = items(d, 0).body_names(); - if bodies.is_empty() { + let (bodies, components) = targets(app, d); + if bodies.is_empty() && components.is_empty() { return Err("select bodies first".into()); } let need_point = |i: usize, what: &str| sel_point(app, d, items(d, i).first()).ok_or(format!("select {what} first")); let num = |t: Vec3| json!([mm(t.x), mm(t.y), mm(t.z)]); - let mut p = json!({ "bodies": bodies }); + let mut p = targets_json(app, d); match *mode { TRANSLATE => p["translate"] = json!([x, y, z]), FREE => { @@ -401,7 +473,7 @@ fn step(app: &SolveApp, d: &Dialog) -> Result { fn axis_line(app: &SolveApp, d: &Dialog, s: &Sel) -> Option<(Vec3, Vec3)> { let (o, a) = modelled_axis(app, s)?; match chain(d) { - Some(c) if on_moved(d, s) => Some((apply_point(&c, o), apply_vector(&c, a))), + Some(c) if on_moved(&bodies_of(app, d), s) => Some((apply_point(&c, o), apply_vector(&c, a))), _ => Some((o, a)), } } diff --git a/crates/ui-egui/src/dialogs_move_tests.rs b/crates/ui-egui/src/dialogs_move_tests.rs index 2288bde01..28bf04548 100644 --- a/crates/ui-egui/src/dialogs_move_tests.rs +++ b/crates/ui-egui/src/dialogs_move_tests.rs @@ -643,3 +643,109 @@ fn editing_a_move_about_a_world_axis_keeps_the_angle_expression() { let Kind::Move { rx, ry, rz, .. } = &d.kind else { panic!("not a move") }; assert_eq!((rx.as_str(), ry.as_str(), rz.as_str()), ("0 deg", "0 deg", "45 deg")); } + +/// A design with a component `Part` holding a 20 mm cube at the origin, seen from above, with no +/// dialog open. Returns the harness and the part's placement. +fn part_harness() -> (crate::scenario::Harness, u64) { + let mut h = crate::scenario::Harness::new(); + let made = h.app.run("component.create", json!({"name": "Part", "grounded": false})).unwrap(); + h.app.run("solid.box", json!({"length": 20, "width": 20, "height": 20, "body_name": "Peg"})).unwrap(); + h.app.run("component.activate", json!({"component": "root"})).unwrap(); + h.app.ui.show_browser = false; + h.app.ui.show_timeline = false; + h.app.set_origin_shown(false); + h.step(&json!({"call": "ui.view", "params": {"view": "top"}})).unwrap(); + (h, made["occurrence"].as_u64().unwrap()) +} + +/// Opens Move/Copy with the viewport in component (`components`) or body pick mode, Create Copy +/// ticked or not, then clicks the top of the cube. +fn click_cube_in_move(components: bool, copy: bool) -> (crate::scenario::Harness, u64) { + let (mut h, occurrence) = part_harness(); + h.app.start("solid.move"); + h.settle(); + h.app.ui.pick_components = components; + h.app.ui.pick_bodies = !components; + if copy { + h.app.dialog.as_mut().unwrap().extra.insert("copy".into(), json!(true)); + } + h.step(&json!({"click": {"world": [10, 10, 20]}})).unwrap(); + (h, occurrence) +} + +#[test] +fn a_component_picked_with_create_copy_is_moved_as_a_component_copy() { + let (h, occurrence) = click_cube_in_move(true, true); + let d = h.app.dialog.as_ref().unwrap(); + assert_eq!(d.inputs[0].items, vec![Sel::Occurrence { path: vec![occurrence] }]); + let p = crate::dialogs_move::params(&h.app, d).unwrap(); + assert_eq!(p["occurrences"], json!([[occurrence]])); + assert_eq!(p["bodies"], json!([])); + assert_eq!(p["copy"], json!(true)); +} + +#[test] +fn a_body_picked_with_create_copy_is_still_a_body_copy() { + let (h, _) = click_cube_in_move(false, true); + let d = h.app.dialog.as_ref().unwrap(); + assert!(matches!(d.inputs[0].items.as_slice(), [Sel::Body { .. }]), "{:?}", d.inputs[0].items); + let p = crate::dialogs_move::params(&h.app, d).unwrap(); + assert_eq!(p["bodies"].as_array().map(Vec::len), Some(1)); + assert!(p.get("occurrences").is_none()); + assert_eq!(p["copy"], json!(true)); +} + +#[test] +fn a_component_picked_without_create_copy_moves_its_bodies_as_before() { + let (h, occurrence) = click_cube_in_move(true, false); + let d = h.app.dialog.as_ref().unwrap(); + assert_eq!(d.inputs[0].items, vec![Sel::Occurrence { path: vec![occurrence] }]); + let p = crate::dialogs_move::params(&h.app, d).unwrap(); + assert_eq!(p["bodies"].as_array().map(Vec::len), Some(1), "the component's body moves"); + assert!(p.get("occurrences").is_none()); + assert!(p.get("copy").is_none()); +} + +#[test] +fn a_component_picked_before_create_copy_is_ticked_is_copied_as_a_component() { + let (mut h, occurrence) = click_cube_in_move(true, false); + h.app.dialog.as_mut().unwrap().extra.insert("copy".into(), json!(true)); + let p = crate::dialogs_move::params(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(p["occurrences"], json!([[occurrence]])); + let placements = h.app.session.doc.occurrences.len(); + h.app.session.execute("solid.move", &p).unwrap(); + assert_eq!(h.app.session.doc.occurrences.len(), placements + 1, "OK copies the component"); +} + +#[test] +fn editing_a_move_never_takes_a_component_pick() { + // An existing move of another body is edited, and the component is clicked in component mode. + let (mut h, _) = part_harness(); + h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [100, 0, 0], "body_name": "Plate"})).unwrap(); + let moved = h.app.run("solid.move", json!({"bodies": ["Plate"], "translate": [0, 0, 5]})).unwrap()["feature"].as_u64().unwrap(); + h.app.dialog = Some(crate::dialogs::for_feature(&h.app, moved, None).unwrap()); + h.settle(); + h.app.ui.pick_components = true; + h.app.ui.pick_bodies = false; + h.step(&json!({"click": {"world": [10, 10, 20]}})).unwrap(); + let items = h.app.dialog.as_ref().unwrap().inputs[0].items.clone(); + assert!(items.iter().any(|s| matches!(s, Sel::Body { name } if name == "Peg")), "the click picks the body: {items:?}"); + assert!(!items.iter().any(|s| matches!(s, Sel::Occurrence { .. })), "an edited move's picks stay bodies: {items:?}"); +} + +#[test] +fn selected_components_are_copied_when_create_copy_is_ticked_after_them() { + // One selected placement starts the Browser's own component move, so two are selected here. + let (mut h, first) = part_harness(); + let second = h.app.run("occurrence.copy", json!({"occurrence": first, "translate": [50, 0, 0]})).unwrap()["occurrence"].as_u64().unwrap(); + h.app.session.selection = vec![Sel::Occurrence { path: vec![first] }, Sel::Occurrence { path: vec![second] }]; + h.app.start("solid.move"); + let picked = vec![Sel::Occurrence { path: vec![first] }, Sel::Occurrence { path: vec![second] }]; + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items, picked); + let p = crate::dialogs_move::params(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(p["bodies"].as_array().map(Vec::len), Some(2), "without a copy the components' bodies move"); + assert!(p.get("occurrences").is_none()); + h.app.dialog.as_mut().unwrap().extra.insert("copy".into(), json!(true)); + let p = crate::dialogs_move::params(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(p["occurrences"], json!([[first], [second]])); +} diff --git a/crates/ui-egui/src/dialogs_part_size.rs b/crates/ui-egui/src/dialogs_part_size.rs index d233a2ac1..95c8f159b 100644 --- a/crates/ui-egui/src/dialogs_part_size.rs +++ b/crates/ui-egui/src/dialogs_part_size.rs @@ -18,12 +18,16 @@ pub(crate) fn configuration(app: &SolveApp, component: u64) -> Option { if size.is_empty() { return None; } - Some(configuration_name(size, part.length)) + Some(configuration_name(&part.family, size, part.length)) } -fn configuration_name(size: &str, length: Option) -> String { +/// An inch family's length is in fractional inches (`1/2-13 UNC×2 in`), a metric one's in mm. +fn configuration_name(family: &str, size: &str, length: Option) -> String { match length.filter(|length| length.is_finite() && *length > 0.0) { - Some(length) => format!("{size}×{length}"), + Some(length) => match solidcraft_engine::cmd::part_length_label(family, length) { + Some(label) => format!("{size}×{label}"), + None => format!("{size}×{length}"), + }, None => size.to_owned(), } } @@ -183,14 +187,14 @@ pub fn rows(app: &SolveApp, ui: &mut egui::Ui, k: &mut Resize) -> bool { choice_row(ui, "Size", "part_resize_size", &mut k.size, &sizes); if let Some(lengths) = k.lengths() { let mut index = k.length.and_then(|l| lengths.iter().position(|x| *x == l)).unwrap_or(0); - let labels: Vec = lengths.iter().map(|l| crate::prefs::show_mm(app, *l, 1)).collect(); + let labels: Vec = lengths.iter().map(|l| crate::dialogs_parts::length_label(app, &k.family.id, *l)).collect(); let labels: Vec<&str> = labels.iter().map(String::as_str).collect(); choice_row(ui, "Length", "part_resize_length", &mut index, &labels); k.length = lengths.get(index).copied(); } if let Some((size, _)) = k.family.sizes.get(k.size) { row(ui, "Configuration", |ui| { - ui.label(configuration_name(size, k.length)); + ui.label(configuration_name(&k.family.id, size, k.length)); }); } crate::ui_kit::text(ui, crate::i18n::tr("ui.part_size_shared"), crate::ui_kit::Text::Hint("part_size_shared")); @@ -479,6 +483,10 @@ mod tests { ("set_screw", "M5", Some(10.0)), ("dowel_pin", "6", Some(20.0)), ("bearing", "608", None), + ("hex_cap_screw_inch", "1/2-13 UNC", Some(2.0 * 25.4)), + ("hex_nut_inch", "1/2-13 UNC", None), + ("washer_sae", "1/2", None), + ("washer_uss", "1/2", None), ] { let (app, id) = part(family, size, length); let k = Resize::new(&app, id).unwrap(); @@ -541,6 +549,23 @@ mod tests { assert_eq!(commands[0].1["length"], 20.5); } + /// #10316: an inch part's lengths are fractional inches in a millimetre design too, and the + /// command still takes millimetres. + #[test] + fn part_size_shows_an_inch_part_in_fractional_inches() { + let (app, id) = part("hex_cap_screw_inch", "1/2-13 UNC", Some(1.5 * 25.4)); + assert_eq!(configuration(&app, id).as_deref(), Some("1/2-13 UNC×1-1/2 in")); + let mut h = crate::scenario::Harness::new(); + h.app = app; + h.app.home.open = false; + menu(&mut h.app, Target::Component { id }); + h.frames(3); + assert!(h.widget_near("1-1/2 in", "Length").is_some()); + change(&mut h.app, "5/8-11 UNC", Some(2.0 * 25.4)); + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!((commands[0].1["size"].as_str(), commands[0].1["length"].as_f64()), (Some("5/8-11 UNC"), Some(50.8))); + } + #[test] fn part_size_real_widgets_change_size_length_and_confirm_once() { let (app, id) = part("socket_head_cap_screw", "M5", Some(20.5)); diff --git a/crates/ui-egui/src/dialogs_parts.rs b/crates/ui-egui/src/dialogs_parts.rs index d6f0c4b59..36e6fd0d1 100644 --- a/crates/ui-egui/src/dialogs_parts.rs +++ b/crates/ui-egui/src/dialogs_parts.rs @@ -20,6 +20,8 @@ pub struct Family { pub id: String, pub name: String, pub standard: String, + /// `metric` or `inch`: the Unit system list shows the families of one at a time. + pub system: String, /// Size names and their table rows. pub sizes: Vec<(String, Value)>, pub lengths: Option>, @@ -43,6 +45,7 @@ pub fn families(v: &Value) -> Vec { Some(Family { name: f.get("name").and_then(Value::as_str).unwrap_or(&id).to_string(), standard: f.get("standard").and_then(Value::as_str).unwrap_or("").to_string(), + system: f.get("system").and_then(Value::as_str).unwrap_or("metric").to_string(), sizes, lengths: f.get("lengths").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_f64).collect()), id, @@ -61,6 +64,9 @@ pub(crate) fn family_name(f: &Family) -> String { } } +/// The Unit system list: each system's id in the library and its label. +const SYSTEMS: [(&str, &str); 2] = [("metric", "Metric"), ("inch", "Inch")]; + #[derive(Clone, Debug)] pub struct Pt { pub family: usize, @@ -120,6 +126,12 @@ pub fn insert_params(lib: &[Family], k: &Pt, holes: &[Sel]) -> Result String { + solidcraft_engine::cmd::part_length_label(family, mm).unwrap_or_else(|| crate::prefs::show_mm(app, mm, 1)) +} + /// Where the Length list opens for a size: the index of the length an insert of it gets when /// none is asked for, which `parts.library` reports beside the size's table values. The list /// carries no item of its own for it, so a size whose default is missing opens on the first. @@ -162,12 +174,34 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Pt, inputs: &[SelInpu }); return false; } - let names: Vec = - lib.iter().map(|f| if f.standard.is_empty() { family_name(f) } else { format!("{} ({})", family_name(f), f.standard) }).collect(); + // The Unit system list picks metric or inch; Type lists that system's families. The system + // shown is the chosen family's, so a new system moves the choice to its first family. + let current = lib.get(k.family).map_or("metric", |f| f.system.as_str()); + let mut system = SYSTEMS.iter().position(|s| s.0 == current).unwrap_or(0); + let was_system = system; + choice_row(ui, "Unit system", "pt_system", &mut system, &SYSTEMS.map(|s| s.1)); + let system_id = SYSTEMS.get(system).map_or("metric", |s| s.0); + if system != was_system + && let Some(first) = lib.iter().position(|f| f.system == system_id) + { + k.family = first; + k.size = 0; + k.length = None; + } + let shown: Vec = (0..lib.len()).filter(|i| lib.get(*i).is_some_and(|f| f.system == system_id)).collect(); + let names: Vec = shown + .iter() + .filter_map(|i| lib.get(*i)) + .map(|f| if f.standard.is_empty() { family_name(f) } else { format!("{} ({})", family_name(f), f.standard) }) + .collect(); let refs: Vec<&str> = names.iter().map(String::as_str).collect(); - let before = k.family; - choice_row(ui, "Type", "pt_family", &mut k.family, &refs); - if k.family != before { + let mut pick = shown.iter().position(|i| *i == k.family).unwrap_or(0); + let before = pick; + choice_row(ui, "Type", "pt_family", &mut pick, &refs); + if pick != before + && let Some(i) = shown.get(pick) + { + k.family = *i; k.size = 0; k.length = None; } @@ -180,7 +214,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Pt, inputs: &[SelInpu k.length = None; } if let Some(ls) = &f.lengths { - let labels: Vec = ls.iter().map(|l| crate::prefs::show_mm(app, *l, 1)).collect(); + let labels: Vec = ls.iter().map(|l| length_label(app, &f.id, *l)).collect(); let refs: Vec<&str> = labels.iter().map(String::as_str).collect(); let mut i = k.length.unwrap_or_else(|| default_length(f, k.size, ls)); form_row(ui, "Length", |ui| { @@ -302,7 +336,8 @@ mod tests { for f in &l { assert_ne!(family_name(f), f.name, "{}", f.id); } - let unknown = Family { id: "spring".into(), name: "Spring".into(), standard: String::new(), sizes: vec![], lengths: None }; + let unknown = + Family { id: "spring".into(), name: "Spring".into(), standard: String::new(), system: "metric".into(), sizes: vec![], lengths: None }; assert_eq!(family_name(&unknown), "Spring"); } @@ -339,6 +374,38 @@ mod tests { assert!(insert_params(&[], &k, &[]).is_err()); } + /// #10316: the Unit system list above Type picks metric or inch, and Type then lists that + /// system's families only. + #[test] + fn the_system_list_picks_the_families_type_shows() { + let chosen = |h: &crate::scenario::Harness| { + let Kind::Part(k) = &h.app.dialog.as_ref().unwrap().kind else { panic!("not Insert Part") }; + commands(&h.app, k, &[]).unwrap()[0].1.clone() + }; + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.start("parts.insert"); + h.frames(3); + assert!(h.widget_near("Metric", "Unit system").is_some()); + assert_eq!(chosen(&h)["family"], "socket_head_cap_screw"); + h.step(&json!({"click":{"handle":"dialog:Unit system"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Unit system:Inch"}})).unwrap(); + h.frames(2); + assert_eq!((chosen(&h)["family"].as_str(), chosen(&h)["size"].as_str()), (Some("hex_cap_screw_inch"), Some("1/4-20 UNC"))); + // Type now lists the inch families and no metric one. + h.step(&json!({"click":{"handle":"dialog:Type"}})).unwrap(); + assert!(crate::scenario::handle_at("dialog:Type:Plain washer, USS (wide) (ANSI B18.22.1 Type A)").is_some()); + assert!(crate::scenario::handle_at("dialog:Type:Hex nut (ISO 4032)").is_none()); + h.step(&json!({"click":{"handle":"dialog:Type:Hex nut (inch) (ASME B18.2.2)"}})).unwrap(); + h.frames(2); + assert_eq!(chosen(&h)["family"], "hex_nut_inch"); + // Back to metric: the first metric family again. + h.step(&json!({"click":{"handle":"dialog:Unit system"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Unit system:Metric"}})).unwrap(); + h.frames(2); + assert_eq!(chosen(&h)["family"], "socket_head_cap_screw"); + } + /// Every dimension the library gives for a size is labelled in words, in each family. #[test] fn every_library_dimension_has_a_label_in_words() { diff --git a/crates/ui-egui/src/dialogs_sketch_tests.rs b/crates/ui-egui/src/dialogs_sketch_tests.rs index 86a6b2b50..fab58f2c2 100644 --- a/crates/ui-egui/src/dialogs_sketch_tests.rs +++ b/crates/ui-egui/src/dialogs_sketch_tests.rs @@ -11,6 +11,35 @@ fn fixture() -> Harness { h } +// --------------------------------------------------------------------------- +// #10181 +// --------------------------------------------------------------------------- + +/// #10181: the Project panel left open by a sketch that ends offers its context error +/// ("`sketch.project` is not available right now: no sketch is being edited") as something to +/// report: the dialog draws a "Create Issue…" button for a refusal that only says the sketch +/// is gone, which is guidance, not a failure. +#[test] +fn a_context_error_offers_no_create_issue_button_10181() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Body1"})).unwrap(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.settle(); + h.app.session.selection = vec![Sel::Face { body: "Body1".into(), index: 5, point: solidcraft_engine::geom::Vec3::new(20.0, 15.0, 20.0) }]; + h.app.start("sketch.project"); + h.frames(4); + assert!(h.app.dialog.as_ref().is_some_and(|d| matches!(d.kind, Kind::SketchProject { .. })), "the Project panel opens for the live sketch"); + // The sketch ends while the Project panel is still open. + h.app.finish_sketch(); + h.frames(4); + if h.app.dialog.is_some() { + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + h.settle(); + } + let error = h.app.dialog.as_ref().and_then(|d| d.error.clone()); + assert!(scenario::handle_at("dialog:create_issue").is_none(), "the Project panel offers its context error as something to report: {error:?}"); +} + fn picked(h: &Harness, command: &str) -> Dialog { let mut d = Dialog::for_command(&h.app, command).unwrap(); let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap(); diff --git a/crates/ui-egui/src/extrude_edit_tests.rs b/crates/ui-egui/src/extrude_edit_tests.rs index 921356fd6..66707fc2a 100644 --- a/crates/ui-egui/src/extrude_edit_tests.rs +++ b/crates/ui-egui/src/extrude_edit_tests.rs @@ -55,19 +55,49 @@ fn undoing_the_edited_feature_closes_its_editor_and_preserves_redo() { assert!(h.app.dialog.is_none(), "the restored feature can be edited normally"); } +// An editor kept open over an Undo refused its OK and Cancel afterwards, and Redo then lost the +// edited feature's place (#10688): the Undo cancels it first, as starting another tool does. #[test] -fn undo_that_keeps_the_edited_feature_keeps_its_editor() { +fn undo_that_keeps_the_edited_feature_cancels_its_editor_first() { let mut h = make(json!({})); let feature = h.app.session.doc.find_feature("Depth").unwrap().id; h.app.run("solid.box", json!({"corner":[30,0,0],"length":2,"width":2,"height":2})).unwrap(); + let full = h.app.session.doc.clone(); open(&mut h); h.app.start("edit.undo"); h.frames(8); assert!(h.app.session.doc.feature(feature).is_some()); - assert_eq!(h.app.dialog.as_ref().unwrap().editing.map(|(id, _)| id), Some(feature)); - assert!(h.app.editing_state.is_some()); - assert!(h.app.session.feature_edit_sketch.is_some()); + assert!(h.app.dialog.is_none() && h.app.editing_state.is_none()); + assert!(h.app.session.feature_edit_sketch.is_none()); + assert_eq!(h.app.session.doc.features.len(), 2); + assert_eq!(h.app.session.doc.marker, None, "the editor's rollback is put back before the Undo"); assert_eq!(h.app.session.redo.len(), 1); + + h.app.start("edit.redo"); + h.frames(8); + assert_eq!(*h.app.session.doc, *full, "Undo then Redo leaves the design as it was"); + open(&mut h); + h.step(&json!({"widget":"OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "the feature can be edited again"); + assert!(h.app.status.as_ref().is_none_or(|s| !s.0.contains("changed while the feature editor was open")), "{:?}", h.app.status); +} + +// A History step while an editor is open moved from the editor's rollback and left OK and +// Cancel refusing the design (#10688): the step cancels the editor, then moves from the marker. +#[test] +fn a_history_step_cancels_the_editor_and_steps_from_the_design_marker() { + let mut h = make(json!({})); + h.app.run("solid.box", json!({"corner":[30,0,0],"length":2,"width":2,"height":2})).unwrap(); + open(&mut h); + assert_eq!(h.app.session.doc.marker, Some(1), "Edit Feature rolls back to the extrude"); + crate::timeline::run_transport(&mut h.app, crate::ui_kit::HistoryTransport::Back); + h.frames(8); + assert!(h.app.dialog.is_none() && h.app.editing_state.is_none()); + assert_eq!(h.app.session.doc.marker, Some(2), "one step back from the end, not from the editor's rollback"); + crate::timeline::run_transport(&mut h.app, crate::ui_kit::HistoryTransport::Last); + h.frames(8); + assert_eq!(h.app.session.doc.marker, None); + assert_eq!(h.app.session.world_state().unwrap().body("Main").unwrap().mesh().bounds().max.z, 10.0); } #[test] diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 67f7920d6..af430ac74 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -136,10 +136,14 @@ pub const SYSTEM: &str = "system"; /// Match the system's preferred locale tags against the catalogs: the exact tag first /// (`zh-TW`, `pt-BR`, `en-GB`), then the tag's base language (`zh-CN` → `zh`, `de-AT` → `de`), -/// then English. Tags come in the system's order of preference; the first one that matches wins. +/// then English. A Chinese tag goes by its script or region instead ([`chinese_catalog`]). +/// Tags come in the system's order of preference; the first one that matches wins. pub fn match_system_tags(tags: &[String]) -> &'static str { for tag in tags { let tag = tag.replace('_', "-"); + if let Some(catalog) = chinese_catalog(&tag) { + return catalog; + } if let Some(catalog) = LOCALES.iter().find(|catalog| catalog.id.eq_ignore_ascii_case(&tag)) { return catalog.id; } @@ -151,11 +155,39 @@ pub fn match_system_tags(tags: &[String]) -> &'static str { ENGLISH.id } +/// The catalog for a Chinese tag (#10306): by its script when it has one (`Hant` → `zh-TW`, +/// `Hans` → `zh`), else by its region (`TW`, `HK` and `MO` use Traditional characters, so +/// `zh-TW`; any other region, or none, `zh`). macOS lists its languages with a script +/// (`zh-Hant-TW`), which no catalog matches exactly, and the base `zh` is Simplified. +fn chinese_catalog(tag: &str) -> Option<&'static str> { + let mut parts = tag.split('-'); + if !parts.next().is_some_and(|base| base.eq_ignore_ascii_case("zh")) { + return None; + } + let rest: Vec<&str> = parts.collect(); + let traditional = match rest.iter().find(|part| part.len() == 4) { + Some(script) => script.eq_ignore_ascii_case("Hant"), + None => rest.iter().any(|part| ["TW", "HK", "MO"].iter().any(|region| part.eq_ignore_ascii_case(region))), + }; + let id = if traditional { "zh-TW" } else { "zh" }; + LOCALES.iter().find(|catalog| catalog.id == id).map(|catalog| catalog.id) +} + /// The catalog id the system asks for, read once per process: the OS locale on desktop /// (Windows, macOS, Linux/BSD) and `navigator.languages` in the browser. pub fn system_language() -> &'static str { - static CACHED: OnceLock<&'static str> = OnceLock::new(); - CACHED.get_or_init(|| match_system_tags(&sys_locale::get_locales().collect::>())) + SYSTEM_LANGUAGE.get_or_init(|| { + // Tests read the same words on every PC, whatever its language. + if cfg!(test) { ENGLISH.id } else { match_system_tags(&sys_locale::get_locales().collect::>()) } + }) +} + +static SYSTEM_LANGUAGE: OnceLock<&'static str> = OnceLock::new(); + +/// `cfg!(test)` for the tests outside this crate, which link it without that: they all start from +/// the test harness, which calls this first. +pub(crate) fn pin_system_language() { + let _ = SYSTEM_LANGUAGE.set(ENGLISH.id); } /// The catalog id a `language` preference resolves to: the saved choice, or the system's for @@ -411,6 +443,33 @@ mod tests { assert_eq!(super::match_system_tags(&tags(&["xx-YY"])), "en", "unknown: English"); assert_eq!(super::match_system_tags(&tags(&[])), "en", "nothing: English"); assert_eq!(super::match_system_tags(&tags(&["xx-YY", "de-DE"])), "de", "the first tag that matches wins"); + // #10306: a Chinese tag goes by its script, else by its region. + for (tag, want) in [ + ("zh-Hant-TW", "zh-TW"), + ("zh-Hant-HK", "zh-TW"), + ("zh-Hant", "zh-TW"), + ("zh_Hant_MO", "zh-TW"), + ("ZH-HANT-tw", "zh-TW"), + ("zh-Hant-CN", "zh-TW"), + ("zh-HK", "zh-TW"), + ("zh-MO", "zh-TW"), + ("zh-Hans-CN", "zh"), + ("zh-Hans", "zh"), + ("zh-Hans-TW", "zh"), + ("zh-SG", "zh"), + ("zh", "zh"), + ] { + assert_eq!(super::match_system_tags(&tags(&[tag])), want, "{tag}"); + } + // Other languages keep the exact tag, then the base language. + assert_eq!(super::match_system_tags(&tags(&["sr-Latn-RS"])), "sr"); + assert_eq!(super::match_system_tags(&tags(&["zhx-TW", "de"])), "de", "only zh itself is Chinese"); + } + + /// Tests name English words, so the PC's own language never reaches them (#10297). + #[test] + fn tests_take_english_as_the_system_language() { + assert_eq!(super::system_language(), "en"); } /// A saved language is never overridden: only `system` resolves through the OS (#10138). diff --git a/crates/ui-egui/src/joint_handles.rs b/crates/ui-egui/src/joint_handles.rs index 6da0d7767..6c0197847 100644 --- a/crates/ui-egui/src/joint_handles.rs +++ b/crates/ui-egui/src/joint_handles.rs @@ -1023,8 +1023,9 @@ mod tests { let invalid = crate::prefs::lenient(&json!({"joint_rotation_coarse":0,"joint_rotation_fine":-3})); assert_eq!((invalid.joint_rotation_coarse, invalid.joint_rotation_fine), (10., 0.1)); } - /// Two boards held by two planar joints whose planes cross (#10331): the second joint can't - /// close its loop, so Move names it instead of saying the part has no movable axis. + /// Two boards held by two planar joints whose faces can never meet (the yellow front against + /// the red top, #10331): the second joint can't close its loop, so Move names it instead of + /// saying the part has no movable axis. #[test] fn blocked_move_names_a_conflicting_joint_of_the_part() { let mut h = Harness::new(); @@ -1038,7 +1039,7 @@ mod tests { h.app.run("occurrence.ground", json!({"occurrence":"Yellow:1","grounded":true})).unwrap(); let planar = |name: &str, a: [i32; 3], b: [i32; 3]| json!({"type":"planar","a":{"occurrence":"Yellow","face":a},"b":{"occurrence":"Red","face":b},"name":name}); h.app.run("joint.create", planar("Top", [200, 50, 20], [200, 350, 0])).unwrap(); - h.app.run("joint.create", planar("Front", [200, 0, 10], [200, 0, 30])).unwrap(); + h.app.run("joint.create", planar("Front", [200, 0, 10], [200, 50, 40])).unwrap(); let solved = joints::solve(&h.app.session.doc, &h.app.session.model.state()); let conflicting: Vec<_> = solved.conflicts.iter().map(|(_, name, _)| name.as_str()).collect(); assert!(!conflicting.is_empty(), "the scenario must conflict: {:?}", solved.conflicts); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 983648040..a79be3b44 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1162,6 +1162,10 @@ impl SolveApp { if self.file_load.busy() || self.file_picker.is_some() || self.saving.is_some() { return Err("a file operation is in progress".into()); } + // The editor's own marker moves come through here, so only Undo, Redo and Play close it. + if matches!(id, "edit.undo" | "edit.redo" | "timeline.play") { + self.close_editor_for_history()?; + } // Commands may start only detected slicers and the programs the user added under Custom…. if matches!(id, "file.save_mesh" | "file.send_to_slicer") { solidcraft_engine::slicers::set_chosen_programs(&self.preferences.custom_slicers); @@ -2099,6 +2103,22 @@ impl SolveApp { self.open_feature_edit(id, marker, original); } + /// Undo, Redo and the History bar would change the design under an open feature editor (Edit + /// Hole, Edit Box, …), whose OK and Cancel then refuse it (#10688). They cancel the editor + /// first, putting its marker back, as starting another tool does; while it is still opening + /// they wait for it. + pub(crate) fn close_editor_for_history(&mut self) -> Result<(), String> { + if self.pending_feature_edit.is_some() { + let why = i18n::tr("ui.history_waits_for_editor").to_string(); + self.set_status(why.clone(), true); + return Err(why); + } + if self.editing_state.is_some() || self.dialog.as_ref().is_some_and(|d| d.editing.is_some()) { + dialogs::cancel(self); + } + Ok(()) + } + fn open_feature_edit(&mut self, id: u64, marker: Option, original: Session) { self.editing_state = Some(dialogs::EditingState { source: self.session.scratch(), original }); // The id check matters while another feature's reopening is still pending: a later call diff --git a/crates/ui-egui/src/move_preview.rs b/crates/ui-egui/src/move_preview.rs index b6583ce6e..5a18495af 100644 --- a/crates/ui-egui/src/move_preview.rs +++ b/crates/ui-egui/src/move_preview.rs @@ -23,11 +23,12 @@ pub(crate) struct MovePreview { cached: Option, } -/// The listed bodies' world meshes, for the design and revision they were taken from. +/// The world meshes of the bodies drawn (the listed bodies, and the bodies of the components +/// copied), for the design and revision they were taken from. struct Cached { document: Arc, revision: u64, - bodies: Vec, + names: Vec, meshes: Vec>, } @@ -71,25 +72,38 @@ impl MovePreview { return None; } let bodies: Vec = params.get("bodies")?.as_array()?.iter().map(|b| b.as_str().map(str::to_string)).collect::>()?; - if bodies.is_empty() { + // The components copied (`occurrences`): their bodies are drawn moved, as copies of them. + let components: Vec> = match params.get("occurrences") { + None => Vec::new(), + Some(Value::Array(list)) => { + list.iter().map(|path| path.as_array()?.iter().map(Value::as_u64).collect::>>()).collect::>()? + } + Some(_) => return None, + }; + if bodies.is_empty() && components.is_empty() { return None; } - if self - .cached - .as_ref() - .is_none_or(|c| c.revision != app.session.revision || !Arc::ptr_eq(&c.document, &app.session.doc) || c.bodies != bodies) + let copy = params.get("copy").and_then(Value::as_bool) == Some(true); + // Only a copy takes components (the engine refuses them otherwise). + if !components.is_empty() && !copy { + return None; + } + let mut names = bodies.clone(); + for path in &components { + names.extend(app.session.occurrence_bodies(path, true).ok()?); + } + if self.cached.as_ref().is_none_or(|c| c.revision != app.session.revision || !Arc::ptr_eq(&c.document, &app.session.doc) || c.names != names) { let state = crate::open_meshing::session_world(&app.session); - let meshes: Vec> = bodies.iter().map(|n| state.body(n).map(|b| b.mesh())).collect::>()?; + let meshes: Vec> = names.iter().map(|n| state.body(n).map(|b| b.mesh())).collect::>()?; if meshes.iter().map(|m| m.triangles.len()).sum::() > MAX_TRIANGLES { return None; } - self.cached = Some(Cached { document: app.session.doc.clone(), revision: app.session.revision, bodies: bodies.clone(), meshes }); + self.cached = Some(Cached { document: app.session.doc.clone(), revision: app.session.revision, names: names.clone(), meshes }); } let cache = self.cached.as_ref()?; // About the world origin, as the Move feature turns bodies (`kernel::transform`). let m = rigid(translate, Vec3::ZERO, axis, angle); - let copy = params.get("copy").and_then(Value::as_bool) == Some(true); let mut scene = GpuScene::default(); let removed = scene.color(colors.removed); let mut bounds = Aabb3::EMPTY; @@ -205,4 +219,31 @@ mod tests { } assert!(pv.compute(&app, &[("solid.extrude".to_string(), json!({}))], c).is_none()); } + + /// A copy of a component is drawn where the copy lands: the component's bodies moved, the + /// component itself left where it was, so the preview is not the scratch design's. + #[test] + fn a_component_copy_is_previewed_where_the_copy_lands() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 5, "body_name": "Plate"})).unwrap(); + let made = s.execute("component.create", &json!({"name": "Part", "grounded": false})).unwrap(); + s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 15, "body_name": "Peg"})).unwrap(); + s.execute("component.activate", &json!({"component": "root"})).unwrap(); + let occurrence = made["occurrence"].as_u64().unwrap(); + let app = SolveApp::new(s, Services::default()); + let c = colors(&app); + let mut pv = MovePreview::default(); + // The component's box is 0..20 along X; the copy lands 50 mm along. + let copy = [("solid.move".to_string(), json!({"bodies": [], "occurrences": [[occurrence]], "copy": true, "translate": [50, 0, 0]}))]; + let built = pv.compute(&app, ©, c).expect("taken here").expect("built"); + assert!(built.replaced.is_empty(), "a copy keeps the original shown"); + assert!(near(Vec3::new(built.bounds.min.x, 0.0, 0.0), Vec3::new(50.0, 0.0, 0.0)), "{:?}", built.bounds); + assert!(near(Vec3::new(built.bounds.max.x, 0.0, 0.0), Vec3::new(70.0, 0.0, 0.0)), "{:?}", built.bounds); + // With bodies listed too, the component's copy is drawn alongside the body's: the + // component's box is 15 mm tall, the Plate 5 mm, so the height shows it is there. + let mixed = [("solid.move".to_string(), json!({"bodies": ["Plate"], "occurrences": [[occurrence]], "copy": true, "translate": [50, 0, 0]}))]; + let built = pv.compute(&app, &mixed, c).expect("taken here").expect("built"); + assert!(near(Vec3::new(built.bounds.min.x, 0.0, 0.0), Vec3::new(50.0, 0.0, 0.0)), "{:?}", built.bounds); + assert!(near(Vec3::new(0.0, 0.0, built.bounds.max.z), Vec3::new(0.0, 0.0, 15.0)), "{:?}", built.bounds); + } } diff --git a/crates/ui-egui/src/occurrence_ui_tests.rs b/crates/ui-egui/src/occurrence_ui_tests.rs index 3fc39dbbe..d75e76937 100644 --- a/crates/ui-egui/src/occurrence_ui_tests.rs +++ b/crates/ui-egui/src/occurrence_ui_tests.rs @@ -34,6 +34,38 @@ fn fixture() -> (Harness, u64, u64, u64) { (h, component, first, second) } +#[test] +fn viewport_restores_isolated_occurrences_and_undo_restores_isolation() { + for label in ["Show All", "Unisolate"] { + let (mut h, _, first, second) = fixture(); + h.app.session.selection.clear(); + let menu_item = + |h: &Harness, label: &str| context_menu::items(&h.app, &Target::Viewport).into_iter().find(|item| item.label == label).unwrap(); + assert!(!menu_item(&h, label).enabled, "nothing is hidden yet"); + let isolate = + context_menu::items(&h.app, &Target::Occurrence { path: vec![first] }).into_iter().find(|item| item.label == "Isolate").unwrap(); + context_menu::run_item(&mut h.app, &isolate, egui::Pos2::ZERO); + assert!(h.app.session.visibility.hidden_bodies.is_empty()); + assert_eq!(h.app.session.visibility.hidden_occurrences, vec![vec![second]]); + let other_body = h.app.session.occurrence_bodies(&[second], false).unwrap()[0].clone(); + assert!(!h.app.session.body_visible(&other_body)); + + let restore = menu_item(&h, label); + assert!(restore.enabled, "{label} must restore a hidden component instance"); + let undo = h.app.session.undo.len(); + context_menu::run_item(&mut h.app, &restore, egui::Pos2::ZERO); + assert!(h.app.session.visibility.hidden_occurrences.is_empty()); + assert!(h.app.session.body_visible(&other_body)); + assert_eq!(h.app.session.undo.len(), undo + 1, "restoring visibility is one undo step"); + assert!(!menu_item(&h, label).enabled, "all component instances are visible again"); + + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.visibility.hidden_occurrences, vec![vec![second]]); + assert!(!h.app.session.body_visible(&other_body)); + assert!(menu_item(&h, label).enabled); + } +} + #[test] fn folder_visibility_shortcut_targets_only_the_clicked_placement() { let (mut h, component, first, second) = fixture(); diff --git a/crates/ui-egui/src/params_dialog.rs b/crates/ui-egui/src/params_dialog.rs index 4cfd352d9..44df7a69f 100644 --- a/crates/ui-egui/src/params_dialog.rs +++ b/crates/ui-egui/src/params_dialog.rs @@ -109,6 +109,19 @@ struct Row { text: Option, } +impl Row { + /// Whether the Filter box's text (lower case) is in the row's name, expression, text, + /// comment or group. The expression lets a parameter's name find every one that uses it + /// (#9706). + fn matches(&self, filter: &str) -> bool { + filter.is_empty() + || [&self.name, &self.expression, &self.comment, &self.group] + .into_iter() + .chain(self.text.as_ref()) + .any(|field| field.to_ascii_lowercase().contains(filter)) + } +} + fn rows(app: &mut SolveApp) -> Vec { let list = app.session.execute("parameters.list", &json!({})).unwrap_or_default(); // Sketch dimension parameters: the sketch that owns each. @@ -273,15 +286,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui_kit::text(ui, error, ui_kit::Text::Error("parameters_error")); } let filter = d.filter.to_ascii_lowercase(); - let visible: Vec<_> = all - .iter() - .filter(|r| { - filter.is_empty() - || r.name.to_ascii_lowercase().contains(&filter) - || r.comment.to_ascii_lowercase().contains(&filter) - || r.group.to_ascii_lowercase().contains(&filter) - }) - .collect(); + let visible: Vec<_> = all.iter().filter(|r| r.matches(&filter)).collect(); // One Name-column floor for every table in this dialog so Favorites, User and // Model sections stay lined up when only some lists hold a long name (#8551 review). let name_floor = visible @@ -1472,6 +1477,27 @@ mod tests { assert_eq!(groups, [("Sketch1".into(), vec!["s_d3", "s_d2", "s_d1"]), ("Box1".into(), vec!["b_len", "b_h"])]); } + /// #9706: the Filter box reads expressions too, so a parameter's name lists every parameter + /// that uses it, and a value finds the parameter that holds it. + #[test] + fn the_filter_lists_the_parameters_that_use_a_name() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width": 1600, "height": 1400})); + for (name, expression) in [("width", "40 mm"), ("height", "width * 2"), ("depth", "5 mm")] { + h.app.run("parameters.add", json!({"name": name, "expression": expression})).unwrap(); + } + h.app.start("parameters.change"); + h.frames(6); + let all = ["width", "height", "depth"]; + for (filter, expected) in [("width", vec!["width", "height"]), ("WIDTH *", vec!["height"]), ("5 mm", vec!["depth"]), ("", all.to_vec())] { + h.app.params.as_mut().unwrap().filter = filter.into(); + h.frames(4); + let shown: Vec<&str> = all.into_iter().filter(|n| crate::scenario::rect_of(&format!("dialog:table:user:{n}")).is_some()).collect(); + assert_eq!(shown, expected, "filter {filter:?}"); + } + } + /// #8563: clicking a Name heading sorts every table in the window, the choice outlives the /// window, and moving a user parameter waits for the listed order. #[test] diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 47aee60fe..92185b34f 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -9116,9 +9116,8 @@ mod tests { #[test] fn language_preference_switches_and_persists() { let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); - // A first start follows the system (#10138); pin English so the words below are fixed. + // A first start follows the system (#10138), which is English in a test. assert_eq!(app.preferences.language, crate::i18n::SYSTEM); - app.preferences.language = "en".into(); assert_eq!(app.tr("ui.preferences"), "Preferences"); assert_eq!(app.tr("ui.extrude"), "Extrude"); diff --git a/crates/ui-egui/src/scenario.rs b/crates/ui-egui/src/scenario.rs index e8c9c333a..36c7b3b09 100644 --- a/crates/ui-egui/src/scenario.rs +++ b/crates/ui-egui/src/scenario.rs @@ -178,6 +178,7 @@ impl Drop for Harness { impl Harness { pub fn new() -> Harness { + crate::i18n::pin_system_language(); let mut h = Harness { app: SolveApp::new(Session::default(), Services::default()), ctx: { @@ -595,6 +596,20 @@ impl Harness { } else if let Some(how) = s.get("restart").and_then(Value::as_str) { // "crash": the app dies (its autosave lock goes with it, the entry stays); // "close": it closes normally. Then a new app starts on the same folders. + if how == "crash" { + // The work so far is autosaved before the crash: the write runs on a worker + // thread, which a loaded machine had not finished (#10690). The autosave's + // own ticks write it; a bounded wait, so an autosave that stopped writing + // still fails the recovery that follows. + for _ in 0..600 { + let caught_up = self.app.autosave.as_ref().and_then(|a| a.active.as_ref()).is_none_or(|a| a.caught_up(&self.app.session)); + if caught_up { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + self.frames(1); + } + } let mut old = std::mem::replace(&mut self.app, SolveApp::new(Session::default(), Services::default())); if how == "close" { crate::recovery_ui::close(&mut old); diff --git a/crates/ui-egui/src/settings_profiles_tests.rs b/crates/ui-egui/src/settings_profiles_tests.rs index c9fc6dead..bacbd7428 100644 --- a/crates/ui-egui/src/settings_profiles_tests.rs +++ b/crates/ui-egui/src/settings_profiles_tests.rs @@ -330,6 +330,31 @@ fn starting_a_profile_command_opens_preferences_instead_of_failing() { assert!(h.app.prefs_window.open); } +#[test] +fn typing_a_profile_name_keeps_focus_out_of_preferences_search() { + let mut h = Harness::new(); + h.app.home.open = false; + h.call("ui.prefs", json!({"open": "General"})); + h.frames(3); + h.step(&json!({"text": "profiles"})).expect("find Settings profiles"); + h.frames(3); + h.step(&json!({"click": {"handle": "dialog:Name"}})).expect("focus the profile name"); + h.frames(2); + let name_focus = h.ctx.memory(|memory| memory.focused()).expect("the name field has focus"); + for text in ["Lap", "top"] { + h.step(&json!({"text": text})).expect("type a profile name"); + h.frames(2); + assert_eq!(h.app.prefs_window.filter, "profiles", "profile-name text went to Preferences search"); + assert_eq!(h.ctx.memory(|memory| memory.focused()), Some(name_focus), "the name field keeps focus"); + } + assert!(h.widget("Laptop").is_some(), "the name field contains the typed name"); + h.step(&json!({"widget": "Save"})).expect("save the profile"); + h.frames(2); + assert_eq!(h.app.settings_profiles.active.as_deref(), Some("Laptop")); + assert_eq!(h.app.settings_profiles.names(), ["Laptop"]); + assert_eq!(h.app.prefs_window.filter, "profiles"); +} + #[test] fn choosing_a_profile_in_preferences_applies_it() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/sketch_moving_click_tests.rs b/crates/ui-egui/src/sketch_moving_click_tests.rs index f0bef1582..ba5e3919c 100644 --- a/crates/ui-egui/src/sketch_moving_click_tests.rs +++ b/crates/ui-egui/src/sketch_moving_click_tests.rs @@ -197,6 +197,26 @@ fn chain_with_a_line(on: bool) -> Harness { h } +/// #10653: Tangent Arc's first click on a line between its ends is refused at once, with the +/// tool's hint as the error, and picks nothing; a click on the line's end starts the arc. +#[test] +fn a_tangent_arc_first_click_off_a_curves_end_is_refused_at_once() { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[0,0],[20,0]],"connect":false,"infer":false})).unwrap(); + h.app.cam.distance = 120.0; + h.settle(); + h.step(&json!({"start":"sketch.arc.tangent"})).unwrap(); + click_at(&mut h, [10.0, 0.0]); + let refused = h.app.status.as_ref().is_some_and(|s| s.2 && s.0.contains("click the end of a line or arc")); + assert!(refused, "{:?}", h.app.status); + assert_eq!(h.app.tool.as_ref().map(|t| t.pts.len()), Some(0), "nothing picked"); + click_at(&mut h, [20.0, 0.0]); + click_at(&mut h, [30.0, 10.0]); + assert_eq!(curves(&h), 2, "{:?}", h.app.status); + assert!(sketch(&h).curves.iter().any(|c| matches!(c.kind, CurveKind::Arc { .. })), "the arc from the line's end"); +} + fn click_at(h: &mut Harness, at: [f64; 2]) { h.step(&json!({"move":{"sketch":at}})).unwrap(); h.frames(2); diff --git a/crates/ui-egui/src/sketch_pattern_tree.rs b/crates/ui-egui/src/sketch_pattern_tree.rs index 8991f684f..19b086b0c 100644 --- a/crates/ui-egui/src/sketch_pattern_tree.rs +++ b/crates/ui-egui/src/sketch_pattern_tree.rs @@ -25,26 +25,24 @@ pub(crate) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, sketch: u64, depth: us let suffix = pattern.id.strip_prefix("pat").unwrap_or(&pattern.id); let label = format!("{} {suffix}", crate::i18n::tr_label(name)); let active = app.session.active_sketch == Some(sketch); - let curves: Vec<_> = app - .session - .doc - .sketch(sketch) - .map(|sk| { + // The sources are inputs to the pattern: selecting its row must only delete copies. + // Select point copies when the point itself is a source; curve endpoints go with curves. + let sources: std::collections::BTreeSet<_> = pattern.entities.iter().collect(); + let copies: Vec<_> = pattern + .instances + .iter() + .flat_map(|instance| &instance.curves) + .map(|id| Sel::SketchCurve { id: id.clone(), sketch: None }) + .chain( pattern - .entities + .instances .iter() - .chain(pattern.instances.iter().flat_map(|i| &i.curves)) - .map(|id| { - if sk.curve_index(id).is_some() { - Sel::SketchCurve { id: id.clone(), sketch: None } - } else { - Sel::SketchPoint { id: id.clone() } - } - }) - .collect() - }) - .unwrap_or_default(); - let selected = active && !curves.is_empty() && curves.iter().all(|curve| app.session.selection.contains(curve)); + .flat_map(|instance| &instance.points) + .filter(|(source, _)| sources.contains(source)) + .map(|(_, id)| Sel::SketchPoint { id: id.clone() }), + ) + .collect(); + let selected = active && !copies.is_empty() && copies.iter().all(|copy| app.session.selection.contains(copy)); let response = draw_row( ui, ui.id().with(("sketch_pattern", sketch, &pattern.id)), @@ -62,7 +60,7 @@ pub(crate) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, sketch: u64, depth: us crate::sketch_modify_ui::edit_pattern(app, &pattern.id); } } else if response.clicked { - let items = if active { curves } else { vec![Sel::Feature { id: sketch }] }; + let items = if active { copies } else { vec![Sel::Feature { id: sketch }] }; let _ = app.run("select.set", json!({"items":items})); } } @@ -137,6 +135,59 @@ mod tests { assert!(crate::scenario::handle_at(&handle).is_some()); } + #[test] + fn deleting_a_pattern_row_preserves_sources_and_other_patterns() { + for left_history in [false, true] { + for circular in [false, true] { + for entities in [json!(["source"]), json!(["marker"]), json!(["source", "marker"])] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.show_browser = true; + h.app.preferences.timeline_left = left_history; + h.app.run("sketch.create", json!({"plane":"XY","name":"Patterned Sketch"})).unwrap(); + let sketch = h.app.session.active_sketch.unwrap(); + h.app.run("sketch.line", json!({"points":[[10,5],[15,5]],"ids":["source"]})).unwrap(); + h.app.run("sketch.point", json!({"point":[10,10],"id":"marker"})).unwrap(); + h.app.run("sketch.constraint.fix", json!({"entities":["source","marker"]})).unwrap(); + let sibling = h.app.run("sketch.pattern.rectangular", json!({"entities":entities,"count":2,"spacing":50})).unwrap(); + let command = if circular { "sketch.pattern.circular" } else { "sketch.pattern.rectangular" }; + let params = if circular { + json!({"entities":entities,"count":3,"center":"origin"}) + } else { + json!({"entities":entities,"count":3,"spacing":20}) + }; + let target = h.app.run(command, params).unwrap(); + let sk = h.app.session.doc.sketch(sketch).unwrap(); + let pattern = sk.patterns.iter().find(|p| p.id == target["pattern"]).unwrap().clone(); + let before = serde_json::to_value(sk).unwrap(); + h.frames(6); + let scope = if left_history { "timeline" } else { "browser" }; + h.step(&json!({"click":{"handle":format!("{scope}:sketch-pattern:{sketch}:{}", pattern.id)}})).unwrap(); + h.step(&json!({"key":"Delete"})).unwrap(); + h.frames(3); + + let sk = h.app.session.doc.sketch(sketch).unwrap(); + assert!(sk.curve_index("source").is_some(), "source curve lost: {scope}, {command}, {entities}"); + assert!(sk.point_index("marker").is_some(), "source point lost: {scope}, {command}, {entities}"); + assert_eq!(sk.patterns.len(), 1, "only the selected pattern should go"); + assert_eq!(sk.patterns[0].id, sibling["pattern"]); + for instance in &pattern.instances { + assert!(instance.curves.iter().all(|id| sk.curve_index(id).is_none())); + assert!(instance.points.iter().all(|(_, id)| sk.point_index(id).is_none())); + assert!(instance.constraints.iter().all(|id| sk.constraints.iter().all(|c| &c.id != id))); + } + let report = h.app.run("sketch.inspect", json!({})).unwrap(); + assert_eq!(report["dof"], 0, "fixed sources and the surviving pattern stay constrained"); + let after = serde_json::to_value(h.app.session.doc.sketch(sketch).unwrap()).unwrap(); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(serde_json::to_value(h.app.session.doc.sketch(sketch).unwrap()).unwrap(), before); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(serde_json::to_value(h.app.session.doc.sketch(sketch).unwrap()).unwrap(), after); + } + } + } + } + /// Where a text starts, drawn inside `within`. fn text_left(h: &Harness, text: &str, within: egui::Rect) -> f32 { let mut at = None; diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index 63a8f7ca8..1ec114ff5 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -1368,6 +1368,13 @@ pub(crate) fn place_point(app: &mut SolveApp, tool: &mut Tool, p: (Vec2, Option< return; } let p = crate::sketch_dims::placed(app, tool, &p); + // Tangent Arc starts at the end of a line, arc or spline. A first click anywhere else (on a + // line between its ends, in empty space) is refused now, saying where to click, instead of + // failing at the second click on a point the command can't take (#10653). + if tool.cmd == "sketch.arc.tangent" && tool.pts.is_empty() && !tangent_start(app, &p) { + app.set_status(hint(tool.cmd).unwrap_or_default(), true); + return; + } tool.pts.push(p); if n > 0 && tool.pts.len() >= n { if run_points(app, tool) { @@ -1379,6 +1386,13 @@ pub(crate) fn place_point(app: &mut SolveApp, tool: &mut Tool, p: (Vec2, Option< } } +/// Whether a click picked a sketch point a tangent arc can start at. +fn tangent_start(app: &SolveApp, p: &(Vec2, Option)) -> bool { + let Some(id) = &p.1 else { return false }; + let state = crate::open_meshing::session_world(&app.session); + app.session.active_sketch.and_then(|sid| state.sketch(sid)).is_some_and(|ss| solidcraft_engine::cmd::tangent_arc_starts_at(&ss.sketch, id)) +} + fn run_points(app: &mut SolveApp, t: &Tool) -> bool { let p = &t.pts; let width = |a: Vec2, b: Vec2, c: Vec2| -> f64 { 2.0 * (b - a).normalized().map(|d| d.cross(c - a).abs()).unwrap_or(1.0) }; diff --git a/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs b/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs index 347f2fa22..6596d8701 100644 --- a/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs +++ b/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs @@ -149,3 +149,63 @@ fn play(h: &mut Harness) { } h.frames(2); } + +#[test] +fn trimming_construction_source_and_offsets_by_click_or_drag_is_independent() { + for drag in [false, true] { + let mut h = Harness::new(); + h.app.home.open = false; + run(&mut h, "sketch.create", json!({"plane":"XY"})); + run(&mut h, "sketch.line", json!({"points":[[0,0],[40,40]],"construction":true,"infer":false,"connect":false,"ids":["source"]})); + let out = run(&mut h, "sketch.offset", json!({"curves":["source"],"distance":2,"symmetric":true,"chain":false})); + let parameter = out["param"].as_str().unwrap().to_string(); + let mut curves = vec!["source".to_string()]; + curves.extend(out["curves"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string())); + run(&mut h, "sketch.line", json!({"points":[[-20,20],[60,20]],"infer":false,"connect":false})); + h.call("ui.view", json!({"view":"top"})); + h.app.cam.distance = 100.0; + h.frames(3); + h.call("ui.start", json!({"command":"sketch.trim"})); + h.frames(2); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + if drag { + let a = screen(&mut h, 4.0, 5.0); + let b = screen(&mut h, 15.0, 5.0); + let mut path = vec![a]; + path.extend(steps(a, b, 16)); + let c = screen(&mut h, -10.0, 5.0); + path.extend(steps(b, c, 16)); + path.extend(steps(c, b, 16)); + press_and_move(&mut h, &path); + assert_eq!(h.app.session.doc.to_json(), before); + release(&mut h, b); + } else { + let points = [[10.0, 10.0], [10.0 - 2f64.sqrt(), 10.0 + 2f64.sqrt()], [10.0 + 2f64.sqrt(), 10.0 - 2f64.sqrt()]]; + for point in points { + h.step(&json!({"click":{"sketch":point}})).unwrap(); + h.frames(2); + } + } + assert_eq!(h.app.session.undo.len(), undo + if drag { 1 } else { 3 }, "drag {drag}: {:?}", h.app.status); + let sk = sketch(&h); + assert_eq!( + sk.constraints.iter().filter(|c| c.param.as_deref() == Some(¶meter)).count(), + 2, + "distance dimensions survive actual Trim gestures" + ); + let Shape::Line { a: origin, b: end } = sk.shape(sk.curve_index("source").unwrap()).unwrap() else { panic!("source line") }; + let direction = (end - origin).normalized().unwrap(); + for id in curves { + let Shape::Line { a, .. } = sk.shape(sk.curve_index(&id).unwrap()).unwrap() else { panic!("line") }; + assert!((a.y - 20.0).abs() < 1e-5, "drag {drag}: {id} {a:?}"); + if id != "source" { + assert!((direction.cross(a - origin).abs() - 2.0).abs() < 1e-6, "drag {drag}: {id} keeps 2 mm"); + } + } + for _ in 0..if drag { 1 } else { 3 } { + run(&mut h, "edit.undo", json!({})); + } + assert_eq!(h.app.session.doc.to_json(), before); + } +} diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index 1291d294f..b4897f57e 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -17,6 +17,10 @@ use crate::theme::Tokens; /// Apply transport actions from the current marker; endpoints stay bounded, including an /// empty design. All orientations reach the same rollback command. pub(crate) fn run_transport(app: &mut SolveApp, control: crate::ui_kit::HistoryTransport) { + // A step moves from the marker the design has, not the one an open editor rolled to (#10688). + if app.close_editor_for_history().is_err() { + return; + } let n = app.session.doc.features.len(); let marker = app.session.doc.marker.unwrap_or(n); let position = match control { @@ -1550,7 +1554,7 @@ mod tests { ("axis_point", PlaneRef::AxisPoint { axis: reference(), point: reference() }), ("two_edges", PlaneRef::TwoEdges { a: reference(), b: reference() }), ("three_points", PlaneRef::ThreePoints { a: reference(), b: reference(), c: reference() }), - ("tangent", PlaneRef::Tangent { face: reference(), at: Vec3::ZERO }), + ("tangent", PlaneRef::Tangent { face: reference(), at: Vec3::ZERO, reference: None, angle: None }), ("along_path", PlaneRef::AlongPath { path: reference(), t: "0.5".into() }), ("perpendicular", PlaneRef::Perpendicular { plane: reference(), line: reference() }), ] { diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 8223f4b25..90885755a 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -3251,7 +3251,8 @@ pub(crate) fn cancel_unfinished(app: &mut SolveApp) -> bool { pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) { crate::viewport_status::reconcile(app, ctx); crate::browser::update_folder_pick(app, ctx); - if design_shown(app) { + let chat_owner = crate::agent_chat::owns_keyboard_input(app, ctx); + if design_shown(app) && !chat_owner { crate::navigation::step_key_hold(app, ctx); } else { app.viewport.key_hold = None; @@ -3327,6 +3328,7 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) { } if popup_owner || inline_editor + || chat_owner || (crate::viewport_status::enabled(app) && app.ui.palette_open) || (ctx.egui_wants_keyboard_input() && !(crate::viewport_status::enabled(app) && app.viewport_status.owns_focus(ctx))) { diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index d118edb91..ca319e6b5 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -785,6 +785,9 @@ pub(crate) fn projection_preselection(selection: &[solidcraft_engine::Sel]) -> O Some(match item { Sel::Body { name } => json!({"body":name}), Sel::ExternalSketchCurve { sketch, id } => json!({"sketch":sketch,"curve":id}), + // A straight line of another sketch, picked into the dialog, names its sketch + // (#3726): the same reference the external pick stands for (#10291). + Sel::SketchCurve { id, sketch: Some(sketch) } => json!({"sketch":sketch,"curve":id}), Sel::ExternalSketchPoint { sketch, id } => json!({"sketch":sketch,"point":id}), Sel::Vertex { body, point } => json!({"body":body,"vertex":[point.x,point.y,point.z]}), Sel::Edge { body, point, .. } => json!({"body":body,"edge":[point.x,point.y,point.z]}), diff --git a/crates/ui-egui/src/ui_kit/details.rs b/crates/ui-egui/src/ui_kit/details.rs index 250a0c182..99dab28cf 100644 --- a/crates/ui-egui/src/ui_kit/details.rs +++ b/crates/ui-egui/src/ui_kit/details.rs @@ -45,13 +45,33 @@ pub(crate) fn details_field_owned_escape(ctx: &egui::Context) -> bool { #[derive(Clone, Debug, PartialEq)] pub(crate) enum DetailValue { - Number { value: f64, min: f64, max: f64, suffix: String }, - Length { value: f64, units: String }, + Number { + value: f64, + min: f64, + max: f64, + suffix: String, + }, + /// Shown to `decimals` places, as the design shows lengths. + Length { + value: f64, + units: String, + decimals: u8, + }, Angle(f64), - Slider { value: f64, min: f64, max: f64 }, - Axis { value: [f64; 3], current: String }, + Slider { + value: f64, + min: f64, + max: f64, + }, + Axis { + value: [f64; 3], + current: String, + }, Check(bool), - Choice { selected: usize, options: Vec }, + Choice { + selected: usize, + options: Vec, + }, } pub(crate) struct DetailSetting { @@ -136,7 +156,7 @@ fn setting(ui: &mut Ui, field: &DetailSetting, focus: bool) -> Option Some(super::number_field(ui, value, *min..=*max, 0.01, suffix)), - DetailValue::Length { value, units } => Some(super::length_field(ui, value, units, 6)), + DetailValue::Length { value, units, decimals } => Some(super::length_field(ui, value, units, *decimals)), DetailValue::Angle(value) => Some(super::angle_field(ui, value)), DetailValue::Slider { value, min, max } => Some(super::slider(ui, value, *min..=*max, Default::default())), DetailValue::Check(value) => Some(super::checkbox(ui, "", value)), @@ -228,6 +248,9 @@ pub(crate) fn details(ui: &mut Ui, id: &str, description: &Details, max_height: ui.ctx().data_mut(|data| data.insert_temp(egui::Id::new(CONTROL_FOCUS), Vec::::new())); ui.ctx().data_mut(|data| data.insert_temp(egui::Id::new(OWNED_POPUPS), Vec::::new())); ui.set_width((t.form_card_width + if description.findings.is_empty() { 0.0 } else { t.space_24 * 2.0 }).min(ui.available_width())); + // A card's area is as tall as it was last frame: allowed `max_height`, a body that grew + // after the first frame scrolls instead, and its last row was cut off (#10708). + ui.set_max_height(max_height); super::scope(ui, |ui| { let mut caption_height = 0.0; if let Some(caption) = &description.caption { diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs index 400f270e8..86327e846 100644 --- a/crates/ui-egui/src/ui_kit/fields.rs +++ b/crates/ui-egui/src/ui_kit/fields.rs @@ -686,6 +686,9 @@ fn editor_reserving(ui: &mut Ui, value: &mut String, hint: &str, completion: boo ui.ctx().data_mut(|data| data.insert_temp(egui::Id::new("sc_focused_editor"), response.id)); } super::text_menu::menu(ui, &mut response, value, super::text_menu::Field::LINE); + if response.has_focus() { + crate::prefs_search::note_key_sink(ui.ctx()); + } if completion && ui.is_enabled() { ui.ctx().data_mut(|data| { let id = egui::Id::new("sc_value_fields"); @@ -1330,7 +1333,20 @@ pub(crate) fn bounded_length_field( /// Angle in degrees, dragged or typed. Tokens: control_height, scope control/font tokens. pub(crate) fn angle_field(ui: &mut Ui, value: &mut f64) -> Response { - let response = ui.add(egui::DragValue::new(value).speed(1.0).suffix(" deg").custom_parser(crate::prefs::parse_number)); + // An owner that keeps the angle in radians gives back the value the field set a hair off + // (-3 deg as -2.9999999999999996). The field takes that for a change made elsewhere and + // rewrites what is being typed from it, which drops a decimal point just typed: "-3." became + // "-3", and the 7 after it made -37 (#10582). It is given the value it set instead. + let set = ui.next_auto_id().with("angle_field_set"); + let mut shown = *value; + if let Some(last) = ui.data(|d| d.get_temp::(set)).filter(|last| (last - shown).abs() <= 1e-9 * last.abs().max(1.0)) { + shown = last; + } + let response = ui.add(egui::DragValue::new(&mut shown).speed(1.0).suffix(" deg").custom_parser(crate::prefs::parse_number)); + if response.changed() { + *value = shown; + ui.data_mut(|d| d.insert_temp(set, shown)); + } Tokens::get().input_bevel(ui, &response); scenario::publish_target(&format!("dialog:angle:{}", label(ui)), response.rect); response diff --git a/crates/ui-egui/src/ui_kit/fields_tests.rs b/crates/ui-egui/src/ui_kit/fields_tests.rs index 135c9a247..0fc0777e4 100644 --- a/crates/ui-egui/src/ui_kit/fields_tests.rs +++ b/crates/ui-egui/src/ui_kit/fields_tests.rs @@ -614,6 +614,30 @@ fn placement_field_keeps_focus_for_owner_validation_on_enter() { assert!(value.contains('x')); } +/// #10582: an angle typed a key at a time keeps its decimal point when its owner keeps it in +/// radians, as Edit Canvas does, and so gives back a hair off the value the field set. +#[test] +fn an_angle_kept_in_radians_takes_a_typed_decimal_point() { + let ctx = crate::fonts::test_context(); + let mut radians = 0.0_f64; + let mut draw = |ui: &mut Ui| { + row(ui, "Angle", |ui| { + let mut degrees = radians.to_degrees(); + if angle_field(ui, &mut degrees).changed() { + radians = degrees.to_radians(); + } + }); + }; + frame(&ctx, vec![], &mut draw); + let at = scenario::rect_of("dialog:angle:Angle").expect("the angle field").center(); + frame(&ctx, pointer(at, true), &mut draw); + frame(&ctx, pointer(at, false), &mut draw); + for typed in ["-", "3", ".", "7"] { + frame(&ctx, vec![egui::Event::Text(typed.into())], &mut draw); + } + assert!((radians.to_degrees() + 3.7).abs() < 1e-9, "typed -3.7, the angle is {}", radians.to_degrees()); +} + #[test] fn bounded_name_editor_keeps_unicode_character_cap() { let ctx = crate::fonts::test_context(); diff --git a/crates/ui-egui/src/view_pick.rs b/crates/ui-egui/src/view_pick.rs index 2c864fc92..65b940581 100644 --- a/crates/ui-egui/src/view_pick.rs +++ b/crates/ui-egui/src/view_pick.rs @@ -150,9 +150,22 @@ pub fn pick_command(app: &mut SolveApp, p: &Value) -> Result { .and_then(|(so, sn)| section_cap(app, &st, &bounds, input, so, sn, kept.first().map(|c| c.t), include_ghosted, replaced, &active_bodies)); let face_t = kept.first().map(|c| c.t).or(cap.as_ref().map(|(t, _, _)| *t)); let (edge, vertex) = match (edges_on, input.pixel) { - (true, Some(pos)) => { - near_edges(app, &st, &bounds, &proj, input, pos, face_t, edge_px, &active_bodies, replaced, include_ghosted, wireframe, slack) - } + (true, Some(pos)) => near_edges( + app, + &st, + &bounds, + &proj, + input, + pos, + face_t, + edge_px, + &active_bodies, + replaced, + include_ghosted, + wireframe, + slack, + section, + ), _ => (None, None), }; hits.push(match (all, cap, kept) { @@ -382,11 +395,16 @@ fn near_edges( include_ghosted: bool, wireframe: bool, slack: f64, + section: Option<(Vec3, Vec3)>, ) -> (Option, Option) { let reach = crate::pick_index::reach(proj, pos, edge_px.max(6.0)); + // The section removes a half-space and nothing there is drawn, so the mouse picker skips + // edges and vertices in it; a pick must not answer with what the user cannot see (#10704, + // the same `kept` test `viewport::pick` applies). + let kept = |p: Vec3| section.is_none_or(|(so, sn)| sn.dot(p) <= sn.dot(so) + SECTION_EPS); // `slack` is the body's own: what counts as lying on the face in front depends on how // coarsely that body is meshed, never on where the camera stands. - let visible = |p: Vec3, slack: f64| wireframe || face_t.is_none_or(|t| (p - input.o).dot(input.d) <= t + slack); + let visible = |p: Vec3, slack: f64| kept(p) && (wireframe || face_t.is_none_or(|t| (p - input.o).dot(input.d) <= t + slack)); let mut best_e: Option = None; let mut best_v: Option = None; for (i, b) in st.bodies.iter().enumerate() { diff --git a/crates/ui-egui/src/view_pick_tests.rs b/crates/ui-egui/src/view_pick_tests.rs index a632b0316..3ca9e3735 100644 --- a/crates/ui-egui/src/view_pick_tests.rs +++ b/crates/ui-egui/src/view_pick_tests.rs @@ -237,3 +237,40 @@ fn the_mouse_picker_stops_at_a_section_cap() { other => panic!("the top face: {other:?}"), } } + +/// With a Section Analysis on, `view.pick` must not answer with edges or vertices in the +/// half the section removes: the mouse picker has skipped them since #6722, and an agent +/// must not get an answer the user cannot see (#10704). +#[test] +fn a_section_pick_skips_edges_and_vertices_in_the_removed_half() { + let mut h = Harness::new(); + h.call("engine.execute", json!({"command": "solid.box", "params": {"length": 40, "width": 30, "height": 20}})); + h.app.cam = Camera { + target: Vec3::new(20.0, 15.0, 10.0), + yaw: 0.0, + pitch: std::f64::consts::FRAC_PI_2, + roll: 0.0, + distance: 200.0, + fov: 0.0, + up: Default::default(), + }; + // Section XZ at 15 mm: keeps y 0..15, removes y 15..30. + h.call("engine.execute", json!({"command": "inspect.section", "params": {"plane": {"origin": [0, 15, 0], "normal": [0, 1, 0]}}})); + // The same projection the model-frame pick builds, so a world point's pixel can be picked. + let rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(960.0, 600.0)); + let cam = h.app.cam; + let proj = crate::viewport::Proj { cam, vp: cam.view_proj(960.0 / 600.0, crate::viewport::scene_radius(&h.app)), rect }; + let px = |p: [f64; 3]| { + let sp = proj.to_screen(Vec3::new(p[0], p[1], p[2])).unwrap(); + json!([sp.x as f64, sp.y as f64]) + }; + // Top-view pixels on the removed half's top edge, corner, and mid-edge: nothing is drawn + // there, so the pick answers with nothing (it used to return the edge, with `body: null`). + for w in [[40.0, 25.0, 20.0], [40.0, 30.0, 20.0], [20.0, 30.0, 20.0]] { + let r = pick(&mut h, json!({"pixels": [px(w)]})); + assert_eq!(r["hits"][0], serde_json::Value::Null, "the removed half must pick nothing at {w:?}: {}", r["hits"][0]); + } + // The same pick on the kept half's edge (y < 15) still answers with that edge. + let r = pick(&mut h, json!({"pixels": [px([40.0, 5.0, 20.0])]})); + assert!(r["hits"][0]["edge"].get("index").is_some(), "the kept half's edge must still pick: {}", r["hits"][0]); +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 5ed884907..05e59b883 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -98,13 +98,10 @@ pub struct ViewportState { lod_rest: CameraRest, /// Each body mesh's box (the mesh held, so its address stays its own), from the last state. mesh_bounds: std::sync::Mutex, - /// Each shown body mesh's section index for the cut's normal (the mesh held, so its address - /// stays its own): a Section Analysis dragged along its normal cuts through it. + /// Each shown body mesh's section index (the mesh held, so its address stays its own): a + /// Section Analysis dragged or tilted cuts through it. section_index: std::sync::Mutex< - std::collections::HashMap< - (usize, [u64; 3]), - (std::sync::Arc, std::sync::Arc), - >, + std::collections::HashMap, std::sync::Arc)>, >, /// Each body mesh's picking index (made the first time a pick reaches the body), kept while /// the mesh is part of the world state. @@ -462,6 +459,13 @@ fn scene_bounds(app: &SolveApp) -> solidcraft_engine::geom::Aabb3 { b } +/// The ambient occlusion radius (0: off): 4% of what the frame draws, the box the depth range uses, +/// so a preview in an empty design has its own. Nothing to draw has no occlusion (#9327). +fn ao_radius(app: &SolveApp) -> f32 { + let size = scene_bounds(app).diagonal(); + if app.preferences.ambient_occlusion && app.ui.visual_style != 2 && size > 0.0 { (size * 0.04).clamp(1e-4, 1e6) as f32 } else { 0.0 } +} + pub fn scene_radius(app: &SolveApp) -> f64 { let b = scene_bounds(app); let r = if b.is_empty() { 50.0 } else { b.diagonal() * 0.5 + b.center().dist(app.cam.target) }; @@ -1666,18 +1670,17 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene { let col = sc.color(c4(Tokens::view().text.gamma_multiply(0.9))); let mut kept = app.viewport.section_index.lock().map(|mut k| std::mem::take(&mut *k)).unwrap_or_default(); let mut made = std::collections::HashMap::with_capacity(kept.len()); - let normal = [n.x.to_bits(), n.y.to_bits(), n.z.to_bits()]; // The closed solid bodies the plane cuts and where it cuts them: their hatches by part. let by_part = app.preferences.section_hatch == crate::prefs::SectionHatch::ByPart; let mut cuts: Vec<(&str, Vec<(Vec3, Vec3)>)> = Vec::new(); for b in st.bodies.iter().filter(|b| app.body_visible(&b.name)) { let mesh = b.mesh(); - let key = (std::sync::Arc::as_ptr(&mesh) as usize, normal); - let index = match kept.remove(&key).filter(|(m, i)| std::sync::Arc::ptr_eq(m, &mesh) && i.normal() == n) { + let key = std::sync::Arc::as_ptr(&mesh) as usize; + let index = match kept.remove(&key).filter(|(m, _)| std::sync::Arc::ptr_eq(m, &mesh)) { Some((_, index)) => index, - None => std::sync::Arc::new(solidcraft_engine::view::SectionIndex::new(&mesh, n)), + None => std::sync::Arc::new(solidcraft_engine::view::SectionIndex::new(&mesh)), }; - let segments = index.segments(&mesh, o); + let segments = index.segments(&mesh, o, n); for (a, c) in &segments { sc.line(a.to_f32(), c.to_f32(), col, 1.8, false); } @@ -2034,22 +2037,39 @@ pub fn origin_planes(app: &SolveApp) -> Vec<(&'static str, Vec3, [Vec3; 4])> { .collect() } -/// The plane Create Sketch would put the sketch on, while it waits for one (#6975): the origin -/// or construction plane under the pointer, in the view or in the browser. The grid is drawn on -/// it, so the sketch's plane shows before the click. +/// The plane Create Sketch would put the sketch on: the origin or construction plane under the +/// pointer while it waits (#6975), or the plane selected in the view (#10804). The grid is drawn +/// on it, so the sketch's plane shows before the click. pub fn previewed_sketch_plane(app: &SolveApp) -> Option { - if app.session.active_sketch.is_some() || !app.picking_sketch_plane() { + if app.session.active_sketch.is_some() { return None; } - let name = match (&app.viewport.hover_plane, &app.viewport.hover) { - (Some(name), _) | (None, Some(Hit::Plane { name, .. })) => name, - _ => return None, - }; + if app.picking_sketch_plane() { + let name = match (&app.viewport.hover_plane, &app.viewport.hover) { + (Some(name), _) | (None, Some(Hit::Plane { name, .. })) => name, + _ => return selected_plane(app), + }; + return named_plane(app, name); + } + selected_plane(app) +} + +/// The plane selected in the view, when there is one: Create Sketch takes it, so the grid shows it. +fn selected_plane(app: &SolveApp) -> Option { + let name = app.session.selection.iter().find_map(|sel| match sel { + Sel::Plane { name } => Some(name.as_str()), + _ => None, + })?; + named_plane(app, name) +} + +/// Origin or construction plane `name`. +fn named_plane(app: &SolveApp, name: &str) -> Option { solidcraft_engine::view::construction_planes(&app.session) .into_iter() .find(|(_, n, _)| n == name) .map(|(_, _, p)| p) - .or_else(|| origin_planes(app).into_iter().find(|(n, _, _)| *n == name.as_str()).and_then(|(n, _, _)| Plane::named(n))) + .or_else(|| origin_planes(app).into_iter().find(|(n, _, _)| *n == name).and_then(|(n, _, _)| Plane::named(n))) } /// A point on origin plane `name`'s square that a click at its screen point picks: the middle, @@ -3223,7 +3243,9 @@ pub(crate) fn sketch_constraint_at(app: &SolveApp, pos: Pos2, hit: Option<&Hit>) pub fn candidate(app: &SolveApp, hits: &[Hit]) -> Option<(Hit, Sel)> { if let Some(d) = app.dialog.as_ref().filter(|d| d.wants_picks()) { let snap = d.face_snap(&app.session, hits); - return hits.iter().find_map(|h| d.candidate_on(&app.session, h, snap.as_ref()).map(|s| (h.clone(), s))); + return hits + .iter() + .find_map(|h| d.candidate_on(&app.session, h, snap.as_ref()).map(|s| (h.clone(), crate::dialogs_move::component_pick(app, h, s)))); } hits.iter().filter(|h| pick_allowed(app, h)).find_map(|h| hit_candidate(app, h)) } @@ -3234,7 +3256,10 @@ pub fn candidates(app: &SolveApp, hits: &[Hit]) -> Vec<(Hit, Sel)> { // The face under the cursor is looked up once for every sketch point a face place may // snap to, before Select Other caps its rows. let snap = d.face_snap(&app.session, hits); - return hits.iter().filter_map(|h| d.candidate_on(&app.session, h, snap.as_ref()).map(|s| (h.clone(), s))).collect(); + return hits + .iter() + .filter_map(|h| d.candidate_on(&app.session, h, snap.as_ref()).map(|s| (h.clone(), crate::dialogs_move::component_pick(app, h, s)))) + .collect(); } hits.iter().filter(|h| pick_allowed(app, h)).filter_map(|h| hit_candidate(app, h)).collect() } @@ -4545,11 +4570,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { analysis_colors: crate::gpu::analysis_colors(&t.analysis), access: crate::access::map(app), outline: matches!(app.ui.visual_style, 0 | 3), - ao_radius: if app.preferences.ambient_occlusion && app.ui.visual_style != 2 { - (model_bounds(app).diagonal() * 0.04).clamp(1e-4, 1e6) as f32 - } else { - 0.0 - }, + ao_radius: ao_radius(app), eye: { let e = proj.cam.eye().to_f32(); [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }] @@ -7458,6 +7479,9 @@ mod tests { s.execute("solid.box", &json!({"length": 300, "width": 300, "height": 4, "corner": [-150, -150, -4], "body_name": "plate"})).unwrap(); s.execute("solid.box", &json!({"length": 30, "width": 160, "height": 16, "corner": [0, -80, 0], "operation": "new", "body_name": "block"})) .unwrap(); + // On one side of the view only, too far from the block to shade the rows measured below. + s.execute("solid.box", &json!({"length": 20, "width": 20, "height": 16, "corner": [-110, 60, 0], "operation": "new", "body_name": "marker"})) + .unwrap(); let mut app = SolveApp::new(s, crate::Services::default()); let (yaw, pitch) = solidcraft_engine::render::StandardView::Top.angles(); app.cam = Camera { target: Vec3::new(-30.0, 0.0, 0.0), yaw, pitch, roll: 0.0, distance: 200.0, fov: 0.0, ..Default::default() }; @@ -7518,8 +7542,31 @@ mod tests { } // The shader takes the count it is given (the moving frame is a different picture), and // spreads it over the same hemisphere: both darken the contact alike. - assert_ne!(pictures[0], pictures[1], "8 samples draw another grain than 32"); + assert_ne!(pictures[0], pictures[1], "8 samples draw another picture than 32"); assert!((beside[0] - beside[1]).abs() < 0.02, "the same darkening beside the block at 32 and 8 samples: {beside:?}"); + // No grain (#9327): where the plate darkens, neighbouring pixels agree at either count. + let (from, to) = ((edge - reach) as usize, (edge - 4.0) as usize); + for picture in &pictures { + let grain = (y0..y1).flat_map(|y| (from..to).map(move |x| (lum(picture, x, y) - lum(picture, x + 1, y)).abs() / 3.0)).fold(0.0, f64::max); + eprintln!("grain {grain:.2}"); + assert!(grain <= 2.0, "neighbouring pixels differ by {grain:.2} of 255"); + } + for picture in &pictures { + // Blurred by depth: the block's top right beside the edge stays as clear as without AO. + for x in (edge + 1.0) as usize..=(edge + 3.0) as usize { + let y = (y0 + y1) / 2; + assert!((lum(picture, x, y) - lum(&off, x, y)).abs() <= 6.0, "the plate's shade crosses onto the block's top at {x}"); + } + // The map is read the right way up: the plate darkens beside the marker, not at its mirror image. + let shade = |p: Vec3| { + let (x, y, _) = at(p); + lum(picture, x as usize, y as usize) / lum(&off, x as usize, y as usize).max(1.0) + }; + let (beside, mirror) = (shade(Vec3::new(-100.0, 58.0, 0.0)), shade(Vec3::new(-100.0, -58.0, 0.0))); + assert!(beside < 0.99 && (mirror - 1.0).abs() < 0.004, "beside the marker {beside:.4}, at its mirror image {mirror:.4}"); + } + // Off, nothing is read from the released maps: the plate is as bright beside the block as away from it. + assert!((lum(&off, to, y0) - lum(&off, from, y0)).abs() <= 3.0, "AO off darkens nothing"); } /// Faded and see-through bodies are drawn from their plans where the renderer blends them @@ -11486,6 +11533,28 @@ mod tests { assert!(solidcraft_engine::view::section_segments(&m, Vec3::new(0.0, 99.0, 0.0), n).is_empty()); } + /// Tilting a section keeps each body's section index: one serves every normal, so a tilt + /// drag does not rebuild it every frame (#10373). + #[test] + fn tilting_the_section_keeps_its_index() { + let mut s = solidcraft_engine::Session::default(); + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); + let o = Vec3::new(0.0, 15.0, 0.0); + s.section = Some((o, Vec3::new(0.0, -1.0, 0.0))); + let mut app = SolveApp::new(s, crate::Services::default()); + let indexes = + |app: &SolveApp| app.viewport.section_index.lock().unwrap().values().map(|(_, i)| std::sync::Arc::as_ptr(i) as usize).collect::>(); + build_scene(&app); + let first = indexes(&app); + assert_eq!(first.len(), 1); + for k in 1..4 { + let a = (10.0 * k as f64).to_radians(); + app.session.section = Some((o, Vec3::new(0.0, -a.cos(), a.sin()))); + build_scene(&app); + assert_eq!(indexes(&app), first, "tilted {k}"); + } + } + #[test] fn selection_shows_where_the_model_hides_it() { let mut s = solidcraft_engine::Session::default(); @@ -12314,6 +12383,37 @@ mod grid_plane_tests { assert!(on(&app, 1), "the preview grid is drawn even with the grid off"); } + /// #10804: a plane selected in the view, before Create Sketch, is the plane it would use, so + /// the grid lies on it until it is deselected. + #[test] + fn a_selected_plane_previews_on_the_grid_before_create_sketch() { + let rect = Rect::from_min_size(Pos2::ZERO, egui::vec2(800.0, 600.0)); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.ui.show_grid = true; + app.preferences.grid_follows_view = false; + let on = |app: &SolveApp, axis: usize| { + let points: Vec<[f32; 3]> = build_sketch_scene(app, &projection(app, rect)) + .under + .as_chunks::<32>() + .0 + .iter() + .flat_map(|l| [&l[0..12], &l[12..24]]) + .map(|b| [0, 4, 8].map(|i| f32::from_le_bytes(b[i..i + 4].try_into().unwrap()))) + .collect(); + !points.is_empty() && points.iter().all(|p| p[axis].abs() < 1e-3) + }; + assert!(on(&app, 2), "the ground grid"); + // A plane under the pointer, with nothing selected, moves nothing. + app.viewport.hover = Some(Hit::Plane { name: "XZ".into(), point: Vec3::ZERO }); + assert!(on(&app, 2), "a hover alone moves nothing"); + // Select XZ: the grid lies on it before Create Sketch is clicked. + app.session.selection = vec![Sel::Plane { name: "XZ".into() }]; + assert!(on(&app, 1), "the selected plane shows on the grid"); + // Deselecting it returns the grid to the ground. + app.session.selection.clear(); + assert!(on(&app, 2), "deselecting returns the grid"); + } + /// The grid's centre is where the view's axis meets the ground, but at a grazing slant (a /// camera 10 mm above the ground, looking almost along it) no further than the grid's /// half-size from the point under the target, so the ground in front of the camera keeps diff --git a/crates/ui-egui/src/viewport_appearance_tests.rs b/crates/ui-egui/src/viewport_appearance_tests.rs index 3f3a3b8c3..0bab4c3e3 100644 --- a/crates/ui-egui/src/viewport_appearance_tests.rs +++ b/crates/ui-egui/src/viewport_appearance_tests.rs @@ -580,3 +580,25 @@ fn vertex_markers_follow_the_edges_display_mode() { assert!(front.iter().all(|(_, c)| Some(*c) == edge), "style {style}: markers in the edge colour"); } } + +/// The radius is 4% of what the frame draws (#9327): in an empty design a preview's box, not the +/// floor that left the depth map's precision to show as specks; nothing drawn, or AO off, is off. +#[test] +fn the_ambient_occlusion_radius_follows_what_is_drawn() { + use solidcraft_engine::geom::Aabb3; + + let mut app = SolveApp::new(Session::default(), Services::default()); + app.preferences.ambient_occlusion = true; + app.ui.visual_style = 0; + assert_eq!(super::ao_radius(&app), 0.0, "nothing to occlude"); + app.preview.bounds = Aabb3 { min: Vec3::ZERO, max: Vec3::new(30.0, 40.0, 0.0) }; + assert_eq!(super::ao_radius(&app), 2.0, "the preview's box, its diagonal 50"); + app.preview.bounds = Aabb3::EMPTY; + app.run("solid.box", json!({"length": 300, "width": 400, "height": 0.001})).unwrap(); + assert!((super::ao_radius(&app) - 20.0).abs() < 1e-3, "the body's box"); + app.ui.visual_style = 2; + assert_eq!(super::ao_radius(&app), 0.0, "wireframe"); + app.ui.visual_style = 0; + app.preferences.ambient_occlusion = false; + assert_eq!(super::ao_radius(&app), 0.0, "off"); +} diff --git a/crates/ui-egui/src/viewport_details.rs b/crates/ui-egui/src/viewport_details.rs index 80a091bdf..580d7e0a9 100644 --- a/crates/ui-egui/src/viewport_details.rs +++ b/crates/ui-egui/src/viewport_details.rs @@ -16,7 +16,7 @@ fn field(id: &str, label: &str, value: DetailValue) -> DetailSetting { DetailSetting { id: id.into(), label: tr(label), value, enabled: true } } fn length(app: &SolveApp, value: f64) -> DetailValue { - DetailValue::Length { value, units: app.session.doc.units.clone() } + DetailValue::Length { value, units: app.session.doc.units.clone(), decimals: app.preferences.length_decimals } } fn number(value: f64, min: f64, max: f64, suffix: &str) -> DetailValue { DetailValue::Number { value, min, max, suffix: suffix.into() } @@ -26,7 +26,13 @@ fn axis(value: [f64; 3]) -> DetailValue { let current = if axes.iter().any(|axis| *axis == value || axis.map(|v| -v) == value) { crate::viewport_status::direction(value) } else { - let [x, y, z] = value; + // Rounded as the card's other numbers are: a tilted normal reads (0.707, 0.707, 0). + let short = |v: f64| { + let s = format!("{v:.3}"); + let s = s.trim_end_matches('0').trim_end_matches('.'); + if s == "-0" { "0".to_string() } else { s.to_string() } + }; + let [x, y, z] = value.map(short); format!("({x}, {y}, {z})") }; DetailValue::Axis { value, current } diff --git a/crates/ui-egui/src/viewport_overlays_tests.rs b/crates/ui-egui/src/viewport_overlays_tests.rs index e3c05bd86..341d4b257 100644 --- a/crates/ui-egui/src/viewport_overlays_tests.rs +++ b/crates/ui-egui/src/viewport_overlays_tests.rs @@ -67,7 +67,8 @@ fn section_details_live_fields_reconstruct_arbitrary_plane_without_losing_compan assert!((original.1 + flipped.1).len() < 1e-9); h.app.session.doc_mut().units = "in".into(); let effect = h.app.session.status_items().remove(0); - let params = crate::viewport_details::edit_params(&h.app, &effect, "offset", &V::Length { value: -25.4, units: "in".into() }).unwrap(); + let params = + crate::viewport_details::edit_params(&h.app, &effect, "offset", &V::Length { value: -25.4, units: "in".into(), decimals: 2 }).unwrap(); assert_eq!(params["offset"], "-25.4 mm"); assert_eq!(params["hatch"], true); assert_eq!(params["flip"], !current_flip); @@ -121,7 +122,7 @@ fn details_record_scope_preserves_mixed_limits_and_stale_targets_never_move_came crate::viewport_details::dispatch(&mut h.app, &h.ctx, &owner, DetailEvent::Target(target)); assert_eq!(h.app.session.camera, before); let effect = h.app.session.status_items().remove(0); - assert!(crate::viewport_details::edit_params(&h.app, &effect, "gap", &V::Length { value: 1.0, units: "in".into() }).is_none()); + assert!(crate::viewport_details::edit_params(&h.app, &effect, "gap", &V::Length { value: 1.0, units: "in".into(), decimals: 2 }).is_none()); assert!(crate::viewport_details::description(&h.app, &effect).findings.iter().all(|row| !row.target)); } @@ -2792,3 +2793,29 @@ fn summary_preferences_cancel_restores_layout_independently_of_all_effect_polici assert_eq!(crate::scenario::rect_of("viewport_status:summary").is_some(), saved); } } + +#[test] +fn a_section_card_shows_every_row_and_reads_like_its_pill() { + // #10708: the card was cut off below Hatch (and Flip for a tilted plane), and showed + // "15.000000 mm" and a normal with 16 digits. + use crate::ui_kit::DetailValue as V; + for (plane, rows, normal) in [(json!("XZ"), 3, None), (json!({"origin":[20,15,10],"normal":[1,1,0]}), 3, Some("(0.707, 0.707, 0)"))] { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + h.app.run("inspect.section", json!({"plane":plane,"offset":15})).unwrap(); + h.frames(3); + let effect = h.app.session.status_items().remove(0); + let owner = crate::viewport_status::identity(&effect); + h.step(&json!({"click":{"handle":format!("viewport_status:{owner}:setting")}})).unwrap(); + h.frames(4); + let card = crate::scenario::rect_of("viewport_status:card").expect("the card"); + let fields: Vec<_> = ["offset", "flip", "hatch"].iter().filter_map(|f| crate::scenario::rect_of(&format!("details:field:{f}"))).collect(); + assert_eq!(fields.len(), rows); + assert!(fields.iter().all(|f| card.contains_rect(*f)), "{plane}: card {card:?}, rows {fields:?}"); + let description = crate::viewport_details::description(&h.app, &effect); + assert!(description.settings.iter().any(|s| matches!(&s.value, V::Length { decimals: 2, .. }))); + if let Some(normal) = normal { + assert!(description.settings.iter().any(|s| matches!(&s.value, V::Axis { current, .. } if current == normal)), "{plane}"); + } + } +} diff --git a/crates/ui-egui/tests/projection_preselection.rs b/crates/ui-egui/tests/projection_preselection.rs index c69b89090..12e03a95e 100644 --- a/crates/ui-egui/tests/projection_preselection.rs +++ b/crates/ui-egui/tests/projection_preselection.rs @@ -18,6 +18,47 @@ fn setup() -> (Harness, u64) { (h, source) } +/// #10291: a line of another sketch, picked while the Project dialog is open, projects. +/// The pick names the sketch it came from, so the dialog's geometry input holds it and the +/// command gets a reference to it, even when the two sketches lie in parallel planes. +#[test] +fn a_line_of_another_sketch_picked_in_the_project_dialog_projects() { + let mut h = Harness::new(); + // The options dialog is the workflow of the bug report: Project opens a dialog that + // takes the geometry to project. + h.app.preferences.project_options_dialog = true; + // Sketch 1 on plane 1. + let source = h.app.run("sketch.create", json!({"plane":"XY"})).unwrap()["sketch"].as_u64().unwrap(); + h.app.run("sketch.line", json!({"points":[[10,10],[30,10]],"infer":false})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + // Plane 2 parallel to plane 1, and sketch 2 on it. + h.app.run("construct.plane.offset", json!({"base":"XY","offset":10,"name":"Plane2"})).unwrap(); + h.app.run("sketch.create", json!({"plane":"Plane2"})).unwrap(); + h.call("ui.set", json!({"shownSketches":[source]})); + h.call("ui.view", json!({"view":"top"})); + // Project, then pick the line of sketch 1 in the viewport. + h.app.start("sketch.project"); + h.frames(4); + assert!(h.app.dialog.is_some(), "Project opens its options dialog"); + h.step(&json!({"click":{"world":[20,10,0]}})).unwrap(); + let d = h.app.dialog.as_ref().expect("the dialog is still open"); + assert_eq!(d.inputs[0].items.len(), 1, "the line of the other sketch is in the input: {:?}", d.inputs[0].items); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none(), "the dialog closes on a valid pick: {:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", h.app.status); + let sketch = h.app.session.active_sketch.expect("Project leaves the sketch active"); + let state = h.app.session.world_state().unwrap(); + let sk = &state.sketch(sketch).unwrap().sketch; + assert!(sk.curves.iter().any(|curve| curve.link.is_some()), "the line is projected into the sketch"); + // The projection names the sketch it came from, so it follows it. + assert!( + sk.links.iter().any(|l| matches!(&l.source, solidcraft_engine::sketch::LinkSource::SketchCurve { sketch, .. } if *sketch == source)), + "{:?}", + sk.links + ); +} + #[test] fn clicked_external_curve_and_point_project_with_source_identity_and_one_undo() { let (mut h, source) = setup(); diff --git a/crates/ui-egui/tests/ui_layout.rs b/crates/ui-egui/tests/ui_layout.rs index e5c196fac..5d549e644 100644 --- a/crates/ui-egui/tests/ui_layout.rs +++ b/crates/ui-egui/tests/ui_layout.rs @@ -20,6 +20,14 @@ fn harness() -> Harness { h } +/// These tests and the scenarios name English words, whatever the PC's language (#10297). +#[test] +fn the_harness_takes_english_as_the_system_language() { + let h = Harness::new(); + assert_eq!(h.app.preferences.language, solidcraft_ui_egui::i18n::SYSTEM); + assert_eq!(solidcraft_ui_egui::i18n::effective_language(&h.app.preferences.language), "en"); +} + #[test] fn every_dialog_opens_docked_within_its_width_limits() { let mut bad = Vec::new(); diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 5a3f31b1a..7d3717730 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -48,6 +48,11 @@ In the floating layout, Assistant fills the viewport height in the shared rounde space around its edges. The compass and navigation bar move into the remaining space beside it. It overlays the model without changing the viewport projection; clicks and scrolling over the panel stay in the chat. The docked layout retains its side panel. +After clicking in Assistant, keyboard input stays in the chat, including when selecting text +in an answer. Copy, Cut and Paste do not also operate on selected CAD geometry. Moving the +pointer back over the model does not change this: click outside Assistant to return the +keyboard to CAD. Closing or minimising the panel also releases it. + - **Docking:** on the left, Assistant is the first panel, before vertical history and the browser. The drag highlight shows the actual destination bounds. Drag the panel's header (the dotted grip and the title) to the other half of the window and let go. The side it would land on lights up while you drag. You can also pick @@ -167,7 +172,9 @@ messages go as one prompt, in order, when the turn ends normally. short note that the agent's previous step was interrupted. What the interrupted message changed undoes as one step, like any other message. - **Stop** (the square next to the input, or **Esc** in the input) stops the agent and keeps - the queue: the bubbles wait for **Send**. + the queue: the bubbles wait for **Send**. If an external ACP agent does not finish its cancelled + prompt within five seconds, SolidCraft disconnects it and stops its process in the background. + Completed design changes stay undoable, and the queue stays put. Reconnect to start a new agent session. - **New chat** (the header button, **Ctrl+Shift+L** / **Cmd+Shift+L** with the chat focused) stops what runs, clears the conversation, the queue and the files on the chips, and starts a fresh session on the same agent, keeping the agent and its mode. It asks first when a message @@ -414,9 +421,12 @@ per agent, with **Reset**. These settings cover SolidCraft's tools. A coding agent's own tools (its shell, its file edits) follow the agent's own mode, which you pick in the panel's header. When an agent asks before -using one of SolidCraft's tools, SolidCraft answers for you, since its own gate checks the call, -and notes it in the chat as *Auto-allowed*. With **Allow everything**, or after **Always allow**, -the agent's other questions are answered the same way and noted too. +using one of the chat's own SolidCraft tools and names it exactly as the Claude adapter does +(`mcp__solidcraft-app__batch`), SolidCraft answers for you, since its own gate checks the call, +and notes it in the chat as *Auto-allowed*. Any other question appears in the panel, including +a SolidCraft tool an agent words differently and a SolidCraft MCP server you added to the agent +yourself. With **Allow everything**, or after **Always allow**, those questions are answered the +same way and noted too. What counts as "a command given a file name": a parameter that holds a file or folder (`file`, `dir`, `output`, …), or `path` and `source` when the value reads like a file name (a separator, `~`, diff --git a/docs/ambient-occlusion.md b/docs/ambient-occlusion.md index 3bee560d0..a6838cc9e 100644 --- a/docs/ambient-occlusion.md +++ b/docs/ambient-occlusion.md @@ -33,12 +33,11 @@ only display preferences, without adding a modelling undo step or moving the cam The GPU viewport uses 32 hemisphere samples per shaded pixel against an opaque depth prepass (at most 2048 pixels on its longest side), the sample pattern turned by a different angle at each pixel. One pattern for every pixel drew faint shifted copies of -nearby parts (#4167) and stepped bands along contacts (#3407); turned, they become an -even fine grain, which 2× supersampling smooths further. While the view moves (orbit, pan, -zoom, resize), frames take 8 samples on the same turned pattern, and the full 32 follow once -the view has held still for 0.25 s, the settling time adaptive supersampling uses (#7165). -The AO grain changes when the full count arrives, as the edges do when adaptive supersampling -does. `ui.screenshot` waits for that full-quality frame (at most half a second). The radius follows +nearby parts (#4167) and stepped bands along contacts (#3407); turned, they become a grain, +which a 4 × 4 blur by depth takes out: the term has its own texture, worked out once for each +pixel of the prepass (#9327). While the view moves (orbit, pan, zoom, resize), frames take 8 +samples, and the full 32 follow once the view has held still for 0.25 s, the settling time +adaptive supersampling uses (#7165). `ui.screenshot` waits for that full-quality frame (at most half a second). The radius follows model size, and depth-range rejection avoids shadows from distant foreground objects. It supports orthographic and perspective cameras and respects section clipping. Wireframe, transparent bodies, overlays and surface-analysis colours are unaffected. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 78d8ac7b6..63bee380d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -79,7 +79,10 @@ launch and writes it, as one line of hex, to a file only the user can read: | Windows | `%LOCALAPPDATA%\SolidCraft\control\PORT.token` | On Unix the folder is `0700` and the file `0600`; on Windows the file's inherited permissions are -replaced by a single entry for the user. `SOLIDCRAFT_CONTROL_DIR` moves the folder. The file is +replaced by a single entry for the user. `SOLIDCRAFT_CONTROL_DIR` moves the folder. If Windows +doesn't finish restricting the file within five seconds, the default folder (private to the user) +keeps it, but a custom folder gets no token file, and clients then need +`SOLIDCRAFT_CONTROL_TOKEN`. The file is removed when the app exits, unless another launch has written its own token there since, and the next launch writes a new token. The token file's path is printed to stderr at start-up. Beside it, `.pid` holds the app's process id (and, on Linux, @@ -96,7 +99,9 @@ The first request on a connection must carry the token as a top-level `"token"` (`{"id": 1, "method": "ui.inspect", "params": {}, "token": "…"}`); later requests on the same connection may leave it out. A first line without the right token is answered with `{"ok": false, "error": "unauthorized: …"}` and the connection is closed, without running -anything. Tokens are compared in constant time. +anything. Tokens are compared in constant time. A connection that hasn't sent that first request +within five seconds is closed without a reply, and blank lines don't extend the time. So connect +when you have something to send; once authenticated, a connection may stay idle. `solidcraft-cli mcp --connect 127.0.0.1:PORT` reads the token file for that port by itself (`--token T` or `SOLIDCRAFT_CONTROL_TOKEN` give one explicitly). For a test harness, or a diff --git a/docs/features.md b/docs/features.md index e3512845f..019a02701 100644 --- a/docs/features.md +++ b/docs/features.md @@ -122,6 +122,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Control Point Spline (Degree 5) | `sketch.spline.control_point_5` | SKETCH › CREATE | | Fit Point Spline | `sketch.spline.fit_point` | SKETCH › CREATE | | Add Spline Point | `sketch.spline.insert_point` | – | +| Remove Spline Point | `sketch.spline.remove_point` | – | | Reverse Spline Direction | `sketch.spline.reverse` | – | | 3D Spline | `sketch.spline3d` | – | | Spun Profile | `sketch.spun_profile` | SKETCH › CREATE | @@ -730,6 +731,12 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Rename Settings Profile | `settings.profile.rename` | – | | Save Settings Profile | `settings.profile.save` | – | +## `ui.*` + +| Command | Id | Toolbar | +|---|---|---| +| Toggle Assistant (Ctrl+Shift+A) | `ui.assistant` | – | + ## `view.*` | Command | Id | Toolbar | diff --git a/docs/localization.md b/docs/localization.md index 2e71098df..a195be202 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -10,7 +10,8 @@ the app then matches the system's preferred locales — the OS locale on desktop `navigator.languages` in the browser, read with the `sys-locale` crate — against the registry: exact tag, then base language, then English (`match_system_tags` in `crates/ui-egui/src/i18n.rs`). A saved specific language always wins, so existing users keep -their choice. +their choice. In tests and scenarios the system's language is English, so they read the same +words on every PC. ## Messages diff --git a/packaging/linux/AppRun b/packaging/linux/AppRun index 9d27aeee7..36400a922 100755 --- a/packaging/linux/AppRun +++ b/packaging/linux/AppRun @@ -7,12 +7,14 @@ # An AppImage installs nothing, so every AppImage run would otherwise show the # generic "Wayland" icon. Best-effort desktop integration: on first run # (and whenever the AppImage's path changes) install the .desktop entry and the -# hicolor icons into $XDG_DATA_HOME, then launch. Every failure here must leave -# the launch untouched. Opt out with SOLIDCRAFT_NO_DESKTOP_INTEGRATION=1 (the pre-rename -# SOLVECRAFT_NO_DESKTOP_INTEGRATION still works: compatibility shim, docs/compatibility.md), -# or for good with an empty file $XDG_DATA_HOME/solidcraft/no-desktop-integration. Nothing is -# installed either when appimaged (go-appimage) already made an entry for this AppImage, or when -# a launcher that manages AppImages (Gear Lever, AppImageLauncher) started it: it sets +# hicolor icons into $XDG_DATA_HOME, refresh the icon cache, point Icon= at the +# installed PNG (panels that skip the theme cache still show the mark; #10673), +# then launch. Every failure here must leave the launch untouched. Opt out with +# SOLIDCRAFT_NO_DESKTOP_INTEGRATION=1 (the pre-rename SOLVECRAFT_NO_DESKTOP_INTEGRATION +# still works: compatibility shim, docs/compatibility.md), or for good with an empty +# file $XDG_DATA_HOME/solidcraft/no-desktop-integration. Nothing is installed either +# when appimaged (go-appimage) already made an entry for this AppImage, or when a +# launcher that manages AppImages (Gear Lever, AppImageLauncher) started it: it sets # DESKTOPINTEGRATION and owns the menu entry. # # The same step puts `solidcraft-cli` on PATH: a small wrapper script in ~/.local/bin that starts this @@ -98,12 +100,37 @@ integrate() { return 0 done - # Rewrite Exec to this AppImage (the binary is not on the host PATH) and drop - # TryExec, which would hide the entry; everything else is shipped as packaged. + # Icons first: the desktop entry's Icon= points at the installed 256×256 PNG so panels + # that skip the theme cache still show the mark (#10673: Mint Cinnamon AppImage taskbar). + src_icons="$APPDIR/usr/share/icons/hicolor" + icons="$data/icons/hicolor" + if [ -d "$src_icons" ]; then + (cd "$src_icons" && find . -type f) | while IFS= read -r rel; do + mkdir -p "$icons/$(dirname "$rel")" 2>/dev/null || continue + if ! cmp -s "$src_icons/$rel" "$icons/$rel"; then + cp "$src_icons/$rel" "$icons/$rel" 2>/dev/null || true + fi + done + if command -v gtk-update-icon-cache >/dev/null 2>&1; then + gtk-update-icon-cache -q -t -f "$icons" 2>/dev/null || true + elif command -v update-icon-caches >/dev/null 2>&1; then + update-icon-caches "$icons" 2>/dev/null || true + fi + fi + + # Rewrite Exec to this AppImage (the binary is not on the host PATH), drop TryExec + # (which would hide the entry), and point Icon at the installed PNG when we have one. mkdir -p "$apps" 2>/dev/null || return 0 tmp="$apps/.$DESK_ID.tmp.$$" esc="$(printf '%s' "$appimage" | sed 's/[\\&|]/\\&/g')" - if sed -e "s|^Exec=.*|Exec=\"$esc\" %F|" -e '/^TryExec=/d' "$src_desktop" 2>/dev/null >"$tmp"; then + icon_png="$icons/256x256/apps/$DESK_ID.png" + if [ -f "$icon_png" ]; then + icon_esc="$(printf '%s' "$icon_png" | sed 's/[\\&|]/\\&/g')" + icon_sed="s|^Icon=.*|Icon=$icon_esc|" + else + icon_sed='s|^Icon=.*|Icon='"$DESK_ID"'|' + fi + if sed -e "s|^Exec=.*|Exec=\"$esc\" %F|" -e '/^TryExec=/d' -e "$icon_sed" "$src_desktop" 2>/dev/null >"$tmp"; then if cmp -s "$tmp" "$apps/$DESK_ID.desktop"; then rm -f "$tmp" else @@ -127,17 +154,6 @@ integrate() { command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$apps" >/dev/null 2>&1 fi done - - # Icons: per-file compare so an unchanged install costs a handful of cmp calls. - src_icons="$APPDIR/usr/share/icons/hicolor" - [ -d "$src_icons" ] || return 0 - icons="$data/icons/hicolor" - (cd "$src_icons" && find . -type f) | while IFS= read -r rel; do - mkdir -p "$icons/$(dirname "$rel")" 2>/dev/null || continue - if ! cmp -s "$src_icons/$rel" "$icons/$rel"; then - cp "$src_icons/$rel" "$icons/$rel" 2>/dev/null || true - fi - done } # Started through the wrapper `integrate` installs: the command-line tool, with no integration. diff --git a/packaging/tests/apprun_test.py b/packaging/tests/apprun_test.py index 999936dc4..a7703f464 100644 --- a/packaging/tests/apprun_test.py +++ b/packaging/tests/apprun_test.py @@ -82,6 +82,21 @@ class AppRunCli(unittest.TestCase): self.run_apprun(SOLIDCRAFT_NO_DESKTOP_INTEGRATION="1") self.assertFalse(self.wrapper.exists()) + def test_desktop_entry_icon_is_an_absolute_png_path(self): + # Ship a hicolor mark so AppRun can copy it and point Icon= at the install (#10673). + src = self.appdir / "usr/share/icons/hicolor/256x256/apps" + src.mkdir(parents=True) + (src / "io.tangencylabs.solidcraft.png").write_bytes(b"\x89PNG\r\n\x1a\n") + (self.appdir / "usr/share/applications/io.tangencylabs.solidcraft.desktop").write_text( + "[Desktop Entry]\nExec=solidcraft\nIcon=io.tangencylabs.solidcraft\n" + ) + self.run_apprun() + desk = (self.home / ".local/share/applications/io.tangencylabs.solidcraft.desktop").read_text() + installed = self.home / ".local/share/icons/hicolor/256x256/apps/io.tangencylabs.solidcraft.png" + self.assertTrue(installed.is_file()) + self.assertIn(f"Icon={installed}", desk) + self.assertNotIn("Icon=io.tangencylabs.solidcraft\n", desk) + if __name__ == "__main__": unittest.main() diff --git a/skills/solidcraft-modeling/reference.md b/skills/solidcraft-modeling/reference.md index b2f877472..ce581d136 100644 --- a/skills/solidcraft-modeling/reference.md +++ b/skills/solidcraft-modeling/reference.md @@ -82,7 +82,7 @@ Distances are unsigned. Draw the geometry on the correct side first, and the dim | `solid.shell` | `faces:[[x,y,z]]`, `thickness` | A point on each face to remove, or its name from `body_topology`. Fillet first, except an edge of a removed face or a fillet between curved faces (see Order in `SKILL.md`). Bodies with lofted or swept faces are refused (`offset: only bodies with planes, cylinders, cones, spheres and tori`): hollow a loft with a smaller loft and `operation: cut`. | | `solid.hole` | `position:[x,y,z]` on a face (numbers or length expressions such as `["40", "width/2", "t"]`, which the hole then follows) + `diameter`, or `sketch` (+ `points`) | `clearance:"M3"`. `depth` defaults to through all. `type` is one of simple/drilled/counterbore/countersink. A `countersink` needs `cs_diameter` and `cs_angle`; a `counterbore` needs `cb_diameter` and `cb_depth`. `position` is a fixed point; to tie it to the part, add `references: [{edge:[x,y,z], distance}]` (up to two straight edges of the face): the centre then sits at those distances from the edges and follows them. | | `solid.pattern.rectangular` | `features`, `dir1`, `count1`, `spacing1` (+ `dir2`, `count2`, `spacing2`) | Spacing takes expressions and follows parameters. | -| `solid.pattern.circular` | `features`, `axis` (`"Z"`, `{origin, dir}`, or `{face: [x,y,z]}` / `{edge: [x,y,z]}` on a cylinder wall or circular edge, which the pattern follows), `count` | `angle` defaults to 360 deg. A full pattern keeps the COM on the axis, so check its radius with a top-view screenshot. | +| `solid.pattern.circular` | `features`, `axis` (`"Z"`, `{origin, dir}` whose origin may be length expressions the pattern follows, or `{face: [x,y,z]}` / `{edge: [x,y,z]}` on a cylinder wall or circular edge, which the pattern follows), `count` | `angle` defaults to 360 deg. A full pattern keeps the COM on the axis, so check its radius with a top-view screenshot. | | `solid.mirror` | `features:[names]` or `bodies:[names]`, `plane` (`XY`/`XZ`/`YZ`, a construction plane, or `{origin, normal}` whose origin may use length expressions) | Follows parameters. A mirror or pattern feature cannot be listed in `features` of another mirror or pattern, but `bodies` can mirror the body it made. The mirror is a new body with the first free default name: `Body1`, `Body2` from `features`, and `Side (2)`, `Side (3)` from `bodies:["Side"]`. Read the name from `created_bodies`. With `combine:true`, a mirror that overlaps the original joins it and makes no new body. `features` copies only the features listed, so a later cut is left out unless you list it too. `bodies` copies the finished body. To name the mirror, use `body.rename {"body":"Side (2)","name":"Side_L"}`. The new name stays when parameters change. | - **Names:** name every feature (`"name":"Standoff"`) and keep names unique across sketches and features. `timeline.roll_to {"feature":"Plate"}` picks the first match, which can be the sketch. diff --git a/skills/solidcraft-performance/SKILL.md b/skills/solidcraft-performance/SKILL.md index b6adae42f..742208da7 100644 --- a/skills/solidcraft-performance/SKILL.md +++ b/skills/solidcraft-performance/SKILL.md @@ -14,6 +14,7 @@ description: "Use when a SolidCraft change is slow, blocks the window, runs long ## Measure before you claim a speed-up - Profile first. Time with `solidcraft-cli` from `main` and from your branch, alternating runs, after the load is low. On a shared machine check `cut -d' ' -f1 /proc/loadavg` and wait while it is over 24; build with `nice`. - Report medians with the range, the machine, and the cases. The pattern to follow is `docs/perf.md`: what was slow, why, the result, and proof that nothing changed (same bodies, volumes, areas and triangle counts). +- A speed-up never skips work on a mesh's box: decide with the exact bounds (`Body::exact_bounds`, grown by the record's tolerance as `apart` in `crates/kernel/src/ops.rs` does). A mesh is for display, export, previews and mesh bodies. - Do not rewrite kernel code for speed: the kernel is being replaced, and kernel work is paused. Report a slow case with its file under the `kernel-perf` label (CONTRIBUTING.md, "Where help is wanted most"). - Pull requests run only the tests for what they touch; geometry-heavy tests run in the merge queue. Use `cargo xtask test` with the `ci` profile locally (`skills/solidcraft-tests/SKILL.md`). diff --git a/tests/kernel-cases/fillets/1213-round-end-circle-of-bent-tube/expected.json b/tests/kernel-cases/fillets/1213-round-end-circle-of-bent-tube/expected.json index 42964a014..50df020d3 100644 --- a/tests/kernel-cases/fillets/1213-round-end-circle-of-bent-tube/expected.json +++ b/tests/kernel-cases/fillets/1213-round-end-circle-of-bent-tube/expected.json @@ -3,13 +3,13 @@ "tangency-labs/solidcraft#1213", "tangency-labs/solidcraft#1291" ], - "what": "an R3 round on the end circle of a lofted tube whose axis bends (a 60 degree torus section)", + "what": "an R3 round on the end circle of a lofted tube whose axis bends 60 degrees", "source": "analytic", - "method": "five circles R20 square to a centre arc of radius 100 turning 60 degrees, lofted: the tube is a torus section, V = pi*20^2*100*(pi/3) = 131594.7. The R3 round on the start circle removes the spandrel (1-pi/4) r^2 revolved about the tube axis (the end circle is a plain circle in the plane x=0) at its centroid radius R - r (5/6-pi/4)/(1-pi/4) = 19.33 (Pappus): 234.58. V = 131360.1. The loft passes through only five sections, so the tolerance is relaxed to 5e-4.", + "method": "five circles R20 square to a centre arc of radius 100 turning 60 degrees, lofted. SolidCraft's loft is a cubic skin interpolating the five sections at chord-length parameters 0, 1/4, 1/2, 3/4, 1 (knots 0^4 1/2 1^4); every section's control points move rigidly with its plane, so the wall is S(u,v) = C(v) + 20 cos(u) z + 20 sin(u) Y(v), C and Y the cubic interpolants of the section origins and in-plane directions. |Y| is not 1 between the given circles, so those sections are ellipses and the body is not a torus (exact torus: pi*20^2*100*pi/3 = 131594.725). Its volume by the divergence theorem, Gauss quadrature on the wall and the end caps, converged: 131601.597487935. The R3 round on the start circle (the plane x=0) removes the region between the cap, the wall and the rolling ball's canal surface, the ball centre found for each u along the moving spine (touching the cap and the wall), by the divergence theorem, converged to 1e-12: 233.662461919. Pappus on the spandrel (1-pi/4) r^2 at its centroid radius overstates it (234.576949197, exact only for a straight tube; an exact torus gives 233.731514056). V = 131601.597487935 - 233.662461919 = 131367.935026. The value holds for the loft built this way only: a loft with other parameters or knots is another body.", "body_count": 1, - "volume_mm3": 131360.14839866068, + "volume_mm3": 131367.935026, "tolerance": { - "rel": 0.0005 + "rel": 1e-06 }, "continuity": { "order": "g1" diff --git a/tests/kernel-cases/fillets/4782-fillet-bar-edge-wider-than-both-faces/expected.json b/tests/kernel-cases/fillets/4782-fillet-bar-edge-wider-than-both-faces/expected.json index f73e58704..ac3364811 100644 --- a/tests/kernel-cases/fillets/4782-fillet-bar-edge-wider-than-both-faces/expected.json +++ b/tests/kernel-cases/fillets/4782-fillet-bar-edge-wider-than-both-faces/expected.json @@ -4,10 +4,13 @@ ], "what": "the long top edge of a 5x5 bar rounded r10, wider than both faces it rounds", "source": "analytic", - "method": "a convex round past its faces' far edges is built on the faces continued and its removal subtracted (smlib_fillet): the section keeps the bar's 5x5 square within the round's circle, centre (y,z) = (10,-5), radius 10: area 7.87866 (grid quadrature 4000^2); V = 80 area", + "method": "a convex round past its faces' far edges is built on the faces continued and its removal subtracted (smlib_fillet): the section keeps the bar's 5x5 square [0,5]x[0,5] (y,z) within the round's circle, centre (10,-5), radius 10. The circle crosses z=0 at y = 10-sqrt(75) and y=5 at z = sqrt(75)-5, and contains the corner (5,0), so with u = 10-y the area is integral from 5 to sqrt(75) of (sqrt(100-u^2) - 5) du = 50 (pi/3 - pi/6) - 5 (sqrt(75) - 5) = 25 pi/3 - 5 sqrt(75) + 25 = 7.8786686; V = 80 area = 2000 pi/3 - 400 sqrt(75) + 2000 = 630.2934873", "body_count": 1, - "volume_mm3": 630.293125, + "volume_mm3": 630.2934873, "continuity": { "order": "g1" + }, + "tolerance": { + "rel": 1e-06 } -} +} \ No newline at end of file diff --git a/tests/kernel-cases/fillets/KNOWN_FAILING b/tests/kernel-cases/fillets/KNOWN_FAILING index 1b1431351..841c116be 100644 --- a/tests/kernel-cases/fillets/KNOWN_FAILING +++ b/tests/kernel-cases/fillets/KNOWN_FAILING @@ -7,7 +7,7 @@ 1080-fillet-sloped-basin-1-mm-rim-r4-4-edges builds to the analytic volume (rel 3e-9), but the continuity check (g1 at every blend seam) takes in the mitre's creases, G0 by the mitre ruling: the case's continuity seams need the owner's word 2893-chamfer-distance-and-angle-past-the-wall-refused refused for another reason: SMLib SM_ERR_INVALID_INPUT, not a check saying the angle runs past the wall 2893-chamfer-two-distances-elliptical-rim SMLib status 1001: the two arcs of the rim take their chamfer offsets each at its own midpoint, where the faces' angle differs (78.5 and 101.5 deg), and their chamfers do not meet at the tangent corners (held for the owner's ruling on unequal chamfers of a varying angle) -4782-fillet-bar-edge-wider-than-both-faces SMLib status 1001: a convex round past both its faces is not yet built by subtraction +4782-fillet-bar-edge-wider-than-both-faces SMLib f916a8d builds the expected volume (630.2934869 against 630.2934873) but its continuity check finds no blend seams to grade ("Box: no null seams" against ">= g1 at every blend seam") 5158-fillet-round-just-past-a-10mm-face SMLib status 1001: the round passes 5e-6 under the box's top back edge, inside the body's tolerance (1e-5), and subtracting its removal region maps that edge to two of the region's faces (SmTopologyIntersector); 10.0001-10.04 open 851-fillet-arc-then-top-front SMLib status 1001: the top front edge's tangent chain (the edge, the arc round's end curve on the front face, the upright under it) rounded R2; along the end curve the R2 ball sits on the arc round's own centre circle, so that piece is the ball about (39.2538, -19, 8) touching front, top and wall (a torus of tube-centre radius 0), the three-edge rolling-ball corner; the same piece on a plane end arc builds (851-fillet-top-front-then-front-left-upright) 851-fillet-top-front-then-upright SMLib status 1001: the upright's tangent chain (the upright, the first round's end curve on the wall, the arc's top edge) rounded R2; along the end curve the R2 ball sits on the first round's axis, so that piece is the ball about (39.2538, -19, 8) touching front, top and wall (a torus of tube-centre radius 0), the three-edge rolling-ball corner; the upright alone builds, the upright with the end curve fails the same; the same piece on a plane end arc builds (851-fillet-top-front-then-front-left-upright) diff --git a/tests/kernel-cases/fillets/cov-fillet-section-curvature-boss-root-r2/expected.json b/tests/kernel-cases/fillets/cov-fillet-section-curvature-boss-root-r2/expected.json index 06733808a..f752858e7 100644 --- a/tests/kernel-cases/fillets/cov-fillet-section-curvature-boss-root-r2/expected.json +++ b/tests/kernel-cases/fillets/cov-fillet-section-curvature-boss-root-r2/expected.json @@ -11,6 +11,5 @@ }, "tolerance": { "rel": 1e-07 - }, - "timeout_s": 1800 + } } diff --git a/tests/kernel-cases/fillets/every-hole-top-rim-r1-curvature/expected.json b/tests/kernel-cases/fillets/every-hole-top-rim-r1-curvature/expected.json index a05967899..8f1712ccb 100644 --- a/tests/kernel-cases/fillets/every-hole-top-rim-r1-curvature/expected.json +++ b/tests/kernel-cases/fillets/every-hole-top-rim-r1-curvature/expected.json @@ -20,6 +20,5 @@ }, "continuity": { "order": "g2" - }, - "timeout_s": 600 + } } diff --git a/xtask/mesh-decisions.txt b/xtask/mesh-decisions.txt new file mode 100644 index 000000000..d38b0652f --- /dev/null +++ b/xtask/mesh-decisions.txt @@ -0,0 +1,193 @@ +# Functions that decide geometry with a mesh today, one a line: `: `. Sorted. `cargo xtask mesh-decisions` (xtask/src/mesh_decisions.rs) +# fails on a function that uses a mesh outside display, export, previews and mesh bodies and is +# not listed here, and on a listed one that no longer does: a fix removes its line in the same +# pull request. Never add a line: decide with exact geometry (`Body::exact_bounds`, +# `kernel::apart`, the B-rep's faces and edges). These are truck-era uses SMLib answers exactly. +crates/doc/src/appearance.rs:nearest_face picks the face nearest a point by the display mesh's triangles +crates/doc/src/config_styles.rs:Document::configuration_face_indices checks a configuration's named faces against the display mesh +crates/doc/src/construct.rs:GeoRef::name_picks names picked faces and edges through the display mesh +crates/doc/src/construct.rs:named_vertex finds where named edges meet through the display mesh +crates/doc/src/document.rs:MeshData::eq compares imported mesh payloads by their triangles +crates/doc/src/eval.rs:apply_traced_with passes over targets clear of a cut by mesh boxes +crates/doc/src/eval.rs:blend_edges_on finds a blend's edges on the display mesh +crates/doc/src/eval.rs:body_at picks the body whose surface is nearest a point by the display mesh +crates/doc/src/eval.rs:cut_end_past_face finds the gap past a face a cut ends in by the display mesh +crates/doc/src/eval.rs:edge_refs turns edge picks into references through the display mesh +crates/doc/src/eval.rs:eval_feature places features by the display mesh (faces, edges, nearness) +crates/doc/src/eval.rs:face_plane finds a sketch's face plane again on a mesh +crates/doc/src/eval.rs:face_samples takes a point on each face from its mesh triangles +crates/doc/src/eval.rs:faces_through finds the faces near a point and their normals by the display mesh +crates/doc/src/eval.rs:feature_tools_with_constructor reaches a To Object extent by the display mesh +crates/doc/src/eval.rs:height_at measures a point's height on a face by the display mesh +crates/doc/src/eval.rs:hole_axis_size sizes a hole's tools by the bodies its axis meets on the display mesh +crates/doc/src/eval.rs:hole_depth_to works out a hole's To Object depth on the display mesh +crates/doc/src/eval.rs:hole_misses decides a hole misses bodies by their mesh boxes +crates/doc/src/eval.rs:hole_on_surface moves a hole back onto its face by the display mesh +crates/doc/src/eval.rs:hole_reaches decides whether a drill reaches material by the display mesh +crates/doc/src/eval.rs:nearest_object_face picks an extrusion's To Object face by the display mesh +crates/doc/src/eval.rs:off_the_ends moves an edge point off the edge's ends by the display mesh +crates/doc/src/eval.rs:parallel_tapped_wall finds a tapped hole's parallel wall on the display mesh +crates/doc/src/eval.rs:resolve_edges finds edge references again on a mesh +crates/doc/src/eval.rs:tangent_face_chain grows a face pick across tangent edges on the display mesh +crates/doc/src/eval.rs:through_all_distance sizes a Through All extent by the display mesh +crates/doc/src/eval.rs:trim_to_body keeps the tool pieces touching the start by a mesh +crates/doc/src/eval.rs:unrecorded_touches finds touching pieces by a mesh +crates/doc/src/eval_more.rs:FaceSlice::outline finds the wall an outline runs along by mesh triangles +crates/doc/src/eval_more.rs:FaceSlice::recesses finds a plate's recesses by mesh triangles +crates/doc/src/eval_more.rs:beyond_cylinder_reach skips bodies far from a tap marking by their mesh boxes +crates/doc/src/eval_more.rs:body_box boxes a body by a mesh of it +crates/doc/src/eval_more.rs:body_under picks the body under a plastic feature's point by the display mesh +crates/doc/src/eval_more.rs:mesh_box boxes a model body by its display mesh +crates/doc/src/eval_more.rs:on_sheet_material decides whether a point touches a sheet by the display mesh +crates/doc/src/eval_more.rs:planar_normal_at finds the planar face through a point by a mesh +crates/doc/src/eval_more.rs:plastic_eval places plastic features by a mesh +crates/doc/src/eval_more.rs:rib_tool runs a rib to the body by the display mesh +crates/doc/src/eval_more.rs:rib_tool_normal runs a rib to the body by the display mesh +crates/doc/src/eval_more.rs:sheet_eval places sheet-metal features by a mesh +crates/doc/src/history_names.rs:OperandNames::edge names an operand's edge by the display mesh +crates/doc/src/hole_reference.rs:on_reference_face decides whether a point lies on a hole's reference face by the display mesh +crates/doc/src/hole_reference.rs:reference_frame finds a hole's reference edges on the display mesh +crates/doc/src/joints.rs:nearest_plane picks a joint's planar face by the display mesh +crates/doc/src/joints_cam.rs:default_reverse picks a cam follower's side by the display mesh +crates/doc/src/joints_cam.rs:profile_points samples a cam profile's edges from a mesh +crates/doc/src/joints_edge.rs:edge_frame places an edge snap by the display mesh +crates/doc/src/joints_edge.rs:edge_snap places an edge snap by the display mesh +crates/doc/src/joints_edge.rs:face_of picks the planar face beside an edge by the display mesh +crates/doc/src/joints_edge.rs:nearest_edge picks the edge nearest a point by the display mesh +crates/doc/src/joints_face.rs:NamedFace::own_cylinder reads a named face's cylinder from the display mesh +crates/doc/src/joints_face.rs:NamedFace::plane reads a named face's centre and normal from the display mesh +crates/doc/src/joints_face.rs:face_name_at names the face at a pick by its mesh triangles +crates/doc/src/joints_face.rs:outline_centre finds a planar face's centre from mesh triangles +crates/doc/src/joints_face.rs:rim_neighbour finds the face across a cylinder's rim by the display mesh +crates/doc/src/joints_face.rs:round_end_at finds a cylinder's round end by the display mesh +crates/doc/src/lineage.rs:order_legacy_family orders a face family by the display mesh +crates/doc/src/name_lookup.rs:FaceHit::along meets a line with a found face on the display mesh +crates/doc/src/name_lookup.rs:FaceHit::pick_point finds a point that picks a face again on the display mesh +crates/doc/src/name_lookup.rs:face_triangles reads a face's mesh triangles for name lookup +crates/doc/src/name_lookup.rs:locate_edge finds a named edge on the display mesh +crates/doc/src/name_lookup.rs:locate_in finds a named face among bodies by the display mesh +crates/doc/src/name_lookup.rs:nearest_on_face finds the nearest point of a face on its mesh triangles +crates/doc/src/name_lookup.rs:sheet_locate finds a sheet face by its name on the display mesh +crates/doc/src/naming.rs:FaceIndex::new indexes faces by mesh triangles for naming +crates/doc/src/naming.rs:blend_seams finds blend seams on the display mesh +crates/doc/src/naming.rs:carried_face_names carries face names to imported bodies by the display mesh +crates/doc/src/naming.rs:edge_names_at names the edges nearest points by the display mesh +crates/doc/src/naming.rs:edge_names_from names edges from their faces by the display mesh +crates/doc/src/naming.rs:face_centres takes face centres from mesh triangles +crates/doc/src/naming.rs:face_count counts faces by the display mesh +crates/doc/src/naming.rs:face_name_at_body names a face at a point by the display mesh +crates/doc/src/naming.rs:face_names_at names the faces holding points by the display mesh +crates/doc/src/naming.rs:face_spot finds where a face is by the display mesh +crates/doc/src/naming.rs:face_spots finds where faces are by the display mesh +crates/doc/src/naming.rs:geometric_names names faces from sample points on the display mesh +crates/doc/src/naming.rs:mesh_adjacency finds neighbouring faces from mesh edges +crates/doc/src/naming.rs:normals takes face normals from mesh triangles +crates/doc/src/naming.rs:roomiest takes a sample point per face from mesh triangles +crates/doc/src/naming.rs:samples_up_to takes sample points per face from mesh triangles +crates/doc/src/placement_reuse.rs:same_feature compares imported mesh payloads by their triangles +crates/doc/src/print_face.rs:Document::locate_print_face finds a print face by the display mesh +crates/doc/src/project.rs:body_mesh finds a projection's body nearest a point by the display mesh +crates/doc/src/project.rs:cache_key keys projections by the display mesh +crates/doc/src/project.rs:exact_edges finds the picked edges by the display mesh +crates/doc/src/project.rs:first_hits picks the projected curves met first by the display mesh +crates/doc/src/project.rs:nearest_face picks the nearest face by mesh triangles +crates/doc/src/project.rs:resolve_face_indices projects faces through the display mesh +crates/doc/src/project.rs:resolve_named_edge moves a link's point onto a named edge by the display mesh +crates/doc/src/project.rs:resolve_named_face finds a named face for a projection by the display mesh +crates/doc/src/project.rs:resolve_uncached resolves a projection's references by the display mesh +crates/doc/src/project.rs:section_segments sections a body by crossing its mesh triangles +crates/doc/src/project.rs:silhouette projects a body's outline from its mesh triangles +crates/doc/src/project3d.rs:iso_curve cuts an isocurve from mesh triangles +crates/doc/src/project3d.rs:part_of finds a reference's face nearest its point by the display mesh +crates/doc/src/project3d.rs:spun_outline spins a body's outline from mesh triangles +crates/doc/src/project3d.rs:tris reads mesh triangles for 3D projections +crates/doc/src/sheet_convert.rs:behind finds the face behind a planar face by mesh triangles +crates/doc/src/sheet_convert.rs:bend_edge_names names bend edges by the display mesh +crates/doc/src/sheet_convert.rs:convert_body converts a body to sheet metal by the display mesh +crates/doc/src/sheet_face_names.rs:body_sheet_face_names names sheet faces by the display mesh +crates/engine/src/cmd/clearance.rs:clearance measures clearances between B-rep bodies on display meshes +crates/engine/src/cmd/clearance.rs:measure_pair measures a pair's overlap or distance on display meshes +crates/engine/src/cmd/compare.rs:compare_bodies compares two B-rep bodies by meshes +crates/engine/src/cmd/compare.rs:enclosed_volume measures a B-rep body's volume from mesh triangles +crates/engine/src/cmd/component_clone.rs:build places pasted bodies by meshes +crates/engine/src/cmd/component_clone.rs:mesh_distance compares pasted bodies by mesh triangles +crates/engine/src/cmd/component_properties.rs:measure_placed measures a placed component by its display mesh +crates/engine/src/cmd/contact_sweep.rs:ContactGeometry::gap measures gaps by mesh triangles +crates/engine/src/cmd/contact_sweep.rs:ContactGeometry::gaps measures gaps by mesh triangles +crates/engine/src/cmd/contact_sweep.rs:ContactGeometry::hits finds bodies passing through each other by mesh triangles +crates/engine/src/cmd/contact_sweep.rs:ContactGeometry::placed places meshes for contact checks +crates/engine/src/cmd/contact_sweep.rs:contact_mesh tessellates bodies for contact checks +crates/engine/src/cmd/edit.rs:selection_item keeps a selection's face or edge index through the display mesh +crates/engine/src/cmd/face.rs:face_at_state picks the face at a point by the display mesh +crates/engine/src/cmd/face.rs:face_is_planar decides whether a face is planar by mesh triangles +crates/engine/src/cmd/face.rs:face_normal_in takes a planar face's normal from mesh triangles +crates/engine/src/cmd/face.rs:face_normal_world takes a planar face's normal from mesh triangles +crates/engine/src/cmd/face.rs:in_a_planar_face_outline decides whether a point lies in a planar face by mesh triangles +crates/engine/src/cmd/face.rs:on_a_face decides whether a point lies on a face by the display mesh +crates/engine/src/cmd/face.rs:sketch_of_face finds the planar face a sketch starts on by mesh triangles +crates/engine/src/cmd/face.rs:sketch_of_faces groups coplanar picked faces by mesh triangles +crates/engine/src/cmd/features.rs:auto_operation_in chooses a feature's operation by probing the display mesh +crates/engine/src/cmd/features.rs:edge_points turns edge references into points on a mesh +crates/engine/src/cmd/features.rs:through_all_reach sizes a Through All reach by the display mesh +crates/engine/src/cmd/features_more.rs:emboss places an emboss by the display mesh +crates/engine/src/cmd/features_more.rs:snap_point snaps a feature's point by the display mesh +crates/engine/src/cmd/inspect.rs:dist_to measures a distance on the display mesh +crates/engine/src/cmd/interference.rs:face_points takes a point per face from mesh triangles +crates/engine/src/cmd/interference.rs:interference finds interference between B-rep bodies by display meshes +crates/engine/src/cmd/interference.rs:meshes_apart decides two bodies are apart by mesh triangles +crates/engine/src/cmd/join_pieces.rs:adds_nothing decides a join adds no material by display mesh volumes +crates/engine/src/cmd/join_pieces.rs:mesh_volume measures the volume a closed mesh encloses +crates/engine/src/cmd/joints.rs:body_centre centres an occurrence by the display mesh's box +crates/engine/src/cmd/joints.rs:cam_profile samples a cam's picked edges from the display mesh +crates/engine/src/cmd/joints.rs:occurrence_at picks the occurrence nearest a point by the display mesh +crates/engine/src/cmd/measure_sel.rs:closest measures closest points on mesh triangles +crates/engine/src/cmd/measure_sel.rs:describe measures a selection on the display mesh +crates/engine/src/cmd/measure_sel.rs:face_slot finds a slot from mesh triangles +crates/engine/src/cmd/measure_sel.rs:face_tris reads a face's mesh triangles for measuring +crates/engine/src/cmd/measure_sel.rs:resolve_pick resolves a face or edge pick by the display mesh +crates/engine/src/cmd/motion.rs:centres centres occurrences by meshes +crates/engine/src/cmd/motion.rs:overlap measures how deep bodies overlap by meshes +crates/engine/src/cmd/motion.rs:tris reads mesh triangles for motion contact +crates/engine/src/cmd/motion_analysis.rs:shared_volume measures the volume parts share by the display mesh +crates/engine/src/cmd/sketch.rs:face_contains decides whether a face contains a point by mesh triangles +crates/engine/src/cmd/sketch.rs:face_triangles groups mesh triangles by face for sketch picks +crates/engine/src/cmd/sketch_face.rs:capture_impl captures a face for a sketch by a mesh +crates/engine/src/cmd/sketch_inspect.rs:face_at picks the face at a point by the nearest mesh triangle +crates/engine/src/cmd/sketch_inspect.rs:face_min_radius measures a face's least radius from mesh normals +crates/engine/src/cmd/sketch_inspect.rs:minimum_radius measures a face's least radius by the display mesh +crates/engine/src/frames.rs:frame_at picks the body a point lies on by the display mesh +crates/kernel/src/blend_smlib.rs:imp::corner_vertices finds the vertices nearest points by a mesh +crates/kernel/src/blend_smlib.rs:imp::reblend finds a blend's new edges by a mesh +crates/kernel/src/blend_smlib.rs:imp::resolve resolves edge picks for SMLib by a mesh +crates/kernel/src/body.rs:Body::edges gives edge points and lengths from a mesh +crates/kernel/src/body.rs:Body::faces gives face areas and centroids from a mesh +crates/kernel/src/body.rs:Body::meets decides whether bodies meet by meshes +crates/kernel/src/body.rs:Body::meets_each decides whether tools meet a body by meshes +crates/kernel/src/body.rs:Body::volume_at measures a B-rep body's volume from a mesh +crates/kernel/src/distance.rs:DistanceShape::on_face decides whether a point lies on a face by its mesh +crates/kernel/src/helix.rs:sweep_helix_mesh models a thread as a triangle mesh for faceted booleans +crates/kernel/src/intersection.rs:meeting_edges samples meeting edges from a mesh +crates/kernel/src/lip.rs:face_at picks the planar face at a point by a mesh +crates/kernel/src/measure.rs:measure counts a B-rep body's merged topology on a mesh +crates/kernel/src/offset_backend.rs:face_points takes a point per face from mesh triangles +crates/kernel/src/offset_backend.rs:faces_under picks the face under each point by the nearest mesh triangle +crates/kernel/src/offset_backend.rs:with_offsets tags offset faces by a mesh +crates/kernel/src/polyhedron.rs:offset_faces picks the faces to offset by a mesh +crates/kernel/src/provenance.rs:blend_origins traces blend faces by meshes +crates/kernel/src/provenance.rs:extrude_origins traces extrusion faces by meshes +crates/kernel/src/provenance.rs:face_tris reads face triangles for provenance +crates/kernel/src/provenance.rs:offset_origins traces offset faces by meshes +crates/kernel/src/provenance.rs:revolve_origins traces revolution faces by meshes +crates/kernel/src/provenance.rs:swept_origins traces swept faces by meshes +crates/kernel/src/provenance.rs:trace traces a result's faces to its operands by meshes +crates/kernel/src/shell_groups.rs:meshes_meet decides whether bodies meet by mesh triangles +crates/kernel/src/smlib_sweeps.rs:imp::roles gives swept faces their roles by a mesh +crates/kernel/src/surface_trim.rs:cut_by trims a surface by a tool through a mesh +crates/kernel/src/surface_trim.rs:nearest_faces picks the face nearest each point by a mesh +crates/kernel/src/surface_untrim.rs:face_point takes a point inside a face from its largest mesh triangle +crates/kernel/src/surfaces.rs:nearest_face picks the face nearest a point by mesh triangles +crates/kernel/src/topo.rs:cylinder_end_at finds a cylinder's end circle by a mesh +crates/kernel/src/topo.rs:cylinder_extent measures a cylindrical face's extent and side from mesh normals +crates/kernel/src/topo.rs:cylinder_face_at finds the cylindrical face at a point by a mesh +crates/kernel/src/topo.rs:merged_topology counts merged topology from a mesh diff --git a/xtask/src/main.rs b/xtask/src/main.rs index efca38e39..6e83b8d7c 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -16,6 +16,7 @@ mod known_failing; mod layers; mod licences; mod lists; +mod mesh_decisions; mod pending; mod render_assets; mod skills; @@ -110,6 +111,10 @@ commands: skills check that AGENTS.md and skills/*/SKILL.md cite files, `cargo xtask` commands and skills that exist, that the router table lists exactly the skills there are, and that AGENTS.md and new skills stay short + mesh-decisions check that model decisions in crates/doc, crates/engine and crates/kernel use exact + geometry: fails on a function outside display, export, previews and mesh bodies + that uses a mesh and xtask/mesh-decisions.txt does not list, and on a listed one + that no longer does (the list only shrinks) test [CARGO ARGS] [-- TEST ARGS] build the tests with the ci profile, then run every test binary at once (and the doc tests alongside); SOLIDCRAFT_TEST_JOBS=N bounds concurrent test @@ -124,7 +129,8 @@ commands: web-offline-test [--site DIR] check in headless Chrome that the web app works offline and updates to a new build (a stand-in app, or the web build in DIR such as dist/web) - ci fmt --check, assets, icons, licences --check, lists, skills, layers, ui-containers, clippy -D warnings, then the tests + ci fmt --check, assets, icons, licences --check, lists, skills, layers, ui-containers, + mesh-decisions, clippy -D warnings, then the tests with the wasm check alongside, then web-offline-test when Chrome is installed (stops at the first failing step) "; @@ -152,6 +158,7 @@ fn main() -> ExitCode { Some("licences") => licences::run(&root(), rest.contains(&"--check")), Some("fold-pending") => pending::run(&root()), Some("skills") => skills::run(&root()), + Some("mesh-decisions") => mesh_decisions::run(&root()), Some("lists") => lists::run(&root(), rest.contains(&"--fix")), Some("test") => { let (cargo_args, test_args) = rest.iter().position(|a| *a == "--").map_or((&rest[..], &[][..]), |i| (&rest[..i], &rest[i + 1..])); @@ -442,6 +449,7 @@ fn cmd_ci() -> Result<(), String> { skills::run(&root())?; cmd_layers()?; ui_containers::run(&root())?; + mesh_decisions::run(&root())?; let mut c = cargo(); c.args(["clippy", "--workspace", "--all-targets", "--profile", "ci", "--", "-D", "warnings"]); run(c, "cargo clippy -D warnings")?; diff --git a/xtask/src/mesh_decisions.rs b/xtask/src/mesh_decisions.rs new file mode 100644 index 000000000..64fa82c4d --- /dev/null +++ b/xtask/src/mesh_decisions.rs @@ -0,0 +1,518 @@ +//! `cargo xtask mesh-decisions`: model decisions use exact geometry. What an operation does, +//! which bodies it touches, which face or edge a point or a name refers to, depths and nearness +//! are worked out from the exact B-rep (SMLib: `Body::exact_bounds`, `apart` in +//! `crates/kernel/src/ops.rs`, point classification, projection). A mesh, a body's display +//! tessellation or an imported mesh body, is for display, export, picking previews and measuring +//! mesh bodies. +//! +//! The check reads the non-test Rust of the model crates ([`CRATES`]), following each crate's +//! module tree from its `lib.rs` (a `#[cfg(test)]` module, function or impl is left out), and +//! finds the functions that use a mesh ([`site_uses`] names the patterns). The modules and the +//! functions whose job is display, export, previews or mesh bodies are skipped +//! ([`SKIPPED_MODULES`], [`SKIPPED_FUNCTIONS`], each with its reason). +//! Every other function that uses a mesh is a decision site. The sites there are today are +//! listed in [`LIST`], one a line, `: `, sorted +//! (the kernel rig's known-failing format). The list only shrinks: the check fails on a site the +//! list does not name, and on a listed site that no longer uses a mesh (its fix removes its +//! line), as `tests/KNOWN_FAILING_TESTS` and `schema/unconverted.txt` do. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use syn::visit::{self, Visit}; + +pub const LIST: &str = "xtask/mesh-decisions.txt"; + +/// The crates whose code decides geometry: the document, the engine and the kernel. +pub const CRATES: &[&str] = &["crates/doc", "crates/engine", "crates/kernel"]; + +/// The crates where `ModelBody::mesh()` (no argument) is a display mesh. In the kernel, the +/// one argument-less `mesh()` is a T-spline's control net (`geom::tspline::TSpline::mesh`), +/// which is exact geometry, and `ModelBody` does not exist there. +const MODEL_BODY_CRATES: &[&str] = &["crates/doc", "crates/engine"]; + +/// Modules (a file, or a directory with everything below it) whose job is display, export, +/// previews or mesh bodies: their mesh use is what a mesh is for. +pub const SKIPPED_MODULES: &[(&str, &str)] = &[ + ("crates/doc/src/display_quality.rs", "the viewport's display quality levels"), + ("crates/doc/src/placed_mesh.rs", "the display meshes and plans of bodies and placed parts"), + ("crates/engine/src/cmd/file_thumbnail.rs", "a design's thumbnail picture"), + ("crates/engine/src/cmd/mesh.rs", "mesh bodies: repair, decimate and inspect imported meshes"), + ("crates/engine/src/cmd/render", "rendered pictures"), + ("crates/engine/src/cmd/render.rs", "rendered pictures"), + ("crates/engine/src/cmd/silhouette.rs", "a picture's view-aligned silhouette of the display meshes"), + ("crates/engine/src/cmd/surface_analysis.rs", "view analyses: zebra, draft and curvature shading of the display mesh"), + ("crates/engine/src/cmd/view_dxf_meshes.rs", "a drawing's view lines from display meshes"), + ("crates/engine/src/cmd/view_dxf_scene.rs", "a drawing's hidden-line occlusion over display meshes"), + ("crates/engine/src/cosmetic_threads.rs", "cosmetic thread hatching drawn on the displayed triangles"), + ("crates/engine/src/fuzz.rs", "the fuzz harness, which frames what it built"), + ("crates/engine/src/product_scene.rs", "the scene a rendered picture draws"), + ("crates/engine/src/render_jobs.rs", "rendered pictures"), + ("crates/engine/src/slicer_files.rs", "the mesh export a 3D-printing slicer opens"), + ("crates/engine/src/snap.rs", "the pointer's snap preview over the display mesh"), + ("crates/engine/src/view.rs", "the viewport's meshes, edges and highlights"), + ("crates/kernel/src/mesh_convert.rs", "mesh bodies: turning a mesh body into a solid"), + ("crates/kernel/src/meshbody.rs", "mesh bodies"), + ("crates/kernel/src/native/preview.rs", "a feature's preview mesh"), + ("crates/kernel/src/polybool.rs", "mesh bodies: booleans of a body with a closed triangle mesh"), + ("crates/kernel/src/tess", "the mesher: a body's display tessellation"), +]; + +/// Functions, in modules that also decide geometry, whose job is the display mesh itself, a +/// preview, or a mesh body. +pub const SKIPPED_FUNCTIONS: &[(&str, &str)] = &[ + ("crates/doc/src/eval.rs:ModelBody::display_plan", "the display plan"), + ("crates/doc/src/eval.rs:ModelBody::mesh", "the display mesh"), + ("crates/doc/src/eval.rs:ModelBody::mesh_in_place", "the display mesh where the body stands"), + ("crates/doc/src/eval.rs:ModelBody::plan_mesh", "the display plan's mesh"), + ("crates/doc/src/eval.rs:ModelBody::plan_mesh_at", "the display plan's mesh"), + ("crates/doc/src/eval.rs:ModelBody::plan_mesh_in_place_at", "the display plan's mesh where the body stands"), + ("crates/doc/src/eval.rs:ModelBody::plan_mesh_soon", "the display plan's mesh, made ahead"), + ("crates/doc/src/eval.rs:ModelBody::refined_display", "the display plan at a finer quality"), + ("crates/doc/src/eval.rs:ModelState::warm_display", "display meshes made ahead"), + ("crates/doc/src/eval.rs:ModelState::warm_display_at", "display meshes made ahead"), + ("crates/doc/src/eval.rs:ModelState::warm_meshes", "display meshes made ahead"), + ("crates/doc/src/eval.rs:mesh_bodies", "mesh bodies: a mesh import's triangles"), + ("crates/engine/src/cmd/file.rs:saved_preview", "the preview picture saved in a design"), + ("crates/kernel/src/body.rs:Body::classify_point", "mesh bodies: its mesh-body branch (a B-rep is classified by SMLib)"), + ("crates/kernel/src/body.rs:Body::mesh_untimed", "the mesher: a body's tessellation"), + ("crates/kernel/src/body.rs:Body::retained_bytes", "the evaluation cache's memory estimate"), + ("crates/kernel/src/body.rs:Body::unmeshed_faces", "the mesher's report of faces it left out"), +]; + +/// What a function does with a mesh, the patterns the check matches: +/// - `.mesh(t)` (one argument): `kernel::Body::mesh`, a body's tessellation; +/// - `.mesh()` (none), in [`MODEL_BODY_CRATES`]: `ModelBody::mesh`, its display mesh; +/// - `.mesh_plan(t)`, `.mesh_of(plan)`: the tessellation plan and the mesh it evaluates to; +/// - `.plan_mesh()`, `.plan_mesh_at(q)`, `.display_plan()`, `.display_plan_at(q)`: the display +/// plan and its mesh; +/// - `mesh_box(..)`, `body_box(..)`, `reference_mesh(..)`: a box or mesh from a tessellation; +/// - `.triangles`: reading a mesh's triangles (nearest point, ray casts, inside tests); +/// - `closest_on_triangle(..)`: the nearest point of a triangle. +fn site_uses(call: &Call, model_body: bool) -> Option<&'static str> { + match (call, call.name()) { + (Call::Method { args: 1, .. }, "mesh") => Some(".mesh(t)"), + (Call::Method { args: 0, .. }, "mesh") if model_body => Some(".mesh()"), + (Call::Method { .. }, "mesh_plan") => Some(".mesh_plan()"), + (Call::Method { .. }, "mesh_of") => Some(".mesh_of()"), + (Call::Method { .. }, "plan_mesh" | "plan_mesh_at") => Some(".plan_mesh()"), + (Call::Method { .. }, "display_plan" | "display_plan_at") => Some(".display_plan()"), + (Call::Function { .. }, "mesh_box") => Some("mesh_box()"), + (Call::Function { .. }, "body_box") => Some("body_box()"), + (Call::Function { .. }, "reference_mesh") => Some("reference_mesh()"), + (Call::Function { .. }, "closest_on_triangle") => Some("closest_on_triangle()"), + (Call::Field { .. }, "triangles") => Some(".triangles"), + _ => None, + } +} + +/// A use in the source that [`site_uses`] grades. +enum Call { + Method { name: String, args: usize }, + Function { name: String }, + Field { name: String }, +} + +impl Call { + fn name(&self) -> &str { + match self { + Call::Method { name, .. } | Call::Function { name } | Call::Field { name } => name, + } + } +} + +pub fn run(root: &Path) -> Result<(), String> { + println!("{}", check(root, SKIPPED_MODULES, SKIPPED_FUNCTIONS)?); + Ok(()) +} + +/// The sites under `root`, these modules and functions skipped, graded against [`LIST`]. +fn check(root: &Path, modules: &[(&str, &str)], functions: &[(&str, &str)]) -> Result { + let found = scan_skipping(root, modules, functions)?; + let text = std::fs::read_to_string(root.join(LIST)).map_err(|e| format!("{LIST}: {e}"))?; + grade(&text, &found).map_err(|e| format!("{LIST}: {e}")) +} + +/// Every decision site under `root`, these modules and functions skipped: `:` +/// with the patterns it uses. A skipped module that does not exist, or a skipped function that +/// does not use a mesh, is an error: the skips stay true. +fn scan_skipping(root: &Path, modules: &[(&str, &str)], functions: &[(&str, &str)]) -> Result>, String> { + for (skip, _) in modules { + if !root.join(skip).exists() { + return Err(format!("{skip} is skipped but does not exist: take it off SKIPPED_MODULES in xtask/src/mesh_decisions.rs")); + } + } + let mut found = BTreeMap::new(); + for krate in CRATES { + let lib = root.join(krate).join("src/lib.rs"); + let model_body = MODEL_BODY_CRATES.contains(krate); + let mut files = Vec::new(); + module_files(&lib, true, &mut files)?; + files.sort(); + files.dedup(); + for path in files { + let rel = relative(root, &path); + if modules.iter().any(|(skip, _)| rel == *skip || rel.starts_with(&format!("{skip}/"))) { + continue; + } + let source = std::fs::read_to_string(&path).map_err(|e| format!("{rel}: {e}"))?; + for (function, uses) in sites(&source, model_body).map_err(|e| format!("{rel}: {e}"))? { + found.insert(format!("{rel}:{function}"), uses); + } + } + } + for (skip, _) in functions { + if found.remove(*skip).is_none() { + return Err(format!("{skip} is skipped but uses no mesh: take it off SKIPPED_FUNCTIONS in xtask/src/mesh_decisions.rs")); + } + } + Ok(found) +} + +fn relative(root: &Path, path: &Path) -> String { + path.strip_prefix(root).unwrap_or(path).to_string_lossy().replace('\\', "/") +} + +/// The source files of the module at `file` and of every non-test module below it, into `out`. +/// `owns_dir` is whether `file` is a `lib.rs` or `mod.rs` (its submodules sit beside it) rather +/// than `name.rs` (its submodules sit in `name/`). +fn module_files(file: &Path, owns_dir: bool, out: &mut Vec) -> Result<(), String> { + let source = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?; + let ast = syn::parse_file(&source).map_err(|e| format!("{}: cannot parse Rust source: {e}", file.display()))?; + out.push(file.to_path_buf()); + let here = file.parent().unwrap_or(Path::new(".")); + let dir = if owns_dir { here.to_path_buf() } else { here.join(file.file_stem().unwrap_or_default()) }; + declared_modules(&ast.items, here, &dir, out) +} + +/// The out-of-line modules `items` declare. `here` is the directory of the file they are in +/// (`#[path]` resolves against it); `dir` is where their files sit without one. +fn declared_modules(items: &[syn::Item], here: &Path, dir: &Path, out: &mut Vec) -> Result<(), String> { + for item in items { + let syn::Item::Mod(m) = item else { continue }; + if test_only(&m.attrs) { + continue; + } + let name = m.ident.to_string(); + let path = path_attribute(&m.attrs); + match &m.content { + Some((_, inner)) => { + let base = match &path { + Some(p) => here.join(p), + None => dir.join(&name), + }; + declared_modules(inner, &base, &base, out)?; + } + None => match path { + Some(p) => { + let file = here.join(p); + let owns = file.file_name().is_some_and(|f| f == "mod.rs"); + module_files(&file, owns, out)?; + } + None => { + let flat = dir.join(format!("{name}.rs")); + if flat.is_file() { + module_files(&flat, false, out)?; + } else { + module_files(&dir.join(&name).join("mod.rs"), true, out)?; + } + } + }, + } + } + Ok(()) +} + +fn path_attribute(attrs: &[syn::Attribute]) -> Option { + attrs.iter().find(|a| a.path().is_ident("path")).and_then(|a| match &a.meta { + syn::Meta::NameValue(nv) => match &nv.value { + syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(s), .. }) => Some(s.value()), + _ => None, + }, + _ => None, + }) +} + +/// Whether `attrs` keep an item to test builds: `#[test]`, `#[cfg(test)]` or +/// `#[cfg(all(.., test, ..))]`. +fn test_only(attrs: &[syn::Attribute]) -> bool { + attrs.iter().any(|a| { + if a.path().is_ident("test") { + return true; + } + if !a.path().is_ident("cfg") { + return false; + } + let Ok(meta) = a.parse_args::() else { return false }; + match meta { + syn::Meta::Path(p) => p.is_ident("test"), + syn::Meta::List(l) if l.path.is_ident("all") => l + .parse_args_with(syn::punctuated::Punctuated::::parse_terminated) + .is_ok_and(|items| items.iter().any(|m| m.path().is_ident("test"))), + _ => false, + } + }) +} + +/// The functions of `source` that use a mesh, with the patterns each uses (outside test code). +pub fn sites(source: &str, model_body: bool) -> Result>, String> { + let ast = syn::parse_file(source).map_err(|e| format!("cannot parse Rust source: {e}"))?; + let mut finder = Finder { model_body, scope: Vec::new(), found: BTreeMap::new() }; + finder.visit_file(&ast); + Ok(finder.found) +} + +struct Finder { + model_body: bool, + /// The enclosing inline modules, impl type and function, outermost first. + scope: Vec, + found: BTreeMap>, +} + +impl Finder { + fn note(&mut self, call: Call) { + let Some(what) = site_uses(&call, self.model_body) else { return }; + let site = if self.scope.is_empty() { "".to_owned() } else { self.scope.join("::") }; + let uses = self.found.entry(site).or_default(); + if !uses.contains(&what) { + uses.push(what); + } + } + + fn scoped(&mut self, name: String, f: impl FnOnce(&mut Self)) { + self.scope.push(name); + f(self); + self.scope.pop(); + } + + /// A macro's arguments, when they are expressions (`format!`, `vec!`, `assert!`): syn leaves + /// macro bodies unparsed, and a mesh call inside one is a use all the same. + fn macro_args(&mut self, mac: &syn::Macro) { + let parser = syn::punctuated::Punctuated::::parse_terminated; + if let Ok(args) = mac.parse_body_with(parser) { + for e in &args { + self.visit_expr(e); + } + } else if let Ok(block) = mac.parse_body_with(syn::Block::parse_within) { + for s in &block { + self.visit_stmt(s); + } + } + } +} + +fn type_name(ty: &syn::Type) -> String { + match ty { + syn::Type::Path(p) => p.path.segments.last().map_or_else(|| "".to_owned(), |s| s.ident.to_string()), + syn::Type::Reference(r) => type_name(&r.elem), + _ => "".to_owned(), + } +} + +impl<'ast> Visit<'ast> for Finder { + fn visit_item_mod(&mut self, m: &'ast syn::ItemMod) { + if !test_only(&m.attrs) && m.content.is_some() { + self.scoped(m.ident.to_string(), |f| visit::visit_item_mod(f, m)); + } + } + + fn visit_item_fn(&mut self, i: &'ast syn::ItemFn) { + if !test_only(&i.attrs) { + self.scoped(i.sig.ident.to_string(), |f| visit::visit_item_fn(f, i)); + } + } + + fn visit_item_impl(&mut self, i: &'ast syn::ItemImpl) { + if !test_only(&i.attrs) { + self.scoped(type_name(&i.self_ty), |f| visit::visit_item_impl(f, i)); + } + } + + fn visit_impl_item_fn(&mut self, i: &'ast syn::ImplItemFn) { + if !test_only(&i.attrs) { + self.scoped(i.sig.ident.to_string(), |f| visit::visit_impl_item_fn(f, i)); + } + } + + fn visit_item_trait(&mut self, i: &'ast syn::ItemTrait) { + if !test_only(&i.attrs) { + self.scoped(i.ident.to_string(), |f| visit::visit_item_trait(f, i)); + } + } + + fn visit_trait_item_fn(&mut self, i: &'ast syn::TraitItemFn) { + if !test_only(&i.attrs) { + self.scoped(i.sig.ident.to_string(), |f| visit::visit_trait_item_fn(f, i)); + } + } + + fn visit_item_const(&mut self, i: &'ast syn::ItemConst) { + if !test_only(&i.attrs) { + self.scoped(i.ident.to_string(), |f| visit::visit_item_const(f, i)); + } + } + + fn visit_item_static(&mut self, i: &'ast syn::ItemStatic) { + if !test_only(&i.attrs) { + self.scoped(i.ident.to_string(), |f| visit::visit_item_static(f, i)); + } + } + + fn visit_stmt(&mut self, s: &'ast syn::Stmt) { + if let syn::Stmt::Local(l) = s + && test_only(&l.attrs) + { + return; + } + visit::visit_stmt(self, s); + } + + fn visit_expr_method_call(&mut self, e: &'ast syn::ExprMethodCall) { + self.note(Call::Method { name: e.method.to_string(), args: e.args.len() }); + visit::visit_expr_method_call(self, e); + } + + fn visit_expr_call(&mut self, e: &'ast syn::ExprCall) { + if let syn::Expr::Path(p) = e.func.as_ref() + && let Some(last) = p.path.segments.last() + { + self.note(Call::Function { name: last.ident.to_string() }); + } + visit::visit_expr_call(self, e); + } + + fn visit_expr_field(&mut self, e: &'ast syn::ExprField) { + if let syn::Member::Named(name) = &e.member { + self.note(Call::Field { name: name.to_string() }); + } + visit::visit_expr_field(self, e); + } + + fn visit_macro(&mut self, mac: &'ast syn::Macro) { + self.macro_args(mac); + visit::visit_macro(self, mac); + } +} + +/// The gate: every site in `found` is listed in `list`, and every listed site is still found. +fn grade(list: &str, found: &BTreeMap>) -> Result { + let listed = crate::kernel_cases::known_failing(list)?; + let mut problems = Vec::new(); + for (site, uses) in found { + if !listed.iter().any(|(s, _)| s == site) { + problems.push(format!( + "NEW: {site} decides with a mesh ({}): use exact geometry (`Body::exact_bounds`, `kernel::apart`, the B-rep's \ + faces and edges); a mesh is for display, export, previews and mesh bodies", + uses.join(", ") + )); + } + } + for (site, _) in &listed { + if !found.contains_key(*site) { + problems.push(format!("FIXED: {site} no longer uses a mesh: remove its line")); + } + } + if problems.is_empty() { + Ok(format!("mesh-decisions: {} known decision sites use a mesh; no new ones", listed.len())) + } else { + Err(format!("{} problem(s):\n {}", problems.len(), problems.join("\n "))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn found(source: &str) -> BTreeMap> { + sites(source, true).unwrap() + } + + #[test] + fn mesh_uses_are_found_per_function_outside_tests() { + let s = found( + r#" + fn decides(b: &Body) -> bool { b.mesh(&tol).is_ok() } + fn display_mesh(mb: &ModelBody) -> usize { mb.mesh().triangles.len() } + impl Sheet { fn near(&self) -> bool { boxes_apart(&mesh_box(self.mb), &body_box(&self.tool)) } } + fn in_macro(mb: &ModelBody) -> String { format!("{}", mb.plan_mesh().is_some()) } + fn exact(b: &Body) -> bool { b.exact_bounds().is_ok() } + #[cfg(test)] mod tests { fn fixture(b: &Body) { b.mesh(&tol); } } + #[test] fn t(b: &Body) { b.mesh(&tol); } + mod inner { fn nearest(p: Vec3, t: [Vec3; 3]) -> Vec3 { closest_on_triangle(p, t[0], t[1], t[2]) } } + "#, + ); + let keys: Vec<&str> = s.keys().map(String::as_str).collect(); + assert_eq!(keys, ["Sheet::near", "decides", "display_mesh", "in_macro", "inner::nearest"]); + assert_eq!(s["display_mesh"], [".triangles", ".mesh()"]); + assert_eq!(s["Sheet::near"], ["mesh_box()", "body_box()"]); + // In the kernel the argument-less `mesh()` is a T-spline's control net. + assert!(sites("fn regular(ts: &TSpline) -> bool { ts.mesh().is_regular() }", false).unwrap().is_empty()); + assert!(sites("invalid Rust {{", true).is_err(), "unparseable source fails closed"); + } + + const LISTED: &str = "# comment\na.rs:decides why\nb.rs:near why\n"; + + fn sites_of(names: &[&str]) -> BTreeMap> { + names.iter().map(|n| (n.to_string(), vec![".mesh(t)"])).collect() + } + + #[test] + fn listed_sites_pass() { + assert!(grade(LISTED, &sites_of(&["a.rs:decides", "b.rs:near"])).is_ok()); + } + + #[test] + fn a_new_site_fails() { + let e = grade(LISTED, &sites_of(&["a.rs:decides", "b.rs:near", "c.rs:picks"])).unwrap_err(); + assert!(e.contains("NEW: c.rs:picks"), "{e}"); + } + + #[test] + fn a_fixed_site_still_listed_fails() { + let e = grade(LISTED, &sites_of(&["a.rs:decides"])).unwrap_err(); + assert!(e.contains("FIXED: b.rs:near"), "{e}"); + } + + #[test] + fn the_list_is_sorted_with_a_reason_each() { + assert!(grade("b.rs:near why\na.rs:decides why\n", &sites_of(&["a.rs:decides", "b.rs:near"])).is_err()); + assert!(grade("a.rs:decides\n", &sites_of(&["a.rs:decides"])).is_err()); + } + + #[test] + fn the_module_tree_leaves_out_test_modules_and_follows_paths() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("solidcraft-mesh-decisions-{}-{unique}", std::process::id())); + let src = root.join("crates/doc/src"); + std::fs::create_dir_all(src.join("eval")).unwrap(); + std::fs::create_dir_all(root.join("crates/engine/src")).unwrap(); + std::fs::create_dir_all(root.join("crates/kernel/src/tess")).unwrap(); + std::fs::write(src.join("lib.rs"), "mod eval;\n#[cfg(test)]\nmod tests;\n").unwrap(); + std::fs::write(src.join("eval.rs"), "#[path = \"more.rs\"]\nmod more;\nmod nested;\n").unwrap(); + std::fs::write(src.join("more.rs"), "fn skip(mb: &ModelBody) -> bool { mb.mesh().triangles.is_empty() }").unwrap(); + std::fs::write(src.join("eval/nested.rs"), "fn hit(b: &Body) { b.mesh(&t); }").unwrap(); + std::fs::write(src.join("tests.rs"), "fn fixture(b: &Body) { b.mesh(&t); }").unwrap(); + std::fs::write(root.join("crates/engine/src/lib.rs"), "").unwrap(); + std::fs::write(root.join("crates/kernel/src/lib.rs"), "mod tess;").unwrap(); + std::fs::write(root.join("crates/kernel/src/tess/mod.rs"), "fn mesher(b: &Body) { b.mesh_plan(&t); }").unwrap(); + let found = scan_skipping(&root, &[("crates/kernel/src/tess", "the mesher")], &[]).unwrap(); + assert!(scan_skipping(&root, &[("crates/doc/src/gone.rs", "gone")], &[]).is_err(), "a skipped module that is gone fails"); + assert!(scan_skipping(&root, &[], &[("crates/doc/src/more.rs:other", "x")]).is_err(), "a skipped function without a mesh fails"); + let keys: Vec<&str> = found.keys().map(String::as_str).collect(); + assert_eq!(keys, ["crates/doc/src/eval/nested.rs:hit", "crates/doc/src/more.rs:skip"]); + std::fs::create_dir_all(root.join("xtask")).unwrap(); + std::fs::write(root.join(LIST), "crates/doc/src/eval/nested.rs:hit picks a face\ncrates/doc/src/more.rs:skip skips a body\n").unwrap(); + let skips: &[(&str, &str)] = &[("crates/kernel/src/tess", "the mesher")]; + check(&root, skips, &[]).unwrap(); + std::fs::write(src.join("eval/nested.rs"), "fn hit(b: &Body) { b.exact_bounds(); }").unwrap(); + assert!(check(&root, skips, &[]).unwrap_err().contains("FIXED: crates/doc/src/eval/nested.rs:hit")); + std::fs::write(src.join("eval/nested.rs"), "fn hit(b: &Body) { b.mesh(&t); }\nfn picks(b: &Body) { b.mesh(&t); }").unwrap(); + assert!(check(&root, skips, &[]).unwrap_err().contains("NEW: crates/doc/src/eval/nested.rs:picks")); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn the_workspace_has_no_new_mesh_decisions() { + run(Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap()).unwrap(); + } +} diff --git a/xtask/src/web_offline_test.rs b/xtask/src/web_offline_test.rs index 89f99c5bf..42bcccf00 100644 --- a/xtask/src/web_offline_test.rs +++ b/xtask/src/web_offline_test.rs @@ -47,6 +47,9 @@ //! `cargo xtask web-offline`'s generator and a `data-build` marker on ``. Chrome comes from //! `CHROME` or the usual install locations; `cargo xtask ci` skips this test when there is none. //! +//! A real build's copies each get a file of their own, as successive deployments have files +//! named differently. +//! //! The stand-in app has a content-named script, a `shared.js` whose name is the same in every //! build (a page must get its own build's), more files under `icons/` than the browser asks for //! at once, and an on-demand file under `fonts/` (not kept). @@ -240,6 +243,10 @@ pub fn run(root: &Path, site: Option<&str>, required: bool) -> Result<(), String check_site(root, Path::new(dir), &work.0.join("check"))?; for (to, build) in &builds { copy_dir(Path::new(dir), to)?; + // Trunk names files after their contents, so two real deployments differ in more + // than `index.html`; copies of one build don't. A file of its own per copy lets + // a step hold back what one build has and the next lacks (step 13). + std::fs::write(to.join(format!("own-{build}.txt")), format!("{build}\n")).map_err(|e| format!("{}: {e}", to.display()))?; let index = to.join("index.html"); let html = std::fs::read_to_string(&index).map_err(|e| format!("{}: {e}", index.display()))?; std::fs::write(&index, mark(&html, build)?).map_err(|e| format!("{}: {e}", index.display()))?;