diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..8ec0c2e98 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Questions and chat + url: https://discord.gg/FtU4NQNVDH + about: Ask questions and talk with users and contributors on the SolidCraft Discord. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 6221864bd..de3c20024 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -96,9 +96,11 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/locales/de.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/locales/en.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/locales/fr.json | rlartot | French translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | +| assets/locales/gl.json | Pablo López (pablopeza) | Galician translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | | assets/locales/ja.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/locales/ko.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | | assets/locales/ru.json | Alex Pro (del000) | Russian translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | +| assets/locales/pt-BR.json | DuBearte | Brazilian Portuguese translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | | assets/locales/tr.json | macrulz54 | Turkish translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | | assets/locales/uk.json | Igor Bronovskyi (BrunIF) | Ukrainian translation of the English catalog, contributed upstream | MIT OR Apache-2.0 | | assets/locales/zh.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b835ed41c..7e9fcc8cb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,6 +10,8 @@ Help is welcome, whether that's a one-line fix or owning a whole area. This page build it, how the code is laid out, the few rules that aren't negotiable, and where help is needed most. +Questions, ideas or want to say what you're working on? Join the [Discord](https://discord.gg/FtU4NQNVDH). + ## Get it running (about 10 minutes on a fast machine) You need stable Rust 1.95 or newer (required by egui/eframe 0.36). For the web diff --git a/Cargo.lock b/Cargo.lock index 1fa23852d..684cb308d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4215,6 +4215,7 @@ dependencies = [ "serde_json", "sha2 0.10.9", "solidcraft-geom", + "weezl", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index d48e8a619..080e0184c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -71,6 +71,8 @@ ttf-parser = { version = "0.25", default-features = false, features = ["std"] } # images image = { version = "0.25", default-features = false, features = ["png", "hdr"] } png = "0.18.1" +# LZW for GIF animations (MIT OR Apache-2.0, pure Rust; already in the tree through image's tiff). +weezl = "0.1.12" # ui egui = "0.36" diff --git a/README.md b/README.md index f24a498d4..7e972e429 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,17 @@ -# SolidCraft +

+ SolidCraft +

-**An open-source parametric 3D CAD application built in pure Rust.** +

SolidCraft

-Sketch, constrain, and build solids with a parametric feature timeline. Change a dimension -and watch your model rebuild. Run it on your desktop, in your browser, or let AI agents -model through the built-in MCP server. +

+ An open-source parametric 3D CAD application built in pure Rust.
+ Sketch, constrain, and build solids with a parametric feature timeline. Change a dimension + and watch your model rebuild. Run it on your desktop, in your browser, or let AI agents + model through the built-in MCP server. +

-![SolidCraft 0.8: model a Raspberry Pi 4 case from an empty design: a sketch dimensioned with parameters, extrude, fillets and shell, a rim rounded in one pick, standoffs patterned on the board's mounting holes, port cut-outs, vent slots, "Pi 4" engraved in a font, a PETG material with its mass in Properties, and a height change in Parameters](docs/screenshots/demo-0.8.gif) - -*A Raspberry Pi 4 case from an empty design: a sketch dimensioned with the board's parameters, extrude, fillet, shell, the rim rounded in one pick, an M2.5 standoff patterned on the 58 × 49 mm hole rectangle, port cut-outs, vent slots, "Pi 4" engraved in DejaVu Sans Bold and a PETG material defined in the design, with its mass in Properties, then height 24 → 32 mm in Parameters and it all rebuilds. 9× playback. [Full video](https://github.com/bherbruck/solidcraft/raw/refs/heads/main/docs/screenshots/demo-0.8.mp4), recorded with the [demo script](examples/demo/record_ui.sh).* - -## Download +
[![Download for Windows][badge-windows]][windows-msi] [![Download for macOS][badge-macos]][macos-dmg] @@ -18,6 +19,32 @@ model through the built-in MCP server. [![Get it from the Snap Store][badge-snap]][snap-store] [![Try it in your browser][badge-web]][web-app] +
+ +

+ Website · + Download · + Try it in the browser · + Documentation · + Discord · + SolidCore +

+ +

+ CI + Latest release + Downloads + Licence + Discord + Stars +

+ +![SolidCraft 0.8: model a Raspberry Pi 4 case from an empty design: a sketch dimensioned with parameters, extrude, fillets and shell, a rim rounded in one pick, standoffs patterned on the board's mounting holes, port cut-outs, vent slots, "Pi 4" engraved in a font, a PETG material with its mass in Properties, and a height change in Parameters](docs/screenshots/demo-0.8.gif) + +*A Raspberry Pi 4 case from an empty design: a sketch dimensioned with the board's parameters, extrude, fillet, shell, the rim rounded in one pick, an M2.5 standoff patterned on the 58 × 49 mm hole rectangle, port cut-outs, vent slots, "Pi 4" engraved in DejaVu Sans Bold and a PETG material defined in the design, with its mass in Properties, then height 24 → 32 mm in Parameters and it all rebuilds. 9× playback. [Full video](https://github.com/bherbruck/solidcraft/raw/refs/heads/main/docs/screenshots/demo-0.8.mp4), recorded with the [demo script](examples/demo/record_ui.sh).* + +## Download + - **Windows:** download and run the [installer][windows-msi]. Also for [ARM64][windows-arm64-msi] and [32-bit][windows-x86-msi] PCs, or as a [portable zip][windows-portable] that runs without installing. @@ -62,6 +89,8 @@ Install details, upgrading from earlier builds and building from source are in **Documentation:** the [SolidCraft book](https://bherbruck.github.io/solidcraft/) (user guide, developer guide and command reference; sources in [docs/book](docs/book)). +**Community:** chat with users and contributors on [Discord](https://discord.gg/FtU4NQNVDH). + **Status: early but usable for simple parts.** 75 of 76 public reference parts match their analytic or FreeCAD-computed volume, area, centre of mass and bounding box ([docs/oracle.md](docs/oracle.md)); the other is a tracked bug. diff --git a/ROADMAP.md b/ROADMAP.md index 67e1ba716..c39497628 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -54,7 +54,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; optional compact named left feature history with rollback bar, multi-selection and persistent folders above the parts browser), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator; taper handle open), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; preferences | in progress | 6 | | M7 | Thin extrude (walls along open or closed curves: centre, inside, outside or two sides; mitred corners, crossing walls joined; #721), sweep, loft (incl. to a point), rib and web (to next / depth), emboss (planar faces and exact radial emboss/deboss of bounded orthogonal profiles on complete exterior cylinders/sleeves), thread (cosmetic, and modelled M3–M20 outside and inside: the ISO profile screwed in as a faceted cut), coil (smooth B-spline helical walls), pipe, pattern on path, patterns of bodies and components, replace face (parallel), align, remove, feature copy/paste: done. Unique eligible cylindrical targets are inferred for new Emboss features. Left: general curved-face emboss and exact (unfaceted) modelled threads | in progress | 12 | | M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane or a face), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two boundaries exact, three/four refused pending a Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770) and a multi-section **loft** with per-end continuity and crown. Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), sweep guide rails and two-rail sweeps (#771; orientation, twist and end scale done; loft rails #201), and every remaining #757–#772 item | deferred | — | -| M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | +| M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), cams (`joint.cam`: a revolute cam drives a slider or revolute follower along a closed sketch profile or the cam's edges, knife, roller or flat followers, worked out again when the profile changes; drives, studies, closed loops, contact sets), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Cam and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | | M10 | Sheet metal: flange (base, edge, contour), hem, unfold/refold, convert, flat pattern + DXF, rules: done. PLASTIC enclosure subset: Boss, Rib, Web, Lip/Groove, Snap Fit, Rest, Plastic Rules (library, edit, assign; rule draft and clearance as feature defaults): done, tested against hand-computed geometry. UI: SHEET METAL and PLASTIC tabs in Fusion's layout with dialogs (live preview, Edit Feature, pre-selection) for Flange, Hem, Unfold/Refold, Convert, Sheet Metal Rules, Create Flat Pattern (flat view with bend lines, bend table CSV/JSON and DXF export with exact circle/arc/line cutouts), Boss, Lip/Groove, Snap Fit, Rest, Manage and Assign Plastic Rules; Fold (bend along a sketch line); flanges meeting at a corner closed at any angle with the rule's gap; edge flanges with their own angle and height per edge in one feature; corner reliefs (notch, round, rectangular, tear) chosen by the rule; Convert to Sheet Metal from a solid or shelled body by its bend edges (flat faces, sharp bends) | in progress | 36 | | M11 | 2D drawings | deferred | — | | M12 | Release: cross-platform packages, verification and deliberate publication implemented; original current-UI demo refreshed. Trusted distribution signing and broader performance work remain | in progress | 16 | @@ -68,11 +68,23 @@ retain their saved two-finger scroll preference; camera motion is available thro M11 precursor: File → Export Current View as DXF exports shown placed bodies from the current camera as a 2D millimetre drawing, with hidden edges omitted or dashed. Vector occlusion splits -partly hidden edges and includes curved silhouettes. Curves are approximated; drawing sheets, +partly hidden edges and includes curved silhouettes. Repeated part meshes and triangle +hierarchies are shared; bounded desktop preparation and occlusion use up to eight workers. +Curves are approximated; drawing sheets, annotations and exact projected curves remain deferred. See [view DXF](docs/view-dxf.md). +Desktop view DXF export runs in the file-operation worker with five-stage progress and +cooperative cancellation. Curve tolerance (0.0001–1 mm, default 0.01 mm) is remembered alongside +the hidden-edge setting. Cancelled exports preserve the model and the previous destination; +completed drawings publish atomically. The browser still exports synchronously. + ## Interactive modelling +- Thread resolves a suggested metric size when a cylindrical face is picked. Diameter and + pitch selectors expose the existing metric designation parameter; custom designations stay + editable, and Automatic size returns to the face's suggestion. Cosmetic/modelled and + full/partial-length options remain available. This does not add tolerance classes or + left-hand threads. - New Body extrusion and face-offset previews show completed intermediate geometry while a drag continues, then catch up to the exact final value. Changes to the selected geometry, operation or feature still discard obsolete results. Distance arrows and their value boxes diff --git a/apps/solidcraft-cli/tests/action_matrix.rs b/apps/solidcraft-cli/tests/action_matrix.rs index 35d82d961..23781cdc6 100644 --- a/apps/solidcraft-cli/tests/action_matrix.rs +++ b/apps/solidcraft-cli/tests/action_matrix.rs @@ -1559,7 +1559,6 @@ fn a_sketch_on_the_rim_a_shell_leaves() { } #[test] -#[ignore = "fails until #565 is fixed"] fn sketches_after_split_body_and_intersect() { reproduces( None, diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index 9d2b8c899..3d36ed267 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -94,10 +94,20 @@ impl eframe::App for App { solidcraft_ui_egui::recovery_ui::close(&mut self.solve); solidcraft_engine::crash::end_session(); // An update asked to restart into the new version or to run its installer. - if let Some((program, args)) = solidcraft_ui_egui::update::take_launch(&mut self.solve) - && let Err(e) = std::process::Command::new(&program).args(&args).spawn() - { - log::error!("update: starting {}: {e}", program.display()); + if let Some((program, args)) = solidcraft_ui_egui::update::take_launch(&mut self.solve) { + let mut command = std::process::Command::new(&program); + command.args(&args); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + // Not tied to this process: its own process group, and no console (the PowerShell + // that waits for an installer is hidden; the app itself is detached). + let hidden_shell = program.file_stem().is_some_and(|n| n.eq_ignore_ascii_case("powershell")); + command.creation_flags(0x0000_0200 | if hidden_shell { 0x0800_0000 } else { 0x0000_0008 }); + } + if let Err(e) = command.spawn() { + log::error!("update: starting {}: {e}", program.display()); + } } } } diff --git a/apps/solidcraft/src/space_mouse.rs b/apps/solidcraft/src/space_mouse.rs index da872320f..79f08ccdc 100644 --- a/apps/solidcraft/src/space_mouse.rs +++ b/apps/solidcraft/src/space_mouse.rs @@ -347,16 +347,23 @@ impl SpaceMouse { /// Before the app's own hook (which adds the control channel's events): with navigation on, /// the wheel events 3DxWare makes from the cap's motion are dropped. pub fn raw_input_hook(&mut self, enabled: bool, raw: &mut egui::RawInput) { + self.raw_input_hook_at(enabled, raw, Instant::now()); + } + + fn raw_input_hook_at(&mut self, enabled: bool, raw: &mut egui::RawInput, now: Instant) { if !enabled { return; } - let now = Instant::now(); let moving = self.shared.lock().map(|reading| reading.current(now).moving()).unwrap_or(false); self.wheel.filter(moving, now.duration_since(self.started).as_secs_f64(), &mut raw.events); } pub fn tick(&mut self, app: &mut SolveApp, ctx: &Context) { - let now = Instant::now(); + self.tick_at(app, ctx, Instant::now()); + } + + /// The frame at `now`. Tests pass their own clock, so a slow runner can't age a reading. + fn tick_at(&mut self, app: &mut SolveApp, ctx: &Context, now: Instant) { let seconds = now.duration_since(self.last_frame).as_secs_f64(); self.last_frame = now; if now.duration_since(self.mapping_checked_at) >= RETRY_AFTER { @@ -486,6 +493,9 @@ mod tests { #[test] fn each_frame_hands_the_view_its_motion_through_the_drivers_mapping() { // The reader's latest tilt, and a profile that makes tilt roll: the frame's motion rolls. + // The frame runs at the reading's own time, so a slow runner can't let the reading go stale. + let mut app = SolveApp::new(solidcraft_engine::Session::default(), solidcraft_ui_egui::Services::default()); + app.home.open = false; let now = Instant::now(); let mut reading = Reading::new(now); reading.axes.rotation = [0, 350, 0]; @@ -497,9 +507,7 @@ mod tests { wheel: WheelGuard::default(), started: now, }; - let mut app = SolveApp::new(solidcraft_engine::Session::default(), solidcraft_ui_egui::Services::default()); - app.home.open = false; - mouse.tick(&mut app, &Context::default()); + mouse.tick_at(&mut app, &Context::default(), now); let DeviceMotion { motion, seconds } = app.viewport.device_motion.expect("the frame hands the page its motion"); assert_eq!(motion, Motion { translation: [0.0; 3], rotation: [0.0, 0.0, -1.0] }); assert!(seconds > 0.0); @@ -514,8 +522,7 @@ mod tests { } } - fn mouse(reading: Reading) -> SpaceMouse { - let now = Instant::now(); + fn mouse(reading: Reading, now: Instant) -> SpaceMouse { SpaceMouse { shared: Arc::new(Mutex::new(reading)), last_frame: now, @@ -532,36 +539,37 @@ mod tests { let now = Instant::now(); let mut tilted = Reading::new(now); tilted.axes.rotation = [-200, 0, 0]; - let mut moving = mouse(tilted); + let mut moving = mouse(tilted, now); let mut raw = egui::RawInput { events: vec![wheel(), egui::Event::Zoom(1.1), egui::Event::Text("a".into())], ..Default::default() }; - moving.raw_input_hook(true, &mut raw); + moving.raw_input_hook_at(true, &mut raw, now); assert_eq!(raw.events, [egui::Event::Text("a".into())]); // With navigation off, the wheel is the cap's only way to move the view: kept. let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() }; - moving.raw_input_hook(false, &mut raw); + moving.raw_input_hook_at(false, &mut raw, now); assert_eq!(raw.events.len(), 1); // The cap at rest: the wheel is the user's. - let mut resting = mouse(Reading::new(now)); + let mut resting = mouse(Reading::new(now), now); let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() }; - resting.raw_input_hook(true, &mut raw); + resting.raw_input_hook_at(true, &mut raw, now); assert_eq!(raw.events.len(), 1); } #[test] fn the_wheel_is_the_users_again_once_the_cap_has_been_still_a_moment() { - let mut tilted = Reading::new(Instant::now()); + let now = Instant::now(); + let mut tilted = Reading::new(now); tilted.axes.rotation = [-200, 0, 0]; - let mut cap = mouse(tilted); + let mut cap = mouse(tilted, now); let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() }; - cap.raw_input_hook(true, &mut raw); + cap.raw_input_hook_at(true, &mut raw, now); assert!(raw.events.is_empty(), "dropped while the cap moves"); // Let go, then wait out the quiet time. + let later = now + Duration::from_secs_f64(solidcraft_ui_egui::space_mouse::WHEEL_QUIET_S) + Duration::from_millis(60); if let Ok(mut reading) = cap.shared.lock() { - *reading = Reading::new(Instant::now()); + *reading = Reading::new(later); } - std::thread::sleep(Duration::from_secs_f64(solidcraft_ui_egui::space_mouse::WHEEL_QUIET_S) + Duration::from_millis(60)); let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() }; - cap.raw_input_hook(true, &mut raw); + cap.raw_input_hook_at(true, &mut raw, later); assert_eq!(raw.events.len(), 1, "kept once the cap has been still"); } } diff --git a/assets/icons/ui/source/icons.rs b/assets/icons/ui/source/icons.rs index 2f342a8c5..56583146e 100644 --- a/assets/icons/ui/source/icons.rs +++ b/assets/icons/ui/source/icons.rs @@ -1338,6 +1338,20 @@ pub(crate) fn paint_with(p: &Painter, r: Rect, name: &str, ink: Color32, fill: C pen.poly(&[(6.0, 10.0), (18.0, 10.0), (18.0, 15.0), (6.0, 15.0)], pen.fill, a); pen.arrow((21.0, 17.0), (21.0, 6.0), a); } + "cam" => { + // A cam on its shaft, its lobe up under the follower it lifts. + let cam: Vec<(f32, f32)> = (0..36) + .map(|k| { + let t = std::f32::consts::TAU * k as f32 / 36.0; + let r = 5.0 + 3.0 * (0.5 + 0.5 * t.sin()).powi(3); + (11.0 + r * t.cos(), 16.0 - r * t.sin()) + }) + .collect(); + pen.poly(&cam, pen.fill, ink); + pen.dot(11.0, 16.0, ink); + pen.poly(&[(9.0, 2.0), (13.0, 2.0), (13.0, 8.0), (9.0, 8.0)], pen.fill, a); + pen.arrow((18.5, 9.5), (18.5, 2.5), a); + } "interference" => { pen.closed(&[(3.0, 5.0), (14.0, 5.0), (14.0, 16.0), (3.0, 16.0)], ink); pen.poly(&[(9.0, 10.0), (14.0, 10.0), (14.0, 16.0), (9.0, 16.0)], ic.interference, ic.interference); diff --git a/assets/locales/de.json b/assets/locales/de.json index c74bd78cf..a7ef9a7b9 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -24,6 +24,7 @@ "Drive Joint": "Gelenk antreiben", "Edges": "Kanten", "Edit Profile Sketch": "Profile-Skizze bearbeiten", + "Export Animation…": "Animation exportieren…", "Export Current View as DXF": "Aktuelle Ansicht als DXF exportieren", "Export Current View as DXF…": "Aktuelle Ansicht als DXF exportieren…", "Export DXF…": "DXF exportieren…", @@ -59,6 +60,7 @@ "Restore outer boundary": "Äußere Begrenzung wiederherstellen", "Revert Position": "Position zurücksetzen", "Round": "Rund", + "Save the study as an animated GIF, seen as the viewport shows it": "Die Studie als animiertes GIF speichern, so wie der Ansichtsbereich sie zeigt", "Select bodies (a face picks its body)": "Körper auswählen (eine Fläche wählt ihren Körper)", "Selection filter": "Auswahlfilter", "Send your report on GitHub": "Bericht auf GitHub senden", @@ -92,6 +94,13 @@ "browser.precision": "Genauigkeit: {precision}", "browser.sketch_name": "Skizze {number}", "browser.units": "Einheiten: {units}", + "cam.flat": "Flachstößel", + "cam.follower": "Stößel", + "cam.knife": "Schneide", + "cam.needs_joints": "braucht ein Gelenk, das sich dreht, und eines, das gleitet oder schwenkt", + "cam.roller": "Rolle", + "cam.roller_pick": "Rolle (optional)", + "cam.tip_pick": "Spitze (optional)", "cmd.appearance_assign": "Erscheinungsbild", "cmd.appearance_library": "Erscheinungsbild-Bibliothek", "cmd.appearance_list": "Erscheinungsbilder auflisten", @@ -195,6 +204,7 @@ "cmd.inspect_minimum_radius": "Mindestradiusanalyse", "cmd.inspect_zebra": "Zebra-Analyse", "cmd.joint_as_built": "Fertigungsgelenk", + "cmd.joint_cam": "Nocken", "cmd.joint_create": "Gelenk", "cmd.joint_delete": "Gelenk löschen", "cmd.joint_drive": "Gelenke antreiben", @@ -225,6 +235,7 @@ "cmd.model_threads": "Gewinde auflisten", "cmd.motion_delete": "Bewegungsuntersuchung löschen", "cmd.motion_export": "Bewegungsuntersuchung exportieren", + "cmd.motion_export_animation": "Bewegungsanimation exportieren", "cmd.motion_list": "Bewegungsuntersuchungen auflisten", "cmd.motion_play": "Bewegungsuntersuchung abspielen", "cmd.motion_study": "Bewegungsuntersuchung", @@ -428,6 +439,18 @@ "drive.stopped_by_contact": "Angehalten bei {value}: {a} würde {b} durchdringen", "drive.stopped_by_loop": "Angehalten bei {value}: die Schleife über {joint} lässt sich nicht weiter schließen", "drive.unconnected": "Bewegt nichts: {part} ist mit nichts Festgesetztem verbunden", + "dxf.cancel_wait": "Warten, bis der Export angehalten wurde…", + "dxf.cancelled": "DXF-Export abgebrochen", + "dxf.cancelling": "DXF-Export wird abgebrochen", + "dxf.exporting": "DXF wird exportiert", + "dxf.invalid_tolerance": "Die Kurventoleranz muss zwischen 0,0001 und 1 mm liegen.", + "dxf.progress.index": "Flächen vorbereiten (2/5)", + "dxf.progress.meshes": "Netze vorbereiten (1/5)", + "dxf.progress.occlusion": "Verdeckte Kanten ermitteln (4/5)", + "dxf.progress.projection": "Geometrie projizieren (3/5)", + "dxf.progress.write": "DXF schreiben (5/5)", + "dxf.tolerance": "Kurventoleranz", + "dxf.tolerance_help": "Nur sichtbare Körper. Kurven werden durch gerade Segmente angenähert. Eine kleinere Toleranz liefert feinere Kurven und benötigt mehr Zeit und Speicher.", "home.documentation": "Dokumentation", "home.in_this_browser": "in diesem Browser", "home.missing": "fehlt", diff --git a/assets/locales/en.json b/assets/locales/en.json index ffbe52a36..5c5c9f474 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -92,6 +92,7 @@ "Enable rule": "Enable rule", "Enabled": "Enabled", "Explode": "Explode", + "Export Animation…": "Export Animation…", "Export Current View as DXF": "Export Current View as DXF", "Export Current View as DXF…": "Export Current View as DXF…", "Export DXF…": "Export DXF…", @@ -211,6 +212,7 @@ "Round": "Round", "Rule": "Rule", "Save Rule": "Save Rule", + "Save the study as an animated GIF, seen as the viewport shows it": "Save the study as an animated GIF, seen as the viewport shows it", "Saved preview. Geometry is being checked before editing.": "Saved preview. Geometry is being checked before editing.", "Scale factor": "Scale factor", "Search": "Search", @@ -293,6 +295,13 @@ "browser.precision": "Precision: {precision}", "browser.sketch_name": "Sketch{number}", "browser.units": "Units: {units}", + "cam.flat": "Flat face", + "cam.follower": "Follower", + "cam.knife": "Knife edge", + "cam.needs_joints": "needs a joint that turns and one that slides or swings", + "cam.roller": "Roller", + "cam.roller_pick": "Roller (optional)", + "cam.tip_pick": "Tip (optional)", "cmd.appearance_assign": "Appearance", "cmd.appearance_library": "Appearance Library", "cmd.appearance_list": "List Appearances", @@ -396,6 +405,7 @@ "cmd.inspect_minimum_radius": "Minimum Radius Analysis", "cmd.inspect_zebra": "Zebra Analysis", "cmd.joint_as_built": "As-Built Joint", + "cmd.joint_cam": "Cam", "cmd.joint_create": "Joint", "cmd.joint_delete": "Delete Joint", "cmd.joint_drive": "Drive Joints", @@ -426,6 +436,7 @@ "cmd.model_threads": "List Threads", "cmd.motion_delete": "Delete Motion Study", "cmd.motion_export": "Export Motion Study", + "cmd.motion_export_animation": "Export Motion Animation", "cmd.motion_list": "List Motion Studies", "cmd.motion_play": "Play Motion Study", "cmd.motion_study": "Motion Study", @@ -631,6 +642,18 @@ "drive.stopped_by_contact": "Stopped at {value}: {a} would pass through {b}", "drive.stopped_by_loop": "Stopped at {value}: the loop through {joint} can't close any further", "drive.unconnected": "Moves nothing: {part} is not connected to anything grounded", + "dxf.cancel_wait": "Waiting for the export to stop…", + "dxf.cancelled": "DXF export cancelled", + "dxf.cancelling": "Cancelling DXF export", + "dxf.exporting": "Exporting DXF", + "dxf.invalid_tolerance": "Curve tolerance must be between 0.0001 and 1 mm.", + "dxf.progress.index": "Preparing surfaces (2/5)", + "dxf.progress.meshes": "Preparing meshes (1/5)", + "dxf.progress.occlusion": "Resolving hidden lines (4/5)", + "dxf.progress.projection": "Projecting geometry (3/5)", + "dxf.progress.write": "Writing DXF (5/5)", + "dxf.tolerance": "Curve tolerance", + "dxf.tolerance_help": "Visible bodies only. Curves use straight segments. Smaller tolerance gives finer curves and uses more time and memory.", "expression, e.g. 25 mm": "expression, e.g. 25 mm", "fits the face, e.g. M8": "fits the face, e.g. M8", "from the rule": "from the rule", @@ -760,6 +783,10 @@ "sketch_text.path_hint": "A curve of the sketch the text follows: click here, then the curve", "sketch_text.use_font_file": "Use the font file {path}", "the parts library is not available": "the parts library is not available", + "thread.automatic_size": "Automatic size", + "thread.designation": "Designation", + "thread.iso_metric": "ISO metric", + "thread.select_size": "Select size", "timeline.group": "New Feature Folder", "timeline.move_many": "Move Timeline Items", "timeline.move_to_group": "Move Features to Folder", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 8e52631cb..2c853bd50 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -85,6 +85,7 @@ "Enable rule": "Activer la règle", "Enabled": "Activé", "Explode": "Éclater", + "Export Animation…": "Exporter l'animation…", "Extents": "Étendues", "Face": "Face", "Face attachment lost": "Rattachement à la face perdu", @@ -194,6 +195,7 @@ "Round": "Arrondi", "Rule": "Règle", "Save Rule": "Enregistrer la règle", + "Save the study as an animated GIF, seen as the viewport shows it": "Enregistrer l'étude en GIF animé, telle que la fenêtre d'affichage la montre", "Saved preview. Geometry is being checked before editing.": "Aperçu enregistré. La géométrie est en cours de vérification avant modification.", "Scale factor": "Facteur d'échelle", "Search": "Rechercher", @@ -273,6 +275,13 @@ "browser.precision": "Précision : {precision}", "browser.sketch_name": "Esquisse{number}", "browser.units": "Unités : {units}", + "cam.flat": "Plateau", + "cam.follower": "Suiveur", + "cam.knife": "Arête", + "cam.needs_joints": "nécessite une liaison qui tourne et une qui glisse ou pivote", + "cam.roller": "Galet", + "cam.roller_pick": "Galet (facultatif)", + "cam.tip_pick": "Pointe (facultatif)", "cmd.appearance_assign": "Apparence", "cmd.appearance_library": "Bibliothèque d'apparences", "cmd.appearance_list": "Lister les apparences", @@ -376,6 +385,7 @@ "cmd.inspect_minimum_radius": "Analyse du rayon minimal", "cmd.inspect_zebra": "Analyse zébrée", "cmd.joint_as_built": "Liaison telle que construite", + "cmd.joint_cam": "Came", "cmd.joint_create": "Liaison", "cmd.joint_delete": "Supprimer la liaison", "cmd.joint_drive": "Piloter les liaisons", @@ -406,6 +416,7 @@ "cmd.model_threads": "Lister les filetages", "cmd.motion_delete": "Supprimer l'étude de mouvement", "cmd.motion_export": "Exporter l'étude de mouvement", + "cmd.motion_export_animation": "Exporter l'animation du mouvement", "cmd.motion_list": "Lister les études de mouvement", "cmd.motion_play": "Lire l'étude de mouvement", "cmd.motion_study": "Étude de mouvement", diff --git a/assets/locales/gl.json b/assets/locales/gl.json new file mode 100644 index 000000000..725f3d9c9 --- /dev/null +++ b/assets/locales/gl.json @@ -0,0 +1,1480 @@ +{ + "0 turns it off": "0 desactívao", + "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Abre o borrador de GitHub de abaixo e pega o informe copiado no portapapeis.", + "1. Open GitHub draft below. Your title and report will be filled in.": "1. Abre o borrador de GitHub de abaixo. O título e o informe encheranse automaticamente.", + "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Achega a captura de pantalla: cópiaa e pégaa, ou gárdaa e sube o PNG.", + "3. Click Submit new issue on GitHub to send your report.": "3. Preme Submit new issue en GitHub para enviar o informe.", + "A new configuration, a copy of the active one": "Unha configuración nova, copia da activa", + "AI": "IA", + "About SolidCraft": "Acerca de SolidCraft", + "Active": "Activa", + "Active rule": "Regra activa", + "Add": "Engadir", + "Add Key": "Engadir clave", + "Add Mid Radius": "Engadir raio medio", + "Add Row": "Engadir fila", + "Add condition": "Engadir condición", + "Alignment": "Aliñamento", + "All Sketch Points": "Todos os puntos do bosquexo", + "All open designs": "Todos os deseños abertos", + "Allowed expressions, separated by semicolons": "Expresións permitidas, separadas por punto e coma", + "Also deletes": "Tamén elimina", + "Angle 2": "Ángulo 2", + "Animate": "Animar", + "Appearance name": "Nome da aparencia", + "Applied Radius": "Raio aplicado", + "Apply To": "Aplicar a", + "Apply to selection": "Aplicar á selección", + "Arc length": "Lonxitude do arco", + "Area": "Área", + "Attachment": "Ancoraxe", + "BROWSER": "NAVEGADOR", + "Bend Line Position": "Posición da liña de dobra", + "Bend Position": "Posición da dobra", + "Bend Radius": "Raio de dobra", + "Bends": "Dobras", + "Body": "Corpo", + "Boundary": "Contorno", + "Bounding box": "Caixa delimitadora", + "CSV or JSON: updates existing parameters, adds new ones": "CSV ou JSON: actualiza os parámetros existentes e engade os novos", + "Capture All Positions": "Capturar todas as posicións", + "Catch Direction": "Dirección de captura", + "Cells": "Celas", + "Center X": "Centro X", + "Center Y": "Centro Y", + "Center of mass": "Centro de masas", + "Centre to centre": "Entre centros", + "Chamfer Type": "Tipo de chafrán", + "Check collisions": "Comprobar colisións", + "Checked": "Marcado", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Escolle un plano novo. A xeometría e as cotas do bosquexo mantéñense nas súas coordenadas bidimensionais.", + "Circumference": "Circunferencia", + "Close draft": "Pechar o borrador", + "Collisions": "Colisións", + "Colour": "Cor", + "Component1": "Compoñente1", + "Configuration": "Configuración", + "Configuration rules": "Regras de configuración", + "Construction": "Construción", + "Contact": "Contacto", + "Continuity": "Continuidade", + "Copy Error Message": "Copiar a mensaxe de erro", + "Copy Warning Message": "Copiar a mensaxe de aviso", + "Copy all licences": "Copiar todas as licenzas", + "Copy diagnostic information": "Copiar a información de diagnóstico", + "Copy report": "Copiar o informe", + "Copy screenshot": "Copiar a captura de pantalla", + "Corner Relief": "Desafogo de esquina", + "Corner Relief Shape": "Forma do desafogo de esquina", + "Counterbore depth": "Profundidade do avellanado cilíndrico", + "Countersink angle": "Ángulo do avellanado cónico", + "Create Issue — review draft": "Crear incidencia — revisar o borrador", + "Cube": "Cubo", + "Current orthographic view (1:1 mm)": "Vista ortográfica actual (1:1 mm)", + "Current perspective view": "Vista en perspectiva actual", + "Curvature (G2)": "Curvatura (G2)", + "Customize Toolbar": "Personalizar a barra de ferramentas", + "Delete all": "Eliminar todo", + "Delete rule": "Eliminar a regra", + "Delete the row": "Eliminar a fila", + "Delete the set": "Eliminar o conxunto", + "Delete this parameter": "Eliminar este parámetro", + "Density": "Densidade", + "Designs you open or save appear here.": "Os deseños que abras ou gardes aparecen aquí.", + "Determined by To Object. Choose Angle to edit the angular extent.": "Determinado por Ata o obxecto. Escolle Ángulo para editar a extensión angular.", + "Discard": "Descartar", + "Do not export hidden edges": "Non exportar as arestas ocultas", + "Double-click to rename": "Dobre clic para renomear", + "Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "Dobre clic co botón central na vista: Inicio (a vista de inicio, encadrando o que se mostra), Axustar (encadrar o que se mostra mantendo a orientación) ou nada", + "Drive Joint": "Accionar a unión", + "Edges": "Arestas", + "Edit Profile Sketch": "Editar o bosquexo do perfil", + "Enable rule": "Activar a regra", + "Enabled": "Activado", + "Explode": "Explosionar", + "Export Animation…": "Exportar animación…", + "Export Current View as DXF": "Exportar a vista actual como DXF", + "Export Current View as DXF…": "Exportar a vista actual como DXF…", + "Export DXF…": "Exportar DXF…", + "Export hidden edges as dashed lines": "Exportar as arestas ocultas como liñas descontinuas", + "Extents": "Extensións", + "Face": "Cara", + "Face attachment lost": "Perdeuse a ancoraxe á cara", + "Faces": "Caras", + "Faces / edges / vertices": "Caras / arestas / vértices", + "Favourite": "Favorito", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Os ficheiros de moitos programas CAD teñen o Y cara arriba, así que aquí ábrense deitados (Z cara arriba).", + "Filter": "Filtro", + "Find in Browser": "Buscar no navegador", + "Flat": "Plano", + "Flat size": "Tamaño desenvolvido", + "Follow camera (Look At sketches)": "Seguir a cámara (Mirar cara aos bosquexos)", + "Follow the camera (Look At sketches)": "Seguir a cámara (Mirar cara aos bosquexos)", + "Font": "Tipo de letra", + "Full Length": "Lonxitude completa", + "Gap": "Separación", + "Grid": "Grella", + "Height": "Altura", + "Hidden edges": "Arestas ocultas", + "Holes": "Furados", + "Holes (edges on them)": "Furados (arestas sobre eles)", + "Home view": "Vista de inicio", + "In This Design": "Neste deseño", + "In place (surfaces)": "No sitio (superficies)", + "Inside": "Dentro", + "Interferes": "Interfire", + "Issue title": "Título da incidencia", + "Joint Origin1": "Orixe da unión1", + "Keep Tools": "Manter as ferramentas", + "Later": "Máis tarde", + "Leave it": "Deixalo", + "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Ancoraxe á cara antiga. Volver vincular a unha cara certificada crea unha ancoraxe exacta.", + "Length": "Lonxitude", + "Length units": "Unidades de lonxitude", + "Letter Spacing": "Espazado entre letras", + "Library": "Biblioteca", + "Line Spacing": "Espazado entre liñas", + "Loop": "Bucle", + "Margin": "Marxe", + "Mass": "Masa", + "Material": "Material", + "Max": "Máx.", + "Mid Radius": "Raio medio", + "Middle double-click": "Dobre clic central", + "Min": "Mín.", + "Mitre": "Inglete", + "Modeled": "Modelado", + "More toolbar panels": "Máis paneis da barra de ferramentas", + "Motion": "Movemento", + "Move Type": "Tipo de movemento", + "Move earlier": "Mover antes", + "Move later": "Mover despois", + "Name": "Nome", + "No crash reports.": "Non hai informes de fallos.", + "No matching appearances": "Non hai aparencias coincidentes", + "No visible bodies to export.": "Non hai corpos visibles para exportar.", + "None": "Ningún", + "Not available yet": "Aínda non dispoñible", + "Notch": "Entalle", + "Opacity": "Opacidade", + "Open GitHub draft": "Abrir o borrador de GitHub", + "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código aberto en Rust. Con licenza MIT OR Apache-2.0.", + "Other side": "Outro lado", + "Outside": "Fóra", + "Overall length": "Lonxitude total", + "Parameter values": "Valores dos parámetros", + "Pass through": "Atravesar", + "Path": "Traxectoria", + "Per Edge": "Por aresta", + "Pick the tool bodies": "Escolle os corpos ferramenta", + "Picked": "Escollido", + "Place at the origin instead": "Colocar na orixe no seu lugar", + "Playback": "Reprodución", + "Position": "Posición", + "Position (0 to 1)": "Posición (de 0 a 1)", + "Position (G0)": "Posición (G0)", + "Position along the edge, 0 at the start end, 1 at the other": "Posición ao longo da aresta, 0 no extremo inicial e 1 no outro", + "Preview Row": "Previsualizar a fila", + "Preview leaves the current design unchanged.": "A previsualización non cambia o deseño actual.", + "Profiles/Curves": "Perfís/curvas", + "Projection": "Proxección", + "RECENT": "RECENTES", + "RULED SURFACE": "SUPERFICIE REGRADA", + "Radius Fit": "Axuste do raio", + "Ratio": "Proporción", + "Reattach selected face": "Volver ancorar a cara seleccionada", + "Recover": "Recuperar", + "Recover unsaved design?": "Recuperar o deseño sen gardar?", + "Rectangular": "Rectangular", + "Reference face": "Cara de referencia", + "Remove Tools": "Quitar as ferramentas", + "Remove from list": "Quitar da lista", + "Remove override": "Quitar a substitución", + "Remove private design details or paths before sharing.": "Elimina os detalles privados do deseño ou as rutas antes de compartir.", + "Remove screenshot": "Quitar a captura de pantalla", + "Remove the column": "Quitar a columna", + "Remove the track": "Quitar a pista", + "Remove this point": "Quitar este punto", + "Report a bug — review a screenshot and open a GitHub draft": "Informar dun erro — revisar unha captura e abrir un borrador en GitHub", + "Reset Toolbar": "Restablecer a barra de ferramentas", + "Restore outer boundary": "Restaurar o contorno exterior", + "Restore the inherited component or physical material appearance": "Restaurar a aparencia herdada do compoñente ou do material físico", + "Result": "Resultado", + "Retake screenshot": "Repetir a captura de pantalla", + "Reverse": "Inverter", + "Reverse Direction": "Inverter a dirección", + "Revert": "Reverter", + "Revert All Positions": "Reverter todas as posicións", + "Revert Position": "Reverter a posición", + "Review the report and screenshot before opening GitHub.": "Revisa o informe e a captura de pantalla antes de abrir GitHub.", + "Rim Edge": "Aresta do bordo", + "Roll History Marker Here": "Levar o marcador do historial aquí", + "Round": "Redondo", + "Rule": "Regra", + "Save Rule": "Gardar a regra", + "Save the study as an animated GIF, seen as the viewport shows it": "Gardar o estudo como GIF animado, tal e como o mostra a vista", + "Saved preview. Geometry is being checked before editing.": "Previsualización gardada. Estase a comprobar a xeometría antes de editar.", + "Scale factor": "Factor de escala", + "Search": "Buscar", + "Search commands": "Buscar ordes", + "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Seleccionar outro: mantén o botón esquerdo quieto sobre o modelo (ou clic dereito › Seleccionar outro…) para listar todo o que hai baixo o cursor; fai clic de novo no mesmo punto para seleccionar o seguinte. Fai dobre clic co botón central para ir ao Inicio (Preferencias › Navegación).", + "Select bodies (a face picks its body)": "Selecciona corpos (unha cara escolle o seu corpo)", + "Select bodies or faces instead": "Seleccionar corpos ou caras no seu lugar", + "Selection filter": "Filtro de selección", + "Semantic faces share their appearance across instances.": "As caras semánticas comparten a súa aparencia entre instancias.", + "Send your report on GitHub": "Envía o informe en GitHub", + "Shape": "Forma", + "Show Agent Cursor": "Mostrar o cursor do axente", + "Show in folder": "Mostrar no cartafol", + "Show the pointer an AI agent moves (#35)": "Mostrar o punteiro que move un axente de IA (#35)", + "Signed axes": "Eixes con signo", + "Size": "Tamaño", + "Sketch constraints": "Restricións do bosquexo", + "Sketch curves": "Curvas do bosquexo", + "Sketch dimensions": "Cotas do bosquexo", + "Sketch geometry and profiles": "Xeometría e perfís do bosquexo", + "Sketch plane has no body-face attachment.": "O plano do bosquexo non está ancorado a ningunha cara dun corpo.", + "Sketch points": "Puntos do bosquexo", + "Slot width": "Largura da ranura", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft pechouse antes de gardar estes deseños. Pódese abrir a súa última gravación automática.", + "Speed": "Velocidade", + "Stand it up": "Poñela de pé", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Poñela de pé: un cuarto de volta arredor de X, como unha operación Mover que podes desfacer.", + "Stand this part up?": "Poñer esta peza de pé?", + "Step": "Paso", + "Steps": "Pasos", + "Style": "Estilo", + "Suppressed": "Suprimida", + "Swap Ends": "Intercambiar os extremos", + "Tangent (G1)": "Tanxente (G1)", + "Tangent Chain": "Cadea tanxente", + "Tear": "Rasgado", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "O bosquexo descontinuo é unha guía de plano gardada. Selecciona unha cara nova para reparar a ancoraxe.", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "Falta a aparición do autor gardada. Selecciona unha colocación de autor válida antes de volver vincular.", + "Then": "Entón", + "These features will be deleted:": "Eliminaranse estas operacións:", + "These features will fail:": "Fallarán estas operacións:", + "Thickness Outside": "Espesor cara a fóra", + "Thin": "Delgado", + "Thin Extrude": "Extrusión delgada", + "This child is shared. Deleting it removes it from every copy of its parent.": "Este fillo está compartido. Eliminalo quítao de todas as copias do seu pai.", + "This child is shared. Position changes apply to every copy of its parent.": "Este fillo está compartido. Os cambios de posición aplícanse a todas as copias do seu pai.", + "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Esta cara non pode ofrecer unha ancoraxe duradeira. Escolle outra cara ou usa expresamente un plano fixo.", + "To Offset": "Ata o desprazamento", + "Tolerance": "Tolerancia", + "Turn off section analysis before exporting the view.": "Desactiva a análise de sección antes de exportar a vista.", + "Type": "Tipo", + "UNTRIM": "DESRECORTAR", + "Updating the preview": "Actualizando a previsualización", + "Use active author placement": "Usar a colocación de autor activa", + "Use fixed plane": "Usar un plano fixo", + "Use saved fixed plane": "Usar o plano fixo gardado", + "Use selected face as fixed plane": "Usar a cara seleccionada como plano fixo", + "VIEW": "VISTA", + "Value": "Valor", + "Vertices": "Vértices", + "View navigator": "Navegador de vistas", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Só os corpos visibles. As curvas usan segmentos de liña (tolerancia de 0,01 mm).", + "Volume": "Volume", + "Wall": "Parede", + "Wall Location": "Situación da parede", + "Wall Thickness": "Espesor da parede", + "When": "Cando", + "Width": "Largura", + "Will fail": "Fallará", + "angle, height": "ángulo, altura", + "appearance.dielectric_ior": "IOR dieléctrico", + "appearance.metallic": "Metálico", + "appearance.pbr_help": "Ve esta superficie en Render ou nun PNG de produto. Sen refracción nin transmisión.", + "appearance.pbr_opaque": "PBR opaco", + "appearance.roughness": "Rugosidade", + "appearance.surface_response": "Resposta da superficie", + "browser.body_name": "Corpo{number}", + "browser.component_name": "Compoñente{number}", + "browser.parameters": "Parámetros ({count})", + "browser.precision": "Precisión: {precision}", + "browser.sketch_name": "Bosquexo{number}", + "browser.units": "Unidades: {units}", + "cam.flat": "Cara plana", + "cam.follower": "Seguidor", + "cam.knife": "Gume de coitelo", + "cam.needs_joints": "precisa unha unión que xire e outra que esvare ou oscile", + "cam.roller": "Rolete", + "cam.roller_pick": "Rolete (opcional)", + "cam.tip_pick": "Punta (opcional)", + "cmd.appearance_assign": "Aparencia", + "cmd.appearance_library": "Biblioteca de aparencias", + "cmd.appearance_list": "Listar as aparencias", + "cmd.body_rename": "Renomear o corpo", + "cmd.browser_group": "Grupo novo", + "cmd.browser_move": "Mover elementos do navegador", + "cmd.browser_order": "Ordenar elementos do navegador", + "cmd.browser_rename_group": "Renomear o grupo", + "cmd.browser_ungroup": "Desagrupar", + "cmd.browser_visibility": "Mostrar/Ocultar", + "cmd.canvas_calibrate": "Calibrar o lenzo", + "cmd.canvas_decal": "Calcomanía", + "cmd.canvas_delete": "Eliminar o lenzo", + "cmd.canvas_edit": "Editar o lenzo", + "cmd.canvas_insert": "Lenzo", + "cmd.component_activate": "Activar o compoñente", + "cmd.component_break_link": "Romper a ligazón", + "cmd.component_capture_position": "Capturar a posición", + "cmd.component_create": "Compoñente novo", + "cmd.component_delete": "Eliminar o compoñente", + "cmd.component_from_bodies": "Crear compoñentes a partir de corpos", + "cmd.component_insert_design": "Inserir deseño", + "cmd.component_links": "Listar as ligazóns", + "cmd.component_list": "Listar os compoñentes", + "cmd.component_move_bodies": "Mover corpos ao compoñente", + "cmd.component_move_sketches": "Mover bosquexos ao compoñente", + "cmd.component_paste_new": "Pegar como novo", + "cmd.component_properties": "Propiedades físicas do compoñente", + "cmd.component_rename": "Renomear o compoñente", + "cmd.component_revert_position": "Reverter a posición", + "cmd.component_unlock": "Desbloquear o contido", + "cmd.component_update_links": "Actualizar as ligazóns", + "cmd.config_activate": "Activar a configuración", + "cmd.config_column": "Columna de configuración", + "cmd.config_configure": "Configurar", + "cmd.config_preview": "Previsualizar a configuración", + "cmd.config_row": "Fila de configuración", + "cmd.config_rule": "Regra de configuración", + "cmd.config_rules": "Regras de configuración", + "cmd.config_table": "Mostrar a táboa de configuracións", + "cmd.construct_axis_edge": "Eixe pola aresta", + "cmd.construct_axis_normal_to_face": "Eixe perpendicular á cara", + "cmd.construct_axis_through_cylinder": "Eixe por cilindro/cono/toro", + "cmd.construct_axis_two_planes": "Eixe por dous planos", + "cmd.construct_axis_two_points": "Eixe por dous puntos", + "cmd.construct_plane_along_path": "Plano ao longo da traxectoria", + "cmd.construct_plane_midplane": "Plano medio", + "cmd.construct_plane_perpendicular": "Plano perpendicular", + "cmd.construct_plane_tangent": "Plano tanxente", + "cmd.construct_plane_three_points": "Plano por tres puntos", + "cmd.construct_plane_two_edges": "Plano por dúas arestas", + "cmd.construct_point_along_path": "Punto ao longo da traxectoria", + "cmd.construct_point_center": "Punto no centro de círculo/esfera/toro", + "cmd.construct_point_edge_plane": "Punto en aresta e plano", + "cmd.construct_point_three_planes": "Punto por tres planos", + "cmd.construct_point_two_edges": "Punto por dúas arestas", + "cmd.construct_point_vertex": "Punto no vértice", + "cmd.contact_check": "Comprobar o contacto", + "cmd.contact_create": "Conxunto de contacto novo", + "cmd.contact_disable_all": "Desactivar o contacto", + "cmd.contact_edit": "Editar o conxunto de contacto", + "cmd.contact_enable_all": "Activar todo o contacto", + "cmd.contact_enable_sets": "Activar os conxuntos de contacto", + "cmd.contact_list": "Listar os conxuntos de contacto", + "cmd.diagnostics_crash_report": "Informe de fallo", + "cmd.diagnostics_crash_reports": "Informes de fallos", + "cmd.diagnostics_crash_reports_clear": "Eliminar os informes de fallos", + "cmd.diagnostics_crash_test": "Proba de fallo", + "cmd.doc_recover": "Recuperar o deseño", + "cmd.doc_recovery_discard": "Descartar o deseño recuperado", + "cmd.doc_recovery_list": "Deseños recuperables", + "cmd.document_inspect": "Inspeccionar o deseño", + "cmd.document_metadata": "Propiedades do deseño", + "cmd.document_metadata_remove": "Quitar unha propiedade do deseño", + "cmd.document_metadata_set": "Cambiar as propiedades do deseño", + "cmd.document_units": "Cambiar as unidades do deseño", + "cmd.edit_checkpoint": "Punto de control", + "cmd.edit_restore_checkpoint": "Restaurar o punto de control", + "cmd.engine_commands": "Listar as ordes", + "cmd.explode_create": "Vista explosionada", + "cmd.explode_delete": "Eliminar a vista explosionada", + "cmd.explode_list": "Listar as vistas explosionadas", + "cmd.explode_show": "Mostrar a vista explosionada", + "cmd.expr_evaluate": "Avaliar a expresión", + "cmd.face_delete": "Eliminar a cara", + "cmd.file_export": "Exportar", + "cmd.file_insert_mesh": "Inserir malla", + "cmd.file_insert_step": "Inserir STEP", + "cmd.file_save_mesh": "Gardar como malla", + "cmd.file_slicers": "Laminadores instalados", + "cmd.inspect_accessibility": "Análise de accesibilidade", + "cmd.inspect_center_of_mass": "Centro de masas", + "cmd.inspect_compare": "Comparar corpos", + "cmd.inspect_continuity": "Análise de continuidade", + "cmd.inspect_curvature_comb": "Análise con pente de curvatura", + "cmd.inspect_curvature_map": "Análise con mapa de curvatura", + "cmd.inspect_draft": "Análise de ángulo de desmoldaxe", + "cmd.inspect_environment_map": "Análise con mapa de contorno", + "cmd.inspect_interference": "Interferencia", + "cmd.inspect_isocurve": "Análise de isocurvas", + "cmd.inspect_minimum_radius": "Análise de raio mínimo", + "cmd.inspect_zebra": "Análise cebra", + "cmd.joint_as_built": "Unión tal como está", + "cmd.joint_cam": "Leva", + "cmd.joint_create": "Unión", + "cmd.joint_delete": "Eliminar a unión", + "cmd.joint_drive": "Accionar as unións", + "cmd.joint_edit": "Editar a unión", + "cmd.joint_gear": "Engrenaxe", + "cmd.joint_limits": "Límites da unión", + "cmd.joint_list": "Listar as unións", + "cmd.joint_motion_link": "Vínculo de movemento", + "cmd.joint_origin": "Orixe da unión", + "cmd.joint_rack_pinion": "Cremalleira e piñón", + "cmd.joint_reach": "Punto de alcance", + "cmd.joint_rigid_group": "Grupo ríxido", + "cmd.joint_screw": "Parafuso", + "cmd.joint_solve": "Resolver as unións", + "cmd.library_apply": "Aplicar unha entrada da biblioteca local", + "cmd.library_export": "Exportar a biblioteca do deseño", + "cmd.library_inspect": "Inspeccionar a biblioteca local", + "cmd.material_assign": "Material físico", + "cmd.material_create": "Material físico novo", + "cmd.material_delete": "Eliminar o material físico", + "cmd.material_edit": "Editar o material físico", + "cmd.material_list": "Listar os materiais", + "cmd.material_properties_directional": "Módulo elástico direccional", + "cmd.material_properties_validate": "Validar os datos do material físico", + "cmd.mesh_convert": "Converter a malla", + "cmd.model_edges": "Listar as arestas", + "cmd.model_faces": "Listar as caras", + "cmd.model_threads": "Listar as roscas", + "cmd.motion_delete": "Eliminar o estudo de movemento", + "cmd.motion_export": "Exportar o estudo de movemento", + "cmd.motion_export_animation": "Exportar a animación do movemento", + "cmd.motion_list": "Listar os estudos de movemento", + "cmd.motion_play": "Reproducir o estudo de movemento", + "cmd.motion_study": "Estudo de movemento", + "cmd.motion_trace": "Traxectoria do movemento", + "cmd.motion_trace_keep": "Manter a traxectoria do movemento", + "cmd.occurrence_copy": "Pegar (instancia)", + "cmd.occurrence_ground": "Fixar ao chan", + "cmd.occurrence_move": "Mover a aparición", + "cmd.occurrence_properties": "Propiedades físicas da aparición", + "cmd.parameters_add": "Engadir parámetro de usuario", + "cmd.parameters_change": "Cambiar os parámetros", + "cmd.parameters_comment": "Comentar o parámetro", + "cmd.parameters_complete": "Completar a expresión", + "cmd.parameters_delete": "Eliminar o parámetro", + "cmd.parameters_export": "Exportar os parámetros", + "cmd.parameters_favorite": "Parámetro favorito", + "cmd.parameters_graph": "Gráfico de parámetros", + "cmd.parameters_import": "Importar parámetros", + "cmd.parameters_list": "Listar os parámetros", + "cmd.parameters_move": "Mover o parámetro", + "cmd.parameters_rename": "Renomear o parámetro", + "cmd.parameters_users": "Usos do parámetro", + "cmd.parts_fastener": "Inserir elemento de fixación", + "cmd.parts_insert": "Inserir peza", + "cmd.parts_library": "Pezas normalizadas", + "cmd.parts_resize": "Cambiar o tamaño da peza", + "cmd.plastic_assign_rule": "Asignar regra de plástico", + "cmd.plastic_boss": "Saínte", + "cmd.plastic_lip": "Beizo", + "cmd.plastic_manage_rules": "Xestionar as regras de plástico", + "cmd.plastic_rest": "Apoio", + "cmd.plastic_rules": "Listar as regras de plástico", + "cmd.plastic_snap_fit": "Encaixe a presión", + "cmd.render_backends": "Motores de render", + "cmd.render_cancel": "Cancelar o render", + "cmd.render_export": "Exportar a imaxe do render", + "cmd.render_preflight": "Comprobar a solicitude de render", + "cmd.render_scene": "Inspeccionar a escena do render", + "cmd.render_settings_apply": "Aplicar a cámara do render", + "cmd.render_settings_get": "Axustes do render", + "cmd.render_settings_set": "Gardar os axustes do render", + "cmd.render_start": "Renderizar imaxe", + "cmd.render_status": "Progreso do render", + "cmd.select_clear": "Borrar a selección", + "cmd.sheet_convert": "Converter en chapa", + "cmd.sheet_export_bend_table": "Exportar a táboa de dobras", + "cmd.sheet_export_dxf": "Exportar o desenvolvemento como DXF", + "cmd.sheet_flange": "Pestana", + "cmd.sheet_flat_pattern": "Crear o desenvolvemento", + "cmd.sheet_fold": "Dobrar", + "cmd.sheet_hem": "Dobradillo", + "cmd.sheet_manage_rules": "Regras de chapa", + "cmd.sheet_perforate": "Perforar", + "cmd.sheet_refold": "Volver dobrar", + "cmd.sheet_rules": "Listar as regras de chapa", + "cmd.sheet_unfold": "Despregar", + "cmd.sketch_arc_center_point": "Arco por punto central", + "cmd.sketch_arc_tangent": "Arco tanxente", + "cmd.sketch_arc_three_point": "Arco por 3 puntos", + "cmd.sketch_auto_constrain": "Restrición automática", + "cmd.sketch_auto_constrain_from_datum": "Restrición automática desde a referencia", + "cmd.sketch_auto_project": "Proxectar automaticamente as arestas na referencia", + "cmd.sketch_blend_curve": "Curva de transición", + "cmd.sketch_chain": "Cadea", + "cmd.sketch_chamfer_distance_angle": "Chafrán por distancia e ángulo", + "cmd.sketch_chamfer_equal_distance": "Chafrán de distancias iguais", + "cmd.sketch_chamfer_two_distance": "Chafrán de dúas distancias", + "cmd.sketch_circle_center": "Círculo por centro e diámetro", + "cmd.sketch_circle_three_point": "Círculo por 3 puntos", + "cmd.sketch_circle_three_tangent": "Círculo tanxente a 3", + "cmd.sketch_circle_two_point": "Círculo por 2 puntos", + "cmd.sketch_circle_two_tangent": "Círculo tanxente a 2", + "cmd.sketch_constrainer": "Asistente de restricións do bosquexo", + "cmd.sketch_constraint_fix": "Fixar/Liberar", + "cmd.sketch_constraint_midpoint": "Punto medio", + "cmd.sketch_construction": "Normal/Construción", + "cmd.sketch_copy": "Copiar entidades do bosquexo", + "cmd.sketch_cut": "Cortar entidades do bosquexo", + "cmd.sketch_delete": "Eliminar entidades do bosquexo", + "cmd.sketch_dimension_text": "Mover o texto da cota", + "cmd.sketch_drag": "Arrastrar xeometría do bosquexo", + "cmd.sketch_drag_end": "Rematar o arrastre no bosquexo", + "cmd.sketch_draw_dimensioned": "Debuxar xeometría do bosquexo con cotas", + "cmd.sketch_edit": "Editar o bosquexo", + "cmd.sketch_edit_text": "Editar o texto", + "cmd.sketch_export_dxf": "Gardar como DXF", + "cmd.sketch_finish_auto_constrain": "Rematar con restrición automática", + "cmd.sketch_fit_curves_to_section": "Axustar curvas a unha sección de malla", + "cmd.sketch_glyphs": "Iconas de restricións", + "cmd.sketch_include_3d": "Incluír xeometría 3D", + "cmd.sketch_infinite": "Liña infinita", + "cmd.sketch_insert_dxf": "Inserir DXF", + "cmd.sketch_insert_svg": "Inserir SVG", + "cmd.sketch_inspect": "Inspeccionar o bosquexo", + "cmd.sketch_intersection_curve": "Curva de intersección", + "cmd.sketch_isoparametric_curve": "Curva isoparamétrica", + "cmd.sketch_line3d": "Liña 3D", + "cmd.sketch_line_midpoint": "Liña desde o punto medio", + "cmd.sketch_move": "Mover/Copiar entidades do bosquexo", + "cmd.sketch_move3d": "Mover punto 3D", + "cmd.sketch_move_point": "Arrastrar punto do bosquexo", + "cmd.sketch_offset_break": "Romper a asociación do desprazamento", + "cmd.sketch_options": "Opcións da paleta do bosquexo", + "cmd.sketch_paste": "Pegar entidades do bosquexo", + "cmd.sketch_point3d": "Punto 3D", + "cmd.sketch_polygon_circumscribed": "Polígono circunscrito", + "cmd.sketch_polygon_edge": "Polígono por aresta", + "cmd.sketch_polygon_inscribed": "Polígono inscrito", + "cmd.sketch_project_to_surface": "Proxectar na superficie", + "cmd.sketch_rectangle_center": "Rectángulo desde o centro", + "cmd.sketch_rectangle_rounded": "Rectángulo redondeado", + "cmd.sketch_rectangle_three_point": "Rectángulo por 3 puntos", + "cmd.sketch_rectangle_two_point": "Rectángulo por 2 puntos", + "cmd.sketch_redefine": "Redefinir o plano do bosquexo", + "cmd.sketch_slot_arc_center": "Ranura en arco por punto central", + "cmd.sketch_slot_arc_three_point": "Ranura en arco por tres puntos", + "cmd.sketch_slot_center_point": "Ranura por punto central", + "cmd.sketch_slot_center_to_center": "Ranura de centro a centro", + "cmd.sketch_slot_overall": "Ranura total", + "cmd.sketch_snap": "Inferencia de axuste", + "cmd.sketch_solve": "Resolver o bosquexo", + "cmd.sketch_spline3d": "Spline 3D", + "cmd.sketch_spline_control_point": "Spline por puntos de control", + "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_spun_profile": "Perfil de revolución", + "cmd.sketch_toggle_driven": "Alternar cota conducida", + "cmd.solid_align": "Aliñar", + "cmd.solid_boundary_fill": "Encher contorno", + "cmd.solid_bounding_solid": "Sólido envolvente", + "cmd.solid_emboss": "Gravar en relevo", + "cmd.solid_move": "Mover/Copiar", + "cmd.solid_offset_face": "Desprazar a cara", + "cmd.solid_press_pull": "Empurrar/Tirar", + "cmd.solid_remove": "Quitar", + "cmd.solid_replace_face": "Substituír a cara", + "cmd.solid_rib": "Nervio", + "cmd.solid_split_face": "Dividir a cara", + "cmd.solid_web": "Alma", + "cmd.surface_blend": "Superficie de transición", + "cmd.surface_boundary": "Superficie de contorno", + "cmd.surface_extrude": "Extrusión de superficie", + "cmd.surface_fair": "Suavizar a superficie", + "cmd.surface_fillet": "Arredondamento de superficie", + "cmd.surface_loft": "Transición de superficie", + "cmd.surface_match": "Igualar a superficie", + "cmd.surface_offset": "Superficie desprazada", + "cmd.surface_patch": "Parche", + "cmd.surface_reverse_normal": "Inverter a normal", + "cmd.surface_revolve": "Revolución de superficie", + "cmd.surface_ruled": "Superficie regrada", + "cmd.surface_stitch": "Coser", + "cmd.surface_sweep": "Varrido de superficie", + "cmd.surface_thicken": "Engrosar", + "cmd.surface_unstitch": "Descoser", + "cmd.surface_untrim": "Desrecortar", + "cmd.timeline_add": "Engadir operación gravada", + "cmd.timeline_compute_all": "Calcular todo", + "cmd.timeline_copy": "Copiar operacións", + "cmd.timeline_dependents": "Dependentes da operación", + "cmd.timeline_export_script": "Exportar o script de ordes", + "cmd.timeline_inspect": "Inspeccionar a operación", + "cmd.timeline_paste": "Pegar operacións", + "cmd.timeline_redefine": "Editar a operación", + "cmd.timeline_rename": "Renomear", + "cmd.timeline_reorder": "Reordenar a operación", + "cmd.timeline_roll_to": "Levar o marcador do historial", + "cmd.timeline_rollback": "Mover o marcador da liña de tempo", + "cmd.timeline_suppress": "Suprimir a operación", + "cmd.view_apply": "Restaurar a vista con nome", + "cmd.view_delete": "Eliminar a vista con nome", + "cmd.view_list": "Listar as vistas con nome", + "cmd.view_navigate": "Navegar pola vista", + "cmd.view_rename": "Renomear a vista con nome", + "cmd.view_save": "Vista con nome nova", + "command name": "nome da orde", + "coupling.gear_1": "Engrenaxe 1", + "coupling.gear_1_pick": "Engrenaxe 1 (opcional)", + "coupling.gear_2": "Engrenaxe 2", + "coupling.gear_2_pick": "Engrenaxe 2 (opcional)", + "coupling.internal": "Engrenaxe interna", + "coupling.needs_turn_and_slide": "precisa unha unión que xire e outra que esvare", + "coupling.needs_turns": "precisa dúas unións que xiren", + "coupling.not_round": "non é unha cara redonda", + "coupling.nut": "Porca", + "coupling.picked": "escollido", + "coupling.pinion": "Piñón", + "coupling.pinion_pick": "Piñón (opcional)", + "coupling.pitch": "Paso", + "coupling.rack": "Cremalleira", + "coupling.radius_1": "Raio 1", + "coupling.radius_2": "Raio 2", + "dialog.computing": "Calculando… {seconds} s", + "dialog.custom_axis": "↖ Eixe personalizado", + "dialog.edit_title": "EDITAR {title}", + "dialog.select": "↖ Seleccionar", + "dialog.selected_count": "↖ {count} seleccionados", + "dialog.selection_guidance": "Selecciona unha entrada para cambiala. Fai clic nos obxectos seleccionados para quitalos; Ctrl/Cmd-clic tamén os alterna. Revisa a previsualización e preme Aceptar.", + "dialog.selection_step": "{step} de {total}: selecciona {input}", + "dialog.step": "Paso", + "document.save_changes": "Gardar os cambios en {name}?", + "document.unsaved_changes": "{name} ten cambios sen gardar. Se non os gardas, perderanse.", + "drive.stopped_by_contact": "Detido en {value}: {a} atravesaría {b}", + "drive.stopped_by_loop": "Detido en {value}: o bucle a través de {joint} non pode pecharse máis", + "drive.unconnected": "Non move nada: {part} non está conectado a nada fixado", + "dxf.cancel_wait": "Agardando a que se deteña a exportación…", + "dxf.cancelled": "Exportación DXF cancelada", + "dxf.cancelling": "Cancelando a exportación DXF", + "dxf.exporting": "Exportando DXF", + "dxf.invalid_tolerance": "A tolerancia da curva debe estar entre 0,0001 e 1 mm.", + "dxf.progress.index": "Preparando as superficies (2/5)", + "dxf.progress.meshes": "Preparando as mallas (1/5)", + "dxf.progress.occlusion": "Resolvendo as liñas ocultas (4/5)", + "dxf.progress.projection": "Proxectando a xeometría (3/5)", + "dxf.progress.write": "Escribindo o DXF (5/5)", + "dxf.tolerance": "Tolerancia da curva", + "dxf.tolerance_help": "Só os corpos visibles. As curvas usan segmentos rectos. Unha tolerancia menor dá curvas máis finas e usa máis tempo e memoria.", + "expression, e.g. 25 mm": "expresión, p. ex. 25 mm", + "fits the face, e.g. M8": "encaixa na cara, p. ex. M8", + "from the rule": "da regra", + "home.documentation": "Documentación", + "home.in_this_browser": "neste navegador", + "home.missing": "non atopado", + "home.open": "Abrir…", + "home.opened_days_ago": "Aberto hai {count} días", + "home.opened_hours_ago": "Aberto hai {count} h", + "home.opened_just_now": "Aberto agora mesmo", + "home.opened_minutes_ago": "Aberto hai {count} min", + "home.opening": "abrindo…", + "home.recent": "Recentes", + "home.report_issue": "Informar dunha incidencia", + "home.samples": "Exemplos", + "home.whats_new": "Novidades", + "install.button_tip": "Instala SolidCraft como aplicación: ábrese na súa propia xanela e funciona sen conexión", + "install.dock_1": "Escolle Ficheiro › Engadir ao Dock.", + "install.dock_2": "Fai clic en Engadir.", + "install.dock_after": "Despois, SolidCraft ábrese na súa propia xanela desde o Dock e funciona sen conexión.", + "install.done": "Feito", + "install.home_screen_1": "Toca Compartir (no menú … se non está na barra de ferramentas).", + "install.home_screen_2": "Escolle Engadir á pantalla de inicio.", + "install.home_screen_3": "Toca Engadir.", + "install.home_screen_after": "Despois, SolidCraft ábrese desde a súa icona na pantalla de inicio, sen as barras de Safari, e funciona sen conexión.", + "install.menu": "Instalar a aplicación…", + "install.steps_intro": "Safari instala as aplicacións web desde os seus propios menús:", + "install.title": "Instalar SolidCraft", + "joint.from_bodies_hint": "Cada corpo escollido pasa a un compoñente novo propio e queda onde está.", + "joint.one_body": "As dúas seleccións están en {body}. Escolle a segunda noutra peza.", + "joint.one_component": "Estas pezas son corpos dun mesmo compoñente: {bodies}. Unha unión move un compoñente respecto doutro, así que cada peza precisa o seu propio compoñente.", + "nav.touchpad.help": "Mantén Maiús e move o punteiro para desprazar; mantén Alt/Opción e móveo para orbitar. Non fai falta ningún botón do rato. O desprazamento vertical fai zoom.", + "nav.touchpad.label": "Panel táctil", + "nav.touchpad.orbit": "Orbitar (mantén Alt/Opción e move; sen botón do rato)", + "nav.touchpad.pan": "Desprazar (mantén Maiús e move; sen botón do rato)", + "nav.touchpad.scroll": "O panel táctil usa o desprazamento vertical para facer zoom. A túa configuración de desprazamento con dous dedos mantense para os outros axustes predefinidos.", + "nav.touchpad.zoom": "Zoom (desprazamento vertical ou pinza)", + "needs two joints": "precisa dúas unións", + "new configuration": "configuración nova", + "new name": "nome novo", + "new parameter": "parámetro novo", + "no interference": "sen interferencias", + "no joint that moves yet": "aínda non hai ningunha unión que se mova", + "no picture": "sen imaxe", + "pattern.alignment_2": "Aliñamento 2", + "pattern.alignment_hint": "O número inclúe o orixinal. Centrar equilibra as copias; Inverter escolle o lado da copia extra cando o total é par.", + "pattern.direction_1": "Dirección 1", + "pattern.direction_2": "Dirección 2", + "pattern.flip_direction": "Inverter a dirección", + "pick a hole to seat it, or OK places it at the origin": "escolle un furado onde asentala, ou Aceptar colócaa na orixe", + "pick one or two vertices, edges or faces": "escolle un ou dous vértices, arestas ou caras", + "render.background": "Fondo da escena", + "render.fit": "Encadrar o produto", + "render.image_cancel": "Cancelar o render", + "render.image_cancelled": "Render cancelado", + "render.image_cancelling": "Cancelando", + "render.image_check": "Comprobar a solicitude de render", + "render.image_completed": "Imaxe lista para exportar", + "render.image_encoding": "Codificando o PNG", + "render.image_export": "Exportar PNG", + "render.image_failed": "Fallou o render", + "render.image_height": "Altura", + "render.image_help": "Imaxe de previsualización por CPU · PNG · transparencia aproximada", + "render.image_overwrite": "Substituír o ficheiro existente", + "render.image_preparing": "Preparando a imaxe", + "render.image_queued": "Agardando para renderizar", + "render.image_reduce": "Proba cunha imaxe máis pequena ou unha escena máis sinxela.", + "render.image_running": "Renderizando a imaxe", + "render.image_stale": "Esta imaxe usa a escena capturada antes dos cambios posteriores.", + "render.image_start": "Iniciar o render", + "render.image_supported": "A solicitude de render é compatible; a cola e a memoria comprobaranse de novo ao comezar.", + "render.image_title": "Renderizar imaxe", + "render.image_too_large": "Supera o límite de imaxe: 4096 píxeles por lado e 4.194.304 píxeles en total.", + "render.image_transparent": "Fondo transparente", + "render.image_unknown": "Estado do render non dispoñible", + "render.image_use_largest": "Usar o tamaño máis grande con esta proporción:", + "render.image_width": "Largura", + "render.navigation_help": "A cámara móvese como en Deseño (Preferencias › Navegación). Gardar configuración rexistra a cámara actual.", + "render.opaque_image_summary": "PNG de previsualización · PBR opaco · transparencia mesturada", + "render.opaque_preview_help": "PBR opaco e cores simples; transparencia mesturada. A refracción, o HDRI e o render final aínda non están dispoñibles.", + "render.perspective": "Cámara en perspectiva", + "render.preview": "Previsualización integrada", + "render.preview_help": "Sombreado ráster e transparencia mesturada. A refracción, o HDRI e o render final aínda non están dispoñibles.", + "render.reload_settings": "Volver cargar os axustes gardados", + "render.restore_camera": "Restaurar a cámara gardada", + "render.return_design": "Volver a Deseño", + "render.save_setup": "Gardar configuración", + "render.setup_name": "Nome da configuración", + "render.unavailable_preview": "Esta configuración pide un perfil de previsualización non dispoñible.", + "render.unsaved": "Cambios da previsualización sen gardar", + "render.use_preview": "Usar a previsualización integrada", + "sample.bracket.about": "Pestana base con pestanas de aresta e un dobradillo cunha regra de 2 mm", + "sample.bracket.name": "Escuadra de chapa", + "sample.enclosure.about": "Caixa baleirada cun beizo, saíntes para parafusos, un apoio e un encaixe a presión", + "sample.enclosure.name": "Carcasa de plástico", + "sample.flange.about": "Cubo e brida cun patrón circular controlado por un parámetro", + "sample.flange.name": "Brida aparafusada", + "sample.hinge.about": "Dous compoñentes e unha unión de revolución, levada a 60°", + "sample.hinge.name": "Conxunto de bisagra", + "sample.plate.about": "Placa paramétrica con arredondamentos, furados e un saínte mandrilado", + "sample.plate.name": "Placa de exemplo", + "sample.vents.about": "Ranuras nun patrón rectangular: filas, columnas e paso son parámetros", + "sample.vents.name": "Placa de ventilación", + "settings.display_quality_note": "Os niveis máis finos debuxan as caras e arestas curvas máis suaves e tardan máis en xerar a malla. Só cambia a vista, nunca o deseño nin as exportacións.", + "settings.frame_rate_note": "Mostra as imaxes por segundo na esquina inferior dereita da vista. Mentres está activado, a vista redebúxase continuamente.", + "settings.measure_axis_distances": "Mostrar as distancias en X/Y/Z", + "settings.measure_axis_distances_help": "Mostra as compoñentes da distancia segundo os eixes do mundo xunto á distancia total mentres Medir está aberto.", + "settings.msaa_applies_on_restart": "O antialiasing aplicarase a próxima vez que se inicie SolidCraft", + "settings.msaa_reset": "{setting}: este dispositivo gráfico non admite {requested}×; agora é {reset}× (admitidos: {supported}).", + "settings.msaa_unsupported": "Non admitido por este dispositivo gráfico", + "settings.reset_intro": "Estes axustes non funcionan neste ordenador e impedirían que SolidCraft se iniciase, así que se cambiaron:", + "settings.reset_title": "Cambiáronse os axustes", + "settings.supersampling_note": "Debuxa a vista a unha resolución maior e fíltraa cara abaixo: arestas, liñas e grella máis suaves en pantallas por debaixo de 4K. Consome tempo de GPU: uns 2,25× píxeles a 1,5× e 4× a 2×.", + "sketch.degrees_of_freedom": "{count} graos de liberdade", + "sketch.draw_curves": "Debuxar como {linetype}", + "sketch.make_selection": "Converter a selección en {linetype}", + "sketch_text.align_center": "Centro", + "sketch_text.align_left": "Esquerda", + "sketch_text.align_right": "Dereita", + "sketch_text.bold": "Negra", + "sketch_text.builtin_font": "{family} (integrado)", + "sketch_text.font_search": "Buscar tipos de letra", + "sketch_text.italic": "Cursiva", + "sketch_text.loading_fonts": "Buscando os tipos de letra instalados…", + "sketch_text.on_path": "O texto segue a súa traxectoria: a curva colócao", + "sketch_text.path_clear": "Separar o texto da súa curva", + "sketch_text.path_hint": "Unha curva do bosquexo que segue o texto: fai clic aquí e despois na curva", + "sketch_text.use_font_file": "Usar o ficheiro de tipo de letra {path}", + "the parts library is not available": "a biblioteca de pezas non está dispoñible", + "timeline.group": "Cartafol de operacións novo", + "timeline.move_many": "Mover elementos da liña de tempo", + "timeline.move_to_group": "Mover operacións ao cartafol", + "timeline.rename_group": "Renomear o cartafol de operacións", + "timeline.reorder_many": "Reordenar operacións", + "timeline.ungroup": "Quitar os cartafoles de operacións", + "to the next face": "ata a seguinte cara", + "toolbar.image": "IMAXE", + "toolbar.render": "RENDER", + "toolbar.render_scene": "ESCENA", + "trace.points": "{count} puntos ao longo da traxectoria", + "trace.stopped_by_contact": "Remata na mostra {sample}: {a} atravesaría {b}", + "trace.stopped_by_loop": "Remata na mostra {sample}: o bucle a través de {joint} non pode pecharse máis", + "ui.1_degree_of_freedom": "1 grao de liberdade", + "ui.3d_mouse_speed": "Velocidade do rato 3D", + "ui.3d_mouse_windows": "Rato 3D", + "ui.3d_sketch": "Bosquexo 3D", + "ui.about": "Acerca de", + "ui.activate": "Activar", + "ui.active_component": "Compoñente activo", + "ui.agent_chat": "Chat co axente", + "ui.agent_chat_allow": "Permitir", + "ui.agent_chat_allowed": "Permitido", + "ui.agent_chat_answered": "Resposta: {option}", + "ui.agent_chat_approval": "Permitir que o axente faga isto?", + "ui.agent_chat_attach_view": "Achegar a vista", + "ui.agent_chat_attach_view_tip": "Envía unha imaxe da vista actual coa mensaxe", + "ui.agent_chat_auth_agent": "Iniciar sesión con {name}", + "ui.agent_chat_auth_env": "Define {vars} no teu contorno e reinicia SolidCraft.", + "ui.agent_chat_auth_needed": "O axente pídeche que inicies sesión. Inicias sesión co propio axente; SolidCraft nunca ve o teu contrasinal nin as túas claves.", + "ui.agent_chat_auth_none": "O axente non ofrece aquí ningún método para iniciar sesión: inicia sesión como indica a súa propia documentación.", + "ui.agent_chat_auth_retry": "Xa iniciei sesión: conectar de novo", + "ui.agent_chat_auth_terminal": "Executa isto nun terminal e despois preme Conectar de novo:", + "ui.agent_chat_auth_title": "Iniciar sesión no axente", + "ui.agent_chat_cancel": "Cancelar", + "ui.agent_chat_changes": "Cambios: {n}, un só paso de desfacer", + "ui.agent_chat_changes_of": "{n}/{limit} cambios", + "ui.agent_chat_close": "Pechar", + "ui.agent_chat_command": "Orde do axente", + "ui.agent_chat_connect": "Conectar", + "ui.agent_chat_copy": "Copiar", + "ui.agent_chat_custom_hint": "Calquera programa que fale o Agent Client Protocol por stdin e stdout. Non se executa en ningún shell.", + "ui.agent_chat_denied": "Denegado", + "ui.agent_chat_deny": "Denegar", + "ui.agent_chat_desktop_only": "O chat co axente precisa a aplicación de escritorio.", + "ui.agent_chat_detecting": "Buscando axentes…", + "ui.agent_chat_dock_left": "Acoplar á esquerda", + "ui.agent_chat_dock_right": "Acoplar á dereita", + "ui.agent_chat_edit": "Editar", + "ui.agent_chat_exited": "O axente detívose.", + "ui.agent_chat_failed_start": "Non se puido iniciar o axente: {error}", + "ui.agent_chat_intro": "Conversa cun axente de programación que xa uses, ou cun punto de acceso de modelo que escollas. Traballa no deseño aberto a través das ferramentas de SolidCraft: os seus cambios vense mentres os fai e desfanse nun paso por mensaxe. O que pode facer sen preguntar defínese en Preferencias > IA.", + "ui.agent_chat_key_in_env": "clave configurada", + "ui.agent_chat_left": "Esquerda", + "ui.agent_chat_limit": "O axente chegou ao límite de {limit} cambios por mensaxe. Envía outra mensaxe para que continúe.", + "ui.agent_chat_minimize": "Minimizar nunha franxa", + "ui.agent_chat_model_tip": "O modelo que usa o axente. A túa escolla lémbrase para este axente.", + "ui.agent_chat_new": "Chat novo", + "ui.agent_chat_new_confirm": "Comezar un chat novo? Borrarase o actual.", + "ui.agent_chat_new_yes": "Chat novo", + "ui.agent_chat_no_cli": "Non se atopou solidcraft-cli xunto á aplicación, así que o axente non pode chegar ao deseño.", + "ui.agent_chat_no_control": "O punto de acceso do chat co axente non se iniciou, así que o axente non pode chegar ao deseño.", + "ui.agent_chat_no_images": "Este axente non admite imaxes", + "ui.agent_chat_none_found": "Non se atopou ningún axente de programación. Instala un destes e despois preme Actualizar:", + "ui.agent_chat_none_found_short": "Non se atopou ningún axente", + "ui.agent_chat_not_installed": "Non instalado", + "ui.agent_chat_not_signed_in": "sen sesión iniciada", + "ui.agent_chat_permission": "O axente pide executar: {title}", + "ui.agent_chat_pick": "Axente", + "ui.agent_chat_placeholder": "Pídelle ao axente que cambie o deseño…", + "ui.agent_chat_placeholder_busy": "Pon unha mensaxe na cola para cando remate o axente (Ctrl+Intro: enviar agora)", + "ui.agent_chat_privacy": "Nada vai a ningún sitio agás ao axente que executas, coa túa propia conta.", + "ui.agent_chat_privacy_note": "SolidCraft non envía nada a ningún sitio: o axente que executas fala co seu propio servizo coa túa propia conta. SolidCraft nunca ve nin garda ningunha clave nin contrasinal.", + "ui.agent_chat_queue": "Pór na cola", + "ui.agent_chat_queue_full": "Hai demasiadas mensaxes agardando: quita unha ou agarda polo axente.", + "ui.agent_chat_queued": "Na cola", + "ui.agent_chat_queued_stopped": "Na cola (detido, sen enviar)", + "ui.agent_chat_refresh": "Actualizar", + "ui.agent_chat_refused": "Non permitido ao axente: {reason}", + "ui.agent_chat_remove": "Quitar da cola", + "ui.agent_chat_right": "Dereita", + "ui.agent_chat_save": "Gardar", + "ui.agent_chat_send": "Enviar", + "ui.agent_chat_send_now": "Enviar agora", + "ui.agent_chat_send_now_tip": "Detén o paso actual do axente e envía isto a continuación (Ctrl+Intro)", + "ui.agent_chat_side": "Lado do chat co axente", + "ui.agent_chat_signed_in": "sesión iniciada", + "ui.agent_chat_state_auth": "Hai que iniciar sesión", + "ui.agent_chat_state_busy": "Traballando…", + "ui.agent_chat_state_exited": "Axente detido", + "ui.agent_chat_state_off": "Sen conexión", + "ui.agent_chat_state_ready": "Listo", + "ui.agent_chat_state_starting": "Iniciando…", + "ui.agent_chat_stop": "Deter", + "ui.agent_chat_stop_tip": "Detén o axente e todo o que iniciou", + "ui.agent_chat_stop_turn_tip": "Detén o axente (Esc). As mensaxes na cola seguen na cola.", + "ui.agent_chat_turn_limit": "Cambios por mensaxe", + "ui.agent_chat_undo_changes": "Desfacer estes cambios", + "ui.agent_chat_undo_label": "Chat co axente: {message}", + "ui.agent_chat_undone": "(desfeito)", + "ui.agent_chat_view_attached": "Vista achegada", + "ui.agent_cursor": "Cursor do axente", + "ui.agent_cursor_speed": "Velocidade do cursor do axente", + "ui.ai_add": "Engadir", + "ui.ai_add_agent": "Engadir axente…", + "ui.ai_add_agent_title": "Engadir axente", + "ui.ai_add_api": "API compatible con OpenAI", + "ui.ai_add_custom": "Orde personalizada", + "ui.ai_add_installed": "Axente instalado", + "ui.ai_add_installed_note": "Unha entrada propia para un axente instalado, por exemplo con outros argumentos. Os axentes instalados lístanse por si sós.", + "ui.ai_added": "engadido", + "ui.ai_agent_mode_tip": "O modo propio do axente: as súas propias ferramentas (shell, edición de ficheiros) seguen ese modo. As ferramentas de SolidCraft seguen os permisos de Preferencias > IA.", + "ui.ai_agents": "Axentes", + "ui.ai_always_allow": "Permitir sempre", + "ui.ai_always_allow_tip": "Permitir {tool} a este axente de agora en diante, sen preguntar", + "ui.ai_always_allowed": "Permitido sempre", + "ui.ai_always_allowed_none": "Aínda non hai nada permitido sempre. As respostas «Permitir sempre» que deas no chat lístanse aquí.", + "ui.ai_auto_allowed": "Permitido automaticamente: {title} ({why})", + "ui.ai_auto_mode": "a túa configuración de permisos", + "ui.ai_auto_ours": "SolidCraft comproba as súas propias ferramentas", + "ui.ai_auto_remembered": "escolliches Permitir sempre", + "ui.ai_bad_url": "Introduce un URL que comece por http:// ou https://", + "ui.ai_base_url": "URL base", + "ui.ai_button": "IA", + "ui.ai_copy_suffix": "copia", + "ui.ai_custom_url": "URL personalizado", + "ui.ai_default": "Predeterminado", + "ui.ai_http_busy": "o punto de acceso está ocupado ou superou o seu límite; téntao de novo máis tarde", + "ui.ai_http_key": "o punto de acceso rexeitou a clave: compróbaa en Preferencias > IA", + "ui.ai_http_not_found": "non existe ese punto de acceso ou modelo: comproba o URL base e o nome do modelo", + "ui.ai_key": "Clave da API", + "ui.ai_key_hint": "opcional; gárdase no chaveiro do sistema", + "ui.ai_key_needs_https": "A clave só se envía por HTTPS ou a este ordenador.", + "ui.ai_key_note": "Gárdase no chaveiro do sistema, nunca nos axustes de SolidCraft. Déixaa baleira para un servidor local.", + "ui.ai_keychain_error": "O chaveiro do sistema rexeitouno: {error}", + "ui.ai_mode_all": "Permitir todo", + "ui.ai_mode_all_note": "Nada pregunta antes. Os informes de fallos seguen fóra do seu alcance e os límites de cartafoles seguen aplicándose.", + "ui.ai_mode_all_warning": "O axente pode gardar, sobrescribir, exportar e substituír o teu deseño sen preguntar. Usa isto só cun axente no que confíes e con deseños que teñas gardados.", + "ui.ai_mode_ask": "Preguntar sempre", + "ui.ai_mode_ask_note": "Cada cambio no deseño e cada acción con ficheiros agardan a que premas Permitir.", + "ui.ai_mode_edits": "Permitir automaticamente as edicións do modelo", + "ui.ai_mode_edits_note": "As ordes de modelado execútanse sen preguntar; gardar, abrir, exportar e outras accións con ficheiros ou destrutivas seguen preguntando.", + "ui.ai_mode_global": "Como se definiu arriba", + "ui.ai_model": "Modelo", + "ui.ai_modes_scope": "Estes axustes cobren as ferramentas de SolidCraft. As ferramentas propias dun axente (o seu shell, as súas edicións de ficheiros) seguen o modo propio do axente, que escolles na cabeceira do panel de chat cando o axente ten modos.", + "ui.ai_name": "Nome", + "ui.ai_need_command": "Introduce a orde que inicia o axente", + "ui.ai_need_model": "Introduce o nome do modelo", + "ui.ai_no_answer": "O axente non respondeu a tempo", + "ui.ai_no_http": "Esta compilación non pode chegar a puntos de acceso de API", + "ui.ai_no_keychain": "O chaveiro do sistema non está dispoñible, así que non se pode gardar unha clave. Un servidor local sen clave segue funcionando.", + "ui.ai_panel": "Panel", + "ui.ai_permissions": "Permisos", + "ui.ai_preset": "Axuste predefinido", + "ui.ai_remove": "Quitar", + "ui.ai_request_limit": "detívose tras 24 solicitudes para unha mensaxe; envía outra mensaxe para continuar", + "ui.ai_reset": "Restablecer", + "ui.ai_settings": "Axustes de IA…", + "ui.ai_show_features": "Mostrar as funcións de IA", + "ui.ai_show_features_note": "O chat co axente: un panel onde un axente de programación que xa usas, ou un punto de acceso de modelo que escollas, traballa no deseño aberto. Desactivado: sen botón de IA, atallo, entrada de menú nin panel, e non se busca nin se inicia nada.", + "ui.ai_switch_tip": "Cambiar o axente desta conversa", + "ui.ai_test": "Probar", + "ui.ai_test_acp_ok": "Responde: {agent}", + "ui.ai_test_acp_tip": "Inicia o axente un momento e pídelle unha sesión; despois remátaa", + "ui.ai_test_api_tip": "Pídelle ao punto de acceso os seus modelos", + "ui.ai_test_no_model": "Alcanzado: {count} modelos, pero non {model}", + "ui.ai_test_ok": "Alcanzado: {count} modelos", + "ui.ai_testing": "Probando…", + "ui.ai_tool_done": "feito", + "ui.ai_tool_failed": "fallou", + "ui.ai_tool_running": "en execución", + "ui.ai_tool_unfold": "Fai clic para ver o que devolveu", + "ui.ai_tool_waiting": "agardando", + "ui.ai_toolbar_button": "Mostrar o botón na barra de ferramentas", + "ui.ai_toolbar_button_note": "O botón de IA no extremo dereito da barra de ferramentas. Ctrl+Maiús+A e o menú Vista seguen abrindo o panel.", + "ui.ai_undo_tip": "Desfai nun só paso todo o que cambiou o axente para esta mensaxe", + "ui.all": "Todo", + "ui.analysis": "Análise", + "ui.angle": "Ángulo", + "ui.angle_decimals": "Decimais dos ángulos", + "ui.animateJoint": "Animar a unión", + "ui.animate_view_changes": "Animar os cambios de vista", + "ui.animation": "Animación", + "ui.animation_speed": "Velocidade da animación", + "ui.anti_aliasing": "Antialiasing", + "ui.apply": "Aplicar", + "ui.arc": "Arco", + "ui.assemble": "Ensamblar", + "ui.autosave_every": "Gardar automaticamente cada", + "ui.axes": "Eixes", + "ui.axis": "Eixe", + "ui.base_point": "Punto base", + "ui.blocked": "Bloqueado", + "ui.bodies": "Corpos", + "ui.box": "Caixa", + "ui.break": "Romper", + "ui.calibrate": "Calibrar", + "ui.cancel": "Cancelar", + "ui.canvases": "Lenzos", + "ui.center": "Centro", + "ui.centerline": "Liña central", + "ui.chain": "Cadea", + "ui.chamfer": "Chafrán", + "ui.chamfer_type": "Tipo de chafrán", + "ui.change_workspace": "Cambiar de espazo de traballo", + "ui.chord_length": "Lonxitude da corda", + "ui.circle": "Círculo", + "ui.circular_pattern": "Patrón circular", + "ui.clear": "Borrar", + "ui.clear_recent": "Borrar recentes", + "ui.clear_the_selection": "Borrar a selección", + "ui.click_selects_whole_bodies": "Un clic selecciona corpos enteiros", + "ui.click_then_press_key": "Fai clic e despois preme a tecla nova", + "ui.close": "Pechar", + "ui.coil": "Hélice", + "ui.coincident": "Coincidente", + "ui.collapse": "Contraer", + "ui.collinear": "Colineal", + "ui.colour_vision": "Visión da cor", + "ui.colour_vision_deutan": "Deutan", + "ui.colour_vision_deutan_tip": "Para unha percepción do verde débil ou ausente", + "ui.colour_vision_failed": "Fallido", + "ui.colour_vision_fixed": "Fixo", + "ui.colour_vision_mode": "Modo", + "ui.colour_vision_note": "Cambia as cores que levan un significado: estados do bosquexo, eixes, dobras, análises e iconas. Se usas os filtros de cor de Windows, déixao desactivado.", + "ui.colour_vision_off": "Desactivado", + "ui.colour_vision_off_tip": "As cores propias do tema", + "ui.colour_vision_projected": "Proxectado", + "ui.colour_vision_protan": "Protan", + "ui.colour_vision_protan_tip": "Para unha percepción do vermello débil ou ausente", + "ui.colour_vision_sample": "Mostra", + "ui.colour_vision_tritan": "Tritan", + "ui.colour_vision_tritan_tip": "Para unha percepción do azul débil ou ausente", + "ui.combine": "Combinar", + "ui.coming_later": "máis adiante", + "ui.command_done": "{command} feito", + "ui.command_palette_hint": "Escribe unha orde, p. ex. {example} — ou preme S para buscar", + "ui.concentric": "Concéntrica", + "ui.configurations": "Configuracións", + "ui.conic_curve": "Curva cónica", + "ui.constant": "Constante", + "ui.constraints_conflict": "Conflito de restricións", + "ui.construct": "Construír", + "ui.construction": "Construción", + "ui.context_menu": "Menú contextual", + "ui.copy": "Copiar", + "ui.corner": "Esquina", + "ui.corners": "Esquinas", + "ui.counterbore": "Avellanado cilíndrico", + "ui.countersink": "Avellanado cónico", + "ui.create": "Crear", + "ui.create_copy": "Crear copia", + "ui.create_sketch": "Crear bosquexo", + "ui.current": "actual", + "ui.curvature": "Curvatura", + "ui.curvature_g2": "Curvatura (G2)", + "ui.curves": "Curvas", + "ui.custom_program": "Personalizado…", + "ui.custom_program_tip": "Escolle un programa laminador para engadilo á lista", + "ui.customizeToolbar": "Personalizar a barra de ferramentas…", + "ui.cut": "Cortar", + "ui.cylinder": "Cilindro", + "ui.dark": "Escuro", + "ui.default_modelling_orientation": "Orientación de modelado predeterminada", + "ui.degrees_of_freedom": "graos de liberdade", + "ui.delete": "Eliminar", + "ui.depth": "Profundidade", + "ui.design": "Deseño", + "ui.design_properties.author": "Autor", + "ui.design_properties.description": "Descrición", + "ui.design_properties.exports": "As exportacións STEP, IGES e 3MF levan estes datos cando o formato ten sitio para eles.", + "ui.design_properties.license": "Licenza", + "ui.design_properties.not_text": "Gardado como algo distinto de texto; escribir aquí substitúeo.", + "ui.design_properties.organization": "Organización", + "ui.design_properties.others": "Datos doutras ferramentas", + "ui.design_properties.others_note": "Consérvanse no deseño tal como están e nunca se exportan.", + "ui.design_properties.part_number": "Número de peza", + "ui.design_properties.project": "Proxecto", + "ui.design_properties.revision": "Revisión", + "ui.diameter": "Diámetro", + "ui.dimension": "Cota", + "ui.direction": "Dirección", + "ui.display_quality": "Calidade de visualización", + "ui.display_quality_coarse": "Baixa", + "ui.display_quality_fine": "Fina", + "ui.display_quality_normal": "Normal", + "ui.display_quality_ultra": "Ultra", + "ui.distance": "Distancia", + "ui.distance_1": "Distancia 1", + "ui.distance_2": "Distancia 2", + "ui.document_settings": "Axustes do documento", + "ui.don_t_save": "Non gardar", + "ui.draft": "Ángulo de desmoldaxe", + "ui.drawing": "Debuxo", + "ui.drill_point": "Punta de broca", + "ui.edit": "Editar", + "ui.editJointLimits": "Editar os límites da unión", + "ui.edit_section_analysis": "Editar a análise de sección", + "ui.ellipse": "Elipse", + "ui.end_radius": "Raio final", + "ui.end_scale": "Escala final", + "ui.entities": "Entidades", + "ui.equal": "Igual", + "ui.equivalent_radius": "Raio equivalente", + "ui.expand": "Expandir", + "ui.exportDxf": "Exportar DXF…", + "ui.export_ellipsis": "Exportar...", + "ui.export_ellipsis_keymap": "Exportar…", + "ui.export_keymap_tip": "Teclas, favoritos da caixa S e a barra de ferramentas, como un ficheiro", + "ui.extend": "Estender", + "ui.extent_type": "Tipo de extensión", + "ui.extrude": "Extruír", + "ui.factor": "Factor", + "ui.feature_history": "Historial de operacións", + "ui.feature_options": "Opcións da operación", + "ui.features": "Operacións", + "ui.file": "Ficheiro", + "ui.fillet": "Arredondamento", + "ui.filter_commands_or_keys": "Filtrar ordes ou teclas", + "ui.findInTimeline": "Buscar na liña de tempo", + "ui.findInWindow": "Buscar na xanela", + "ui.finish_sketch": "Rematar o bosquexo", + "ui.fit": "Axustar", + "ui.fix_unfix": "Fixar/Liberar", + "ui.flat": "Plano", + "ui.flip": "Inverter", + "ui.format": "Formato", + "ui.frame_rate": "Imaxes por segundo", + "ui.front": "Fronte", + "ui.fully_constrained": "Totalmente restrinxido", + "ui.general": "Xeral", + "ui.graphics": "Gráficos", + "ui.ground_shadow": "Sombra no chan", + "ui.groupSelected": "Agrupar a selección", + "ui.heading_add_ins": "COMPLEMENTOS", + "ui.heading_assemble": "ENSAMBLAR", + "ui.heading_box": "CAIXA", + "ui.heading_chamfer": "CHAFRÁN", + "ui.heading_circular_pattern": "PATRÓN CIRCULAR", + "ui.heading_coil": "HÉLICE", + "ui.heading_combine": "COMBINAR", + "ui.heading_configure": "CONFIGURAR", + "ui.heading_constraints": "RESTRICIÓNS", + "ui.heading_construct": "CONSTRUÍR", + "ui.heading_create": "CREAR", + "ui.heading_create_sketch": "CREAR BOSQUEXO", + "ui.heading_cylinder": "CILINDRO", + "ui.heading_design": "DESEÑO", + "ui.heading_draft": "ÁNGULO DE DESMOLDAXE", + "ui.heading_edit": "EDITAR", + "ui.heading_extrude": "EXTRUÍR", + "ui.heading_fillet": "ARREDONDAMENTO", + "ui.heading_finish_sketch": "REMATAR O BOSQUEXO", + "ui.heading_front": "FRONTE", + "ui.heading_hole": "FURADO", + "ui.heading_home": "INICIO", + "ui.heading_insert": "INSERIR", + "ui.heading_inspect": "INSPECCIONAR", + "ui.heading_loft": "TRANSICIÓN", + "ui.heading_make": "FABRICAR", + "ui.heading_measure": "MEDIR", + "ui.heading_mesh": "MALLA", + "ui.heading_mirror": "SIMETRÍA", + "ui.heading_modify": "MODIFICAR", + "ui.heading_move": "MOVER", + "ui.heading_move_copy": "MOVER/COPIAR", + "ui.heading_offset": "DESPRAZAMENTO", + "ui.heading_offset_plane": "PLANO DESPRAZADO", + "ui.heading_ok": "ACEPTAR", + "ui.heading_parameters": "PARÁMETROS", + "ui.heading_pattern": "PATRÓN", + "ui.heading_pattern_on_path": "PATRÓN NUNHA TRAXECTORIA", + "ui.heading_pipe": "TUBO", + "ui.heading_plane_at_angle": "PLANO EN ÁNGULO", + "ui.heading_plastic": "PLÁSTICO", + "ui.heading_position": "POSICIÓN", + "ui.heading_prepare": "PREPARAR", + "ui.heading_rectangular_pattern": "PATRÓN RECTANGULAR", + "ui.heading_revolve": "REVOLUCIÓN", + "ui.heading_right": "DEREITA", + "ui.heading_save_mesh": "GARDAR COMO MALLA", + "ui.heading_scale": "ESCALA", + "ui.heading_section_analysis": "ANÁLISE DE SECCIÓN", + "ui.heading_select": "SELECCIONAR", + "ui.heading_setup": "CONFIGURACIÓN", + "ui.heading_sheet_metal": "CHAPA", + "ui.heading_shell": "BALEIRADO", + "ui.heading_sketch": "BOSQUEXO", + "ui.heading_sketch_palette": "PALETA DO BOSQUEXO", + "ui.heading_sketch_scale": "ESCALA DO BOSQUEXO", + "ui.heading_solid": "SÓLIDO", + "ui.heading_sphere": "ESFERA", + "ui.heading_split_body": "DIVIDIR O CORPO", + "ui.heading_surface": "SUPERFICIE", + "ui.heading_sweep": "VARRIDO", + "ui.heading_thread": "ROSCA", + "ui.heading_top": "SUPERIOR", + "ui.heading_torus": "TORO", + "ui.heading_utilities": "UTILIDADES", + "ui.heading_utility": "UTILIDADE", + "ui.help": "Axuda", + "ui.hide": "Ocultar", + "ui.hideAxes": "Ocultar os eixes", + "ui.hideDimension": "Ocultar a cota", + "ui.hideOrigin": "Ocultar a orixe", + "ui.hidePlanes": "Ocultar os planos", + "ui.hideProfile": "Ocultar o perfil", + "ui.hole": "Furado", + "ui.hole_tap_type": "Tipo de roscado do furado", + "ui.hole_type": "Tipo de furado", + "ui.home": "Inicio", + "ui.homeView": "Vista de inicio", + "ui.horizontal_vertical": "Horizontal/Vertical", + "ui.import_ellipsis": "Importar…", + "ui.infinite": "Infinito", + "ui.insert": "Inserir", + "ui.inspect": "Inspeccionar", + "ui.intersect": "Intersecar", + "ui.isolate": "Illar", + "ui.join": "Unir", + "ui.joints": "Unións", + "ui.keyboard_shortcuts": "Atallos de teclado", + "ui.language": "Idioma", + "ui.length_decimals": "Decimais das lonxitudes", + "ui.light": "Claro", + "ui.line": "Liña", + "ui.linetype": "Tipo de liña", + "ui.lock": "Bloquear", + "ui.loft": "Transición", + "ui.look_at": "Mirar cara a", + "ui.look_at_anim_desc": "Vista de eixe, Mirar cara a, Inicio e Axustar", + "ui.manufacture": "Fabricación", + "ui.material_review.axes": "Eixes locais do material; non se asigna ningunha orientación do corpo.", + "ui.material_review.claims": "As fontes e as licenzas son afirmacións sen verificar. Os valores que faltan seguen sendo descoñecidos.", + "ui.material_review.compressive_strength": "Resistencia á compresión", + "ui.material_review.conditions": "Condicións indicadas", + "ui.material_review.density": "Densidade", + "ui.material_review.derived": "Módulos isótropos derivados", + "ui.material_review.elasticity": "Elasticidade", + "ui.material_review.input": "Pega unha ficha de material do esquema 1 (JSON)", + "ui.material_review.limit": "A ficha supera o límite de entrada de 256 KiB.", + "ui.material_review.moisture_unit": "kg de auga / kg de material seco", + "ui.material_review.properties": "Propiedades", + "ui.material_review.review": "Revisar a ficha", + "ui.material_review.scope": "Só candidato: non se asigna nin se garda. A validación numérica non é unha certificación de enxeñaría.", + "ui.material_review.shear_strength": "Resistencia ao cortante", + "ui.material_review.source": "Fonte", + "ui.material_review.specific_heat": "Calor específica", + "ui.material_review.tensile_strength": "Resistencia á tracción", + "ui.material_review.thermal_conductivity": "Condutividade térmica", + "ui.material_review.thermal_expansion": "Dilatación térmica", + "ui.material_review.title": "Revisar os datos do material físico", + "ui.material_review.unknown": "Descoñecido", + "ui.material_review.yield_strength": "Límite elástico", + "ui.measure": "Medir", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "3MF con etiquetas de cara", + "ui.mesh_format_stl": "STL", + "ui.midpoint": "Punto medio", + "ui.mirror": "Simetría", + "ui.mirror_line": "Liña de simetría", + "ui.modify": "Modificar", + "ui.move": "Mover", + "ui.multiple": "Múltiple", + "ui.named_views": "Vistas con nome", + "ui.navigation": "Navegación", + "ui.needs_design": "{command}: abre primeiro un deseño", + "ui.newSketchGroup": "Grupo de bosquexos novo", + "ui.new_body": "Corpo novo", + "ui.new_design": "Deseño novo", + "ui.no_slicer_found": "Non se atopou ningún laminador", + "ui.normal": "Normal", + "ui.normalConstruction": "Normal / Construción", + "ui.not_a_program": "{path} non é un programa que se poida iniciar", + "ui.object_type": "Tipo de obxecto", + "ui.objects": "Obxectos", + "ui.offer_to_stand_up_y_up_files": "Ofrecer poñer de pé os ficheiros con Y cara arriba", + "ui.offset": "Desprazamento", + "ui.offset_plane": "Plano desprazado", + "ui.one_side": "Un lado", + "ui.open": "Abrir", + "ui.open_ellipsis": "Abrir...", + "ui.open_preferences": "Abrir as preferencias", + "ui.open_recent": "Abrir recentes", + "ui.operation": "Operación", + "ui.options": "Opcións", + "ui.orbit": "Orbitar", + "ui.orbit_around": "Orbitar arredor de", + "ui.orientation": "Orientación", + "ui.origin": "Orixe", + "ui.palette_points": "Puntos", + "ui.palette_profile": "Perfil", + "ui.pan": "Desprazar", + "ui.pan_zoom_orbit": "Desprazar, zoom, orbitar", + "ui.parallel": "Paralela", + "ui.parameters": "Parámetros", + "ui.paste": "Pegar", + "ui.path": "Traxectoria", + "ui.pattern_on_path": "Patrón nunha traxectoria", + "ui.perpendicular": "Perpendicular", + "ui.perspective_view": "Vista en perspectiva", + "ui.pinToShortcuts": "Fixar nos atallos", + "ui.pinToToolbar": "Fixar na barra de ferramentas", + "ui.pipe": "Tubo", + "ui.placement": "Colocación", + "ui.plane": "Plano", + "ui.plane_at_angle": "Plano en ángulo", + "ui.point": "Punto", + "ui.point_under_the_cursor": "Punto baixo o cursor", + "ui.points": "Puntos", + "ui.polygon": "Polígono", + "ui.preferences": "Preferencias", + "ui.press_a_key": "preme unha tecla…", + "ui.profile": "Perfil", + "ui.profile_plane": "Plano do perfil", + "ui.profiles": "Perfís", + "ui.project": "Proxectar", + "ui.project_face_edges_sketch": "Proxectar as arestas da cara en bosquexos novos", + "ui.properties": "Propiedades", + "ui.pull_direction": "Dirección de extracción", + "ui.quantity": "Cantidade", + "ui.quantity_2": "Cantidade 2", + "ui.quit": "Saír", + "ui.radial_context_menu": "Menú contextual radial", + "ui.radius": "Raio", + "ui.radius_type": "Tipo de raio", + "ui.reachable": "Alcanzable", + "ui.rectangle": "Rectángulo", + "ui.rectangular_pattern": "Patrón rectangular", + "ui.redo": "Refacer", + "ui.removeFromToolbar": "Quitar da barra de ferramentas", + "ui.removeSection": "Quitar a sección", + "ui.render": "Render", + "ui.renderer": "Motor de render", + "ui.repeat": "Repetir", + "ui.report_a_bug": "Informar dun erro", + "ui.reset": "Restablecer", + "ui.reset_all": "Restablecer todo", + "ui.reset_the_settings_on_this_page": "Restablecer os axustes desta páxina", + "ui.restore": "Restaurar", + "ui.restore_defaults": "Restaurar os valores predeterminados", + "ui.reverse_zoom_direction": "Inverter a dirección do zoom", + "ui.revolve": "Revolución", + "ui.right": "Dereita", + "ui.save": "Gardar", + "ui.save_as": "Gardar como", + "ui.save_as_ellipsis": "Gardar como...", + "ui.save_mesh_no_slicer": "Non se atopou ningún laminador: escolle Personalizado… e selecciona o teu programa laminador, ou desactiva Enviar ao laminador", + "ui.save_mesh_pick_bodies": "Selecciona os corpos que queres gardar", + "ui.save_mesh_temp_failed": "Non se puido crear {folder}: {error}", + "ui.saved_to": "Gardado {path}", + "ui.scale": "Escala", + "ui.section_analysis": "Análise de sección", + "ui.select": "Seleccionar", + "ui.selectOther": "Seleccionar outro…", + "ui.selectTangentChain": "Seleccionar cadea tanxente", + "ui.select_other_hint": "Seleccionar outro: mantén o botón esquerdo quieto sobre o modelo (ou clic dereito › Seleccionar outro…) para listar todo o que hai baixo o cursor; fai clic de novo no mesmo punto para seleccionar o seguinte.", + "ui.selection": "Selección", + "ui.send": "Enviar", + "ui.send_to_slicer": "Enviar ao laminador", + "ui.sent_to_slicer": "Enviado a {slicer}", + "ui.shell": "Baleirado", + "ui.show": "Mostrar", + "ui.showAll": "Mostrar todo", + "ui.showAllBodies": "Mostrar todos os corpos", + "ui.showAxes": "Mostrar os eixes", + "ui.showDimension": "Mostrar a cota", + "ui.showOrigin": "Mostrar a orixe", + "ui.showPlanes": "Mostrar os planos", + "ui.show_constraints": "Restricións", + "ui.show_construction_geometries": "Xeometrías de construción", + "ui.show_dimensions": "Cotas", + "ui.show_points": "Mostrar os puntos", + "ui.show_profile": "Mostrar o perfil", + "ui.show_projected_geometries": "Xeometrías proxectadas", + "ui.simple": "Simple", + "ui.simulation": "Simulación", + "ui.single": "Único", + "ui.sketch": "Bosquexo", + "ui.sketch_dimension": "Cota do bosquexo", + "ui.sketch_grid": "Grella do bosquexo", + "ui.sketch_scale": "Escala do bosquexo", + "ui.sketch_status": "Estado do bosquexo", + "ui.sketches": "Bosquexos", + "ui.slice": "Laminar", + "ui.slicer": "Laminador", + "ui.slicer_delete_tip": "{program}\nPreme Suprimir para quitalo da lista", + "ui.slot": "Ranura", + "ui.smooth": "Suave", + "ui.smooth_wheel_zoom": "Zoom suave coa roda", + "ui.smooth_wheel_zoom_tip": "Desactívao para aplicar cada movemento da roda de inmediato, sen suavizado", + "ui.snap": "Axuste", + "ui.space_mouse_hint": "Move e rota a vista á vez; os bosquexos só usan desprazamento e zoom.", + "ui.space_mouse_navigate": "Navegar con SpaceNavigator / SpaceMouse", + "ui.spacing": "Espazado", + "ui.spacing_2": "Espazado 2", + "ui.sphere": "Esfera", + "ui.spline": "Spline", + "ui.split_body": "Dividir o corpo", + "ui.stand_up_tip": "Despois de abrir un ficheiro STEP ou IGES con Z cara arriba, ofrecer un cuarto de volta arredor de X", + "ui.start": "Inicio", + "ui.start_radius": "Raio inicial", + "ui.supersampling": "Supermostraxe (SSAA)", + "ui.supersampling_adaptive": "Só cando a vista está quieta", + "ui.supersampling_off": "Desactivado (1×)", + "ui.suppress": "Suprimir", + "ui.sweep": "Varrido", + "ui.sweep_follow_direction": "Seguir a dirección", + "ui.sweep_keep_as_drawn": "Manter como se debuxou", + "ui.sweep_turn_with_path": "Xirar coa traxectoria", + "ui.symmetric": "Simétrico", + "ui.symmetry": "Simetría", + "ui.system": "Sistema", + "ui.tangent": "Tanxente", + "ui.taper_angle": "Ángulo de conicidade", + "ui.tapped": "Roscado", + "ui.text": "Texto", + "ui.theme": "Tema", + "ui.thickness": "Espesor", + "ui.thread": "Rosca", + "ui.timeline_bottom": "Liña de tempo abaixo", + "ui.timeline_left_note": "A disposición á esquerda mostra a barra de retroceso enriba do navegador de pezas e escena.", + "ui.timeline_left_sidebar": "Barra lateral esquerda", + "ui.tip_angle": "Ángulo da punta", + "ui.to_object": "Ata o obxecto", + "ui.tool_direction": "Dirección da ferramenta", + "ui.top": "Superior", + "ui.torus": "Toro", + "ui.total_angle": "Ángulo total", + "ui.trackpad_pan_tip": "Os xestos do panel táctil desprazan (desactivado: fan zoom como a roda); a roda do rato fai zoom, a roda do polgar despraza de lado e a pinza sempre fai zoom", + "ui.trim": "Recortar", + "ui.twist": "Torsión", + "ui.two_finger_scroll_pans": "O desprazamento con dous dedos despraza a vista", + "ui.two_sides": "Dous lados", + "ui.ui_scale": "Escala da interface", + "ui.undo": "Desfacer", + "ui.unground": "Soltar do chan", + "ui.unisolate": "Deixar de illar", + "ui.units": "Unidades", + "ui.units_of_new_designs": "Unidades dos deseños novos", + "ui.unlock": "Desbloquear", + "ui.unsuppress": "Deixar de suprimir", + "ui.untitled": "Sen título", + "ui.up_axis_note": "Que eixe apunta cara arriba nas vistas (vista de eixe, Inicio, Mirar cara a). Os deseños non cambian.", + "ui.updateToCurrentView": "Actualizar á vista actual", + "ui.variable": "Variable", + "ui.view_centre": "Centro da vista", + "ui.visual_shaded_hidden_edges": "Sombreado con arestas ocultas", + "ui.visual_shaded_with_edges": "Sombreado con arestas", + "ui.visual_style": "Estilo visual", + "ui.visual_wireframe": "Arames", + "ui.workspace": "espazo de traballo", + "ui.x_distance": "Distancia en X", + "ui.y_distance": "Distancia en Y", + "ui.y_up": "Y cara arriba", + "ui.z_up": "Z cara arriba", + "ui.zoom": "Zoom", + "ui.zoom_to_cursor_tip": "A roda fai zoom cara ao punto baixo o cursor (desactivado: cara ao centro da vista)", + "ui.zoom_to_the_cursor": "Zoom cara ao cursor", + "update.available": "Está dispoñible SolidCraft {version}", + "update.button": "Actualizar", + "update.button_tip": "Está dispoñible SolidCraft {version}", + "update.button_version": "Actualizar a {version}", + "update.check_automatically": "Buscar actualizacións automaticamente", + "update.check_now": "Comprobar agora", + "update.checking": "Comprobando…", + "update.copy": "Copiar", + "update.dmg_opened": "A imaxe de disco está aberta e verificada: arrastra SolidCraft a Aplicacións, substituíndo a copia antiga, e despois reinicia SolidCraft.", + "update.download": "Descargar", + "update.download_open": "Descargar e abrir", + "update.downloading": "Descargando e verificando… {done} de {total} MB", + "update.failed": "Non se puido comprobar: {error}", + "update.file": "Descargar obtén {file}.", + "update.install_failed": "A actualización non se instalou: {error}. Non se cambiou nada; Descargar obtén o paquete no seu lugar.", + "update.install_msi": "Instalar (pecha SolidCraft)", + "update.installed": "SolidCraft {version} está instalado. Reinicia para usalo.", + "update.installer_started": "O instalador iníciase cando se pecha SolidCraft.", + "update.later": "Lembrarmo máis tarde", + "update.no_notes": "Esta versión non ten notas.", + "update.package_hint": "Esta copia veu dun {kind}. Descarga o paquete novo e despois instálao con:", + "update.prefs_dev": "Esta é unha compilación de desenvolvemento ({version}): non busca actualizacións.", + "update.prefs_flatpak": "Flatpak actualiza esta copia ({version}): executa {command} ou usa o teu centro de software. SolidCraft non comproba.", + "update.prefs_label": "Actualizacións", + "update.prefs_note": "Esta é a versión {version} de SolidCraft ({kind}). Unha comprobación pídelle a GitHub a última versión e non envía nada máis.", + "update.release_page": "Abrir a páxina da versión", + "update.restart": "Reiniciar agora", + "update.restart_later": "Máis tarde", + "update.show": "Mostrar a actualización a {version}", + "update.skip": "Omitir esta versión", + "update.system_hint": "Esta copia é un {kind}. Actualízaa con:", + "update.title": "Actualización dispoñible", + "update.up_to_date": "SolidCraft está actualizado.", + "update.update_now": "Actualizar agora", + "update.you_have": "Tes a versión {version}." +} diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 4bb4502fe..f5a41eaa1 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -92,6 +92,7 @@ "Enable rule": "ルールを有効化", "Enabled": "有効", "Explode": "分解", + "Export Animation…": "アニメーションをエクスポート…", "Export Current View as DXF": "現在の表示をDXFでエクスポート", "Export Current View as DXF…": "現在の表示をDXFでエクスポート…", "Export DXF…": "DXFをエクスポート…", @@ -211,6 +212,7 @@ "Round": "丸め", "Rule": "ルール", "Save Rule": "ルールを保存", + "Save the study as an animated GIF, seen as the viewport shows it": "ビューポートの表示どおりにスタディをアニメーション GIF として保存", "Saved preview. Geometry is being checked before editing.": "保存済みのプレビューです。編集前にジオメトリを検証しています。", "Scale factor": "尺度係数", "Search": "検索", @@ -293,6 +295,13 @@ "browser.precision": "精度: {precision}", "browser.sketch_name": "スケッチ{number}", "browser.units": "単位: {units}", + "cam.flat": "平面", + "cam.follower": "従動節", + "cam.knife": "ナイフエッジ", + "cam.needs_joints": "回転するジョイントと、スライドまたは揺動するジョイントが必要", + "cam.roller": "ローラー", + "cam.roller_pick": "ローラー (オプション)", + "cam.tip_pick": "先端 (オプション)", "cmd.appearance_assign": "外観", "cmd.appearance_library": "外観ライブラリ", "cmd.appearance_list": "外観を一覧表示", @@ -396,6 +405,7 @@ "cmd.inspect_minimum_radius": "最小半径解析", "cmd.inspect_zebra": "ゼブラ解析", "cmd.joint_as_built": "現位置ジョイント", + "cmd.joint_cam": "カム", "cmd.joint_create": "ジョイント", "cmd.joint_delete": "ジョイントを削除", "cmd.joint_drive": "ジョイントを駆動", @@ -426,6 +436,7 @@ "cmd.model_threads": "ねじを一覧表示", "cmd.motion_delete": "モーション スタディを削除", "cmd.motion_export": "モーション スタディをエクスポート", + "cmd.motion_export_animation": "モーション アニメーションをエクスポート", "cmd.motion_list": "モーション スタディを一覧表示", "cmd.motion_play": "モーション スタディを再生", "cmd.motion_study": "モーション スタディ", @@ -631,6 +642,18 @@ "drive.stopped_by_contact": "{value} で停止: {a} が {b} を通り抜けてしまいます", "drive.stopped_by_loop": "{value} で停止: {joint} を通るループはこれ以上閉じられません", "drive.unconnected": "何も動きません: {part} は空間固定されたものに接続されていません", + "dxf.cancel_wait": "出力処理の停止を待っています…", + "dxf.cancelled": "DXF出力をキャンセルしました", + "dxf.cancelling": "DXF出力をキャンセル中", + "dxf.exporting": "DXFを出力中", + "dxf.invalid_tolerance": "曲線の許容誤差は0.0001~1 mmで指定してください。", + "dxf.progress.index": "面データを準備中 (2/5)", + "dxf.progress.meshes": "メッシュを準備中 (1/5)", + "dxf.progress.occlusion": "隠線を判定中 (4/5)", + "dxf.progress.projection": "形状を投影中 (3/5)", + "dxf.progress.write": "DXFを書き込み中 (5/5)", + "dxf.tolerance": "曲線の許容誤差", + "dxf.tolerance_help": "表示中のボディを出力し、曲線は線分で近似します。許容誤差を小さくすると曲線が滑らかになりますが、処理時間とメモリ使用量が増えます。", "expression, e.g. 25 mm": "計算式 (例: 25 mm)", "fits the face, e.g. M8": "面に適合するサイズ (例: M8)", "from the rule": "ルールから", @@ -760,6 +783,10 @@ "sketch_text.path_hint": "文字が沿うスケッチの曲線: ここをクリックしてから曲線をクリック", "sketch_text.use_font_file": "フォント ファイル {path} を使用", "the parts library is not available": "パーツライブラリは利用できません", + "thread.automatic_size": "サイズを自動選択", + "thread.designation": "ねじの呼び", + "thread.iso_metric": "ISOメートルねじ", + "thread.select_size": "サイズを選択", "timeline.group": "フィーチャーフォルダを新規作成", "timeline.move_many": "タイムライン項目を移動", "timeline.move_to_group": "フィーチャーをフォルダへ移動", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index a274a3582..df52217ae 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -24,6 +24,7 @@ "Drive Joint": "조인트 구동", "Edges": "모서리", "Edit Profile Sketch": "윤곽 스케치 편집", + "Export Animation…": "애니메이션 내보내기…", "Export Current View as DXF": "현재 뷰를 DXF로 내보내기", "Export Current View as DXF…": "현재 뷰를 DXF로 내보내기…", "Export DXF…": "DXF 내보내기…", @@ -59,6 +60,7 @@ "Restore outer boundary": "외부 경계 복원", "Revert Position": "위치 복원", "Round": "둥글게", + "Save the study as an animated GIF, seen as the viewport shows it": "뷰포트에 보이는 대로 스터디를 애니메이션 GIF로 저장", "Select bodies (a face picks its body)": "바디 선택(면을 클릭하면 해당 바디 선택)", "Selection filter": "선택 필터", "Send your report on GitHub": "GitHub에서 보고서 보내기", @@ -92,6 +94,13 @@ "browser.precision": "정밀도: {precision}", "browser.sketch_name": "스케치{number}", "browser.units": "단위: {units}", + "cam.flat": "평면", + "cam.follower": "종동절", + "cam.knife": "나이프 에지", + "cam.needs_joints": "회전하는 관절과 미끄러지거나 흔들리는 관절이 필요함", + "cam.roller": "롤러", + "cam.roller_pick": "롤러 (선택 사항)", + "cam.tip_pick": "끝점 (선택 사항)", "cmd.appearance_assign": "외관", "cmd.appearance_library": "외관 라이브러리", "cmd.appearance_list": "외관 목록", @@ -195,6 +204,7 @@ "cmd.inspect_minimum_radius": "최소 반경 분석", "cmd.inspect_zebra": "얼룩말줄무늬 분석", "cmd.joint_as_built": "조립 상태 관절", + "cmd.joint_cam": "캠", "cmd.joint_create": "관절", "cmd.joint_delete": "관절 삭제", "cmd.joint_drive": "관절 구동", @@ -225,6 +235,7 @@ "cmd.model_threads": "나사산 목록", "cmd.motion_delete": "운동 연구 삭제", "cmd.motion_export": "운동 연구 내보내기", + "cmd.motion_export_animation": "모션 애니메이션 내보내기", "cmd.motion_list": "운동 연구 목록", "cmd.motion_play": "운동 연구 재생", "cmd.motion_study": "운동 연구", @@ -428,6 +439,18 @@ "drive.stopped_by_contact": "{value}에서 멈춤: {a}이(가) {b}을(를) 통과하게 됩니다", "drive.stopped_by_loop": "{value}에서 멈춤: {joint}을(를) 지나는 루프를 더 이상 닫을 수 없습니다", "drive.unconnected": "아무것도 움직이지 않습니다: {part}이(가) 고정된 것에 연결되어 있지 않습니다", + "dxf.cancel_wait": "내보내기가 중지될 때까지 기다리는 중…", + "dxf.cancelled": "DXF 내보내기를 취소했습니다", + "dxf.cancelling": "DXF 내보내기 취소 중", + "dxf.exporting": "DXF 내보내는 중", + "dxf.invalid_tolerance": "곡선 허용 오차는 0.0001~1 mm 범위여야 합니다.", + "dxf.progress.index": "면 데이터 준비 중 (2/5)", + "dxf.progress.meshes": "메시 준비 중 (1/5)", + "dxf.progress.occlusion": "숨은선 판정 중 (4/5)", + "dxf.progress.projection": "형상 투영 중 (3/5)", + "dxf.progress.write": "DXF 쓰는 중 (5/5)", + "dxf.tolerance": "곡선 허용 오차", + "dxf.tolerance_help": "표시된 바디만 내보내며 곡선은 직선 구간으로 근사합니다. 허용 오차가 작을수록 곡선이 매끄러워지지만 처리 시간과 메모리 사용량이 늘어납니다.", "home.documentation": "문서", "home.in_this_browser": "이 브라우저에 저장됨", "home.missing": "찾을 수 없음", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json new file mode 100644 index 000000000..c45e1a6a7 --- /dev/null +++ b/assets/locales/pt-BR.json @@ -0,0 +1,1460 @@ +{ + "0 turns it off": "0 desativa", + "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Abra o rascunho do GitHub abaixo e cole o relatório copiado para a área de transferência.", + "1. Open GitHub draft below. Your title and report will be filled in.": "1. Abra o rascunho do GitHub abaixo. O título e o relatório serão preenchidos.", + "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Anexe a captura de tela: copie e cole, ou salve e envie o PNG.", + "3. Click Submit new issue on GitHub to send your report.": "3. Clique em Submit new issue no GitHub para enviar o relatório.", + "A new configuration, a copy of the active one": "Uma nova configuração, cópia da ativa", + "AI": "IA", + "About SolidCraft": "Sobre o SolidCraft", + "Active": "Ativo", + "Active rule": "Regra ativa", + "Add": "Adicionar", + "Add Key": "Adicionar chave", + "Add Mid Radius": "Adicionar raio intermediário", + "Add Row": "Adicionar linha", + "Add condition": "Adicionar condição", + "Alignment": "Alinhamento", + "All Sketch Points": "Todos os pontos do esboço", + "All open designs": "Todos os projetos abertos", + "Allowed expressions, separated by semicolons": "Expressões permitidas, separadas por ponto e vírgula", + "Also deletes": "Também exclui", + "Angle 2": "Ângulo 2", + "Animate": "Animar", + "Appearance name": "Nome da aparência", + "Applied Radius": "Raio aplicado", + "Apply To": "Aplicar a", + "Apply to selection": "Aplicar à seleção", + "Arc length": "Comprimento do arco", + "Area": "Área", + "Attachment": "Fixação", + "BROWSER": "NAVEGADOR", + "Bend Line Position": "Posição da linha de dobra", + "Bend Position": "Posição da dobra", + "Bend Radius": "Raio de dobra", + "Bends": "Dobras", + "Body": "Corpo", + "Boundary": "Contorno", + "Bounding box": "Caixa delimitadora", + "CSV or JSON: updates existing parameters, adds new ones": "CSV ou JSON: atualiza parâmetros existentes e adiciona novos", + "Capture All Positions": "Capturar todas as posições", + "Catch Direction": "Direção do encaixe", + "Cells": "Células", + "Center X": "Centro X", + "Center Y": "Centro Y", + "Center of mass": "Centro de massa", + "Centre to centre": "Centro a centro", + "Chamfer Type": "Tipo de chanfro", + "Check collisions": "Verificar colisões", + "Checked": "Marcado", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Escolha um novo plano. A geometria e as cotas do esboço permanecem inalteradas em suas coordenadas bidimensionais.", + "Circumference": "Circunferência", + "Close draft": "Fechar rascunho", + "Collisions": "Colisões", + "Colour": "Cor", + "Component1": "Componente1", + "Configuration": "Configuração", + "Configuration rules": "Regras de configuração", + "Construction": "Construção", + "Contact": "Contato", + "Continuity": "Continuidade", + "Copy Error Message": "Copiar mensagem de erro", + "Copy Warning Message": "Copiar mensagem de aviso", + "Copy all licences": "Copiar todas as licenças", + "Copy diagnostic information": "Copiar informações de diagnóstico", + "Copy report": "Copiar relatório", + "Copy screenshot": "Copiar captura de tela", + "Corner Relief": "Alívio de canto", + "Corner Relief Shape": "Forma do alívio de canto", + "Counterbore depth": "Profundidade do rebaixo", + "Countersink angle": "Ângulo do escareado", + "Create Issue — review draft": "Criar issue — revisar rascunho", + "Cube": "Cubo", + "Current orthographic view (1:1 mm)": "Vista ortográfica atual (1:1 mm)", + "Current perspective view": "Vista em perspectiva atual", + "Curvature (G2)": "Curvatura (G2)", + "Customize Toolbar": "Personalizar barra de ferramentas", + "Delete all": "Excluir tudo", + "Delete rule": "Excluir regra", + "Delete the row": "Excluir a linha", + "Delete the set": "Excluir o conjunto", + "Delete this parameter": "Excluir este parâmetro", + "Density": "Densidade", + "Designs you open or save appear here.": "Os projetos que você abrir ou salvar aparecem aqui.", + "Determined by To Object. Choose Angle to edit the angular extent.": "Determinado por Até o objeto. Escolha Ângulo para editar a extensão angular.", + "Discard": "Descartar", + "Do not export hidden edges": "Não exportar arestas ocultas", + "Double-click to rename": "Clique duas vezes para renomear", + "Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "Clique duplo com o botão do meio na vista: Início (a vista inicial, enquadrando o que é mostrado), Ajustar (enquadra o que é mostrado, mantendo a orientação) ou nada", + "Drive Joint": "Acionar junta", + "Edges": "Arestas", + "Edit Profile Sketch": "Editar esboço do perfil", + "Enable rule": "Ativar regra", + "Enabled": "Ativado", + "Explode": "Explodir", + "Export Animation…": "Exportar animação…", + "Export Current View as DXF": "Exportar vista atual como DXF", + "Export Current View as DXF…": "Exportar vista atual como DXF…", + "Export DXF…": "Exportar DXF…", + "Export hidden edges as dashed lines": "Exportar arestas ocultas como linhas tracejadas", + "Extents": "Extensões", + "Face": "Face", + "Face attachment lost": "Fixação à face perdida", + "Faces": "Faces", + "Faces / edges / vertices": "Faces / arestas / vértices", + "Favourite": "Favorito", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Arquivos de muitos programas CAD usam Y para cima, então abrem deitados aqui (Z para cima).", + "Filter": "Filtro", + "Find in Browser": "Localizar no navegador", + "Flat": "Plano", + "Flat size": "Tamanho planificado", + "Follow camera (Look At sketches)": "Seguir a câmera (Olhar para os esboços)", + "Follow the camera (Look At sketches)": "Seguir a câmera (Olhar para os esboços)", + "Font": "Fonte", + "Full Length": "Comprimento total", + "Gap": "Folga", + "Grid": "Grade", + "Height": "Altura", + "Hidden edges": "Arestas ocultas", + "Holes": "Furos", + "Holes (edges on them)": "Furos (arestas neles)", + "Home view": "Vista inicial", + "In This Design": "Neste projeto", + "In place (surfaces)": "No lugar (superfícies)", + "Inside": "Dentro", + "Interferes": "Interfere", + "Issue title": "Título da issue", + "Joint Origin1": "Origem da junta1", + "Keep Tools": "Manter ferramentas", + "Later": "Depois", + "Leave it": "Deixar assim", + "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Fixação de face antiga. Vincular novamente a uma face certificada cria uma fixação exata.", + "Length": "Comprimento", + "Length units": "Unidades de comprimento", + "Letter Spacing": "Espaçamento entre letras", + "Library": "Biblioteca", + "Line Spacing": "Espaçamento entre linhas", + "Loop": "Laço", + "Margin": "Margem", + "Mass": "Massa", + "Material": "Material", + "Max": "Máx.", + "Mid Radius": "Raio intermediário", + "Middle double-click": "Clique duplo do meio", + "Min": "Mín.", + "Mitre": "Meia-esquadria", + "Modeled": "Modelado", + "More toolbar panels": "Mais painéis da barra de ferramentas", + "Motion": "Movimento", + "Move Type": "Tipo de movimento", + "Move earlier": "Mover para antes", + "Move later": "Mover para depois", + "Name": "Nome", + "No crash reports.": "Nenhum relatório de falha.", + "No matching appearances": "Nenhuma aparência correspondente", + "No visible bodies to export.": "Nenhum corpo visível para exportar.", + "None": "Nenhum", + "Not available yet": "Ainda não disponível", + "Notch": "Entalhe", + "Opacity": "Opacidade", + "Open GitHub draft": "Abrir rascunho no GitHub", + "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código aberto em Rust. Licenciado sob MIT OU Apache-2.0.", + "Other side": "Outro lado", + "Outside": "Fora", + "Overall length": "Comprimento total", + "Parameter values": "Valores dos parâmetros", + "Pass through": "Atravessar", + "Path": "Caminho", + "Per Edge": "Por aresta", + "Pick the tool bodies": "Selecione os corpos de ferramenta", + "Picked": "Selecionado", + "Place at the origin instead": "Colocar na origem", + "Playback": "Reprodução", + "Position": "Posição", + "Position (0 to 1)": "Posição (0 a 1)", + "Position (G0)": "Posição (G0)", + "Position along the edge, 0 at the start end, 1 at the other": "Posição ao longo da aresta: 0 na extremidade inicial, 1 na outra", + "Preview Row": "Visualizar linha", + "Preview leaves the current design unchanged.": "A visualização não altera o projeto atual.", + "Profiles/Curves": "Perfis/Curvas", + "Projection": "Projeção", + "RECENT": "RECENTES", + "RULED SURFACE": "SUPERFÍCIE REGRADA", + "Radius Fit": "Ajuste de raio", + "Ratio": "Razão", + "Reattach selected face": "Fixar novamente na face selecionada", + "Recover": "Recuperar", + "Recover unsaved design?": "Recuperar projeto não salvo?", + "Rectangular": "Retangular", + "Reference face": "Face de referência", + "Remove Tools": "Remover ferramentas", + "Remove from list": "Remover da lista", + "Remove override": "Remover substituição", + "Remove private design details or paths before sharing.": "Remova detalhes privados do projeto ou caminhos antes de compartilhar.", + "Remove screenshot": "Remover captura de tela", + "Remove the column": "Remover a coluna", + "Remove the track": "Remover a trilha", + "Remove this point": "Remover este ponto", + "Report a bug — review a screenshot and open a GitHub draft": "Relatar um bug — revise uma captura de tela e abra um rascunho no GitHub", + "Reset Toolbar": "Redefinir barra de ferramentas", + "Restore outer boundary": "Restaurar contorno externo", + "Restore the inherited component or physical material appearance": "Restaurar a aparência herdada do componente ou do material físico", + "Result": "Resultado", + "Retake screenshot": "Refazer captura de tela", + "Reverse": "Inverter", + "Reverse Direction": "Inverter direção", + "Revert": "Reverter", + "Revert All Positions": "Reverter todas as posições", + "Revert Position": "Reverter posição", + "Review the report and screenshot before opening GitHub.": "Revise o relatório e a captura de tela antes de abrir o GitHub.", + "Rim Edge": "Aresta da borda", + "Roll History Marker Here": "Mover o marcador do histórico para cá", + "Round": "Arredondado", + "Rule": "Regra", + "Save Rule": "Salvar regra", + "Save the study as an animated GIF, seen as the viewport shows it": "Salvar o estudo como GIF animado, como a janela de visualização o mostra", + "Saved preview. Geometry is being checked before editing.": "Visualização salva. A geometria está sendo verificada antes da edição.", + "Scale factor": "Fator de escala", + "Search": "Pesquisar", + "Search commands": "Pesquisar comandos", + "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Selecionar outro: mantenha o botão esquerdo parado sobre o modelo (ou clique com o botão direito › Selecionar outro…) para listar tudo sob o cursor; clique de novo no mesmo ponto para selecionar o próximo item ali. Clique duas vezes com o botão do meio para ir ao Início (Preferências › Navegação).", + "Select bodies (a face picks its body)": "Selecione corpos (uma face seleciona seu corpo)", + "Select bodies or faces instead": "Selecionar corpos ou faces em vez disso", + "Selection filter": "Filtro de seleção", + "Semantic faces share their appearance across instances.": "Faces semânticas compartilham a aparência entre instâncias.", + "Send your report on GitHub": "Envie seu relatório no GitHub", + "Shape": "Forma", + "Show Agent Cursor": "Mostrar cursor do agente", + "Show in folder": "Mostrar na pasta", + "Show the pointer an AI agent moves (#35)": "Mostrar o ponteiro que um agente de IA move (#35)", + "Signed axes": "Eixos com sinal", + "Size": "Tamanho", + "Sketch constraints": "Restrições do esboço", + "Sketch curves": "Curvas do esboço", + "Sketch dimensions": "Cotas do esboço", + "Sketch geometry and profiles": "Geometria e perfis do esboço", + "Sketch plane has no body-face attachment.": "O plano do esboço não está fixado a uma face de corpo.", + "Sketch points": "Pontos do esboço", + "Slot width": "Largura do rasgo", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "O SolidCraft fechou antes de estes projetos serem salvos. O último salvamento automático deles pode ser aberto.", + "Speed": "Velocidade", + "Stand it up": "Colocar em pé", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Colocar em pé: um quarto de volta em torno de X, como um recurso Mover que pode ser desfeito.", + "Stand this part up?": "Colocar esta peça em pé?", + "Step": "Passo", + "Steps": "Passos", + "Style": "Estilo", + "Suppressed": "Suprimido", + "Swap Ends": "Trocar extremidades", + "Tangent (G1)": "Tangente (G1)", + "Tangent Chain": "Cadeia tangente", + "Tear": "Rasgo", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "O esboço tracejado é uma guia de plano salva. Selecione uma nova face para reparar a fixação.", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "A ocorrência de autoria salva não existe mais. Selecione um posicionamento de autoria válido antes de vincular novamente.", + "Then": "Então", + "These features will be deleted:": "Estes recursos serão excluídos:", + "These features will fail:": "Estes recursos vão falhar:", + "Thickness Outside": "Espessura para fora", + "Thin": "Fino", + "Thin Extrude": "Extrusão fina", + "This child is shared. Deleting it removes it from every copy of its parent.": "Este filho é compartilhado. Excluí-lo o remove de todas as cópias do pai.", + "This child is shared. Position changes apply to every copy of its parent.": "Este filho é compartilhado. Mudanças de posição se aplicam a todas as cópias do pai.", + "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Esta face não pode fornecer uma fixação duradoura. Escolha outra face ou use explicitamente um plano fixo.", + "To Offset": "Deslocamento final", + "Tolerance": "Tolerância", + "Turn off section analysis before exporting the view.": "Desative a análise de seção antes de exportar a vista.", + "Type": "Tipo", + "UNTRIM": "DESAPARAR", + "Updating the preview": "Atualizando a visualização", + "Use active author placement": "Usar o posicionamento de autoria ativo", + "Use fixed plane": "Usar plano fixo", + "Use saved fixed plane": "Usar o plano fixo salvo", + "Use selected face as fixed plane": "Usar a face selecionada como plano fixo", + "VIEW": "VISTA", + "Value": "Valor", + "Vertices": "Vértices", + "View navigator": "Navegador de vistas", + "Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Somente corpos visíveis. As curvas usam segmentos de reta (tolerância de 0,01 mm).", + "Volume": "Volume", + "Wall": "Parede", + "Wall Location": "Posição da parede", + "Wall Thickness": "Espessura da parede", + "When": "Quando", + "Width": "Largura", + "Will fail": "Vai falhar", + "angle, height": "ângulo, altura", + "appearance.dielectric_ior": "IOR dielétrico", + "appearance.metallic": "Metálico", + "appearance.pbr_help": "Veja esta superfície em Renderizar ou em um PNG de produto. Sem refração nem transmissão.", + "appearance.pbr_opaque": "PBR opaco", + "appearance.roughness": "Rugosidade", + "appearance.surface_response": "Resposta da superfície", + "browser.body_name": "Corpo{number}", + "browser.component_name": "Componente{number}", + "browser.parameters": "Parâmetros ({count})", + "browser.precision": "Precisão: {precision}", + "browser.sketch_name": "Esboço{number}", + "browser.units": "Unidades: {units}", + "cmd.appearance_assign": "Aparência", + "cmd.appearance_library": "Biblioteca de aparências", + "cmd.appearance_list": "Listar aparências", + "cmd.body_rename": "Renomear corpo", + "cmd.browser_group": "Novo grupo", + "cmd.browser_move": "Mover itens do navegador", + "cmd.browser_order": "Ordenar itens do navegador", + "cmd.browser_rename_group": "Renomear grupo", + "cmd.browser_ungroup": "Desagrupar", + "cmd.browser_visibility": "Mostrar/Ocultar", + "cmd.canvas_calibrate": "Calibrar tela de referência", + "cmd.canvas_decal": "Decalque", + "cmd.canvas_delete": "Excluir tela de referência", + "cmd.canvas_edit": "Editar tela de referência", + "cmd.canvas_insert": "Tela de referência", + "cmd.component_activate": "Ativar componente", + "cmd.component_break_link": "Quebrar vínculo", + "cmd.component_capture_position": "Capturar posição", + "cmd.component_create": "Novo componente", + "cmd.component_delete": "Excluir componente", + "cmd.component_from_bodies": "Criar componentes a partir de corpos", + "cmd.component_insert_design": "Inserir projeto", + "cmd.component_links": "Listar vínculos", + "cmd.component_list": "Listar componentes", + "cmd.component_move_bodies": "Mover corpos para o componente", + "cmd.component_move_sketches": "Mover esboços para o componente", + "cmd.component_paste_new": "Colar novo", + "cmd.component_properties": "Propriedades físicas do componente", + "cmd.component_rename": "Renomear componente", + "cmd.component_revert_position": "Reverter posição", + "cmd.component_unlock": "Desbloquear conteúdo", + "cmd.component_update_links": "Atualizar vínculos", + "cmd.config_activate": "Ativar configuração", + "cmd.config_column": "Coluna de configuração", + "cmd.config_configure": "Configurar", + "cmd.config_preview": "Visualizar configuração", + "cmd.config_row": "Linha de configuração", + "cmd.config_rule": "Regra de configuração", + "cmd.config_rules": "Regras de configuração", + "cmd.config_table": "Exibir tabela de configurações", + "cmd.construct_axis_edge": "Eixo pela aresta", + "cmd.construct_axis_normal_to_face": "Eixo perpendicular à face", + "cmd.construct_axis_through_cylinder": "Eixo pelo cilindro/cone/toro", + "cmd.construct_axis_two_planes": "Eixo por dois planos", + "cmd.construct_axis_two_points": "Eixo por dois pontos", + "cmd.construct_plane_along_path": "Plano ao longo do caminho", + "cmd.construct_plane_midplane": "Plano médio", + "cmd.construct_plane_perpendicular": "Plano perpendicular", + "cmd.construct_plane_tangent": "Plano tangente", + "cmd.construct_plane_three_points": "Plano por três pontos", + "cmd.construct_plane_two_edges": "Plano por duas arestas", + "cmd.construct_point_along_path": "Ponto ao longo do caminho", + "cmd.construct_point_center": "Ponto no centro do círculo/esfera/toro", + "cmd.construct_point_edge_plane": "Ponto na aresta e no plano", + "cmd.construct_point_three_planes": "Ponto por três planos", + "cmd.construct_point_two_edges": "Ponto por duas arestas", + "cmd.construct_point_vertex": "Ponto no vértice", + "cmd.contact_check": "Verificar contato", + "cmd.contact_create": "Novo conjunto de contato", + "cmd.contact_disable_all": "Desativar contato", + "cmd.contact_edit": "Editar conjunto de contato", + "cmd.contact_enable_all": "Ativar todo o contato", + "cmd.contact_enable_sets": "Ativar conjuntos de contato", + "cmd.contact_list": "Listar conjuntos de contato", + "cmd.diagnostics_crash_report": "Relatório de falha", + "cmd.diagnostics_crash_reports": "Relatórios de falha", + "cmd.diagnostics_crash_reports_clear": "Excluir relatórios de falha", + "cmd.diagnostics_crash_test": "Teste de falha", + "cmd.doc_recover": "Recuperar projeto", + "cmd.doc_recovery_discard": "Descartar projeto recuperado", + "cmd.doc_recovery_list": "Projetos recuperáveis", + "cmd.document_inspect": "Inspecionar projeto", + "cmd.document_metadata": "Propriedades do projeto", + "cmd.document_metadata_remove": "Remover propriedade do projeto", + "cmd.document_metadata_set": "Alterar propriedades do projeto", + "cmd.document_units": "Alterar unidades do projeto", + "cmd.edit_checkpoint": "Ponto de restauração", + "cmd.edit_restore_checkpoint": "Restaurar ponto de restauração", + "cmd.engine_commands": "Listar comandos", + "cmd.explode_create": "Vista explodida", + "cmd.explode_delete": "Excluir vista explodida", + "cmd.explode_list": "Listar vistas explodidas", + "cmd.explode_show": "Mostrar vista explodida", + "cmd.expr_evaluate": "Avaliar expressão", + "cmd.face_delete": "Excluir face", + "cmd.file_export": "Exportar", + "cmd.file_insert_mesh": "Inserir malha", + "cmd.file_insert_step": "Inserir STEP", + "cmd.file_save_mesh": "Salvar como malha", + "cmd.file_slicers": "Fatiadores instalados", + "cmd.inspect_accessibility": "Análise de acessibilidade", + "cmd.inspect_center_of_mass": "Centro de massa", + "cmd.inspect_compare": "Comparar corpos", + "cmd.inspect_continuity": "Análise de continuidade", + "cmd.inspect_curvature_comb": "Análise de pente de curvatura", + "cmd.inspect_curvature_map": "Análise de mapa de curvatura", + "cmd.inspect_draft": "Análise de ângulo de saída", + "cmd.inspect_environment_map": "Análise de mapa de ambiente", + "cmd.inspect_interference": "Interferência", + "cmd.inspect_isocurve": "Análise de isocurvas", + "cmd.inspect_minimum_radius": "Análise de raio mínimo", + "cmd.inspect_zebra": "Análise zebra", + "cmd.joint_as_built": "Junta como construída", + "cmd.joint_create": "Junta", + "cmd.joint_delete": "Excluir junta", + "cmd.joint_drive": "Acionar juntas", + "cmd.joint_edit": "Editar junta", + "cmd.joint_gear": "Engrenagem", + "cmd.joint_limits": "Limites da junta", + "cmd.joint_list": "Listar juntas", + "cmd.joint_motion_link": "Vínculo de movimento", + "cmd.joint_origin": "Origem da junta", + "cmd.joint_rack_pinion": "Cremalheira e pinhão", + "cmd.joint_reach": "Alcançar ponto", + "cmd.joint_rigid_group": "Grupo rígido", + "cmd.joint_screw": "Parafuso", + "cmd.joint_solve": "Resolver juntas", + "cmd.library_apply": "Aplicar entrada da biblioteca local", + "cmd.library_export": "Exportar biblioteca do projeto", + "cmd.library_inspect": "Inspecionar biblioteca local", + "cmd.material_assign": "Material físico", + "cmd.material_create": "Novo material físico", + "cmd.material_delete": "Excluir material físico", + "cmd.material_edit": "Editar material físico", + "cmd.material_list": "Listar materiais", + "cmd.material_properties_directional": "Módulo de elasticidade direcional", + "cmd.material_properties_validate": "Validar dados do material físico", + "cmd.mesh_convert": "Converter malha", + "cmd.model_edges": "Listar arestas", + "cmd.model_faces": "Listar faces", + "cmd.model_threads": "Listar roscas", + "cmd.motion_delete": "Excluir estudo de movimento", + "cmd.motion_export": "Exportar estudo de movimento", + "cmd.motion_export_animation": "Exportar animação de movimento", + "cmd.motion_list": "Listar estudos de movimento", + "cmd.motion_play": "Reproduzir estudo de movimento", + "cmd.motion_study": "Estudo de movimento", + "cmd.motion_trace": "Traçado de movimento", + "cmd.motion_trace_keep": "Manter traçado de movimento", + "cmd.occurrence_copy": "Colar (instância)", + "cmd.occurrence_ground": "Fixar no solo", + "cmd.occurrence_move": "Mover ocorrência", + "cmd.occurrence_properties": "Propriedades físicas da ocorrência", + "cmd.parameters_add": "Adicionar parâmetro do usuário", + "cmd.parameters_change": "Alterar parâmetros", + "cmd.parameters_comment": "Comentar parâmetro", + "cmd.parameters_complete": "Completar expressão", + "cmd.parameters_delete": "Excluir parâmetro", + "cmd.parameters_export": "Exportar parâmetros", + "cmd.parameters_favorite": "Favoritar parâmetro", + "cmd.parameters_graph": "Grafo de parâmetros", + "cmd.parameters_import": "Importar parâmetros", + "cmd.parameters_list": "Listar parâmetros", + "cmd.parameters_move": "Mover parâmetro", + "cmd.parameters_rename": "Renomear parâmetro", + "cmd.parameters_users": "Usuários do parâmetro", + "cmd.parts_fastener": "Inserir fixador", + "cmd.parts_insert": "Inserir peça", + "cmd.parts_library": "Peças padrão", + "cmd.parts_resize": "Alterar tamanho da peça", + "cmd.plastic_assign_rule": "Atribuir regra de plástico", + "cmd.plastic_boss": "Ressalto", + "cmd.plastic_lip": "Lábio", + "cmd.plastic_manage_rules": "Gerenciar regras de plástico", + "cmd.plastic_rest": "Apoio", + "cmd.plastic_rules": "Listar regras de plástico", + "cmd.plastic_snap_fit": "Encaixe por pressão", + "cmd.render_backends": "Backends de renderização", + "cmd.render_cancel": "Cancelar renderização", + "cmd.render_export": "Exportar imagem renderizada", + "cmd.render_preflight": "Verificar pedido de renderização", + "cmd.render_scene": "Inspecionar cena de renderização", + "cmd.render_settings_apply": "Aplicar câmera de renderização", + "cmd.render_settings_get": "Configurações de renderização", + "cmd.render_settings_set": "Salvar configurações de renderização", + "cmd.render_start": "Renderizar imagem", + "cmd.render_status": "Progresso da renderização", + "cmd.select_clear": "Limpar seleção", + "cmd.sheet_convert": "Converter em chapa metálica", + "cmd.sheet_export_bend_table": "Exportar tabela de dobras", + "cmd.sheet_export_dxf": "Exportar planificação como DXF", + "cmd.sheet_flange": "Flange", + "cmd.sheet_flat_pattern": "Criar planificação", + "cmd.sheet_fold": "Dobrar", + "cmd.sheet_hem": "Bainha", + "cmd.sheet_manage_rules": "Regras de chapa metálica", + "cmd.sheet_perforate": "Perfurar", + "cmd.sheet_refold": "Redobrar", + "cmd.sheet_rules": "Listar regras de chapa metálica", + "cmd.sheet_unfold": "Desdobrar", + "cmd.sketch_arc_center_point": "Arco por ponto central", + "cmd.sketch_arc_tangent": "Arco tangente", + "cmd.sketch_arc_three_point": "Arco por 3 pontos", + "cmd.sketch_auto_constrain": "Restrição automática", + "cmd.sketch_auto_constrain_from_datum": "Restrição automática a partir da referência", + "cmd.sketch_auto_project": "Projetar arestas automaticamente na referência", + "cmd.sketch_blend_curve": "Curva de concordância", + "cmd.sketch_chain": "Cadeia", + "cmd.sketch_chamfer_distance_angle": "Chanfro por distância e ângulo", + "cmd.sketch_chamfer_equal_distance": "Chanfro de distâncias iguais", + "cmd.sketch_chamfer_two_distance": "Chanfro de duas distâncias", + "cmd.sketch_circle_center": "Círculo por centro e diâmetro", + "cmd.sketch_circle_three_point": "Círculo por 3 pontos", + "cmd.sketch_circle_three_tangent": "Círculo tangente a 3", + "cmd.sketch_circle_two_point": "Círculo por 2 pontos", + "cmd.sketch_circle_two_tangent": "Círculo tangente a 2", + "cmd.sketch_constrainer": "Restringidor de esboço", + "cmd.sketch_constraint_fix": "Fixar/Liberar", + "cmd.sketch_constraint_midpoint": "Ponto médio", + "cmd.sketch_construction": "Normal/Construção", + "cmd.sketch_copy": "Copiar entidades do esboço", + "cmd.sketch_cut": "Recortar entidades do esboço", + "cmd.sketch_delete": "Excluir entidades do esboço", + "cmd.sketch_dimension_text": "Mover texto da cota", + "cmd.sketch_drag": "Arrastar geometria do esboço", + "cmd.sketch_drag_end": "Terminar arrasto do esboço", + "cmd.sketch_draw_dimensioned": "Desenhar geometria cotada", + "cmd.sketch_edit": "Editar esboço", + "cmd.sketch_edit_text": "Editar texto", + "cmd.sketch_export_dxf": "Salvar como DXF", + "cmd.sketch_finish_auto_constrain": "Concluir com restrição automática", + "cmd.sketch_fit_curves_to_section": "Ajustar curvas à seção da malha", + "cmd.sketch_glyphs": "Símbolos de restrição", + "cmd.sketch_include_3d": "Incluir geometria 3D", + "cmd.sketch_infinite": "Linha infinita", + "cmd.sketch_insert_dxf": "Inserir DXF", + "cmd.sketch_insert_svg": "Inserir SVG", + "cmd.sketch_inspect": "Inspecionar esboço", + "cmd.sketch_intersection_curve": "Curva de interseção", + "cmd.sketch_isoparametric_curve": "Curva isoparamétrica", + "cmd.sketch_line3d": "Linha 3D", + "cmd.sketch_line_midpoint": "Linha pelo ponto médio", + "cmd.sketch_move": "Mover/Copiar entidades do esboço", + "cmd.sketch_move3d": "Mover ponto 3D", + "cmd.sketch_move_point": "Arrastar ponto do esboço", + "cmd.sketch_offset_break": "Quebrar associação de deslocamento", + "cmd.sketch_options": "Opções da paleta de esboço", + "cmd.sketch_paste": "Colar entidades do esboço", + "cmd.sketch_point3d": "Ponto 3D", + "cmd.sketch_polygon_circumscribed": "Polígono circunscrito", + "cmd.sketch_polygon_edge": "Polígono por aresta", + "cmd.sketch_polygon_inscribed": "Polígono inscrito", + "cmd.sketch_project_to_surface": "Projetar na superfície", + "cmd.sketch_rectangle_center": "Retângulo pelo centro", + "cmd.sketch_rectangle_rounded": "Retângulo arredondado", + "cmd.sketch_rectangle_three_point": "Retângulo por 3 pontos", + "cmd.sketch_rectangle_two_point": "Retângulo por 2 pontos", + "cmd.sketch_redefine": "Redefinir plano do esboço", + "cmd.sketch_slot_arc_center": "Rasgo em arco por ponto central", + "cmd.sketch_slot_arc_three_point": "Rasgo em arco por três pontos", + "cmd.sketch_slot_center_point": "Rasgo por ponto central", + "cmd.sketch_slot_center_to_center": "Rasgo de centro a centro", + "cmd.sketch_slot_overall": "Rasgo pelo comprimento total", + "cmd.sketch_snap": "Inferência de encaixe", + "cmd.sketch_solve": "Resolver esboço", + "cmd.sketch_spline3d": "Spline 3D", + "cmd.sketch_spline_control_point": "Spline por pontos de controle", + "cmd.sketch_spline_control_point_5": "Spline por pontos de controle (grau 5)", + "cmd.sketch_spline_fit_point": "Spline por pontos de ajuste", + "cmd.sketch_spun_profile": "Perfil de revolução", + "cmd.sketch_toggle_driven": "Alternar cota conduzida", + "cmd.solid_align": "Alinhar", + "cmd.solid_boundary_fill": "Preenchimento de contorno", + "cmd.solid_bounding_solid": "Sólido envolvente", + "cmd.solid_emboss": "Gravar em relevo", + "cmd.solid_move": "Mover/Copiar", + "cmd.solid_offset_face": "Deslocar face", + "cmd.solid_press_pull": "Empurrar/Puxar", + "cmd.solid_remove": "Remover", + "cmd.solid_replace_face": "Substituir face", + "cmd.solid_rib": "Nervura", + "cmd.solid_split_face": "Dividir face", + "cmd.solid_web": "Alma", + "cmd.surface_blend": "Superfície de concordância", + "cmd.surface_boundary": "Superfície de contorno", + "cmd.surface_extrude": "Extrusão de superfície", + "cmd.surface_fair": "Suavizar superfície", + "cmd.surface_fillet": "Concordância de superfície", + "cmd.surface_loft": "Loft de superfície", + "cmd.surface_match": "Casar superfície", + "cmd.surface_offset": "Deslocar superfície", + "cmd.surface_patch": "Remendo", + "cmd.surface_reverse_normal": "Inverter normal", + "cmd.surface_revolve": "Revolução de superfície", + "cmd.surface_ruled": "Superfície regrada", + "cmd.surface_stitch": "Costurar", + "cmd.surface_sweep": "Varredura de superfície", + "cmd.surface_thicken": "Espessar", + "cmd.surface_unstitch": "Descosturar", + "cmd.surface_untrim": "Desaparar", + "cmd.timeline_add": "Adicionar recurso gravado", + "cmd.timeline_compute_all": "Calcular tudo", + "cmd.timeline_copy": "Copiar recursos", + "cmd.timeline_dependents": "Dependentes do recurso", + "cmd.timeline_export_script": "Exportar script de comandos", + "cmd.timeline_inspect": "Inspecionar recurso", + "cmd.timeline_paste": "Colar recursos", + "cmd.timeline_redefine": "Editar recurso", + "cmd.timeline_rename": "Renomear", + "cmd.timeline_reorder": "Reordenar recurso", + "cmd.timeline_roll_to": "Mover marcador do histórico", + "cmd.timeline_rollback": "Mover marcador da linha do tempo", + "cmd.timeline_suppress": "Suprimir recurso", + "cmd.view_apply": "Restaurar vista nomeada", + "cmd.view_delete": "Excluir vista nomeada", + "cmd.view_list": "Listar vistas nomeadas", + "cmd.view_navigate": "Navegar na vista", + "cmd.view_rename": "Renomear vista nomeada", + "cmd.view_save": "Nova vista nomeada", + "command name": "nome do comando", + "coupling.gear_1": "Engrenagem 1", + "coupling.gear_1_pick": "Engrenagem 1 (opcional)", + "coupling.gear_2": "Engrenagem 2", + "coupling.gear_2_pick": "Engrenagem 2 (opcional)", + "coupling.internal": "Engrenagem interna", + "coupling.needs_turn_and_slide": "precisa de uma junta que gire e outra que deslize", + "coupling.needs_turns": "precisa de duas juntas que girem", + "coupling.not_round": "não é uma face circular", + "coupling.nut": "Porca", + "coupling.picked": "selecionado", + "coupling.pinion": "Pinhão", + "coupling.pinion_pick": "Pinhão (opcional)", + "coupling.pitch": "Passo", + "coupling.rack": "Cremalheira", + "coupling.radius_1": "Raio 1", + "coupling.radius_2": "Raio 2", + "dialog.computing": "Calculando… {seconds} s", + "dialog.custom_axis": "↖ Eixo personalizado", + "dialog.edit_title": "EDITAR {title}", + "dialog.select": "↖ Selecionar", + "dialog.selected_count": "↖ {count} selecionados", + "dialog.selection_guidance": "Selecione uma entrada para alterá-la. Clique nos objetos selecionados para removê-los; Ctrl/Cmd-clique também os alterna. Revise a visualização e pressione OK.", + "dialog.selection_step": "{step} de {total}: selecione {input}", + "dialog.step": "Passo", + "document.save_changes": "Salvar as alterações em {name}?", + "document.unsaved_changes": "{name} tem alterações não salvas. Se você não salvar, elas serão perdidas.", + "drive.stopped_by_contact": "Parado em {value}: {a} atravessaria {b}", + "drive.stopped_by_loop": "Parado em {value}: o laço por {joint} não pode fechar mais", + "drive.unconnected": "Não move nada: {part} não está conectado a nada fixo", + "expression, e.g. 25 mm": "expressão, p. ex. 25 mm", + "fits the face, e.g. M8": "se ajusta à face, p. ex. M8", + "from the rule": "da regra", + "home.documentation": "Documentação", + "home.in_this_browser": "neste navegador", + "home.missing": "ausente", + "home.open": "Abrir…", + "home.opened_days_ago": "Aberto há {count} dias", + "home.opened_hours_ago": "Aberto há {count} h", + "home.opened_just_now": "Aberto agora mesmo", + "home.opened_minutes_ago": "Aberto há {count} min", + "home.opening": "abrindo…", + "home.recent": "Recentes", + "home.report_issue": "Relatar um problema", + "home.samples": "Exemplos", + "home.whats_new": "Novidades", + "install.button_tip": "Instale o SolidCraft como aplicativo: ele abre em sua própria janela e funciona offline", + "install.dock_1": "Escolha Arquivo › Adicionar ao Dock.", + "install.dock_2": "Clique em Adicionar.", + "install.dock_after": "O SolidCraft passa a abrir em sua própria janela pelo Dock e funciona offline.", + "install.done": "Concluído", + "install.home_screen_1": "Toque em Compartilhar (no menu … se não estiver na barra de ferramentas).", + "install.home_screen_2": "Escolha Adicionar à Tela de Início.", + "install.home_screen_3": "Toque em Adicionar.", + "install.home_screen_after": "O SolidCraft passa a abrir pelo ícone na Tela de Início, sem as barras do Safari, e funciona offline.", + "install.menu": "Instalar aplicativo…", + "install.steps_intro": "O Safari instala aplicativos web pelos próprios menus:", + "install.title": "Instalar o SolidCraft", + "joint.from_bodies_hint": "Cada corpo selecionado vai para um novo componente próprio e permanece onde está.", + "joint.one_body": "As duas seleções estão em {body}. Selecione a segunda em outra peça.", + "joint.one_component": "Estas peças são corpos de um mesmo componente: {bodies}. Uma junta move um componente em relação a outro, então cada peça precisa de seu próprio componente.", + "nav.touchpad.help": "Segure Shift e mova o ponteiro para deslocar; segure Alt/Option e mova para orbitar. Não é preciso botão do mouse. A rolagem vertical aplica zoom.", + "nav.touchpad.label": "Touchpad", + "nav.touchpad.orbit": "Orbitar (segure Alt/Option e mova; sem botão do mouse)", + "nav.touchpad.pan": "Deslocar (segure Shift e mova; sem botão do mouse)", + "nav.touchpad.scroll": "O touchpad usa a rolagem vertical para zoom. Sua configuração de deslocamento com dois dedos é mantida para as outras predefinições.", + "nav.touchpad.zoom": "Zoom (rolagem vertical ou pinça)", + "needs two joints": "precisa de duas juntas", + "new configuration": "nova configuração", + "new name": "novo nome", + "new parameter": "novo parâmetro", + "no interference": "sem interferência", + "no joint that moves yet": "ainda não há junta que se mova", + "no picture": "sem imagem", + "pattern.alignment_2": "Alinhamento 2", + "pattern.alignment_hint": "As contagens incluem o original. Centralizar equilibra as cópias; Inverter escolhe o lado extra para totais pares.", + "pattern.direction_1": "Direção 1", + "pattern.direction_2": "Direção 2", + "pattern.flip_direction": "Inverter direção", + "pick a hole to seat it, or OK places it at the origin": "selecione um furo para assentá-la, ou OK a coloca na origem", + "pick one or two vertices, edges or faces": "selecione um ou dois vértices, arestas ou faces", + "render.background": "Fundo da cena", + "render.fit": "Enquadrar produto", + "render.image_cancel": "Cancelar renderização", + "render.image_cancelled": "Renderização cancelada", + "render.image_cancelling": "Cancelando", + "render.image_check": "Verificar pedido de renderização", + "render.image_completed": "Imagem pronta para exportar", + "render.image_encoding": "Codificando PNG", + "render.image_export": "Exportar PNG", + "render.image_failed": "Falha na renderização", + "render.image_height": "Altura", + "render.image_help": "Imagem de pré-visualização por CPU · PNG · transparência aproximada", + "render.image_overwrite": "Substituir arquivo existente", + "render.image_preparing": "Preparando imagem", + "render.image_queued": "Aguardando para renderizar", + "render.image_reduce": "Tente uma imagem menor ou uma cena mais simples.", + "render.image_running": "Renderizando imagem", + "render.image_stale": "Esta imagem usa a cena capturada antes das alterações seguintes.", + "render.image_start": "Iniciar renderização", + "render.image_supported": "O pedido de renderização é suportado; a fila e o pool de memória são verificados de novo no início.", + "render.image_title": "Renderizar imagem", + "render.image_too_large": "Acima do limite de imagem: 4096 pixels por lado e 4.194.304 pixels no total.", + "render.image_transparent": "Fundo transparente", + "render.image_unknown": "Estado da renderização indisponível", + "render.image_use_largest": "Usar o maior tamanho nesta proporção:", + "render.image_width": "Largura", + "render.navigation_help": "A câmera se move como em Projeto (Preferências › Navegação). Salvar configuração grava a câmera atual.", + "render.opaque_image_summary": "PNG de pré-visualização · PBR opaco · transparência mesclada", + "render.opaque_preview_help": "PBR opaco e cores simples; transparência mesclada. Refração, HDRI e renderização final ainda não estão disponíveis.", + "render.perspective": "Câmera em perspectiva", + "render.preview": "Pré-visualização integrada", + "render.preview_help": "Sombreamento rasterizado e transparência mesclada. Refração, HDRI e renderização final ainda não estão disponíveis.", + "render.reload_settings": "Recarregar configurações salvas", + "render.restore_camera": "Restaurar câmera salva", + "render.return_design": "Voltar ao projeto", + "render.save_setup": "Salvar configuração", + "render.setup_name": "Nome da configuração", + "render.unavailable_preview": "Esta configuração pede um perfil de pré-visualização indisponível.", + "render.unsaved": "Alterações de pré-visualização não salvas", + "render.use_preview": "Usar pré-visualização integrada", + "sample.bracket.about": "Flange base com flanges de aresta e uma bainha, com regra de 2 mm", + "sample.bracket.name": "Suporte de chapa metálica", + "sample.enclosure.about": "Caixa oca com lábio, ressaltos de parafuso, apoio e encaixe por pressão", + "sample.enclosure.name": "Gabinete plástico", + "sample.flange.about": "Cubo e flange com padrão circular controlado por um parâmetro", + "sample.flange.name": "Flange aparafusado", + "sample.hinge.about": "Dois componentes e uma junta de revolução, acionada até 60°", + "sample.hinge.name": "Montagem de dobradiça", + "sample.plate.about": "Placa paramétrica com concordâncias, furos e um ressalto furado", + "sample.plate.name": "Placa de exemplo", + "sample.vents.about": "Rasgos em padrão retangular: linhas, colunas e passo são parâmetros", + "sample.vents.name": "Placa de ventilação", + "settings.display_quality_note": "Níveis mais finos desenham faces e arestas curvas mais suaves e demoram mais para gerar a malha. Só a janela de visualização muda, nunca o projeto ou as exportações.", + "settings.frame_rate_note": "Mostra quadros por segundo no canto inferior direito da vista. Enquanto estiver ativo, a vista é redesenhada continuamente.", + "settings.measure_axis_distances": "Mostrar distâncias X/Y/Z", + "settings.measure_axis_distances_help": "Mostrar as componentes nos eixos do mundo junto com a distância total enquanto Medir está aberto.", + "settings.msaa_applies_on_restart": "O antisserrilhamento vale na próxima vez que o SolidCraft iniciar", + "settings.msaa_reset": "{setting}: {requested}× não é suportado por este dispositivo gráfico; agora é {reset}× (suportados: {supported}).", + "settings.msaa_unsupported": "Não suportado por este dispositivo gráfico", + "settings.reset_intro": "Estas configurações não funcionam neste computador e impediriam o SolidCraft de iniciar, por isso foram alteradas:", + "settings.reset_title": "As configurações foram alteradas", + "settings.supersampling_note": "Desenha a vista em resolução maior e a filtra para baixo: arestas, linhas e grade mais suaves em telas abaixo de 4K. Custa tempo de GPU: cerca de 2,25× os pixels em 1,5× e 4× em 2×.", + "sketch.degrees_of_freedom": "{count} graus de liberdade", + "sketch.draw_curves": "Desenhar como {linetype}", + "sketch.make_selection": "Converter a seleção em {linetype}", + "sketch_text.align_center": "Centro", + "sketch_text.align_left": "Esquerda", + "sketch_text.align_right": "Direita", + "sketch_text.bold": "Negrito", + "sketch_text.builtin_font": "{family} (incorporada)", + "sketch_text.font_search": "Pesquisar fontes", + "sketch_text.italic": "Itálico", + "sketch_text.loading_fonts": "Procurando fontes instaladas…", + "sketch_text.on_path": "O texto segue seu caminho: a curva o posiciona", + "sketch_text.path_clear": "Tirar o texto da curva", + "sketch_text.path_hint": "Uma curva do esboço que o texto segue: clique aqui e depois na curva", + "sketch_text.use_font_file": "Usar o arquivo de fonte {path}", + "the parts library is not available": "a biblioteca de peças não está disponível", + "timeline.group": "Nova pasta de recursos", + "timeline.move_many": "Mover itens da linha do tempo", + "timeline.move_to_group": "Mover recursos para a pasta", + "timeline.rename_group": "Renomear pasta de recursos", + "timeline.reorder_many": "Reordenar recursos", + "timeline.ungroup": "Remover pastas de recursos", + "to the next face": "até a próxima face", + "toolbar.image": "IMAGEM", + "toolbar.render": "RENDERIZAR", + "toolbar.render_scene": "CENA", + "trace.points": "{count} pontos ao longo do caminho", + "trace.stopped_by_contact": "Termina na amostra {sample}: {a} atravessaria {b}", + "trace.stopped_by_loop": "Termina na amostra {sample}: o laço por {joint} não pode fechar mais", + "ui.1_degree_of_freedom": "1 grau de liberdade", + "ui.3d_mouse_speed": "Velocidade do mouse 3D", + "ui.3d_mouse_windows": "Mouse 3D", + "ui.3d_sketch": "Esboço 3D", + "ui.about": "Sobre", + "ui.activate": "Ativar", + "ui.active_component": "Componente ativo", + "ui.agent_chat": "Chat com agente", + "ui.agent_chat_allow": "Permitir", + "ui.agent_chat_allowed": "Permitido", + "ui.agent_chat_answered": "Resposta: {option}", + "ui.agent_chat_approval": "Permitir que o agente faça isto?", + "ui.agent_chat_attach_view": "Anexar vista", + "ui.agent_chat_attach_view_tip": "Enviar uma imagem da vista atual com a mensagem", + "ui.agent_chat_auth_agent": "Entrar com {name}", + "ui.agent_chat_auth_env": "Defina {vars} no seu ambiente e reinicie o SolidCraft.", + "ui.agent_chat_auth_needed": "O agente pede que você entre. Você entra no próprio agente; o SolidCraft nunca vê sua senha ou chaves.", + "ui.agent_chat_auth_none": "O agente não oferece forma de entrar aqui: entre do jeito descrito na documentação dele.", + "ui.agent_chat_auth_retry": "Já entrei: conectar de novo", + "ui.agent_chat_auth_terminal": "Execute isto em um terminal e depois pressione Conectar de novo:", + "ui.agent_chat_auth_title": "Entrar no agente", + "ui.agent_chat_cancel": "Cancelar", + "ui.agent_chat_changes": "Alterações: {n}, um passo de desfazer", + "ui.agent_chat_changes_of": "{n}/{limit} alterações", + "ui.agent_chat_close": "Fechar", + "ui.agent_chat_command": "Comando do agente", + "ui.agent_chat_connect": "Conectar", + "ui.agent_chat_copy": "Copiar", + "ui.agent_chat_custom_hint": "Qualquer programa que fale o Agent Client Protocol por stdin e stdout. Nenhum shell o executa.", + "ui.agent_chat_denied": "Negado", + "ui.agent_chat_deny": "Negar", + "ui.agent_chat_desktop_only": "O chat com agente precisa do aplicativo para desktop.", + "ui.agent_chat_detecting": "Procurando agentes…", + "ui.agent_chat_dock_left": "Encaixar à esquerda", + "ui.agent_chat_dock_right": "Encaixar à direita", + "ui.agent_chat_edit": "Editar", + "ui.agent_chat_exited": "O agente parou.", + "ui.agent_chat_failed_start": "O agente não pôde iniciar: {error}", + "ui.agent_chat_intro": "Converse com um agente de programação que você já usa, ou com um endpoint de modelo que você escolher. Ele trabalha no projeto aberto pelas ferramentas do SolidCraft: as alterações aparecem conforme são feitas e se desfazem em um passo por mensagem. O que ele pode fazer sem perguntar é definido em Preferências > IA.", + "ui.agent_chat_key_in_env": "chave definida", + "ui.agent_chat_left": "Esquerda", + "ui.agent_chat_limit": "O agente atingiu o limite de {limit} alterações por mensagem. Envie outra mensagem para que ele continue.", + "ui.agent_chat_minimize": "Minimizar para uma faixa", + "ui.agent_chat_model_tip": "O modelo que o agente usa. Sua escolha é lembrada para este agente.", + "ui.agent_chat_new": "Novo chat", + "ui.agent_chat_new_confirm": "Começar um novo chat? O atual será apagado.", + "ui.agent_chat_new_yes": "Novo chat", + "ui.agent_chat_no_cli": "O solidcraft-cli não foi encontrado junto ao aplicativo, então o agente não consegue acessar o projeto.", + "ui.agent_chat_no_control": "O endpoint do chat com agente não iniciou, então o agente não consegue acessar o projeto.", + "ui.agent_chat_no_images": "Este agente não aceita imagens", + "ui.agent_chat_none_found": "Nenhum agente de programação encontrado. Instale um destes e pressione Atualizar:", + "ui.agent_chat_none_found_short": "Nenhum agente encontrado", + "ui.agent_chat_not_installed": "Não instalado", + "ui.agent_chat_not_signed_in": "não conectado", + "ui.agent_chat_permission": "O agente pede para executar: {title}", + "ui.agent_chat_pick": "Agente", + "ui.agent_chat_placeholder": "Peça ao agente para alterar o projeto…", + "ui.agent_chat_placeholder_busy": "Enfileirar uma mensagem para quando o agente terminar (Ctrl+Enter: enviar agora)", + "ui.agent_chat_privacy": "Nada vai para lugar algum além do agente que você executa, na sua própria conta.", + "ui.agent_chat_privacy_note": "O SolidCraft não envia nada a lugar nenhum: o agente que você executa fala com o próprio serviço, na sua própria conta. O SolidCraft nunca vê nem guarda chaves ou senhas.", + "ui.agent_chat_queue": "Fila", + "ui.agent_chat_queue_full": "Há mensagens demais esperando: remova uma ou aguarde o agente.", + "ui.agent_chat_queued": "Na fila", + "ui.agent_chat_queued_stopped": "Na fila (parado, não enviado)", + "ui.agent_chat_refresh": "Atualizar", + "ui.agent_chat_refused": "Não permitido para o agente: {reason}", + "ui.agent_chat_remove": "Remover da fila", + "ui.agent_chat_right": "Direita", + "ui.agent_chat_save": "Salvar", + "ui.agent_chat_send": "Enviar", + "ui.agent_chat_send_now": "Enviar agora", + "ui.agent_chat_send_now_tip": "Parar o passo atual do agente e enviar esta em seguida (Ctrl+Enter)", + "ui.agent_chat_side": "Lado do chat com agente", + "ui.agent_chat_signed_in": "conectado", + "ui.agent_chat_state_auth": "É preciso entrar", + "ui.agent_chat_state_busy": "Trabalhando…", + "ui.agent_chat_state_exited": "Agente parado", + "ui.agent_chat_state_off": "Não conectado", + "ui.agent_chat_state_ready": "Pronto", + "ui.agent_chat_state_starting": "Iniciando…", + "ui.agent_chat_stop": "Parar", + "ui.agent_chat_stop_tip": "Parar o agente e tudo o que ele iniciou", + "ui.agent_chat_stop_turn_tip": "Parar o agente (Esc). As mensagens na fila continuam na fila.", + "ui.agent_chat_turn_limit": "Alterações por mensagem", + "ui.agent_chat_undo_changes": "Desfazer estas alterações", + "ui.agent_chat_undo_label": "Chat com agente: {message}", + "ui.agent_chat_undone": "(desfeito)", + "ui.agent_chat_view_attached": "Vista anexada", + "ui.agent_cursor": "Cursor do agente", + "ui.agent_cursor_speed": "Velocidade do cursor do agente", + "ui.ai_add": "Adicionar", + "ui.ai_add_agent": "Adicionar agente…", + "ui.ai_add_agent_title": "Adicionar agente", + "ui.ai_add_api": "API compatível com OpenAI", + "ui.ai_add_custom": "Comando personalizado", + "ui.ai_add_installed": "Agente instalado", + "ui.ai_add_installed_note": "Uma entrada própria para um agente instalado, por exemplo com outros argumentos. Os agentes instalados são listados por si mesmos.", + "ui.ai_added": "adicionado", + "ui.ai_agent_mode_tip": "O modo do próprio agente: as ferramentas dele (shell, edição de arquivos) o seguem. As ferramentas do SolidCraft seguem as permissões em Preferências > IA.", + "ui.ai_agents": "Agentes", + "ui.ai_always_allow": "Sempre permitir", + "ui.ai_always_allow_tip": "Permitir {tool} para este agente daqui em diante, sem perguntar", + "ui.ai_always_allowed": "Sempre permitidos", + "ui.ai_always_allowed_none": "Nada é sempre permitido ainda. As respostas \"Sempre permitir\" que você der no chat aparecem aqui.", + "ui.ai_auto_allowed": "Permitido automaticamente: {title} ({why})", + "ui.ai_auto_mode": "sua configuração de permissão", + "ui.ai_auto_ours": "o SolidCraft verifica as próprias ferramentas", + "ui.ai_auto_remembered": "você escolheu Sempre permitir", + "ui.ai_bad_url": "Digite uma URL que comece com http:// ou https://", + "ui.ai_base_url": "URL base", + "ui.ai_button": "IA", + "ui.ai_copy_suffix": "cópia", + "ui.ai_custom_url": "URL personalizada", + "ui.ai_default": "Padrão", + "ui.ai_http_busy": "o endpoint está ocupado ou acima do limite; tente de novo mais tarde", + "ui.ai_http_key": "o endpoint recusou a chave: verifique-a em Preferências > IA", + "ui.ai_http_not_found": "endpoint ou modelo inexistente: verifique a URL base e o nome do modelo", + "ui.ai_key": "Chave de API", + "ui.ai_key_hint": "opcional; guardada no chaveiro do sistema", + "ui.ai_key_needs_https": "Uma chave só é enviada por HTTPS ou para este computador.", + "ui.ai_key_note": "Guardada no chaveiro do sistema, nunca nas configurações do SolidCraft. Deixe em branco para um servidor local.", + "ui.ai_keychain_error": "O chaveiro do sistema recusou: {error}", + "ui.ai_mode_all": "Permitir tudo", + "ui.ai_mode_all_note": "Nada pergunta antes. Os relatórios de falha continuam fora de alcance e os limites de pasta ainda valem.", + "ui.ai_mode_all_warning": "O agente pode salvar, sobrescrever, exportar e substituir seu projeto sem perguntar. Use isto só com um agente em que você confie e em projetos que você já salvou.", + "ui.ai_mode_ask": "Perguntar sempre", + "ui.ai_mode_ask_note": "Cada alteração no projeto e cada ação com arquivos aguarda o seu Permitir.", + "ui.ai_mode_edits": "Permitir edições do modelo automaticamente", + "ui.ai_mode_edits_note": "Comandos de modelagem rodam sem perguntar; salvar, abrir, exportar e outras ações com arquivos ou destrutivas ainda perguntam.", + "ui.ai_mode_global": "Como definido acima", + "ui.ai_model": "Modelo", + "ui.ai_modes_scope": "Estas configurações valem para as ferramentas do SolidCraft. As ferramentas do próprio agente (shell, edição de arquivos) seguem o modo do agente, que você escolhe no cabeçalho do painel de chat quando o agente tem modos.", + "ui.ai_name": "Nome", + "ui.ai_need_command": "Digite o comando que inicia o agente", + "ui.ai_need_model": "Digite o nome do modelo", + "ui.ai_no_answer": "O agente não respondeu a tempo", + "ui.ai_no_http": "Esta versão não consegue acessar endpoints de API", + "ui.ai_no_keychain": "O chaveiro do sistema não está disponível, então não é possível guardar uma chave. Um servidor local sem chave ainda funciona.", + "ui.ai_panel": "Painel", + "ui.ai_permissions": "Permissões", + "ui.ai_preset": "Predefinição", + "ui.ai_remove": "Remover", + "ui.ai_request_limit": "parou após 24 requisições para uma mensagem; envie outra mensagem para continuar", + "ui.ai_reset": "Redefinir", + "ui.ai_settings": "Configurações de IA…", + "ui.ai_show_features": "Mostrar recursos de IA", + "ui.ai_show_features_note": "O chat com agente: um painel onde um agente de programação que você já usa, ou um endpoint de modelo que você escolher, trabalha no projeto aberto. Desativado: sem botão de IA, atalho, item de menu ou painel, e nada é procurado nem iniciado.", + "ui.ai_switch_tip": "Trocar o agente desta conversa", + "ui.ai_test": "Testar", + "ui.ai_test_acp_ok": "Responde: {agent}", + "ui.ai_test_acp_tip": "Inicia o agente por um instante e pede uma sessão; depois o encerra", + "ui.ai_test_api_tip": "Pede ao endpoint a lista de modelos", + "ui.ai_test_no_model": "Acessado: {count} modelos, mas não {model}", + "ui.ai_test_ok": "Acessado: {count} modelos", + "ui.ai_testing": "Testando…", + "ui.ai_tool_done": "concluído", + "ui.ai_tool_failed": "falhou", + "ui.ai_tool_running": "executando", + "ui.ai_tool_unfold": "Clique para ver o que retornou", + "ui.ai_tool_waiting": "aguardando", + "ui.ai_toolbar_button": "Mostrar botão na barra de ferramentas", + "ui.ai_toolbar_button_note": "O botão de IA no fim direito da barra de ferramentas. Ctrl+Shift+A e o menu Exibir ainda abrem o painel.", + "ui.ai_undo_tip": "Desfazer tudo o que o agente alterou nesta mensagem, em um passo", + "ui.all": "Tudo", + "ui.analysis": "Análise", + "ui.angle": "Ângulo", + "ui.angle_decimals": "Casas decimais de ângulo", + "ui.animateJoint": "Animar junta", + "ui.animate_view_changes": "Animar mudanças de vista", + "ui.animation": "Animação", + "ui.animation_speed": "Velocidade da animação", + "ui.anti_aliasing": "Antisserrilhamento", + "ui.apply": "Aplicar", + "ui.arc": "Arco", + "ui.assemble": "Montar", + "ui.autosave_every": "Salvar automaticamente a cada", + "ui.axes": "Eixos", + "ui.axis": "Eixo", + "ui.base_point": "Ponto base", + "ui.blocked": "Bloqueado", + "ui.bodies": "Corpos", + "ui.box": "Caixa", + "ui.break": "Quebrar", + "ui.calibrate": "Calibrar", + "ui.cancel": "Cancelar", + "ui.canvases": "Telas de referência", + "ui.center": "Centro", + "ui.centerline": "Linha de centro", + "ui.chain": "Cadeia", + "ui.chamfer": "Chanfro", + "ui.chamfer_type": "Tipo de chanfro", + "ui.change_workspace": "Mudar espaço de trabalho", + "ui.chord_length": "Comprimento da corda", + "ui.circle": "Círculo", + "ui.circular_pattern": "Padrão circular", + "ui.clear": "Limpar", + "ui.clear_recent": "Limpar recentes", + "ui.clear_the_selection": "Limpar a seleção", + "ui.click_selects_whole_bodies": "O clique seleciona corpos inteiros", + "ui.click_then_press_key": "Clique e depois pressione a nova tecla", + "ui.close": "Fechar", + "ui.coil": "Espiral", + "ui.coincident": "Coincidente", + "ui.collapse": "Recolher", + "ui.collinear": "Colinear", + "ui.colour_vision": "Visão de cores", + "ui.colour_vision_deutan": "Deutan", + "ui.colour_vision_deutan_tip": "Para percepção do verde fraca ou ausente", + "ui.colour_vision_failed": "Falhou", + "ui.colour_vision_fixed": "Fixo", + "ui.colour_vision_mode": "Modo", + "ui.colour_vision_note": "Muda as cores que carregam significado: estados do esboço, eixos, dobras, análises e ícones. Se você usa filtros de cor do Windows, deixe isto desativado.", + "ui.colour_vision_off": "Desativado", + "ui.colour_vision_off_tip": "As cores do próprio tema", + "ui.colour_vision_projected": "Projetado", + "ui.colour_vision_protan": "Protan", + "ui.colour_vision_protan_tip": "Para percepção do vermelho fraca ou ausente", + "ui.colour_vision_sample": "Amostra", + "ui.colour_vision_tritan": "Tritan", + "ui.colour_vision_tritan_tip": "Para percepção do azul fraca ou ausente", + "ui.combine": "Combinar", + "ui.coming_later": "em breve", + "ui.command_done": "{command} concluído", + "ui.command_palette_hint": "Digite um comando, p. ex. {example} — ou pressione S para pesquisar", + "ui.concentric": "Concêntrico", + "ui.configurations": "Configurações", + "ui.conic_curve": "Curva cônica", + "ui.constant": "Constante", + "ui.constraints_conflict": "Restrições em conflito", + "ui.construct": "Construir", + "ui.construction": "Construção", + "ui.context_menu": "Menu de contexto", + "ui.copy": "Copiar", + "ui.corner": "Canto", + "ui.corners": "Cantos", + "ui.counterbore": "Rebaixo", + "ui.countersink": "Escareado", + "ui.create": "Criar", + "ui.create_copy": "Criar cópia", + "ui.create_sketch": "Criar esboço", + "ui.current": "atual", + "ui.curvature": "Curvatura", + "ui.curvature_g2": "Curvatura (G2)", + "ui.curves": "Curvas", + "ui.custom_program": "Personalizado…", + "ui.custom_program_tip": "Escolha um programa fatiador para adicionar à lista", + "ui.customizeToolbar": "Personalizar barra de ferramentas…", + "ui.cut": "Recortar", + "ui.cylinder": "Cilindro", + "ui.dark": "Escuro", + "ui.default_modelling_orientation": "Orientação padrão de modelagem", + "ui.degrees_of_freedom": "graus de liberdade", + "ui.delete": "Excluir", + "ui.depth": "Profundidade", + "ui.design": "Projeto", + "ui.design_properties.author": "Autor", + "ui.design_properties.description": "Descrição", + "ui.design_properties.exports": "As exportações STEP, IGES e 3MF levam estes dados onde o formato tem lugar para eles.", + "ui.design_properties.license": "Licença", + "ui.design_properties.not_text": "Salvo como algo diferente de texto; digitar aqui o substitui.", + "ui.design_properties.organization": "Organização", + "ui.design_properties.others": "Dados de outras ferramentas", + "ui.design_properties.others_note": "Mantidos no projeto como estão e nunca exportados.", + "ui.design_properties.part_number": "Número da peça", + "ui.design_properties.project": "Projeto", + "ui.design_properties.revision": "Revisão", + "ui.diameter": "Diâmetro", + "ui.dimension": "Cota", + "ui.direction": "Direção", + "ui.display_quality": "Qualidade de exibição", + "ui.display_quality_coarse": "Grosseira", + "ui.display_quality_fine": "Fina", + "ui.display_quality_normal": "Normal", + "ui.display_quality_ultra": "Ultra", + "ui.distance": "Distância", + "ui.distance_1": "Distância 1", + "ui.distance_2": "Distância 2", + "ui.document_settings": "Configurações do documento", + "ui.don_t_save": "Não salvar", + "ui.draft": "Ângulo de saída", + "ui.drawing": "Desenho", + "ui.drill_point": "Ponta de broca", + "ui.edit": "Editar", + "ui.editJointLimits": "Editar limites da junta", + "ui.edit_section_analysis": "Editar análise de seção", + "ui.ellipse": "Elipse", + "ui.end_radius": "Raio final", + "ui.end_scale": "Escala final", + "ui.entities": "Entidades", + "ui.equal": "Igual", + "ui.equivalent_radius": "Raio equivalente", + "ui.expand": "Expandir", + "ui.exportDxf": "Exportar DXF…", + "ui.export_ellipsis": "Exportar...", + "ui.export_ellipsis_keymap": "Exportar…", + "ui.export_keymap_tip": "Teclas, favoritos da caixa S e a barra de ferramentas, como um arquivo", + "ui.extend": "Estender", + "ui.extent_type": "Tipo de extensão", + "ui.extrude": "Extrudar", + "ui.factor": "Fator", + "ui.feature_history": "Histórico de recursos", + "ui.feature_options": "Opções do recurso", + "ui.features": "Recursos", + "ui.file": "Arquivo", + "ui.fillet": "Concordância", + "ui.filter_commands_or_keys": "Filtrar comandos ou teclas", + "ui.findInTimeline": "Localizar na linha do tempo", + "ui.findInWindow": "Localizar na janela", + "ui.finish_sketch": "Concluir esboço", + "ui.fit": "Ajustar", + "ui.fix_unfix": "Fixar/Liberar", + "ui.flat": "Plano", + "ui.flip": "Inverter", + "ui.format": "Formato", + "ui.frame_rate": "Taxa de quadros", + "ui.front": "Frente", + "ui.fully_constrained": "Totalmente restrito", + "ui.general": "Geral", + "ui.graphics": "Gráficos", + "ui.ground_shadow": "Sombra no chão", + "ui.groupSelected": "Agrupar seleção", + "ui.heading_add_ins": "COMPLEMENTOS", + "ui.heading_assemble": "MONTAR", + "ui.heading_box": "CAIXA", + "ui.heading_chamfer": "CHANFRO", + "ui.heading_circular_pattern": "PADRÃO CIRCULAR", + "ui.heading_coil": "ESPIRAL", + "ui.heading_combine": "COMBINAR", + "ui.heading_configure": "CONFIGURAR", + "ui.heading_constraints": "RESTRIÇÕES", + "ui.heading_construct": "CONSTRUIR", + "ui.heading_create": "CRIAR", + "ui.heading_create_sketch": "CRIAR ESBOÇO", + "ui.heading_cylinder": "CILINDRO", + "ui.heading_design": "PROJETO", + "ui.heading_draft": "ÂNGULO DE SAÍDA", + "ui.heading_edit": "EDITAR", + "ui.heading_extrude": "EXTRUDAR", + "ui.heading_fillet": "CONCORDÂNCIA", + "ui.heading_finish_sketch": "CONCLUIR ESBOÇO", + "ui.heading_front": "FRENTE", + "ui.heading_hole": "FURO", + "ui.heading_home": "INÍCIO", + "ui.heading_insert": "INSERIR", + "ui.heading_inspect": "INSPECIONAR", + "ui.heading_loft": "LOFT", + "ui.heading_make": "FABRICAR", + "ui.heading_measure": "MEDIR", + "ui.heading_mesh": "MALHA", + "ui.heading_mirror": "ESPELHAR", + "ui.heading_modify": "MODIFICAR", + "ui.heading_move": "MOVER", + "ui.heading_move_copy": "MOVER/COPIAR", + "ui.heading_offset": "DESLOCAMENTO", + "ui.heading_offset_plane": "PLANO DESLOCADO", + "ui.heading_ok": "OK", + "ui.heading_parameters": "PARÂMETROS", + "ui.heading_pattern": "PADRÃO", + "ui.heading_pattern_on_path": "PADRÃO NO CAMINHO", + "ui.heading_pipe": "TUBO", + "ui.heading_plane_at_angle": "PLANO EM ÂNGULO", + "ui.heading_plastic": "PLÁSTICO", + "ui.heading_position": "POSIÇÃO", + "ui.heading_prepare": "PREPARAR", + "ui.heading_rectangular_pattern": "PADRÃO RETANGULAR", + "ui.heading_revolve": "REVOLUÇÃO", + "ui.heading_right": "DIREITA", + "ui.heading_save_mesh": "SALVAR COMO MALHA", + "ui.heading_scale": "ESCALA", + "ui.heading_section_analysis": "ANÁLISE DE SEÇÃO", + "ui.heading_select": "SELECIONAR", + "ui.heading_setup": "CONFIGURAÇÃO", + "ui.heading_sheet_metal": "CHAPA METÁLICA", + "ui.heading_shell": "CASCA", + "ui.heading_sketch": "ESBOÇO", + "ui.heading_sketch_palette": "PALETA DE ESBOÇO", + "ui.heading_sketch_scale": "ESCALA DO ESBOÇO", + "ui.heading_solid": "SÓLIDO", + "ui.heading_sphere": "ESFERA", + "ui.heading_split_body": "DIVIDIR CORPO", + "ui.heading_surface": "SUPERFÍCIE", + "ui.heading_sweep": "VARREDURA", + "ui.heading_thread": "ROSCA", + "ui.heading_top": "TOPO", + "ui.heading_torus": "TORO", + "ui.heading_utilities": "UTILITÁRIOS", + "ui.heading_utility": "UTILITÁRIO", + "ui.help": "Ajuda", + "ui.hide": "Ocultar", + "ui.hideAxes": "Ocultar eixos", + "ui.hideDimension": "Ocultar cota", + "ui.hideOrigin": "Ocultar origem", + "ui.hidePlanes": "Ocultar planos", + "ui.hideProfile": "Ocultar perfil", + "ui.hole": "Furo", + "ui.hole_tap_type": "Tipo de rosca do furo", + "ui.hole_type": "Tipo de furo", + "ui.home": "Início", + "ui.homeView": "Vista inicial", + "ui.horizontal_vertical": "Horizontal/Vertical", + "ui.import_ellipsis": "Importar…", + "ui.infinite": "Infinita", + "ui.insert": "Inserir", + "ui.inspect": "Inspecionar", + "ui.intersect": "Interseção", + "ui.isolate": "Isolar", + "ui.join": "Unir", + "ui.joints": "Juntas", + "ui.keyboard_shortcuts": "Atalhos de teclado", + "ui.language": "Idioma", + "ui.length_decimals": "Casas decimais de comprimento", + "ui.light": "Claro", + "ui.line": "Linha", + "ui.linetype": "Tipo de linha", + "ui.lock": "Bloquear", + "ui.loft": "Loft", + "ui.look_at": "Olhar para", + "ui.look_at_anim_desc": "Vista do eixo, Olhar para, Início e Ajustar", + "ui.manufacture": "Fabricação", + "ui.material_review.axes": "Eixos locais do material; nenhuma orientação de corpo é atribuída.", + "ui.material_review.claims": "Fontes e licenças são declarações não verificadas. Valores ausentes continuam desconhecidos.", + "ui.material_review.compressive_strength": "Resistência à compressão", + "ui.material_review.conditions": "Condições declaradas", + "ui.material_review.density": "Densidade", + "ui.material_review.derived": "Módulos isotrópicos derivados", + "ui.material_review.elasticity": "Elasticidade", + "ui.material_review.input": "Cole um cartão de material schema-1 (JSON)", + "ui.material_review.limit": "O cartão excede o limite de entrada de 256 KiB.", + "ui.material_review.moisture_unit": "kg de água / kg de material seco", + "ui.material_review.properties": "Propriedades", + "ui.material_review.review": "Revisar cartão", + "ui.material_review.scope": "Apenas candidato: não é atribuído nem salvo. Validação numérica não é certificação de engenharia.", + "ui.material_review.shear_strength": "Resistência ao cisalhamento", + "ui.material_review.source": "Fonte", + "ui.material_review.specific_heat": "Calor específico", + "ui.material_review.tensile_strength": "Resistência à tração", + "ui.material_review.thermal_conductivity": "Condutividade térmica", + "ui.material_review.thermal_expansion": "Dilatação térmica", + "ui.material_review.title": "Revisar dados do material físico", + "ui.material_review.unknown": "Desconhecido", + "ui.material_review.yield_strength": "Limite de escoamento", + "ui.measure": "Medir", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "3MF com marcação de faces", + "ui.mesh_format_stl": "STL", + "ui.midpoint": "Ponto médio", + "ui.mirror": "Espelhar", + "ui.mirror_line": "Linha de espelho", + "ui.modify": "Modificar", + "ui.move": "Mover", + "ui.multiple": "Múltiplo", + "ui.named_views": "Vistas nomeadas", + "ui.navigation": "Navegação", + "ui.needs_design": "{command}: abra um projeto primeiro", + "ui.newSketchGroup": "Novo grupo de esboços", + "ui.new_body": "Novo corpo", + "ui.new_design": "Novo projeto", + "ui.no_slicer_found": "Nenhum fatiador encontrado", + "ui.normal": "Normal", + "ui.normalConstruction": "Normal / Construção", + "ui.not_a_program": "{path} não é um programa que possa ser iniciado", + "ui.object_type": "Tipo de objeto", + "ui.objects": "Objetos", + "ui.offer_to_stand_up_y_up_files": "Oferecer colocar em pé arquivos com Y para cima", + "ui.offset": "Deslocamento", + "ui.offset_plane": "Plano deslocado", + "ui.one_side": "Um lado", + "ui.open": "Abrir", + "ui.open_ellipsis": "Abrir...", + "ui.open_preferences": "Abrir preferências", + "ui.open_recent": "Abrir recente", + "ui.operation": "Operação", + "ui.options": "Opções", + "ui.orbit": "Orbitar", + "ui.orbit_around": "Orbitar em torno de", + "ui.orientation": "Orientação", + "ui.origin": "Origem", + "ui.palette_points": "Pontos", + "ui.palette_profile": "Perfil", + "ui.pan": "Deslocar", + "ui.pan_zoom_orbit": "Deslocar, zoom, orbitar", + "ui.parallel": "Paralelo", + "ui.parameters": "Parâmetros", + "ui.paste": "Colar", + "ui.path": "Caminho", + "ui.pattern_on_path": "Padrão no caminho", + "ui.perpendicular": "Perpendicular", + "ui.perspective_view": "Vista em perspectiva", + "ui.pinToShortcuts": "Fixar nos atalhos", + "ui.pinToToolbar": "Fixar na barra de ferramentas", + "ui.pipe": "Tubo", + "ui.placement": "Posicionamento", + "ui.plane": "Plano", + "ui.plane_at_angle": "Plano em ângulo", + "ui.point": "Ponto", + "ui.point_under_the_cursor": "Ponto sob o cursor", + "ui.points": "Pontos", + "ui.polygon": "Polígono", + "ui.preferences": "Preferências", + "ui.press_a_key": "pressione uma tecla…", + "ui.profile": "Perfil", + "ui.profile_plane": "Plano do perfil", + "ui.profiles": "Perfis", + "ui.project": "Projetar", + "ui.project_face_edges_sketch": "Projetar arestas da face em novos esboços", + "ui.properties": "Propriedades", + "ui.pull_direction": "Direção de extração", + "ui.quantity": "Quantidade", + "ui.quantity_2": "Quantidade 2", + "ui.quit": "Sair", + "ui.radial_context_menu": "Menu de contexto radial", + "ui.radius": "Raio", + "ui.radius_type": "Tipo de raio", + "ui.reachable": "Alcançável", + "ui.rectangle": "Retângulo", + "ui.rectangular_pattern": "Padrão retangular", + "ui.redo": "Refazer", + "ui.removeFromToolbar": "Remover da barra de ferramentas", + "ui.removeSection": "Remover seção", + "ui.render": "Renderizar", + "ui.renderer": "Renderizador", + "ui.repeat": "Repetir", + "ui.report_a_bug": "Relatar um bug", + "ui.reset": "Redefinir", + "ui.reset_all": "Redefinir tudo", + "ui.reset_the_settings_on_this_page": "Redefinir as configurações desta página", + "ui.restore": "Restaurar", + "ui.restore_defaults": "Restaurar padrões", + "ui.reverse_zoom_direction": "Inverter direção do zoom", + "ui.revolve": "Revolução", + "ui.right": "Direita", + "ui.save": "Salvar", + "ui.save_as": "Salvar como", + "ui.save_as_ellipsis": "Salvar como...", + "ui.save_mesh_no_slicer": "Nenhum fatiador encontrado: escolha Personalizado… e selecione seu programa fatiador, ou desative Enviar ao fatiador", + "ui.save_mesh_pick_bodies": "Selecione os corpos a salvar", + "ui.save_mesh_temp_failed": "Não foi possível criar {folder}: {error}", + "ui.saved_to": "Salvo {path}", + "ui.scale": "Escala", + "ui.section_analysis": "Análise de seção", + "ui.select": "Selecionar", + "ui.selectOther": "Selecionar outro…", + "ui.selectTangentChain": "Selecionar cadeia tangente", + "ui.select_other_hint": "Selecionar outro: mantenha o botão esquerdo parado sobre o modelo (ou clique com o botão direito › Selecionar outro…) para listar tudo sob o cursor; clique de novo no mesmo ponto para selecionar o próximo item ali.", + "ui.selection": "Seleção", + "ui.send": "Enviar", + "ui.send_to_slicer": "Enviar ao fatiador", + "ui.sent_to_slicer": "Enviado para {slicer}", + "ui.shell": "Casca", + "ui.show": "Mostrar", + "ui.showAll": "Mostrar tudo", + "ui.showAllBodies": "Mostrar todos os corpos", + "ui.showAxes": "Mostrar eixos", + "ui.showDimension": "Mostrar cota", + "ui.showOrigin": "Mostrar origem", + "ui.showPlanes": "Mostrar planos", + "ui.show_constraints": "Restrições", + "ui.show_construction_geometries": "Geometrias de construção", + "ui.show_dimensions": "Cotas", + "ui.show_points": "Mostrar pontos", + "ui.show_profile": "Mostrar perfil", + "ui.show_projected_geometries": "Geometrias projetadas", + "ui.simple": "Simples", + "ui.simulation": "Simulação", + "ui.single": "Único", + "ui.sketch": "Esboço", + "ui.sketch_dimension": "Cota do esboço", + "ui.sketch_grid": "Grade do esboço", + "ui.sketch_scale": "Escala do esboço", + "ui.sketch_status": "Estado do esboço", + "ui.sketches": "Esboços", + "ui.slice": "Fatiar", + "ui.slicer": "Fatiador", + "ui.slicer_delete_tip": "{program}\nPressione Delete para removê-lo da lista", + "ui.slot": "Rasgo", + "ui.smooth": "Suave", + "ui.smooth_wheel_zoom": "Zoom suave com a roda", + "ui.smooth_wheel_zoom_tip": "Desative para aplicar cada evento da roda na hora, sem rastro de suavização", + "ui.snap": "Encaixe", + "ui.space_mouse_hint": "Move e gira a vista juntos; esboços usam apenas deslocamento e zoom.", + "ui.space_mouse_navigate": "Navegar com SpaceNavigator / SpaceMouse", + "ui.spacing": "Espaçamento", + "ui.spacing_2": "Espaçamento 2", + "ui.sphere": "Esfera", + "ui.spline": "Spline", + "ui.split_body": "Dividir corpo", + "ui.stand_up_tip": "Depois que um arquivo STEP ou IGES abrir com Z para cima, oferecer um quarto de volta em torno de X", + "ui.start": "Início", + "ui.start_radius": "Raio inicial", + "ui.supersampling": "Supersampling (SSAA)", + "ui.supersampling_adaptive": "Só quando a vista está parada", + "ui.supersampling_off": "Desativado (1×)", + "ui.suppress": "Suprimir", + "ui.sweep": "Varredura", + "ui.sweep_follow_direction": "Seguir direção", + "ui.sweep_keep_as_drawn": "Manter como desenhado", + "ui.sweep_turn_with_path": "Girar com o caminho", + "ui.symmetric": "Simétrico", + "ui.symmetry": "Simetria", + "ui.system": "Sistema", + "ui.tangent": "Tangente", + "ui.taper_angle": "Ângulo de inclinação", + "ui.tapped": "Roscado", + "ui.text": "Texto", + "ui.theme": "Tema", + "ui.thickness": "Espessura", + "ui.thread": "Rosca", + "ui.timeline_bottom": "Linha do tempo inferior", + "ui.timeline_left_note": "O layout à esquerda mostra a barra de retrocesso acima do navegador de peças e cena.", + "ui.timeline_left_sidebar": "Barra lateral esquerda", + "ui.tip_angle": "Ângulo da ponta", + "ui.to_object": "Até o objeto", + "ui.tool_direction": "Direção da ferramenta", + "ui.top": "Topo", + "ui.torus": "Toro", + "ui.total_angle": "Ângulo total", + "ui.trackpad_pan_tip": "Gestos do trackpad deslocam (desativado: dão zoom como a roda); a roda do mouse dá zoom, a roda do polegar desloca para os lados, a pinça sempre dá zoom", + "ui.trim": "Aparar", + "ui.twist": "Torção", + "ui.two_finger_scroll_pans": "Rolagem com dois dedos desloca", + "ui.two_sides": "Dois lados", + "ui.ui_scale": "Escala da interface", + "ui.undo": "Desfazer", + "ui.unground": "Liberar do solo", + "ui.unisolate": "Desfazer isolamento", + "ui.units": "Unidades", + "ui.units_of_new_designs": "Unidades de novos projetos", + "ui.unlock": "Desbloquear", + "ui.unsuppress": "Reativar", + "ui.untitled": "Sem título", + "ui.up_axis_note": "Qual eixo aponta para cima nas vistas (vista do eixo, Início, Olhar para). Os projetos não mudam.", + "ui.updateToCurrentView": "Atualizar para a vista atual", + "ui.variable": "Variável", + "ui.view_centre": "Centro da vista", + "ui.visual_shaded_hidden_edges": "Sombreado com arestas ocultas", + "ui.visual_shaded_with_edges": "Sombreado com arestas", + "ui.visual_style": "Estilo visual", + "ui.visual_wireframe": "Aramado", + "ui.workspace": "espaço de trabalho", + "ui.x_distance": "Distância X", + "ui.y_distance": "Distância Y", + "ui.y_up": "Y para cima", + "ui.z_up": "Z para cima", + "ui.zoom": "Zoom", + "ui.zoom_to_cursor_tip": "A roda dá zoom em direção ao ponto sob o cursor (desativado: em direção ao centro da vista)", + "ui.zoom_to_the_cursor": "Zoom em direção ao cursor", + "update.available": "O SolidCraft {version} está disponível", + "update.button": "Atualizar", + "update.button_tip": "O SolidCraft {version} está disponível", + "update.button_version": "Atualizar para {version}", + "update.check_automatically": "Verificar atualizações automaticamente", + "update.check_now": "Verificar agora", + "update.checking": "Verificando…", + "update.copy": "Copiar", + "update.dmg_opened": "A imagem de disco está aberta e verificada: arraste o SolidCraft para Aplicativos, substituindo a cópia antiga, e reinicie o SolidCraft.", + "update.download": "Baixar", + "update.download_open": "Baixar e abrir", + "update.downloading": "Baixando e verificando… {done} de {total} MB", + "update.failed": "Não foi possível verificar: {error}", + "update.file": "Baixar obtém {file}.", + "update.install_failed": "A atualização não foi instalada: {error}. Nada foi alterado; Baixar obtém o pacote em vez disso.", + "update.install_msi": "Instalar (fecha o SolidCraft)", + "update.installed": "O SolidCraft {version} está instalado. Reinicie para usá-lo.", + "update.installer_started": "O instalador começa quando o SolidCraft fechar.", + "update.later": "Lembrar mais tarde", + "update.no_notes": "Esta versão não tem notas.", + "update.package_hint": "Esta cópia veio de um {kind}. Baixe o novo pacote e instale-o com:", + "update.prefs_dev": "Esta é uma versão de desenvolvimento ({version}): ela não verifica atualizações.", + "update.prefs_flatpak": "O Flatpak atualiza esta cópia ({version}): execute {command} ou use sua central de programas. O SolidCraft não verifica.", + "update.prefs_label": "Atualizações", + "update.prefs_note": "Este é o SolidCraft {version} ({kind}). Uma verificação pergunta ao GitHub pela versão mais recente e não envia mais nada.", + "update.release_page": "Abrir página da versão", + "update.restart": "Reiniciar agora", + "update.restart_later": "Depois", + "update.show": "Mostrar a atualização para {version}", + "update.skip": "Pular esta versão", + "update.system_hint": "Esta cópia é um {kind}. Atualize-a com:", + "update.title": "Atualização disponível", + "update.up_to_date": "O SolidCraft está atualizado.", + "update.update_now": "Atualizar agora", + "update.you_have": "Você tem a {version}." +} diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 30f1ab3b4..b50bfd44d 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -81,6 +81,7 @@ "Enable rule": "Включить правило", "Enabled": "Включено", "Explode": "Разобрать", + "Export Animation…": "Экспортировать анимацию…", "Extents": "Пределы", "Face attachment lost": "Привязка к грани потеряна", "Faces": "Грани", @@ -177,6 +178,7 @@ "Round": "Круглая", "Rule": "Правило", "Save Rule": "Сохранить правило", + "Save the study as an animated GIF, seen as the viewport shows it": "Сохранить исследование как анимированный GIF, как его показывает видовой экран", "Saved preview. Geometry is being checked before editing.": "Сохранённый предпросмотр. Геометрия проверяется перед редактированием.", "Scale factor": "Коэффициент масштаба", "Search": "Поиск", @@ -249,6 +251,13 @@ "browser.precision": "Точность: {precision}", "browser.sketch_name": "Эскиз{number}", "browser.units": "Единицы: {units}", + "cam.flat": "Плоский", + "cam.follower": "Толкатель", + "cam.knife": "Острие", + "cam.needs_joints": "нужны вращающееся и скользящее или качающееся сопряжения", + "cam.roller": "Ролик", + "cam.roller_pick": "Ролик (необязательно)", + "cam.tip_pick": "Острие (необязательно)", "cmd.appearance_assign": "Внешний вид", "cmd.appearance_library": "Библиотека внешних видов", "cmd.appearance_list": "Список внешних видов", @@ -352,6 +361,7 @@ "cmd.inspect_minimum_radius": "Анализ минимального радиуса", "cmd.inspect_zebra": "Зебра-анализ", "cmd.joint_as_built": "Сопряжение на месте", + "cmd.joint_cam": "Кулачок", "cmd.joint_create": "Сопряжение", "cmd.joint_delete": "Удалить сопряжение", "cmd.joint_drive": "Привод сопряжений", @@ -378,6 +388,7 @@ "cmd.model_threads": "Список резьб", "cmd.motion_delete": "Удалить исследование движения", "cmd.motion_export": "Экспортировать исследование движения", + "cmd.motion_export_animation": "Экспортировать анимацию движения", "cmd.motion_list": "Список исследований движения", "cmd.motion_play": "Воспроизвести исследование движения", "cmd.motion_study": "Исследование движения", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index e916335a0..eb75ca654 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -85,6 +85,7 @@ "Enable rule": "Kuralı etkinleştir", "Enabled": "Etkin", "Explode": "Patlat", + "Export Animation…": "Animasyonu dışa aktar…", "Extents": "Kapsamlar", "Face": "Yüz", "Face attachment lost": "Yüze bağlama kayboldu", @@ -193,6 +194,7 @@ "Round": "Yuvarlak", "Rule": "Kural", "Save Rule": "Kuralı kaydet", + "Save the study as an animated GIF, seen as the viewport shows it": "Etüdü görünüm alanında göründüğü gibi animasyonlu GIF olarak kaydet", "Saved preview. Geometry is being checked before editing.": "Kaydedilmiş önizleme. Düzenlemeden önce geometri kontrol ediliyor.", "Scale factor": "Ölçek faktörü", "Search": "Ara", @@ -400,6 +402,7 @@ "cmd.model_threads": "Dişleri listele", "cmd.motion_delete": "Hareket etüdünü sil", "cmd.motion_export": "Hareket etüdünü dışa aktar", + "cmd.motion_export_animation": "Hareket animasyonunu dışa aktar", "cmd.motion_list": "Hareket etütlerini listele", "cmd.motion_play": "Hareket etüdünü oynat", "cmd.motion_study": "Hareket etüdü", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 86c162c33..3b931791c 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -92,6 +92,7 @@ "Enable rule": "Увімкнути правило", "Enabled": "Увімкнено", "Explode": "Рознести", + "Export Animation…": "Експортувати анімацію…", "Export Current View as DXF": "Експортувати поточний вид як DXF", "Export Current View as DXF…": "Експортувати поточний вид як DXF…", "Export DXF…": "Експорт DXF…", @@ -211,6 +212,7 @@ "Round": "Круглий", "Rule": "Правило", "Save Rule": "Зберегти правило", + "Save the study as an animated GIF, seen as the viewport shows it": "Зберегти дослідження як анімований GIF, як його показує вікно перегляду", "Saved preview. Geometry is being checked before editing.": "Збережений перегляд. Геометрію перевіряють перед редагуванням.", "Scale factor": "Коефіцієнт масштабу", "Search": "Пошук", @@ -293,6 +295,13 @@ "browser.precision": "Точність: {precision}", "browser.sketch_name": "Ескіз{number}", "browser.units": "Одиниці: {units}", + "cam.flat": "Плоский", + "cam.follower": "Штовхач", + "cam.knife": "Вістря", + "cam.needs_joints": "потрібні обертове й ковзне або хитне з'єднання", + "cam.roller": "Ролик", + "cam.roller_pick": "Ролик (необов'язково)", + "cam.tip_pick": "Вістря (необов'язково)", "cmd.appearance_assign": "Вигляд", "cmd.appearance_library": "Бібліотека виглядів", "cmd.appearance_list": "Список виглядів", @@ -396,6 +405,7 @@ "cmd.inspect_minimum_radius": "Аналіз мінімального радіуса", "cmd.inspect_zebra": "Зебра-аналіз", "cmd.joint_as_built": "З'єднання за поточним положенням", + "cmd.joint_cam": "Кулачок", "cmd.joint_create": "З'єднання", "cmd.joint_delete": "Видалити з'єднання", "cmd.joint_drive": "Керувати з'єднаннями", @@ -426,6 +436,7 @@ "cmd.model_threads": "Список різьб", "cmd.motion_delete": "Видалити дослідження руху", "cmd.motion_export": "Експортувати дослідження руху", + "cmd.motion_export_animation": "Експортувати анімацію руху", "cmd.motion_list": "Список досліджень руху", "cmd.motion_play": "Відтворити дослідження руху", "cmd.motion_study": "Дослідження руху", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index b310f839a..dbea5f178 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -92,6 +92,7 @@ "Enable rule": "启用规则", "Enabled": "已启用", "Explode": "爆炸", + "Export Animation…": "导出动画…", "Export Current View as DXF": "将当前视图导出为DXF", "Export Current View as DXF…": "将当前视图导出为DXF…", "Export DXF…": "导出DXF…", @@ -211,6 +212,7 @@ "Round": "圆角", "Rule": "规则", "Save Rule": "保存规则", + "Save the study as an animated GIF, seen as the viewport shows it": "按视口中的显示将研究保存为动画 GIF", "Saved preview. Geometry is being checked before editing.": "已保存预览。编辑前正在检查几何。", "Scale factor": "比例因子", "Search": "搜索", @@ -293,6 +295,13 @@ "browser.precision": "精度: {precision}", "browser.sketch_name": "草图{number}", "browser.units": "单位: {units}", + "cam.flat": "平底", + "cam.follower": "从动件", + "cam.knife": "尖顶", + "cam.needs_joints": "需要一个旋转接头和一个滑动或摆动接头", + "cam.roller": "滚子", + "cam.roller_pick": "滚子(可选)", + "cam.tip_pick": "尖端(可选)", "cmd.appearance_assign": "外观", "cmd.appearance_library": "外观库", "cmd.appearance_list": "列出外观", @@ -396,6 +405,7 @@ "cmd.inspect_minimum_radius": "最小半径分析", "cmd.inspect_zebra": "斑马纹分析", "cmd.joint_as_built": "现状接头", + "cmd.joint_cam": "凸轮", "cmd.joint_create": "接头", "cmd.joint_delete": "删除接头", "cmd.joint_drive": "驱动接头", @@ -426,6 +436,7 @@ "cmd.model_threads": "列出螺纹", "cmd.motion_delete": "删除运动研究", "cmd.motion_export": "导出运动研究", + "cmd.motion_export_animation": "导出运动动画", "cmd.motion_list": "列出运动研究", "cmd.motion_play": "播放运动研究", "cmd.motion_study": "运动研究", @@ -631,6 +642,18 @@ "drive.stopped_by_contact": "停在 {value}:{a} 会穿过 {b}", "drive.stopped_by_loop": "停在 {value}:经过 {joint} 的环路无法再闭合", "drive.unconnected": "没有任何移动:{part} 未连接到任何固定的零部件", + "dxf.cancel_wait": "正在等待导出停止…", + "dxf.cancelled": "DXF 导出已取消", + "dxf.cancelling": "正在取消 DXF 导出", + "dxf.exporting": "正在导出 DXF", + "dxf.invalid_tolerance": "曲线公差必须介于 0.0001 和 1 mm 之间。", + "dxf.progress.index": "正在准备曲面 (2/5)", + "dxf.progress.meshes": "正在准备网格 (1/5)", + "dxf.progress.occlusion": "正在判定隐藏线 (4/5)", + "dxf.progress.projection": "正在投影几何体 (3/5)", + "dxf.progress.write": "正在写入 DXF (5/5)", + "dxf.tolerance": "曲线公差", + "dxf.tolerance_help": "仅导出可见实体。曲线使用直线段近似。公差越小,曲线越精细,但需要更多时间和内存。", "expression, e.g. 25 mm": "表达式,例如 25 mm", "fits the face, e.g. M8": "适配该面,例如 M8", "from the rule": "来自规则", @@ -760,6 +783,10 @@ "sketch_text.path_hint": "文字所跟随的草图曲线:先单击此处,再选择曲线", "sketch_text.use_font_file": "使用字体文件 {path}", "the parts library is not available": "零件库不可用", + "thread.automatic_size": "自动尺寸", + "thread.designation": "螺纹标记", + "thread.iso_metric": "ISO 公制", + "thread.select_size": "选择尺寸", "timeline.group": "新建特征文件夹", "timeline.move_many": "移动时间线项目", "timeline.move_to_group": "将特征移至文件夹", diff --git a/crates/derive/src/lib.rs b/crates/derive/src/lib.rs index 74d4ff4e2..4fb8e1a78 100644 --- a/crates/derive/src/lib.rs +++ b/crates/derive/src/lib.rs @@ -21,7 +21,8 @@ //! `|i: usize, n: usize| -> &'static str`; it may read the other fields; //! - `pinned`: a face pick that stays where it is when the feature moves; //! `pick_if = cond`: a face pick when `cond` holds, else a position; -//! - `placement`: a primitive's placement point (its X, Y and Z expressions are not inputs); +//! - `placement`: a primitive's placement point, or an optional one (its X, Y and Z expressions +//! are not inputs); //! - `profiles_of = sketch_field`, optionally with `when = cond`: a profile selection; //! - `after = field`: visit this field right after `field` instead of in declaration order (where //! the parameter names already given need it); @@ -162,7 +163,8 @@ fn walk_field(b: &Ident, r: &Roles, which: Which, mutable: bool) -> Tokens { #w::Each::<#w::Vec3>::#each(#b, &mut |p| f(if #pick { #w::Geo::Pick(p) } else { #w::Geo::Pos(p) })); } } - Some(Geo::Placement) => quote! { f(#w::Geo::Placement(#b)); }, + // A point or an optional one (a hole's `at`, #1678). + Some(Geo::Placement) => quote! { #w::Each::::#each(#b, &mut |p| f(#w::Geo::Placement(p))); }, Some(Geo::Profiles { .. }) => { let (id, when) = (pre(b, "sketch"), pre(b, "when")); quote! { diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 97780eb46..00523f8e4 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -662,6 +662,12 @@ pub enum FeatureKind { Hole { #[walk(pick_if = points.is_none())] position: FacePick, + /// The position as length expressions, when it was given that way (#1678): the hole is + /// drilled where they evaluate, and follows the parameters. `position` keeps the point + /// they gave when the hole was made. + #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_point_expr")] + #[walk(placement)] + at: Option, /// Drilling direction (into the material). direction: Dir, #[walk(length = "Diameter")] @@ -1935,6 +1941,22 @@ mod point_expr { } } +/// [`point_expr`] for an optional point. +mod opt_point_expr { + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + #[derive(Serialize, Deserialize)] + struct Wrap(#[serde(with = "super::point_expr")] super::PointExpr); + + pub fn serialize(p: &Option, s: S) -> Result { + p.as_ref().map(|p| Wrap(p.clone())).serialize(s) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + Ok(Option::::deserialize(d)?.map(|w| w.0)) + } +} + impl FeatureKind { /// A sheet metal feature (its result depends on the sheet metal rules). pub fn is_plastic(&self) -> bool { diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 40cde9bd1..0b5ddf0cf 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -209,6 +209,12 @@ const ISO_COARSE: [(f64, f64); 22] = [ (56.0, 5.5), ]; +/// Nominal diameters and coarse pitches (mm) used for automatic ISO metric thread sizing. +/// Other diameter/pitch pairs can be supplied as explicit designations. +pub fn metric_thread_sizes() -> &'static [(f64, f64)] { + &ISO_COARSE +} + /// "M8" or "M8x1" → (nominal diameter, pitch). pub fn parse_metric_thread(s: &str) -> Option<(f64, f64)> { let t = s.trim().to_ascii_uppercase(); @@ -221,7 +227,7 @@ pub fn parse_metric_thread(s: &str) -> Option<(f64, f64)> { Some(p) => p, None => ISO_COARSE.iter().find(|(n, _)| (n - d).abs() < 1e-9)?.1, }; - (d > 0.0 && pitch > 0.0 && pitch < d).then_some((d, pitch)) + (d.is_finite() && pitch.is_finite() && d > 0.0 && pitch > 0.0 && pitch < d).then_some((d, pitch)) } /// The metric thread a cylinder of this diameter takes: a shaft is the major diameter, a hole @@ -241,6 +247,12 @@ fn format_thread(d: f64, p: f64) -> String { if coarse { format!("M{}", num(d)) } else { format!("M{}x{}", num(d), num(p)) } } +/// The automatic ISO metric designation for a cylindrical face, using the same fit check as +/// a thread feature without an explicit size. This query does not change the model. +pub fn suggested_thread(st: &ModelState, p: Vec3) -> Result { + thread_on(st, 0, p, None, None).map(|t| t.designation) +} + /// A cosmetic thread on the cylindrical face at `p`. fn thread_on(st: &ModelState, feature: u64, p: Vec3, designation: Option<&str>, length: Option) -> Result { let (body, cyl) = st @@ -1930,6 +1942,39 @@ fn extend_for_coplanar(st: &ModelState, plane: &Plane, r: &Region2, lo: f64, hi: (lo2, hi2) } +/// Whether a tapered tool, run on by `depth` behind the plane it starts in (`dir` the way it +/// extrudes), stays where running on changes nothing: in the targets for a join, out of them for +/// a cut. Its sides keep their slope, so the section there is the profile grown by up to `widen` +/// all round; that grown outline is probed at two depths. +#[allow(clippy::too_many_arguments)] +fn taper_run_on_fits(st: &ModelState, start: &Plane, dir: Vec3, r: &Region2, depth: f64, widen: f64, op: Operation, targets: &[String]) -> bool { + const MAX_SEGMENTS: usize = 2_000; + let meshes: Vec> = st.bodies.iter().filter(|b| targets.is_empty() || targets.contains(&b.name)).map(|b| b.mesh()).collect(); + if meshes.is_empty() || !depth.is_finite() || !widen.is_finite() { + return false; + } + let want = op == Operation::Join; + // Each loop counterclockwise with the side away from the material: right of the outer loop, + // left of a hole. + let loops: Vec<(solidcraft_geom::Loop2, f64)> = std::iter::once((r.outer.ccw(), 1.0)).chain(r.holes.iter().map(|h| (h.ccw(), -1.0))).collect(); + let count: usize = loops.iter().map(|(l, _)| l.segs.len()).sum(); + if count > MAX_SEGMENTS { + return false; + } + loops.iter().all(|(lp, side)| { + lp.segs.iter().all(|seg| { + [0.0, 0.25, 0.5, 0.75].iter().all(|t| { + let Some(d) = seg.derivative(*t).normalized() else { return true }; + let out = Vec2::new(d.y, -d.x) * *side; + [0.5, 1.0].iter().all(|k| { + let p = start.to_world(seg.point_at(*t) + out * (widen * k)) - dir * (depth * k); + meshes.iter().any(|m| m.contains(p)) == want + }) + }) + }) + }) +} + /// How high (mm) a tapered tool's sides stand straight where it starts on a face it can't run /// on into. const TAPER_FOOT: f64 = 0.01; @@ -2300,8 +2345,8 @@ fn sketch_hole_dir(st: &ModelState, spots: &[Vec3], n: Vec3) -> Vec3 { /// Where a hole feature drills (each on the surface) and in which direction: at its sketch /// points perpendicular to the sketch (into the material), else at its position. -fn hole_spots(st: &ModelState, f: &Feature) -> Result<(Vec, Vec3)> { - let FeatureKind::Hole { position, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) }; +fn hole_spots(vals: &BTreeMap, st: &ModelState, f: &Feature) -> Result<(Vec, Vec3)> { + let FeatureKind::Hole { position, at, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) }; let (spots, dir) = match points { Some(sp) => { let ss = @@ -2317,7 +2362,7 @@ fn hole_spots(st: &ModelState, f: &Feature) -> Result<(Vec, Vec3)> { } None => { let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?; - let at = hole_on_surface(st, position.0, dir); + let at = hole_on_surface(st, hole_position(vals, position, at)?, dir); let dir = hole_dir_into_face(st, at, dir); return Ok((vec![hole_on_surface(st, at, dir)], dir)); } @@ -2351,8 +2396,8 @@ fn hole_depth_to(st: &ModelState, at: &Vec3, dir: Vec3, to: &Option, depth } /// A hole's spots as given (not yet moved onto the surface) and its direction. -fn hole_spots_raw(st: &ModelState, f: &Feature) -> Result<(Vec, Vec3)> { - let FeatureKind::Hole { position, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) }; +fn hole_spots_raw(vals: &BTreeMap, st: &ModelState, f: &Feature) -> Result<(Vec, Vec3)> { + let FeatureKind::Hole { position, at, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) }; match points { Some(sp) => { let ss = st.sketch(sp.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {}", sp.sketch)))?; @@ -2364,16 +2409,29 @@ fn hole_spots_raw(st: &ModelState, f: &Feature) -> Result<(Vec, Vec3)> { } None => { let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?; - Ok((vec![position.0], hole_dir_into_face(st, hole_on_surface(st, position.0, dir), dir))) + let p = hole_position(vals, position, at)?; + Ok((vec![p], hole_dir_into_face(st, hole_on_surface(st, p, dir), dir))) } } } +/// Where a hole placed by position is drilled: its `at` expressions evaluated, so it follows the +/// parameters (#1678), else the point it was given. +fn hole_position(vals: &BTreeMap, position: &crate::FacePick, at: &Option) -> Result { + let Some([x, y, z]) = at else { return Ok(position.0) }; + let p = + Vec3::new(Document::eval_in(vals, x, Kind::Length)?, Document::eval_in(vals, y, Kind::Length)?, Document::eval_in(vals, z, Kind::Length)?); + if ![p.x, p.y, p.z].iter().all(|c| c.is_finite() && c.abs() < 1e9) { + return Err(DocError::Invalid("the hole's position is out of range".into())); + } + Ok(p) +} + /// The cutting tools of a hole feature at every spot, each with its exact geometry when it is a /// straight cylinder (see [`hole_tools_and_prisms`]). fn hole_feature_tools(vals: &BTreeMap, st: &ModelState, f: &Feature) -> Result)>> { let FeatureKind::Hole { diameter, depth, hole, to, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) }; - let (spots, dir) = hole_spots(st, f)?; + let (spots, dir) = hole_spots(vals, st, f)?; if spots.is_empty() || spots.len() > 10_000 { return Err(DocError::Invalid("a hole needs 1…10000 points".into())); } @@ -2815,16 +2873,40 @@ fn feature_tools_with_constructor( // sides standing on a face are curved where they meet it (along text, say), // and the boolean finds no result there. The sides keep their slope, so // the profile stays the section at the start. + let roles = crate::lineage::ProfileRoles { sketch: Some(&ss), region: Some(r), caps: caps.clone() }; + // A start that is a whole face of the target (a foot under a part's base) is sewn on + // along it, as it lies: run on, the sides would leave the face through its edges. + if on_face + && *operation == Operation::Join + && let Ok(exact) = kernel::extrude_tapered_between(&start_plane, r, 0.0, len, 0.0, sign, taper) + && st + .bodies + .iter() + .filter(|t| targets.is_empty() || targets.iter().any(|x| *x == t.name)) + .any(|t| kernel::can_join_touching_faces(&t.body, &exact)) + { + growth = growth.max(len * taper.tan().abs()); + return Ok(roles.tool(exact, None)); + } let (lo, hi) = if sign < 0.0 { (from - len, from) } else { (from, from + len) }; let (l2, h2) = extend_for_coplanar(st, &ss.plane, r, lo, hi, *operation, &crate::plain(targets)); - let (a, b) = if sign < 0.0 { (from - h2, from - l2) } else { (l2 - from, h2 - from) }; + let (mut a, b) = if sign < 0.0 { (from - h2, from - l2) } else { (l2 - from, h2 - from) }; + // A taper that narrows the tool away from the face widens it as it runs on into it, past + // the profile (where the profile is the whole face, out through the body's sides, #1534): + // then it starts on the face instead. + if a < 0.0 && a * taper.tan() > 0.0 { + let dir = n * sign; + if !taper_run_on_fits(st, &start_plane, dir, r, -a, a * taper.tan(), *operation, &crate::plain(targets)) { + a = 0.0; + } + } // A start that can't run on (the profile hangs over the face's edge): // the sides stand straight for a hair first, so the boolean can push the // face the tool stands on into the body. let foot = if a >= 0.0 && on_face { TAPER_FOOT.min((b - a) * 0.01) } else { 0.0 }; let body = kernel::extrude_tapered_between(&start_plane, r, a, b, foot, sign, taper)?; growth = growth.max(a.abs().max(b.abs()) * taper.tan().abs()); - Ok(crate::lineage::ProfileRoles { sketch: Some(&ss), region: Some(r), caps: caps.clone() }.tool(body, None)) + Ok(roles.tool(body, None)) }) .collect::>()?; // Profiles apart by more than the tools grow (the letters of a text): the tools @@ -3085,6 +3167,9 @@ fn feature_tools_with_constructor( { return build_curved(®ions, -axis_w, tb); } + // A new body is final: its planar faces come out whole. A boolean's tool is not + // healed (the boolean heals its result). + let revolve = if operation == Operation::NewBody { kernel::revolve_whole } else { kernel::revolve }; if *convention == crate::RevolveConvention::SketchNormal { let mut out = Vec::new(); for (region, region_extent) in regions.iter().zip(®ion_extents) { @@ -3093,7 +3178,7 @@ fn feature_tools_with_constructor( out.extend(build_curved(std::slice::from_ref(region), rotation_axis, tb)?); continue; } - let bodies = kernel::revolve(&ss.plane, std::slice::from_ref(region), o, d, region_extent.sweep)?; + let bodies = revolve(&ss.plane, std::slice::from_ref(region), o, d, region_extent.sweep)?; let m = crate::rigid(Vec3::ZERO, origin_w, rotation_axis, region_extent.start); for body in bodies { out.push(if region_extent.start.abs() < 1e-12 { @@ -3105,7 +3190,7 @@ fn feature_tools_with_constructor( } return Ok(out); } - let bodies = kernel::revolve(&ss.plane, ®ions, o, d, ang)?; + let bodies = revolve(&ss.plane, ®ions, o, d, ang)?; if start.abs() < 1e-12 { return Ok(regions.iter().zip(bodies).map(|(r, body)| tool(r, body, None)).collect()); } @@ -3755,7 +3840,7 @@ fn replay( // A hole is drilled again at each copy of its spot (found on the surface there), so // a blind hole's depth counts from the face at the copy, not from the bottom of the // original hole under the original spot. - let (spots, dir) = hole_spots_raw(st, src)?; + let (spots, dir) = hole_spots_raw(vals, st, src)?; for (k, m) in mats.iter().enumerate() { let d = crate::apply_vector(m, dir).normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?; for p in &spots { @@ -4208,7 +4293,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: apply_traced(st, f, tools, *operation, &crate::plain(targets)) } FeatureKind::Hole { thread, diameter, .. } => { - let (spots, dir) = hole_spots(st, f)?; + let (spots, dir) = hole_spots(vals, st, f)?; let tools = hole_feature_tools(vals, st, f)?; let handled = sheet_hole_cut(st, f, &tools, warning)?; let tools: Vec = tools.into_iter().map(|(tool, _)| tool).collect(); @@ -4410,31 +4495,35 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: FeatureKind::Split { body, plane, tool, sketch, line } => { let i = st.bodies.iter().position(|b| &b.name == body).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?; let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Unknown(format!("body `{body}`"))) }; + let input = mb.traced(); let parts = match tool { // A sketch line: the plane through it along the sketch's normal. _ if sketch.is_some() || line.is_some() => { let (Some(sketch), Some(line)) = (sketch, line) else { return Err(DocError::Invalid("a sketch line tool needs both its sketch and its line".into())); }; - kernel::split_by_plane(&mb.body, &sketch_line_plane(st, sketch.0, line)?)? + split_by_plane_traced(&input, &sketch_line_plane(st, sketch.0, line)?)? } // A face of a body (its surface extended). Some(t) => { let tb = st.body(&t.body).ok_or_else(|| DocError::Unknown(format!("body `{}`", t.body)))?; let face = crate::appearance::face_index_at(tb, t.point.0) .ok_or_else(|| DocError::Invalid(format!("no face of `{}` at the tool point", t.body)))?; + // The pieces keep the planar roles of the faces they share with the body (#565). kernel::split_body(&mb.body, &kernel::SplitTool::Face { body: &tb.body, face })? + .into_iter() + .map(|part| Ok(Traced::step(part.with_preserved_planar_sources(&mb.body)?, &[&input]))) + .collect::>>()? } None => { let pl = doc.resolve_plane_in(vals, plane, 0, Some(st))?; - kernel::split_by_plane(&mb.body, &pl)? + split_by_plane_traced(&input, &pl)? } }; if parts.len() < 2 { return Err(DocError::Invalid("the tool does not split the body".into())); } - let input = mb.traced(); - let mut it = parts.into_iter().map(|part| Traced::step(part, &[&input])); + let mut it = parts.into_iter(); if let (Some(first), Some(slot)) = (it.next(), st.bodies.get_mut(i)) { *slot = ModelBody::traced_new(mb.name.clone(), first, mb.feature); } @@ -5291,6 +5380,23 @@ mod body_name_tests { } } +/// The parts of a body split by a plane, on its positive side first (only the non-empty ones). +/// Each part's cut face is named `section` after the half-space box that cut it, so it takes an +/// attachment that follows the plane (#565); the box's other faces never reach the part. +fn split_by_plane_traced(input: &Traced, plane: &Plane) -> Result> { + let mut parts = Vec::new(); + for positive in [true, false] { + let (part, tool) = kernel::half_space(&input.body, plane, positive)?; + let Some(part) = part else { continue }; + // The box's cap in the plane: its start cap on the positive side, its end cap on the other. + let section = Some("section".to_string()); + let caps = if positive { [section, None] } else { [None, section] }; + let tool = crate::lineage::ProfileRoles { sketch: None, region: None, caps }.tool(tool, None); + parts.push(Traced::step(part, &[input, &tool])); + } + Ok(parts) +} + /// The plane a straight sketch line sweeps along its sketch's normal: through the line, its x /// along the line and its y along the normal (a Split Body tool, #1552). pub fn sketch_line_plane(st: &ModelState, sketch: u64, line: &str) -> Result { diff --git a/crates/doc/src/format/pending/cam-couplings.rs b/crates/doc/src/format/pending/cam-couplings.rs new file mode 100644 index 000000000..1f5c7917f --- /dev/null +++ b/crates/doc/src/format/pending/cam-couplings.rs @@ -0,0 +1,8 @@ +//! A motion link can carry a `cam` coupling (`joint.cam`): the cam's `profile` (a sketch's closed +//! profile by its outer loop's curve ids, or picked edges of the cam's bodies with their names), +//! the `follower` (`knife`, `roller` with a `radius`, or `flat`), an optional `tip` (a joint origin +//! where the follower touches) and `reverse` (the side it rides from). The link then also saves +//! `lift`, the follower's values over one turn of the cam, worked out from the profile again +//! whenever the design changes. Older designs need no transformation: a link without them is a +//! plain motion link, as it always was; 0.13.x asks for an update instead of reading a cam's +//! follower as a plain link of ratio 1. diff --git a/crates/doc/src/format/pending/hole-position-expressions.rs b/crates/doc/src/format/pending/hole-position-expressions.rs new file mode 100644 index 000000000..8c5257abe --- /dev/null +++ b/crates/doc/src/format/pending/hole-position-expressions.rs @@ -0,0 +1,5 @@ +//! A Hole placed by position can keep that position as length expressions (`at`: `[x, y, z]`, +//! numbers as numbers, expressions as strings), and is drilled where they evaluate, so it follows +//! the design's parameters (#1678). `position` still holds the point it was made at. Older designs +//! need no transformation: a hole without `at` is drilled at `position` as before; 0.13.x asks for +//! an update instead of drilling a moved hole at its old point. diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index f526d4c7c..c8fae80a3 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -1,8 +1,8 @@ //! Joints between occurrences: joint origins (snap frames on component geometry, re-found on //! every solve so they follow edits), joints (rigid, revolute, slider, cylindrical, pin-slot, //! planar, ball) with their motion values and limits, motion links (gears, racks and screws are -//! links whose ratio comes from radii or a pitch), and the solver that places occurrences from -//! the joint graph. +//! links whose ratio comes from radii or a pitch; a cam's follower follows a table worked out from +//! its profile, `joints_cam.rs`), and the solver that places occurrences from the joint graph. //! //! A joint makes B's joint frame coincide with A's frame moved by the joint's motion: //! `T_B · F_b = T_A · F_a · M(q) · Flip`, so `T_B = T_A · F_a · M(q) · Flip · F_b⁻¹`, where `T` @@ -140,7 +140,8 @@ pub struct Joint { pub suppressed: bool, } -/// Value of joint `b` (index `ib`) = ratio · value of joint `a` (index `ia`) + offset. +/// Value of joint `b` (index `ib`) = ratio · value of joint `a` (index `ia`) + offset, or for a +/// cam, its `lift` table at a's value + offset. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MotionLink { pub a: u64, @@ -152,11 +153,29 @@ pub struct MotionLink { pub ratio: f64, #[serde(default)] pub offset: f64, - /// Gears, a rack and pinion or a screw: what the ratio comes from. The ratio is worked out - /// from it again whenever the design changes (`coupling_ratio`), so it follows the radii and - /// the pitch; the last one worked out is kept in `ratio`. + /// Gears, a rack and pinion, a screw or a cam: what the ratio (or a cam's table) comes from. + /// It is worked out from it again whenever the design changes (`coupling_values`), so it + /// follows the radii, the pitch and the cam's profile; the last one worked out is kept in + /// `ratio` and `lift`. #[serde(default, skip_serializing_if = "Option::is_none")] pub coupling: Option, + /// A cam's follower values over one turn of a (`cam::CAM_SAMPLES` of them, in b's units, the + /// offset left out); empty for every other link. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub lift: Vec, +} + +impl MotionLink { + /// b's value for a's value `x` (before b's limits). A cam's table that is not whole (a + /// hand-edited file) gives no value, so b keeps where it is; a table on any other link is + /// not read. + pub fn follow(&self, x: f64) -> f64 { + match &self.coupling { + Some(Coupling::Cam(_)) if self.lift.len() == cam::CAM_SAMPLES => cam::lift_at(&self.lift, x) + self.offset, + Some(Coupling::Cam(_)) => f64::NAN, + _ => self.ratio * x + self.offset, + } + } } /// A length a coupling's ratio comes from: millimetres, an expression over the design's @@ -199,14 +218,22 @@ pub enum Coupling { #[serde(default, skip_serializing_if = "std::ops::Not::not")] reverse: bool, }, + /// A cam on a revolute joint (a) and its follower (b, a slider or a revolute): b rides the + /// cam's profile (`joints_cam.rs`). + Cam(cam::Cam), } impl Coupling { - /// The lengths the ratio comes from: a's gear and b's, or the pinion's radius or the pitch. + /// The lengths the ratio comes from: a's gear and b's, the pinion's radius, the pitch, or a + /// cam's roller radius. pub fn sizes(&self) -> Vec<&Size> { match self { Coupling::Gear { ra, rb, .. } => vec![ra, rb], Coupling::RackPinion { radius: s, .. } | Coupling::Screw { pitch: s, .. } => vec![s], + Coupling::Cam(c) => match &c.follower { + cam::Follower::Roller { radius } => vec![radius], + _ => Vec::new(), + }, } } @@ -214,6 +241,10 @@ impl Coupling { match self { Coupling::Gear { ra, rb, .. } => vec![ra, rb], Coupling::RackPinion { radius: s, .. } | Coupling::Screw { pitch: s, .. } => vec![s], + Coupling::Cam(c) => match &mut c.follower { + cam::Follower::Roller { radius } => vec![radius], + _ => Vec::new(), + }, } } } @@ -231,14 +262,18 @@ fn size_of(doc: &Document, st: &ModelState, s: &Size) -> Result { if v.is_finite() && v > 1e-9 && v <= MAX_SIZE { Ok(v) } else { - Err(DocError::Invalid(format!("a gear, rack or screw needs a positive length, not {v}"))) + Err(DocError::Invalid(format!("a gear, rack, screw or roller needs a positive length, not {v}"))) } } -/// The ratio a link's coupling gives it (b's value per a's, in radians and mm), worked out from -/// the geometry and parameters it is defined by; `None` for a plain link. -pub fn coupling_ratio(doc: &Document, st: &ModelState, l: &MotionLink) -> Option> { - l.coupling.as_ref().map(|c| coupled(doc, st, l, c)) +/// The ratio a link's coupling gives it (b's value per a's, in radians and mm) and a cam's table +/// (`MotionLink::lift`; empty for the others), worked out from the geometry and parameters it is +/// defined by; `None` for a plain link. +pub fn coupling_values(doc: &Document, st: &ModelState, l: &MotionLink) -> Option)>> { + l.coupling.as_ref().map(|c| match c { + Coupling::Cam(c) => cam::table(doc, st, l, c).map(|t| (1.0, t)), + c => coupled(doc, st, l, c).map(|r| (r, Vec::new())), + }) } fn coupled(doc: &Document, st: &ModelState, l: &MotionLink, c: &Coupling) -> Result { @@ -260,6 +295,8 @@ fn coupled(doc: &Document, st: &ModelState, l: &MotionLink, c: &Coupling) -> Res } Coupling::RackPinion { radius, reverse } => Ok(travel(size_of(doc, st, radius)?)? * sign(*reverse)), Coupling::Screw { pitch, reverse } => Ok(travel(size_of(doc, st, pitch)? / std::f64::consts::TAU)? * sign(*reverse)), + // A cam's follower follows its table (`coupling_values`), not a ratio. + Coupling::Cam(_) => Ok(1.0), } } @@ -491,7 +528,11 @@ fn apply_links(asm: &Assembly, vals: &mut Values) { let before = linked(vals); for l in &asm.links { let Some(src) = vals.get(&l.a).and_then(|q| q.get(l.ia)).copied() else { continue }; - let mut next = l.ratio * src + l.offset; + let mut next = l.follow(src); + // A hand-edited table (or source) that gives no number leaves b where it is. + if !next.is_finite() { + continue; + } if let Some((lo, hi)) = limits.get(&(l.b, l.ib)) { next = next.max(*lo).min(*hi); } @@ -1388,6 +1429,9 @@ impl Document { } } +#[path = "joints_cam.rs"] +pub mod cam; + #[path = "joints_reach.rs"] mod reach; pub use reach::{REACH_TOL, Reach, Reached, reach}; @@ -1425,7 +1469,8 @@ mod tests { suppressed: false, }) .collect(); - let links = (1..n).rev().map(|a| MotionLink { a, ia: 0, b: a + 1, ib: 0, ratio: 2.0, offset: 0.0, coupling: None }).collect(); + let links = + (1..n).rev().map(|a| MotionLink { a, ia: 0, b: a + 1, ib: 0, ratio: 2.0, offset: 0.0, coupling: None, lift: Vec::new() }).collect(); Assembly { joints, links, ..Assembly::default() } } @@ -1477,8 +1522,8 @@ mod tests { } let st = ModelState::default(); let ratio = |a: u64, b: u64, c: Coupling| { - let l = MotionLink { a, ia: 0, b, ib: 0, ratio: 0.0, offset: 0.0, coupling: Some(c) }; - coupling_ratio(&doc, &st, &l).map(|r| r.map_err(|e| e.to_string())) + let l = MotionLink { a, ia: 0, b, ib: 0, ratio: 0.0, offset: 0.0, coupling: Some(c), lift: Vec::new() }; + coupling_values(&doc, &st, &l).map(|r| r.map(|(ratio, _)| ratio).map_err(|e| e.to_string())) }; let len = Size::Length; assert_eq!(ratio(1, 2, Coupling::Gear { ra: len(10.0), rb: len(40.0), internal: false, reverse: false }), Some(Ok(-0.25))); diff --git a/crates/doc/src/joints_cam.rs b/crates/doc/src/joints_cam.rs new file mode 100644 index 000000000..6d8454ae5 --- /dev/null +++ b/crates/doc/src/joints_cam.rs @@ -0,0 +1,1024 @@ +//! Cams (`joint.cam`): a revolute joint (the cam) drives a follower joint, a slider (a translating +//! follower) or a revolute (an oscillating follower), so that the follower rides the cam's +//! profile. The follower's value over one turn of the cam is worked out from the profile (a closed +//! sketch profile or a closed loop of the cam body's edges) and the follower (a knife edge, a +//! roller or a flat face) and kept on the motion link as a table, which `MotionLink::follow` +//! interpolates; the table is worked out again whenever the design changes. +//! +//! Everything is worked out in the cam's fixed frame C: the frame of the cam joint's other side, +//! in which the cam's profile turns by the joint's value about z. The follower's line (or pivot) is +//! its joint's A-side frame, which stays put whichever side of that joint moves. The follower comes +//! toward the cam from where it starts (a translating follower from far along its line, an +//! oscillating one from its arm pointing away from the cam's axis) and stops where it first +//! touches the profile: the follower stays in contact, as a spring would hold it. + +use std::f64::consts::TAU; + +use serde::{Deserialize, Serialize}; +use solidcraft_geom::{Vec2, Vec3}; + +use super::{JointKind, JointOrigin, MotionLink, Size, component_bodies, component_of, flip_of, occurrence_world, size_of}; +use crate::{DocError, Document, IDENTITY, Mat, ModelState, Result, apply_point, apply_vector, mat_inverse, mat_mul}; + +/// Samples of a cam's table over one turn of the cam (one per degree). +pub const CAM_SAMPLES: usize = 360; +/// Points a cam's profile is sampled into at most. +pub const MAX_PROFILE_POINTS: usize = 20_000; +/// Edges a cam's profile is picked from at most. +pub const MAX_PROFILE_EDGES: usize = 64; + +/// Where a cam's profile comes from. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum CamProfile { + /// A closed profile of a sketch (feature id) in the cam's component, by the ids of its outer + /// loop's curves (the profile sharing most of them; with none given, the profile with the + /// largest outer loop): that outer loop. + Sketch { + sketch: u64, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + curves: Vec, + }, + /// Edges of the cam's bodies forming one closed loop: points on them in the component's + /// coordinates and the edges' persistent names (found first). + Edges { + occurrence: u64, + picks: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + names: Vec, + }, +} + +/// What touches the cam. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Follower { + /// A point (a knife edge seen along the cam's axis). + #[default] + Knife, + /// A roller of radius `radius` about the follower's point. + Roller { radius: Size }, + /// A flat face square to a translating follower's line. + Flat, +} + +/// A cam coupling's definition. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Cam { + pub profile: CamProfile, + #[serde(default)] + pub follower: Follower, + /// An oscillating follower's knife tip or roller centre, on the follower. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tip: Option, + /// A translating follower rides the cam from the −z side of its line; an oscillating one + /// comes to the cam turning the other way. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub reverse: bool, +} + +/// A value of a periodic table over one turn of `x` (radians): a monotone cubic through the +/// samples (Hermite, with central slopes limited as Fritsch and Carlson do), so it has no kinks +/// and never goes past its two samples (a follower on a dwell stays on it up to a rise). NaN for +/// an empty table or a non-finite `x`. +pub fn lift_at(table: &[f64], x: f64) -> f64 { + let n = table.len(); + let u = (x.rem_euclid(TAU) / TAU * n as f64).rem_euclid(n as f64); + if n == 0 || !u.is_finite() { + return f64::NAN; + } + let i = u.floor(); + let f = u - i; + let i = i as usize; + let at = |k: usize| table.get(k % n).copied().unwrap_or(f64::NAN); + let (p0, p1, p2, p3) = (at(i + n - 1), at(i), at(i + 1), at(i + 2)); + // The slope at a sample from the steps either side: none where they disagree (an extremum or + // a flat), else their mean, at most three times the smaller. + let slope = |a: f64, b: f64| if a * b <= 0.0 { 0.0 } else { 0.5 * (a + b).signum() * (a + b).abs().min(6.0 * a.abs().min(b.abs())) }; + let (m1, m2) = (slope(p1 - p0, p2 - p1), slope(p2 - p1, p3 - p2)); + let (f2, f3) = (f * f, f * f * f); + (2.0 * f3 - 3.0 * f2 + 1.0) * p1 + (f3 - 2.0 * f2 + f) * m1 + (3.0 * f2 - 2.0 * f3) * p2 + (f3 - f2) * m2 +} + +fn rot(v: Vec2, a: f64) -> Vec2 { + let (s, c) = a.sin_cos(); + Vec2::new(v.x * c - v.y * s, v.x * s + v.y * c) +} + +/// Where a translating follower coming along `-d` from far along its line through `g` first +/// touches the closed polygon `poly`: the largest `t` of its point `g + t·d` (its roller's centre +/// for `r > 0`; for `flat`, its face square to `d`). `None` when it misses the profile. +pub fn first_contact_along(poly: &[Vec2], g: Vec2, d: Vec2, r: f64, flat: bool) -> Option { + let n = d.perp(); + let mut best: Option = None; + let mut take = |t: f64| { + if t.is_finite() && best.is_none_or(|b| t > b) { + best = Some(t); + } + }; + if flat { + for p in poly { + take((*p - g).dot(d)); + } + return best; + } + let count = poly.len(); + for i in 0..count { + let (Some(&p), Some(&q)) = (poly.get(i), poly.get((i + 1) % count)) else { continue }; + let (a, b) = ((p - g).dot(n), (q - g).dot(n)); + // Edges wholly outside the band the follower sweeps. + if a.min(b) > r || a.max(b) < -r { + continue; + } + if r <= 0.0 { + if a == b { + // Along the line: both ends. + take((p - g).dot(d)); + take((q - g).dot(d)); + } else { + let k = a / (a - b); + take((p - g).dot(d) + (q - p).dot(d) * k); + } + continue; + } + // The roller's centre a radius from the edge: on its two parallels (the foot within the + // edge) or about its start (each vertex starts one edge). + let len = p.dist(q); + if let Some(e) = (q - p).normalized() { + let m = e.perp(); + let dm = d.dot(m); + if dm.abs() > 1e-15 { + for side in [r, -r] { + let t = (side - (g - p).dot(m)) / dm; + let foot = (g + d * t - p).dot(e); + if (0.0..=len).contains(&foot) { + take(t); + } + } + } + } + if a.abs() <= r { + take((p - g).dot(d) + (r * r - a * a).max(0.0).sqrt()); + } + } + best +} + +/// The angles in [0, 2π) where an oscillating follower's tip touches the closed polygon `poly`: +/// its tip (a roller's centre for `r > 0`) at `arm` from the pivot `pivot`, turned from the angle +/// `start` the way `turn` says (+1 counter-clockwise), sorted. +fn touches_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, start: f64, turn: f64) -> Vec { + let tip = |a: f64| pivot + Vec2::from_angle(a) * arm; + let count = poly.len(); + let edge = |i: usize| Some((*poly.get(i)?, *poly.get((i + 1) % count)?)); + let mut out = Vec::new(); + let mut take = |a: f64, keep: &dyn Fn(Vec2) -> bool| { + let turned = (turn * (a - start)).rem_euclid(TAU); + if turned.is_finite() && turned < TAU && keep(tip(a)) { + out.push(turned); + } + }; + // Angles of the tip's direction u where u·w = h: both solutions. + let meet = |w: Vec2, h: f64| -> Vec { + let len = w.len(); + if len <= 0.0 || !(h / len).is_finite() || (h / len).abs() > 1.0 { + return Vec::new(); + } + let (base, spread) = (w.angle(), (h / len).clamp(-1.0, 1.0).acos()); + vec![base + spread, base - spread] + }; + for (p, q) in (0..count).filter_map(edge) { + let near = dist_to_segment(pivot, p, q); + let far = (p - pivot).len().max((q - pivot).len()); + if near > arm + r || far < arm - r { + continue; + } + let len = p.dist(q); + let Some(e) = (q - p).normalized() else { continue }; + let m = e.perp(); + // On a parallel of the edge a radius away (the edge itself for a knife), the foot within it. + for side in if r > 0.0 { vec![r, -r] } else { vec![0.0] } { + for a in meet(m * arm, side - (pivot - p).dot(m)) { + take(a, &|t: Vec2| (0.0..=len).contains(&(t - p).dot(e))); + } + } + if r > 0.0 { + // A radius from the edge's start: |pivot + arm·u − p| = r. + let w = p - pivot; + for a in meet(w, (arm * arm + w.len2() - r * r) / (2.0 * arm)) { + take(a, &|_| true); + } + } + } + out.sort_by(f64::total_cmp); + out +} + +/// Whether an oscillating follower's tip, turned `turned` from `start` the way `turn` says, +/// overlaps the profile by more than `slack`. +fn overlaps_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, (start, turn): (f64, f64), turned: f64, slack: f64) -> bool { + let at = pivot + Vec2::from_angle(start + turn * turned) * arm; + let n = poly.len(); + let gap = + (0..n).filter_map(|i| Some((*poly.get(i)?, *poly.get((i + 1) % n)?))).map(|(p, q)| dist_to_segment(at, p, q)).fold(f64::INFINITY, f64::min); + // Inside counts only clear of the boundary: a knife on an edge touches it. + gap < r - slack || (gap > slack && inside(poly, at)) +} + +/// Where an oscillating follower first touches the closed polygon `poly` turning from `start` +/// (the angle it turns through, in (0, 2π)): see `touches_turning`. `None` when it misses the +/// profile or starts on it. +pub fn first_contact_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, start: f64, turn: f64) -> Option { + if overlaps_turning(poly, pivot, arm, r, (start, turn), 0.0, -f64::EPSILON) { + return None; + } + touches_turning(poly, pivot, arm, r, start, turn).into_iter().find(|t| *t > 0.0) +} + +/// Where an oscillating follower that touched the profile at `from` (turned from `start`) is +/// after the cam turned on a little: pushed back to where the profile now lets it be when its tip +/// overlaps the profile (by more than `slack`), else on to where it next touches. It stays on the +/// part of the profile it rides, however the profile crosses its tip's circle elsewhere. +pub fn next_contact_turning(poly: &[Vec2], pivot: Vec2, arm: f64, r: f64, (start, turn): (f64, f64), from: f64, slack: f64) -> Option { + let touches = touches_turning(poly, pivot, arm, r, start, turn); + // A touch where the tip is clear of the rest of the profile (a roller inside the profile is a + // radius from the parallels of the edges near the one it overlaps too). + let clear = |t: &f64| !overlaps_turning(poly, pivot, arm, r, (start, turn), *t, slack); + if overlaps_turning(poly, pivot, arm, r, (start, turn), from, slack) { + touches.into_iter().rev().filter(|t| *t < from).find(clear) + } else { + touches.into_iter().filter(|t| *t >= from - 1e-12).find(clear) + } +} + +fn dist_to_segment(x: Vec2, p: Vec2, q: Vec2) -> f64 { + let d = q - p; + let t = if d.len2() > 0.0 { ((x - p).dot(d) / d.len2()).clamp(0.0, 1.0) } else { 0.0 }; + x.dist(p + d * t) +} + +/// Even-odd containment in a closed polygon. +fn inside(poly: &[Vec2], x: Vec2) -> bool { + let n = poly.len(); + let mut inside = false; + for i in 0..n { + let (Some(a), Some(b)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; + if (a.y > x.y) != (b.y > x.y) && x.x < a.x + (x.y - a.y) / (b.y - a.y) * (b.x - a.x) { + inside = !inside; + } + } + inside +} + +/// Everything a cam's table is worked out from, in the cam's fixed frame C. +struct Setup { + /// The profile at cam value 0. + poly: Vec, + /// +1 when the cam turns by +value about C's z (it is the joint's b side), −1 otherwise. + turn: f64, + /// A translating follower's line (a point and its unit direction, the slider's +z), or an + /// oscillating follower's pivot. + at: Vec2, + dir: Vec2, + /// An oscillating follower's arm (pivot to tip) where it is now. + arm: Option, + /// The side a translating follower rides from (+1: from +dir), or the way an oscillating one + /// turns toward the cam (+1: counter-clockwise). + side: f64, + /// b's value per mm of the follower's travel along `dir`, or per radian of its turn about z. + gain: f64, + radius: f64, + flat: bool, + size: f64, + /// C in the world, and the occurrence the follower's joint moves. + frame: Mat, + moving: u64, +} + +fn joint(doc: &Document, id: u64) -> Result<&super::Joint> { + doc.assembly.joints.iter().find(|j| j.id == id).ok_or_else(|| DocError::Unknown(format!("joint {id}"))) +} + +fn world(doc: &Document, occ: u64) -> Mat { + if occ == 0 { IDENTITY } else { occurrence_world(doc, occ) } +} + +/// The profile's points in its component's coordinates, the occurrence placing them, and the +/// profile's size. `fa`, `fb`: the cam joint's frames (picked edges continue along the edges in +/// the plane square to the cam's axis). +fn profile_points(doc: &Document, st: &ModelState, p: &CamProfile, cam: &super::Joint, (fa, fb): (&Mat, &Mat)) -> Result<(Vec, u64, f64)> { + let bad = |m: &str| DocError::Invalid(format!("cam: {m}")); + match p { + CamProfile::Sketch { sketch, curves } => { + let sk = st.sketches.iter().find(|s| s.feature == *sketch).ok_or_else(|| bad(&format!("no sketch {sketch}")))?; + let comp = doc.feature(*sketch).map(|f| f.component).unwrap_or(0); + let sides: Vec = + [cam.b.occurrence, cam.a.occurrence].into_iter().filter(|o| component_of(doc, *o).is_ok_and(|c| c == comp)).collect(); + let occ = match sides.as_slice() { + [o] => *o, + [] => return Err(bad("the profile's sketch must be in the component the cam joint turns")), + _ => return Err(bad("both sides of the cam joint are that sketch's component: pick the cam's edges instead")), + }; + let lp = &sketch_profile(sk, curves).ok_or_else(|| bad("the sketch has no closed profile (or the cam's profile is gone)"))?.region.outer; + let too_many = || bad(&format!("the profile is too detailed (more than {MAX_PROFILE_POINTS} points)")); + let size = bounds_2d(&sampled(lp, 0.1).ok_or_else(too_many)?); + let pts = sampled(lp, tolerance(size)).ok_or_else(too_many)?; + let pl = &sk.plane; + Ok((pts.iter().map(|q| pl.origin + pl.x * q.x + pl.y * q.y).collect(), occ, size)) + } + CamProfile::Edges { occurrence, picks, names } => { + if *occurrence != cam.a.occurrence && *occurrence != cam.b.occurrence { + return Err(bad("the profile's edges must be on the part the cam joint turns")); + } + if picks.is_empty() || picks.len() > MAX_PROFILE_EDGES || !picks.iter().all(|p| p.is_finite()) { + return Err(bad(&format!("pick 1 to {MAX_PROFILE_EDGES} edges"))); + } + let comp = component_of(doc, *occurrence)?; + let bodies = component_bodies(doc, st, comp); + let size = bodies.iter().map(|b| b.body.size()).fold(0.0, f64::max); + if bodies.is_empty() || !size.is_finite() || size <= 0.0 { + return Err(bad("the cam has no body")); + } + // Each body sampled to its own size (a large part beside the cam leaves the cam fine). + // Each body's edges with the faces beside them. + let meshes: Vec = + bodies.iter().map(|b| b.body.tessellate(tolerance(b.body.size()))).collect::>()?; + let edges: Vec<(usize, &Vec, &[u32])> = meshes + .iter() + .enumerate() + .flat_map(|(k, m)| m.edges.iter().enumerate().map(move |(i, e)| (k, e, m.edge_faces.get(i).map(Vec::as_slice).unwrap_or(&[])))) + .collect(); + let mut lines: Vec<&Vec> = Vec::new(); + let mut sides: Vec<(usize, &[u32])> = Vec::new(); + for (k, pick) in picks.iter().enumerate() { + let mut at = *pick; + // A named edge is looked for on the body that has it, and only there. + let mut on: Option = None; + if let Some(name) = names.get(k).filter(|n| !n.is_empty()) { + let (body, p) = bodies + .iter() + .enumerate() + .find_map(|(i, b)| crate::naming::find_edge(b, name, *pick).ok().map(|(p, _)| (i, p))) + .ok_or_else(|| bad(&format!("the edge `{name}` no longer exists (edit the cam to pick again)")))?; + (on, at) = (Some(body), p); + } + let nearest = edges + .iter() + .filter(|e| on.is_none_or(|b| e.0 == b)) + .map(|e| { + let d = e.1.windows(2).filter_map(|w| match w { + [p, q] => Some(at.dist_to_segment(*p, *q)), + _ => None, + }); + (d.fold(f64::MAX, f64::min), e) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .filter(|(d, _)| *d <= 1e-3 * size + 1e-3) + .ok_or_else(|| bad("no edge there"))?; + if !lines.iter().any(|l| std::ptr::eq(*l, nearest.1.1)) { + lines.push(nearest.1.1); + sides.push((nearest.1.0, nearest.1.2)); + } + } + // The other edges in the picked edges' plane square to the cam's axis, beside a face of + // theirs: a loop continues along them (a circle the kernel keeps as two arcs is picked + // with one click), and not onto another part touching it. + let f = if *occurrence == cam.b.occurrence { fb } else { fa }; + let axis = Vec3::new(f[2][0], f[2][1], f[2][2]); + let level = lines.first().and_then(|l| l.first()).map(|p| p.dot(axis)).unwrap_or(0.0); + // Joins and the plane to the picked edges' own size, not their bodies' (a small cam in a + // component with a large part must not close a gap of its own size). + let span = extent(lines.iter().flat_map(|l| l.iter())); + let (flat, join) = (1e-6 * span + 1e-9, 1e-6 * span + 1e-9); + let beside = |(k, faces): (usize, &[u32])| sides.iter().any(|(sk, sf)| *sk == k && sf.iter().any(|f| faces.contains(f))); + let pool: Vec<&Vec> = edges + .iter() + .filter(|(k, e, faces)| { + !lines.iter().any(|l| std::ptr::eq(*l, *e)) && beside((*k, faces)) && e.iter().all(|p| (p.dot(axis) - level).abs() <= flat) + }) + .map(|(_, e, _)| *e) + .collect(); + let loop_ = chain(&lines, &pool, join) + .ok_or_else(|| bad(&format!("the picked edges must form one closed loop (of at most {MAX_PROFILE_POINTS} points)")))?; + // The profile's own size (not its bodies'), for the checks on its plane and area. + let size = extent(loop_.iter()); + Ok((loop_, *occurrence, size)) + } + } +} + +/// Polylines joined end to end into one closed loop, without the repeated joints and the closing +/// point: every one of `lines` once, either way round, continued along `pool` where no line goes +/// on. `None` when they don't close, or close leaving a line out. +fn chain(lines: &[&Vec], pool: &[&Vec], tol: f64) -> Option> { + let (first, rest) = lines.split_first()?; + let mut out: Vec = first.to_vec(); + let (mut used, mut taken) = (vec![false; rest.len()], vec![false; pool.len()]); + // The pool's ends by their cell of a `tol` grid, so the next one is found among a few. + let cell = |p: Vec3| -> Option<[i64; 3]> { + let c = [p.x / tol, p.y / tol, p.z / tol]; + c.iter().all(|v| v.is_finite() && v.abs() < 1e15).then(|| c.map(|v| v.round() as i64)) + }; + let mut ends: std::collections::BTreeMap<[i64; 3], Vec<(usize, bool)>> = std::collections::BTreeMap::new(); + for (k, l) in pool.iter().enumerate() { + for (p, flip) in [(l.first(), false), (l.last(), true)] { + if let Some(c) = p.and_then(|p| cell(*p)) { + ends.entry(c).or_default().push((k, flip)); + } + } + } + let near_end = |end: Vec3, taken: &[bool]| -> Option<(usize, bool)> { + let c = cell(end)?; + for d in 0..27i64 { + let key = [c[0] + d % 3 - 1, c[1] + d / 3 % 3 - 1, c[2] + d / 9 - 1]; + for &(k, flip) in ends.get(&key).into_iter().flatten() { + let l = pool.get(k)?; + let p = if flip { l.last()? } else { l.first()? }; + if taken.get(k) == Some(&false) && p.dist(end) <= tol { + return Some((k, flip)); + } + } + } + None + }; + // The next picked polyline on from `end` (a few at most), and whether it runs backwards. + let next = |end: Vec3, used: &[bool]| { + rest.iter().enumerate().filter(|(k, _)| used.get(*k) == Some(&false)).find_map(|(k, l)| { + if l.first()?.dist(end) <= tol { + Some((k, false)) + } else if l.last()?.dist(end) <= tol { + Some((k, true)) + } else { + None + } + }) + }; + for _ in 0..rest.len() + pool.len() { + let end = *out.last()?; + if out.len() > 3 && out.first()?.dist(end) <= tol { + break; + } + if out.len() > MAX_PROFILE_POINTS { + return None; + } + let (l, flip) = match next(end, &used) { + Some((k, flip)) => { + *used.get_mut(k)? = true; + (*rest.get(k)?, flip) + } + None => { + let (k, flip) = near_end(end, &taken)?; + *taken.get_mut(k)? = true; + (*pool.get(k)?, flip) + } + }; + if flip { + out.extend(l.iter().rev().skip(1)); + } else { + out.extend(l.iter().skip(1)); + } + } + if out.len() < 4 || out.len() > MAX_PROFILE_POINTS + 1 || out.first()?.dist(*out.last()?) > tol || !used.iter().all(|u| *u) { + return None; + } + out.pop(); + Some(out) +} + +/// The profile of a solved sketch a cam's `curves` name: the one sharing most of them (the larger +/// on a tie), or with none named the one with the largest outer loop. `None` when no profile +/// shares at least half of them (most of the cam's outline gone: a neighbouring region sharing a +/// curve with it is not the cam). +pub fn sketch_profile<'a>(sk: &'a crate::SolvedSketch, curves: &[String]) -> Option<&'a solidcraft_sketch::Profile> { + if curves.len() > MAX_PROFILE_POINTS { + return None; + } + let named: std::collections::BTreeSet<&String> = curves.iter().collect(); + let shared = |p: &solidcraft_sketch::Profile| p.outer_curves.iter().filter(|c| named.contains(c)).count(); + let area = |p: &solidcraft_sketch::Profile| p.region.outer.signed_area().abs(); + sk.profiles + .iter() + .filter(|p| curves.is_empty() || 2 * shared(p) >= curves.len()) + .max_by(|a, b| shared(a).cmp(&shared(b)).then(area(a).total_cmp(&area(b)))) +} + +/// A loop's polyline within `tol`, segment by segment: `None` past `MAX_PROFILE_POINTS` points. +fn sampled(lp: &solidcraft_geom::Loop2, tol: f64) -> Option> { + let mut out = Vec::new(); + for seg in &lp.segs { + let p = seg.polyline(tol); + out.extend(p.iter().take(p.len().saturating_sub(1))); + if out.len() > MAX_PROFILE_POINTS { + return None; + } + } + Some(out) +} + +/// The diagonal of the box around some points (0 for none). +fn extent<'a>(pts: impl Iterator) -> f64 { + let (lo, hi) = pts.fold((Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)), |(lo, hi), p| { + (Vec3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z)), Vec3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z))) + }); + if lo.x <= hi.x { (hi - lo).len() } else { 0.0 } +} + +fn bounds_2d(pts: &[Vec2]) -> f64 { + let (mut lo, mut hi) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)); + for p in pts { + lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y)); + hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y)); + } + if lo.x <= hi.x { (hi - lo).len() } else { 0.0 } +} + +/// The chord error a profile is sampled to: 0.1 µm per 100 mm of its size, at least 0.1 µm. +fn tolerance(size: f64) -> f64 { + 1e-4 * (size / 100.0).max(1.0) +} + +/// The joints, frames and profile a cam link's table is worked out from. +fn setup(doc: &Document, st: &ModelState, l: &MotionLink, c: &Cam) -> Result { + let bad = |m: &str| DocError::Invalid(format!("cam: {m}")); + let (cam, fol) = (joint(doc, l.a)?, joint(doc, l.b)?); + if cam.kind != JointKind::Revolute { + return Err(bad("the cam turns on a revolute joint")); + } + if !matches!(fol.kind, JointKind::Slider | JointKind::Revolute) { + return Err(bad("the follower slides (slider) or swings (revolute)")); + } + if cam.a.occurrence == cam.b.occurrence { + return Err(bad("the cam joint joins two parts")); + } + let (fa, fb) = (super::resolve_origin(doc, st, &cam.a)?, super::resolve_origin(doc, st, &cam.b)?); + let (pts, occ, size) = profile_points(doc, st, &c.profile, cam, (&fa, &fb))?; + if pts.len() < 3 || pts.len() > MAX_PROFILE_POINTS || !size.is_finite() || size <= 0.0 { + return Err(bad(&format!("the profile must have 3 to {MAX_PROFILE_POINTS} points"))); + } + let inv = |m: &Mat| mat_inverse(m).ok_or_else(|| bad("degenerate frame")); + // The cam's fixed frame C (world) and the profile at value 0 in it, as `through` places the + // joint's sides. + let on_b = occ == cam.b.occurrence; + let (frame, local, fixed) = if on_b { + (mat_mul(&world(doc, cam.a.occurrence), &fa), mat_mul(&flip_of(cam), &inv(&fb)?), cam.a.occurrence) + } else { + (mat_mul(&mat_mul(&world(doc, cam.b.occurrence), &fb), &inv(&flip_of(cam))?), inv(&fa)?, cam.b.occurrence) + }; + let v: Vec = pts.iter().map(|p| apply_point(&local, *p)).collect(); + let mean = v.iter().map(|p| p.z).sum::() / v.len() as f64; + if v.iter().any(|p| (p.z - mean).abs() > 1e-6 * size + 1e-9) { + return Err(bad("the profile must lie in a plane square to the cam's axis")); + } + let poly: Vec = v.iter().map(|p| Vec2::new(p.x, p.y)).collect(); + if !poly.iter().all(|p| p.is_finite()) || area(&poly).abs() <= 1e-12 * size * size { + return Err(bad("the profile encloses no area")); + } + // The follower's line or pivot in C: its joint's frame on the side that stays (the side away + // from the cam's fixed part moves; b when neither side is that part), as `through` places it. + // The moving side travels (or turns) by +value along its z when it is b, −value when it is a. + let c_inv = inv(&frame)?; + let moves_b = follower_is_b(doc, cam, fol, (fixed, occ))?; + let (ga, gb) = (super::resolve_origin(doc, st, &fol.a)?, super::resolve_origin(doc, st, &fol.b)?); + let guide = if moves_b { + mat_mul(&world(doc, fol.a.occurrence), &ga) + } else { + mat_mul(&mat_mul(&world(doc, fol.b.occurrence), &gb), &inv(&flip_of(fol))?) + }; + let to_c = mat_mul(&c_inv, &guide); + let (g, d) = (apply_point(&to_c, Vec3::ZERO), apply_vector(&to_c, Vec3::Z)); + let (moving, sign_f) = if moves_b { (fol.b.occurrence, 1.0) } else { (fol.a.occurrence, -1.0) }; + let (radius, flat) = match &c.follower { + Follower::Knife => (0.0, false), + Follower::Roller { radius } => (size_of(doc, st, radius)?, false), + Follower::Flat => (0.0, true), + }; + let side = if c.reverse { -1.0 } else { 1.0 }; + let turn = if on_b { 1.0 } else { -1.0 }; + let at = Vec2::new(g.x, g.y); + // Where the follower touches now (in C): its tip, or the roller's picked round face. + let face = match &c.follower { + Follower::Roller { radius: Size::Circle(o) } => Some(o), + _ => None, + }; + // A roller picked by its round face (as its radius or its tip) turns about the face's axis: + // square to the profile's plane. + let roller = matches!(c.follower, Follower::Roller { .. }); + for o in [c.tip.as_ref(), face].into_iter().flatten().filter(|o| roller && matches!(o.snap, super::Snap::CircleCenter { .. })) { + let at = mat_mul(&c_inv, &doc.origin_world(st, o)?); + if Vec3::new(at[2][0], at[2][1], 0.0).len() > 1e-6 { + return Err(bad("the roller's axis must be parallel to the cam's")); + } + } + let tip = match c.tip.as_ref().or(face) { + Some(o) => { + let t = apply_point(&mat_mul(&c_inv, &doc.origin_world(st, o)?), Vec3::ZERO); + Some(Vec2::new(t.x, t.y)) + } + None => None, + }; + if fol.kind == JointKind::Slider { + if d.z.abs() > 1e-6 { + return Err(bad("the follower must slide square to the cam's axis")); + } + let dir = Vec2::new(d.x, d.y).normalized().ok_or_else(|| bad("degenerate frame"))?; + // Its line: along the slider's axis, through its tip (where it is across the line, which + // doesn't change as it slides), else through the axis. + let at = tip.map(|t| at + dir.perp() * (t - at).dot(dir.perp())).unwrap_or(at); + return Ok(Setup { poly, turn, at, dir, arm: None, side, gain: sign_f, radius, flat, size, frame, moving }); + } + if flat { + return Err(bad("a flat-faced follower slides (use a slider)")); + } + if Vec2::new(d.x, d.y).len() > 1e-6 { + return Err(bad("the follower must swing about an axis parallel to the cam's")); + } + let t = tip.ok_or_else(|| bad("an oscillating follower needs its tip (the knife's point or the roller's centre)"))?; + if at.len() <= 1e-9 * size { + return Err(bad("the follower's pivot is on the cam's axis")); + } + let arm = t - at; + if arm.len() <= 1e-9 * size { + return Err(bad("the follower's tip is on its pivot")); + } + // b turns the follower by its value about the joint's z, which is C's z or against it. + Ok(Setup { poly, turn, at, dir: Vec2::X, arm: Some(arm), side, gain: sign_f * d.z.signum(), radius, flat, size, frame, moving }) +} + +/// How many moving joints part occurrence `from` from each occurrence it is joined to, over the +/// unsuppressed joints but `skip`: a rigid joint moves nothing, and the root and the grounded +/// occurrences are all fixed to the world (`u64::MAX` here), so they cost nothing either. +fn hops(doc: &Document, from: u64, skip: [u64; 2]) -> std::collections::BTreeMap { + const WORLD: u64 = u64::MAX; + let mut next: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + let mut join = |a: u64, b: u64, cost: usize| { + next.entry(a).or_default().push((b, cost)); + next.entry(b).or_default().push((a, cost)); + }; + for j in doc.assembly.joints.iter().filter(|j| !j.suppressed && !skip.contains(&j.id)).take(super::MAX_JOINTS) { + join(j.a.occurrence, j.b.occurrence, usize::from(j.kind != JointKind::Rigid)); + } + join(0, WORLD, 0); + for o in doc.occurrences.iter().filter(|o| o.grounded) { + join(o.id, WORLD, 0); + } + // Breadth first with free steps taken first (each occurrence settled once, at its least cost). + let mut cost = std::collections::BTreeMap::from([(from, 0usize)]); + let mut done = std::collections::BTreeSet::new(); + let mut queue = std::collections::VecDeque::from([from]); + while let Some(o) = queue.pop_front() { + if !done.insert(o) { + continue; + } + let here = cost.get(&o).copied().unwrap_or(0); + for (other, step) in next.get(&o).into_iter().flatten() { + let d = here + step; + if cost.get(other).is_none_or(|c| d < *c) { + cost.insert(*other, d); + if *step == 0 { + queue.push_front(*other); + } else { + queue.push_back(*other); + } + } + } + } + cost +} + +/// Whether a follower joint's b side is the follower (its a side the guide): the guide is the side +/// fewer moving joints from the part the cam turns against (`frame`), through the other joints. A guide joined only to +/// the profile's part (`cam`) would turn with the profile: refused. +fn follower_is_b(doc: &Document, cam_joint: &super::Joint, fol: &super::Joint, (frame, cam): (u64, u64)) -> Result { + let skip = [cam_joint.id, fol.id]; + let from = hops(doc, frame, skip); + Ok(match (from.get(&fol.a.occurrence), from.get(&fol.b.occurrence)) { + (Some(a), Some(b)) => a <= b, + (Some(_), None) => true, + (None, Some(_)) => false, + (None, None) => { + let from = hops(doc, cam, skip); + if from.contains_key(&fol.a.occurrence) || from.contains_key(&fol.b.occurrence) { + return Err(DocError::Invalid( + "cam: the follower's guide turns with the cam's profile (put it on the part the cam turns against)".into(), + )); + } + true + } + }) +} + +/// A polygon's signed area, from its first point (so a small profile far from the axis keeps its +/// digits). +fn area(poly: &[Vec2]) -> f64 { + let (n, o) = (poly.len(), poly.first().copied().unwrap_or(Vec2::ZERO)); + (0..n).filter_map(|i| Some((*poly.get(i)? - o).cross(*poly.get((i + 1) % n)? - o))).sum::() / 2.0 +} + +/// The follower's places at the samples 0 ..= `CAM_SAMPLES` of a turn, `place(u, prev)` giving +/// it with the cam `u` samples on (from `prev`, where it was, when it is `follows`ed from sample +/// to sample). A followed follower must come back where it started after the turn. A step much +/// larger than the steps either side of it is followed again in finer steps: a smooth rise +/// shrinks with them, a jump (the follower leaving the profile and landing on another part of it) +/// stays one step, and is refused. `floor`: steps no larger than it are not looked at. +fn round(place: &dyn Fn(f64, Option) -> Result, follows: bool, floor: f64) -> Result> { + let mut raw: Vec = Vec::with_capacity(CAM_SAMPLES + 1); + for k in 0..=CAM_SAMPLES { + let prev = if follows { raw.last().copied() } else { None }; + raw.push(place(k as f64, prev)?); + } + let at = |k: usize| raw.get(k).copied().unwrap_or(f64::NAN); + if follows && (at(0) - at(CAM_SAMPLES)).abs() > 1e-6 { + return Err(DocError::Invalid("cam: after a turn of the cam the follower does not come back where it started (it would jump)".into())); + } + let step = |k: usize| (at(k + 1) - at(k)).abs(); + for k in 0..CAM_SAMPLES { + let (d, around) = (step(k), step((k + CAM_SAMPLES - 1) % CAM_SAMPLES).max(step((k + 1) % CAM_SAMPLES))); + if d <= floor || d <= 3.0 * around { + continue; + } + let (mut here, mut most) = (at(k), 0.0f64); + for j in 1..=32 { + let next = place(k as f64 + f64::from(j) / 32.0, follows.then_some(here))?; + most = most.max((next - here).abs()); + here = next; + } + if most > 0.5 * d { + return Err(DocError::Invalid(format!("cam: the follower would jump near {k} degrees of the cam's turn (it leaves the profile there)"))); + } + } + Ok(raw) +} + +/// A cam link's table: b's values at a's values 2π·k / `CAM_SAMPLES`, offset left out. A +/// translating follower stands at its first contact coming along its line; an oscillating one +/// starts at its first contact turning from pointing away from the cam's axis and is followed from +/// sample to sample (`round`). +pub fn table(doc: &Document, st: &ModelState, l: &MotionLink, c: &Cam) -> Result> { + let s = setup(doc, st, l, c)?; + let start = s.at.angle(); + let follows = s.arm.is_some(); + // Where the follower is with the cam `u` samples on: mm along its line, or the angle its arm + // turned through from pointing away from the cam's axis (the same direction in C at every + // sample), on from `prev` for an arm. + let place = |u: f64, prev: Option| -> Result { + // The follower turned back instead of the profile turned on. + let q = -s.turn * TAU * u / CAM_SAMPLES as f64; + match s.arm { + None => first_contact_along(&s.poly, rot(s.at, q), rot(s.dir * s.side, q), s.radius, s.flat) + .map(|t| t * s.side) + .ok_or_else(|| DocError::Invalid("cam: the follower's line misses the cam at some angles".into())), + Some(arm) => { + let (pivot, from) = (rot(s.at, q), (start + q, s.side)); + match prev { + None => first_contact_turning(&s.poly, pivot, arm.len(), s.radius, from.0, from.1), + Some(p) => next_contact_turning(&s.poly, pivot, arm.len(), s.radius, from, p, 1e-9 * s.size), + } + .ok_or_else(|| DocError::Invalid("cam: the follower's arm does not reach the cam at every angle (or starts on it)".into())) + } + } + }; + let raw = round(&place, follows, if follows { 1e-6 } else { 1e-6 * s.size })?; + let out: Vec = raw.iter().take(CAM_SAMPLES).map(|v| s.gain * if follows { start + s.side * v } else { *v }).collect(); + if !out.iter().all(|v| v.is_finite() && v.abs() <= 1e9 * s.size.max(1.0)) { + return Err(DocError::Invalid("cam: the follower's travel is out of range".into())); + } + Ok(out) +} + +/// The side a new cam's follower rides it from, as `Cam::reverse`: a translating follower from the +/// side of the cam's axis its bodies are on now, an oscillating one turning toward the cam the way +/// its arm is turned now from pointing away from the cam's axis. +pub fn default_reverse(doc: &Document, st: &ModelState, l: &MotionLink, c: &Cam) -> Result { + let s = setup(doc, st, l, &Cam { reverse: false, ..c.clone() })?; + if let Some(arm) = s.arm { + let off = (arm.angle() - s.at.angle() + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI; + return Ok(off < 0.0); + } + let comp = component_of(doc, s.moving)?; + let bb = component_bodies(doc, st, comp).iter().fold(solidcraft_geom::Aabb3::EMPTY, |bb, b| bb.union(&b.mesh().bounds())); + if bb.min.x > bb.max.x { + return Ok(false); + } + let inv = mat_inverse(&s.frame).ok_or_else(|| DocError::Invalid("cam: degenerate frame".into()))?; + let centre = apply_point(&mat_mul(&inv, &world(doc, s.moving)), bb.center()); + // The cam's axis is C's z: the follower is on the −dir side of it. + Ok(Vec2::new(centre.x, centre.y).dot(s.dir) < 0.0) +} + +/// How far a translating follower's line passes from the cam's axis (mm; 0 for an oscillating one). +pub fn follower_offset(doc: &Document, st: &ModelState, l: &MotionLink, c: &Cam) -> Result { + let s = setup(doc, st, l, c)?; + Ok(if s.arm.is_some() { 0.0 } else { s.at.cross(s.dir).abs() }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A circle of radius `r` about `c` as a polygon of `n` points (its sag is r·(1 − cos π/n)). + fn circle(c: Vec2, r: f64, n: usize) -> Vec { + (0..n).map(|k| c + Vec2::from_angle(TAU * k as f64 / n as f64) * r).collect() + } + + /// An eccentric circle (radius 30, its centre 10 from the axis) turned by θ against a + /// follower sliding along +x: a knife edge on a line `h` from the axis stands at + /// 10·cos θ + √(30² − (h − 10·sin θ)²), a roller of radius 5 as the knife on the circle of + /// radius 35, and a flat face at 10·cos θ + 30. + #[test] + fn a_translating_follower_rides_an_eccentric_circle() { + let (e, r) = (10.0, 30.0); + let poly = circle(Vec2::new(e, 0.0), r, 4096); + for k in 0..72 { + let th = TAU * k as f64 / 72.0 - 0.3; + // The follower turned back by θ, as `table` does. + let (d, at) = (rot(Vec2::X, -th), |h: f64| rot(Vec2::new(0.0, h), -th)); + for h in [0.0, 6.0, -12.0] { + let knife = first_contact_along(&poly, at(h), d, 0.0, false).unwrap_or(f64::NAN); + let want = e * th.cos() + (r * r - (h - e * th.sin()).powi(2)).sqrt(); + assert!((knife - want).abs() < 1e-4, "knife θ {th} h {h}: {knife} vs {want}"); + let roller = first_contact_along(&poly, at(h), d, 5.0, false).unwrap_or(f64::NAN); + let want = e * th.cos() + ((r + 5.0).powi(2) - (h - e * th.sin()).powi(2)).sqrt(); + assert!((roller - want).abs() < 1e-4, "roller θ {th} h {h}: {roller} vs {want}"); + } + let flat = first_contact_along(&poly, Vec2::ZERO, d, 0.0, true).unwrap_or(f64::NAN); + assert!((flat - (e * th.cos() + r)).abs() < 1e-4, "flat θ {th}: {flat}"); + } + // A line past the cam misses it. + assert_eq!(first_contact_along(&poly, Vec2::new(0.0, 50.0), Vec2::X, 0.0, false), None); + assert_eq!(first_contact_along(&poly, Vec2::new(0.0, 50.0), Vec2::X, 5.0, false), None); + } + + /// An arm of 50 about (−50, 40) with a roller of 5 on the same cam: the roller's centre is where + /// the arm's circle meets the circle of radius 35 about the cam's centre, the first of the two + /// met turning from the arm pointing away from the axis. + #[test] + fn an_oscillating_follower_meets_the_offset_circle() { + let (e, r, roller) = (10.0, 30.0, 5.0); + let (pivot, arm) = (Vec2::new(-50.0, 40.0), 50.0); + let start = pivot.angle(); + for k in 0..36 { + let th = TAU * k as f64 / 36.0; + let c = Vec2::from_angle(th) * e; + let poly = circle(c, r, 4096); + // The two circles meet at m ± n. + let (dv, l) = (c - pivot, (c - pivot).len()); + let a = (arm * arm - (r + roller).powi(2) + l * l) / (2.0 * l); + let m = pivot + dv * (a / l); + let n = dv.perp() * ((arm * arm - a * a).sqrt() / l); + for turn in [1.0, -1.0] { + let swept = |p: Vec2| (turn * ((p - pivot).angle() - start)).rem_euclid(TAU); + let want = swept(m + n).min(swept(m - n)); + let got = first_contact_turning(&poly, pivot, arm, roller, start, turn).unwrap_or(f64::NAN); + assert!((got - want).abs() < 1e-5, "θ {th} turn {turn}: {got} vs {want}"); + } + } + // Followed on from where it touches, it stays on the part of the profile it rides: a C + // whose two arms both cross the tip's circle, the tip resting on the second arm. + let c: Vec = [(-10.0, 20.0), (30.0, 20.0), (30.0, 14.0), (-4.0, 14.0), (-4.0, -14.0), (30.0, -14.0), (30.0, -20.0), (-10.0, -20.0)] + .into_iter() + .map(|(x, y)| Vec2::new(x, y)) + .collect(); + let (pv, l) = (Vec2::new(40.0, 0.0), 22.0); + let touches = touches_turning(&c, pv, l, 0.0, 0.0, 1.0); + let on = |t: f64| (pv + Vec2::from_angle(t) * l).y; + let first = first_contact_turning(&c, pv, l, 0.0, 0.0, 1.0).unwrap_or(f64::NAN); + let second = touches.iter().copied().find(|t| on(*t) < 0.0 && *t > first).unwrap_or(f64::NAN); + assert!(on(first) > 0.0 && second > first, "{touches:?}"); + let stay = next_contact_turning(&c, pv, l, 0.0, (0.0, 1.0), second, 1e-9).unwrap_or(f64::NAN); + assert!((stay - second).abs() < 1e-12, "{stay} vs {second}"); + // A knife on an edge touches it, it doesn't overlap it; just inside, it does. + let square: Vec = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].into_iter().map(|(x, y)| Vec2::new(x, y)).collect(); + let (pv, l) = (Vec2::new(0.0, -4.0), 3.0); + let up = std::f64::consts::FRAC_PI_2; + assert!(!overlaps_turning(&square, pv, l, 0.0, (up, 1.0), 0.0, 1e-9)); + assert!(overlaps_turning(&square, pv, l + 0.01, 0.0, (up, 1.0), 0.0, 1e-9)); + assert!((area(&square.iter().map(|p| *p * 0.004 + Vec2::new(524_288.0, 524_288.0)).collect::>()) - 6.4e-5).abs() < 1e-12); + // An arm that can't reach, and one that starts on the cam. + let poly = circle(Vec2::new(e, 0.0), r, 512); + assert_eq!(first_contact_turning(&poly, pivot, 5.0, 0.0, start, 1.0), None); + assert_eq!(first_contact_turning(&poly, Vec2::new(10.0, 0.0), 10.0, 0.0, 0.0, 1.0), None); + } + + /// An arm whose first contact vanishes mid-turn and lands on another lobe jumps, though it + /// comes back after the turn: refused. On the eccentric circle it follows smoothly. + #[test] + fn a_follower_that_jumps_is_refused() { + let arm_round = |poly: &[Vec2], pivot: Vec2, arm: f64| { + let start = pivot.angle(); + let place = |u: f64, prev: Option| -> Result { + let q = -TAU * u / CAM_SAMPLES as f64; + let p = rot(pivot, q); + match prev { + None => first_contact_turning(poly, p, arm, 0.0, start + q, 1.0), + Some(v) => next_contact_turning(poly, p, arm, 0.0, (start + q, 1.0), v, 1e-9), + } + .ok_or_else(|| DocError::Invalid("misses".into())) + }; + round(&place, true, 1e-6) + }; + let lobes: Vec = (0..240) + .map(|k| { + let t = TAU * f64::from(k) / 240.0; + Vec2::from_angle(t) * (28.0 + 2.0 / 3.0 + 13.0 * (3.0 * t).cos()) + }) + .collect(); + let e = arm_round(&lobes, Vec2::new(35.0, 0.0), 20.0).map_err(|e| e.to_string()).err().unwrap_or_default(); + assert!(e.contains("jump"), "{e}"); + assert!(arm_round(&circle(Vec2::new(10.0, 0.0), 30.0, 2048), Vec2::new(-50.0, 40.0), 50.0).is_ok()); + } + + /// The table is read between its samples by a periodic cubic: a cosine sampled once a degree + /// reads back within a millionth anywhere, a turn either way round included; nothing reads + /// from an empty table or at a non-finite angle. + #[test] + fn a_table_reads_smoothly_between_its_samples() { + let t: Vec = (0..CAM_SAMPLES).map(|k| (TAU * k as f64 / CAM_SAMPLES as f64).cos()).collect(); + for x in [0.0, 0.0123, 1.0, 3.1, -2.5, 6.2, 40.0, -1e5] { + assert!((lift_at(&t, x) - x.cos()).abs() < 1e-6, "{x}: {}", lift_at(&t, x)); + } + assert!(lift_at(&[], 1.0).is_nan() && lift_at(&t, f64::NAN).is_nan() && lift_at(&t, f64::INFINITY).is_nan()); + // A dwell up to a rise reads flat up to the rise: never below the dwell, nor past the rise. + let mut step = vec![30.0; CAM_SAMPLES]; + for (k, v) in step.iter_mut().enumerate().skip(100).take(60) { + *v = 30.0 + 0.9 * (k - 99) as f64; + } + for k in 0..36_000 { + let v = lift_at(&step, TAU * k as f64 / 36_000.0); + assert!((30.0 - 1e-12..=30.0 + 0.9 * 60.0 + 1e-12).contains(&v), "{k}: {v}"); + } + assert!(lift_at(&[2.0], 1e300).is_finite()); + } + + /// The guide is the side of the follower's joint fewer moving joints from the cam's frame: a + /// guide on four rigid joints from it beats a piston three moving joints round a slider-crank; + /// a guide only on the cam's own side is refused. + #[test] + fn the_guide_is_the_side_fewer_moving_joints_from_the_frame() { + let origin = JointOrigin { occurrence: 0, snap: super::super::Snap::Point { point: Vec3::ZERO, z: None } }; + let joint = |id: u64, kind: JointKind, a: u64, b: u64| super::super::Joint { + id, + name: format!("J{id}"), + kind, + a: JointOrigin { occurrence: a, ..origin.clone() }, + b: JointOrigin { occurrence: b, ..origin.clone() }, + values: Vec::new(), + limits: Vec::new(), + flip: false, + offset: 0.0, + angle: 0.0, + suppressed: false, + }; + let occ = |id: u64, grounded: bool| crate::Occurrence { id, component: id, parent: 0, name: format!("O{id}"), transform: IDENTITY, grounded }; + // 1 frame (grounded), 2 cam, 3-6 a rigid chain to the guide 7, 8 the piston, 9 crank, 10 rod. + let mut doc = Document { occurrences: (1..=10).map(|id| occ(id, id == 1)).collect(), ..Document::default() }; + let (r, v, s) = (JointKind::Rigid, JointKind::Revolute, JointKind::Slider); + doc.assembly.joints = vec![ + joint(1, v, 1, 2), + joint(2, r, 1, 3), + joint(3, r, 3, 4), + joint(4, r, 4, 5), + joint(5, r, 5, 7), + joint(6, s, 8, 7), + joint(7, v, 1, 9), + joint(8, v, 9, 10), + joint(9, v, 10, 8), + ]; + let (cam, fol) = (doc.assembly.joints[0].clone(), doc.assembly.joints[5].clone()); + // The piston (a) follows, the guide (b) stays. + assert!(matches!(follower_is_b(&doc, &cam, &fol, (1, 2)), Ok(false))); + // A guide joined only to the cam turns with it. + doc.assembly.joints[1] = joint(2, r, 2, 3); + doc.occurrences.iter_mut().for_each(|o| o.grounded = o.id == 2); + doc.assembly.joints.truncate(6); + assert!(follower_is_b(&doc, &cam, &fol, (1, 2)).is_err()); + } + + /// Edges join end to end either way round into one closed loop; a gap or a spare edge is no loop. + #[test] + fn edges_chain_into_one_closed_loop() { + let p = |x: f64, y: f64| Vec3::new(x, y, 0.0); + let (a, b, c) = (vec![p(0.0, 0.0), p(1.0, 0.0)], vec![p(0.0, 1.0), p(1.0, 0.0)], vec![p(0.0, 1.0), p(0.0, 0.0)]); + let loop3 = chain(&[&a, &b, &c], &[], 1e-9).unwrap_or_default(); + assert_eq!(loop3, vec![p(0.0, 0.0), p(1.0, 0.0), p(0.0, 1.0)]); + assert_eq!(chain(&[&a, &b], &[], 1e-9), None); + let d = vec![p(5.0, 5.0), p(6.0, 6.0)]; + assert_eq!(chain(&[&a, &b, &c, &d], &[], 1e-9), None); + let ring = vec![p(1.0, 0.0), p(0.0, 1.0), p(-1.0, 0.0), p(0.0, -1.0), p(1.0, 0.0)]; + assert_eq!(chain(&[&ring], &[], 1e-9).map(|l| l.len()), Some(4)); + // One pick goes on along the other edges of its plane; a spare pick still fails. + assert_eq!(chain(&[&a], &[&d, &c, &b], 1e-9).map(|l| l.len()), Some(3)); + assert_eq!(chain(&[&a, &d], &[&c, &b], 1e-9), None); + // A loop of many short edges goes round from one of them, found by their ends; past the + // point cap it is refused, without going on round it. + let ring = |n: usize| -> Vec> { + let at = |k: usize| Vec3::new((TAU * k as f64 / n as f64).cos(), (TAU * k as f64 / n as f64).sin(), 0.0) * 100.0; + (0..n).map(|k| vec![at(k), at(k + 1)]).collect() + }; + let small = ring(10_000); + let rest: Vec<&Vec> = small.iter().skip(1).rev().collect(); + assert_eq!(chain(&[&small[0]], &rest, 1e-6).map(|l| l.len()), Some(10_000)); + let big = ring(100_000); + let rest: Vec<&Vec> = big.iter().skip(1).collect(); + assert_eq!(chain(&[&big[0]], &rest, 1e-7), None); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index ae00b365d..285b7d3f9 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -58,9 +58,9 @@ pub use assembly::{ pub use document::*; pub use eval::{ EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SolvedSketch, ThreadInfo, curve_pick_error, edge_names_for, - edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, object_height, parse_metric_thread, pattern_matrices, - revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, state_in_frame, state_in_frame_at, - through_all_distance, world_state, world_state_reusing, + edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, metric_thread_sizes, object_height, parse_metric_thread, + pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, state_in_frame, + state_in_frame_at, suggested_thread, through_all_distance, world_state, world_state_reusing, }; pub use expr::Expr; pub use names::{BodyName, FeatureName, SketchId}; diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 89d54bfd5..3991dcb29 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -8,6 +8,10 @@ license.workspace = true [lints] workspace = true +[features] +default = [] +raytrace-cpu = ["solidcraft-render/raytrace-cpu"] + [dependencies] solidcraft-geom = { workspace = true } solidcraft-sketch = { workspace = true } diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index ffe5510fe..80a4c5ff5 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -214,10 +214,18 @@ fn rename(s: &mut Session, p: &Value) -> Result { let id = component(s, p, "component", cmd)?; let name = str_(p, "name").map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128).ok_or_else(|| bad(cmd, "`name` must be 1…128 characters"))?; + let d = s.doc_mut(); if id == 0 { - s.doc_mut().name = name.to_string(); - } else if let Some(c) = s.doc_mut().components.iter_mut().find(|c| c.id == id) { - c.name = name.to_string(); + d.name = name.to_string(); + } else if let Some(c) = d.components.iter_mut().find(|c| c.id == id) { + let old = std::mem::replace(&mut c.name, name.to_string()); + // Placements still named after the component ("Old:2") follow it (#1665); others keep theirs. + for o in d.occurrences.iter_mut().filter(|o| o.component == id) { + let k = o.name.strip_prefix(old.as_str()).and_then(|r| r.strip_prefix(':')); + if let Some(k) = k.filter(|k| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())) { + o.name = format!("{name}:{k}"); + } + } } Ok(json!({"component": id, "name": name})) } diff --git a/crates/engine/src/cmd/component_clone_assembly.rs b/crates/engine/src/cmd/component_clone_assembly.rs index 88a2f2c97..7cf3a027c 100644 --- a/crates/engine/src/cmd/component_clone_assembly.rs +++ b/crates/engine/src/cmd/component_clone_assembly.rs @@ -3,6 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use solidcraft_doc::Document; +use solidcraft_doc::joints::cam::CamProfile; use solidcraft_doc::joints::{Assembly, Coupling, JointOrigin, Size, Snap}; use crate::{EngineError, Result}; @@ -102,9 +103,31 @@ fn budget(assembly: &Assembly) -> Result<()> { return Err(invalid("exploded view contains non-finite moves")); } } - if !assembly.links.iter().all(|l| l.ratio.is_finite() && l.offset.is_finite()) { + if !assembly.links.iter().all(|l| l.ratio.is_finite() && l.offset.is_finite() && l.lift.iter().all(|v| v.is_finite())) { return Err(invalid("motion link contains non-finite values")); } + for cam in assembly.links.iter().filter_map(|l| match &l.coupling { + Some(Coupling::Cam(c)) => Some(c), + _ => None, + }) { + add_references(&mut references, cam.tip.iter().count())?; + if let Some(tip) = &cam.tip { + finite_origin(tip)?; + } + match &cam.profile { + CamProfile::Sketch { curves, .. } => { + add_references(&mut references, curves.len())?; + curves.iter().try_for_each(|c| text(c))?; + } + CamProfile::Edges { picks, names, .. } => { + add_references(&mut references, picks.len() + names.len())?; + if !picks.iter().all(|p| p.is_finite()) { + return Err(invalid("motion link contains non-finite values")); + } + names.iter().try_for_each(|n| text(n))?; + } + } + } for size in assembly.links.iter().filter_map(|l| l.coupling.as_ref()).flat_map(Coupling::sizes) { match size { Size::Length(v) if !v.is_finite() => return Err(invalid("motion link contains non-finite values")), @@ -300,12 +323,26 @@ pub(super) fn clone_assembly( continue; } let mut item = old.clone(); - // A gear's picked round faces are on occurrences of the copy too. + // A gear's picked round faces are on occurrences of the copy too, and so are a cam's + // profile and its follower's tip. let faces = item.coupling.as_mut().is_none_or(|c| { - c.sizes_mut().into_iter().all(|size| match size { + let sizes = c.sizes_mut().into_iter().all(|size| match size { Size::Circle(o) => origin(o, occurrences, features, bodies).map(|new| *o = new).is_some(), _ => true, - }) + }); + let Coupling::Cam(cam) = c else { return sizes }; + let tip = match &mut cam.tip { + Some(t) => origin(t, occurrences, features, bodies).map(|new| *t = new).is_some(), + None => true, + }; + let profile = match &mut cam.profile { + CamProfile::Sketch { sketch, .. } => features.get(sketch).map(|new| *sketch = *new).is_some(), + CamProfile::Edges { occurrence, names, .. } => { + occurrences.get(occurrence).map(|new| *occurrence = *new).is_some() + && names.iter_mut().all(|n| n.is_empty() || face_name(n, features, bodies).map(|new| *n = new).is_some()) + } + }; + sizes && tip && profile }); match (joints.get(&old.a), joints.get(&old.b)) { (Some(aa), Some(bb)) if faces => { diff --git a/crates/engine/src/cmd/component_clone_assembly_tests.rs b/crates/engine/src/cmd/component_clone_assembly_tests.rs index f9157eabe..63f110363 100644 --- a/crates/engine/src/cmd/component_clone_assembly_tests.rs +++ b/crates/engine/src/cmd/component_clone_assembly_tests.rs @@ -44,8 +44,8 @@ fn documents() -> (Document, Document) { NamedOrigin { name: "Outside".into(), origin: at(9) }, ]; source.assembly.links = vec![ - MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.3, coupling: None }, - MotionLink { a: 1, ia: 0, b: 3, ib: 0, ratio: 1.0, offset: 0.0, coupling: None }, + MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.3, coupling: None, lift: Vec::new() }, + MotionLink { a: 1, ia: 0, b: 3, ib: 0, ratio: 1.0, offset: 0.0, coupling: None, lift: Vec::new() }, ]; source.assembly.contact_sets = vec![ ContactSet { id: 1, name: "Internal contact".into(), occurrences: vec![1, 2], suppressed: true }, @@ -106,8 +106,8 @@ fn copied_gears_take_their_picked_faces_along() { let circle = |face: &str| Size::Circle(JointOrigin { occurrence: 1, snap: Snap::CircleCenter { pick: Vec3::X, face: Some(face.into()) } }); let gear = |ra| Coupling::Gear { ra, rb: Size::Length(5.0), internal: false, reverse: false }; source.assembly.links = vec![ - MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.0, coupling: Some(gear(circle("F1:side"))) }, - MotionLink { a: 2, ia: 0, b: 1, ib: 0, ratio: -0.5, offset: 0.0, coupling: Some(gear(circle("F99:side"))) }, + MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.0, coupling: Some(gear(circle("F1:side"))), lift: Vec::new() }, + MotionLink { a: 2, ia: 0, b: 1, ib: 0, ratio: -0.5, offset: 0.0, coupling: Some(gear(circle("F99:side"))), lift: Vec::new() }, ]; let mut destination = source.clone(); destination.occurrences.extend([101, 102].map(occurrence)); diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index fa07dd151..025b2c35b 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -55,7 +55,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "CREATE") .icon("hole") .key("H") - .params("position: [x,y,z] on a face | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); direction?: [x,y,z] (default: into the face, against its outward normal; one that leaves the face is mirrored into it; ignored with sketch points); diameter | thread (a tapped hole: the tap drill, major − pitch) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\" (cosmetic)"), + .params("position: [x,y,z] on a face (numbers, or length expressions the hole follows) | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); direction?: [x,y,z] (default: into the face, against its outward normal; one that leaves the face is mirrored into it; ignored with sketch points); diameter | thread (a tapped hole: the tap drill, major − pitch) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\" (cosmetic)"), CommandSpec::new("solid.pipe", "Pipe", pipe) .at("SOLID", "CREATE") .icon("pipe") @@ -79,7 +79,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.thread", "Thread", thread) .at("SOLID", "CREATE") .icon("thread") - .params("face: [x,y,z] on a cylindrical face; designation?: ISO metric (\"M8\", \"M8x1\"; default: the size that fits); length?: expr (default: the whole face). Cosmetic: the model is unchanged, model.threads lists it"), + .params("face: [x,y,z] on a cylindrical face; designation?: ISO metric (\"M8\", \"M8x1\"; default: the size that fits); length?: expr (default: the whole face); modeled?: bool (default false). Cosmetic: the model is unchanged, model.threads lists it. Modeled: cuts the thread profile into the body"), CommandSpec::new("solid.shell", "Shell", shell) .at("SOLID", "MODIFY") .icon("shell") @@ -1633,10 +1633,36 @@ fn hole(s: &mut Session, p: &Value) -> Result { { return Err(bad(cmd, format!("unknown thread `{t}` (ISO metric, like M6 or M6x0.75)"))); } - let position = match (&points, p.get("position").and_then(vec3)) { + // A position given as length expressions (#1678), say `["leg_h*0.4", "width/2", "t"]`: kept, + // so the hole follows the parameters; drilled where they evaluate now. + let at: Option = match p.get("position").and_then(Value::as_array) { + Some(a) if points.is_none() && a.len() == 3 && a.iter().any(Value::is_string) => { + let mut coords = Vec::with_capacity(3); + for v in a { + let e = match v { + Value::String(x) => x.trim().to_string(), + Value::Number(n) => n.to_string(), + _ => return Err(bad(cmd, "`position` must be [x, y, z]: numbers or length expressions")), + }; + check_expr(s, &e, Kind::Length, cmd, "position")?; + coords.push(solidcraft_doc::Expr::new(e)); + } + let [x, y, z]: [solidcraft_doc::Expr; 3] = coords.try_into().map_err(|_| bad(cmd, "`position` must be [x, y, z]"))?; + Some([x, y, z]) + } + _ => None, + }; + let at_value = match &at { + Some([x, y, z]) => { + let c = |e: &solidcraft_doc::Expr| s.doc.eval(e, Kind::Length).map_err(|e| bad(cmd, format!("`position`: {e}"))); + Some(Vec3::new(c(x)?, c(y)?, c(z)?)).filter(|v| v.is_finite()) + } + None => None, + }; + let position = match (&points, at_value.or_else(|| p.get("position").and_then(vec3))) { (Some((_, first, _)), None) => *first, (_, Some(x)) => x, - (None, None) => return Err(bad(cmd, "`position` must be [x, y, z] (or give `sketch` and `points`)")), + (None, None) => return Err(bad(cmd, "`position` must be [x, y, z], numbers or length expressions (or give `sketch` and `points`)")), }; let direction = match (p.get("direction").and_then(vec3), &points) { (None, Some((_, _, d))) => *d, @@ -1706,6 +1732,7 @@ fn hole(s: &mut Session, p: &Value) -> Result { &p, FeatureKind::Hole { position: FacePick(position), + at, direction: Dir(direction), diameter, depth, diff --git a/crates/engine/src/cmd/features_more.rs b/crates/engine/src/cmd/features_more.rs index 556a0319b..055b56c9f 100644 --- a/crates/engine/src/cmd/features_more.rs +++ b/crates/engine/src/cmd/features_more.rs @@ -161,6 +161,8 @@ fn emboss(s: &mut Session, p: &Value) -> Result { let at = solidcraft_doc::apply_point(&s.active_component_frame(), local); let state = s.world_state(); let mut candidates = Vec::new(); + // The nearest face off the point: (distance, body), for the error when none holds it. + let mut nearest: Option<(f64, &str)> = None; for body in &state.bodies { let definition = body.definition_name(); if !targets.is_empty() && !targets.iter().any(|n| n == definition || n == &body.name) { @@ -179,14 +181,30 @@ fn emboss(s: &mut Session, p: &Value) -> Result { inside.then_some(((at - a).dot(n).abs(), *face as usize)) }) .min_by(|a, b| a.0.total_cmp(&b.0)); - if let Some((distance, index)) = closest - && distance < (body.body.size() * 1e-3).max(1e-3) - { - candidates.push((body, index)); + match closest { + Some((distance, index)) if distance < (body.body.size() * 1e-3).max(1e-3) => candidates.push((body, index)), + Some((distance, _)) if nearest.is_none_or(|(d, _)| distance < d) => nearest = Some((distance, body.name.as_str())), + _ => {} } } - if candidates.len() != 1 { - return Err(bad(cmd, "`face` must identify exactly one target body surface")); + // #392: say what is wrong with the point, not only that it picks no single face. + let point = format!("[{}, {}, {}]", local.x, local.y, local.z); + match (candidates.as_slice(), nearest) { + ([], Some((d, body))) => { + return Err(bad( + cmd, + format!("`face` {point} lies on no face: the nearest, on `{body}`, is {d:.3} mm away; give a point on the face"), + )); + } + ([], None) => return Err(bad(cmd, format!("`face` {point} lies on no face of the target bodies"))), + ([_], _) => {} + (more, _) => { + let names: Vec<&str> = more.iter().map(|(b, _)| b.name.as_str()).collect(); + return Err(bad( + cmd, + format!("`face` {point} lies on faces of {} bodies ({}): name one in `targets`", names.len(), names.join(", ")), + )); + } } let (selected, index) = candidates.first().copied().ok_or_else(|| bad(cmd, "no target face"))?; let name = selected.definition_name(); diff --git a/crates/engine/src/cmd/features_more_tests.rs b/crates/engine/src/cmd/features_more_tests.rs index 7852fc00b..edcb2a6c0 100644 --- a/crates/engine/src/cmd/features_more_tests.rs +++ b/crates/engine/src/cmd/features_more_tests.rs @@ -92,6 +92,23 @@ fn emboss_and_deboss_on_a_face() { assert!(s.execute("solid.emboss", &json!({"sketch": "Logo", "depth": 1, "mode": "sideways"})).is_err()); } +#[test] +fn emboss_face_off_the_part_says_how_far() { + // #392: a point beside the face was refused with "`face` must identify exactly one target + // body surface", which didn't say the point was off the face. + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "A"})); + run(&mut s, "sketch.create", json!({"plane": {"face": [20, 15, 10]}, "name": "Logo"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [15, 15]})); + run(&mut s, "sketch.finish", json!({})); + let e = s.execute("solid.emboss", &json!({"sketch": "Logo", "depth": 1, "face": [20, 15, 11.25]})).unwrap_err().to_string(); + assert!(e.contains("[20, 15, 11.25] lies on no face: the nearest, on `A`, is 1.250 mm away"), "{e}"); + run(&mut s, "solid.box", json!({"length": 10, "width": 30, "height": 10, "corner": [40, 0, 0], "operation": "new_body", "body_name": "B"})); + let e = s.execute("solid.emboss", &json!({"sketch": "Logo", "depth": 1, "face": [40, 15, 5]})).unwrap_err().to_string(); + assert!(e.contains("lies on faces of 2 bodies (A, B): name one in `targets`"), "{e}"); + run(&mut s, "solid.emboss", json!({"sketch": "Logo", "depth": 1, "face": [20, 15, 10]})); +} + fn cylinder_badge() -> Session { let mut s = Session::default(); run(&mut s, "parameters.add", json!({"name":"badge_depth","expression":"1 mm"})); @@ -765,6 +782,60 @@ fn a_tapered_text_joins_a_block_on_its_face_or_hanging_over_its_edge() { } } +/// A tapered foot extruded 3 mm down from a part's bottom face and joined (#1534). Run on into +/// the part with their slope, sides that narrow the foot away from the face widened it past the +/// face: a box got a lip round its walls (0.16 mm wide, and nothing said), a cylinder's join found +/// no result, and sides that widen the foot met the face's edge there. A foot on the whole face is +/// sewn on along it; one drawn just inside the face's edge starts on it. Either way: the part plus +/// the frustum, and nothing beside the part's walls. +#[test] +fn a_tapered_foot_under_a_part_joins_as_drawn() { + // (round, the foot's half width: the whole face, or just inside its edge) + for (round, half) in [(false, 15.0), (true, 15.0), (false, 14.9)] { + for taper in [-20.0f64, 20.0] { + let t = taper.to_radians().tan(); + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane":"XY"})); + if round { + run(&mut s, "sketch.circle.center", json!({"center":[0,0],"radius":15})); + } else { + run(&mut s, "sketch.rectangle.two_point", json!({"p0":[-15,-15],"p1":[15,15]})); + } + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance":10,"body_name":"B"})); + let taper_deg = format!("{taper} deg"); + if half < 15.0 { + run(&mut s, "sketch.create", json!({"plane":"XY"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0":[-half,-half],"p1":[half,half]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance":3,"direction":"negative","operation":"join","taper":taper_deg})); + } else { + let foot = json!({"face":[5,1,0],"face_body":"B","distance":3,"direction":"positive","operation":"join","taper":taper_deg}); + run(&mut s, "solid.extrude", foot); + } + let (part, frustum) = if round { + let r = 15.0 + 3.0 * t; + (std::f64::consts::PI * 225.0 * 10.0, std::f64::consts::PI * (225.0 + 15.0 * r + r * r)) + } else { + let side = 2.0 * half + 6.0 * t; + (9000.0, 4.0 * half * half + 2.0 * half * side + side * side) + }; + let v = volume(&mut s); + // The cylinder is measured on its mesh; a foot that starts on the face stands straight + // for a hair first. + let tol = if round || half < 15.0 { 2e-4 } else { 1e-9 } * (part + frustum); + assert!((v - (part + frustum)).abs() < tol, "round {round}, half {half}, taper {taper}: {v} for {}", part + frustum); + assert_eq!(s.world_state().bodies.len(), 1); + let state = s.model.state(); + let mesh = state.body("B").unwrap().mesh(); + // Beside the part, above the foot's start: nothing. + let out = |x: f64, y: f64| if round { x.hypot(y) } else { x.abs().max(y.abs()) } > 15.0 + 1e-6; + let beside = mesh.positions.iter().filter(|p| p.z > 1e-6 && out(p.x, p.y)).count(); + assert_eq!(beside, 0, "round {round}, half {half}, taper {taper}: {:?}", mesh.bounds()); + } + } +} + /// A rounded part as drawn in the app: a rectangle and a quarter circle tangent to its top /// line, extruded together. The arc (about (62.17, -21), radius 21) ends square at the front /// face and in a knife-edge tip where it runs into the back face. diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 78147187f..354307422 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -278,6 +278,19 @@ fn default_name_for(name: &str, path: &str) -> Option { (!stem.is_empty()).then_some(stem) } +/// The name a design takes when saved to `path`, if it changes: its file's name while it has +/// none of its own ([`default_name_for`]), or while it still has the name it took from the file +/// it was saved as before, so Save As under another name renames it too (#1710). A name the +/// user chose is kept. +fn saved_name(name: &str, old_path: Option<&str>, path: &str) -> Option { + if let Some(stem) = default_name_for(name, path) { + return Some(stem); + } + let stem = |p: &str| std::path::Path::new(p).file_stem().map(|x| x.to_string_lossy().trim().to_string()).filter(|x| !x.is_empty()); + let (old, new) = (stem(old_path?)?, stem(path)?); + (name.trim() == old && new != old).then_some(new) +} + /// Rename the design, and the undo and redo states that still carry the old name, so undo /// does not bring the default name back and leave the design looking changed. fn rename_design(s: &mut Session, from: &str, to: &str) { @@ -291,8 +304,9 @@ 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) -> Result { solidcraft_io::vfs::check(path).map_err(|e| EngineError::Other(e.to_string()))?; - // Saving an unnamed design names it after its file (not an undoable edit). - let renamed = default_name_for(&s.doc.name, path).map(|stem| (s.doc.name.clone(), stem)); + // Saving an unnamed design, or one named after the file it was saved as, names it after its + // file (not an undoable edit). + let renamed = saved_name(&s.doc.name, s.path.as_deref(), path).map(|stem| (s.doc.name.clone(), stem)); if let Some((from, to)) = &renamed { rename_design(s, from, to); } @@ -883,9 +897,20 @@ mod tests { // Undoing the box does not bring the old name back. s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.doc.name, "bracket"); - // Saving under another file keeps the name it now has. - s.execute("file.save_as", &json!({"path":dir.join("copy.solidcraft")})).unwrap(); - assert_eq!(s.doc.name, "bracket"); + // Saved under another file, a name taken from the old file follows it (#1710), in the + // file too, so reopening shows it. + let copy = dir.join("copy.solidcraft"); + s.execute("file.save_as", &json!({"path":copy})).unwrap(); + assert_eq!(s.doc.name, "copy"); + let mut reopened = Session::default(); + reopened.execute("doc.open", &json!({"path":copy})).unwrap(); + assert_eq!(reopened.doc.name, "copy"); + // Saving again to the same file changes nothing. + s.execute("file.save", &json!({})).unwrap(); + assert_eq!(s.doc.name, "copy"); + // As in the issue: a design opened from its file, then saved as another. + reopened.execute("file.save_as", &json!({"path":dir.join("third.solidcraft")})).unwrap(); + assert_eq!(reopened.doc.name, "third"); // A failed save leaves the name alone. let mut failed = Session::default(); assert!(failed.execute("file.save_as", &json!({"path":dir.join("missing-dir").join("plate.solidcraft")})).is_err()); diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index 4b8fdbfe3..91b55ed3f 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -7,6 +7,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; use solidcraft_doc::expr::Kind; +use solidcraft_doc::joints::cam::{self, Cam, CamProfile, Follower}; use solidcraft_doc::joints::{self, Coupling, Joint, JointKind, JointOrigin, MotionLink, NamedOrigin, Size, Snap}; use solidcraft_geom::{Aabb3, Vec3}; @@ -60,6 +61,9 @@ pub static COMMANDS: &[CommandSpec] = &[ travel per turn (mm or an expression); reverse?: bool (a left-hand thread); link?: index (replace that motion link) → link, \ ratio (mm per degree, or degrees per mm); b keeps where it is", ), + CommandSpec::new("joint.cam", "Cam", cam_cmd).at("SOLID", "ASSEMBLE").icon("cam").params( + "a: the cam's joint (revolute); b: the follower's joint, a slider (a translating follower) or a revolute (an oscillating one), b driven by a; profile: {sketch: id|name, index?: the profile (default: the largest)} | {edges: [[x,y,z]…] (points on edges of the cam's bodies forming one closed loop, world), occurrence?}: the cam's outline, in a plane square to its axis, read again whenever the design changes; follower?: knife|roller|flat (default knife; flat: a face square to a slider's line); radius?: the roller's radius (mm, an expression or {circle: [x,y,z], occurrence?}: the roller's round face, which is its tip too); tip?: a joint origin where the follower touches: its knife's point or its roller's centre, such as {circle: [x,y,z]} on the roller (needed for an oscillating follower; a translating one's line runs through it, by default along its slider's axis); flip?: bool (ride the cam from the other side than the one the follower is on now); link?: index (replace that motion link) → link, lift: {min, max, rise, unit} (b's travel over a turn of the cam), reverse (the side it rides from), follower_offset (mm: how far a translating follower's line passes from the cam's axis); b keeps where it is", + ), CommandSpec::new("joint.limits", "Joint Limits", limits).params("joint; index?: value index (default 0); min?, max? (omit both to clear)"), CommandSpec::new("joint.edit", "Edit Joint", edit).params("joint; type?, flip?, offset?, angle?, suppressed?, name?"), CommandSpec::new("joint.delete", "Delete Joint", delete).params("joint: id|name (or origin: name, link: index)"), @@ -80,29 +84,30 @@ pub fn resolve(s: &mut Session) -> joints::Solution { resolve_holding(s, &BTreeMap::new()) } -/// Work out the ratios of the coupled motion links again (a radius or a parameter may have -/// changed). A coupling that can't be worked out (its face gone) keeps its last ratio; -/// `joint.list` says why. +/// Work out the ratios (and cam tables) of the coupled motion links again (a radius, a parameter +/// or a cam's profile may have changed). A coupling that can't be worked out (its face gone) +/// keeps its last ratio and table; `joint.list` says why. fn recouple(s: &mut Session) { if s.doc.assembly.links.iter().all(|l| l.coupling.is_none()) { return; } let st = s.model.state(); - let changed: Vec<(usize, f64)> = s + let changed: Vec<(usize, (f64, Vec))> = s .doc .assembly .links .iter() .enumerate() - .filter_map(|(i, l)| joints::coupling_ratio(&s.doc, &st, l)?.ok().filter(|r| *r != l.ratio).map(|r| (i, r))) + .filter_map(|(i, l)| joints::coupling_values(&s.doc, &st, l)?.ok().filter(|(r, t)| *r != l.ratio || *t != l.lift).map(|v| (i, v))) .collect(); if changed.is_empty() { return; } let doc = s.doc_mut(); - for (i, r) in changed { + for (i, (r, t)) in changed { if let Some(l) = doc.assembly.links.get_mut(i) { l.ratio = r; + l.lift = t; } } } @@ -305,8 +310,29 @@ fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result Ok(o), + // A circle given by its centre, where no face lies (#393). + Err(e) => match (what == "circle").then(|| circle_centre(s, occurrence, local(world))).flatten() { + Some(snap) => Ok(JointOrigin { occurrence, snap }), + None => Err(bad(cmd, e.to_string())), + }, + } +} + +/// The round end of a cylindrical face of the occurrence's bodies centred at `pick`: a point on +/// its axis there, pointing out of that end (as picking its circular edge gives). +fn circle_centre(s: &Session, occurrence: u64, pick: Vec3) -> Option { + let component = if occurrence == 0 { 0 } else { s.doc.occurrences.iter().find(|o| o.id == occurrence)?.component }; + let st = s.model.state(); + let c = st + .bodies + .iter() + .filter(|b| s.doc.model_body_component(b) == component) + .find_map(|b| solidcraft_doc::kernel::cylinder_end_at(&b.body, pick))?; + let along = (pick - c.axis_point).dot(c.axis); + let (at, dir) = if (along - c.start).abs() <= (c.end - along).abs() { (c.start, -1.0) } else { (c.end, 1.0) }; + Some(Snap::Point { point: c.axis_point + c.axis * at, z: Some(c.axis * dir) }) } pub(crate) fn joint_id(s: &Session, v: Option<&Value>, cmd: &str) -> Result { @@ -688,7 +714,7 @@ fn motion_link(s: &mut Session, p: &Value) -> Result { None => 0.0, }; let ratio = ratio * ratio_scale(s, a, ia, b, ib); - s.doc_mut().assembly.links.push(MotionLink { a, ia, b, ib, ratio, offset, coupling: None }); + s.doc_mut().assembly.links.push(MotionLink { a, ia, b, ib, ratio, offset, coupling: None, lift: Vec::new() }); let sol = resolve(s); Ok(sol_json(&sol, p)) } @@ -699,7 +725,10 @@ fn size_param(s: &Session, p: &Value, key: &str, cmd: &str) -> Result { match p.get(key) { Some(Value::Number(n)) => n.as_f64().map(Size::Length).ok_or_else(|| bad(cmd, format!("`{key}` must be a finite length"))), Some(Value::String(t)) if t.len() <= 1000 => Ok(Size::Expr(t.trim().to_string())), - Some(o @ Value::Object(m)) if m.contains_key("circle") => Ok(Size::Circle(origin_param(s, Some(o), cmd)?)), + Some(o @ Value::Object(m)) if m.contains_key("circle") => match origin_param(s, Some(o), cmd)? { + o @ JointOrigin { snap: Snap::CircleCenter { .. }, .. } => Ok(Size::Circle(o)), + _ => Err(bad(cmd, format!("`{key}`: give a point on the round face, not its centre"))), + }, _ => Err(bad(cmd, format!("`{key}` must be a length (mm or an expression) or a round face ({{circle: [x, y, z]}})"))), } } @@ -742,7 +771,7 @@ fn gear(s: &mut Session, p: &Value) -> Result { internal: bool_(p, "internal").unwrap_or(false), reverse: reverse(p), }; - couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c) }) + couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() }) } fn rack_pinion(s: &mut Session, p: &Value) -> Result { @@ -750,7 +779,7 @@ fn rack_pinion(s: &mut Session, p: &Value) -> Result { let (a, b) = joint_pair(s, p, cmd)?; let (ia, ib) = turn_and_travel(s, a, b, cmd)?; let c = Coupling::RackPinion { radius: size_param(s, p, "radius", cmd)?, reverse: reverse(p) }; - couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c) }) + couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() }) } fn screw(s: &mut Session, p: &Value) -> Result { @@ -770,7 +799,120 @@ fn screw(s: &mut Session, p: &Value) -> Result { } }; let c = Coupling::Screw { pitch: size_param(s, p, "pitch", cmd)?, reverse: reverse(p) }; - couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c) }) + couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() }) +} + +fn cam_cmd(s: &mut Session, p: &Value) -> Result { + let cmd = "joint.cam"; + let (a, b) = joint_pair(s, p, cmd)?; + let kind = |id: u64| s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.kind); + if kind(a) != Some(JointKind::Revolute) { + return Err(bad(cmd, "the cam (a) turns on a revolute joint")); + } + let oscillating = match kind(b) { + Some(JointKind::Slider) => false, + Some(JointKind::Revolute) => true, + _ => return Err(bad(cmd, "the follower (b) is a slider or a revolute joint")), + }; + let follower = match str_(p, "follower").unwrap_or("knife") { + "knife" => Follower::Knife, + "roller" => Follower::Roller { radius: size_param(s, p, "radius", cmd)? }, + "flat" => Follower::Flat, + _ => return Err(bad(cmd, "`follower` is knife, roller or flat")), + }; + if oscillating && p.get("tip").is_none() && !matches!(follower, Follower::Roller { radius: Size::Circle(_) }) { + return Err(bad(cmd, "an oscillating follower needs `tip`: its knife's point or its roller's centre ({circle: [x, y, z]} on the roller)")); + } + let tip = match p.get("tip") { + Some(v) => Some(origin_param(s, Some(v), cmd)?), + None => None, + }; + let mut c = Cam { profile: cam_profile(s, p, cmd)?, follower, tip, reverse: false }; + let probe = MotionLink { a, ia: 0, b, ib: 0, ratio: 1.0, offset: 0.0, coupling: None, lift: Vec::new() }; + let st = s.model.state(); + c.reverse = cam::default_reverse(&s.doc, &st, &probe, &c).map_err(|e| bad(cmd, e.to_string()))? != bool_(p, "flip").unwrap_or(false); + let offset = cam::follower_offset(&s.doc, &st, &probe, &c).map_err(|e| bad(cmd, e.to_string()))?; + let reverse = c.reverse; + let mut out = couple(s, p, cmd, MotionLink { coupling: Some(Coupling::Cam(c)), ..probe })?; + let index = out["link"].as_u64().and_then(|i| usize::try_from(i).ok()).unwrap_or(usize::MAX); + if let (Some(o), Some(l)) = (out.as_object_mut(), s.doc.assembly.links.get(index)) { + o.remove("ratio"); + o.insert("lift".into(), lift_json(l, oscillating)); + o.insert("reverse".into(), json!(reverse)); + if !oscillating { + o.insert("follower_offset".into(), json!(offset)); + } + } + Ok(out) +} + +/// A cam's follower travel over a turn of the cam: b's lowest and highest values and their +/// difference, in degrees (`angle`) or mm. +fn lift_json(l: &MotionLink, angle: bool) -> Value { + // A table that is not whole (a hand-edited file) moves nothing, and says so. + if l.lift.len() != cam::CAM_SAMPLES { + return Value::Null; + } + let unit = |v: f64| if angle { v.to_degrees() } else { v }; + let (lo, hi) = l.lift.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + let (lo, hi) = (unit(lo + l.offset), unit(hi + l.offset)); + json!({"min": lo, "max": hi, "rise": hi - lo, "unit": if angle { "deg" } else { "mm" }}) +} + +/// A cam's profile: a sketch's closed profile (kept by its outer loop's curve ids, so the sketch's +/// other profiles may change), or picked edges of the cam's bodies (kept in the component's +/// coordinates with the edges' names). +fn cam_profile(s: &Session, p: &Value, cmd: &str) -> Result { + let v = p.get("profile").ok_or_else(|| bad(cmd, "`profile` is required: {sketch: id|name} or {edges: [[x, y, z], …]}"))?; + if let Some(sk) = v.get("sketch") { + let sketch = super::features::sketch_id(s, Some(sk), cmd, "profile.sketch")?; + let st = s.model.state(); + let solved = + st.sketches.iter().find(|x| x.feature == sketch).ok_or_else(|| bad(cmd, "that sketch is not evaluated (it is after the marker?)"))?; + let picked = match v.get("index") { + None => cam::sketch_profile(solved, &[]), + Some(i) => i.as_u64().and_then(|i| usize::try_from(i).ok()).and_then(|i| solved.profiles.get(i)), + }; + let profile = picked.ok_or_else(|| bad(cmd, "the sketch has no such closed profile (an open curve makes none)"))?; + return Ok(CamProfile::Sketch { sketch, curves: profile.outer_curves.clone() }); + } + let Some(Value::Array(pts)) = v.get("edges") else { + return Err(bad(cmd, "`profile` is {sketch: id|name} or {edges: [[x, y, z], …]}")); + }; + if pts.is_empty() || pts.len() > cam::MAX_PROFILE_EDGES { + return Err(bad(cmd, format!("pick 1 to {} edges", cam::MAX_PROFILE_EDGES))); + } + let world: Vec = pts.iter().map(vec3).collect::>().ok_or_else(|| bad(cmd, "`edges` are finite [x, y, z] points"))?; + let occurrence = match v.get("occurrence") { + Some(o) => occurrence_id(s, Some(o), cmd)?, + None => world.first().and_then(|w| occurrence_at(s, *w)).ok_or_else(|| bad(cmd, "no body there"))?, + }; + let t = if occurrence == 0 { solidcraft_doc::IDENTITY } else { joints::occurrence_world(&s.doc, occurrence) }; + let inv = solidcraft_doc::mat_inverse(&t).ok_or_else(|| bad(cmd, "occurrence transform"))?; + let picks: Vec = world.iter().map(|w| solidcraft_doc::apply_point(&inv, *w)).collect(); + let comp = s.doc.occurrences.iter().find(|o| o.id == occurrence).map(|o| o.component).unwrap_or(0); + let st = s.model.state(); + let bodies: Vec<&solidcraft_doc::ModelBody> = st.bodies.iter().filter(|b| s.doc.model_body_component(b) == comp).collect(); + // Each pick's edge name on the body whose edges pass nearest it. + let names = picks + .iter() + .map(|q| { + let near = |b: &&solidcraft_doc::ModelBody| { + b.mesh() + .edges + .iter() + .flat_map(|e| e.windows(2)) + .filter_map(|w| Some(q.dist_to_segment(*w.first()?, *w.get(1)?))) + .fold(f64::MAX, f64::min) + }; + bodies + .iter() + .min_by(|x, y| near(x).total_cmp(&near(y))) + .and_then(|b| solidcraft_doc::naming::edge_names_at(b, &[*q]).into_iter().next()) + .unwrap_or_default() + }) + .collect(); + Ok(CamProfile::Edges { occurrence, picks, names }) } /// Add a coupling's motion link, or put it in place of link `link`: its ratio worked out from its @@ -802,14 +944,18 @@ fn couple(s: &mut Session, p: &Value, cmd: &str, mut l: MotionLink) -> Result break, } } - l.ratio = joints::coupling_ratio(&s.doc, &s.model.state(), &l).unwrap_or(Ok(l.ratio)).map_err(|e| bad(cmd, e.to_string()))?; + (l.ratio, l.lift) = + joints::coupling_values(&s.doc, &s.model.state(), &l).unwrap_or(Ok((l.ratio, Vec::new()))).map_err(|e| bad(cmd, e.to_string()))?; let vals = joints::joint_values(&s.doc.assembly); let value = |id: u64, i: usize| vals.get(&id).and_then(|q| q.get(i)).copied().unwrap_or(0.0); // A link put in place of another keeps its offset, as a radius edited in the design does. l.offset = match replace.and_then(|i| links.get(i)) { Some(old) => old.offset, - None => value(l.b, l.ib) - l.ratio * value(l.a, l.ia), + None => value(l.b, l.ib) - MotionLink { offset: 0.0, ..l.clone() }.follow(value(l.a, l.ia)), }; + if !l.offset.is_finite() { + return Err(bad(cmd, "the coupling gives the driven joint no value where it is")); + } let shown = l.ratio / ratio_scale(s, l.a, l.ia, l.b, l.ib); let doc = s.doc_mut(); let index = match replace { @@ -970,10 +1116,17 @@ fn list(s: &mut Session, p: &Value) -> Result { json!({"a": l.a, "ia": l.ia, "b": l.b, "ib": l.ib, "ratio": ratio, "offset": offset, "unit": if angle { "deg" } else { "mm" }}); if let Some(c) = &l.coupling { v["coupling"] = json!(c); - if let Some(Err(e)) = joints::coupling_ratio(&s.doc, &st, l) { + if let Some(Err(e)) = joints::coupling_values(&s.doc, &st, l) { v["error"] = json!(e.to_string()); } } + // A cam's follower follows its table, not a ratio: its travel instead. + if matches!(l.coupling, Some(Coupling::Cam(_))) + && let Some(o) = v.as_object_mut() + { + o.remove("ratio"); + o.insert("lift".into(), lift_json(l, angle)); + } v }) .collect(); diff --git a/crates/engine/src/cmd/joints_cam_tests.rs b/crates/engine/src/cmd/joints_cam_tests.rs new file mode 100644 index 000000000..3ed46a746 --- /dev/null +++ b/crates/engine/src/cmd/joints_cam_tests.rs @@ -0,0 +1,435 @@ +//! Cams: a revolute joint drives a follower that rides the cam's profile. Expected values are +//! analytic: an eccentric circle of radius R whose centre is e from its axis puts a knife-edge +//! follower on a line h from the axis at e·cos θ + √(R² − (h − e·sin θ)²), a roller of radius r +//! where a knife on the circle of radius R + r would be, a flat face at e·cos θ + R; an +//! oscillating follower's roller sits where its arm's circle meets the circle of radius R + r. + +use super::*; +use solidcraft_doc::joints::Coupling; +use solidcraft_doc::joints::cam::CamProfile; + +/// The cam's eccentricity and radius (mm). +const E: f64 = 10.0; +const R: f64 = 30.0; + +fn joint_id(s: &Session, name: &str) -> u64 { + s.doc.assembly.joints.iter().find(|j| j.name == name).map(|j| j.id).unwrap_or(0) +} + +/// A joint's value as `joint.list` gives it (degrees or mm). +fn shown(s: &mut Session, joint: &str) -> f64 { + let l = run(s, "joint.list", json!({"quiet": true})); + let j = l["joints"].as_array().into_iter().flatten().find(|j| j["name"] == joint).cloned().unwrap_or_default(); + j["values"][0]["value"].as_f64().unwrap_or(f64::NAN) +} + +/// Where a knife edge on a line `h` from the axis stands on the circle of radius `r` about the +/// cam's centre turned by `deg`. +fn knife(deg: f64, h: f64, r: f64) -> f64 { + let t = deg.to_radians(); + E * t.cos() + (r * r - (h - E * t.sin()).powi(2)).sqrt() +} + +/// A grounded base, and a cam: a disc of radius `rc` (a parameter, 30 mm) about (10, 0), 5 mm thick, +/// drawn in sketch `CamSketch` of its own component, on a revolute joint `Cam` about Z through the +/// origin (the cam is its b side). +fn cam_on_base() -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "rc", "expression": "30 mm"})); + run(&mut s, "parameters.add", json!({"name": "th", "expression": "5 mm"})); + part(&mut s, "Base", [-90.0, -90.0, -20.0]); + let g = occ(&s, "Base"); + run(&mut s, "occurrence.ground", json!({"occurrence": g, "grounded": true})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Cam"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "CamSketch"})); + run(&mut s, "sketch.circle.center", json!({"center": [E, 0], "radius": R, "id": "c1"})); + run(&mut s, "sketch.dimension", json!({"entities": ["c1"], "type": "radius", "value": "rc"})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": "th"})); + pin(&mut s, "revolute", "Cam", "Base", "Cam", Vec3::ZERO, Vec3::Z); + s +} + +/// A tappet (a 20 mm bar, 4 wide) sliding along +X on the line y = `h`, its end at x = `tip`, on a +/// slider `Tappet`. +fn tappet(s: &mut Session, h: f64, tip: f64) { + run(s, "component.activate", json!({"component": "root"})); + run(s, "component.create", json!({"name": "Tappet"})); + run(s, "solid.box", json!({"length": 20, "width": 4, "height": 5, "corner": [tip, h - 2.0, 0]})); + pin(s, "slider", "Tappet", "Base", "Tappet", Vec3::new(0.0, h, 2.5), Vec3::X); +} + +fn close(got: f64, want: f64, tol: f64) -> bool { + (got - want).abs() < tol +} + +/// A knife-edge tappet on the eccentric circle, its line through the axis and 6 mm past it, rises +/// and falls as e·cos θ + √(R² − (h − e·sin θ)²); the tappet's body goes with it. +#[test] +fn a_knife_edge_tappet_rides_an_eccentric_circle() { + for h in [0.0, 6.0] { + let mut s = cam_on_base(); + let tip = knife(0.0, h, R); + tappet(&mut s, h, tip); + let r = run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}})); + assert_eq!((r["link"].clone(), r["reverse"].clone()), (json!(0), json!(false)), "{r}"); + assert!(close(r["follower_offset"].as_f64().unwrap_or(f64::NAN), h, 1e-9), "{r}"); + // It stays where it is, and its travel over a turn is the cam's. + assert!(close(shown(&mut s, "Tappet"), 0.0, 1e-9), "{r}"); + let over_a_turn: Vec = (0..3600).map(|k| knife(f64::from(k) / 10.0, h, R)).collect(); + let rise = over_a_turn.iter().fold(f64::MIN, |a, b| a.max(*b)) - over_a_turn.iter().fold(f64::MAX, |a, b| a.min(*b)); + assert!(close(r["lift"]["rise"].as_f64().unwrap_or(f64::NAN), rise, 2e-3), "{r} vs {rise}"); + for deg in [30.0f64, 90.0, 135.0, 200.0, 300.0, -45.0, 400.0] { + let d = run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg})); + assert_eq!(d["conflicts"].as_array().map(Vec::len), Some(0), "{d}"); + let want = knife(deg, h, R) - tip; + assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "h {h} θ {deg}: {} vs {want}", shown(&mut s, "Tappet")); + let end = place(&s, "Tappet", Vec3::new(tip, h, 2.5)); + assert!(close(end.x, tip + want, 1e-3) && close(end.y, h, 1e-9), "{end:?}"); + } + } +} + +/// The follower's line is through its tip, wherever its slider's origin is across the line; a +/// guide of its own (grounded, the slider's b side) makes the tappet the slider's a side, and it +/// rides the same way. +#[test] +fn a_tappet_on_a_guide_of_its_own_rides_its_tip_s_line() { + let h = 6.0; + let tip = knife(0.0, h, R); + let mut s = cam_on_base(); + part(&mut s, "Guide", [70.0, 20.0, 0.0]); + let g = occ(&s, "Guide"); + run(&mut s, "occurrence.ground", json!({"occurrence": g, "grounded": true})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Tappet"})); + run(&mut s, "solid.box", json!({"length": 20, "width": 4, "height": 5, "corner": [tip, h - 2.0, 0]})); + // The slider's origins 9 mm across from the tappet's line, a the tappet, b the guide. + pin(&mut s, "slider", "Tappet", "Tappet", "Guide", Vec3::new(0.0, h + 9.0, 2.5), Vec3::X); + let r = run( + &mut s, + "joint.cam", + json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "tip": {"occurrence": "Tappet", "point": [tip, h, 2.5]}}), + ); + assert!(close(r["follower_offset"].as_f64().unwrap_or(f64::NAN), h, 1e-9), "{r}"); + for deg in [70.0f64, 160.0, 290.0] { + run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg})); + let end = place(&s, "Tappet", Vec3::new(tip, h, 2.5)); + assert!(close(end.x, knife(deg, h, R), 1e-3), "θ {deg}: {end:?} vs {}", knife(deg, h, R)); + } +} + +/// A roller of radius 5 rides the circle of radius R + 5; a flat face e·cos θ + R, and when the +/// cam's radius parameter grows by 2 the flat face stands 2 further out at every angle. +#[test] +fn rollers_and_flat_faces_ride_their_offset_circles() { + let mut s = cam_on_base(); + let tip = knife(0.0, 0.0, R + 5.0); + tappet(&mut s, 0.0, tip); + run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": "5 mm"})); + for deg in [60.0f64, 150.0, 250.0] { + run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg})); + let want = knife(deg, 0.0, R + 5.0) - tip; + assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "roller θ {deg}: {} vs {want}", shown(&mut s, "Tappet")); + } + let mut s = cam_on_base(); + tappet(&mut s, 3.0, E + R); + run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "flat"})); + for deg in [60.0f64, 150.0, 250.0] { + run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg})); + let want = E * deg.to_radians().cos() - E; + assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "flat θ {deg}: {} vs {want}", shown(&mut s, "Tappet")); + } + // Editing the profile: the table is worked out again. + run(&mut s, "parameters.change", json!({"name": "rc", "expression": "32 mm"})); + let want = E * 250f64.to_radians().cos() - E + 2.0; + assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "after the edit: {} vs {want}", shown(&mut s, "Tappet")); +} + +/// The cam's top edge picked on its body gives the table its sketch gives, and follows the +/// design the same way. +#[test] +fn picked_edges_give_the_sketch_s_table() { + let table = |profile: Value| { + let mut s = cam_on_base(); + tappet(&mut s, 0.0, E + R); + run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": profile})); + s.doc.assembly.links.first().map(|l| (l.lift.clone(), l.offset)).unwrap_or_default() + }; + let (sketch, a) = table(json!({"sketch": "CamSketch"})); + let (edges, b) = table(json!({"edges": [[E + R, 0, 5]]})); + assert_eq!((sketch.len(), edges.len()), (360, 360)); + assert!(sketch.iter().zip(&edges).all(|(x, y)| close(*x, *y, 1e-3)) && close(a, b, 1e-3)); + // A second disc of the cam's component touching it in the same plane is not part of its loop. + let mut s = cam_on_base(); + run(&mut s, "component.activate", json!({"component": "Cam"})); + run(&mut s, "solid.cylinder", json!({"base": [E + R + 20.0, 0, 0], "axis": [0, 0, 1], "radius": 20, "height": 5})); + tappet(&mut s, 0.0, E + R); + run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[E - R, 0, 5]]}})); + let touching = s.doc.assembly.links.first().map(|l| l.lift.clone()).unwrap_or_default(); + assert!(touching.len() == 360 && touching.iter().zip(&sketch).all(|(x, y)| close(*x, *y, 1e-3)), "{touching:?}"); + let mut s = cam_on_base(); + tappet(&mut s, 0.0, E + R); + run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[E + R, 0, 5]]}})); + assert!(matches!( + s.doc.assembly.links.first().and_then(|l| l.coupling.clone()), + Some(Coupling::Cam(c)) if matches!(&c.profile, CamProfile::Edges { names, .. } if names.first().is_some_and(|n| !n.is_empty())) + )); + run(&mut s, "parameters.change", json!({"name": "rc", "expression": "32 mm"})); + // A thicker cam: the picked edge is found at its new height, and its loop with it. + run(&mut s, "parameters.change", json!({"name": "th", "expression": "7 mm"})); + let l = run(&mut s, "joint.list", json!({"quiet": true})); + assert!(l["links"][0].get("error").is_none(), "{l}"); + run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 90})); + let want = knife(90.0, 0.0, 32.0) - (E + R); + assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "{} vs {want}", shown(&mut s, "Tappet")); +} + +/// An arm of 50 about (−50, 40) with a roller of 5: its roller's centre is where the arm's circle +/// meets the circle of radius R + 5 about the cam's centre, the meeting it turns into first from +/// pointing away from the cam's axis. +#[test] +fn an_oscillating_roller_follower_swings_to_the_offset_circle() { + let (pivot, arm, roller) = (Vec3::new(-50.0, 40.0, 2.5), 50.0, 5.0); + let away = pivot.y.atan2(pivot.x); + let wrap = |a: f64| (a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI; + let angle = |p: Vec3| (p.y - pivot.y).atan2(p.x - pivot.x); + // Where the roller's centre is at cam angle `deg`, turning the way `turn` says. + let centre = |deg: f64, turn: f64| { + let c = Vec3::new(E * deg.to_radians().cos(), E * deg.to_radians().sin(), 2.5); + let [p, q] = meet(pivot, arm, c, R + roller); + let swept = |x: Vec3| (turn * (angle(x) - away)).rem_euclid(std::f64::consts::TAU); + if swept(p) < swept(q) { p } else { q } + }; + let [p, q] = meet(pivot, arm, Vec3::new(E, 0.0, 2.5), R + roller); + let start = if wrap(angle(p) - away).abs() < wrap(angle(q) - away).abs() { p } else { q }; + let turn = wrap(angle(start) - away).signum(); + let mut s = cam_on_base(); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Arm"})); + run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 5, "corner": [start.x - 2.0, start.y - 2.0, 0]})); + pin(&mut s, "revolute", "Arm", "Base", "Arm", pivot, Vec3::Z); + // An oscillating follower needs its tip. + assert!(s.execute("joint.cam", &json!({"a": "Cam", "b": "Arm", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": 5})).is_err()); + let r = run( + &mut s, + "joint.cam", + json!({"a": "Cam", "b": "Arm", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": 5, + "tip": {"occurrence": "Arm", "point": [start.x, start.y, 2.5]}}), + ); + assert_eq!((r["reverse"].clone(), r["lift"]["unit"].clone()), (json!(turn < 0.0), json!("deg")), "{r}"); + for deg in [40.0f64, 120.0, 210.0, 330.0] { + run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg})); + let want = wrap(angle(centre(deg, turn)) - angle(start)).to_degrees(); + assert!(close(shown(&mut s, "Arm"), want, 1e-3), "θ {deg}: {} vs {want}", shown(&mut s, "Arm")); + let at = place(&s, "Arm", start); + assert!(at.dist(centre(deg, turn)) < 1e-3, "θ {deg}: {at:?}"); + } + // The roller's round face picked on its arm is where it touches, and its radius: the same table. + let table = s.doc.assembly.links.first().map(|l| l.lift.clone()).unwrap_or_default(); + let mut t = cam_on_base(); + run(&mut t, "component.activate", json!({"component": "root"})); + run(&mut t, "component.create", json!({"name": "Arm"})); + run(&mut t, "solid.cylinder", json!({"base": [start.x, start.y, 0], "axis": [0, 0, 1], "radius": roller, "height": 5})); + pin(&mut t, "revolute", "Arm", "Base", "Arm", pivot, Vec3::Z); + let face = [start.x + roller, start.y, 2.5]; + run( + &mut t, + "joint.cam", + json!({"a": "Cam", "b": "Arm", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": {"occurrence": "Arm", "circle": face}}), + ); + let picked = t.doc.assembly.links.first().map(|l| l.lift.clone()).unwrap_or_default(); + assert!(picked.len() == 360 && picked.iter().zip(&table).all(|(x, y)| close(*x, *y, 1e-6))); +} + +/// A stationary cam: the profile on the grounded part, a rotor turning about it with the tappet's +/// guide on it. Turned by +θ against the cam, the tappet stands where it would on a cam turned by +/// −θ. A guide on the cam's own (grounded) side would turn with the profile: refused. +#[test] +fn a_stationary_cam_drives_a_follower_on_a_turning_rotor() { + let h = 6.0; + let tip = knife(0.0, h, R); + let mut s = cam_on_base(); + // The cam is the fixed part: ground it, and take the base off its joint. + let (cam, base) = (occ(&s, "Cam"), occ(&s, "Base")); + run(&mut s, "joint.delete", json!({"joint": "Cam"})); + run(&mut s, "occurrence.ground", json!({"occurrence": cam, "grounded": true})); + run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": false})); + pin(&mut s, "revolute", "Turret", "Cam", "Base", Vec3::ZERO, Vec3::Z); + tappet(&mut s, h, tip); + run(&mut s, "joint.cam", json!({"a": "Turret", "b": "Tappet", "profile": {"sketch": "CamSketch"}})); + for deg in [50.0f64, 140.0, 260.0] { + let d = run(&mut s, "joint.drive", json!({"joint": "Turret", "value": deg})); + assert_eq!(d["conflicts"].as_array().map(Vec::len), Some(0), "{d}"); + let want = knife(-deg, h, R) - tip; + assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "θ {deg}: {} vs {want}", shown(&mut s, "Tappet")); + } + let mut s = cam_on_base(); + let (cam, base) = (occ(&s, "Cam"), occ(&s, "Base")); + run(&mut s, "joint.delete", json!({"joint": "Cam"})); + run(&mut s, "occurrence.ground", json!({"occurrence": cam, "grounded": true})); + run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": false})); + part(&mut s, "Rotor", [-90.0, 60.0, -20.0]); + pin(&mut s, "revolute", "Turret", "Cam", "Rotor", Vec3::ZERO, Vec3::Z); + run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true})); + tappet(&mut s, h, tip); + let e = s.execute("joint.cam", &json!({"a": "Turret", "b": "Tappet", "profile": {"sketch": "CamSketch"}})).map_err(|e| e.to_string()).err(); + assert!(e.as_deref().is_some_and(|e| e.contains("turns with the cam")), "{e:?}"); +} + +/// A motion study turning the cam plays the tappet through its analytic travel. +#[test] +fn a_cam_plays_in_a_motion_study() { + let mut s = cam_on_base(); + let tip = knife(0.0, 0.0, R); + tappet(&mut s, 0.0, tip); + run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}})); + run(&mut s, "motion.study", json!({"name": "Turn", "steps": 10, "keys": [{"joint": "Cam", "points": [[0, 0], [10, 360]]}]})); + for step in [0, 2, 5, 7, 10] { + run(&mut s, "motion.play", json!({"study": "Turn", "step": step})); + let want = knife(36.0 * f64::from(step), 0.0, R) - tip; + assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "step {step}: {} vs {want}", shown(&mut s, "Tappet")); + } +} + +/// The tappet is the piston of a slider-crank: a 40 mm rod from its end to a 20 mm crank about +/// (95, 0). Turning the cam moves the tappet, and the loop turns the crank to where the rod's +/// circle meets the crank's, on the branch it started on. A stop in a contact set with the cam and +/// the tappet halts the cam where the tappet reaches it; the cam and the flat tappet only touch. +#[test] +fn a_cam_drives_a_closed_loop_and_stops_at_a_contact() { + let mut s = cam_on_base(); + let tip = knife(0.0, 0.0, R); + tappet(&mut s, 0.0, tip); + let (q, end) = (Vec3::new(95.0, 0.0, 2.5), Vec3::new(tip + 20.0, 0.0, 2.5)); + let crank_pin = |x: f64| meet(q, 20.0, Vec3::new(x, 0.0, 2.5), 40.0).into_iter().find(|p| p.y > 0.0).unwrap_or(Vec3::ZERO); + let pin0 = crank_pin(end.x); + for (name, at) in [("Rod", end), ("Crank", pin0)] { + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": name})); + run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [at.x - 1.0, at.y - 1.0, 10]})); + } + pin(&mut s, "revolute", "Crank", "Base", "Crank", q, Vec3::Z); + pin(&mut s, "revolute", "Wrist", "Tappet", "Rod", end, Vec3::Z); + pin(&mut s, "revolute", "Big end", "Rod", "Crank", pin0, Vec3::Z); + run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}})); + for deg in [45.0f64, 120.0, 180.0] { + let d = run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg})); + assert_eq!(d["conflicts"].as_array().map(Vec::len), Some(0), "{d}"); + let x = end.x + knife(deg, 0.0, R) - tip; + let at = place(&s, "Crank", pin0); + assert!(at.dist(crank_pin(x)) < 1e-3, "θ {deg}: {at:?} vs {:?}", crank_pin(x)); + } + // A flat tappet, a stop 5 mm past where its end is at the top, and contact on. + let mut s = cam_on_base(); + tappet(&mut s, 0.0, E + R); + run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "flat"})); + run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 180})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Stop"})); + run(&mut s, "solid.box", json!({"length": 3, "width": 4, "height": 5, "corner": [E + R + 15.0, -2, 0]})); + let st = occ(&s, "Stop"); + run(&mut s, "occurrence.ground", json!({"occurrence": st, "grounded": true})); + run(&mut s, "contact.create", json!({"occurrences": ["Cam", "Tappet", "Stop"]})); + // Touching the cam stops nothing: half a turn moves the tappet 20 mm back up, as far as the stop. + let d = run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 90})); + assert!(d["stopped_by_contact"].is_null(), "{d}"); + let d = run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 0})); + assert!(d["stopped_by_contact"].is_object(), "{d}"); + let reached = shown(&mut s, "Tappet"); + assert!(reached > -5.5 && reached < -4.5, "{reached}"); +} + +/// What a cam can't be made from is refused, and a table edited by hand never puts a NaN into a +/// joint's value. +#[test] +fn hostile_cams_are_refused() { + let mut s = cam_on_base(); + tappet(&mut s, 0.0, E + R); + let refused = |s: &mut Session, p: Value| s.execute("joint.cam", &p).map_err(|e| e.to_string()).err().unwrap_or_else(|| panic!("accepted {p}")); + // An open curve makes no closed profile. + run(&mut s, "component.activate", json!({"component": "Cam"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Open"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [20, 5], [10, 20]]})); + run(&mut s, "sketch.finish", json!({})); + let e = refused(&mut s, json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "Open"}})); + assert!(e.contains("closed profile"), "{e}"); + // Two closed edges are not one loop; a line past the cam misses it. + let e = refused(&mut s, json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[E + R, 0, 5], [E + R, 0, 0]]}})); + assert!(e.contains("closed loop"), "{e}"); + let mut far = cam_on_base(); + tappet(&mut far, 50.0, 0.0); + let e = refused(&mut far, json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}})); + assert!(e.contains("misses"), "{e}"); + for p in [ + json!({"a": "Tappet", "b": "Cam", "profile": {"sketch": "CamSketch"}}), + json!({"a": "Cam", "b": "Cam", "profile": {"sketch": "CamSketch"}}), + json!({"a": "Cam", "b": "Tappet"}), + json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch", "index": 7}}), + json!({"a": "Cam", "b": "Tappet", "profile": {"edges": []}}), + json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[1, "x", 0]]}}), + json!({"a": "Cam", "b": "Tappet", "profile": {"edges": vec![[E + R, 0.0, 5.0]; 65]}}), + json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller"}), + json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": -1}), + json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": "nope"}), + json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": 1e300}), + json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "spring"}), + json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "link": 3}), + ] { + refused(&mut s, p); + } + assert!(s.doc.assembly.links.is_empty()); + // A table edited by hand: NaN leaves the follower where it is, any length reads. + run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}})); + let before = solidcraft_doc::joints::joint_values(&s.doc.assembly); + for lift in [vec![f64::NAN; 360], vec![1.0, 2.0, 3.0], vec![f64::INFINITY]] { + let mut d = (*s.doc).clone(); + if let Some(l) = d.assembly.links.first_mut() { + l.lift = lift; + } + let vals = solidcraft_doc::joints::joint_values(&d.assembly); + assert!(vals.values().flatten().all(|v| v.is_finite()), "{vals:?}"); + // The follower keeps where it is. + assert_eq!(vals.get(&joint_id(&s, "Tappet")), d.assembly.joints.iter().find(|j| j.name == "Tappet").map(|j| &j.values), "{before:?}"); + } + // A table on a plain link is not read. + let mut d = (*s.doc).clone(); + if let Some(l) = d.assembly.links.first_mut() { + (l.coupling, l.ratio, l.offset) = (None, 0.0, 3.0); + } + assert_eq!(solidcraft_doc::joints::joint_values(&d.assembly).get(&joint_id(&s, "Tappet")).and_then(|q| q.first()).copied(), Some(3.0)); + // A roller's picked face must turn about an axis parallel to the cam's, a tip given or not. + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Pin"})); + run(&mut s, "solid.cylinder", json!({"base": [60, 30, 0], "axis": [1, 0, 0], "radius": 3, "height": 10})); + run(&mut s, "joint.delete", json!({"link": 0})); + let tilted = json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", + "radius": {"occurrence": "Pin", "circle": [65, 33, 0]}, "tip": {"occurrence": "Tappet", "point": [E + R, 0, 2.5]}}); + let e = refused(&mut s, tilted); + assert!(e.contains("roller's axis"), "{e}"); +} + +/// A cam saves and opens with its definition and table; a link saved before cams reads as a +/// plain link. +#[test] +fn cams_save_and_open_with_their_table() { + let mut s = cam_on_base(); + tappet(&mut s, 0.0, E + R); + run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": 2})); + run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 30})); + let text = s.doc.to_json(); + let back = solidcraft_doc::format::read(&text).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(back.assembly.links, s.doc.assembly.links); + assert_eq!(back.assembly.links.first().map(|l| l.lift.len()), Some(360)); + let l = run(&mut s, "joint.list", json!({})); + let link = &l["links"][0]; + assert!(link.get("ratio").is_none() && link["lift"]["unit"] == "mm" && link["coupling"]["type"] == "cam", "{link}"); + assert!(link["coupling"].get("lift").is_none(), "{link}"); + let mut v: Value = serde_json::from_str(&text).unwrap_or_default(); + for l in v["assembly"]["links"].as_array_mut().into_iter().flatten() { + l.as_object_mut().map(|o| (o.remove("coupling"), o.remove("lift"))); + } + let old = solidcraft_doc::format::read(&v.to_string()).unwrap_or_else(|e| panic!("{e}")); + assert!(old.assembly.links.iter().all(|l| l.coupling.is_none() && l.lift.is_empty())); +} diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rs index e86571f8f..d02a803c5 100644 --- a/crates/engine/src/cmd/joints_tests.rs +++ b/crates/engine/src/cmd/joints_tests.rs @@ -34,6 +34,40 @@ fn leaf(s: &mut Session, name: &str) { run(s, "solid.cylinder", json!({"base": [0, 33, 4], "axis": [1, 0, 0], "radius": 4, "height": 40, "operation": "new"})); } +#[test] +fn circle_given_by_its_centre_takes_that_round_end() { + // #393: `circle` at the centre of a round end, as the parameters document, was refused with + // "no cylindrical face there" (no face lies at a centre). + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name": "Plate"})); + run(&mut s, "solid.box", json!({"length": 30, "width": 20, "height": 6, "corner": [-15, -10, 0]})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": "Knob"})); + run(&mut s, "solid.cylinder", json!({"base": [0, 0, 6], "axis": [0, 0, 1], "radius": 10, "height": 10, "operation": "new"})); + let r = run( + &mut s, + "joint.create", + json!({"type": "cylindrical", "a": {"occurrence": "Plate", "face": [0, 0, 6]}, "b": {"occurrence": "Knob", "circle": [0, 0, 6]}, "name": "J"}), + ); + assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}"); + // The knob's bottom circle already sits on the plate's top: its axis stays put (it may turn + // about it, to line up the two frames' x). + for z in [6.0, 16.0] { + assert!(near(place(&s, "Knob", Vec3::new(0.0, 0.0, z)), Vec3::new(0.0, 0.0, z)), "{:?}", place(&s, "Knob", Vec3::new(0.0, 0.0, z))); + } + // The top end's centre: its axis points up, out of the knob. + run(&mut s, "joint.origin", json!({"occurrence": "Knob", "circle": [0, 0, 16], "name": "Top"})); + let top = s.doc.assembly.origins.iter().find(|o| o.name == "Top").map(|o| o.origin.snap.clone()); + assert!( + matches!(top, Some(solidcraft_doc::joints::Snap::Point { point, z: Some(z) }) if near(point, Vec3::new(0.0, 0.0, 16.0)) && near(z, Vec3::Z)), + "{top:?}" + ); + // Off the axis is still refused, and so is a coupling size (it follows a face). + assert!(s.execute("joint.origin", &json!({"occurrence": "Knob", "circle": [3, 0, 6]})).is_err()); + let e = s.execute("joint.screw", &json!({"joint": "J", "pitch": {"occurrence": "Knob", "circle": [0, 0, 6]}})).unwrap_err(); + assert!(e.to_string().contains("not its centre"), "{e}"); +} + #[test] fn revolute_hinge_turns_about_the_knuckle() { let mut s = Session::default(); @@ -1411,3 +1445,6 @@ fn hostile_trace_params_are_refused() { #[path = "joints_coupling_tests.rs"] mod coupling; + +#[path = "joints_cam_tests.rs"] +mod cam; diff --git a/crates/engine/src/cmd/lineage_face_tests.rs b/crates/engine/src/cmd/lineage_face_tests.rs index 70224f98d..680dfb1fd 100644 --- a/crates/engine/src/cmd/lineage_face_tests.rs +++ b/crates/engine/src/cmd/lineage_face_tests.rs @@ -326,3 +326,76 @@ fn every_flat_face_of_an_elbow_up_and_an_elbow_down_takes_a_sketch() { ); every_flat_face_takes_a_sketch(&mut s); } + +/// #565: Split Body by a plane a parameter moves (a raw plane, a construction plane or a sketch +/// line). The face the split cuts on each part is named after the half-space that cut it +/// (`F:section`): a sketch and an offset plane attach to it and follow the plane. +#[test] +fn the_face_a_split_cuts_takes_a_sketch_and_an_offset_plane_that_follow_the_plane() { + for tool in ["plane", "construction", "line"] { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "split_x", "expression": "15 mm"})); + run(&mut s, "solid.box", json!({"length": 40, "width": 20, "height": 10, "body_name": "Block"})); + let split = match tool { + "plane" => json!({"body": "Block", "plane": {"origin": ["split_x", 0, 0], "normal": [1, 0, 0]}}), + "construction" => { + run(&mut s, "construct.plane.offset", json!({"base": "YZ", "offset": "split_x", "name": "Cut"})); + json!({"body": "Block", "plane": "Cut"}) + } + _ => { + let id = run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Guide"}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.line", json!({"points": [[15, -10], [15, 30]], "ids": ["cut"], "connect": false})); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "cut", "mode": "vertical"})); + run(&mut s, "sketch.dimension", json!({"entities": ["origin", "cut.start"], "type": "horizontal", "value": "split_x"})); + run(&mut s, "sketch.finish", json!({})); + json!({"body": "Block", "sketch": id, "line": "cut"}) + } + }; + run(&mut s, "solid.split_body", split); + no_errors(&s); + // Each part's cut face (the two lie on one another, so each is picked by body and index). + let cut_face = |s: &Session, body: &str, x: f64| { + let state = s.model.state(); + let b = &state.body(body).unwrap().body; + let index = (0..b.face_count()) + .find(|i| b.planar_face(*i).is_some_and(|p| p.normal().x.abs() > 0.999 && (p.origin.x - x).abs() < 1e-9)) + .unwrap_or_else(|| panic!("{tool}: no cut face on `{body}`")); + json!({"face": [x, 10, 5], "body": body, "index": index}) + }; + let mut normals = Vec::new(); + for (k, body) in ["Block", "Block (1)"].into_iter().enumerate() { + let pick = cut_face(&s, body, 15.); + run(&mut s, "sketch.create", json!({"plane": pick, "name": format!("OnCut{k}")})); + run(&mut s, "sketch.finish", json!({})); + let (plane, certificate) = healthy(&s, &format!("OnCut{k}")); + assert_eq!(certificate, Some(FaceCertificate::Lineage), "{tool} {body}"); + assert!((plane.origin.x - 15.).abs() < 1e-9 && plane.normal().x.abs() > 0.999, "{tool} {body}: {plane:?}"); + normals.push(plane.normal().x); + let pick = cut_face(&s, body, 15.); + run(&mut s, "construct.plane.offset", json!({"base": pick, "offset": 2, "name": format!("Off{k}")})); + } + assert!(normals[0] * normals[1] < 0., "{tool}: the two cut faces face each other's way: {normals:?}"); + no_errors(&s); + + run(&mut s, "parameters.change", json!({"name": "split_x", "expression": "20 mm"})); + no_errors(&s); + let offset = |s: &Session, name: &str| { + let feature = s.doc.find_feature(name).map(|f| f.id).unwrap(); + let state = s.model.state(); + match state.construct.iter().find(|c| c.feature == feature).map(|c| &c.geom) { + Some(solidcraft_doc::construct::ConstructGeom::Plane(p)) => *p, + other => panic!("{tool} {name}: {other:?}"), + } + }; + for (k, n) in normals.iter().enumerate() { + let (plane, _) = healthy(&s, &format!("OnCut{k}")); + assert!((plane.origin.x - 20.).abs() < 1e-9 && (plane.normal().x - n).abs() < 1e-9, "{tool} OnCut{k}: {plane:?}"); + let off = offset(&s, &format!("Off{k}")); + assert!((off.origin.x - (20. + 2. * n)).abs() < 1e-9, "{tool} Off{k}: {off:?}"); + } + let t = reopened(&s); + for k in 0..2 { + assert!((healthy(&t, &format!("OnCut{k}")).0.origin.x - 20.).abs() < 1e-9, "{tool} reopened OnCut{k}"); + } + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 348838098..e7380d9d2 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -74,6 +74,7 @@ mod sketch_modify; mod sketch_project; mod surface; mod surface_analysis; +mod surface_boundary; mod surface_match; mod view_dxf; mod view_navigation; @@ -236,6 +237,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(sketch_canvas::COMMANDS.iter()); v.extend(sketch_3d::COMMANDS.iter()); v.extend(surface_analysis::COMMANDS.iter()); + v.extend(surface_boundary::COMMANDS.iter()); v.extend(surface::COMMANDS.iter()); v.extend(surface_match::COMMANDS.iter()); v.extend(sketch_modify::COMMANDS.iter()); diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs index 2e5759119..cc42c1511 100644 --- a/crates/engine/src/cmd/motion.rs +++ b/crates/engine/src/cmd/motion.rs @@ -14,6 +14,8 @@ use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, reso use crate::params::{bad, bool_, str_, vec3}; use crate::{EngineError, Result, Session}; +#[path = "motion_animation.rs"] +mod animation; #[path = "contact_sweep.rs"] mod contact_sweep; @@ -54,6 +56,9 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("motion.export", "Export Motion Study", export) .noundo() .params("study; samples? (default steps + 1); path? (.json or .csv) → occurrence positions per step (the design is not changed)"), + CommandSpec::new("motion.export_animation", "Export Motion Animation", animation::export).noundo().params( + "study: id|name, or joint: id|name with from and to (degrees for angles, mm for distances, or expressions) and index?; path: a .gif file, or a folder for PNG frames (frame-0001.png, frame-0002.png, …); samples? (frames, 2…1000; default the study's steps + 1, or 100); width?, height? (16…4096 pixels, default 800 × 500); camera?: {target, yaw, pitch, roll?, distance, fov?, up?} (ui.camera's reply; fields left out keep the default view: view.apply's camera, or the home view framing the model); fps? (1…50, default 20); grid?, axes? (default true: the ground grid and the origin's axes) - draws the study as it plays, or the joint as it is driven, with the headless renderer → path, format, frames, width, height, fps (GIF), bytes, renderer, stopped_at, stopped_by_loop, stopped_by_contact (the design is not changed)", + ), CommandSpec::new("motion.trace", "Motion Trace", trace).at("SOLID", "ASSEMBLE").icon("trace").noundo().params(concat!( trace_doc!(), " → points: [[x,y,z]…] world positions, samples (taken), stopped_at (the sample where the motion stopped short; the trace \ @@ -718,19 +723,45 @@ fn sample_trace(s: &Session, p: &Value, cmd: &str) -> Result<(Vec, Value)> let local = solidcraft_doc::mat_inverse(&world(&t)?) .map(|m| solidcraft_doc::apply_point(&m, at)) .ok_or_else(|| bad(cmd, "the occurrence's placement is not invertible"))?; - let samples = |default: usize| match p.get("samples") { + let (default, given, plan) = motion_plan(s, p, cmd)?; + let n = sample_count(p, default.min(MAX_TRACE), MAX_TRACE, cmd)?; + let mut points = Vec::new(); + let mut stop = (Value::Null, Value::Null, Value::Null); + for k in 0..n { + let want = plan(&t, k, n); + let (r, _) = drive_with_contact(&mut t, &want, &given)?; + points.push(solidcraft_doc::apply_point(&world(&t)?, local)); + if r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object() { + stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone()); + break; + } + } + let name = s.doc.occurrences.iter().find(|o| Some(&o.id) == path.last()).map_or_else(|| "root".to_string(), |o| o.name.clone()); + let out = json!({"occurrence": name, "samples": points.len(), "stopped_at": stop.0, "stopped_by_loop": stop.1, "stopped_by_contact": stop.2}); + Ok((points, out)) +} + +/// `samples`, 2…`max`, or `default` without it. +fn sample_count(p: &Value, default: usize, max: usize, cmd: &str) -> Result { + match p.get("samples") { Some(v) => v .as_f64() - .filter(|n| n.is_finite() && *n >= 2.0 && *n <= MAX_TRACE as f64) + .filter(|n| n.is_finite() && *n >= 2.0 && *n <= max as f64) .map(|n| n.round() as usize) - .ok_or_else(|| bad(cmd, format!("`samples` must be 2…{MAX_TRACE}"))), - None => Ok(default), - }; - let (n, given, plan): (usize, BTreeSet<(u64, usize)>, Plan) = match (p.get("study"), p.get("joint")) { + .ok_or_else(|| bad(cmd, format!("`samples` must be 2…{max}"))), + None => Ok(default.max(2)), + } +} + +/// The motion a trace or an animation samples: a study played from start to end, or one joint +/// value driven from `from` to `to`. Returns the default sample count (the study's steps + 1, or +/// 100), the values driven and what they are at sample `k` of `n`. +fn motion_plan(s: &Session, p: &Value, cmd: &str) -> Result<(usize, BTreeSet<(u64, usize)>, Plan)> { + Ok(match (p.get("study"), p.get("joint")) { (Some(_), Some(_)) => return Err(bad(cmd, "give `study` or `joint`, not both")), (Some(_), None) => { let m = s.doc.assembly.studies.get(study_index(s, p, cmd)?).cloned().ok_or_else(|| bad(cmd, "study"))?; - let n = samples((m.steps as usize).saturating_add(1).clamp(2, MAX_TRACE))?; + let n = (m.steps as usize).saturating_add(1); (n, keyed(&m), Box::new(move |t, k, n| values_at(t, &m, f64::from(m.steps) * k as f64 / (n - 1) as f64))) } (None, Some(j)) => { @@ -750,7 +781,7 @@ fn sample_trace(s: &Session, p: &Value, cmd: &str) -> Result<(Vec, Value)> }; let end = |key: &str| match p.get(key) { Some(v) => value(s, v, kind.is_angle(index), cmd), - None => Err(bad(cmd, format!("give `from` and `to`: the joint's values the trace runs between (no `{key}`)"))), + None => Err(bad(cmd, format!("give `from` and `to`: the joint's values the motion runs between (no `{key}`)"))), }; let (from, to) = (end("from")?, end("to")?); let plan: Plan = Box::new(move |t, k, n| { @@ -761,24 +792,10 @@ fn sample_trace(s: &Session, p: &Value, cmd: &str) -> Result<(Vec, Value)> } vec![(id, q)] }); - (samples(100)?, BTreeSet::from([(id, index)]), plan) + (100, BTreeSet::from([(id, index)]), plan) } (None, None) => return Err(bad(cmd, "give a `study`, or a `joint` with `from` and `to`")), - }; - let mut points = Vec::new(); - let mut stop = (Value::Null, Value::Null, Value::Null); - for k in 0..n { - let want = plan(&t, k, n); - let (r, _) = drive_with_contact(&mut t, &want, &given)?; - points.push(solidcraft_doc::apply_point(&world(&t)?, local)); - if r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object() { - stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone()); - break; - } - } - let name = s.doc.occurrences.iter().find(|o| Some(&o.id) == path.last()).map_or_else(|| "root".to_string(), |o| o.name.clone()); - let out = json!({"occurrence": name, "samples": points.len(), "stopped_at": stop.0, "stopped_by_loop": stop.1, "stopped_by_contact": stop.2}); - Ok((points, out)) + }) } fn trace(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/motion_animation.rs b/crates/engine/src/cmd/motion_animation.rs new file mode 100644 index 000000000..53bd07951 --- /dev/null +++ b/crates/engine/src/cmd/motion_animation.rs @@ -0,0 +1,154 @@ +//! Motion animations (`motion.export_animation`): a study played, or one joint driven, drawn +//! frame by frame by the headless renderer the host installed ([`crate::capture`]) and written as +//! an animated GIF or a folder of PNG frames. Sampled on a copy, as a trace is: the design is not +//! changed. + +use serde_json::{Value, json}; + +use super::{drive_with_contact, motion_plan, sample_count}; +use crate::capture::{self, Renderer}; +use crate::params::{bad, str_}; +use crate::render::Camera; +use crate::{Result, Session}; + +/// Most frames of one animation. +const MAX_FRAMES: usize = 1000; +/// Largest frame side, in pixels. +const MAX_SIDE: u32 = 4096; +/// Most pixels of a GIF's frames together: they are held in memory (4 bytes each) until the +/// palette is chosen, so 256 MB at most. +const MAX_GIF_PIXELS: usize = 1 << 26; +/// Most pixels of a PNG folder's frames together (each frame is written as it is drawn): about +/// 500 frames of 1920 × 1080. +const MAX_PNG_PIXELS: usize = 1 << 30; +/// The camera fields `camera` may set: those of `ui.camera`'s reply. +const FIELDS: [&str; 7] = ["target", "yaw", "pitch", "roll", "distance", "fov", "up"]; + +pub(super) fn export(s: &mut Session, p: &Value) -> Result { + export_with(s, p, capture::installed().as_deref()) +} + +/// [`export`] drawn by `renderer`. +pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) -> Result { + let cmd = "motion.export_animation"; + let path = str_(p, "path") + .filter(|x| !x.trim().is_empty() && x.len() <= 4096 && !x.chars().any(char::is_control)) + .ok_or_else(|| bad(cmd, "`path` must name a .gif file, or a folder for PNG frames"))?; + let lower = path.to_ascii_lowercase(); + if lower.ends_with(".png") { + return Err(bad(cmd, "`path` is a .gif file or a folder for the PNG frames (frame-0001.png, …), not one .png")); + } + let gif = lower.ends_with(".gif"); + // In the browser written files stay in memory until the host takes them, and the host is not + // told of removed ones: a folder of frames would pile up there. + if !gif && cfg!(target_arch = "wasm32") { + return Err(bad(cmd, "a folder of PNG frames is not available in the browser: give a .gif path")); + } + let side = |key: &str, default: u32| match p.get(key) { + None => Ok(default), + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && (16.0..=f64::from(MAX_SIDE)).contains(n)) + .map(|n| n.round() as u32) + .ok_or_else(|| bad(cmd, format!("`{key}` must be 16…{MAX_SIDE} pixels"))), + }; + let (width, height) = (side("width", 800)?, side("height", 500)?); + let fps = match p.get("fps") { + None => 20.0, + Some(v) => v.as_f64().filter(|n| n.is_finite() && (1.0..=50.0).contains(n)).ok_or_else(|| bad(cmd, "`fps` must be 1…50"))?, + }; + let cam = camera(s, p.get("camera"), cmd)?; + let shown = |key: &str| match p.get(key) { + None => Ok(true), + Some(Value::Bool(b)) => Ok(*b), + Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))), + }; + let guides = crate::view::Guides { grid: shown("grid")?, axes: shown("axes")? }; + let (default, given, plan) = motion_plan(s, p, cmd)?; + // At least 4 frames fit even at the largest size. + let max = MAX_FRAMES.min(if gif { MAX_GIF_PIXELS } else { MAX_PNG_PIXELS } / (width as usize * height as usize)); + let n = sample_count(p, default.min(max), max, cmd).map_err(|_| bad(cmd, format!("`samples` must be 2…{max} for {width} × {height} frames")))?; + let renderer = renderer.ok_or_else(|| bad(cmd, "no renderer is installed to draw pictures in this process"))?; + // A destination outside an agent's folders is refused before anything is drawn. + let io = |e: std::io::Error| bad(cmd, format!("{path}: {e}")); + solidcraft_io::vfs::check(path).map_err(io)?; + let frame_path = |k: usize| std::path::Path::new(path).join(format!("frame-{k:04}.png")).to_string_lossy().to_string(); + if !gif { + solidcraft_io::vfs::create_dir_all(path).map_err(io)?; + // The frames of an earlier export here go first, so the folder never mixes two + // animations: not after a shorter one, nor when this one fails part way. + for stale in (1..=MAX_FRAMES).map(frame_path).filter(|f| solidcraft_io::vfs::exists(f)) { + solidcraft_io::vfs::remove(&stale).map_err(|e| bad(cmd, format!("{stale}: {e}")))?; + } + } + let mut t = s.scratch(); + // From where the parts are placed: moves only shown (an exploded view, the pose an open + // Motion Study dialog shows) are not where the joints are solved. + t.pending_moves.clear(); + let (mut frames, mut bytes, mut drawn_by) = (Vec::new(), 0, ""); + let mut stop = (Value::Null, Value::Null, Value::Null); + for k in 0..n { + let want = plan(&t, k, n); + let (r, _) = drive_with_contact(&mut t, &want, &given)?; + if stop.0.is_null() && (r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object()) { + stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone()); + } + let scene = crate::view::scene_with_guides(&t, &cam, s.section, guides); + let picture = capture::rgba_with(Some(renderer), &scene, &cam, width, height).map_err(|e| bad(cmd, e))?; + drawn_by = picture.renderer; + if gif { + frames.push(picture.rgba); + } else { + let png = crate::render::png(width as usize, height as usize, picture.rgba).ok_or_else(|| bad(cmd, "PNG encoding failed"))?; + let file = frame_path(k + 1); + solidcraft_io::vfs::write(&file, &png).map_err(|e| bad(cmd, format!("{file}: {e}")))?; + bytes += png.len(); + } + } + let mut out = json!({"path": path, "format": if gif { "gif" } else { "png" }, "frames": n, "width": width, "height": height}); + if gif { + // GIF counts in hundredths of a second, and viewers slow anything under 2 down. + let delay = (100.0 / fps).round().clamp(2.0, 100.0) as u16; + let gif = crate::render::gif(width as usize, height as usize, &frames, delay).ok_or_else(|| bad(cmd, "GIF encoding failed"))?; + solidcraft_io::write_atomic(std::path::Path::new(path), &gif, false).map_err(io)?; + bytes = gif.len(); + out["fps"] = json!(100.0 / f64::from(delay)); + } + out["bytes"] = json!(bytes); + out["renderer"] = json!(drawn_by); + if let Some(w) = capture::warning(drawn_by) { + out["warning"] = json!(w); + } + out["stopped_at"] = stop.0; + out["stopped_by_loop"] = stop.1; + out["stopped_by_contact"] = stop.2; + Ok(out) +} + +/// The camera the frames are drawn from: the session's (`view.apply`), or the home view framing +/// the model, with the fields `given` sets (`ui.camera`'s reply sets them all). +fn camera(s: &Session, given: Option<&Value>, cmd: &str) -> Result { + let base = s.camera.unwrap_or_else(|| crate::view::home_camera(s)); + let Some(given) = given else { return Ok(base) }; + let fields = given.as_object().ok_or_else(|| bad(cmd, "`camera` must be an object, such as ui.camera's reply"))?; + let mut v = serde_json::to_value(base).map_err(|e| bad(cmd, e.to_string()))?; + for (k, x) in fields { + if !FIELDS.contains(&k.as_str()) { + return Err(bad(cmd, format!("unknown camera field `{k}` (it takes {})", FIELDS.join(", ")))); + } + if let Some(o) = v.as_object_mut() { + o.insert(k.clone(), x.clone()); + } + } + let mut cam: Camera = serde_json::from_value(v).map_err(|e| bad(cmd, format!("bad camera: {e}")))?; + if !cam.is_valid() || cam.distance > 1e15 || cam.pitch.abs() > std::f64::consts::FRAC_PI_2 || !(0.0..3.0).contains(&cam.fov) { + return Err(bad( + cmd, + "the camera must be finite, with a distance up to 1e15 mm, a pitch within ±π/2 and a fov of 0 (orthographic) to 3 radians", + )); + } + // Straight up or down keeps a heading, as ui.camera does. + let lim = std::f64::consts::FRAC_PI_2 - 1e-6; + cam.pitch = cam.pitch.clamp(-lim, lim); + Ok(cam) +} diff --git a/crates/engine/src/cmd/motion_tests.rs b/crates/engine/src/cmd/motion_tests.rs index 6ee3215ad..44974d82b 100644 --- a/crates/engine/src/cmd/motion_tests.rs +++ b/crates/engine/src/cmd/motion_tests.rs @@ -173,3 +173,235 @@ fn exploded_views_show_without_changing_the_design() { ); assert_eq!(run(&mut s, "explode.list", json!({}))["views"].as_array().map(Vec::len), Some(2)); } + +/// Pictures drawn by the CPU rasterizer (the engine has no GPU): real views of the scene. +fn cpu(scene: &crate::render::Scene, cam: &crate::render::Camera, w: u32, h: u32) -> Result { + Ok(crate::capture::Picture { rgba: crate::render::render(scene, cam, w as usize, h as usize).rgba, renderer: "cpu" }) +} + +/// A folder of its own for one test's files. +fn out_dir(test: &str) -> std::path::PathBuf { + let dir = solidcraft_io::vfs::temp_dir().join(format!("solidcraft-anim-{test}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A GIF's logical screen size and the number of its frames (image descriptors). +fn gif_frames(gif: &[u8]) -> (usize, usize, usize) { + let u16_at = |i: usize| usize::from(u16::from_le_bytes([gif[i], gif[i + 1]])); + assert_eq!(&gif[..6], b"GIF89a"); + let mut at = 13 + if gif[10] & 0x80 != 0 { 3 << ((gif[10] & 7) + 1) } else { 0 }; + let mut frames = 0; + // Each block: a size byte and that many bytes, up to a 0. + let skip_blocks = |mut at: usize| { + while gif[at] != 0 { + at += usize::from(gif[at]) + 1; + } + at + 1 + }; + loop { + match gif[at] { + 0x3B => return (u16_at(6), u16_at(8), frames), + 0x21 => at = skip_blocks(at + 2), + 0x2C => { + frames += 1; + at = skip_blocks(at + 11); + } + b => panic!("unexpected GIF block {b:#x}"), + } + } +} + +/// A PNG's width and height (its IHDR). +fn png_size(png: &[u8]) -> (u32, u32) { + let be = |i: usize| u32::from_be_bytes([png[i], png[i + 1], png[i + 2], png[i + 3]]); + (be(16), be(20)) +} + +#[test] +fn an_animation_has_the_frames_and_the_size_asked_for() { + let mut s = rail(); + run(&mut s, "motion.study", json!({"name": "Push", "steps": 10, "keys": [{"joint": "Rail", "points": [[0, 10], [10, 0]]}]})); + let dir = out_dir("size"); + let before = s.doc.clone(); + let gif = dir.join("push.gif"); + let p = json!({"study": "Push", "path": gif.to_string_lossy(), "samples": 6, "width": 64, "height": 40, "fps": 25}); + let r = super::animation::export_with(&s, &p, Some(&cpu)).unwrap(); + assert_eq!( + (r["format"].as_str(), r["frames"].as_u64(), r["width"].as_u64(), r["height"].as_u64()), + (Some("gif"), Some(6), Some(64), Some(40)), + "{r}" + ); + assert_eq!(r["fps"], 25.0, "{r}"); + let bytes = std::fs::read(&gif).unwrap(); + assert_eq!(r["bytes"].as_u64(), Some(bytes.len() as u64)); + assert_eq!(gif_frames(&bytes), (64, 40, 6)); + // Without samples: the study's steps + 1. + let r = + super::animation::export_with(&s, &json!({"study": "Push", "path": gif.to_string_lossy(), "width": 32, "height": 32}), Some(&cpu)).unwrap(); + assert_eq!(gif_frames(&std::fs::read(&gif).unwrap()), (32, 32, 11), "{r}"); + // A folder of PNG frames, made where missing; a joint driven instead of a study. + let frames = dir.join("frames").join("rail"); + let p = json!({"joint": "Rail", "from": 10, "to": 0, "path": frames.to_string_lossy(), "samples": 3, "width": 48, "height": 30}); + let r = super::animation::export_with(&s, &p, Some(&cpu)).unwrap(); + assert_eq!((r["format"].as_str(), r["frames"].as_u64()), (Some("png"), Some(3)), "{r}"); + let mut names: Vec = std::fs::read_dir(&frames).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect(); + names.sort(); + assert_eq!(names, ["frame-0001.png", "frame-0002.png", "frame-0003.png"]); + assert!(names.iter().all(|n| png_size(&std::fs::read(frames.join(n)).unwrap()) == (48, 30))); + // A shorter export into the same folder leaves no frames of a longer one behind, past a gap + // too; other files stay. + std::fs::write(frames.join("notes.txt"), "mine").unwrap(); + std::fs::write(frames.join("frame-0005.png"), "older").unwrap(); + super::animation::export_with(&s, &json!({"joint": "Rail", "from": 10, "to": 0, "path": frames.to_string_lossy(), "samples": 2}), Some(&cpu)) + .unwrap(); + let mut names: Vec = std::fs::read_dir(&frames).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect(); + names.sort(); + assert_eq!(names, ["frame-0001.png", "frame-0002.png", "notes.txt"]); + assert_eq!(*s.doc, *before, "the design is not changed"); + // Through the registry, with the renderer the host installed. + crate::capture::install_test_renderer(); + let r = run(&mut s, "motion.export_animation", json!({"study": "Push", "path": gif.to_string_lossy(), "samples": 2, "width": 16, "height": 16})); + assert_eq!(r["frames"], 2, "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_two_frame_drive_gives_two_different_frames() { + let s = rail(); + let dir = out_dir("two"); + let frames = |name: &str, to: f64| { + let folder = dir.join(name); + let p = json!({"joint": "Rail", "from": 10, "to": to, "path": folder.to_string_lossy(), "samples": 2, "width": 120, "height": 80}); + super::animation::export_with(&s, &p, Some(&cpu)).unwrap(); + (std::fs::read(folder.join("frame-0001.png")).unwrap(), std::fs::read(folder.join("frame-0002.png")).unwrap()) + }; + let (a, b) = frames("moved", -5.0); + assert_ne!(a, b, "B moved 15 mm between the frames"); + // Held still, the two frames are the same picture: the difference is the motion. + let (c, d) = frames("still", 10.0); + assert_eq!(c, d); + assert_eq!(a, c, "both start at 10 mm"); + // Without the ground grid and the axes, the same pose is another picture. + let bare = dir.join("bare"); + let p = json!({"joint": "Rail", "from": 10, "to": 10, "path": bare.to_string_lossy(), "samples": 2, "width": 120, "height": 80, "grid": false, "axes": false}); + super::animation::export_with(&s, &p, Some(&cpu)).unwrap(); + assert_ne!(std::fs::read(bare.join("frame-0001.png")).unwrap(), c); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_animation_is_drawn_from_the_camera_given() { + let mut s = rail(); + let dir = out_dir("camera"); + // A renderer is 'static (hosts install it for the process): it shares what it saw. + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let record = { + let seen = seen.clone(); + move |scene: &crate::render::Scene, cam: &crate::render::Camera, w: u32, h: u32| { + seen.lock().unwrap().push(*cam); + cpu(scene, cam, w, h) + } + }; + let path = dir.join("cam.gif"); + let base = json!({"joint": "Rail", "from": 10, "to": 0, "path": path.to_string_lossy(), "samples": 3, "width": 40, "height": 30}); + let with = |camera: Value| { + let mut p = base.clone(); + p["camera"] = camera; + p + }; + // ui.camera's reply, every field. + let reply = json!({"target": [1.0, 2.0, 3.0], "yaw": 0.5, "pitch": -0.25, "roll": 0.1, "distance": 300.0, "fov": 0.6, "up": "y"}); + super::animation::export_with(&s, &with(reply.clone()), Some(&record)).unwrap(); + let cams = std::mem::take(&mut *seen.lock().unwrap()); + assert_eq!(cams.len(), 3); + assert!(cams.iter().all(|c| json!(c) == reply), "{cams:?}"); + // Fields left out keep the default view: view.apply's camera. + run(&mut s, "view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 1, "pitch": 0.2, "distance": 80}})); + super::animation::export_with(&s, &with(json!({"yaw": 2.0})), Some(&record)).unwrap(); + let cams = std::mem::take(&mut *seen.lock().unwrap()); + assert!(cams.iter().all(|c| c.yaw == 2.0 && c.pitch == 0.2 && c.distance == 80.0), "{cams:?}"); + // Without one: view.apply's camera as it is; and another camera draws another picture. + super::animation::export_with(&s, &base, Some(&record)).unwrap(); + assert!(seen.lock().unwrap().iter().all(|c| Some(*c) == s.camera)); + let pictures = |camera: Value| { + let folder = dir.join(format!("p{}", camera["yaw"])); + let mut p = with(camera); + p["path"] = json!(folder.to_string_lossy()); + super::animation::export_with(&s, &p, Some(&cpu)).unwrap(); + std::fs::read(folder.join("frame-0001.png")).unwrap() + }; + assert_ne!(pictures(json!({"yaw": 0.3})), pictures(json!({"yaw": 1.3}))); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn hostile_animation_params_are_refused() { + let mut s = rail(); + run(&mut s, "motion.study", json!({"name": "Push", "steps": 10, "keys": [{"joint": "Rail", "points": [[0, 10], [10, 0]]}]})); + let dir = out_dir("hostile"); + let gif = dir.join("x.gif").to_string_lossy().to_string(); + let base = json!({"study": "Push", "path": gif, "samples": 2, "width": 16, "height": 16}); + let refused = |change: Value| { + let mut p = base.clone(); + if let (Some(p), Some(change)) = (p.as_object_mut(), change.as_object()) { + for (k, v) in change { + if v.is_null() { + p.remove(k); + } else { + p.insert(k.clone(), v.clone()); + } + } + } + super::animation::export_with(&s, &p, Some(&cpu)).err().map(|e| e.to_string()) + }; + for change in [ + json!({"samples": 0}), + json!({"samples": 1}), + json!({"samples": 1e9}), + json!({"samples": "many"}), + json!({"samples": 1001}), + json!({"width": 1e9}), + json!({"width": -16}), + json!({"height": 3}), + json!({"height": f64::MAX}), + json!({"fps": 0}), + json!({"fps": 1e9}), + json!({"path": ""}), + json!({"path": null}), + json!({"path": "one.png"}), + json!({"path": "a\u{0}b.gif"}), + json!({"path": "x".repeat(5000)}), + json!({"camera": "iso"}), + json!({"camera": {"distance": -1}}), + json!({"camera": {"distance": 1e300}}), + json!({"camera": {"pitch": 4}}), + json!({"camera": {"fov": 9}}), + json!({"camera": {"target": [1, 2]}}), + json!({"camera": {"fit": true}}), + json!({"grid": "no"}), + json!({"axes": 1}), + json!({"study": null}), + json!({"study": "Nope"}), + json!({"study": null, "joint": "Rail"}), + // 4096 × 4096 frames: a GIF holds four of them. + json!({"width": 4096, "height": 4096, "samples": 5}), + ] { + assert!(refused(change.clone()).is_some(), "{change} was accepted"); + } + let e = refused(json!({"width": 4096, "height": 4096, "samples": 5})).unwrap(); + assert!(e.contains("2…4 for 4096 × 4096"), "{e}"); + assert!(super::animation::export_with(&s, &base, None).unwrap_err().to_string().contains("no renderer")); + assert!(!std::path::Path::new(&gif).exists(), "nothing refused was written"); + // An agent's export lands only inside its folders. + let root = dir.join("root"); + std::fs::create_dir_all(&root).unwrap(); + solidcraft_io::vfs::scoped(Some(solidcraft_io::vfs::PathScope::new([root.clone()])), || { + let e = refused(json!({"path": dir.join("out").to_string_lossy()})).unwrap(); + assert!(e.contains("outside the folders this agent may use"), "{e}"); + assert!(refused(json!({"path": root.join("in.gif").to_string_lossy()})).is_none()); + }); + assert!(root.join("in.gif").exists() && !dir.join("out").exists()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/cmd/occurrence_tests.rs b/crates/engine/src/cmd/occurrence_tests.rs index 31a1bed87..c88c7f8c2 100644 --- a/crates/engine/src/cmd/occurrence_tests.rs +++ b/crates/engine/src/cmd/occurrence_tests.rs @@ -66,6 +66,22 @@ fn instance_selection_survives_rename_move_capture_and_serde() { assert_eq!(roundtrip, s.selection); } +#[test] +fn component_rename_carries_into_placement_names() { + // #1665: the browser row shows the placement's name, so a rename has to reach it. + let mut s = Session::default(); + let (component, first) = created(&mut s, "Block"); + let second = run(&mut s, "occurrence.copy", json!({"component": component, "translate": [20,0,0]}))["occurrence"].as_u64().unwrap(); + let third = run(&mut s, "occurrence.copy", json!({"component": component, "translate": [40,0,0]}))["occurrence"].as_u64().unwrap(); + let name = |s: &Session, id: u64| s.doc.occurrences.iter().find(|o| o.id == id).unwrap().name.clone(); + assert_eq!(name(&s, second), "Block:2"); + // A placement named otherwise (an import's own name) keeps it. + s.doc_mut().occurrences.iter_mut().find(|o| o.id == third).unwrap().name = "Blockade:3".into(); + run(&mut s, "component.rename", json!({"component": component, "name": "box"})); + assert_eq!([name(&s, first), name(&s, second), name(&s, third)], ["box:1", "box:2", "Blockade:3"]); + assert_eq!(run(&mut s, "component.list", json!({}))["components"][0]["children"][0]["name"], "box:1"); +} + #[test] fn instance_selection_delete_removes_only_selected_instance() { let mut s = Session::default(); diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rs index 301cd5ddc..32ed8b1fd 100644 --- a/crates/engine/src/cmd/render.rs +++ b/crates/engine/src/cmd/render.rs @@ -14,7 +14,7 @@ mod jobs; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("render.preflight", "Check Render Request", jobs::preflight).noundo().doc_only() - .params("setup?: saved name OR settings?: full RenderSetup; transparent_background?: false; replace?: false. Validates the installed image host and bounded captured product scene without starting work. Stale geometry is rejected. See docs/render-jobs.md"), + .params("setup?: saved name OR settings?: full RenderSetup; integrator?: raster (default) or raytrace; raytrace?: bounded runtime lights/exposure_ev/shadows/reflections/anisotropic_faces options, only with raytrace; environment?: {path: scoped HDR, rotation_radians: 0, intensity: 1, samples: 16}; explicit sRGB/D65 HDR primaries required. Opaque CPU preview with selected mirror/rough-specular reflections and certified planar anisotropy. HDR with rough reflections or anisotropy requires fully metallic selected bodies and all effective faces; unsupported combinations refuse. No MIS, GI or glass/refraction. transparent_background?: false; replace?: false. Optional CPU raytracing requires a raytrace-cpu build and native host, checked before scene capture. Stale geometry is rejected. See docs/render-jobs.md"), CommandSpec::new("render.start", "Render Image", jobs::start).noundo().doc_only().at("RENDER", "IMAGE").icon("box") .params("Same request as render.preflight. Captures an immutable product scene and queues a bounded image job. Returns its session-scoped job identity, captured scene_generation and progress. Does not change the design. See docs/render-jobs.md"), CommandSpec::new("render.status", "Render Progress", jobs::status).noundo().doc_only() diff --git a/crates/engine/src/cmd/render/job_tests.rs b/crates/engine/src/cmd/render/job_tests.rs index 3caec0b44..8804daf9b 100644 --- a/crates/engine/src/cmd/render/job_tests.rs +++ b/crates/engine/src/cmd/render/job_tests.rs @@ -23,6 +23,31 @@ fn finish(host: &CpuHost) { panic!("cooperative job did not finish"); } +#[test] +fn missing_image_host_is_rejected_before_stale_scene_capture() { + let mut s = Session::default(); + for (command, params) in [ + ("sketch.create", json!({"plane":"XY"})), + ("sketch.rectangle.two_point", json!({"p0":[5,5],"p1":[25,20]})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"distance":5})), + ("sketch.edit", json!({"sketch":"Sketch1"})), + ("sketch.drag", json!({"entity":"l1.start","from":[5,5],"to":[4,5],"live":true})), + ] { + s.execute(command, ¶ms).unwrap(); + } + assert!(s.model.is_stale()); + let doc = s.doc.clone(); + let before = (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len()); + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &request()).unwrap_err().to_string(); + assert!(error.contains("no image host is installed"), "{error}"); + assert!(s.model.is_stale()); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len())); + } +} + #[test] fn runtime_commands_preserve_document_history_and_evaluation() { let (mut s, host) = session(); @@ -41,6 +66,46 @@ fn runtime_commands_preserve_document_history_and_evaluation() { assert_eq!(s.execute("render.cancel", &json!({"job":id})).unwrap()["progress"]["phase"], "completed"); } +#[test] +fn omitted_integrator_remains_raster_and_options_do_not_change_viewport_quality() { + let (mut s, host) = session(); + let implicit = s.execute("render.preflight", &request()).unwrap(); + let explicit = s.execute("render.preflight", &json!({"integrator":"raster","settings":{"width":16,"height":16}})).unwrap(); + assert_eq!(implicit, explicit); + assert_eq!(implicit["request"]["integrator"], "raster"); + assert_eq!(implicit["resolved"]["executor"], "cpu-product"); + assert!(s.execute("render.preflight", &json!({"raytrace":{"shadows":true}})).is_err()); + assert!(s.execute("render.preflight", &json!({"integrator":"quality"})).is_err()); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(not(feature = "raytrace-cpu"))] +#[test] +fn compiled_out_raytrace_is_rejected_before_scene_capture() { + let (mut s, host) = session(); + for (command, params) in [ + ("sketch.create", json!({"plane":"XY"})), + ("sketch.rectangle.two_point", json!({"p0":[5,5],"p1":[25,20]})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"distance":5})), + ("sketch.edit", json!({"sketch":"Sketch1"})), + ("sketch.drag", json!({"entity":"l1.start","from":[5,5],"to":[4,5],"live":true})), + ] { + s.execute(command, ¶ms).unwrap(); + } + assert!(s.model.is_stale()); + let doc = s.doc.clone(); + let before = (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len()); + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &json!({"integrator":"raytrace","replace":true})).unwrap_err().to_string(); + assert!(error.contains("not compiled in"), "{error}"); + assert!(s.model.is_stale()); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len())); + assert_eq!(host.admitted_bytes(), 0); + } +} + #[test] fn identities_are_isolated_across_documents_scratch_and_new() { let (mut a, host) = session(); @@ -217,3 +282,87 @@ fn native_start_and_cancel_measure_cached_capture_without_timing_assertions() { ); assert!(status.progress.phase.terminal()); } +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn native_raytrace_preflight_start_and_frame_preserve_document_and_roundtrip_request() { + let mut s = Session::default(); + s.set_render_job_host(Some(CpuHost::for_platform().unwrap())).unwrap(); + s.execute("solid.box", &json!({"length":20,"width":15,"height":10})).unwrap(); + s.execute("render.scene", &json!({})).unwrap(); + let doc = s.doc.clone(); + let before = (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len()); + let params = json!({"integrator":"raytrace","settings":{"width":32,"height":32},"raytrace":{"preset":"neutral","shadows":true}}); + let preflight = s.execute("render.preflight", ¶ms).unwrap(); + let request: solidcraft_render::job::ImageRequest = serde_json::from_value(preflight["request"].clone()).unwrap(); + assert_eq!(request.integrator, solidcraft_render::job::Integrator::Raytrace); + assert_eq!(preflight["resolved"]["executor"], "cpu-raytrace"); + let started = s.execute("render.start", ¶ms).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Completed); + let frame = handle.frame().unwrap().unwrap(); + assert_eq!(frame.info.job, id); + assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); + assert_eq!((frame.info.width, frame.info.height), (32, 32)); + assert!(frame.png().starts_with(b"\x89PNG\r\n\x1a\n")); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert_eq!(before, (s.revision, s.evaluations, s.is_dirty(), s.undo.len(), s.redo.len())); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn captured_hdr_input_lights_geometry_after_source_removal_and_preserves_history() { + let host = CpuHost::for_platform().unwrap(); + let mut s = Session::default(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("solidcraft-hdri-{}-{nonce}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let source = dir.join("original.hdr"); + s.execute("solid.box", &json!({"length":20,"width":20,"height":20})).unwrap(); + s.execute("render.scene", &json!({})).unwrap(); + let bytes = |primaries: &str| { + let mut b = format!("#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n{primaries}\n-Y 2 +X 4\n").into_bytes(); + for _ in 0..8 { + b.extend_from_slice(&[128, 64, 32, 129]); + } + b + }; + std::fs::write(&source, bytes("")).unwrap(); + let params = json!({"integrator":"raytrace","raytrace":{"lights":[]},"settings":{"width":9,"height":9,"background":[13,27,41]},"environment":{"path":source.to_str().unwrap(),"samples":64}}); + let doc = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.is_dirty()); + assert!(s.execute("render.preflight", ¶ms).unwrap_err().to_string().contains("primaries")); + assert_eq!(host.admitted_bytes(), 0); + std::fs::write(&source, bytes("PRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n")).unwrap(); + let preflight = s.execute("render.preflight", ¶ms).unwrap(); + assert_eq!(preflight["environment"]["color_policy"], "explicit_linear_srgb_d65"); + assert_eq!(preflight["environment"]["header"]["width"], 4); + assert!(preflight["resolved"]["profile"]["features"].as_array().unwrap().contains(&json!("hdri"))); + assert_eq!(preflight["environment"]["source_sha256"].as_array().unwrap().len(), 32); + assert!(!preflight["environment"].to_string().contains(dir.to_str().unwrap())); + assert_eq!(host.admitted_bytes(), 0); + let mut unlit = params.clone(); + unlit.as_object_mut().unwrap().remove("environment"); + let base = s.execute("render.start", &unlit).unwrap(); + let base_id: JobId = serde_json::from_value(base["job"].clone()).unwrap(); + let base_handle = s.render_jobs.handle(base_id).unwrap(); + base_handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + let baseline = base_handle.frame().unwrap().unwrap().png().to_vec(); + let reply = s.execute("render.start", ¶ms).unwrap(); + assert_eq!(reply["environment"], preflight["environment"]); + let id: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + // Captured bytes remain sufficient after the source disappears. + std::fs::remove_file(source).unwrap(); + let handle = s.render_jobs.handle(id).unwrap(); + assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, solidcraft_render::job::Phase::Completed); + assert_ne!(handle.frame().unwrap().unwrap().png(), baseline.as_slice(), "captured HDR must illuminate actual geometry"); + assert_eq!(serde_json::to_value(handle.status().unwrap()).unwrap()["environment"], preflight["environment"]); + let output = dir.join("background.png"); + s.execute("render.export", &json!({"job":id,"path":output.to_str().unwrap()})).unwrap(); + assert!(std::fs::metadata(output).unwrap().len() > 0); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.is_dirty())); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/engine/src/cmd/render/jobs.rs b/crates/engine/src/cmd/render/jobs.rs index 8056c6272..82c68c9f2 100644 --- a/crates/engine/src/cmd/render/jobs.rs +++ b/crates/engine/src/cmd/render/jobs.rs @@ -4,24 +4,88 @@ use serde_json::{Value, json}; use solidcraft_doc::render_settings::RenderSetup; use solidcraft_render::{ RenderOperation, RenderRequest, - job::{ImageRequest, JobId}, + job::{ImageRequest, Integrator, JobId, RaytraceOptions}, }; #[derive(Default, Deserialize)] #[serde(default, deny_unknown_fields)] struct Start { + integrator: Integrator, + environment: Option, + raytrace: Option, setup: Option, settings: Option, transparent_background: bool, replace: bool, } -fn prepare(s: &Session, params: &Value, command: &str) -> Result<(Start, solidcraft_render::ProductScene, ImageRequest, Value)> { +#[derive(Deserialize)] +#[serde(default, deny_unknown_fields)] +struct EnvironmentRequest { + path: String, + rotation_radians: f64, + intensity: f64, + samples: u32, +} +impl Default for EnvironmentRequest { + fn default() -> Self { + Self { path: String::new(), rotation_radians: 0.0, intensity: 1.0, samples: 16 } + } +} + +type Prepared = + (Start, solidcraft_render::ProductScene, ImageRequest, Value, Option); + +fn prepare(s: &Session, params: &Value, command: &str) -> Result { let input: Start = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; if input.setup.is_some() && input.settings.is_some() { return Err(bad(command, "choose either setup or settings")); } + // Reject unavailable execution before capturing authoritative product meshes. + // Runtime services are independent of the document and can be checked cold. + let host = s.render_job_host().ok_or_else(|| bad(command, "no image host is installed"))?; + if !host.is_available() { + return Err(bad(command, "image host is unavailable")); + } + host.validate_integrator(input.integrator).map_err(job_error)?; + if input.integrator == Integrator::Raster && input.raytrace.is_some() { + return Err(bad(command, "raytrace options require integrator: raytrace")); + } + if input.integrator == Integrator::Raytrace && input.transparent_background { + return Err(bad(command, "raytrace supports opaque backgrounds only")); + } + if let Some(options) = &input.raytrace { + options.validate().map_err(job_error)?; + } + let environment = if let Some(environment) = &input.environment { + if input.integrator != Integrator::Raytrace + || environment.path.is_empty() + || environment.path.len() > 4096 + || environment.path.capacity() > 4096 + || environment.path.chars().any(char::is_control) + { + return Err(bad(command, "environment requires raytrace and a bounded HDR input path")); + } + // The established scoped, bounded file reader and HDR decoder remain the only input path. + let bytes = + solidcraft_io::vfs::read(&environment.path, solidcraft_render::lighting::MAX_HDR_BYTES).map_err(|e| bad(command, e.to_string()))?; + let source = solidcraft_render::lighting::HdrSource::new(bytes).map_err(|e| bad(command, e.to_string()))?; + Some( + solidcraft_render::lighting::environment_input::EnvironmentInput::new( + source, + environment.rotation_radians, + environment.intensity, + environment.samples, + ) + .map_err(|e| bad(command, e.to_string()))?, + ) + } else { + None + }; let scene = crate::product_scene::extract(s)?; + if environment.is_some() { + input.raytrace.as_ref().unwrap_or(&RaytraceOptions::default()).validate_environment_reflections(&scene).map_err(job_error)?; + } let settings = if let Some(name) = &input.setup { s.doc.render.setups.get(name).cloned().ok_or_else(|| bad(command, "no saved render setup with that name"))? } else if let Some(settings) = &input.settings { @@ -39,12 +103,17 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<(Start, solidcr if settings.exposure_ev != 0.0 || settings.environment_rotation != 0.0 || settings.environment_intensity != 1.0 { return Err(bad(command, "exposure and environment controls are not supported by the R4a CPU image executor")); } - let host = s.render_job_host().ok_or_else(|| bad(command, "no image host is installed"))?; - if !host.is_available() { - return Err(bad(command, "image host is unavailable")); + let descriptor = host.descriptor_for(input.integrator).map_err(job_error)?; + let expected_executor = descriptor.id.clone(); + let mut backend = s.render_backend(); + backend.executors = vec![descriptor]; + let mut features = scene.required_features(); + if environment.is_some() { + features.push(solidcraft_render::RenderFeature::Hdri); } + let environment_info = environment.as_ref().map(|e| e.metadata()); let resolved = solidcraft_render::resolve_request( - &[s.render_backend()], + &[backend], &RenderRequest { backend: Some(settings.backend.clone()), mode: settings.mode, @@ -52,33 +121,53 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<(Start, solidcr width: u64::from(settings.width), height: u64::from(settings.height), format: Some(settings.format), - features: scene.required_features(), + features, policy: Default::default(), }, ) .map_err(|e| bad(command, e.to_string()))?; - if resolved.executor.as_str() != "cpu-product" { + if resolved.executor != expected_executor { return Err(bad(command, "resolved executor is not installed as an image job host")); } let request = ImageRequest { + integrator: input.integrator, + raytrace: input.raytrace.clone(), camera: settings.camera, width: settings.width, height: settings.height, background: settings.background, transparent_background: input.transparent_background, }; - let admission = solidcraft_render::job::admit(&scene, &request).map_err(job_error)?; - let reply = json!({"resolved":resolved,"admission":admission,"request":request,"scene_generation":s.revision,"host":host.kind(),"transparency":"sorted_alpha_approximation","refraction":false}); - Ok((input, scene, request, reply)) + let mut admission = solidcraft_render::job::admit(&scene, &request).map_err(job_error)?; + let environment_bytes = environment.as_ref().map_or(Ok(0), |e| e.required_bytes()).map_err(|e| bad(command, e.to_string()))?; + let retained_lights = request.raytrace.as_ref().map_or(Ok(0), |o| o.retained_bytes()).map_err(job_error)?; + let retained_environment = + if environment_info.is_some() { std::mem::size_of::() as u64 } else { 0 }; + let retained_request_bytes = retained_lights.checked_add(retained_environment).ok_or_else(|| bad(command, "request metadata overflow"))?; + + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(environment_bytes) + .and_then(|v| v.checked_add(retained_request_bytes)) + .filter(|v| *v <= 384 * 1024 * 1024) + .ok_or_else(|| bad(command, "environment job exceeds per-job memory limit"))?; + admission.preparation_bytes = + admission.preparation_bytes.checked_add(environment_bytes).ok_or_else(|| bad(command, "environment admission overflow"))?; + let transparency = match input.integrator { + Integrator::Raster => "sorted_alpha_approximation", + Integrator::Raytrace => "opaque_only", + }; + let reply = json!({"environment":environment_info,"retained_request_bytes":retained_request_bytes,"resolved":resolved,"admission":admission,"request":request,"scene_generation":s.revision,"host":host.kind(),"transparency":transparency,"refraction":false}); + Ok((input, scene, request, reply, environment)) } pub(super) fn preflight(s: &mut Session, params: &Value) -> Result { - prepare(s, params, "render.preflight").map(|(_, _, _, reply)| reply) + prepare(s, params, "render.preflight").map(|(_, _, _, reply, _)| reply) } pub(super) fn start(s: &mut Session, params: &Value) -> Result { - let (input, scene, request, _) = prepare(s, params, "render.start")?; - let status = s.render_jobs.start(s.revision, scene, request, input.replace).map_err(job_error)?; + let (input, scene, request, _, environment) = prepare(s, params, "render.start")?; + let status = s.render_jobs.start_with_environment(s.revision, scene, request, input.replace, environment).map_err(job_error)?; Ok(json!(status)) } diff --git a/crates/engine/src/cmd/view_dxf.rs b/crates/engine/src/cmd/view_dxf.rs index 3a18f0db6..c62488411 100644 --- a/crates/engine/src/cmd/view_dxf.rs +++ b/crates/engine/src/cmd/view_dxf.rs @@ -1,6 +1,10 @@ //! A drawing of the visible bodies from a supplied viewport camera. No screen pixels, grid, //! selection highlights or tessellation diagonals are exported. +#[path = "view_dxf_meshes.rs"] +mod meshes; +#[path = "view_dxf_progress.rs"] +mod progress; #[path = "view_dxf_projection.rs"] mod projection; @@ -46,28 +50,17 @@ fn export(s: &mut Session, p: &Value) -> Result { if let Some(path) = path { solidcraft_io::vfs::check(path).map_err(|e| crate::EngineError::Other(e.to_string()))?; } - let world = s.world_state(); - let mut meshes = Vec::new(); - let mut count = 0usize; - for body in world.bodies.iter().filter(|b| s.body_visible(&b.name)) { - let mesh = body.body.reference_display_mesh_angular(tolerance, solidcraft_kernel::DISPLAY_ANGLE)?; - count = count.saturating_add(mesh.triangles.len()).saturating_add(mesh.edges.iter().map(Vec::len).sum::()); - if count > 1_000_000 { - return Err(bad(CMD, "view too complex to export; hide bodies or increase tolerance")); - } - if mesh.triangles.is_empty() { - return Err(bad(CMD, format!("{} has no exportable surface", body.name))); - } - meshes.push(mesh); - } - if meshes.is_empty() { - return Err(bad(CMD, "no visible bodies to export")); - } - let lines = projection::drawing(&meshes, &cam).map_err(|e| bad(CMD, e))?; + let started = std::time::Instant::now(); + progress::Stage::new("dxf_meshes", 1).check().map_err(|e| bad(CMD, e))?; + let meshes = meshes::prepare(s, tolerance)?; + let prepare_ms = started.elapsed().as_secs_f64() * 1000.; + let drawing = projection::drawing(&meshes, &cam).map_err(|e| bad(CMD, e))?; + let writing = progress::Stage::new("dxf_write", 1); + writing.check().map_err(|e| bad(CMD, e))?; let mut visible = 0; let mut hidden = 0; let mut entities = Vec::new(); - for line in lines { + for line in drawing.lines { if line.hidden && !dashed { continue; } @@ -86,9 +79,14 @@ fn export(s: &mut Session, p: &Value) -> Result { layers.push(DxfLayer { linetype: DxfLinetype::Hidden, ..DxfLayer::new("HIDDEN", 8) }); } let text = solidcraft_io::write_dxf_drawing(&layers, &entities); + writing.check().map_err(|e| bad(CMD, e))?; let mut result = json!({"visible":visible,"hidden":hidden,"units":"mm","tolerance":tolerance,"projection":if cam.fov > 0.0 {"perspective"} else {"orthographic"}}); + result["stats"] = json!({"bodies":meshes.placements.len(),"shared_meshes":meshes.meshes.len(),"triangles":meshes.triangles, + "mesh_bytes":meshes.bytes,"worker_limit":meshes::WORKERS,"segments":drawing.segments,"occlusion_work":drawing.work, + "prepare_ms":prepare_ms,"projection_ms":drawing.projection_ms,"occlusion_ms":drawing.occlusion_ms}); if let Some(path) = path { - solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| crate::EngineError::Other(e.to_string()))?; + solidcraft_io::vfs::check(path).map_err(|e| crate::EngineError::Other(e.to_string()))?; + solidcraft_io::write_atomic(std::path::Path::new(path), text.as_bytes(), false).map_err(|e| crate::EngineError::Other(e.to_string()))?; result["path"] = json!(path); } else { result["dxf"] = json!(text); diff --git a/crates/engine/src/cmd/view_dxf_meshes.rs b/crates/engine/src/cmd/view_dxf_meshes.rs new file mode 100644 index 000000000..ec3f0e4d9 --- /dev/null +++ b/crates/engine/src/cmd/view_dxf_meshes.rs @@ -0,0 +1,207 @@ +//! Export-only mesh instances. Keep one geometry buffer per unambiguous definition, while +//! retaining the current placed body's edge choices (tangent classification can vary after +//! placement). Never modify the document, fuse parts, or share across separate exports. +use std::collections::BTreeMap; +use std::mem::size_of; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use solidcraft_doc::{IDENTITY, Mat, ModelBody, mat_inverse, mat_mul}; +use solidcraft_geom::{Aabb3, Mesh, Vec3}; +use solidcraft_kernel::{KernelError, map_with_local_pools}; + +use super::{CMD, progress::Stage}; +use crate::params::bad; +use crate::{Result, Session}; + +#[cfg(not(target_arch = "wasm32"))] +pub(super) const WORKERS: usize = 8; +#[cfg(target_arch = "wasm32")] +pub(super) const WORKERS: usize = 1; +const MESH_BYTES: usize = 512 * 1024 * 1024; +const MAX_BODIES: usize = 100_000; + +pub(super) struct Placement { + pub mesh: usize, + pub transform: Mat, + pub visibility: Vec, +} +pub(super) struct Scene { + pub meshes: Vec>, + pub placements: Vec, + pub triangles: usize, + pub bytes: usize, +} + +struct Group { + first: usize, + inverse: Mat, +} +struct Item<'a> { + body: &'a ModelBody, + group: usize, + keep: bool, + transform: Mat, +} +struct Prepared { + mesh: Option>, + visibility: Vec, + triangles: usize, +} + +pub(super) fn claim(counter: &AtomicUsize, amount: usize, limit: usize) -> bool { + let mut old = counter.load(Ordering::Relaxed); + loop { + let Some(next) = old.checked_add(amount).filter(|n| *n <= limit) else { return false }; + match counter.compare_exchange_weak(old, next, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => return true, + Err(current) => old = current, + } + } +} + +pub(super) fn buffer_bytes(m: &Mesh) -> usize { + m.positions.capacity() * size_of::() + + m.normals.capacity() * size_of::() + + m.triangles.capacity() * size_of::<[u32; 3]>() + + m.tri_face.capacity() * size_of::() + + m.edges.capacity() * size_of::>() + + m.edges.iter().map(|e| e.capacity() * size_of::()).sum::() + + m.seams.capacity() + + m.smooth_edges.capacity() + + m.sharp_edges.capacity() + + m.edge_faces.capacity() * size_of::>() + + m.edge_faces.iter().map(|e| e.capacity() * size_of::()).sum::() +} + +fn rigid(m: &Mat) -> bool { + if m.iter().flatten().any(|v| !v.is_finite()) || m.iter().zip([0., 0., 0., 1.]).any(|(c, w)| (c[3] - w).abs() > 1e-10) { + return false; + } + let axes = [Vec3::new(m[0][0], m[0][1], m[0][2]), Vec3::new(m[1][0], m[1][1], m[1][2]), Vec3::new(m[2][0], m[2][1], m[2][2])]; + let [x, y, z] = axes; + (x.len2() - 1.).abs() < 1e-9 + && (y.len2() - 1.).abs() < 1e-9 + && (z.len2() - 1.).abs() < 1e-9 + && x.dot(y).abs() < 1e-9 + && x.dot(z).abs() < 1e-9 + && y.dot(z).abs() < 1e-9 + && (x.cross(y).dot(z) - 1.).abs() < 1e-9 +} + +pub(super) fn prepare(s: &Session, tolerance: f64) -> Result { + let world = s.world_state(); + let state = s.model.state(); + let mut definitions = BTreeMap::new(); + for body in &state.bodies { + *definitions.entry((body.component, body.definition_name(), body.feature)).or_insert(0usize) += 1; + } + let mut by_definition = BTreeMap::new(); + let mut groups: Vec = Vec::new(); + let mut items = Vec::new(); + for (index, body) in world.bodies.iter().enumerate().filter(|(_, b)| s.body_visible(&b.name)) { + if items.len() >= MAX_BODIES { + return Err(bad(CMD, "too many placed bodies to export")); + } + let key = (body.component, body.definition_name(), body.feature); + let unambiguous = definitions.get(&key) == Some(&1); + let reused = unambiguous + .then(|| by_definition.get(&key).copied()) + .flatten() + .and_then(|g: usize| groups.get(g).map(|group| (g, mat_mul(&body.source_transform, &group.inverse)))) + .filter(|(_, m)| rigid(m)); + let (group, transform) = if let Some(reused) = reused { + reused + } else { + let g = groups.len(); + groups.push(Group { first: index, inverse: mat_inverse(&body.source_transform).unwrap_or(IDENTITY) }); + if unambiguous && mat_inverse(&body.source_transform).is_some() { + by_definition.entry(key).or_insert(g); + } + (g, IDENTITY) + }; + let keep = groups.get(group).is_some_and(|g| g.first == index); + items.push(Item { body, group, keep, transform }); + } + if items.is_empty() { + return Err(bad(CMD, "no visible bodies to export")); + } + let progress = Stage::new("dxf_meshes", items.len()); + let bytes = AtomicUsize::new(0); + let results = map_with_local_pools(&items, WORKERS, |item| { + progress.check().map_err(|e| KernelError::Failed(e.into()))?; + let mut mesh = item.body.body.reference_display_mesh_angular(tolerance, solidcraft_kernel::DISPLAY_ANGLE)?; + if mesh.triangles.is_empty() { + return Err(KernelError::Invalid(format!("{} has no exportable surface", item.body.name))); + } + let visibility = (0..mesh.edges.len()).map(|i| mesh.shaded_edge_visible(i)).collect(); + let triangles = mesh.triangles.len(); + let mesh = if item.keep { + // These are owned export buffers, not the document's cached mesh. Picking and + // shading data are unused by vector occlusion; edge choices were captured above. + mesh.normals = Vec::new(); + mesh.tri_face = Vec::new(); + mesh.seams = Vec::new(); + mesh.smooth_edges = Vec::new(); + mesh.sharp_edges = Vec::new(); + mesh.edge_faces = Vec::new(); + if !claim(&bytes, buffer_bytes(&mesh), MESH_BYTES) { + return Err(KernelError::Invalid("view exceeds export memory budget; hide bodies or increase tolerance".into())); + } + Some(Arc::new(mesh)) + } else { + None + }; + progress.advance(1).map_err(|e| KernelError::Failed(e.into()))?; + Ok(Prepared { mesh, visibility, triangles }) + }); + let mut prepared = results.into_iter().collect::>>()?; + let mut meshes: Vec>> = vec![None; groups.len()]; + for (item, p) in items.iter().zip(&mut prepared) { + if let Some(mesh) = p.mesh.take() + && let Some(slot) = meshes.get_mut(item.group) + { + *slot = Some(mesh); + } + } + let meshes = meshes.into_iter().map(|m| m.ok_or_else(|| bad(CMD, "missing export geometry"))).collect::>>()?; + let mut placements = Vec::with_capacity(items.len()); + let mut triangles = 0usize; + for (item, p) in items.iter().zip(prepared) { + if meshes.get(item.group).is_none_or(|m| m.edges.len() != p.visibility.len()) { + return Err(bad(CMD, "placed edge identity changed")); + } + triangles = triangles.saturating_add(p.triangles); + placements.push(Placement { mesh: item.group, transform: item.transform, visibility: p.visibility }); + } + Ok(Scene { meshes, placements, triangles, bytes: bytes.load(Ordering::Relaxed) }) +} + +pub(super) fn transformed_bounds(mesh: &Mesh, m: &Mat) -> Aabb3 { + let b = mesh.bounds(); + let mut out = Aabb3::EMPTY; + for x in [b.min.x, b.max.x] { + for y in [b.min.y, b.max.y] { + for z in [b.min.z, b.max.z] { + out.add(solidcraft_doc::apply_point(m, Vec3::new(x, y, z))); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn only_proper_rigid_placements_share_geometry() { + assert!(rigid(&solidcraft_doc::rigid(Vec3::new(1., 2., 3.), Vec3::ZERO, Vec3::Z, 0.7))); + let mut m = IDENTITY; + m[0][0] = -1.; + assert!(!rigid(&m)); + m[0][0] = 2.; + assert!(!rigid(&m)); + m[0][0] = f64::NAN; + assert!(!rigid(&m)); + } +} diff --git a/crates/engine/src/cmd/view_dxf_progress.rs b/crates/engine/src/cmd/view_dxf_progress.rs new file mode 100644 index 000000000..4c4adca7f --- /dev/null +++ b/crates/engine/src/cmd/view_dxf_progress.rs @@ -0,0 +1,35 @@ +//! Stage counters shared by the export worker and its bounded computation workers. +use std::sync::{Arc, Mutex}; + +pub(super) const CANCELLED: &str = "DXF export cancelled"; + +pub(super) struct Stage { + watch: Option>, + name: &'static str, + total: usize, + done: Mutex, +} + +impl Stage { + pub fn new(name: &'static str, total: usize) -> Self { + let stage = Self { watch: solidcraft_kernel::watch::current(), name, total: total.max(1), done: Mutex::new(0) }; + if let Some(watch) = &stage.watch { + watch.progress(name, 0, stage.total); + } + stage + } + pub fn check(&self) -> Result<(), &'static str> { + if self.watch.as_ref().is_some_and(|w| w.cancelled()) { Err(CANCELLED) } else { Ok(()) } + } + pub fn advance(&self, count: usize) -> Result<(), &'static str> { + self.check()?; + if let Some(watch) = &self.watch { + // Serialize reports as well as increments: eight workers must not report a + // smaller completed count after a larger one. + let mut done = self.done.lock().map_err(|_| "export progress unavailable")?; + *done = done.saturating_add(count).min(self.total); + watch.progress(self.name, *done, self.total); + } + self.check() + } +} diff --git a/crates/engine/src/cmd/view_dxf_projection.rs b/crates/engine/src/cmd/view_dxf_projection.rs index c496b2ac9..bfb08025b 100644 --- a/crates/engine/src/cmd/view_dxf_projection.rs +++ b/crates/engine/src/cmd/view_dxf_projection.rs @@ -1,10 +1,27 @@ //! Vector hidden-line removal: intersect each projected edge with triangle half planes and //! its depth plane, then union occluded parameter intervals. A BVH bounds the candidate work. -use solidcraft_geom::{Aabb3, Mesh, Vec2, Vec3}; +#[cfg(test)] +use solidcraft_geom::Mesh; +use solidcraft_geom::{Aabb3, Vec2, Vec3}; use solidcraft_io::{DxfEntity, DxfShape}; use solidcraft_render::Camera; use std::collections::BTreeMap; +#[path = "view_dxf_scene.rs"] +mod scene; + +pub(super) struct Drawing { + pub lines: Vec, + pub work: usize, + pub segments: usize, + pub projection_ms: f64, + pub occlusion_ms: f64, +} + +pub(super) fn drawing(meshes: &super::meshes::Scene, cam: &Camera) -> Result { + scene::drawing(meshes, cam) +} + /// Keep the hidden curves connected: restarting a dash on every short chord would make a /// small circular hole look solid. Degree-two joins continue; junctions end the polyline. pub(super) fn connect(entities: Vec) -> Vec { @@ -50,6 +67,7 @@ pub(super) fn connect(entities: Vec) -> Vec { result } +#[derive(Clone, Debug)] pub(super) struct Line { pub a: Vec2, pub b: Vec2, @@ -73,15 +91,18 @@ fn overlap(a: &Aabb3, b: &Aabb3) -> bool { a.min.x <= b.max.x && b.min.x <= a.max.x && a.min.y <= b.max.y && b.min.y <= a.max.y } +#[cfg(test)] struct Triangle { p: [Vec3; 3], bounds: Aabb3, } +#[cfg(test)] struct Tree { bounds: Aabb3, children: Option<(Box, Box)>, triangles: Vec, } +#[cfg(test)] impl Tree { fn new(mut triangles: Vec) -> Self { let b = triangles.iter().fold(Aabb3::EMPTY, |b, t| b.union(&t.bounds)); @@ -213,6 +234,7 @@ fn merge_lines(lines: Vec, eps: f64) -> Vec { /// B-rep edges plus curved silhouettes. Triangle adjacency is welded by position because /// different faces can have different vertex indices along their shared boundary. +#[cfg(test)] fn edges(mesh: &Mesh, cam: &Camera, eps: f64) -> Vec<(Vec3, Vec3)> { let mut result = Vec::new(); for (_, e) in mesh.edges.iter().enumerate().filter(|(i, _)| mesh.shaded_edge_visible(*i)) { @@ -241,7 +263,8 @@ fn edges(mesh: &Mesh, cam: &Camera, eps: f64) -> Vec<(Vec3, Vec3)> { result } -pub(super) fn drawing(meshes: &[Mesh], cam: &Camera) -> Result, &'static str> { +#[cfg(test)] +fn reference_drawing(meshes: &[Mesh], cam: &Camera) -> Result, &'static str> { let (right, up, back) = cam.basis(); let scale = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.bounds())).diagonal().max(1.0); let eps = scale * 1e-8; diff --git a/crates/engine/src/cmd/view_dxf_scene.rs b/crates/engine/src/cmd/view_dxf_scene.rs new file mode 100644 index 000000000..849dcb568 --- /dev/null +++ b/crates/engine/src/cmd/view_dxf_scene.rs @@ -0,0 +1,627 @@ +//! Two levels of occlusion acceleration: an instance tree over projected bounds, and one +//! triangle hierarchy per shared mesh. Per-placement node bounds are small; projected +//! triangle coordinates are evaluated only in visited leaves. Covered line intervals prune +//! subsequent nodes and instances, including the entire query once coverage is complete. +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use solidcraft_doc::apply_point; +use solidcraft_geom::{Aabb3, Mesh, Vec3}; +use solidcraft_render::Camera; + +use super::super::meshes::{Placement, Scene, WORKERS, claim, transformed_bounds}; +use super::super::progress::Stage; +use super::{Drawing, Line, bounds, clip, key, merge_lines, occluded, overlap, xy}; + +const TOO_COMPLEX: &str = "view exceeds export work budget; hide bodies or increase tolerance"; +const MAX_LINES: usize = 1_000_000; +const MAX_SEGMENTS: usize = 4_000_000; +const MAX_SHARED_TRIANGLES: usize = 2_000_000; +const MAX_VIEW_NODES: usize = 256 * 1024 * 1024 / std::mem::size_of::(); +const WORK: usize = 200_000_000; + +fn parallel(items: &[T], f: impl Fn(&T) -> Result + Sync) -> Result, &'static str> { + solidcraft_kernel::map_on_threads(items, WORKERS, f).into_iter().map(|r| r.ok_or("export worker failed")?).collect() +} + +struct Node { + bounds: Aabb3, + start: usize, + end: usize, + children: Option<(usize, usize)>, +} +struct Bvh { + nodes: Vec, + ids: Vec, +} +impl Bvh { + fn new(boxes: &[Aabb3], flat: bool) -> Self { + let mut tree = Self { nodes: Vec::new(), ids: (0..boxes.len()).collect() }; + if !boxes.is_empty() { + tree.build(boxes, 0, boxes.len(), flat); + } + tree + } + fn build(&mut self, boxes: &[Aabb3], start: usize, end: usize, flat: bool) -> usize { + let b = self.ids.get(start..end).into_iter().flatten().filter_map(|i| boxes.get(*i)).fold(Aabb3::EMPTY, |b, t| b.union(t)); + let index = self.nodes.len(); + self.nodes.push(Node { bounds: b, start, end, children: None }); + if end - start > 8 { + let size = b.size(); + let axis = if !flat && size.z > size.x.max(size.y) { + 2 + } else if size.x > size.y { + 0 + } else { + 1 + }; + let value = |i: &usize| { + boxes.get(*i).map(|b| b.center()).map_or(0., |p| match axis { + 0 => p.x, + 1 => p.y, + _ => p.z, + }) + }; + let mid = start + (end - start) / 2; + if let Some(ids) = self.ids.get_mut(start..end) { + ids.select_nth_unstable_by(mid - start, |a, b| value(a).total_cmp(&value(b)).then_with(|| a.cmp(b))); + } + let left = self.build(boxes, start, mid, flat); + let right = self.build(boxes, mid, end, flat); + if let Some(node) = self.nodes.get_mut(index) { + node.children = Some((left, right)); + } + } + index + } +} + +struct Edge { + vertices: [u32; 2], + start: usize, + end: usize, +} +struct Side { + key: [[i64; 3]; 2], + vertices: [u32; 2], + triangle: usize, +} +struct Shared { + mesh: Arc, + tree: Bvh, + edges: Vec, + incident: Vec, +} +impl Shared { + fn new(mesh: &Arc, eps: f64, progress: &Stage) -> Result { + let mut boxes = Vec::with_capacity(mesh.triangles.len()); + let mut sides = Vec::new(); + for (i, indices) in mesh.triangles.iter().enumerate() { + if i.is_multiple_of(1024) { + progress.check()?; + } + let points = mesh.tri(indices).ok_or("invalid export triangle")?; + if points.iter().any(|p| !p.is_finite()) { + return Err("model contains invalid coordinates"); + } + boxes.push(bounds(points)); + for (a, b) in [(0, 1), (1, 2), (2, 0)] { + let (Some(pa), Some(pb), Some(ia), Some(ib)) = (points.get(a), points.get(b), indices.get(a), indices.get(b)) else { + return Err("invalid export edge"); + }; + let (ka, kb) = (key(*pa, eps), key(*pb, eps)); + if ka == kb { + continue; + } + let (key, vertices) = if ka < kb { ([ka, kb], [*ia, *ib]) } else { ([kb, ka], [*ib, *ia]) }; + sides.push(Side { key, vertices, triangle: i }); + } + } + let tree = Bvh::new(&boxes, false); + sides.sort_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.triangle.cmp(&b.triangle))); + let mut edges: Vec = Vec::new(); + let mut incident = Vec::with_capacity(sides.len()); + let mut previous = None; + for side in sides { + if previous != Some(side.key) { + edges.push(Edge { vertices: side.vertices, start: incident.len(), end: incident.len() }); + previous = Some(side.key); + } + incident.push(side.triangle); + if let Some(e) = edges.last_mut() { + e.end = incident.len(); + } + } + Ok(Self { mesh: mesh.clone(), tree, edges, incident }) + } +} + +struct View<'a> { + cam: &'a Camera, + right: Vec3, + up: Vec3, + back: Vec3, +} +impl<'a> View<'a> { + fn new(cam: &'a Camera) -> Self { + let (right, up, back) = cam.basis(); + Self { cam, right, up, back } + } + fn project(&self, p: Vec3) -> Result { + if !p.is_finite() { + return Err("model contains invalid coordinates"); + } + let d = p - self.cam.target; + let z = d.dot(self.back); + let projected = if self.cam.fov > 0. { + let w = self.cam.distance - z; + if w <= self.cam.distance * 1e-6 { + return Err("model crosses the camera eye plane; zoom out before exporting"); + } + Vec3::new(d.dot(self.right) * self.cam.distance / w, d.dot(self.up) * self.cam.distance / w, 1. / w) + } else { + Vec3::new(d.dot(self.right), d.dot(self.up), z) + }; + if !projected.is_finite() || projected.len() > 1e12 { + return Err("projected coordinates exceed the export range"); + } + Ok(projected) + } + fn triangle(&self, shared: &Shared, placed: &Placement, id: usize) -> Result<[Vec3; 3], &'static str> { + let indices = shared.mesh.triangles.get(id).ok_or("invalid export triangle")?; + let [a, b, c] = shared.mesh.tri(indices).ok_or("invalid export triangle")?; + Ok([ + self.project(apply_point(&placed.transform, a))?, + self.project(apply_point(&placed.transform, b))?, + self.project(apply_point(&placed.transform, c))?, + ]) + } +} + +struct Projected { + nodes: Vec, + segments: Vec<(Vec3, Vec3)>, +} +impl Projected { + fn new(shared: &Shared, placed: &Placement, view: &View<'_>, eps: f64, segments: &AtomicUsize, progress: &Stage) -> Result { + let mut nodes = vec![Aabb3::EMPTY; shared.tree.nodes.len()]; + // Exact projected leaf bounds avoid false near-eye errors from empty corners of a + // rotated model-space box. Interior bounds are just unions of the child bounds. + let mut front = vec![false; shared.mesh.triangles.len()]; + for (i, node) in shared.tree.nodes.iter().enumerate().rev() { + if i.is_multiple_of(1024) { + progress.check()?; + } + let mut b = Aabb3::EMPTY; + if let Some((left, right)) = node.children { + b = nodes.get(left).ok_or("invalid export tree")?.union(nodes.get(right).ok_or("invalid export tree")?); + } else { + for id in shared.tree.ids.get(node.start..node.end).ok_or("invalid export tree")? { + let p = view.triangle(shared, placed, *id)?; + b = b.union(&bounds(p)); + if let Some(f) = front.get_mut(*id) { + // A positive projective scale preserves the projected winding. + *f = super::cross(xy(p[1] - p[0]), xy(p[2] - p[0])) > 0.; + } + } + } + if let Some(slot) = nodes.get_mut(i) { + *slot = b; + } + } + let mut result = Vec::new(); + let mut add = |a: Vec3, b: Vec3| -> Result<(), &'static str> { + let (a, b) = (view.project(apply_point(&placed.transform, a))?, view.project(apply_point(&placed.transform, b))?); + if xy(a).dist(xy(b)) > eps { + if !claim(segments, 1, MAX_SEGMENTS) { + return Err(TOO_COMPLEX); + } + result.push((a, b)); + } + Ok(()) + }; + for (i, edge) in shared.mesh.edges.iter().enumerate() { + if !placed.visibility.get(i).copied().unwrap_or(false) { + continue; + } + for w in edge.windows(2) { + if let (Some(a), Some(b)) = (w.first(), w.get(1)) { + add(*a, *b)?; + } + } + } + for edge in &shared.edges { + let mut positive = false; + let mut negative = false; + for id in shared.incident.get(edge.start..edge.end).ok_or("invalid export adjacency")? { + if front.get(*id).copied().ok_or("invalid export adjacency")? { + positive = true; + } else { + negative = true; + } + } + if (positive && negative) || edge.end - edge.start == 1 { + let a = shared.mesh.positions.get(edge.vertices[0] as usize).ok_or("invalid silhouette")?; + let b = shared.mesh.positions.get(edge.vertices[1] as usize).ok_or("invalid silhouette")?; + add(*a, *b)?; + } + } + Ok(Self { nodes, segments: result }) + } +} + +/// A sorted union, updated as occluders are found. A node's line interval already covered by +/// nearer triangles cannot change the result and is skipped before visiting its children. +#[derive(Default)] +struct Coverage { + spans: Vec<(f64, f64)>, +} +impl Coverage { + fn contains(&self, lo: f64, hi: f64) -> bool { + self.spans.iter().any(|(a, b)| *a <= lo && *b >= hi) + } + fn add(&mut self, mut lo: f64, mut hi: f64) -> Result<(), &'static str> { + let first = self.spans.partition_point(|(_, b)| *b + 1e-9 < lo); + let mut end = first; + while let Some((a, b)) = self.spans.get(end) { + if *a > hi + 1e-9 { + break; + } + lo = lo.min(*a); + hi = hi.max(*b); + end += 1; + } + if first == end && self.spans.len() >= MAX_LINES / 2 { + return Err(TOO_COMPLEX); + } + self.spans.splice(first..end, [(lo, hi)]); + Ok(()) + } +} + +fn rectangle(a: Vec3, b: Vec3, box_: &Aabb3) -> Option<(f64, f64)> { + let (mut lo, mut hi) = (0., 1.); + for (v0, v1) in [ + (a.x - box_.min.x, b.x - box_.min.x), + (box_.max.x - a.x, box_.max.x - b.x), + (a.y - box_.min.y, b.y - box_.min.y), + (box_.max.y - a.y, box_.max.y - b.y), + ] { + if !clip(&mut lo, &mut hi, v0, v1) { + return None; + } + } + Some((lo, hi)) +} + +struct Budget<'a> { + global: &'a AtomicUsize, + progress: &'a Stage, + local: usize, + spent: usize, +} +impl<'a> Budget<'a> { + fn new(global: &'a AtomicUsize, progress: &'a Stage) -> Self { + Self { global, progress, local: 0, spent: 0 } + } + fn spend(&mut self) -> Result<(), &'static str> { + if self.local == 0 { + self.progress.check()?; + let mut old = self.global.load(Ordering::Relaxed); + loop { + let granted = old.min(4096); + if granted == 0 { + return Err(TOO_COMPLEX); + } + match self.global.compare_exchange_weak(old, old - granted, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => { + self.local = granted; + break; + } + Err(current) => old = current, + } + } + } + self.local -= 1; + self.spent += 1; + Ok(()) + } +} + +struct Query<'a, 'b> { + shared: &'a [Shared], + scene: &'a Scene, + projected: &'a [Projected], + instances: &'a Bvh, + view: &'a View<'a>, + depth_eps: f64, + a: Vec3, + b: Vec3, + bounds: Aabb3, + covered: Coverage, + budget: &'b mut Budget<'a>, +} +impl Query<'_, '_> { + fn relevant(&self, b: &Aabb3) -> bool { + if b.max.z <= self.a.z.min(self.b.z) + self.depth_eps || !overlap(b, &self.bounds) { + return false; + } + rectangle(self.a, self.b, b).is_some_and(|(lo, hi)| !self.covered.contains(lo, hi)) + } + fn instance_node(&mut self, index: usize) -> Result<(), &'static str> { + self.budget.spend()?; + let node = self.instances.nodes.get(index).ok_or("invalid instance tree")?; + if !self.relevant(&node.bounds) { + return Ok(()); + } + if let Some((left, right)) = node.children { + let depth = |i: usize| self.instances.nodes.get(i).map_or(f64::NEG_INFINITY, |n| n.bounds.max.z); + let (near, far) = if depth(left) >= depth(right) { (left, right) } else { (right, left) }; + self.instance_node(near)?; + if !self.covered.contains(0., 1.) { + self.instance_node(far)?; + } + } else { + for id in self.instances.ids.get(node.start..node.end).ok_or("invalid instance tree")? { + self.mesh_node(*id, 0)?; + if self.covered.contains(0., 1.) { + break; + } + } + } + Ok(()) + } + fn mesh_node(&mut self, instance: usize, index: usize) -> Result<(), &'static str> { + self.budget.spend()?; + let placed = self.scene.placements.get(instance).ok_or("invalid instance")?; + let shared = self.shared.get(placed.mesh).ok_or("invalid shared geometry")?; + let projected = self.projected.get(instance).ok_or("invalid instance bounds")?; + let b = projected.nodes.get(index).ok_or("invalid mesh tree")?; + if !self.relevant(b) { + return Ok(()); + } + let node = shared.tree.nodes.get(index).ok_or("invalid mesh tree")?; + if let Some((left, right)) = node.children { + let depth = |i: usize| projected.nodes.get(i).map_or(f64::NEG_INFINITY, |b| b.max.z); + let (near, far) = if depth(left) >= depth(right) { (left, right) } else { (right, left) }; + self.mesh_node(instance, near)?; + if !self.covered.contains(0., 1.) { + self.mesh_node(instance, far)?; + } + } else { + for id in shared.tree.ids.get(node.start..node.end).ok_or("invalid mesh tree")? { + self.budget.spend()?; + let points = self.view.triangle(shared, placed, *id)?; + if let Some((lo, hi)) = occluded(self.a, self.b, points, self.depth_eps) { + self.covered.add(lo, hi)?; + if self.covered.contains(0., 1.) { + break; + } + } + } + } + Ok(()) + } +} + +pub(super) fn drawing(scene: &Scene, cam: &Camera) -> Result { + let start = Instant::now(); + let scale = scene + .placements + .iter() + .filter_map(|p| scene.meshes.get(p.mesh).map(|m| transformed_bounds(m, &p.transform))) + .fold(Aabb3::EMPTY, |b, p| b.union(&p)) + .diagonal() + .max(1.); + if !scale.is_finite() { + return Err("model contains invalid coordinates"); + } + let eps = scale * 1e-8; + // Indexed input can have many triangles but very few positions. Bound adjacency/sort + // scratch space as well as the retained mesh bytes before starting parallel builders. + let unique_triangles = scene.meshes.iter().try_fold(0usize, |n, m| n.checked_add(m.triangles.len())); + if unique_triangles.is_none_or(|n| n > MAX_SHARED_TRIANGLES) { + return Err("view exceeds export memory budget; hide bodies or increase tolerance"); + } + let progress = Stage::new("dxf_index", scene.meshes.len()); + let shared = parallel(&scene.meshes, |m| { + progress.check()?; + let shared = Shared::new(m, eps, &progress)?; + progress.advance(1)?; + Ok(shared) + })?; + let count = scene.placements.iter().try_fold(0usize, |n, p| n.checked_add(shared.get(p.mesh)?.tree.nodes.len())); + if count.is_none_or(|n| n > MAX_VIEW_NODES) { + return Err("view exceeds export memory budget; hide bodies or increase tolerance"); + } + let view = View::new(cam); + let count = AtomicUsize::new(0); + let progress = Stage::new("dxf_projection", scene.placements.len()); + let projected = parallel(&scene.placements, |p| { + progress.check()?; + let projected = Projected::new(shared.get(p.mesh).ok_or("missing shared geometry")?, p, &view, eps, &count, &progress)?; + progress.advance(1)?; + Ok(projected) + })?; + let boxes = projected.iter().map(|p| p.nodes.first().copied().unwrap_or(Aabb3::EMPTY)).collect::>(); + let mut instances = Bvh::new(&boxes, true); + // The view is fixed for the entire drawing. Sort the at-most-eight members of each + // instance leaf once, rather than allocating/sorting on every line query. + for node in instances.nodes.iter().filter(|n| n.children.is_none()) { + if let Some(ids) = instances.ids.get_mut(node.start..node.end) { + ids.sort_unstable_by(|a, b| { + boxes + .get(*b) + .map_or(f64::NEG_INFINITY, |b| b.max.z) + .total_cmp(&boxes.get(*a).map_or(f64::NEG_INFINITY, |b| b.max.z)) + .then_with(|| a.cmp(b)) + }); + } + } + let segment_count = count.load(Ordering::Relaxed); + let projection_ms = start.elapsed().as_secs_f64() * 1000.; + let start = Instant::now(); + let depth_eps = if cam.fov > 0. { 1e-8 / cam.distance } else { eps }; + let global = AtomicUsize::new(WORK); + let output = AtomicUsize::new(0); + let chunks = projected.iter().flat_map(|p| p.segments.chunks(128)).collect::>(); + let progress = Stage::new("dxf_occlusion", segment_count); + let results = parallel(&chunks, |chunk| { + progress.check()?; + let mut budget = Budget::new(&global, &progress); + let mut lines = Vec::new(); + for &(a, b) in *chunk { + let mut query = Query { + shared: &shared, + scene, + projected: &projected, + instances: &instances, + view: &view, + depth_eps, + a, + b, + bounds: bounds([a, b]), + covered: Coverage::default(), + budget: &mut budget, + }; + query.instance_node(0)?; + let mut cursor = 0.; + let mut emit = |lo: f64, hi: f64, hidden: bool| -> Result<(), &'static str> { + let (p, q) = (xy(a + (b - a) * lo), xy(a + (b - a) * hi)); + if p.dist(q) > eps { + if !claim(&output, 1, MAX_LINES) { + return Err(TOO_COMPLEX); + } + lines.push(Line { a: p, b: q, hidden }); + } + Ok(()) + }; + for (lo, hi) in query.covered.spans { + emit(cursor, lo, false)?; + emit(lo, hi, true)?; + cursor = hi; + } + emit(cursor, 1., false)?; + } + progress.advance(chunk.len())?; + Ok((lines, budget.spent)) + })?; + let work = results.iter().map(|(_, n)| *n).sum(); + let lines = merge_lines(results.into_iter().flat_map(|(lines, _)| lines).collect(), eps); + progress.check()?; + Ok(Drawing { lines, work, segments: segment_count, projection_ms, occlusion_ms: start.elapsed().as_secs_f64() * 1000. }) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn coverage_handles_disjoint_spans_and_early_complete_coverage() { + let mut c = Coverage::default(); + c.add(0.4, 0.6).unwrap(); + c.add(0., 0.2).unwrap(); + assert!(c.contains(0.05, 0.15)); + assert!(!c.contains(0., 1.)); + c.add(0.2, 0.9).unwrap(); + c.add(0.8, 1.).unwrap(); + assert_eq!(c.spans, vec![(0., 1.)]); + } + + fn box_mesh() -> Mesh { + let mut mesh = Mesh::default(); + mesh.positions = vec![ + Vec3::new(0., 0., 0.), + Vec3::new(8., 0., 0.), + Vec3::new(8., 6., 0.), + Vec3::new(0., 6., 0.), + Vec3::new(0., 0., 3.), + Vec3::new(8., 0., 3.), + Vec3::new(8., 6., 3.), + Vec3::new(0., 6., 3.), + ]; + mesh.triangles = + vec![[0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7], [0, 1, 5], [0, 5, 4], [1, 2, 6], [1, 6, 5], [2, 3, 7], [2, 7, 6], [3, 0, 4], [3, 4, 7]]; + mesh.edges = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7)] + .into_iter() + .map(|(a, b)| vec![mesh.positions[a], mesh.positions[b]]) + .collect(); + mesh + } + + fn canonical(lines: Vec) -> Vec<([i64; 2], [i64; 2], bool)> { + let k = |p: solidcraft_geom::Vec2| [(p.x * 1e6).round() as i64, (p.y * 1e6).round() as i64]; + let mut result = lines + .into_iter() + .map(|l| { + let (a, b) = (k(l.a), k(l.b)); + if a < b { (a, b, l.hidden) } else { (b, a, l.hidden) } + }) + .collect::>(); + result.sort_unstable(); + result + } + + #[test] + fn shared_rotated_instances_match_flat_occlusion_in_orthographic_and_perspective_views() { + use std::sync::Arc; + let mesh = box_mesh(); + let mut placements = Vec::new(); + let mut flat = Vec::new(); + for (offset, angle) in [(Vec3::ZERO, 0.), (Vec3::new(3., 2., 4.), 0.3), (Vec3::new(2., 1., -4.), -0.6)] { + let transform = solidcraft_doc::rigid(offset, Vec3::ZERO, Vec3::Z, angle); + placements.push(Placement { mesh: 0, transform, visibility: vec![true; mesh.edges.len()] }); + let mut placed = mesh.clone(); + placed.positions = placed.positions.iter().map(|p| apply_point(&transform, *p)).collect(); + placed.edges = placed.edges.iter().map(|e| e.iter().map(|p| apply_point(&transform, *p)).collect()).collect(); + flat.push(placed); + } + let scene = Scene { meshes: vec![Arc::new(mesh)], placements, triangles: 36, bytes: 0 }; + for (yaw, pitch, roll) in [(0., std::f64::consts::FRAC_PI_2, 0.), (0.7, 0.4, 0.2), (0., 0., 0.)] { + for fov in [0., 0.6] { + let cam = Camera { target: Vec3::new(4., 3., 1.), yaw, pitch, roll, fov, distance: 100., ..Default::default() }; + let expected = super::super::reference_drawing(&flat, &cam).unwrap(); + let actual = drawing(&scene, &cam).unwrap(); + assert_eq!(canonical(actual.lines), canonical(expected), "yaw={yaw}, pitch={pitch}, fov={fov}"); + } + } + } + + #[test] + fn repeated_surface_over_one_million_triangles_keeps_one_mesh_and_exports_all_placements() { + use solidcraft_render::StandardView; + use std::sync::Arc; + let mut mesh = Mesh::default(); + for y in 0..=100 { + for x in 0..=100 { + mesh.positions.push(Vec3::new(x as f64 / 10., y as f64 / 10., 0.)); + } + } + for y in 0..100u32 { + for x in 0..100u32 { + let a = y * 101 + x; + mesh.triangles.extend([[a, a + 1, a + 102], [a, a + 102, a + 101]]); + } + } + mesh.edges = vec![ + vec![Vec3::ZERO, Vec3::new(10., 0., 0.)], + vec![Vec3::new(10., 0., 0.), Vec3::new(10., 10., 0.)], + vec![Vec3::new(10., 10., 0.), Vec3::new(0., 10., 0.)], + vec![Vec3::new(0., 10., 0.), Vec3::ZERO], + ]; + let placements = (0..60) + .map(|i| Placement { + mesh: 0, + transform: solidcraft_doc::rigid(Vec3::new((i % 10) as f64 * 20., (i / 10) as f64 * 20., 0.), Vec3::ZERO, Vec3::Z, 0.), + visibility: vec![true; 4], + }) + .collect(); + let scene = Scene { meshes: vec![Arc::new(mesh)], placements, triangles: 1_200_000, bytes: 0 }; + let mut cam = Camera { target: Vec3::new(95., 55., 0.), fov: 0., distance: 300., ..Default::default() }; + cam.set_view(StandardView::Top); + let result = drawing(&scene, &cam).unwrap(); + assert_eq!(scene.meshes.len(), 1); + assert_eq!(result.lines.len(), 240); + assert!(result.lines.iter().all(|l| !l.hidden)); + } +} diff --git a/crates/engine/src/cmd/view_dxf_tests.rs b/crates/engine/src/cmd/view_dxf_tests.rs index 3b6242a63..9b8c37e48 100644 --- a/crates/engine/src/cmd/view_dxf_tests.rs +++ b/crates/engine/src/cmd/view_dxf_tests.rs @@ -21,6 +21,49 @@ fn export(s: &mut Session, c: Camera, hidden: &str) -> Value { run(s, CMD, json!({"camera":c,"hidden":hidden})) } +#[test] +fn view_dxf_cancellation_at_each_stage_preserves_the_destination_and_document() { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + struct CancelAt { + stage: &'static str, + cancelled: AtomicBool, + reached: AtomicBool, + } + impl solidcraft_kernel::watch::Watch for CancelAt { + fn cancelled(&self) -> bool { + self.cancelled.load(Ordering::Relaxed) + } + fn progress(&self, stage: &'static str, done: usize, _total: usize) { + if stage == self.stage && (done > 0 || stage == "dxf_write") { + self.reached.store(true, Ordering::Relaxed); + self.cancelled.store(true, Ordering::Relaxed); + } + } + } + let dir = std::env::temp_dir().join(format!("solidcraft-dxf-cancel-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("drawing.dxf"); + let mut s = sample(); + let doc = s.doc.clone(); + let undo = s.undo.len(); + for stage in ["dxf_meshes", "dxf_index", "dxf_projection", "dxf_occlusion", "dxf_write"] { + std::fs::write(&path, b"previous drawing").unwrap(); + let watch = Arc::new(CancelAt { stage, cancelled: AtomicBool::new(false), reached: AtomicBool::new(false) }); + let result = solidcraft_kernel::watch::watching(watch.clone(), || { + s.execute(CMD, &json!({"camera":camera(StandardView::Top),"path":path.to_string_lossy()})) + }); + assert!(result.unwrap_err().to_string().contains("cancelled"), "{stage}"); + assert!(watch.reached.load(Ordering::Relaxed), "{stage}"); + assert_eq!(std::fs::read(&path).unwrap(), b"previous drawing", "{stage}"); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert_eq!(s.undo.len(), undo); + } + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn view_dxf_blind_back_hole_is_omitted_or_dashed_and_front_hole_is_visible() { let mut s = sample(); @@ -100,3 +143,32 @@ fn view_dxf_rejects_invalid_options_and_near_eye_geometry_without_panicking() { c.fov = 4.; assert!(s.execute(CMD, &json!({"camera":c})).is_err()); } + +#[test] +fn view_dxf_keeps_every_occurrence_while_sharing_geometry() { + let mut s = Session::default(); + let component = run(&mut s, "component.create", json!({"name":"Repeated part"}))["component"].as_u64().unwrap(); + run(&mut s, "solid.box", json!({"length":8,"width":6,"height":3})); + for x in [15., 30.] { + run(&mut s, "occurrence.copy", json!({"component":component,"translate":[x,0,0]})); + } + run(&mut s, "component.activate", json!({"component":0})); + let doc = s.doc.clone(); + let result = export(&mut s, camera(StandardView::Top), "dashed"); + assert_eq!(result["stats"]["bodies"], 3); + assert_eq!(result["stats"]["shared_meshes"], 1); + assert_eq!(result["stats"]["worker_limit"], meshes::WORKERS); + assert!(result["hidden"].as_u64().unwrap() > 0); + let lines = solidcraft_io::read_dxf(result["dxf"].as_str().unwrap()).unwrap(); + let mut centers = std::collections::BTreeSet::new(); + for line in lines { + if let solidcraft_io::Geom2::Line(a, b) = line { + // Each translated copy has a visible top perimeter, including the offscreen one. + if (a.y - b.y).abs() > 5.9 { + centers.insert(((a.x + 20.) / 15.).floor() as i64); + } + } + } + assert!(centers.len() >= 3, "{centers:?}"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.doc)); +} diff --git a/crates/engine/src/render_jobs.rs b/crates/engine/src/render_jobs.rs index 267e171d4..a9b40cef3 100644 --- a/crates/engine/src/render_jobs.rs +++ b/crates/engine/src/render_jobs.rs @@ -77,12 +77,13 @@ impl Jobs { Ok(()) } - pub(crate) fn start( + pub(crate) fn start_with_environment( &mut self, revision: u64, scene: solidcraft_render::ProductScene, request: solidcraft_render::job::ImageRequest, replace: bool, + environment: Option, ) -> Result { self.collect()?; let host = self.host.as_ref().ok_or_else(|| JobError::new(ErrorCode::HostUnavailable, "no image host is installed"))?.clone(); @@ -109,7 +110,7 @@ impl Jobs { } let serial = self.serial.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "render job identity exhausted"))?; let generation = self.generation.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "render generation exhausted"))?; - let handle = host.submit(JobId { session: self.owner, serial, generation }, revision, scene, request)?; + let handle = host.submit_with_environment(JobId { session: self.owner, serial, generation }, revision, scene, request, environment)?; let status = handle.status()?; self.serial = serial; self.generation = generation; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c5c419f8d..db68167a5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -512,6 +512,30 @@ fn revolve_and_primitives() { assert!(rel(m["total"]["volume_mm3"].as_f64().unwrap(), PI * 125.0 * 5.0 / 2.0) < 5e-4); } +/// #726: a revolve swept each profile edge into two or three patches and left the planar ones +/// apart, so a pick on such a face took part of it, and a sketch or an extrude there was refused +/// ("the selected planar face no longer exists") until a later feature merged them. +#[test] +fn revolved_planar_faces_come_out_whole() { + for angle in [360, 240] { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XZ"})); + run(&mut s, "sketch.line", json!({"points": [[8, 0], [30, 0], [30, -6], [18, -6], [18, -22], [8, -22]], "closed": true})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.revolve", json!({"axis": "Z", "angle": angle})); + // Picks at 170°, in the last patch, which 240° covers whichever way it turns. + let at = |r: f64, z: f64| json!([r * 170f64.to_radians().cos(), r * 170f64.to_radians().sin(), z]); + // The flange's top annulus (z = 6, r 18…30), well inside it. + let sk = run(&mut s, "sketch.create", json!({"plane": {"face": at(24.0, 6.0)}})); + assert_eq!(sk["attachment"], "exact_face", "{angle}°: {sk}"); + run(&mut s, "sketch.finish", json!({})); + // The bottom annulus (z = 0, r 8…30). + let v = volume(&mut s); + run(&mut s, "solid.extrude", json!({"face": at(20.0, 0.0), "distance": 2, "operation": "join"})); + assert!(volume(&mut s) > v + 1.0, "{angle}°: the extrude added nothing"); + } +} + /// A spherical shell (a half ring between two arcs, both radial lines on the axis) revolved on a /// sketch plane that does not pass through the origin: the body is the shell, as it is on XY. /// Before, built in place, it measured a third too large (truck tessellates the degenerate faces @@ -1196,6 +1220,43 @@ fn extrude_auto_operation() { assert!(rel(volume(&mut s), 40.0 * 30.0 * 15.0 - 100.0 * 8.0) < 1e-6); } +/// #1666: a loft between two 18-point polylines has twisted (bilinear) side faces. Each was +/// meshed as two flat triangles, which cross the surface; the mesh volume was 16 800.6 mm³ +/// against the B-rep's 17 884. Divided to the chord tolerance, the mesh matches the B-rep. +#[test] +fn twisted_ruled_faces_are_meshed_to_the_chord_tolerance() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Bottom"})); + run( + &mut s, + "sketch.line", + json!({"closed": true, "infer": false, "connect": false, "points": [[-26,3],[-24.76384,3],[-16.0568,14.97217],[-8,4.90117],[0,14.90117],[8,4.90117],[16.0568,14.97217],[24.76384,3],[26,3],[26,0],[23.23616,0],[15.9432,10.02783],[8,0.09883],[0,10.09883],[-8,0.09883],[-15.9432,10.02783],[-23.23616,0],[-26,0]]}), + ); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 90.5, "name": "Top"})); + run( + &mut s, + "sketch.line", + json!({"closed": true, "infer": false, "connect": false, "points": [[-26,3],[-24,3],[-16,3],[-8,3],[0,3],[8,3],[16,3],[24,3],[26,3],[26,0],[24,0],[16,0],[8,0],[0,0],[-8,0],[-16,0],[-24,0],[-26,0]]}), + ); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.loft", json!({"sections": [{"sketch": "Bottom"}, {"sketch": "Top"}], "operation": "new"})); + let st = s.model.state(); + let body = &st.bodies.first().unwrap().body; + let exact = solidcraft_kernel::measure(body).unwrap().volume; + let mesh = body.tessellate(0.05).unwrap(); + let volume: f64 = mesh + .triangles + .iter() + .map(|t| { + let p = |i: u32| mesh.positions[i as usize]; + p(t[0]).dot(p(t[1]).cross(p(t[2]))) / 6.0 + }) + .sum(); + assert!(mesh.triangles.len() > 72, "the twisted faces are divided: {} triangles", mesh.triangles.len()); + assert!(rel(volume.abs(), exact) < 2e-3, "mesh {volume} against B-rep {exact}"); +} + /// #1633: to an object, the extrude goes to it on whichever side it is, whatever its /// `direction`: through the body to its far face is a Cut, out to something above is a Join. #[test] @@ -1217,6 +1278,41 @@ fn extrude_auto_operation_follows_the_to_object() { assert_eq!(extrude_reach(&s, &json!({"face": [20, 15, 20], "distance": 5, "direction": "negative"})), Some(-5.0)); } +/// #1678: a hole's `position` takes length expressions, keeps them and follows the parameters: a +/// hole on a plate's middle line stays there when the plate gets wider. A position of plain +/// numbers is stored as before, with no `at`. +#[test] +fn a_hole_position_of_expressions_follows_the_parameters() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "width", "expression": "30 mm"})); + run(&mut s, "parameters.add", json!({"name": "t", "expression": "4 mm"})); + run(&mut s, "solid.box", json!({"length": 100, "width": "width", "height": "t", "body_name": "Plate"})); + run(&mut s, "solid.hole", json!({"position": ["40", "width/2", "t"], "clearance": "M5", "name": "Middle"})); + run(&mut s, "solid.hole", json!({"position": [80, 10, 4], "clearance": "M5", "name": "Fixed"})); + let centre_y = |s: &Session| { + let st = s.model.state(); + solidcraft_kernel::measure(&st.body("Plate").unwrap().body).unwrap().centroid.y + }; + let hole = |s: &Session, name: &str| -> Value { + let saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + saved["features"].as_array().and_then(|f| f.iter().find(|f| f["name"] == name)).cloned().unwrap() + }; + assert_eq!(hole(&s, "Middle")["at"], json!([40.0, "width/2", "t"]), "the expressions are kept"); + assert!(hole(&s, "Fixed").get("at").is_none(), "plain numbers are stored as before"); + // The fixed hole sits off the middle line, so it alone moves the centre; widen the plate. + let before = centre_y(&s); + run(&mut s, "parameters.change", json!({"name": "width", "expression": "40 mm"})); + let after = centre_y(&s); + // The middle hole is at y = 20 now (the plate's middle); the fixed one stays at y = 10. With + // the middle hole left at y = 15 the centre would sit lower still. + let plate = 100.0 * 40.0 * 4.0; + let hole_v = std::f64::consts::PI * (5.5f64 / 2.0).powi(2) * 4.0; + let want = (plate * 20.0 - hole_v * 20.0 - hole_v * 10.0) / (plate - 2.0 * hole_v); + assert!((after - want).abs() < 1e-3, "centre y {after}, want {want} (was {before})"); + // A bad expression is refused. + assert!(s.execute("solid.hole", &json!({"position": ["40", "nope/2", "t"], "diameter": 3})).is_err()); +} + /// Additive extrusions default to joining even when only a profile side touches material. #[test] fn auto_extrude_joins_side_contact_elbow_and_keeps_new_body_explicit() { diff --git a/crates/engine/src/thread_tests.rs b/crates/engine/src/thread_tests.rs index 906fcb62f..3b725197b 100644 --- a/crates/engine/src/thread_tests.rs +++ b/crates/engine/src/thread_tests.rs @@ -22,6 +22,18 @@ fn volume(s: &mut Session, b: &str) -> f64 { const SIZES: [(f64, f64); 9] = [(3.0, 0.5), (4.0, 0.7), (5.0, 0.8), (6.0, 1.0), (8.0, 1.25), (10.0, 1.5), (12.0, 1.75), (16.0, 2.0), (20.0, 2.5)]; +#[test] +fn non_finite_thread_designations_are_refused_without_changing_the_design() { + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius":4,"height":10})); + let saved = s.doc.to_json(); + for designation in ["Minfx1", "M8xinf", "MNaNx1", "M8xNaN", "M1e999x1"] { + let result = s.execute("solid.thread", &json!({"face":[4,0,2],"designation":designation})); + assert!(result.is_err(), "{designation}: {result:?}"); + assert_eq!(s.doc.to_json(), saved); + } +} + /// ∫ 2π r · width(r) dr over [a, b]: the volume one turn of the groove takes out (a screw /// motion of a section in an axial plane sweeps 2π∫r dA per turn). fn per_turn(a: f64, b: f64, width: impl Fn(f64) -> f64) -> f64 { diff --git a/crates/engine/tests/mesh_export_regressions.rs b/crates/engine/tests/mesh_export_regressions.rs new file mode 100644 index 000000000..1d51267a2 --- /dev/null +++ b/crates/engine/tests/mesh_export_regressions.rs @@ -0,0 +1,77 @@ +//! Mesh export regressions: a closed body exports as a closed mesh. + +use std::collections::HashMap; + +use serde_json::{Value, json}; +use solidcraft_engine::Session; +use solidcraft_io::{Format, export, read_3mf, read_stl}; + +fn run(s: &mut Session, script: Value) { + for c in script.as_array().into_iter().flatten() { + let (id, p) = (c["command"].as_str().unwrap_or_default(), &c["params"]); + if let Err(e) = s.execute(id, p) { + panic!("{id} {p}: {e}"); + } + } +} + +/// The edges (by vertex index) that are not used by exactly two triangles. +fn open_edges(triangles: &[[u32; 3]]) -> Vec<((u32, u32), u32)> { + let mut uses: HashMap<(u32, u32), u32> = HashMap::new(); + for t in triangles { + for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + *uses.entry((a.min(b), a.max(b))).or_default() += 1; + } + } + uses.into_iter().filter(|(_, n)| *n != 2).collect() +} + +/// A bowl section (lines and arcs) revolved about Z, its rim cut by a large cylinder across it. +/// The edge where the cylinder meets the inner cone is an intersection curve; one of its samples +/// lay a few ten-thousandths of a millimetre off both surfaces, each face put the point on its +/// own surface, and the exported mesh had a crack there (four edges used once). +#[test] +fn a_rim_cut_by_a_cylinder_exports_closed() { + let mut s = Session::default(); + run( + &mut s, + json!([ + {"command": "sketch.create", "params": {"plane": "XZ", "name": "Section"}}, + {"command": "sketch.line", "params": {"points": [[0, 0], [48.8, 0], [50.0240096077, -1.2]]}}, + {"command": "sketch.arc.three_point", "params": {"start": [50.0240096077, -1.2], "end": [58.7867965644, -21.2132034356], "through": [52.5188160894, -12.0326443841]}}, + {"command": "sketch.line", "params": {"points": [[58.7867965644, -21.2132034356], [85.5735931288, -48], [82.1794805791, -48], [57.0897402896, -22.9102597104]]}}, + {"command": "sketch.arc.three_point", "params": {"start": [57.0897402896, -22.9102597104], "end": [48.3846976331, -7.0875], "through": [51.6125175266, -15.6176451113]}}, + {"command": "sketch.arc.three_point", "params": {"start": [48.3846976331, -7.0875], "end": [42.5300120096, -2.4], "through": [46.2800120096, -3.7162515012]}}, + {"command": "sketch.line", "params": {"points": [[42.5300120096, -2.4], [0, -2.4], [0, 0]]}}, + {"command": "sketch.finish", "params": {}}, + {"command": "solid.revolve", "params": {"sketch": "Section", "axis": "Z"}}, + {"command": "sketch.create", "params": {"plane": "YZ", "name": "RimCutter"}}, + {"command": "sketch.arc.three_point", "params": {"start": [-100, 11.6204810674], "end": [100, 46.4045454912], "through": [-52, 8]}}, + {"command": "sketch.line", "params": {"points": [[100, 46.4045454912], [100, 70], [-100, 70], [-100, 11.6204810674]]}}, + {"command": "sketch.finish", "params": {}}, + {"command": "solid.extrude", "params": {"sketch": "RimCutter", "distance": 200, "direction": "symmetric", "operation": "cut"}} + ]), + ); + let st = s.model.state(); + assert_eq!(st.bodies.len(), 1); + + let (objects, _) = read_3mf(&export(&st, &[], Format::ThreeMf, "cove").unwrap()).unwrap(); + assert_eq!(objects.len(), 1); + let open = open_edges(&objects[0].triangles); + assert!(open.is_empty(), "3MF: {} edges not used twice, e.g. {:?}", open.len(), open.first()); + + // STL has no indices: vertices are the same where their coordinates are. + let mut index: HashMap<[u32; 3], u32> = HashMap::new(); + let triangles: Vec<[u32; 3]> = read_stl(&export(&st, &[], Format::StlBinary, "cove").unwrap()) + .unwrap() + .iter() + .map(|t| { + t.map(|p| { + let n = index.len() as u32; + *index.entry(p.map(f32::to_bits)).or_insert(n) + }) + }) + .collect(); + let open = open_edges(&triangles); + assert!(open.is_empty(), "STL: {} edges not used twice, e.g. {:?}", open.len(), open.first()); +} diff --git a/crates/geom/src/bvh.rs b/crates/geom/src/bvh.rs new file mode 100644 index 000000000..24c5dc804 --- /dev/null +++ b/crates/geom/src/bvh.rs @@ -0,0 +1,270 @@ +//! A bounding volume hierarchy over boxes: the nearest hit along a ray, or every item whose box +//! passes a test, without looking at each item. Built once (median split on the widest axis of +//! the box centres, a few items per leaf) and only read afterwards. [`MeshIndex`] holds one over +//! a mesh's triangles and one over its edge segments, for picking. + +use crate::{Aabb3, Mesh, Vec3}; + +/// Most items in a leaf. +const LEAF: usize = 4; + +#[derive(Clone, Copy, Debug)] +struct Node { + bounds: Aabb3, + /// A leaf: the first of its `count` items in [`Bvh::order`]. Otherwise its children are + /// `first` and `first + 1`. + first: u32, + count: u32, +} + +/// A hierarchy over boxes; items are the boxes' indices. +#[derive(Clone, Debug, Default)] +pub struct Bvh { + nodes: Vec, + order: Vec, +} + +impl Bvh { + /// The hierarchy over `boxes` (empty boxes are left out). + pub fn new(boxes: &[Aabb3]) -> Bvh { + let mut order: Vec = + (0..boxes.len().min(u32::MAX as usize)).filter(|&i| boxes.get(i).is_some_and(|b| !b.is_empty() && finite(b))).map(|i| i as u32).collect(); + if order.is_empty() { + return Bvh::default(); + } + let item = |i: u32| boxes.get(i as usize).copied().unwrap_or(Aabb3::EMPTY); + let centre = |i: u32| item(i).center(); + let mut nodes = vec![Node { bounds: Aabb3::EMPTY, first: 0, count: 0 }]; + // (node, start, end) in `order` still to be filled in. + let mut todo = vec![(0usize, 0usize, order.len())]; + while let Some((n, start, end)) = todo.pop() { + let Some(span) = order.get_mut(start..end) else { continue }; + let mut bounds = Aabb3::EMPTY; + let mut centres = Aabb3::EMPTY; + for &i in span.iter() { + bounds = bounds.union(&item(i)); + centres.add(centre(i)); + } + let size = centres.size(); + let axis = if size.x >= size.y && size.x >= size.z { + 0 + } else if size.y >= size.z { + 1 + } else { + 2 + }; + let extent = [size.x, size.y, size.z][axis]; + if span.len() <= LEAF || !(extent > 0.0) { + if let Some(node) = nodes.get_mut(n) { + *node = Node { bounds, first: start as u32, count: span.len() as u32 }; + } + continue; + } + let key = |i: &u32| { + let c = centre(*i); + [c.x, c.y, c.z][axis] + }; + let mid = span.len() / 2; + span.select_nth_unstable_by(mid, |a, b| key(a).total_cmp(&key(b))); + let left = nodes.len(); + nodes.push(Node { bounds: Aabb3::EMPTY, first: 0, count: 0 }); + nodes.push(Node { bounds: Aabb3::EMPTY, first: 0, count: 0 }); + if let Some(node) = nodes.get_mut(n) { + *node = Node { bounds, first: left as u32, count: 0 }; + } + todo.push((left, start, start + mid)); + todo.push((left + 1, start + mid, end)); + } + Bvh { nodes, order } + } + + /// The box around everything (empty for no items). + pub fn bounds(&self) -> Aabb3 { + self.nodes.first().map_or(Aabb3::EMPTY, |n| n.bounds) + } + + /// Calls `item` with every item in a leaf whose box, and every box above it, `enter` accepts. + pub fn visit(&self, mut enter: impl FnMut(&Aabb3) -> bool, mut item: impl FnMut(u32)) { + let mut stack = vec![0usize]; + while let Some(n) = stack.pop() { + let Some(node) = self.nodes.get(n) else { continue }; + if !enter(&node.bounds) { + continue; + } + if node.count > 0 { + let (a, b) = (node.first as usize, node.first as usize + node.count as usize); + for &i in self.order.get(a..b).unwrap_or(&[]) { + item(i); + } + } else { + stack.push(node.first as usize + 1); + stack.push(node.first as usize); + } + } + } + + /// The nearest item along the ray from `o` along `d`: `hit` gives an item's distance along + /// `d` (`None`: missed). Equal distances go to the lowest item, as a scan in item order + /// keeping strictly nearer hits would answer. Boxes are entered nearest first, and one that + /// starts past the best hit so far is skipped. + pub fn nearest(&self, o: Vec3, d: Vec3, mut hit: impl FnMut(u32) -> Option) -> Option<(f64, u32)> { + if ![o.x, o.y, o.z, d.x, d.y, d.z].iter().all(|v| v.is_finite()) { + return None; + } + let inv = Vec3::new(1.0 / d.x, 1.0 / d.y, 1.0 / d.z); + let mut best: Option<(f64, u32)> = None; + let root = self.nodes.first().and_then(|n| ray_box(o, d, inv, &n.bounds, 0.0))?; + let mut stack = vec![(0usize, root)]; + while let Some((n, t0)) = stack.pop() { + if best.is_some_and(|(bt, _)| t0 > bt) { + continue; + } + let Some(node) = self.nodes.get(n) else { continue }; + if node.count > 0 { + let (a, b) = (node.first as usize, node.first as usize + node.count as usize); + for &i in self.order.get(a..b).unwrap_or(&[]) { + if let Some(t) = hit(i) + && best.is_none_or(|(bt, bi)| t < bt || (t == bt && i < bi)) + { + best = Some((t, i)); + } + } + continue; + } + let (l, r) = (node.first as usize, node.first as usize + 1); + let tl = self.nodes.get(l).and_then(|c| ray_box(o, d, inv, &c.bounds, 0.0)); + let tr = self.nodes.get(r).and_then(|c| ray_box(o, d, inv, &c.bounds, 0.0)); + // The nearer child is popped first. + match (tl, tr) { + (Some(a), Some(b)) if a <= b => stack.extend([(r, b), (l, a)]), + (Some(a), Some(b)) => stack.extend([(l, a), (r, b)]), + (Some(a), None) => stack.push((l, a)), + (None, Some(b)) => stack.push((r, b)), + (None, None) => {} + } + } + best + } +} + +fn finite(b: &Aabb3) -> bool { + [b.min.x, b.min.y, b.min.z, b.max.x, b.max.y, b.max.z].iter().all(|v| v.is_finite()) +} + +/// Where the ray from `o` along `d` (`inv` = 1 / `d` per axis) enters box `b` grown by `pad`, +/// from 0 on; `None` when it misses or the box lies behind. +fn ray_box(o: Vec3, d: Vec3, inv: Vec3, b: &Aabb3, pad: f64) -> Option { + let (mut t0, mut t1) = (0.0f64, f64::INFINITY); + for (o, d, inv, lo, hi) in [(o.x, d.x, inv.x, b.min.x, b.max.x), (o.y, d.y, inv.y, b.min.y, b.max.y), (o.z, d.z, inv.z, b.min.z, b.max.z)] { + let (lo, hi) = (lo - pad, hi + pad); + if d == 0.0 || !inv.is_finite() { + if o < lo || o > hi { + return None; + } + continue; + } + let (a, b) = ((lo - o) * inv, (hi - o) * inv); + let (a, b) = if a <= b { (a, b) } else { (b, a) }; + t0 = t0.max(a); + t1 = t1.min(b); + if t0 > t1 { + return None; + } + } + (t0 <= t1).then_some(t0) +} + +/// The farthest any corner of `b` lies along `d` from `o` (0 when the box is behind). +fn farthest_along(o: Vec3, d: Vec3, b: &Aabb3) -> f64 { + let along = |lo: f64, hi: f64, o: f64, d: f64| if d >= 0.0 { (hi - o) * d } else { (lo - o) * d }; + (along(b.min.x, b.max.x, o.x, d.x) + along(b.min.y, b.max.y, o.y, d.y) + along(b.min.z, b.max.z, o.z, d.z)).max(0.0) +} + +/// A mesh's triangles and edge segments in hierarchies, for picking: the nearest triangle along +/// a ray, and the edge segments near one. Built from one mesh and answers only for it. +#[derive(Clone, Debug, Default)] +pub struct MeshIndex { + triangles: Bvh, + triangle_count: usize, + segments: Bvh, + /// Per segment item: its edge, and its first point in that edge's polyline. + segment_of: Vec<(u32, u32)>, +} + +impl MeshIndex { + /// The index of `mesh`. + pub fn new(mesh: &Mesh) -> MeshIndex { + let pad = |mut b: Aabb3| { + // Flat boxes (a triangle square to an axis) are grown a little, so a ray through + // them is never lost to rounding in the box test. + let scale = [b.min.x, b.min.y, b.min.z, b.max.x, b.max.y, b.max.z].iter().fold(1.0f64, |m, v| m.max(v.abs())); + let e = scale * 1e-9; + b.min -= Vec3::new(e, e, e); + b.max += Vec3::new(e, e, e); + b + }; + let boxes: Vec = mesh + .triangles + .iter() + .map(|t| { + let mut b = Aabb3::EMPTY; + for p in mesh.tri(t).into_iter().flatten() { + b.add(p); + } + if b.is_empty() { b } else { pad(b) } + }) + .collect(); + let mut segment_of = Vec::new(); + let mut seg_boxes = Vec::new(); + for (ei, e) in mesh.edges.iter().enumerate() { + // A one-point edge still has its vertex: it stands as a segment from it to itself. + let n = if e.len() == 1 { 1 } else { e.len().saturating_sub(1) }; + for si in 0..n { + let (Some(a), Some(b)) = (e.get(si), e.get(si + 1).or(e.get(si))) else { continue }; + let mut bx = Aabb3::EMPTY; + bx.add(*a); + bx.add(*b); + seg_boxes.push(pad(bx)); + segment_of.push((ei as u32, si as u32)); + } + } + MeshIndex { triangles: Bvh::new(&boxes), triangle_count: mesh.triangles.len(), segments: Bvh::new(&seg_boxes), segment_of } + } + + /// [`Mesh::raycast`] through the index: the same answer, including which triangle wins a tie. + /// For a mesh other than the one indexed, the plain scan answers. + pub fn raycast(&self, mesh: &Mesh, o: Vec3, dir: Vec3) -> Option<(f64, usize)> { + if mesh.triangles.len() != self.triangle_count { + return mesh.raycast(o, dir); + } + let frame = crate::mesh::RayFrame::new(o, dir)?; + self.triangles + .nearest(o, dir, |i| mesh.triangles.get(i as usize).and_then(|t| mesh.tri(t)).and_then(|p| frame.hit(p))) + .map(|(t, i)| (t, i as usize)) + } + + /// Calls `f(edge, first point)` for every edge segment that may come within `a + b·t` of the + /// ray from `o` along unit `d`, `t` being the distance along it (each at most once). A + /// constant `a` suits an orthographic view; a perspective view widens with `b`. + pub fn segments_near(&self, o: Vec3, d: Vec3, a: f64, b: f64, mut f: impl FnMut(usize, usize)) { + if ![a, b, o.x, o.y, o.z, d.x, d.y, d.z].iter().all(|v| v.is_finite()) { + return; + } + let inv = Vec3::new(1.0 / d.x, 1.0 / d.y, 1.0 / d.z); + self.segments.visit( + |bx| { + let reach = a.max(0.0) + b.max(0.0) * farthest_along(o, d, bx); + ray_box(o, d, inv, bx, reach).is_some() + }, + |i| { + if let Some((e, s)) = self.segment_of.get(i as usize) { + f(*e as usize, *s as usize); + } + }, + ); + } +} + +#[cfg(test)] +#[path = "bvh_tests.rs"] +mod tests; diff --git a/crates/geom/src/bvh_tests.rs b/crates/geom/src/bvh_tests.rs new file mode 100644 index 000000000..f551e963d --- /dev/null +++ b/crates/geom/src/bvh_tests.rs @@ -0,0 +1,130 @@ +use super::*; + +/// A small deterministic generator (the tests need no crate for randomness). +struct Lcg(u64); + +impl Lcg { + fn next(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } + fn range(&mut self, lo: f64, hi: f64) -> f64 { + lo + (hi - lo) * self.next() + } + fn vec(&mut self, r: f64) -> Vec3 { + Vec3::new(self.range(-r, r), self.range(-r, r), self.range(-r, r)) + } +} + +/// A grid of `n` × `n` squares of two triangles on z = 0, and `extra` random triangles above. +fn mesh(n: u32, extra: usize, rng: &mut Lcg) -> Mesh { + let mut positions: Vec = (0..=n).flat_map(|j| (0..=n).map(move |i| Vec3::new(f64::from(i), f64::from(j), 0.0))).collect(); + let id = |i: u32, j: u32| j * (n + 1) + i; + let mut triangles = Vec::new(); + for j in 0..n { + for i in 0..n { + triangles.push([id(i, j), id(i + 1, j), id(i + 1, j + 1)]); + triangles.push([id(i, j), id(i + 1, j + 1), id(i, j + 1)]); + } + } + for _ in 0..extra { + let c = rng.vec(f64::from(n)) + Vec3::new(0.0, 0.0, f64::from(n)); + let k = positions.len() as u32; + positions.extend([c + rng.vec(1.5), c + rng.vec(1.5), c + rng.vec(1.5)]); + triangles.push([k, k + 1, k + 2]); + } + let edges = + (0..n).map(|i| (0..=n).map(|j| Vec3::new(f64::from(i), f64::from(j), 0.0)).collect()).chain([vec![Vec3::new(0.5, 0.5, 2.0)]]).collect(); + Mesh { tri_face: vec![0; triangles.len()], positions, triangles, edges, ..Default::default() } +} + +#[test] +fn indexed_raycast_answers_as_the_scan_does() { + let mut rng = Lcg(7); + let m = mesh(12, 400, &mut rng); + let index = MeshIndex::new(&m); + let mut hits = 0; + for k in 0..4000 { + // Every few rays go straight down through grid vertices and edges, where two or more + // triangles tie. + let (o, d) = if k % 4 == 0 { + let p = Vec3::new(f64::from(k % 13), f64::from((k / 13) % 13) * 0.5, 50.0); + (p, Vec3::new(0.0, 0.0, -1.0)) + } else { + let o = rng.vec(40.0) + Vec3::new(6.0, 6.0, 0.0); + let target = Vec3::new(rng.range(-1.0, 13.0), rng.range(-1.0, 13.0), rng.range(-2.0, 14.0)); + let Some(d) = (target - o).normalized() else { continue }; + (o, d) + }; + let want = m.raycast(o, d); + assert_eq!(index.raycast(&m, o, d), want, "ray {k} from {o:?} along {d:?}"); + hits += usize::from(want.is_some()); + } + assert!(hits > 1000, "the rays should mostly hit ({hits})"); +} + +#[test] +fn indexed_raycast_of_another_mesh_falls_back_to_the_scan() { + let mut rng = Lcg(3); + let (a, b) = (mesh(2, 0, &mut rng), mesh(5, 0, &mut rng)); + let index = MeshIndex::new(&a); + let (o, d) = (Vec3::new(4.5, 4.2, 9.0), Vec3::new(0.0, 0.0, -1.0)); + assert!(b.raycast(o, d).is_some()); + assert_eq!(index.raycast(&b, o, d), b.raycast(o, d)); +} + +/// Distance from point `p` to the ray from `o` along unit `d` (from its start on), and how far along. +fn ray_point(o: Vec3, d: Vec3, p: Vec3) -> (f64, f64) { + let t = (p - o).dot(d).max(0.0); + ((o + d * t).dist(p), t) +} + +#[test] +fn segments_near_the_ray_are_all_reported() { + let mut rng = Lcg(11); + let m = mesh(16, 0, &mut rng); + let index = MeshIndex::new(&m); + for k in 0..500 { + let o = rng.vec(30.0) + Vec3::new(8.0, 8.0, 30.0); + let target = Vec3::new(rng.range(0.0, 16.0), rng.range(0.0, 16.0), 0.0); + let Some(d) = (target - o).normalized() else { continue }; + let (a, b) = if k % 2 == 0 { (0.3, 0.0) } else { (0.0, 0.01) }; + let mut got = std::collections::HashSet::new(); + index.segments_near(o, d, a, b, |e, s| { + assert!(got.insert((e, s)), "segment {e}/{s} reported twice"); + }); + for (ei, e) in m.edges.iter().enumerate() { + for (si, w) in e.windows(2).enumerate() { + // Sampled along the segment: any point within reach must have its segment reported. + for f in 0..=8 { + let p = w[0] + (w[1] - w[0]) * (f64::from(f) / 8.0); + let (dist, t) = ray_point(o, d, p); + if dist <= a + b * t { + assert!(got.contains(&(ei, si)), "ray {k}: segment {ei}/{si} is within reach but was not reported"); + } + } + } + } + // The one-point edge stands as its own segment. + let last = m.edges.len() - 1; + let (dist, t) = ray_point(o, d, Vec3::new(0.5, 0.5, 2.0)); + if dist <= a + b * t { + assert!(got.contains(&(last, 0))); + } + } +} + +#[test] +fn hostile_boxes_never_panic() { + let nan = Vec3::new(f64::NAN, 0.0, 0.0); + let boxes = [Aabb3::EMPTY, Aabb3 { min: nan, max: nan }, Aabb3 { min: Vec3::ZERO, max: Vec3::new(1.0, 1.0, 1.0) }]; + let bvh = Bvh::new(&boxes); + assert_eq!(bvh.nearest(Vec3::new(0.5, 0.5, 5.0), Vec3::new(0.0, 0.0, -1.0), |i| Some(f64::from(i))), Some((2.0, 2))); + assert_eq!(bvh.nearest(Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 0.0), |_| Some(1.0)), None); + let empty = Bvh::new(&[]); + assert!(empty.nearest(Vec3::ZERO, Vec3::new(0.0, 0.0, 1.0), |_| Some(1.0)).is_none()); + empty.visit(|_| true, |_| panic!("an empty hierarchy has no items")); + let m = Mesh { positions: vec![Vec3::ZERO], triangles: vec![[0, 5, 9]], ..Default::default() }; + assert!(MeshIndex::new(&m).raycast(&m, Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.0, 0.0, -1.0)).is_none()); + MeshIndex::new(&m).segments_near(Vec3::ZERO, Vec3::new(0.0, 0.0, 1.0), f64::NAN, 0.0, |_, _| panic!("no segments")); +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 347d150d0..2ad4f3d89 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -12,6 +12,7 @@ mod arcfit; pub mod blend; pub mod brep; pub mod bspline; +mod bvh; pub mod compare; pub mod env; pub mod fill; @@ -25,6 +26,7 @@ mod vec; pub use arcfit::MAX_FIT_PIECES; pub use blend::hermite_bezier; +pub use bvh::{Bvh, MeshIndex}; pub use mesh::{Aabb3, BoxedTriangle, InsideIndex, MassProperties, Mesh, MeshMeasure, find_close_pair}; pub use plane::Plane; pub use profile::{Loop2, MAX_BEZIER_CTRL, MAX_BEZIER_DEGREE, MAX_DERIVATIVE_ORDER, Region2, Seg2, bezier, regions_apart}; diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 8a9045d47..92339a0ab 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -559,13 +559,39 @@ impl Mesh { /// two triangles that share an edge get exactly opposite values there. A ray through a /// shared edge or vertex hits at least one of them; it never slips between them. pub fn raycast(&self, o: Vec3, dir: Vec3) -> Option<(f64, usize)> { - let comp = |v: Vec3, k: usize| match k { - 0 => v.x, - 1 => v.y, - _ => v.z, - }; - // The ray's dominant axis becomes z; x and y follow it cyclically, swapped to keep - // the frame right-handed when the ray runs towards −z. + let frame = RayFrame::new(o, dir)?; + let mut best: Option<(f64, usize)> = None; + for (i, t) in self.triangles.iter().enumerate() { + let Some(p) = self.tri(t) else { continue }; + if let Some(t) = frame.hit(p) + && best.is_none_or(|(bt, _)| t < bt) + { + best = Some((t, i)); + } + } + best + } +} + +/// A ray in the frame of [`Mesh::raycast`]'s watertight test: its dominant axis becomes z; x and +/// y follow it cyclically, swapped to keep the frame right-handed when the ray runs towards −z. +pub(crate) struct RayFrame { + o: Vec3, + k: [usize; 3], + s: [f64; 3], +} + +fn comp(v: Vec3, k: usize) -> f64 { + match k { + 0 => v.x, + 1 => v.y, + _ => v.z, + } +} + +impl RayFrame { + /// `None` for a direction that is zero or not finite. + pub(crate) fn new(o: Vec3, dir: Vec3) -> Option { let a = [dir.x.abs(), dir.y.abs(), dir.z.abs()]; let kz = if a[0] >= a[1] && a[0] >= a[2] { 0 @@ -582,33 +608,31 @@ impl Mesh { if dz < 0.0 { std::mem::swap(&mut kx, &mut ky); } - let (sx, sy, sz) = (comp(dir, kx) / dz, comp(dir, ky) / dz, 1.0 / dz); - // A vertex in the ray's frame: (x, y) across the ray, z scaled along it. - let frame = |p: Vec3| { - let q = p - o; - let z = comp(q, kz); - (comp(q, kx) - sx * z, comp(q, ky) - sy * z, sz * z) - }; - let mut best: Option<(f64, usize)> = None; - for (i, t) in self.triangles.iter().enumerate() { - let Some([pa, pb, pc]) = self.tri(t) else { continue }; - let ((ax, ay, az), (bx, by, bz), (cx, cy, cz)) = (frame(pa), frame(pb), frame(pc)); - let u = cx * by - cy * bx; - let v = ax * cy - ay * cx; - let w = bx * ay - by * ax; - if (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0) { - continue; - } - let det = u + v + w; - if det == 0.0 { - continue; - } - let t = (u * az + v * bz + w * cz) / det; - if t.is_finite() && t > 1e-9 && best.is_none_or(|(bt, _)| t < bt) { - best = Some((t, i)); - } + Some(RayFrame { o, k: [kx, ky, kz], s: [comp(dir, kx) / dz, comp(dir, ky) / dz, 1.0 / dz] }) + } + + /// A vertex in the ray's frame: (x, y) across the ray, z scaled along it. + fn frame(&self, p: Vec3) -> (f64, f64, f64) { + let q = p - self.o; + let z = comp(q, self.k[2]); + (comp(q, self.k[0]) - self.s[0] * z, comp(q, self.k[1]) - self.s[1] * z, self.s[2] * z) + } + + /// The distance along the ray to triangle `[pa, pb, pc]` (`None`: missed, or not in front). + pub(crate) fn hit(&self, [pa, pb, pc]: [Vec3; 3]) -> Option { + let ((ax, ay, az), (bx, by, bz), (cx, cy, cz)) = (self.frame(pa), self.frame(pb), self.frame(pc)); + let u = cx * by - cy * bx; + let v = ax * cy - ay * cx; + let w = bx * ay - by * ax; + if (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0) { + return None; } - best + let det = u + v + w; + if det == 0.0 { + return None; + } + let t = (u * az + v * bz + w * cz) / det; + (t.is_finite() && t > 1e-9).then_some(t) } } diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 98f4515a8..852004806 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -21,6 +21,7 @@ use wgpu::util::DeviceExt; pub mod capture; mod pbr; +pub mod pick; #[cfg(not(target_arch = "wasm32"))] pub mod select; pub mod view; diff --git a/crates/gpu/src/pick.rs b/crates/gpu/src/pick.rs new file mode 100644 index 000000000..c62d2c7c0 --- /dev/null +++ b/crates/gpu/src/pick.rs @@ -0,0 +1,503 @@ +//! The pick buffer: which model edges are visible at each pixel of the viewport, for picking on a +//! large model without testing every edge. Surfaces are drawn into the depth buffer only; then +//! every edge segment is drawn as a line carrying its id, depth tested against them (lifted +//! toward the eye by the picker's slack, the depth by which an edge may lie behind a face and +//! still count as visible) and written into an `R32Uint` id texture (0: no edge). +//! +//! The pass is drawn once per view (camera, viewport size, model), and only small tiles around +//! the cursor are read back, so a pointer moving over a still view reads a few kilobytes and +//! draws nothing. Read-backs arrive a frame or two later ([`PickResults`]); until a tile is in, +//! the picker answers on the CPU. The ids are hints: the picker still runs its exact tests on +//! the edges a tile names. + +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::{Arc, Mutex}; + +use wgpu::util::DeviceExt; + +/// The side of a read-back tile, in pixels (a multiple of 64, so rows need no padding). +pub const TILE: u32 = 128; +/// Most tiles kept from one view. +const KEEP: usize = 6; +/// Most read-backs in flight. +const IN_FLIGHT: usize = 3; +/// Bytes per surface vertex (position) and per edge vertex (position, id). +const FACE_VERTEX: u64 = 12; +const EDGE_VERTEX: u64 = 16; +const UNIFORM_SIZE: u64 = 96; + +const SHADER: &str = r#" +struct U { + vp: mat4x4, + eye: vec4, // eye position, w = 1 for perspective + back: vec4, // toward the eye (orthographic), w = how far edges are lifted toward it +}; +@group(0) @binding(0) var u: U; + +@vertex +fn vs_face(@location(0) p: vec3) -> @builtin(position) vec4 { + return u.vp * vec4(p, 1.0); +} + +@fragment +fn fs_face() -> @location(0) u32 { + return 0u; +} + +struct EOut { + @builtin(position) pos: vec4, + @location(0) @interpolate(flat) id: u32, +}; + +@vertex +fn vs_edge(@location(0) p: vec3, @location(1) id: u32) -> EOut { + var toward = u.back.xyz; + if (u.eye.w > 0.5) { + let v = u.eye.xyz - p; + let l = length(v); + if (l > 0.0) { + toward = v / l; + } + } + var o: EOut; + o.pos = u.vp * vec4(p + toward * u.back.w, 1.0); + o.id = id; + return o; +} + +@fragment +fn fs_edge(i: EOut) -> @location(0) u32 { + return i.id; +} +"#; + +/// What the pass draws: surfaces (for depth) and edge segments with their ids (from 1). +#[derive(Default, Clone)] +pub struct PickScene { + faces: Vec, + edges: Vec, +} + +impl PickScene { + pub fn triangle(&mut self, t: [[f32; 3]; 3]) { + for p in t { + for c in p { + self.faces.extend_from_slice(&c.to_le_bytes()); + } + } + } + + /// Segment `a`–`b` of the edge `id` (0 is no edge: not drawn). + pub fn segment(&mut self, a: [f32; 3], b: [f32; 3], id: u32) { + if id == 0 { + return; + } + for p in [a, b] { + for c in p { + self.edges.extend_from_slice(&c.to_le_bytes()); + } + self.edges.extend_from_slice(&id.to_le_bytes()); + } + } + + pub fn is_empty(&self) -> bool { + self.edges.is_empty() + } +} + +/// The view the pass is drawn for. +#[derive(Clone, Copy, Debug)] +pub struct PickView { + /// Changes whenever anything below or the scene changes. + pub key: u64, + /// Column-major view-projection (as [`crate::view::Frame::view_proj`]). + pub view_proj: [[f32; 4]; 4], + /// Eye position, and 1 for a perspective camera (0: orthographic). + pub eye: [f32; 4], + /// Direction toward the eye (orthographic). + pub back: [f32; 3], + /// How far edges are lifted toward the eye (model units). + pub lift: f32, + /// The viewport in physical pixels. + pub size: [u32; 2], +} + +/// Edge ids of a block of pixels of one view. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PickTile { + pub key: u64, + pub origin: [u32; 2], + pub size: [u32; 2], + /// Row-major, `size[0] * size[1]`. + pub ids: Vec, +} + +impl PickTile { + /// Whether the tile is of view `key` and holds every pixel of `[x0, y0, x1, y1]` (inclusive) + /// that lies inside a viewport of `view` pixels. + pub fn covers(&self, key: u64, view: [u32; 2], [x0, y0, x1, y1]: [i64; 4]) -> bool { + let clamp = |v: i64, n: u32| v.clamp(0, i64::from(n.max(1)) - 1); + let (x0, x1, y0, y1) = (clamp(x0, view[0]), clamp(x1, view[0]), clamp(y0, view[1]), clamp(y1, view[1])); + let [ox, oy] = self.origin.map(i64::from); + let [w, h] = self.size.map(i64::from); + self.key == key && x0 >= ox && y0 >= oy && x1 < ox + w && y1 < oy + h + } + + /// The ids within `[x0, y0, x1, y1]` (inclusive; outside the tile: none), each once. + pub fn ids_in(&self, [x0, y0, x1, y1]: [i64; 4]) -> Vec { + let [ox, oy] = self.origin.map(i64::from); + let [w, h] = self.size.map(i64::from); + let mut out = Vec::new(); + for y in y0.max(oy)..=y1.min(oy + h - 1) { + for x in x0.max(ox)..=x1.min(ox + w - 1) { + if let Some(&id) = self.ids.get(((y - oy) * w + (x - ox)) as usize) + && id != 0 + { + out.push(id); + } + } + } + out.sort_unstable(); + out.dedup(); + out + } +} + +/// The tiles read back so far (of the latest view only), newest last. +#[derive(Default, Debug)] +pub struct PickResults { + pub tiles: Vec, +} + +impl PickResults { + /// The newest tile of view `key` covering `window`. + pub fn tile(&self, key: u64, view: [u32; 2], window: [i64; 4]) -> Option<&PickTile> { + self.tiles.iter().rev().find(|t| t.covers(key, view, window)) + } +} + +pub type PickOut = Arc>; + +/// The tile (origin and size) around pixel `centre` of a viewport of `view` pixels. +pub fn tile_around(centre: [u32; 2], view: [u32; 2]) -> ([u32; 2], [u32; 2]) { + let size = [TILE.min(view[0]), TILE.min(view[1])]; + let origin = [0, 1].map(|k| centre[k].saturating_sub(size[k] / 2).min(view[k].saturating_sub(size[k]))); + (origin, size) +} + +const NEW: u8 = 0; +const MAPPING: u8 = 1; +const READY: u8 = 2; +const FAILED: u8 = 3; + +/// A tile being copied out of the id texture. +struct Pending { + key: u64, + origin: [u32; 2], + size: [u32; 2], + bytes_per_row: u32, + buffer: wgpu::Buffer, + /// The frame whose commands copy it (it is mapped once they are submitted). + frame: u64, + state: Arc, +} + +struct Target { + size: [u32; 2], + ids: wgpu::Texture, + ids_view: wgpu::TextureView, + depth_view: wgpu::TextureView, +} + +struct Uploaded { + key: u64, + faces: Option<(wgpu::Buffer, u32)>, + edges: Option<(wgpu::Buffer, u32)>, +} + +/// The pass's pipelines, its textures and the read-backs in flight, on one device. +pub struct PickBuffer { + face: wgpu::RenderPipeline, + edge: wgpu::RenderPipeline, + uniform: wgpu::Buffer, + bind: wgpu::BindGroup, + scene: Option, + target: Option, + /// The view drawn into the textures. + drawn: Option, + pending: Vec, + frame: u64, +} + +const DEPTH: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float; +const IDS: wgpu::TextureFormat = wgpu::TextureFormat::R32Uint; + +impl PickBuffer { + pub fn new(device: &wgpu::Device) -> PickBuffer { + let module = + device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("sc_pick"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("sc_pick"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("sc_pick"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sc_pick_u"), + size: UNIFORM_SIZE, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("sc_pick"), + layout: &bgl, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }], + }); + const FA: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![0 => Float32x3]; + const EA: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Uint32]; + let pipeline = |label: &str, + vs: &str, + fs: &str, + stride: u64, + attributes: &'static [wgpu::VertexAttribute], + topology: wgpu::PrimitiveTopology, + write: bool, + mask: wgpu::ColorWrites| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some(vs), + buffers: &[Some(wgpu::VertexBufferLayout { array_stride: stride, step_mode: wgpu::VertexStepMode::Vertex, attributes })], + compilation_options: Default::default(), + }, + primitive: wgpu::PrimitiveState { topology, ..Default::default() }, + depth_stencil: Some(wgpu::DepthStencilState { + format: DEPTH, + depth_write_enabled: Some(write), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(fs), + targets: &[Some(wgpu::ColorTargetState { format: IDS, blend: None, write_mask: mask })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }; + let face = + pipeline("sc_pick_face", "vs_face", "fs_face", FACE_VERTEX, &FA, wgpu::PrimitiveTopology::TriangleList, true, wgpu::ColorWrites::empty()); + let edge = pipeline("sc_pick_edge", "vs_edge", "fs_edge", EDGE_VERTEX, &EA, wgpu::PrimitiveTopology::LineList, false, wgpu::ColorWrites::ALL); + PickBuffer { face, edge, uniform, bind, scene: None, target: None, drawn: None, pending: Vec::new(), frame: 0 } + } + + /// Before the frame is submitted: collect the tiles read back, then draw `view` of `scene` + /// (`scene_key` names it; it is uploaded when that changes) unless it is drawn already, and + /// start reading back the tile around pixel `centre` unless it is in or on its way. The tiles + /// land in `out` a frame or two later; keep frames coming until then. + #[allow(clippy::too_many_arguments)] + pub fn prepare( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + scene_key: u64, + scene: &PickScene, + view: &PickView, + centre: Option<[u32; 2]>, + out: &PickOut, + ) { + self.frame += 1; + self.collect(device, out); + let [w, h] = view.size; + let max = device.limits().max_texture_dimension_2d; + if w == 0 || h == 0 || w > max || h > max { + return; + } + if self.scene.as_ref().is_none_or(|s| s.key != scene_key) { + let limit = device.limits().max_buffer_size; + let upload = |label: &str, bytes: &[u8], stride: u64| { + let n = bytes.len() as u64 / stride; + (n > 0 && (bytes.len() as u64) <= limit && n <= u64::from(u32::MAX)).then(|| { + ( + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some(label), + contents: bytes, + usage: wgpu::BufferUsages::VERTEX, + }), + n as u32, + ) + }) + }; + self.scene = Some(Uploaded { + key: scene_key, + faces: upload("sc_pick_faces", &scene.faces, FACE_VERTEX), + edges: upload("sc_pick_edges", &scene.edges, EDGE_VERTEX), + }); + self.drawn = None; + } + if self.target.as_ref().is_none_or(|t| t.size != view.size) { + let texture = |label: &str, format, usage| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + }; + let ids = texture("sc_pick_ids", IDS, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC); + let depth = texture("sc_pick_depth", DEPTH, wgpu::TextureUsages::RENDER_ATTACHMENT); + let (ids_view, depth_view) = (ids.create_view(&Default::default()), depth.create_view(&Default::default())); + self.target = Some(Target { size: view.size, ids, ids_view, depth_view }); + self.drawn = None; + } + let (Some(target), Some(scene)) = (&self.target, &self.scene) else { return }; + if self.drawn != Some(view.key) { + queue.write_buffer(&self.uniform, 0, &uniform_bytes(view)); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("sc_pick"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target.ids_view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &target.depth_view, + depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }), + stencil_ops: None, + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_bind_group(0, &self.bind, &[]); + for (pipeline, part) in [(&self.face, &scene.faces), (&self.edge, &scene.edges)] { + if let Some((buffer, n)) = part { + pass.set_pipeline(pipeline); + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw(0..*n, 0..1); + } + } + drop(pass); + self.drawn = Some(view.key); + // Tiles of other views no longer answer. + self.pending.retain(|p| p.key == view.key); + if let Ok(mut o) = out.lock() { + o.tiles.retain(|t| t.key == view.key); + } + } + let Some(centre) = centre else { return }; + let (origin, size) = tile_around(centre, view.size); + let known = out.lock().is_ok_and(|o| o.tiles.iter().any(|t| t.key == view.key && t.origin == origin && t.size == size)) + || self.pending.iter().any(|p| p.key == view.key && p.origin == origin && p.size == size); + if known || self.pending.len() >= IN_FLIGHT { + return; + } + let bytes_per_row = (size[0] * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sc_pick_tile"), + size: u64::from(bytes_per_row) * u64::from(size[1]), + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { + texture: &target.ids, + mip_level: 0, + origin: wgpu::Origin3d { x: origin[0], y: origin[1], z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyBufferInfo { + buffer: &buffer, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(bytes_per_row), rows_per_image: Some(size[1]) }, + }, + wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, + ); + self.pending.push(Pending { key: view.key, origin, size, bytes_per_row, buffer, frame: self.frame, state: Arc::new(AtomicU8::new(NEW)) }); + } + + /// Whether read-backs are still on their way (keep frames coming). + pub fn waiting(&self) -> bool { + !self.pending.is_empty() + } + + /// Maps the copies earlier frames submitted and moves the mapped ones into `out`. + fn collect(&mut self, device: &wgpu::Device, out: &PickOut) { + let frame = self.frame; + for p in &self.pending { + if p.frame < frame && p.state.load(Ordering::Acquire) == NEW { + p.state.store(MAPPING, Ordering::Release); + let state = p.state.clone(); + p.buffer.slice(..).map_async(wgpu::MapMode::Read, move |r| state.store(if r.is_ok() { READY } else { FAILED }, Ordering::Release)); + } + } + if self.pending.iter().any(|p| p.state.load(Ordering::Acquire) == MAPPING) { + let _ = device.poll(wgpu::PollType::Poll); + } + let mut done = Vec::new(); + self.pending.retain(|p| match p.state.load(Ordering::Acquire) { + READY => { + if let Ok(bytes) = p.buffer.slice(..).get_mapped_range() { + let [w, h] = p.size; + let mut ids = Vec::with_capacity(w as usize * h as usize); + for row in bytes.chunks(p.bytes_per_row as usize).take(h as usize) { + ids.extend(row.as_chunks::<4>().0.iter().take(w as usize).map(|c| u32::from_le_bytes(*c))); + } + done.push(PickTile { key: p.key, origin: p.origin, size: p.size, ids }); + } + p.buffer.unmap(); + false + } + FAILED => false, + _ => true, + }); + if !done.is_empty() + && let Ok(mut o) = out.lock() + { + for t in done { + if self.drawn == Some(t.key) && t.ids.len() == t.size[0] as usize * t.size[1] as usize { + o.tiles.retain(|x| x.key == t.key); + o.tiles.push(t); + } + } + let excess = o.tiles.len().saturating_sub(KEEP); + o.tiles.drain(..excess); + } + } +} + +fn uniform_bytes(v: &PickView) -> Vec { + let mut b = Vec::with_capacity(UNIFORM_SIZE as usize); + for col in v.view_proj { + for x in col { + b.extend_from_slice(&x.to_le_bytes()); + } + } + for x in v.eye.into_iter().chain(v.back).chain([v.lift]) { + b.extend_from_slice(&x.to_le_bytes()); + } + b +} + +#[cfg(test)] +#[path = "pick_tests.rs"] +mod tests; diff --git a/crates/gpu/src/pick_tests.rs b/crates/gpu/src/pick_tests.rs new file mode 100644 index 000000000..5ccb5e2b9 --- /dev/null +++ b/crates/gpu/src/pick_tests.rs @@ -0,0 +1,79 @@ +use super::*; + +/// Looking down −z at x, y in −10..10 (orthographic): depth 0 at z = 50, 1 at z = −50. +const VIEW: [[f32; 4]; 4] = [[0.1, 0.0, 0.0, 0.0], [0.0, 0.1, 0.0, 0.0], [0.0, 0.0, -0.01, 0.0], [0.0, 0.0, 0.5, 1.0]]; +const SIZE: u32 = 64; + +/// The pixel of model point (x, y). +fn px(x: f32, y: f32) -> [i64; 2] { + [((x / 10.0 + 1.0) * 0.5 * SIZE as f32) as i64, ((1.0 - y / 10.0) * 0.5 * SIZE as f32) as i64] +} + +/// A square face at z = 0 (x, y in −5..5), and three edges: 1 on it, 2 well behind it, 3 behind +/// it by less than the lift. +fn scene() -> PickScene { + let mut s = PickScene::default(); + let (a, b, c, d) = ([-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]); + s.triangle([a, b, c]); + s.triangle([a, c, d]); + s.segment([-8.0, 0.0, 0.0], [8.0, 0.0, 0.0], 1); + s.segment([2.0, -8.0, -3.0], [2.0, 8.0, -3.0], 2); + s.segment([-2.0, -8.0, -0.2], [-2.0, 8.0, -0.2], 3); + s +} + +#[test] +fn the_pick_buffer_names_the_edges_seen_at_each_pixel() { + let (_, device, queue) = match crate::open_headless() { + Ok(d) => d, + Err(e) => { + assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "a GPU is required here: {e}"); + eprintln!("skipping: {e}"); + return; + } + }; + let mut pb = PickBuffer::new(&device); + let out = PickOut::default(); + let view = PickView { key: 7, view_proj: VIEW, eye: [0.0, 0.0, 100.0, 0.0], back: [0.0, 0.0, 1.0], lift: 0.5, size: [SIZE, SIZE] }; + let scene = scene(); + let all = [0, 0, SIZE as i64 - 1, SIZE as i64 - 1]; + for _ in 0..8 { + let mut encoder = device.create_command_encoder(&Default::default()); + pb.prepare(&device, &queue, &mut encoder, 1, &scene, &view, Some([SIZE / 2, SIZE / 2]), &out); + queue.submit([encoder.finish()]); + let _ = device.poll(wgpu::PollType::wait_indefinitely()); + if out.lock().unwrap().tile(7, [SIZE, SIZE], all).is_some() { + break; + } + } + let results = out.lock().unwrap(); + let tile = results.tile(7, [SIZE, SIZE], all).expect("the tile is read back within a few frames"); + let at = |x: f32, y: f32| { + let [px, py] = px(x, y); + tile.ids_in([px - 1, py - 1, px + 1, py + 1]) + }; + assert_eq!(at(0.0, 0.0), vec![1], "the edge on the face"); + assert_eq!(at(2.0, 3.0), Vec::::new(), "the edge behind the face is hidden"); + assert_eq!(at(2.0, 7.5), vec![2], "and seen where the face does not cover it"); + assert_eq!(at(-2.0, 3.0), vec![3], "an edge behind the face by less than the lift counts as seen"); + assert_eq!(at(3.5, 3.5), Vec::::new(), "the face itself names no edge"); + assert!(results.tile(8, [SIZE, SIZE], all).is_none(), "another view's tile does not answer"); + drop(results); + assert!(!pb.waiting()); +} + +#[test] +fn tiles_cover_the_window_around_the_cursor_inside_the_view() { + assert_eq!(tile_around([10, 10], [1000, 800]), ([0, 0], [TILE, TILE])); + assert_eq!(tile_around([500, 400], [1000, 800]), ([500 - TILE / 2, 400 - TILE / 2], [TILE, TILE])); + assert_eq!(tile_around([999, 799], [1000, 800]), ([1000 - TILE, 800 - TILE], [TILE, TILE])); + assert_eq!(tile_around([30, 20], [50, 40]), ([0, 0], [50, 40])); + let t = PickTile { key: 1, origin: [100, 100], size: [TILE, TILE], ids: vec![0; (TILE * TILE) as usize] }; + assert!(t.covers(1, [1000, 800], [110, 110, 120, 120])); + assert!(!t.covers(1, [1000, 800], [90, 110, 120, 120])); + assert!(!t.covers(2, [1000, 800], [110, 110, 120, 120])); + // A window past the view's border needs only the pixels inside it. + let corner = PickTile { key: 1, origin: [0, 0], size: [TILE, TILE], ids: vec![5; (TILE * TILE) as usize] }; + assert!(corner.covers(1, [1000, 800], [-8, -8, 8, 8])); + assert_eq!(corner.ids_in([-8, -8, 8, 8]), vec![5]); +} diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs index c29542af3..d3f8e8015 100644 --- a/crates/gpu/src/view.rs +++ b/crates/gpu/src/view.rs @@ -1335,6 +1335,7 @@ impl Renderer { tris(pass, &res.trans, &h.trans); tris(pass, &res.guide_trans, &h.guide_trans); tris(pass, &res.xray, &pv.xray); + tris(pass, &res.xray, &h.xray); lines(pass, &res.overlay, &m.overlays); lines(pass, &res.overlay, &sk.overlays); lines(pass, &res.overlay, &h.overlays); diff --git a/crates/io/src/vfs.rs b/crates/io/src/vfs.rs index 5749f2af4..05b6ebae8 100644 --- a/crates/io/src/vfs.rs +++ b/crates/io/src/vfs.rs @@ -50,6 +50,11 @@ mod imp { check(path)?; std::fs::remove_file(path) } + /// A folder and the folders above it, where missing. + pub fn create_dir_all(path: &str) -> Result<()> { + check(path)?; + std::fs::create_dir_all(path) + } } #[cfg(target_arch = "wasm32")] @@ -94,6 +99,10 @@ mod imp { pub fn remove(path: &str) -> Result<()> { FILES.with(|f| f.borrow_mut().remove(path)).map(|_| ()).ok_or_else(|| missing(path)) } + /// Files are keyed by their whole path here: a folder needs no making. + pub fn create_dir_all(_path: &str) -> Result<()> { + Ok(()) + } pub fn insert(path: &str, bytes: Vec) { FILES.with(|f| f.borrow_mut().insert(path.to_string(), bytes)); } diff --git a/crates/kernel/src/blend_fit.rs b/crates/kernel/src/blend_fit.rs index f2e553016..8deb9063d 100644 --- a/crates/kernel/src/blend_fit.rs +++ b/crates/kernel/src/blend_fit.rs @@ -116,9 +116,52 @@ impl Frame { if !(sa.is_finite() && sb.is_finite() && sa > 0.0 && sb > 0.0) { return None; } + self.prism(self.ta * sa, self.tb * sb) + } + + /// For a round, the arc of its cross-section from the setback on face a to the one on face + /// b, in [`ARC_PIECES`] pieces, as offsets from the edge; `None` for a chamfer. + fn arc(&self, size: Size) -> Option> { + let Size::Round(r) = size else { return None }; + let (sa, sb) = self.setbacks(size)?; + let half = 0.5 * self.ta.dot(self.tb).clamp(-1.0, 1.0).acos(); + // The ball's centre, on the bisector, `r` from both faces. + let centre = (self.ta + self.tb).normalized()? * (r / half.sin()); + let (a, b) = (self.ta * sa - centre, self.tb * sb - centre); + (0..=ARC_PIECES).map(|k| Some(centre + (a + (b - a) * (k as f64 / ARC_PIECES as f64)).normalized()? * r)).collect() + } + + /// What a blend of the edge at `size` changes, within the wedge: for a round, the fan of + /// prisms from the edge to the pieces of its arc (between the edge and the arc lies all it + /// takes away or fills; the ball's side of the arc is left as it is), for a chamfer the + /// wedge itself. + fn pieces(&self, size: Size) -> Option> { + match self.arc(size) { + Some(arc) => arc.windows(2).map(|w| self.prism(*w.first()?, *w.get(1)?)).collect(), + None => Some(vec![self.wedge(size)?]), + } + } + + /// The blend's own surface at `size`, as polygons: the strips between its arc's pieces, or + /// the chamfer's face. + fn surface(&self, size: Size) -> Option>> { + match self.arc(size) { + Some(arc) => arc + .windows(2) + .map(|w| { + let (u, v) = (*w.first()?, *w.get(1)?); + Some(vec![self.p0 + u, self.p0 + v, self.p1 + v, self.p1 + u]) + }) + .collect(), + None => Some(vec![self.wedge(size)?.faces.get(2)?.clone()]), + } + } + + /// The triangle between the edge and the offsets `u` and `w` across it, swept along the edge. + fn prism(&self, u: Vec3, w: Vec3) -> Option { let d = (self.p1 - self.p0).normalized()?; - let (a0, b0) = (self.p0 + self.ta * sa, self.p0 + self.tb * sb); - let (a1, b1) = (self.p1 + self.ta * sa, self.p1 + self.tb * sb); + let (a0, b0) = (self.p0 + u, self.p0 + w); + let (a1, b1) = (self.p1 + u, self.p1 + w); // Each side's plane, facing away from the triangle's third corner. let side = |p: Vec3, q: Vec3, opposite: Vec3| -> Option<(Vec3, f64)> { let mut n = d.cross(q - p).normalized()?; @@ -130,13 +173,18 @@ impl Frame { let planes = [side(self.p0, a0, b0)?, side(self.p0, b0, a0)?, side(a0, b0, self.p0)?, (-d, -d.dot(self.p0)), (d, d.dot(self.p1))]; let faces = vec![vec![self.p0, a0, a1, self.p1], vec![self.p0, b0, b1, self.p1], vec![a0, b0, b1, a1], vec![self.p0, a0, b0], vec![self.p1, a1, b1]]; - let area = 0.5 * (self.ta * sa).cross(self.tb * sb).len(); + let area = 0.5 * u.cross(w).len(); Some(Wedge { planes, faces, volume: area * self.p0.dist(self.p1) }) } } -/// `poly` clipped to the half-spaces, each moved `eps` inwards: is anything left? -fn reaches_inside(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64) -> bool { +/// Pieces a round's arc is divided into for [`Frame::pieces`] and [`Frame::surface`]: each +/// chord sags under 0.5 % of the radius. +const ARC_PIECES: usize = 8; + +/// `poly` clipped to the half-spaces `n·x <= c`, each moved `eps` inwards (empty when nothing +/// is left). +fn clip(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64) -> Vec { let mut cur: Vec = poly.to_vec(); for (n, c) in planes { let c = c - eps; @@ -152,11 +200,53 @@ fn reaches_inside(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64) -> bool { } } if next.is_empty() { - return false; + return next; } cur = next; } - true + cur +} + +/// `poly` clipped to the half-spaces, each moved `eps` inwards: is anything left? +fn reaches_inside(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64) -> bool { + !clip(poly, planes, eps).is_empty() +} + +/// Most polygons [`reaches_inside_beyond`] clips before it gives up and answers yes. +const MAX_CLIPS: usize = 4096; + +/// Whether the part of `poly` outside every one of the wedges `trimmed` (by more than `out`) +/// reaches inside `planes` (by `eps`). A face beside or at the end of another edge the same +/// feature blends is trimmed back to that blend, so its part inside that edge's wedge is gone +/// (#1668). +fn reaches_inside_beyond(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64, trimmed: &[&Wedge], out: f64) -> bool { + let mut parts = vec![poly.to_vec()]; + for w in trimmed { + // Outside a convex wedge is outside one of its planes (pieces may overlap: only + // whether anything is left counts). + let mut next = Vec::new(); + for part in &parts { + for (n, c) in &w.planes { + let piece = clip(part, &[(-*n, -*c)], out); + if !piece.is_empty() { + next.push(piece); + } + } + if next.len() > MAX_CLIPS { + return true; + } + } + parts = next; + } + parts.iter().any(|p| reaches_inside(p, planes, eps)) +} + +/// Whether two sets of convex prisms overlap (by more than `eps`): a face of one reaches +/// inside the other. +fn overlap(a: &[Wedge], b: &[Wedge], eps: f64) -> bool { + a.iter().any(|x| { + b.iter().any(|y| y.faces.iter().any(|p| reaches_inside(p, &x.planes, eps)) || x.faces.iter().any(|p| reaches_inside(p, &y.planes, eps))) + }) } /// The body's straight edges between planar faces nearest the points (each once; `None` for a @@ -275,11 +365,22 @@ fn first_clash(sel: &Selection, size: Size) -> Option { // Planar faces are exact in the mesh; curved ones are within the chord. let flat = (sel.size * 1e-7).max(1e-9); let curved = sel.chord * 2.0; - for (f, w) in sel.frames.iter().zip(&wedges) { + // Planar faces beside an edge lie in its wedge's side planes: outside it means further. + let out = (sel.size * 1e-6).max(1e-8); + for (i, (f, w)) in sel.frames.iter().zip(&wedges).enumerate() { let (Some(f), Some(w)) = (f, w) else { continue }; let hit = sel.tris.iter().filter(|(_, face)| !f.allowed.contains(face)).any(|(t, face)| { let eps = if sel.planar.get(*face).copied().unwrap_or(false) { flat } else { curved }; - reaches_inside(t, &w.planes, eps) + // The other blended edges this face runs along or ends them trim it back. + let trimmed: Vec<&Wedge> = sel + .frames + .iter() + .zip(&wedges) + .enumerate() + .filter(|(j, (fj, _))| *j != i && fj.as_ref().is_some_and(|fj| fj.allowed.contains(face))) + .filter_map(|(_, (_, wj))| wj.as_ref()) + .collect(); + reaches_inside_beyond(t, &w.planes, eps, &trimmed, out) }); if hit { return Some(Clash::Face); @@ -295,7 +396,7 @@ fn first_clash(sel: &Selection, size: Size) -> Option { continue; } let meet = wj.faces.iter().any(|p| reaches_inside(p, &wi.planes, eps)) || wi.faces.iter().any(|p| reaches_inside(p, &wj.planes, eps)); - if meet { + if meet && blends_cross(fi, wi, fj, wj, size, eps) { return Some(Clash::Blend); } } @@ -303,6 +404,15 @@ fn first_clash(sel: &Selection, size: Size) -> Option { None } +/// Two blends whose wedges overlap: do they cross? Rounds on both sides of a wall (the outside +/// round's wedge reaches past the inside corner, which the inside round fills) need not: they +/// cross only where what one changes (between its edge and its arc) overlaps what the other +/// does, or where either's surface runs into the other's wedge (#1668). +fn blends_cross(fi: &Frame, wi: &Wedge, fj: &Frame, wj: &Wedge, size: Size, eps: f64) -> bool { + let (Some(pi), Some(pj), Some(si), Some(sj)) = (fi.pieces(size), fj.pieces(size), fi.surface(size), fj.surface(size)) else { return true }; + overlap(&pi, &pj, eps) || sj.iter().any(|p| reaches_inside(p, &wi.planes, eps)) || si.iter().any(|p| reaches_inside(p, &wj.planes, eps)) +} + /// The step the largest fitting size is given to: three significant digits. fn step(v: f64) -> f64 { 10f64.powf(v.log10().floor() - 3.0) diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index ffcfd70ec..7d12b14df 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -305,6 +305,18 @@ pub fn canonical_revolve_axis(plane: &Plane, region: &Region2, axis_origin: Vec2 /// Revolve each region about the sketch axis by `angle` radians. /// This legacy API preserves its historical sweep sign behavior. pub fn revolve(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec2, angle: f64) -> Result> { + revolved(plane, regions, axis_origin, axis_dir, angle, false) +} + +/// [`revolve`] for bodies that are final (new bodies, not a boolean's tools): a partial turn's +/// planar faces come out whole too, as a full turn's always do (#726). A tool is left as swept: +/// healed, its planar faces meet a target exactly where they are tangent to it, and the +/// boolean leaves pieces there that touch. The boolean heals its own result anyway. +pub fn revolve_whole(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec2, angle: f64) -> Result> { + revolved(plane, regions, axis_origin, axis_dir, angle, true) +} + +fn revolved(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec2, angle: f64, whole: bool) -> Result> { let angle = finite(angle, "angle")?; if angle.abs() < 1e-6 { return Err(KernelError::Invalid("revolve angle is zero".into())); @@ -447,11 +459,46 @@ pub fn revolve(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: let closed = angle.abs() >= std::f64::consts::TAU; let history = guard("revolve history", || Ok(record::swept_face(&solid, &f, &seeds(&profile), closed)))?; let solid = if shift.len() > 0.0 { builder::translated(&solid, v3(shift)) } else { solid }; + let (solid, history) = if closed || whole { turned_whole(solid, history) } else { (solid, history) }; out.push(record::attach(Body::new(solid)?, &[], history, Default::default())?); } Ok(out) } +/// A revolved solid with its planar faces whole (#726): the sweep turns each profile edge into +/// two or three patches, the planar ones on revolved surfaces, which stayed apart until a later +/// feature healed the body, so a pick on one took part of the face. Healed as booleans heal +/// their results, each face is still generated, from the profile edges of the patches merged +/// into it. The solid as it was when healing fails or can't be followed. +fn turned_whole(solid: Solid, faces: Option>) -> (Solid, Option>) { + let Some(given) = faces.as_ref() else { return (solid, faces) }; + let Ok(size) = Body::new(solid.clone()).map(|b| b.size()) else { return (solid, faces) }; + let healed = guard("heal revolve", || { + let (healed, map) = crate::heal::heal_traced(solid.clone(), size, &[]); + let failed = || KernelError::Failed("heal revolve".into()); + if !crate::boolean_record::edges_evaluate(&healed) { + return Err(failed()); + } + let carried = map + .ok_or_else(failed)? + .faces + .iter() + .map(|under| { + let mut origins: Vec<_> = under.iter().map(|i| given.get(*i).map(|f| f.origins.clone())).collect::>>()?.concat(); + origins.sort(); + origins.dedup(); + Some(FaceProv { origins, change: crate::history::Change::Generated }) + }) + .collect::>>() + .ok_or_else(failed)?; + Ok((healed, carried)) + }); + match healed { + Ok((healed, carried)) => (healed, Some(carried)), + Err(_) => (solid, faces), + } +} + /// Axis-aligned box between two corners. pub fn box_solid(a: Vec3, b: Vec3) -> Result { let (lo, hi) = (a.min(b), a.max(b)); diff --git a/crates/kernel/src/curveblend.rs b/crates/kernel/src/curveblend.rs index d72347128..37b606a54 100644 --- a/crates/kernel/src/curveblend.rs +++ b/crates/kernel/src/curveblend.rs @@ -1723,10 +1723,14 @@ fn curve_blend_sized(solid: &Solid, ids: &[mt::EdgeID], size: f64, size_law: Siz continue; } let h = length(k) / (samples - 1) as f64; - let spaced = |nb: usize, from_end: bool| -> Result>> { + // A neighbour shorter than two of the strip's steps lends none: its own sections are + // spaced far closer (a small round beside a long line), and borrowing them made the + // strip overshoot and fold back on itself past the joint, which its faces' meshes + // then folded with (#1667). The strip ends on the joint's section on its own. + let spaced = |nb: usize, from_end: bool| -> Result> { let l = length(nb); if !(l > 2.0 * h && h > 0.0) { - return Ok(None); + return Ok(Vec::new()); } let mut out = Vec::with_capacity(2); for j in [1.0, 2.0] { @@ -1735,7 +1739,7 @@ fn curve_blend_sized(solid: &Solid, ids: &[mt::EdgeID], size: f64, size_law: Siz if from_end { out.reverse(); } - Ok(Some(out)) + Ok(out) }; let (prev, next) = ((k + n - 1) % n, (k + 1) % n); let list = esec.get(k).ok_or_else(|| KernelError::Failed("section".into()))?; @@ -1748,23 +1752,22 @@ fn curve_blend_sized(solid: &Solid, ids: &[mt::EdgeID], size: f64, size_law: Siz _ => false, }; let before = match (closed || k > 0) && rolls(prev) { - true => spaced(prev, true)? - .map(|b| if smooth([list.first(), list.get(1), list.get(2)], [list.first(), b.get(1), b.first()]) { b } else { Vec::new() }), - false => Some(Vec::new()), + true => { + let b = spaced(prev, true)?; + if smooth([list.first(), list.get(1), list.get(2)], [list.first(), b.get(1), b.first()]) { b } else { Vec::new() } + } + false => Vec::new(), }; let after = match (closed || k + 1 < n) && rolls(next) { - true => spaced(next, false)?.map(|a| { + true => { + let a = spaced(next, false)?; let m = list.len(); let tail = [list.last(), m.checked_sub(2).and_then(|i| list.get(i)), m.checked_sub(3).and_then(|i| list.get(i))]; if smooth(tail, [list.last(), a.first(), a.get(1)]) { a } else { Vec::new() } - }), - false => Some(Vec::new()), + } + false => Vec::new(), }; - let fit = match (before, after) { - (Some(b), Some(a)) => crate::guard("fit curve blend", || fit_strip(list, &b, &a, round))?, - _ => crate::guard("fit curve blend", || fit_sections(&esec, k, closed, round))?, - }; - let mut fit = fit; + let mut fit = crate::guard("fit curve blend", || fit_strip(list, &before, &after, round))?; fit.span = guides.get(k).and_then(Option::as_ref).map(|g| g.span).unwrap_or((0.0, 1.0)); fits.push(Some(fit)); } diff --git a/crates/kernel/src/curveblend_tests.rs b/crates/kernel/src/curveblend_tests.rs index cf88c6116..12fc36b10 100644 --- a/crates/kernel/src/curveblend_tests.rs +++ b/crates/kernel/src/curveblend_tests.rs @@ -693,3 +693,39 @@ fn chamfer_a_chain_of_a_line_and_an_arc_into_a_slanted_end() { let got = volume(&body) - volume(&made); assert!((got - want).abs() < want * 1e-3, "removed {got} vs {want}"); } + +/// #1667: an R1 round around the end of a long bar whose four long edges are R5. The chain is +/// 290 mm lines and quarter turns of 7.85 mm, so the lines' sections are spaced far wider than +/// the turns'; borrowing the turns' sections for the lines' ends made their strips overshoot and +/// fold back past the joints, the strips' meshes folded with them, and the measured volume came +/// out thousands of mm³ off. The R1 pipe is exact: the corner's section, `1 - π/4`, along the +/// lines, and round each turn's axis at the section's centroid (Pappus). +#[test] +fn round_along_long_lines_and_small_turns_measures_its_volume() { + use std::f64::consts::{FRAC_PI_2, FRAC_PI_4}; + let (w, d, h) = (300.0, 60.0, 40.0); + let bar = crate::build::box_solid(Vec3::new(-w / 2.0, 0.0, 0.0), Vec3::new(w / 2.0, d, h)).unwrap(); + let long = [Vec3::new(-w / 2.0, d / 2.0, 0.0), Vec3::new(w / 2.0, d / 2.0, 0.0), Vec3::new(-w / 2.0, d / 2.0, h), Vec3::new(w / 2.0, d / 2.0, h)]; + let rounded = fillet(&bar, &long, 5.0).unwrap(); + // The rolling ball along the end face's loop (the exact blends would take this loop; a + // loop next to free-form faces, as in the issue, comes here). + let ids: Vec = crate::body::Body::unique_edges(&rounded.solid) + .into_iter() + .filter(|e| [e.front(), e.back()].iter().all(|v| crate::blend::vtx(v).y.abs() < 1e-9)) + .map(|e| e.id()) + .collect(); + assert_eq!(ids.len(), 8); + let (solid, _) = crate::guard("test", || curve_blend(&rounded.solid, &ids, rounded.size(), 1.0, true)).unwrap(); + let body = Body::new(solid).unwrap(); + assert!(body.validity().is_empty(), "{:?}", body.validity()); + let section = 1.0 - FRAC_PI_4; + // The section's centroid lies this far from its corner along each side. + let inset = (5.0 / 6.0 - FRAC_PI_4) / section; + let lines = 2.0 * (w - 10.0) + 2.0 * (h - 10.0); + let turns = 4.0 * FRAC_PI_2 * (5.0 - inset); + let want = w * d * h - 4.0 * 25.0 * section * d - section * (lines + turns); + let m = crate::measure(&body).unwrap(); + assert!((m.volume - want).abs() < 1e-5 * want, "{} vs {want}", m.volume); + // Centred across the bar, as the part is. + assert!(m.centroid.x.abs() < 1e-3, "centre of mass x {}", m.centroid.x); +} diff --git a/crates/kernel/src/issue_1080_tests.rs b/crates/kernel/src/issue_1080_tests.rs index 914ffa3f5..4d3f66484 100644 --- a/crates/kernel/src/issue_1080_tests.rs +++ b/crates/kernel/src/issue_1080_tests.rs @@ -94,3 +94,28 @@ fn a_result_that_removes_more_than_the_blend_is_refused() { let m = too_large(crate::blend_fit::check_volume(&b, worse, &e, size)); assert!(m.contains("more than the chamfer can"), "{m}"); } + +/// #1668: a box shelled outward 2 mm, open at the bottom. R5 on its top outer edge alone would +/// reach past the sharp inside corner 2 mm away; with the inside edge rounded in the same +/// fillet, that corner is filled, and the two build as one feature as they do one after the +/// other: the outer round takes (1 - π/4) · 25 mm² along 104 mm, the inner one adds it along +/// 100 mm. +#[test] +fn rounds_on_both_sides_of_a_wall_build_as_one_fillet() { + let outer = box_solid(Vec3::new(-52.0, -32.0, 0.0), Vec3::new(52.0, 32.0, 42.0)).unwrap(); + let shelled = cut(&outer, [-50.0, -30.0, -1.0], [50.0, 30.0, 40.0]); + let (out_edge, in_edge) = (Vec3::new(0.0, 32.0, 42.0), Vec3::new(0.0, 30.0, 40.0)); + let m = too_large(crate::fillet(&shelled, &[out_edge], 5.0)); + assert!(m.contains("runs past the faces beside the edge"), "{m}"); + let both = crate::fillet(&shelled, &[out_edge, in_edge], 5.0).unwrap(); + assert!(both.validity().is_empty(), "{:?}", both.validity()); + let section = (1.0 - std::f64::consts::FRAC_PI_4) * 25.0; + let want = shelled.volume_at(0.01).unwrap() - section * 104.0 + section * 100.0; + let v = crate::measure(&both).unwrap().volume; + assert!((v - want).abs() < 1e-4 * want, "{v} vs {want}"); + let stepped = crate::fillet(&crate::fillet(&shelled, &[in_edge], 5.0).unwrap(), &[out_edge], 5.0).unwrap(); + assert!((crate::measure(&stepped).unwrap().volume - v).abs() < 1e-4 * want); + // Past the wall's own room they still cross: R7's outer round reaches the inner one's arc. + let m = too_large(crate::fillet(&shelled, &[out_edge, in_edge], 7.0)); + assert!(m.contains("the largest radius that fits"), "{m}"); +} diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index daf37d7b7..39110a8b3 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -85,7 +85,7 @@ mod outline; #[cfg(test)] mod outline_tests; mod par; -pub use par::{for_each_on_threads, map_on_threads}; +pub use par::{for_each_on_threads, map_on_threads, map_with_local_pools}; #[cfg(test)] mod pinch_tests; mod planar_faces; @@ -134,8 +134,8 @@ pub use boolean_diagnostics::{BooleanDiagnostics, BooleanFallback, BooleanStrate pub use boundary::{Boundary, boundary_patch}; pub use bridge::{Continuity, Frame, blend_between, bridge, chain, chain_closes, frames, frames_across, sample_grid}; pub use build::{ - PathSeg, box_solid, canonical_revolve_axis, cylinder, extrude, extrude_tapered, extrude_tapered_between, loft, revolve, sphere, sweep, - sweep_with, torus, + PathSeg, box_solid, canonical_revolve_axis, cylinder, extrude, extrude_tapered, extrude_tapered_between, loft, revolve, revolve_whole, sphere, + sweep, sweep_with, torus, }; pub use continuity::{ ContinuityReport, ContinuityTolerances, EdgePick, MAX_SAMPLES, MIN_SAMPLES, SeamReport, SeamVerdict, SeamWorst, pick_edges, seam_diagnostics, @@ -159,7 +159,7 @@ pub use mesh_convert::convert_prismatic_mesh; pub use meshbody::{MAX_TRIANGLES, mesh_body}; pub use native::{decode_native_body, encode_native_body, native_preview_mesh}; pub use offset::with_same_surface; -pub use ops::{BoolOp, boolean, can_join_touching_faces, join_apart, split_by_plane, transform, transform_matrix, union_apart}; +pub use ops::{BoolOp, boolean, can_join_touching_faces, half_space, join_apart, split_by_plane, transform, transform_matrix, union_apart}; pub use polybool::{faceted_boolean, planar_boolean}; pub use polyhedron::{HalfSpace, convex_polyhedron, draft, offset_faces, shell}; pub use prism::{PLANAR_FIT_TOL, extrude_planar_regions, planar_regions_boolean}; @@ -181,7 +181,7 @@ pub use surfaces::{ sweep_sheet_points, sweep_sheet_points_with, sweep_sheet_with, thicken, trim, unstitch, }; pub use sweep_path::{SweepControl, SweepOrientation, sweep_path, sweep_path_with}; -pub use topo::{CylinderFace, cylinder_face_at}; +pub use topo::{CylinderFace, cylinder_end_at, cylinder_face_at}; pub use topo::{TopoCounts, merged_topology, seam_flags}; pub use tspline::tspline_sheet; diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 5cfc713c6..f84c768b5 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -363,7 +363,9 @@ fn boolean_via(a: &Body, b: &Body, op: BoolOp, whole: &dyn Fn(&Body, &Body, Bool match op { BoolOp::Cut => r = r.and_then(|result| result.map(|body| body.with_preserved_boolean_planar_sources(a, b, true)).transpose()), BoolOp::Union => r = r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()), - BoolOp::Intersect => {} + // Every face of an intersection lies on one operand's face, as a union's does: the same + // roles carry over (#565). + BoolOp::Intersect => r = r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()), } // A retry's result is held to what the operation can do at all; one that fails is refused // rather than returned wrong (issue #616). @@ -1426,15 +1428,19 @@ pub fn transform(body: &Body, translate: Vec3, origin: Vec3, axis: Vec3, angle: pub fn split_by_plane(body: &Body, plane: &solidcraft_geom::Plane) -> Result> { let mut out = Vec::new(); for positive in [true, false] { - out.extend(half_space(body, plane, positive)?); + out.extend(half_space(body, plane, positive)?.0); } Ok(out) } -/// The part of a body on one side of a plane (`None` when nothing is there): its intersection -/// with [`half_box`] (whose history it carries, over the body and the box). -pub(crate) fn half_space(body: &Body, plane: &solidcraft_geom::Plane, positive: bool) -> Result> { - boolean(body, &half_box(body, plane, positive)?, BoolOp::Intersect) +/// The part of a body on one side of a plane (`None` when nothing is there), and the tool it is +/// cut with: the part is the body's intersection with [`half_box`] (the tool), whose history it +/// carries, over the body and the box. The box's face in the plane, the part's cut face, is its +/// start cap on the positive side and its end cap on the negative side. +pub fn half_space(body: &Body, plane: &solidcraft_geom::Plane, positive: bool) -> Result<(Option, Body)> { + // The box's own construction roles describe no face of the design: the cut face has none. + let tool = half_box(body, plane, positive)?.with_face_sources(None); + Ok((boolean(body, &tool, BoolOp::Intersect)?, tool)) } /// A box covering everything of `body` on one side of a plane, its start cap in the plane. diff --git a/crates/kernel/src/par.rs b/crates/kernel/src/par.rs index 5e08be765..b18ea88bb 100644 --- a/crates/kernel/src/par.rs +++ b/crates/kernel/src/par.rs @@ -33,6 +33,37 @@ pub fn for_each_on_threads(items: &[T], max_threads: usize, f: impl Fn( let _ = map_on_threads(items, max_threads, f); } +/// Independent kernel jobs, with one computation lane per native dispatcher. Each dispatcher +/// owns a single-thread Rayon pool: nested triangulation neither queues behind a common +/// one-thread pool nor multiplies the requested concurrency. No second body can be stolen by +/// a worker while it fills a shared lazy mesh cell. The browser runs serially. +pub fn map_with_local_pools(items: &[T], max_threads: usize, f: impl Fn(&T) -> Result + Sync) -> Vec> { + #[cfg(not(target_arch = "wasm32"))] + let one = |item: &T| { + use std::cell::OnceCell; + thread_local! { + static POOL: OnceCell = const { OnceCell::new() }; + } + POOL.with(|cell| { + if cell.get().is_none() { + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(1) + .build() + .map_err(|e| crate::KernelError::Failed(format!("cannot start mesh worker: {e}")))?; + let _ = cell.set(pool); + } + let pool = cell.get().ok_or_else(|| crate::KernelError::Failed("missing mesh worker".into()))?; + pool.install(|| guard("mesh worker", || f(item))) + }) + }; + #[cfg(target_arch = "wasm32")] + let one = |item: &T| guard("mesh worker", || f(item)); + map_on_threads(items, max_threads, one) + .into_iter() + .map(|r| r.unwrap_or_else(|| Err(crate::KernelError::Internal("mesh worker failed".into())))) + .collect() +} + /// `f` over `items` as [`for_each_on_threads`] runs it, results in item order (`None` where an /// item panicked). pub fn map_on_threads(items: &[T], max_threads: usize, f: impl Fn(&T) -> R + Sync) -> Vec> { @@ -82,6 +113,19 @@ mod tests { use super::*; use crate::KernelError; + #[test] + fn local_pools_keep_order_and_errors_and_bound_nested_parallelism() { + let items: Vec = (0..32).collect(); + let result = map_with_local_pools(&items, 8, |i| { + #[cfg(not(target_arch = "wasm32"))] + assert_eq!(rayon::current_num_threads(), 1); + if *i == 7 { Err(KernelError::Invalid("seven".into())) } else { Ok(*i * 2) } + }); + for (i, r) in result.iter().enumerate() { + assert_eq!(r.as_ref().ok().copied(), (i != 7).then_some(i * 2)); + } + } + #[test] fn each_item_once_on_threads() { let items: Vec = (0..1000).collect(); diff --git a/crates/kernel/src/record_tests.rs b/crates/kernel/src/record_tests.rs index 35fd1b5d5..e6cd574a3 100644 --- a/crates/kernel/src/record_tests.rs +++ b/crates/kernel/src/record_tests.rs @@ -208,15 +208,23 @@ fn expected_revolution(b: &Body, r: &Region2) -> Vec> { #[test] fn revolve_partial_and_full() { let r = Region2 { outer: rect(10.0, 0.0, 20.0, 5.0), holes: vec![rect(12.0, 1.0, 14.0, 2.0).reversed()] }; - // Under half a turn truck sweeps in two parts, beyond it in three; a full turn has no caps. - for (angle, parts, caps) in [(FRAC_PI_2, 2, 2), (1.5 * PI, 3, 2), (TAU, 3, 0)] { - let b = crate::revolve(&SIDE, std::slice::from_ref(&r), Vec2::ZERO, Vec2::Y, angle).unwrap().pop().unwrap(); - let got = origins(&b); - assert_eq!(got, expected_revolution(&b, &r), "angle {angle}"); - for k in 0..8 { - assert_eq!(got.iter().filter(|o| **o == [P(k)]).count(), parts, "segment {k} at angle {angle}"); + // Under half a turn truck sweeps in two parts, beyond it in three; a full turn has no caps, + // and its planar faces (from the segments square to the axis) are whole (#726), as a partial + // turn's are when it is final (`revolve_whole`). + let segs: Vec = r.outer.segs.iter().chain(r.holes.iter().flat_map(|h| &h.segs)).cloned().collect(); + for whole in [false, true] { + for (angle, parts, caps) in [(FRAC_PI_2, 2, 2), (1.5 * PI, 3, 2), (TAU, 3, 0)] { + let revolve = if whole { crate::revolve_whole } else { crate::revolve }; + let b = revolve(&SIDE, std::slice::from_ref(&r), Vec2::ZERO, Vec2::Y, angle).unwrap().pop().unwrap(); + let got = origins(&b); + assert_eq!(got, expected_revolution(&b, &r), "angle {angle}, whole {whole}"); + for (k, s) in segs.iter().enumerate() { + let square = matches!(s, Seg2::Line { a, b } if (a.y - b.y).abs() < 1e-12); + let want = if (angle == TAU || whole) && square { 1 } else { parts }; + assert_eq!(got.iter().filter(|o| **o == [P(k)]).count(), want, "segment {k} at angle {angle}, whole {whole}"); + } + assert_eq!(got.iter().filter(|o| **o == [START] || **o == [END]).count(), caps); } - assert_eq!(got.iter().filter(|o| **o == [START] || **o == [END]).count(), caps); } } diff --git a/crates/kernel/src/topo.rs b/crates/kernel/src/topo.rs index 32c5c6aa3..60be2b42a 100644 --- a/crates/kernel/src/topo.rs +++ b/crates/kernel/src/topo.rs @@ -663,6 +663,32 @@ pub fn cylinder_face_at(b: &Body, p: Vec3) -> Option { let tol = (size * 1e-4).max(1e-6); let surfs = classify_faces(b, &mesh, nf, tol); let Surf::Cylinder { axis, p: ap, r } = *surfs.get(face as usize)? else { return None }; + Some(cylinder_extent(&mesh, face, axis, ap, r)) +} + +/// The cylindrical face one of whose end circles is centred at `p` (a circle given by its +/// centre, where no face lies), the nearest when several are. +pub fn cylinder_end_at(b: &Body, p: Vec3) -> Option { + let size = b.size(); + let tol = (size * 1e-3).max(1e-3); + let mesh = b.tessellate(tol).ok()?; + let surfs = classify_faces(b, &mesh, b.face_count(), (size * 1e-4).max(1e-6)); + let mut best: Option<(f64, CylinderFace)> = None; + for (face, s) in surfs.iter().enumerate() { + let Surf::Cylinder { axis, p: ap, r } = *s else { continue }; + let c = cylinder_extent(&mesh, u32::try_from(face).ok()?, axis, ap, r); + let v = p - c.axis_point; + let along = v.dot(c.axis); + let off = (v - c.axis * along).len() + (along - c.start).abs().min((c.end - along).abs()); + if off <= tol && best.is_none_or(|(bo, _)| off < bo) { + best = Some((off, c)); + } + } + best.map(|(_, c)| c) +} + +/// The extent along its axis, and the side, of a cylindrical face of a tessellated body. +fn cylinder_extent(mesh: &Mesh, face: u32, axis: Vec3, ap: Vec3, r: f64) -> CylinderFace { let mut lo = f64::INFINITY; let mut hi = f64::NEG_INFINITY; let mut inward = 0.0; @@ -679,5 +705,5 @@ pub fn cylinder_face_at(b: &Body, p: Vec3) -> Option { inward += n.dot(radial); } } - Some(CylinderFace { axis_point: ap, axis, radius: r, start: lo, end: hi, internal: inward < 0.0 }) + CylinderFace { axis_point: ap, axis, radius: r, start: lo, end: hi, internal: inward < 0.0 } } diff --git a/crates/kernel/src/watch.rs b/crates/kernel/src/watch.rs index 840988c27..97f96fb9f 100644 --- a/crates/kernel/src/watch.rs +++ b/crates/kernel/src/watch.rs @@ -34,7 +34,7 @@ pub fn watching(watch: Arc, f: impl FnOnce() -> R) -> R { } /// The watch over this thread's work, to hand to the worker threads it starts. -pub(crate) fn current() -> Option> { +pub fn current() -> Option> { CURRENT.with(|c| c.borrow().clone()) } diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index bdb3c11b1..dfa086c24 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -831,6 +831,59 @@ fn bridged_screenshots_with_grid_or_axes_are_model_renders() { let _ = std::fs::remove_dir_all(&dir); } +/// #1677: a hidden window gives no picture. With no `source`, a model render comes back and says +/// it is one (`fallback`); asked for the window, the tool says why there is none, at once. +#[test] +fn a_hidden_window_screenshot_says_so() { + struct Hidden { + calls: Vec, + } + impl crate::backend::Backend for Hidden { + fn call(&mut self, method: &str, params: Value) -> Result { + self.calls.push(method.to_string()); + match method { + "ui.screenshot" => Err("no frame was presented (window hidden?); use ui.render".into()), + "ui.render" => { + let path = params["path"].as_str().ok_or("missing `path`")?; + std::fs::write(path, b"\x89PNG").map_err(|e| e.to_string())?; + Ok(json!({"path": path, "width": 64, "height": 48})) + } + other => Err(format!("unknown method `{other}`")), + } + } + fn has_ui(&self) -> bool { + true + } + fn describe(&self) -> String { + "app".into() + } + } + let dir = std::env::temp_dir().join(format!("solidcraft-mcp-hidden-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("shot.png").to_string_lossy().to_string(); + let shoot = |extra: Value| { + let mut args = json!({"path": path, "width": 64, "height": 48}); + args.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let mut app = Hidden { calls: Vec::new() }; + let r = crate::tools::call_tool(&mut app, "screenshot", &args); + (app.calls, r) + }; + // The default: the window first, then a model render that says why. + let (calls, r) = shoot(json!({})); + assert!(r["isError"] != json!(true), "{r}"); + assert_eq!(calls, ["ui.screenshot", "ui.render"]); + let info: Value = serde_json::from_str(r["content"][1]["text"].as_str().unwrap()).unwrap(); + assert_eq!(info["source"], "model", "{info}"); + assert!(info["fallback"].as_str().is_some_and(|f| f.contains("window hidden")), "{info}"); + // Asked for the window: an error naming the cause and the way out, and no render. + let (calls, r) = shoot(json!({"source": "window"})); + assert_eq!(r["isError"], json!(true), "{r}"); + let text = r["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("window hidden") && text.contains("source \"model\""), "{text}"); + assert_eq!(calls, ["ui.screenshot"]); + let _ = std::fs::remove_dir_all(&dir); +} + /// #530: in a design with many bodies every feature result lists all of them, so a batch reply /// is mostly the same body list once per step. A compact batch reply names only what each step /// added or changed. diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 561ecc995..138361d03 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -639,11 +639,21 @@ fn capture(b: &mut dyn Backend, a: &Map) -> Result<(Vec, Valu } b.call("ui.render", params) }; + let asked_window = str_arg(a, "source") == Some("window"); + let mut fallback = None; let (info, source) = if window { match b.call("ui.screenshot", json!({"path": path})) { Ok(v) => (v, "window"), - // No presented frame (minimised or hidden window): fall back to a model render. - Err(_) => (render(b)?, "model"), + // Asked for the window: say why there is none, so the caller can show it or ask for + // a model render (#1677). + Err(e) if asked_window => { + return Err(format!("screenshot: the window gave no picture ({e}); show the window, or use source \"model\"")); + } + // No presented frame (minimised or hidden window): a model render, and the reply says so. + Err(e) => { + fallback = Some(e); + (render(b)?, "model") + } } } else { (render(b)?, "model") @@ -659,6 +669,9 @@ fn capture(b: &mut dyn Backend, a: &Map) -> Result<(Vec, Valu }; let bytes = png.len(); let mut reply = json!({"source": source, "path": keep, "width": w, "height": h, "bytes": bytes}); + if let Some(why) = fallback { + reply["fallback"] = json!(format!("the window gave no picture ({why}); this is a model render")); + } // What drew a model render (gpu, gpu-software or cpu), and the warning a CPU render carries. for k in ["renderer", "warning"] { if let Some(v) = info.get(k).filter(|v| !v.is_null()) { diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index b988a4ad2..6abcd321a 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -8,6 +8,10 @@ license.workspace = true [lints] workspace = true +[features] +default = [] +raytrace-cpu = [] + [dependencies] solidcraft-geom = { workspace = true } serde = { workspace = true } @@ -15,6 +19,7 @@ image = { workspace = true, features = ["jpeg"] } moxcms = { workspace = true } png = { workspace = true } sha2 = { workspace = true } +weezl = { workspace = true } [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/render/src/anisotropic_surface.rs b/crates/render/src/anisotropic_surface.rs new file mode 100644 index 000000000..d2f696605 --- /dev/null +++ b/crates/render/src/anisotropic_surface.rs @@ -0,0 +1,294 @@ +//! Original anisotropic GGX reflection with separable Smith masking and Schlick Fresnel. +//! +//! Mathematics: Heitz, JCGT 7(4), 2018, equations 1 and 2, +//! . No external implementation adapted. +//! Sampling here uses the **NDF**, not Heitz's visible-normal (VNDF) sampler: +//! `p(h) = D(h) * n.h`, then `p(l) = p(h) / (4 * v.h)`. +//! Rejected reflections are null events, never resampled or renormalized. +//! +//! This numerical module does not install a renderer, persist a material or alter +//! engineering axes. The visual frame's normal may be a shading normal, but the +//! original geometric normal is required separately to reject below-surface rays. +//! Consumers retain geometric normals for ray spawning and optical boundaries. +//! No shading-normal energy correction, multiple scattering or transmission is modeled. + +use std::f64::consts::{PI, TAU}; + +use solidcraft_geom::Vec3; + +use crate::surface::{MIN_ROUGHNESS, OpaqueSurface, SurfaceError, unit_direction}; + +/// Admission or finite-arithmetic failure in the anisotropic numerical contract. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AnisotropicError { + /// An existing opaque-surface parameter or direction was invalid. + Surface(SurfaceError), + /// A visual frame was not orthogonal, or opposed its geometric normal. + Frame, + /// A variate was not finite in the half-open interval [0, 1). + Variates, + /// A computed density, response or sample weight was not finite/nonnegative. + Arithmetic, +} + +impl From for AnisotropicError { + fn from(value: SurfaceError) -> Self { + Self::Surface(value) + } +} + +impl std::fmt::Display for AnisotropicError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Surface(e) => std::fmt::Display::fmt(e, f), + Self::Frame => f.write_str("visual frame must be orthogonal and face the geometric normal"), + Self::Variates => f.write_str("anisotropic variates must be finite in [0, 1)"), + Self::Arithmetic => f.write_str("anisotropic result must be finite and nonnegative"), + } + } +} +impl std::error::Error for AnisotropicError {} + +type Result = std::result::Result; + +/// Right-handed orthonormal visual axes; independent of engineering material axes. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct VisualFrame { + normal: Vec3, + tangent: Vec3, + bitangent: Vec3, +} + +impl VisualFrame { + /// Normalize finite nonzero orthogonal inputs. An arbitrary oblique tangent is + /// refused rather than silently choosing a different brushed direction. + /// Roundoff within 1e-10 of perpendicular is removed by orthogonalization. + pub fn new(normal: Vec3, tangent: Vec3) -> Result { + let normal = unit_direction(normal)?; + let tangent = unit_direction(tangent)?; + let dot = normal.dot(tangent); + if dot.abs() > 1e-10 { + return Err(AnisotropicError::Frame); + } + let tangent = unit_direction(tangent - normal * dot)?; + let bitangent = unit_direction(normal.cross(tangent))?; + Ok(Self { normal, tangent, bitangent }) + } + + /// Shading normal, never a replacement for an original geometric normal. + pub fn normal(self) -> Vec3 { + self.normal + } + + /// Visual X axis, associated with the first roughness. + pub fn tangent(self) -> Vec3 { + self.tangent + } + + /// Visual Y axis, associated with the second roughness. + pub fn bitangent(self) -> Vec3 { + self.bitangent + } + + fn local(self, direction: Vec3) -> Vec3 { + Vec3::new(self.tangent.dot(direction), self.bitangent.dot(direction), self.normal.dot(direction)) + } + + fn world(self, local: Vec3) -> Vec3 { + self.tangent * local.x + self.bitangent * local.y + self.normal * local.z + } + + fn geometric(self, normal: Vec3) -> Result { + let normal = unit_direction(normal)?; + if normal.dot(self.normal) <= 0.0 { + return Err(AnisotropicError::Frame); + } + Ok(normal) + } +} + +/// A bounded opaque response with two perceptual roughness axes in [0.045, 1]. +/// Alpha is roughness squared, matching [`OpaqueSurface`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct AnisotropicSurface { + base: OpaqueSurface, + roughness_y: f64, +} + +/// One reflected **specular-only** NDF sample. Fields are in world coordinates. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ReflectionSample { + /// Outgoing direction, pointing away from the surface. + pub direction: Vec3, + /// Unconditional density per steradian, without renormalizing null events. + pub pdf: f64, + /// `specular_brdf * shading_cosine / pdf`, in linear RGB. + /// Diffuse response is excluded; its sampling strategy belongs to the consumer. + pub weight: Vec3, +} + +impl AnisotropicSurface { + /// Linear-sRGB reflectance, metal fraction and IOR use the opaque contract. + /// Perfect delta mirrors and out-of-range roughness are refused, not clamped. + pub fn new(base_color: Vec3, metallic: f64, roughness_x: f64, roughness_y: f64, dielectric_ior: f64) -> Result { + let base = OpaqueSurface::new(base_color, metallic, roughness_x, dielectric_ior)?; + if !roughness_y.is_finite() || !(MIN_ROUGHNESS..=1.0).contains(&roughness_y) { + return Err(SurfaceError::Roughness.into()); + } + Ok(Self { base, roughness_y }) + } + + /// Admitted perceptual roughness along visual X and Y. + pub fn roughness(self) -> [f64; 2] { + [self.base.roughness(), self.roughness_y] + } + + fn alpha(self) -> [f64; 2] { + [self.base.roughness().powi(2), self.roughness_y.powi(2)] + } + + fn fresnel(self, cosine: f64) -> Vec3 { + let f0 = self.base.normal_reflectance(); + f0 + (Vec3::new(1.0, 1.0, 1.0) - f0) * (1.0 - cosine.clamp(0.0, 1.0)).powi(5) + } + + fn distribution_local(self, h: Vec3) -> f64 { + if h.z <= 0.0 { + return 0.0; + } + let [ax, ay] = self.alpha(); + let q = (h.x / ax).powi(2) + (h.y / ay).powi(2) + h.z * h.z; + 1.0 / (PI * ax * ay * q * q) + } + + // Smith G1 / cosine, avoiding division by tiny cosines and tan(theta). + fn visibility(self, w: Vec3) -> f64 { + let [ax, ay] = self.alpha(); + 2.0 / (w.z + (w.z * w.z + (ax * w.x).powi(2) + (ay * w.y).powi(2)).sqrt()) + } + + /// GGX normal distribution D, per steradian of microfacet normal. + /// This is not a normalized probability density: [`Self::normal_pdf`] is. + pub fn distribution(self, frame: VisualFrame, half: Vec3) -> Result { + finite_scalar(self.distribution_local(frame.local(unit_direction(half)?))) + } + + /// Projected NDF density `D(h) * n.h` on the upper shading hemisphere. + /// Its integral over that hemisphere is one. + pub fn normal_pdf(self, frame: VisualFrame, half: Vec3) -> Result { + let h = frame.local(unit_direction(half)?); + finite_scalar(self.distribution_local(h) * h.z.max(0.0)) + } + + /// Sample the projected NDF by stretching a radial GGX slope distribution. + /// The inverse radial CDF is `r = sqrt(u/(1-u))`; homogeneous coordinates + /// `(alpha_x*sqrt(u)*cos(phi), alpha_y*sqrt(u)*sin(phi), sqrt(1-u))` + /// avoid a large intermediate radius. No heap, rejection loop or RNG is used. + pub fn sample_normal(self, frame: VisualFrame, variates: [f64; 2]) -> Result { + let [u, azimuth] = variates; + if !variates.into_iter().all(|v| v.is_finite() && (0.0..1.0).contains(&v)) { + return Err(AnisotropicError::Variates); + } + let [ax, ay] = self.alpha(); + let phi = TAU * azimuth; + let radial = u.sqrt(); + let h = unit_direction(Vec3::new(ax * radial * phi.cos(), ay * radial * phi.sin(), (1.0 - u).sqrt()))?; + Ok(unit_direction(frame.world(h))?) + } + + fn directions(self, frame: VisualFrame, geometric: Vec3, view: Vec3, light: Vec3) -> Result> { + let geometric = frame.geometric(geometric)?; + let view = unit_direction(view)?; + let light = unit_direction(light)?; + let (v, l) = (frame.local(view), frame.local(light)); + if v.z <= 0.0 || l.z <= 0.0 || geometric.dot(view) <= 0.0 || geometric.dot(light) <= 0.0 { + return Ok(None); + } + let h = unit_direction(view + light)?; + Ok(Some((v, l, frame.local(h)))) + } + + fn specular_local(self, v: Vec3, l: Vec3, h: Vec3) -> Result { + finite_rgb(self.fresnel(v.dot(h)) * (self.distribution_local(h) * 0.25 * self.visibility(v) * self.visibility(l))) + } + + /// Specular component only, with independent geometric hemisphere rejection. + /// All input directions point away from the surface. + pub fn specular_brdf(self, frame: VisualFrame, geometric: Vec3, view: Vec3, light: Vec3) -> Result { + let Some((v, l, h)) = self.directions(frame, geometric, view, light)? else { return Ok(Vec3::ZERO) }; + self.specular_local(v, l, h) + } + + /// Full opaque BRDF, including the same symmetric attenuated Lambert term as + /// [`OpaqueSurface`]. No radiance, cosine, exposure or display transform included. + /// Equal roughness axes delegate to the existing isotropic numerical contract. + pub fn brdf(self, frame: VisualFrame, geometric: Vec3, view: Vec3, light: Vec3) -> Result { + let Some((v, l, h)) = self.directions(frame, geometric, view, light)? else { return Ok(Vec3::ZERO) }; + if self.base.roughness() == self.roughness_y { + return Ok(self.base.brdf(frame.normal, view, light)?); + } + let specular = self.specular_local(v, l, h)?; + let fv = self.fresnel(v.z); + let fl = self.fresnel(l.z); + let diffuse = self.base.base_color() * ((1.0 - self.base.metallic()) / PI); + finite_rgb( + specular + + Vec3::new( + (1.0 - fv.x) * (1.0 - fl.x) * diffuse.x, + (1.0 - fv.y) * (1.0 - fl.y) * diffuse.y, + (1.0 - fv.z) * (1.0 - fl.z) * diffuse.z, + ), + ) + } + + /// Unconditional reflected-direction density for the specular NDF sampler. + /// Integrates to the acceptance probability, not necessarily one: invalid + /// microfacets and below-geometric/shading-hemisphere reflections are null events. + /// A mixture with a diffuse or environment sampler must use its own mixture PDF. + pub fn reflection_pdf(self, frame: VisualFrame, geometric: Vec3, view: Vec3, light: Vec3) -> Result { + let Some((v, _, h)) = self.directions(frame, geometric, view, light)? else { return Ok(0.0) }; + finite_scalar(self.distribution_local(h) * h.z.max(0.0) / (4.0 * v.dot(h).max(0.0))) + } + + /// One specular NDF attempt. `None` is a zero-contribution event and must + /// still count towards the consumer's sample denominator. Never retry until + /// success. Ray origins/visibility use the consumer's original geometric data. + pub fn sample_reflection(self, frame: VisualFrame, geometric: Vec3, view: Vec3, variates: [f64; 2]) -> Result> { + let geometric = frame.geometric(geometric)?; + let view = unit_direction(view)?; + let half = self.sample_normal(frame, variates)?; + let v = frame.local(view); + if v.z <= 0.0 || geometric.dot(view) <= 0.0 { + return Ok(None); + } + let vh = view.dot(half); + if vh <= 0.0 { + return Ok(None); + } + let light = unit_direction(half * (2.0 * vh) - view)?; + let l = frame.local(light); + if l.z <= 0.0 || geometric.dot(light) <= 0.0 { + return Ok(None); + } + let h = frame.local(half); + let pdf = self.reflection_pdf(frame, geometric, view, light)?; + if pdf <= 0.0 { + return Err(AnisotropicError::Arithmetic); + } + // Cancel D algebraically in f_spec * cos / pdf. No tiny-cosine division. + let weight = finite_rgb(self.fresnel(vh) * (self.visibility(v) * (self.visibility(l) * l.z) * vh / h.z))?; + Ok(Some(ReflectionSample { direction: light, pdf, weight })) + } +} + +fn finite_scalar(value: f64) -> Result { + if value.is_finite() && value >= 0.0 { Ok(value) } else { Err(AnisotropicError::Arithmetic) } +} + +fn finite_rgb(value: Vec3) -> Result { + if value.is_finite() && [value.x, value.y, value.z].into_iter().all(|c| c >= 0.0) { Ok(value) } else { Err(AnisotropicError::Arithmetic) } +} + +#[cfg(test)] +#[path = "anisotropic_surface_tests.rs"] +mod tests; diff --git a/crates/render/src/anisotropic_surface_tests.rs b/crates/render/src/anisotropic_surface_tests.rs new file mode 100644 index 000000000..6e963aebb --- /dev/null +++ b/crates/render/src/anisotropic_surface_tests.rs @@ -0,0 +1,277 @@ +use super::*; + +fn frame() -> VisualFrame { + VisualFrame::new(Vec3::Z, Vec3::X).unwrap() +} + +fn surface(rx: f64, ry: f64) -> AnisotropicSurface { + AnisotropicSurface::new(Vec3::new(0.8, 0.5, 0.2), 1.0, rx, ry, 1.5).unwrap() +} + +fn close(a: f64, b: f64, tolerance: f64) { + assert!((a - b).abs() <= tolerance * (1.0 + a.abs().max(b.abs())), "{a} != {b}"); +} + +fn close_rgb(a: Vec3, b: Vec3, tolerance: f64) { + close(a.x, b.x, tolerance); + close(a.y, b.y, tolerance); + close(a.z, b.z, tolerance); +} + +fn hemisphere(mu: f64, phi: f64) -> Vec3 { + let radius = (1.0 - mu * mu).sqrt(); + Vec3::new(radius * phi.cos(), radius * phi.sin(), mu) +} + +#[test] +fn constructor_rejects_hostile_parameters_on_both_axes() { + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0, MIN_ROUGHNESS.next_down(), 1.01] { + assert!(AnisotropicSurface::new(Vec3::X, 1.0, bad, 0.5, 1.5).is_err()); + assert!(AnisotropicSurface::new(Vec3::X, 1.0, 0.5, bad, 1.5).is_err()); + } + for bad in [f64::NAN, f64::INFINITY, -0.1, 1.1] { + assert!(AnisotropicSurface::new(Vec3::new(bad, 0.0, 0.0), 1.0, 0.5, 0.8, 1.5).is_err()); + assert!(AnisotropicSurface::new(Vec3::X, bad, 0.5, 0.8, 1.5).is_err()); + } + for bad in [f64::NAN, 0.99, 3.01] { + assert!(AnisotropicSurface::new(Vec3::X, 1.0, 0.5, 0.8, bad).is_err()); + } + assert_eq!(surface(MIN_ROUGHNESS, 1.0).roughness(), [MIN_ROUGHNESS, 1.0]); +} + +#[test] +fn frame_is_right_handed_and_requires_an_explicit_orthogonal_axis() { + let f = VisualFrame::new(Vec3::new(0.0, 0.0, 1e308), Vec3::new(1e-300, 0.0, 0.0)).unwrap(); + assert_eq!(f.normal(), Vec3::Z); + assert_eq!(f.tangent(), Vec3::X); + assert_eq!(f.bitangent(), Vec3::Y); + for (n, t) in [(Vec3::ZERO, Vec3::X), (Vec3::Z, Vec3::Z), (Vec3::Z, Vec3::X + Vec3::Z), (Vec3::Z, Vec3::new(f64::NAN, 0.0, 0.0))] { + assert!(VisualFrame::new(n, t).is_err()); + } + let tilted = VisualFrame::new(Vec3::new(0.3, 0.4, 1.0), Vec3::new(0.8, -0.6, 0.0)).unwrap(); + close(tilted.tangent().dot(tilted.normal()), 0.0, 1e-14); + close_rgb(tilted.tangent().cross(tilted.bitangent()), tilted.normal(), 1e-14); +} + +#[test] +fn normal_incidence_matches_independent_ggx_peak() { + let s = surface(0.3, 0.7); + let d = 1.0 / (PI * 0.3_f64.powi(2) * 0.7_f64.powi(2)); + close(s.distribution(frame(), Vec3::Z).unwrap(), d, 1e-14); + close(s.normal_pdf(frame(), Vec3::Z).unwrap(), d, 1e-14); + close_rgb(s.brdf(frame(), Vec3::Z, Vec3::Z, Vec3::Z).unwrap(), Vec3::new(0.8, 0.5, 0.2) * (d / 4.0), 1e-14); +} + +#[test] +fn isotropic_limit_matches_existing_opaque_contract() { + for r in [MIN_ROUGHNESS, 0.3, 0.7, 1.0] { + for metallic in [0.0, 0.5, 1.0] { + let color = Vec3::new(0.8, 0.5, 0.2); + let a = AnisotropicSurface::new(color, metallic, r, r, 1.5).unwrap(); + let opaque = OpaqueSurface::new(color, metallic, r, 1.5).unwrap(); + for (v, l) in [(Vec3::Z, Vec3::Z), (Vec3::new(0.4, 0.2, 0.8), Vec3::new(-0.2, 0.7, 0.6))] { + assert_eq!(a.brdf(frame(), Vec3::Z, v, l).unwrap(), opaque.brdf(Vec3::Z, v, l).unwrap()); + if metallic == 1.0 { + close_rgb(a.specular_brdf(frame(), Vec3::Z, v, l).unwrap(), opaque.brdf(Vec3::Z, v, l).unwrap(), 1e-10); + } + } + } + } +} + +#[test] +fn reciprocal_for_unequal_axes_and_mixed_metal_fraction() { + for metallic in [0.0, 0.4, 1.0] { + let s = AnisotropicSurface::new(Vec3::new(0.8, 0.5, 0.2), metallic, 0.2, 0.9, 2.0).unwrap(); + for (v, l) in [(Vec3::new(0.4, 0.1, 1.0), Vec3::new(-0.3, 0.2, 0.8)), (Vec3::new(1.0, 0.0, 1e-300), Vec3::new(-1.0, 0.0, 1e-300))] { + close_rgb(s.brdf(frame(), Vec3::Z, v, l).unwrap(), s.brdf(frame(), Vec3::Z, l, v).unwrap(), 1e-12); + } + } +} + +#[test] +fn ninety_degree_visual_rotation_swaps_the_brushed_response() { + let s = surface(0.25, 0.8); + let swapped = surface(0.8, 0.25); + let rotated = VisualFrame::new(Vec3::Z, Vec3::Y).unwrap(); + let light = Vec3::new(0.6, 0.0, 0.8); + let initial = s.brdf(frame(), Vec3::Z, Vec3::Z, light).unwrap(); + let turned = s.brdf(rotated, Vec3::Z, Vec3::Z, light).unwrap(); + assert!((initial - turned).len() > 0.01); + close_rgb(turned, swapped.brdf(frame(), Vec3::Z, Vec3::Z, light).unwrap(), 1e-13); + let h = s.sample_normal(frame(), [0.3, 0.2]).unwrap(); + let rotated_h = s.sample_normal(rotated, [0.3, 0.2]).unwrap(); + close_rgb(rotated_h, Vec3::new(-h.y, h.x, h.z), 1e-14); +} + +#[test] +fn geometric_and_shading_hemispheres_are_independent() { + let shading = VisualFrame::new(Vec3::new(0.8, 0.0, 0.6), Vec3::Y).unwrap(); + let light = Vec3::new(0.99, 0.0, -0.1); + let s = surface(0.5, 0.8); + assert!(shading.normal().dot(light) > 0.0); + assert_eq!(s.brdf(shading, Vec3::Z, Vec3::Z, light).unwrap(), Vec3::ZERO); + assert_eq!(s.reflection_pdf(shading, Vec3::Z, Vec3::Z, light).unwrap(), 0.0); + assert!(s.brdf(frame(), -Vec3::Z, Vec3::Z, Vec3::Z).is_err()); + assert_eq!(s.brdf(frame(), Vec3::Z, Vec3::Z, Vec3::X).unwrap(), Vec3::ZERO); + assert_eq!(s.brdf(frame(), Vec3::Z, -Vec3::Z, Vec3::Z).unwrap(), Vec3::ZERO); +} + +#[test] +fn grazing_and_extreme_finite_direction_magnitudes_remain_finite() { + for (rx, ry) in [(MIN_ROUGHNESS, 1.0), (1.0, MIN_ROUGHNESS), (MIN_ROUGHNESS, MIN_ROUGHNESS)] { + let s = surface(rx, ry); + for (v, l) in [(Vec3::new(1.0, 0.0, 1e-300), Vec3::new(-1.0, 0.0, 1e-300)), (Vec3::new(1e308, 1e308, 1e308), Vec3::new(-1e-300, 0.0, 1e-300))] + { + let b = s.brdf(frame(), Vec3::Z, v, l).unwrap(); + assert!(b.is_finite() && b.x >= 0.0 && b.y >= 0.0 && b.z >= 0.0); + } + for u in [0.0, f64::from_bits(1), 0.5, 1.0_f64.next_down()] { + let h = s.sample_normal(frame(), [u, 0.5]).unwrap(); + assert!(h.is_finite() && h.z > 0.0); + assert!(s.normal_pdf(frame(), h).unwrap().is_finite()); + } + let view = Vec3::new(1.0, 0.0, 1e-300); + let sample = s.sample_reflection(frame(), Vec3::Z, view, [0.0, 0.0]).unwrap().unwrap(); + assert!(sample.pdf.is_finite() && sample.pdf > 0.0 && sample.weight.is_finite()); + // A mathematical density beyond f64 is a typed refusal, never clamped. + assert_eq!(s.sample_reflection(frame(), Vec3::Z, Vec3::new(1.0, 0.0, f64::from_bits(1)), [0.0, 0.0]), Err(AnisotropicError::Arithmetic)); + } +} + +#[test] +fn malformed_directions_and_variates_fail_without_clamping() { + let s = surface(0.5, 0.8); + for bad in [Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 1.0), Vec3::new(f64::INFINITY, 0.0, 1.0)] { + assert!(s.brdf(frame(), Vec3::Z, bad, Vec3::Z).is_err()); + assert!(s.brdf(frame(), bad, Vec3::Z, Vec3::Z).is_err()); + assert!(s.brdf(frame(), Vec3::Z, Vec3::Z, bad).is_err()); + assert!(s.normal_pdf(frame(), bad).is_err()); + } + for bad in [-0.1, 1.0, f64::NAN, f64::INFINITY] { + assert!(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [bad, 0.5]).is_err()); + assert!(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [0.5, bad]).is_err()); + } +} + +#[test] +fn sampled_slopes_follow_the_independent_inverse_radial_cdf() { + let s = surface(0.3, 0.7); + for u in [0.0, 0.01, 0.3, 0.8, 0.9999] { + for azimuth in [0.0, 0.2, 0.5, 0.8] { + let h = s.sample_normal(frame(), [u, azimuth]).unwrap(); + let sx = h.x / (0.3_f64.powi(2) * h.z); + let sy = h.y / (0.7_f64.powi(2) * h.z); + let radius2 = sx * sx + sy * sy; + close(radius2 / (1.0 + radius2), u, 1e-13); + close_rgb(h, s.sample_normal(frame(), [u, azimuth]).unwrap(), 0.0); + } + } +} + +#[test] +fn reflection_samples_match_pdf_and_specular_throughput() { + let s = surface(0.4, 0.8); + let view = unit_direction(Vec3::new(0.2, 0.3, 1.0)).unwrap(); + let mut accepted = 0; + let mut null = 0; + for i in 0..32 { + for j in 0..32 { + let uv = [(i as f64 + 0.5) / 32.0, (j as f64 + 0.5) / 32.0]; + match s.sample_reflection(frame(), Vec3::Z, view, uv).unwrap() { + Some(sample) => { + accepted += 1; + close(sample.pdf, s.reflection_pdf(frame(), Vec3::Z, view, sample.direction).unwrap(), 1e-13); + let expected = s.specular_brdf(frame(), Vec3::Z, view, sample.direction).unwrap() * (sample.direction.z / sample.pdf); + close_rgb(sample.weight, expected, 1e-10); + } + None => null += 1, + } + } + } + assert!(accepted > 0 && null > 0); + assert_eq!(accepted + null, 1024); +} + +#[test] +fn unit_roughness_normal_view_has_half_null_mass_and_uniform_reflection_pdf() { + let s = surface(1.0, 1.0); + assert!(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [0.75, 0.3]).unwrap().is_none()); + let sample = s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [0.25, 0.3]).unwrap().unwrap(); + close(sample.pdf, 1.0 / (4.0 * PI), 1e-14); + let mut accepted = 0; + for i in 0..1024 { + accepted += usize::from(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [(i as f64 + 0.5) / 1024.0, 0.3]).unwrap().is_some()); + } + assert_eq!(accepted, 512); + // p(l)=1/(4*pi) over the upper hemisphere: valid mass exactly1/2. + close(s.reflection_pdf(frame(), Vec3::Z, Vec3::Z, Vec3::Z).unwrap() * (2.0 * PI), 0.5, 1e-14); + assert_eq!(s.reflection_pdf(frame(), Vec3::Z, Vec3::Z, -Vec3::Z).unwrap(), 0.0); +} + +#[test] +fn invisible_microfacets_are_null_and_weights_exclude_the_diffuse_substrate() { + let s = AnisotropicSurface::new(Vec3::new(0.8, 0.5, 0.2), 0.0, 1.0, 1.0, 1.5).unwrap(); + let view = unit_direction(Vec3::new(0.99, 0.0, 0.1)).unwrap(); + assert!(s.sample_reflection(frame(), Vec3::Z, view, [0.9, 0.5]).unwrap().is_none()); + let sample = s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [0.1, 0.2]).unwrap().unwrap(); + let scale = sample.direction.z / sample.pdf; + let specular = s.specular_brdf(frame(), Vec3::Z, Vec3::Z, sample.direction).unwrap() * scale; + let total = s.brdf(frame(), Vec3::Z, Vec3::Z, sample.direction).unwrap() * scale; + close_rgb(sample.weight, specular, 1e-13); + assert!(total.x > sample.weight.x + 0.1); + assert_eq!(s.normal_pdf(frame(), -Vec3::Z).unwrap(), 0.0); + assert_eq!(s.normal_pdf(frame(), Vec3::X).unwrap(), 0.0); +} + +#[test] +fn quadrature_distinguishes_normal_pdf_mass_from_valid_reflection_mass() { + // Finite midpoint grids resolve these broad lobes only. Narrowest admitted + // roughness is tested analytically and with inverse-CDF samples elsewhere. + const N: usize = 256; + for (rx, ry) in [(1.0, 1.0), (0.6, 0.9)] { + let s = surface(rx, ry); + let mut normal_mass = 0.0; + let mut valid_mass = 0.0; + let mut accepted = 0; + for i in 0..N { + for j in 0..N { + let u = (i as f64 + 0.5) / N as f64; + let azimuth = (j as f64 + 0.5) / N as f64; + let l = hemisphere(u, TAU * azimuth); + normal_mass += s.normal_pdf(frame(), l).unwrap(); + valid_mass += s.reflection_pdf(frame(), Vec3::Z, Vec3::Z, l).unwrap(); + accepted += usize::from(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [u, azimuth]).unwrap().is_some()); + } + } + let domega = TAU / (N * N) as f64; + close(normal_mass * domega, 1.0, 0.001); + close(valid_mass * domega, accepted as f64 / (N * N) as f64, 0.003); + assert!(valid_mass * domega < 1.0); + } +} + +#[test] +fn broad_lobe_importance_estimate_agrees_with_integrated_energy() { + // White metal, normal view, deterministic256² grids. A scoped consistency + // check, not universal energy certification or a variance/convergence claim. + const N: usize = 256; + let s = AnisotropicSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 0.6, 0.9, 1.5).unwrap(); + let mut integrated = Vec3::ZERO; + let mut sampled = Vec3::ZERO; + for i in 0..N { + for j in 0..N { + let uv = [(i as f64 + 0.5) / N as f64, (j as f64 + 0.5) / N as f64]; + let light = hemisphere(uv[0], TAU * uv[1]); + integrated += s.specular_brdf(frame(), Vec3::Z, Vec3::Z, light).unwrap() * light.z; + if let Some(sample) = s.sample_reflection(frame(), Vec3::Z, Vec3::Z, uv).unwrap() { + sampled += sample.weight; + } + } + } + integrated = integrated * (TAU / (N * N) as f64); + sampled = sampled / (N * N) as f64; // Includes ALL null attempts. + assert!(integrated.x > 0.0 && integrated.x <= 1.001); + assert!(sampled.x > 0.0 && sampled.x <= 1.001); + close_rgb(integrated, sampled, 0.003); +} diff --git a/crates/render/src/gif.rs b/crates/render/src/gif.rs new file mode 100644 index 000000000..278708a87 --- /dev/null +++ b/crates/render/src/gif.rs @@ -0,0 +1,321 @@ +//! Animated GIF (GIF89a) from RGBA frames, for motion animations. Every frame shares one palette, +//! so a colour keeps its value from frame to frame, and each frame after the first stores only +//! the rectangle that changed. The palette splits the frames' colours where that removes the +//! most squared colour error, so a small, strongly coloured part (a red part, a thin trace line) +//! keeps its colour instead of being averaged into the shading around it. No dithering: what +//! stands still stays still. + +use std::collections::HashMap; + +/// Colours a GIF palette holds. +const PALETTE: usize = 256; + +/// Frames (straight RGBA, `width × height`, rows top to bottom; alpha is ignored) as a GIF that +/// loops forever and shows each frame for `delay` hundredths of a second. `None` without frames, +/// for a frame of the wrong size, or a side GIF can't store (above 65535). +pub fn gif(width: usize, height: usize, frames: &[Vec], delay: u16) -> Option> { + let (w, h) = (u16::try_from(width).ok().filter(|w| *w > 0)?, u16::try_from(height).ok().filter(|h| *h > 0)?); + let bytes = width.checked_mul(height)?.checked_mul(4)?; + if frames.is_empty() || frames.iter().any(|f| f.len() != bytes) { + return None; + } + let (palette, index) = palette(frames); + let mut out = Vec::with_capacity(1024); + out.extend_from_slice(b"GIF89a"); + out.extend_from_slice(&w.to_le_bytes()); + out.extend_from_slice(&h.to_le_bytes()); + // A global table of 256 colours (8 bits each), background colour 0, square pixels. + out.extend_from_slice(&[0xF7, 0, 0]); + for k in 0..PALETTE { + out.extend_from_slice(palette.get(k).unwrap_or(&[0, 0, 0])); + } + // Loop forever (the NETSCAPE2.0 extension every viewer reads). + out.extend_from_slice(&[0x21, 0xFF, 0x0B]); + out.extend_from_slice(b"NETSCAPE2.0"); + out.extend_from_slice(&[0x03, 0x01, 0x00, 0x00, 0x00]); + let mut previous: Option> = None; + for frame in frames { + let now = indices(frame, &index); + let (x0, y0, x1, y1) = previous.as_deref().map_or(Some((0, 0, width - 1, height - 1)), |p| changed(p, &now, width)).unwrap_or((0, 0, 0, 0)); + let mut rect = Vec::with_capacity((x1 - x0 + 1) * (y1 - y0 + 1)); + for y in y0..=y1 { + rect.extend_from_slice(now.get(y * width + x0..=y * width + x1)?); + } + // Graphic control: kept on screen under the next frame (disposal 1), shown `delay`. + out.extend_from_slice(&[0x21, 0xF9, 0x04, 0x04]); + out.extend_from_slice(&delay.to_le_bytes()); + out.extend_from_slice(&[0, 0]); + out.push(0x2C); + for v in [x0, y0, x1 - x0 + 1, y1 - y0 + 1] { + out.extend_from_slice(&u16::try_from(v).ok()?.to_le_bytes()); + } + out.push(0); + out.push(8); + let data = weezl::encode::Encoder::new(weezl::BitOrder::Lsb, 8).encode(&rect).ok()?; + for block in data.chunks(255) { + out.push(block.len() as u8); + out.extend_from_slice(block); + } + out.push(0); + previous = Some(now); + } + out.push(0x3B); + Some(out) +} + +/// The pixels' colours, `0xRRGGBB`. +fn colours(frame: &[u8]) -> impl Iterator + '_ { + frame.as_chunks::<4>().0.iter().map(|&[r, g, b, _]| (u32::from(r) << 16) | (u32::from(g) << 8) | u32::from(b)) +} + +/// A frame's palette indices. +fn indices(frame: &[u8], index: &HashMap) -> Vec { + let mut last = (u32::MAX, 0); + colours(frame) + .map(|k| { + if k != last.0 { + last = (k, index.get(&k).copied().unwrap_or(0)); + } + last.1 + }) + .collect() +} + +/// The smallest rectangle (x0, y0, x1, y1, inclusive) holding every pixel that differs, or `None` +/// when none does. +fn changed(before: &[u8], now: &[u8], width: usize) -> Option<(usize, usize, usize, usize)> { + let mut r: Option<(usize, usize, usize, usize)> = None; + for (i, _) in before.iter().zip(now).enumerate().filter(|(_, (a, b))| a != b) { + let (x, y) = (i % width, i / width); + r = Some(r.map_or((x, y, x, y), |(x0, y0, x1, y1)| (x0.min(x), y0.min(y), x1.max(x), y1.max(y)))); + } + r +} + +/// How many pixels have a colour, and the sums its mean and squared error follow from. +#[derive(Clone, Copy, Default)] +struct Sums { + n: f64, + s: [f64; 3], + q: f64, +} + +impl Sums { + fn of(rgb: u32, n: u64) -> Sums { + let n = n as f64; + let c = [f64::from((rgb >> 16) as u8), f64::from((rgb >> 8) as u8), f64::from(rgb as u8)]; + Sums { n, s: c.map(|v| n * v), q: n * c.iter().map(|v| v * v).sum::() } + } + fn add(&mut self, o: &Sums) { + self.n += o.n; + self.q += o.q; + self.s.iter_mut().zip(o.s).for_each(|(a, b)| *a += b); + } + fn minus(&self, o: &Sums) -> Sums { + let mut s = *self; + s.n -= o.n; + s.q -= o.q; + s.s.iter_mut().zip(o.s).for_each(|(a, b)| *a -= b); + s + } + /// The squared distance of the pixels from their mean colour. + fn error(&self) -> f64 { + if self.n <= 0.0 { 0.0 } else { self.q - self.s.iter().map(|s| s * s).sum::() / self.n } + } + fn mean(&self) -> [u8; 3] { + self.s.map(|s| if self.n > 0.0 { (s / self.n).round().clamp(0.0, 255.0) as u8 } else { 0 }) + } +} + +/// A set of the frames' colours that becomes one palette entry, and its best split: (error +/// removed, channel, the largest value of that channel on the low side). +struct Group { + colours: Vec<(u32, Sums)>, + sums: Sums, + split: Option<(f64, u32, u8)>, +} + +impl Group { + fn new(colours: Vec<(u32, Sums)>) -> Group { + let mut sums = Sums::default(); + colours.iter().for_each(|(_, s)| sums.add(s)); + let mut best: Option<(f64, u32, u8)> = None; + for channel in [16u32, 8, 0] { + let mut bins = [Sums::default(); 256]; + for (k, s) in &colours { + if let Some(b) = bins.get_mut(usize::from((k >> channel) as u8)) { + b.add(s); + } + } + let mut low = Sums::default(); + for (v, b) in bins.iter().enumerate() { + low.add(b); + if low.n <= 0.0 || low.n >= sums.n { + continue; + } + let gain = sums.error() - low.error() - sums.minus(&low).error(); + if best.is_none_or(|(g, _, _)| gain > g) { + best = Some((gain, channel, v as u8)); + } + } + } + Group { colours, sums, split: best.filter(|(g, _, _)| *g > 0.0) } + } +} + +/// One palette for all frames (up to 256 colours) and each colour's index in it. Every colour +/// gets its own entry while there are 256 or fewer. +fn palette(frames: &[Vec]) -> (Vec<[u8; 3]>, HashMap) { + let mut counts: HashMap = HashMap::new(); + for frame in frames { + // Runs of one colour (the background) are counted once per run. + let mut run = (u32::MAX, 0u64); + for k in colours(frame) { + if k != run.0 { + if run.1 > 0 { + *counts.entry(run.0).or_default() += run.1; + } + run = (k, 0); + } + run.1 += 1; + } + if run.1 > 0 { + *counts.entry(run.0).or_default() += run.1; + } + } + let mut groups = vec![Group::new(counts.into_iter().map(|(k, n)| (k, Sums::of(k, n))).collect())]; + while groups.len() < PALETTE { + let Some(i) = groups.iter().enumerate().filter_map(|(i, g)| g.split.map(|s| (i, s.0))).max_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i) + else { + break; + }; + let g = groups.swap_remove(i); + let Some((_, channel, at)) = g.split else { break }; + let (low, high) = g.colours.into_iter().partition(|(k, _)| (k >> channel) as u8 <= at); + groups.push(Group::new(low)); + groups.push(Group::new(high)); + } + let mut index = HashMap::new(); + for (i, g) in groups.iter().enumerate() { + for (k, _) in &g.colours { + index.insert(*k, i as u8); + } + } + (groups.iter().map(|g| g.sums.mean()).collect(), index) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The frames of a GIF this module wrote, as RGBA (each frame drawn over the one before). + fn decode(gif: &[u8]) -> (usize, usize, Vec>, Vec) { + let u16_at = |i: usize| usize::from(u16::from_le_bytes([gif[i], gif[i + 1]])); + assert_eq!(&gif[..6], b"GIF89a"); + let (w, h) = (u16_at(6), u16_at(8)); + let table = &gif[13..13 + 768]; + let mut at = 13 + 768; + let (mut frames, mut delays) = (Vec::new(), Vec::new()); + let mut canvas = vec![0u8; w * h * 4]; + loop { + match gif[at] { + 0x3B => break, + 0x21 => { + if gif[at + 1] == 0xF9 { + delays.push(u16_at(at + 4) as u16); + } + at += 2; + while gif[at] != 0 { + at += usize::from(gif[at]) + 1; + } + at += 1; + } + 0x2C => { + let (x0, y0, fw, fh) = (u16_at(at + 1), u16_at(at + 3), u16_at(at + 5), u16_at(at + 7)); + at += 11; + let mut data = Vec::new(); + while gif[at] != 0 { + data.extend_from_slice(&gif[at + 1..at + 1 + usize::from(gif[at])]); + at += usize::from(gif[at]) + 1; + } + at += 1; + let pixels = weezl::decode::Decoder::new(weezl::BitOrder::Lsb, 8).decode(&data).unwrap(); + assert_eq!(pixels.len(), fw * fh); + for (i, p) in pixels.iter().enumerate() { + let o = ((y0 + i / fw) * w + x0 + i % fw) * 4; + let c = usize::from(*p) * 3; + canvas[o..o + 4].copy_from_slice(&[table[c], table[c + 1], table[c + 2], 255]); + } + frames.push(canvas.clone()); + } + b => panic!("unexpected block {b:#x} at {at}"), + } + } + (w, h, frames, delays) + } + + fn frame(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + (0..w * h).flat_map(|i| f(i % w, i / w).into_iter().chain([255])).collect() + } + + #[test] + fn few_colours_come_back_exactly_and_frames_keep_their_size() { + let (w, h) = (37, 23); + let a = frame(w, h, |x, y| { + if x < 10 { + [250, 30, 30] + } else if y > 15 { + [20, 200, 60] + } else { + [220, 224, 230] + } + }); + // The second frame moves the red band: only that part changes. + let b = frame(w, h, |x, y| { + if (5..15).contains(&x) { + [250, 30, 30] + } else if y > 15 { + [20, 200, 60] + } else { + [220, 224, 230] + } + }); + let bytes = gif(w, h, &[a.clone(), b.clone(), b.clone()], 5).unwrap(); + let (dw, dh, frames, delays) = decode(&bytes); + assert_eq!((dw, dh, delays), (w, h, vec![5, 5, 5])); + assert_eq!(frames, vec![a, b.clone(), b]); + } + + #[test] + fn a_thin_saturated_line_keeps_its_colour_among_many_shades() { + let (w, h) = (300, 200); + // A grey shading with far more than 256 shades, a red part and a 1-pixel green line. + let f = frame(w, h, |x, y| { + if y == 100 { + [30, 220, 40] + } else if (40..80).contains(&x) && (40..80).contains(&y) { + [200 + (y as u8 % 40), 30, 30] + } else { + let g = 60 + ((x * 180) / w) as u8; + [g, g.saturating_add((y / 4) as u8), g.saturating_add(10)] + } + }); + let (_, _, frames, _) = decode(&gif(w, h, std::slice::from_ref(&f), 4).unwrap()); + let px = |img: &[u8], x: usize, y: usize| img[(y * w + x) * 4..(y * w + x) * 4 + 3].to_vec(); + assert_eq!(px(&frames[0], 150, 100), vec![30, 220, 40], "the line keeps its colour"); + let red = px(&frames[0], 60, 60); + assert!(red[0] > 180 && red[1] < 60 && red[2] < 60, "the part stays red: {red:?}"); + // Elsewhere each channel is close to the original. + let worst = f.chunks(4).zip(frames[0].chunks(4)).map(|(a, b)| (0..3).map(|c| a[c].abs_diff(b[c])).max().unwrap()).max().unwrap(); + assert!(worst <= 12, "worst channel error {worst}"); + } + + #[test] + fn bad_input_is_none_not_a_crash() { + assert!(gif(4, 4, &[], 5).is_none()); + assert!(gif(4, 4, &[vec![0; 63]], 5).is_none()); + assert!(gif(0, 4, &[vec![]], 5).is_none()); + assert!(gif(70_000, 1, &[vec![0; 280_000]], 5).is_none()); + assert!(gif(usize::MAX, 2, &[vec![0; 8]], 5).is_none()); + } +} diff --git a/crates/render/src/job/encoding.rs b/crates/render/src/job/encoding.rs new file mode 100644 index 000000000..7d8bb19d2 --- /dev/null +++ b/crates/render/src/job/encoding.rs @@ -0,0 +1,133 @@ +//! Shared bounded, cancellable sRGB PNG row encoder for CPU image integrators. +use super::{CancelToken, ErrorCode, JobError, Result}; +use std::io::Write; +use std::sync::{Arc, Mutex}; + +struct BufferWriter { + bytes: Arc>>, + limit: usize, + cancel: CancelToken, +} + +impl Write for BufferWriter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + if self.cancel.is_cancelled() { + return Err(std::io::Error::other("render cancelled")); + } + let mut out = self.bytes.lock().map_err(|_| std::io::Error::other("PNG output lock poisoned"))?; + if out.len().checked_add(bytes.len()).is_none_or(|n| n > self.limit) { + return Err(std::io::Error::other("PNG output exceeds its byte budget")); + } + out.try_reserve_exact(bytes.len()).map_err(|_| std::io::Error::other("PNG allocation failed"))?; + out.extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + if self.cancel.is_cancelled() { Err(std::io::Error::other("render cancelled")) } else { Ok(()) } + } +} + +pub(crate) struct PngEncoding { + bytes: Arc>>, + writer: Option>, + width: usize, + height: usize, + row: usize, + cancel: CancelToken, +} + +impl PngEncoding { + pub(crate) fn new(width: u32, height: u32, limit: u64, cancel: CancelToken) -> Result { + cancel.check()?; + let limit = usize::try_from(limit).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "PNG byte budget exceeds addressable memory"))?; + let bytes = Arc::new(Mutex::new(Vec::new())); + let writer = BufferWriter { bytes: bytes.clone(), limit, cancel: cancel.clone() }; + let mut encoder = png::Encoder::new(writer, width, height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + encoder.set_source_srgb(png::SrgbRenderingIntent::Perceptual); + let writer = + encoder.write_header().and_then(|w| w.into_stream_writer()).map_err(|e| JobError::new(ErrorCode::EncodingFailed, e.to_string()))?; + Ok(Self { bytes, writer: Some(writer), width: width as usize, height: height as usize, row: 0, cancel }) + } + + pub(crate) fn row(&self) -> usize { + self.row + } + + /// Writes at most one row; callers retain the four-row-per-quantum limit. + pub(crate) fn step(&mut self, rgba: &[u8]) -> Result>> { + self.cancel.check()?; + if self.row < self.height { + let length = self.width.checked_mul(4).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "PNG row overflow"))?; + let start = self.row.checked_mul(length).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "PNG row offset overflow"))?; + let end = start.checked_add(length).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "PNG row end overflow"))?; + let row = rgba.get(start..end).ok_or_else(|| JobError::new(ErrorCode::InvalidScene, "missing PNG row"))?; + self.writer + .as_mut() + .ok_or_else(|| JobError::new(ErrorCode::Internal, "missing PNG writer"))? + .write_all(row) + .map_err(|e| JobError::new(ErrorCode::EncodingFailed, e.to_string()))?; + self.row += 1; + return Ok(None); + } + self.writer + .take() + .ok_or_else(|| JobError::new(ErrorCode::Internal, "missing PNG writer"))? + .finish() + .map_err(|e| JobError::new(ErrorCode::EncodingFailed, e.to_string()))?; + self.cancel.check()?; + let mut bytes = self.bytes.lock().map_err(|_| JobError::new(ErrorCode::Internal, "PNG output lock poisoned"))?; + let png = std::mem::take(&mut *bytes); + if !png.starts_with(b"\x89PNG\r\n\x1a\n") { + return Err(JobError::new(ErrorCode::EncodingFailed, "invalid PNG output")); + } + Ok(Some(png)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rows_roundtrip_and_cancel_before_finish_never_returns_png() { + let rgba = [20, 40, 60, 255, 80, 100, 120, 255]; + let cancel = CancelToken::default(); + let mut encoder = PngEncoding::new(1, 2, 65536, cancel.clone()).unwrap(); + assert!(encoder.step(&rgba).unwrap().is_none()); + assert_eq!(encoder.row(), 1); + assert!(encoder.step(&rgba).unwrap().is_none()); + assert_eq!(encoder.row(), 2); + cancel.cancel(); + assert_eq!(encoder.step(&rgba).unwrap_err().code, ErrorCode::Cancelled); + + let mut encoder = PngEncoding::new(1, 2, 65536, CancelToken::default()).unwrap(); + assert!(encoder.step(&rgba).unwrap().is_none()); + assert!(encoder.step(&rgba).unwrap().is_none()); + let png = encoder.step(&rgba).unwrap().unwrap(); + let decoded = image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), (1, 2)); + assert_eq!(decoded.as_raw(), &rgba); + } + + #[test] + fn encoded_byte_budget_and_missing_rows_are_errors() { + assert!(PngEncoding::new(1, 1, 1, CancelToken::default()).is_err()); + let mut encoder = PngEncoding::new(1, 1, 65536, CancelToken::default()).unwrap(); + assert_eq!(encoder.step(&[]).unwrap_err().code, ErrorCode::InvalidScene); + } + #[test] + fn png_output_budget_and_cancellation_fail_without_partial_publication() { + let bytes = Arc::new(Mutex::new(Vec::new())); + let cancel = CancelToken::default(); + let mut writer = BufferWriter { bytes: bytes.clone(), limit: 4, cancel: cancel.clone() }; + writer.write_all(b"PNG").unwrap(); + assert!(writer.write_all(b"too large").is_err()); + assert_eq!(*bytes.lock().unwrap(), b"PNG"); + cancel.cancel(); + assert!(writer.write_all(b"x").is_err()); + assert!(writer.flush().is_err()); + assert_eq!(*bytes.lock().unwrap(), b"PNG"); + } +} diff --git a/crates/render/src/job/host.rs b/crates/render/src/job/host.rs index 12f09f6fd..01cd554fc 100644 --- a/crates/render/src/job/host.rs +++ b/crates/render/src/job/host.rs @@ -12,8 +12,8 @@ use std::sync::{ use serde::Serialize; use super::{ - Admission, AlphaConvention, CancelToken, ColourEncoding, ErrorCode, FrameInfo, ImageRequest, ImageTask, JobError, JobId, Phase, Progress, Result, - TaskPoll, admit, + Admission, AlphaConvention, CancelToken, ColourEncoding, ErrorCode, FrameInfo, ImageRequest, ImageTask, Integrator, JobError, JobId, Phase, + Progress, Result, TaskPoll, admit, }; use crate::{ Availability, ExecutorDescriptor, ExecutorId, ProductScene, RenderFormat, RenderLimits, RenderMode, RenderOperation, RenderProfile, ScratchLayout, @@ -73,6 +73,18 @@ impl Drop for Reservation { } } +/// Retained runtime input capacities survive work/PNG eviction through status handles. +fn retained_request_bytes(request: &ImageRequest) -> Result { + request.raytrace.as_ref().map_or(Ok(0), |options| options.retained_bytes()) +} + +fn admit_request_sum(work_bytes: u64, request_bytes: u64) -> Result<()> { + if work_bytes.checked_add(request_bytes).is_none_or(|sum| sum > super::image::MAX_JOB_BYTES) { + return Err(JobError::new(ErrorCode::LimitExceeded, "render work and retained request exceed 384 MiB per-job admission")); + } + Ok(()) +} + /// Borrow encoded bytes through the frame, so retaining the data also retains its admission lease. pub struct RenderFrame { pub info: FrameInfo, @@ -87,6 +99,8 @@ impl RenderFrame { #[derive(Clone, Debug, Serialize)] pub struct JobStatus { + #[serde(skip_serializing_if = "Option::is_none")] + pub environment: Option, pub job: JobId, pub scene_generation: u64, pub request: ImageRequest, @@ -102,6 +116,8 @@ struct Data { frame: Option>, } struct Record { + environment: Option, + _request_reservation: Option, id: JobId, scene_generation: u64, request: ImageRequest, @@ -129,6 +145,7 @@ impl JobHandle { pub fn status(&self) -> Result { let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; Ok(JobStatus { + environment: self.0.environment.clone(), job: self.0.id, scene_generation: self.0.scene_generation, request: self.0.request.clone(), @@ -176,16 +193,78 @@ impl JobHandle { } struct Work { + environment: Option, scene: ProductScene, handle: JobHandle, reservation: Reservation, } struct Running { - task: ImageTask, + task: Option, handle: JobHandle, reservation: Option, } +/// One fallibly allocated task, keeping the dispatch enum small in either build. +/// Its bounded metadata allocation fits the existing per-job task allowance. +struct TaskSlot(Vec); +impl TaskSlot { + fn new(task: T) -> Result { + if std::mem::size_of::() > 4096 { + return Err(JobError::new(ErrorCode::LimitExceeded, "render task metadata exceeds its admission allowance")); + } + let mut tasks = Vec::new(); + tasks.try_reserve_exact(1).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve render task slot"))?; + if tasks.capacity() != 1 { + return Err(JobError::new(ErrorCode::LimitExceeded, "render task slot exceeds its bounded capacity")); + } + tasks.push(task); + Ok(Self(tasks)) + } + fn get_mut(&mut self) -> Result<&mut T> { + self.0.first_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render task slot")) + } +} +enum WorkTask { + Raster(TaskSlot), + #[cfg(feature = "raytrace-cpu")] + Raytrace(TaskSlot), +} + +impl WorkTask { + fn new( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + environment: Option, + ) -> Result { + let _ = &environment; + match request.integrator { + Integrator::Raster => ImageTask::new(scene, request, cancel).and_then(TaskSlot::new).map(Self::Raster), + Integrator::Raytrace => { + #[cfg(feature = "raytrace-cpu")] + { + let options = request.raytrace.clone().unwrap_or_default(); + crate::raytrace::image::ImageTask::new_with_environment(scene, request, cancel, options, environment) + .and_then(TaskSlot::new) + .map(Self::Raytrace) + } + #[cfg(not(feature = "raytrace-cpu"))] + { + Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")) + } + } + } + } + + fn step(&mut self, units: usize) -> Result { + match self { + Self::Raster(task) => task.get_mut()?.step(units), + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => task.get_mut()?.step(units), + } + } +} + fn terminal(handle: &JobHandle, error: JobError) { if let Ok(mut data) = handle.0.data.lock() { if data.progress.phase == Phase::Completed { @@ -214,9 +293,9 @@ impl Running { { data.progress.phase = Phase::Preparing; } - let task = ImageTask::new(work.scene, work.handle.0.request.clone(), work.handle.0.cancel.clone()); + let task = WorkTask::new(work.scene, work.handle.0.request.clone(), work.handle.0.cancel.clone(), work.environment); match task { - Ok(task) => Some(Self { task, handle: work.handle, reservation: Some(work.reservation) }), + Ok(task) => Some(Self { task: Some(task), handle: work.handle, reservation: Some(work.reservation) }), Err(e) => { terminal(&work.handle, e); None @@ -225,7 +304,7 @@ impl Running { } fn advance(&mut self, units: usize) -> Result { - let result = self.task.step(units)?; + let result = self.task.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render task"))?.step(units)?; let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; // The final publication check is under the same lock as cancellation. if self.handle.0.cancel.is_cancelled() { @@ -240,6 +319,9 @@ impl Running { Ok(true) } TaskPoll::Complete(png) => { + // Release all integrator scratch before shrinking the shared lease + // to the completed PNG. Retained task metadata also owns memory. + self.task = None; let mut reservation = self.reservation.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render reservation"))?; reservation.shrink(png.capacity() as u64 + 1024)?; let info = FrameInfo { @@ -376,10 +458,39 @@ impl CpuHost { } pub fn descriptor(&self) -> Result { + self.descriptor_for(Integrator::Raster) + } + + /// Check the execution choice without capturing geometry or reserving memory. + pub fn validate_integrator(&self, integrator: Integrator) -> Result<()> { + if !self.is_available() { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU image host has stopped")); + } + if integrator == Integrator::Raytrace && !cfg!(feature = "raytrace-cpu") { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } + if integrator == Integrator::Raytrace && self.kind() != HostKind::NativeWorker { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing requires the native worker host")); + } + Ok(()) + } + + /// Select exactly one executor for this request. Never rely on registry order + /// to choose between raster and raytracing implementations. + pub fn descriptor_for(&self, integrator: Integrator) -> Result { + if integrator == Integrator::Raytrace && !cfg!(feature = "raytrace-cpu") { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } Ok(ExecutorDescriptor { - id: ExecutorId::new("cpu-product").map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?, + id: ExecutorId::new(match integrator { + Integrator::Raster => "cpu-product", + Integrator::Raytrace => "cpu-raytrace", + }) + .map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?, availability: if self.0.shared.stop.load(Ordering::Acquire) { Availability::Unavailable { reason: "CPU image host has stopped".into() } + } else if integrator == Integrator::Raytrace && self.kind() != HostKind::NativeWorker { + Availability::Unavailable { reason: "CPU raytracing requires the native worker host".into() } } else { Availability::Available }, @@ -387,7 +498,11 @@ impl CpuHost { mode: RenderMode::Preview, operation: RenderOperation::Image, formats: vec![RenderFormat::Png], - features: vec![crate::RenderFeature::Pbr], + features: if integrator == Integrator::Raytrace && cfg!(feature = "raytrace-cpu") && self.kind() == HostKind::NativeWorker { + vec![crate::RenderFeature::Pbr, crate::RenderFeature::Hdri] + } else { + vec![crate::RenderFeature::Pbr] + }, }], limits: RenderLimits::default(), scratch: ScratchLayout { sample_scale: 2, sample_bytes_per_pixel: 8, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 }, @@ -395,12 +510,49 @@ impl CpuHost { } pub fn submit(&self, id: JobId, scene_generation: u64, scene: ProductScene, request: ImageRequest) -> Result { + self.submit_with_environment(id, scene_generation, scene, request, None) + } + + /// Captured HDR ownership stays in work, never serialized/cloned into status. + pub fn submit_with_environment( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + environment: Option, + ) -> Result { + if environment.is_some() && request.integrator != Integrator::Raytrace { + return Err(JobError::new(ErrorCode::InvalidRequest, "environment lighting requires CPU raytrace")); + } + self.validate_integrator(request.integrator)?; + if environment.is_some() { + request.raytrace.as_ref().unwrap_or(&super::RaytraceOptions::default()).validate_environment_reflections(&scene)?; + } if id.session == 0 || id.serial == 0 || id.generation == 0 { return Err(JobError::new(ErrorCode::InvalidRequest, "invalid render job identity")); } + let environment_info = environment.as_ref().map(|e| e.metadata()); + let metadata_bytes = + if environment_info.is_some() { std::mem::size_of::() as u64 } else { 0 }; + let request_bytes = retained_request_bytes(&request)? + .checked_add(metadata_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment metadata overflow"))?; + let mut features = scene.required_features(); + if environment.is_some() { + features.push(crate::RenderFeature::Hdri); + } let Admission { estimated_total_bytes, .. } = admit(&scene, &request)?; + let environment_bytes = + environment.as_ref().map_or(Ok(0), |e| e.required_bytes()).map_err(|e| JobError::new(ErrorCode::InvalidRequest, e.to_string()))?; + let estimated_total_bytes = estimated_total_bytes + .checked_add(environment_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment admission overflow"))?; + admit_request_sum(estimated_total_bytes, request_bytes)?; let mut backend = crate::builtin_backend(); - backend.executors.push(self.descriptor()?); + let descriptor = self.descriptor_for(request.integrator)?; + let expected_executor = descriptor.id.clone(); + backend.executors = vec![descriptor]; let resolved = crate::resolve_request( &[backend], &crate::RenderRequest { @@ -410,12 +562,12 @@ impl CpuHost { width: u64::from(request.width), height: u64::from(request.height), format: Some(RenderFormat::Png), - features: scene.required_features(), + features, policy: Default::default(), }, ) .map_err(|e| JobError::new(ErrorCode::HostUnavailable, e.to_string()))?; - if resolved.executor.as_str() != "cpu-product" { + if resolved.executor != expected_executor { return Err(JobError::new(ErrorCode::HostUnavailable, "CPU product executor is unavailable")); } let mut queue = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?; @@ -426,8 +578,12 @@ impl CpuHost { if queue.len() >= QUEUE_LIMIT { return Err(JobError::new(ErrorCode::QueueFull, "CPU image queue is full")); } + admit_request_sum(estimated_total_bytes, request_bytes)?; let reservation = self.0.shared.budget.reserve(estimated_total_bytes)?; + let request_reservation = if request_bytes == 0 { None } else { Some(self.0.shared.budget.reserve(request_bytes)?) }; let handle = JobHandle(Arc::new(Record { + environment: environment_info, + _request_reservation: request_reservation, id, scene_generation, request, @@ -437,7 +593,7 @@ impl CpuHost { #[cfg(not(target_arch = "wasm32"))] done: Condvar::new(), })); - queue.push_back(Work { scene, handle: handle.clone(), reservation }); + queue.push_back(Work { scene, handle: handle.clone(), reservation, environment }); drop(queue); #[cfg(not(target_arch = "wasm32"))] self.0.shared.wake.notify_one(); @@ -514,3 +670,107 @@ fn native_worker(shared: Arc) { } } } +#[cfg(test)] +mod retained_request_tests { + use super::*; + fn request() -> ImageRequest { + let mut lights = Vec::with_capacity(8); + lights.push(super::super::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }); + ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(super::super::RaytraceOptions { lights: Some(lights), ..Default::default() }), + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + } + } + #[test] + fn retained_lights_are_billed_by_original_capacity_and_sum_is_checked() { + let request = request(); + let bytes = retained_request_bytes(&request).unwrap(); + assert_eq!(bytes, 8 * std::mem::size_of::() as u64); + let cap = super::super::image::MAX_JOB_BYTES; + assert!(admit_request_sum(cap - bytes, bytes).is_ok()); + assert_eq!(admit_request_sum(cap - bytes + 1, bytes).unwrap_err().code, ErrorCode::LimitExceeded); + assert_eq!(admit_request_sum(u64::MAX, 1).unwrap_err().code, ErrorCode::LimitExceeded); + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn retained_lights_keep_the_same_pool_lease_after_png_eviction() { + let host = CpuHost::for_platform().unwrap(); + let request = request(); + let expected = retained_request_bytes(&request).unwrap(); + let job = host + .submit( + JobId { session: 99, serial: 1, generation: 1 }, + 1, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + request, + ) + .unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + let frame = job.frame().unwrap().unwrap(); + let held_bytes = host.admitted_bytes(); + assert!(held_bytes > expected); + job.0.data.lock().unwrap().frame = None; + assert_eq!(host.admitted_bytes(), held_bytes); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), expected); + drop(held); + } +} + +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod environment_metadata_lease_tests { + use super::*; + #[test] + fn captured_environment_metadata_survives_png_eviction_without_source_bytes() { + use crate::lighting::{ + HdrSource, + environment_input::{EnvironmentInfo, EnvironmentInput}, + }; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 64, 32, 129]); + } + let input = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.5, 2.0, 16).unwrap(); + let metadata = input.metadata(); + let expected = std::mem::size_of::() as u64; + let host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: None, + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + }; + let job = host + .submit_with_environment( + JobId { session: 1693, serial: 7, generation: 1 }, + 1, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + request, + Some(input), + ) + .unwrap(); + let status = job.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + assert_eq!(status.environment.unwrap().source_sha256, metadata.source_sha256); + let frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + assert_eq!(host.admitted_bytes(), frame._reservation.bytes + expected); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + drop(host); + drop(job); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } +} diff --git a/crates/render/src/job/host_tests.rs b/crates/render/src/job/host_tests.rs index cb5634f97..778c3dbf0 100644 --- a/crates/render/src/job/host_tests.rs +++ b/crates/render/src/job/host_tests.rs @@ -2,7 +2,48 @@ use super::*; use solidcraft_geom::{Aabb3, Mesh}; fn request() -> ImageRequest { - ImageRequest { camera: Default::default(), width: 16, height: 16, background: [40, 80, 120], transparent_background: false } + ImageRequest { + integrator: Default::default(), + raytrace: None, + camera: Default::default(), + width: 16, + height: 16, + background: [40, 80, 120], + transparent_background: false, + } +} + +#[test] +fn legacy_image_requests_default_to_raster_and_reject_unknown_integrators() { + let mut value = serde_json::to_value(request()).unwrap(); + value.as_object_mut().unwrap().remove("integrator"); + let decoded: ImageRequest = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(decoded.integrator, Integrator::Raster); + value["integrator"] = serde_json::json!("gpu_pathtrace"); + assert!(serde_json::from_value::(value).is_err()); +} + +#[cfg(feature = "raytrace-cpu")] +#[test] +fn cooperative_raytrace_descriptor_matches_native_only_validation() { + let host = CpuHost::cooperative(); + assert!(host.validate_integrator(Integrator::Raytrace).is_err()); + assert!(matches!(host.descriptor_for(Integrator::Raytrace).unwrap().availability, Availability::Unavailable { .. })); + assert!(host.validate_integrator(Integrator::Raster).is_ok()); +} + +#[cfg(not(feature = "raytrace-cpu"))] +#[test] +fn compiled_out_raytracing_never_enters_the_host_queue() { + let host = CpuHost::cooperative(); + let mut request = request(); + request.integrator = Integrator::Raytrace; + assert!(host.validate_integrator(Integrator::Raytrace).unwrap_err().message.contains("not compiled in")); + assert!(host.descriptor_for(Integrator::Raytrace).is_err()); + let error = host.submit(JobId { session: 1, serial: 1, generation: 1 }, 0, empty(), request).err().unwrap(); + assert_eq!(error.code, ErrorCode::HostUnavailable); + assert_eq!(host.admitted_bytes(), 0); + assert!(!host.pump(1).unwrap()); } fn empty() -> ProductScene { ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY } diff --git a/crates/render/src/job/image.rs b/crates/render/src/job/image.rs index 48b91379e..09730d8ea 100644 --- a/crates/render/src/job/image.rs +++ b/crates/render/src/job/image.rs @@ -1,8 +1,6 @@ //! Incremental product rasterization. Every phase yields between bounded work units. use std::collections::BTreeMap; -use std::io::Write; -use std::sync::{Arc, Mutex}; use serde::Serialize; use solidcraft_geom::Vec3; @@ -50,6 +48,31 @@ fn add_bytes(sum: &mut u64, count: usize, size: usize) -> Result<()> { /// Conservative admission before allocating pixels or projected-work lists. Source Arcs are /// counted even when another owner already holds them. Allocator and codec internals are estimates. pub fn admit(scene: &ProductScene, request: &ImageRequest) -> Result { + match request.integrator { + super::Integrator::Raster => { + if request.raytrace.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "raytrace options require integrator: raytrace")); + } + admit_base(scene, request) + } + super::Integrator::Raytrace => { + #[cfg(feature = "raytrace-cpu")] + { + let defaults = super::RaytraceOptions::default(); + let options = request.raytrace.as_ref().unwrap_or(&defaults); + options.validate()?; + crate::raytrace::image::admit(scene, request, options) + } + #[cfg(not(feature = "raytrace-cpu"))] + { + Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")) + } + } + } +} + +/// Shared dimension/source admission; integrators add their own complete work budgets. +pub(crate) fn admit_base(scene: &ProductScene, request: &ImageRequest) -> Result { if !request.camera.is_valid() { return Err(JobError::new(ErrorCode::InvalidRequest, "invalid image camera")); } @@ -176,30 +199,6 @@ enum Stage { Done, } -struct BufferWriter { - bytes: Arc>>, - limit: usize, - cancel: CancelToken, -} - -impl Write for BufferWriter { - fn write(&mut self, bytes: &[u8]) -> std::io::Result { - if self.cancel.is_cancelled() { - return Err(std::io::Error::other("render cancelled")); - } - let mut out = self.bytes.lock().map_err(|_| std::io::Error::other("PNG output lock poisoned"))?; - if out.len().checked_add(bytes.len()).is_none_or(|n| n > self.limit) { - return Err(std::io::Error::other("PNG output exceeds its byte budget")); - } - out.try_reserve_exact(bytes.len()).map_err(|_| std::io::Error::other("PNG allocation failed"))?; - out.extend_from_slice(bytes); - Ok(bytes.len()) - } - fn flush(&mut self) -> std::io::Result<()> { - if self.cancel.is_cancelled() { Err(std::io::Error::other("render cancelled")) } else { Ok(()) } - } -} - pub enum TaskPoll { Pending(Progress), Complete(Vec), @@ -238,14 +237,15 @@ pub struct ImageTask { draw: usize, triangle: Option, output: Vec, - encoded: Arc>>, - encoder: Option>, - row: usize, + encoder: Option, } impl ImageTask { pub fn new(scene: ProductScene, request: ImageRequest, cancel: CancelToken) -> Result { cancel.check()?; + if request.integrator != super::Integrator::Raster { + return Err(JobError::new(ErrorCode::InvalidRequest, "raster task cannot execute a raytrace request")); + } let admission = admit(&scene, &request)?; let (sw, sh) = (request.width as usize * SS, request.height as usize * SS); let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(request.camera.target); @@ -289,9 +289,7 @@ impl ImageTask { draw: 0, triangle: None, output, - encoded: Arc::new(Mutex::new(Vec::new())), encoder: None, - row: 0, }) } @@ -307,7 +305,11 @@ impl ImageTask { done: self.pixel_done, total: self.pixel_tests + (self.sw * self.sh) as u64 + u64::from(self.request.width) * u64::from(self.request.height), }, - Stage::Encode => Progress { phase: Phase::Encoding, done: self.row as u64, total: u64::from(self.request.height) }, + Stage::Encode => Progress { + phase: Phase::Encoding, + done: self.encoder.as_ref().map_or(0, |encoder| encoder.row() as u64), + total: u64::from(self.request.height), + }, Stage::Done => Progress { phase: Phase::Completed, done: 1, total: 1 }, } } @@ -562,14 +564,8 @@ impl ImageTask { let width = self.request.width as usize; let index = self.output.len() / 4; if index >= width * self.request.height as usize { - let writer = BufferWriter { bytes: self.encoded.clone(), limit: self.admission.encoded_limit as usize, cancel: self.cancel.clone() }; - let mut encoder = png::Encoder::new(writer, self.request.width, self.request.height); - encoder.set_color(png::ColorType::Rgba); - encoder.set_depth(png::BitDepth::Eight); - encoder.set_source_srgb(png::SrgbRenderingIntent::Perceptual); - self.encoder = Some( - encoder.write_header().and_then(|w| w.into_stream_writer()).map_err(|e| JobError::new(ErrorCode::EncodingFailed, e.to_string()))?, - ); + self.encoder = + Some(super::encoding::PngEncoding::new(self.request.width, self.request.height, self.admission.encoded_limit, self.cancel.clone())?); self.stage = Stage::Encode; // Pixels and prepared geometry are no longer needed during PNG compression. self.pixels = Vec::new(); @@ -600,32 +596,12 @@ impl ImageTask { } fn encode_step(&mut self) -> Result>> { - if self.row < self.request.height as usize { - let length = self.request.width as usize * 4; - let start = self.row * length; - let row = self.output.get(start..start + length).ok_or_else(|| invalid("missing PNG row"))?; - self.encoder - .as_mut() - .ok_or_else(|| invalid("missing PNG writer"))? - .write_all(row) - .map_err(|e| JobError::new(ErrorCode::EncodingFailed, e.to_string()))?; - self.row += 1; - return Ok(None); + let result = self.encoder.as_mut().ok_or_else(|| invalid("missing PNG writer"))?.step(&self.output)?; + if result.is_some() { + self.output = Vec::new(); + self.stage = Stage::Done; } - self.encoder - .take() - .ok_or_else(|| invalid("missing PNG writer"))? - .finish() - .map_err(|e| JobError::new(ErrorCode::EncodingFailed, e.to_string()))?; - self.cancel.check()?; - let mut bytes = self.encoded.lock().map_err(|_| JobError::new(ErrorCode::Internal, "PNG output lock poisoned"))?; - let png = std::mem::take(&mut *bytes); - if !png.starts_with(b"\x89PNG\r\n\x1a\n") { - return Err(JobError::new(ErrorCode::EncodingFailed, "invalid PNG output")); - } - self.output = Vec::new(); - self.stage = Stage::Done; - Ok(Some(png)) + Ok(result) } } diff --git a/crates/render/src/job/image_tests.rs b/crates/render/src/job/image_tests.rs index 18406e1f4..4e0c77fb4 100644 --- a/crates/render/src/job/image_tests.rs +++ b/crates/render/src/job/image_tests.rs @@ -1,11 +1,20 @@ use super::*; use crate::{Camera, ProductMesh, StandardView}; use solidcraft_geom::{Aabb3, Mesh}; +use std::sync::Arc; fn request() -> ImageRequest { let mut camera = Camera { distance: 50.0, ..Default::default() }; camera.set_view(StandardView::Front); - ImageRequest { camera, width: 64, height: 64, background: [20, 40, 60], transparent_background: true } + ImageRequest { + integrator: Default::default(), + raytrace: None, + camera, + width: 64, + height: 64, + background: [20, 40, 60], + transparent_background: true, + } } fn square(name: &str, colour: [u8; 3], opacity: f64, offset: Vec3) -> ProductMesh { @@ -93,9 +102,9 @@ fn encoding_yields_between_rows_and_completed_result_is_consumed_once() { while task.stage != Stage::Encode { assert!(matches!(task.step(64).unwrap(), TaskPoll::Pending(_))); } - let before = task.row; + let before = task.encoder.as_ref().unwrap().row(); assert!(matches!(task.step(usize::MAX).unwrap(), TaskPoll::Pending(_))); - assert!(task.row - before <= 4); + assert!(task.encoder.as_ref().unwrap().row() - before <= 4); loop { if let TaskPoll::Complete(bytes) = task.step(4096).unwrap() { assert_eq!(image::load_from_memory(&bytes).unwrap().width(), 64); @@ -131,17 +140,3 @@ fn invalid_sizes_indices_opacity_and_large_work_lists_fail_without_a_frame() { assert_eq!(ImageTask::new(scene(vec![body]), request(), CancelToken::default()).err().unwrap().code, ErrorCode::LimitExceeded); assert_eq!(std::mem::size_of::(), 16, "admission accounts for each of the three lists"); } - -#[test] -fn png_output_budget_and_cancellation_fail_without_partial_publication() { - let bytes = Arc::new(Mutex::new(Vec::new())); - let cancel = CancelToken::default(); - let mut writer = BufferWriter { bytes: bytes.clone(), limit: 4, cancel: cancel.clone() }; - writer.write_all(b"PNG").unwrap(); - assert!(writer.write_all(b"too large").is_err()); - assert_eq!(*bytes.lock().unwrap(), b"PNG"); - cancel.cancel(); - assert!(writer.write_all(b"x").is_err()); - assert!(writer.flush().is_err()); - assert_eq!(*bytes.lock().unwrap(), b"PNG"); -} diff --git a/crates/render/src/job/mod.rs b/crates/render/src/job/mod.rs index e7f6c45e2..826292669 100644 --- a/crates/render/src/job/mod.rs +++ b/crates/render/src/job/mod.rs @@ -11,8 +11,11 @@ use serde::{Deserialize, Serialize}; use crate::{BackendId, Camera, ExecutorId}; +pub(crate) mod encoding; mod host; -mod image; +pub(crate) mod image; +#[cfg(test)] +mod rt2_tests; pub use host::{CpuHost, HostKind, JobHandle, JobStatus, RenderFrame}; pub use image::{Admission, ImageTask, TaskPoll, admit}; @@ -104,10 +107,290 @@ impl CancelToken { } } +/// Per-request execution choice, independent of viewport graphics presets. +/// Keep both variants parseable in builds without optional raytracing, so those +/// builds return an explicit capability error before capturing model geometry. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Integrator { + #[default] + Raster, + Raytrace, +} + +/// Explicit scene-reflection transport, separate from opaque roughness bounds. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReflectionMode { + Mirror, + RoughSpecular, +} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReflectionBody { + pub body: String, + pub mode: ReflectionMode, +} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct ReflectionOptions { + #[serde(deserialize_with = "bounded_reflection_bodies")] + pub bodies: Vec, + pub max_bounces: u8, + pub samples: u8, +} +impl Default for ReflectionOptions { + fn default() -> Self { + Self { bodies: Vec::new(), max_bounces: 2, samples: 4 } + } +} +fn bounded_reflection_bodies<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { + struct Bodies; + impl<'de> serde::de::Visitor<'de> for Bodies { + type Value = Vec; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("at most64 reflection body overrides") + } + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let mut values = Vec::new(); + while let Some(value) = seq.next_element()? { + if values.len() == 64 { + return Err(serde::de::Error::custom("at most64 reflection bodies")); + } + values.push(value); + } + Ok(values) + } + } + d.deserialize_seq(Bodies) +} +impl ReflectionOptions { + pub fn validate(&self) -> Result<()> { + if !(1..=8).contains(&self.max_bounces) || !(1..=64).contains(&self.samples) || self.bodies.len() > 64 || self.bodies.capacity() > 64 { + return Err(JobError::new(ErrorCode::InvalidRequest, "reflection bounds: 1..8 bounces, 1..64 samples, at most64 body slots")); + } + for (index, body) in self.bodies.iter().enumerate() { + if body.body.is_empty() + || body.body.len() > 128 + || body.body.capacity() > 128 + || self.bodies.iter().take(index).any(|other| other.body == body.body) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "reflection body names must be unique, nonempty and bounded to128 bytes")); + } + } + Ok(()) + } +} + +/// Linear-light runtime inputs. These are never design settings or GPU presets. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DirectionalLightOptions { + pub direction: [f64; 3], + pub color: [f64; 3], + pub intensity: f64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum LightingPreset { + Neutral, + WarmCool, + KeyRim, +} + +/// Explicit visual rotation about a certified planar face's outward normal. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AnisotropicOrientation { + #[default] + Zero, + QuarterTurn, +} + +/// Runtime-only captured planar face selector; no persistent naming is invented. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnisotropicFaceOptions { + pub body_index: usize, + #[serde(deserialize_with = "bounded_anisotropic_body_name")] + pub body_name: String, + pub face: u32, + pub tangent: [f64; 3], + pub orientation: AnisotropicOrientation, + pub roughness_x: f64, + pub roughness_y: f64, +} + +fn bounded_anisotropic_body_name<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { + struct Name; + impl serde::de::Visitor<'_> for Name { + type Value = String; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("captured body name of 1..1024 bytes") + } + fn visit_str(self, value: &str) -> std::result::Result { + if value.is_empty() || value.len() > 1024 { + return Err(E::custom("captured body name of 1..1024 bytes required")); + } + let mut name = String::new(); + name.try_reserve_exact(value.len()).map_err(E::custom)?; + name.push_str(value); + Ok(name) + } + } + d.deserialize_str(Name) +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct RaytraceOptions { + pub reflections: Option, + pub anisotropic_faces: [Option; 2], + pub preset: Option, + #[serde(deserialize_with = "bounded_lights", skip_serializing_if = "Option::is_none")] + pub lights: Option>, + pub exposure_ev: f64, + pub shadows: bool, +} + +impl Default for RaytraceOptions { + fn default() -> Self { + Self { anisotropic_faces: [None, None], reflections: None, preset: None, lights: None, exposure_ev: 0.0, shadows: true } + } +} + +fn bounded_lights<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result>, D::Error> { + struct Lights; + impl<'de> serde::de::Visitor<'de> for Lights { + type Value = Vec; + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("at most eight directional lights") + } + fn visit_seq>(self, mut sequence: A) -> std::result::Result { + let mut lights = Vec::new(); + while let Some(light) = sequence.next_element()? { + if lights.len() == 8 { + return Err(serde::de::Error::custom("at most eight directional lights")); + } + lights.push(light); + } + Ok(lights) + } + } + deserializer.deserialize_seq(Lights).map(Some) +} + +impl RaytraceOptions { + /// One capacity calculation shared by host and engine preflight. + pub fn retained_bytes(&self) -> Result { + self.validate()?; + let limit = || JobError::new(ErrorCode::LimitExceeded, "raytrace request capacity overflow"); + let mut bytes = self + .lights + .as_ref() + .map_or(Some(0), |l| (l.capacity() as u64).checked_mul(std::mem::size_of::() as u64)) + .ok_or_else(limit)?; + if let Some(reflections) = &self.reflections { + let slots = (reflections.bodies.capacity() as u64).checked_mul(std::mem::size_of::() as u64).ok_or_else(limit)?; + bytes = bytes.checked_add(slots).ok_or_else(limit)?; + for body in &reflections.bodies { + bytes = bytes.checked_add(body.body.capacity() as u64).ok_or_else(limit)?; + } + } + for target in self.anisotropic_faces.iter().flatten() { + bytes = bytes.checked_add(target.body_name.capacity() as u64).ok_or_else(limit)?; + } + Ok(bytes) + } + /// No environment NEE on selected reflectors; rough transport must be purely metallic. + /// Rejecting every nonmetallic effective face prevents silently dropping its diffuse HDR. + pub fn validate_environment_reflections(&self, scene: &crate::ProductScene) -> Result<()> { + self.validate()?; + if let Some(reflections) = &self.reflections { + for selector in &reflections.bodies { + let mut bodies = scene.meshes.iter().filter(|b| b.name == selector.body); + let body = bodies.next().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "environment reflection body missing"))?; + if bodies.next().is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "ambiguous environment reflection body")); + } + if selector.mode == ReflectionMode::RoughSpecular + && (body.surface.is_none_or(|s| s.metallic() != 1.0) || body.faces.iter().any(|f| f.surface.is_none_or(|s| s.metallic() != 1.0))) + { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "HDR rough reflection requires fully metallic body and face surfaces; diffuse/specular partition is not supported", + )); + } + } + } + for target in self.anisotropic_faces.iter().flatten() { + let mode = self.reflections.as_ref().and_then(|r| r.bodies.iter().find(|b| b.body == target.body_name).map(|b| b.mode)); + if mode != Some(ReflectionMode::RoughSpecular) { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "HDR anisotropy requires a selected fully metallic rough reflector; anisotropic HDR direct lighting is not supported", + )); + } + } + Ok(()) + } + pub fn validate(&self) -> Result<()> { + if let Some(reflections) = &self.reflections { + reflections.validate()?; + } + for (i, target) in self.anisotropic_faces.iter().enumerate().filter_map(|(i, target)| target.as_ref().map(|target| (i, target))) { + if target.body_name.is_empty() + || target.body_name.len() > 1024 + || target.body_name.capacity() > 1024 + || !target.tangent.iter().all(|v| v.is_finite()) + || !target.tangent.iter().any(|v| *v != 0.0) + || ![target.roughness_x, target.roughness_y].into_iter().all(|v| v.is_finite() && (crate::surface::MIN_ROUGHNESS..=1.0).contains(&v)) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid bounded anisotropic planar face options")); + } + if self.anisotropic_faces.iter().skip(i + 1).flatten().any(|other| target.body_index == other.body_index && target.face == other.face) { + return Err(JobError::new(ErrorCode::InvalidRequest, "duplicate anisotropic captured face")); + } + } + if self.reflections.as_ref().is_some_and(|r| { + r.bodies.iter().any(|b| b.mode == ReflectionMode::Mirror && self.anisotropic_faces.iter().flatten().any(|t| t.body_name == b.body)) + }) { + return Err(JobError::new(ErrorCode::InvalidRequest, "delta mirror cannot have anisotropic rough axes")); + } + if self.preset.is_some() && self.lights.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "choose either a lighting preset or custom lights")); + } + if !self.exposure_ev.is_finite() || !(-16.0..=16.0).contains(&self.exposure_ev) { + return Err(JobError::new(ErrorCode::InvalidRequest, "raytrace exposure_ev must be finite and within -16..16")); + } + if let Some(lights) = &self.lights { + if lights.len() > 8 || lights.capacity() > 8 { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight directional lights")); + } + for light in lights { + let direction_valid = light.direction.iter().all(|n| n.is_finite()) && light.direction.iter().any(|n| *n != 0.0); + if !direction_valid + || !light.color.iter().all(|n| n.is_finite() && (0.0..=1.0).contains(n)) + || !light.intensity.is_finite() + || !(0.0..=64.0).contains(&light.intensity) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid bounded directional light")); + } + } + } + Ok(()) + } +} + /// Fully resolved input; no mutable session, topology graph or GPU resources. #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ImageRequest { + #[serde(default)] + pub integrator: Integrator, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub raytrace: Option, pub camera: Camera, pub width: u32, pub height: u32, @@ -138,3 +421,26 @@ pub struct FrameInfo { pub encoding: ColourEncoding, pub alpha: AlphaConvention, } +#[cfg(test)] +mod runtime_request_roundtrip_tests { + use super::*; + #[test] + fn default_preset_and_empty_lights_requests_roundtrip_without_invalid_null_sequence() { + for options in [ + RaytraceOptions::default(), + RaytraceOptions { preset: Some(LightingPreset::Neutral), ..Default::default() }, + RaytraceOptions { lights: Some(Vec::new()), ..Default::default() }, + ] { + let value = serde_json::to_value(&options).unwrap(); + if options.lights.is_none() { + assert!(value.get("lights").is_none()); + } else { + assert_eq!(value.get("lights").unwrap(), &serde_json::json!([])); + } + let decoded: RaytraceOptions = serde_json::from_value(value).unwrap(); + assert_eq!(decoded, options); + assert!(decoded.validate().is_ok()); + } + assert_eq!(serde_json::from_value::(serde_json::json!({})).unwrap(), RaytraceOptions::default()); + } +} diff --git a/crates/render/src/job/rt2_tests.rs b/crates/render/src/job/rt2_tests.rs new file mode 100644 index 000000000..30d03d145 --- /dev/null +++ b/crates/render/src/job/rt2_tests.rs @@ -0,0 +1,137 @@ +//! Runtime-option and admission regressions; no render timing assumptions. + +use super::*; +use crate::ProductScene; +use solidcraft_geom::Aabb3; + +fn request(integrator: Integrator) -> ImageRequest { + ImageRequest { integrator, raytrace: None, camera: Default::default(), width: 16, height: 16, background: [0; 3], transparent_background: false } +} + +#[test] +fn options_reject_retained_capacity_even_when_no_lights_are_active() { + let options = RaytraceOptions { lights: Some(Vec::with_capacity(64)), ..Default::default() }; + assert_eq!(options.validate().unwrap_err().code, ErrorCode::InvalidRequest); + let serialized = serde_json::to_value(&options).unwrap(); + let decoded: RaytraceOptions = serde_json::from_value(serialized).unwrap(); + assert!(decoded.validate().is_ok(), "wire input retains no oversized source allocation"); +} + +#[cfg(feature = "raytrace-cpu")] +#[test] +fn raytrace_admission_validates_retained_options_before_cloning() { + let scene = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let mut request = request(Integrator::Raytrace); + request.raytrace = Some(RaytraceOptions { lights: Some(Vec::with_capacity(64)), ..Default::default() }); + let original = request.raytrace.as_ref().unwrap(); + assert_eq!(original.validate().unwrap_err().code, ErrorCode::InvalidRequest); + assert!(original.clone().validate().is_ok(), "cloning an empty Vec discards its retained capacity"); + let error = admit(&scene, &request).err().unwrap(); + assert_eq!(error.code, ErrorCode::InvalidRequest); + assert_eq!(request.raytrace.as_ref().unwrap().lights.as_ref().unwrap().capacity(), 64); +} + +#[test] +fn options_preserve_the_eight_light_boundary_and_refuse_the_ninth() { + let light = serde_json::json!({"direction": [0.0, 0.0, -1.0], "color": [1.0, 1.0, 1.0], "intensity": 1.0}); + let accepted: RaytraceOptions = serde_json::from_value(serde_json::json!({"lights": vec![light.clone(); 8]})).unwrap(); + assert!(accepted.validate().is_ok()); + assert!(serde_json::from_value::(serde_json::json!({"lights": vec![light; 9]})).is_err()); +} + +#[test] +fn exposure_refuses_nonfinite_and_out_of_range_values() { + for exposure_ev in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -16.01, 16.01] { + let options = RaytraceOptions { exposure_ev, ..Default::default() }; + assert_eq!(options.validate().unwrap_err().code, ErrorCode::InvalidRequest); + } + for exposure_ev in [-16.0, 16.0] { + assert!(RaytraceOptions { exposure_ev, ..Default::default() }.validate().is_ok()); + } +} + +#[test] +fn rejected_raytrace_submission_leaves_existing_raster_reservation_intact() { + let host = CpuHost::cooperative(); + let scene = || ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let raster = host.submit(JobId { session: 1, serial: 1, generation: 1 }, 1, scene(), request(Integrator::Raster)).unwrap(); + let before = host.admitted_bytes(); + assert!(before > 0); + let error = host.submit(JobId { session: 1, serial: 2, generation: 2 }, 1, scene(), request(Integrator::Raytrace)).err().unwrap(); + assert_eq!(error.code, ErrorCode::HostUnavailable); + assert_eq!(host.admitted_bytes(), before); + assert_eq!(raster.status().unwrap().progress.phase, Phase::Queued); + assert!(raster.frame().unwrap().is_none()); + assert_eq!(raster.cancel().unwrap().progress.phase, Phase::Cancelled); + // Pump only to discard cancelled queued input; it must not produce a frame. + assert!(!host.pump(1).unwrap()); + assert_eq!(host.admitted_bytes(), 0); + assert!(raster.frame().unwrap().is_none()); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn native_integrators_share_one_host_and_retained_frame_budget() { + let host = CpuHost::for_platform().unwrap(); + let scene = || ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let raster_id = JobId { session: 10, serial: 1, generation: 1 }; + let raytrace_id = JobId { session: 20, serial: 1, generation: 1 }; + let raster = host.submit(raster_id, 100, scene(), request(Integrator::Raster)).unwrap(); + let raytrace = host.submit(raytrace_id, 200, scene(), request(Integrator::Raytrace)).unwrap(); + // Deadlock watchdog only; there is no rendering-speed assertion. + for job in [&raster, &raytrace] { + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + } + let raster_frame = raster.frame().unwrap().unwrap(); + let raytrace_frame = raytrace.frame().unwrap().unwrap(); + assert_eq!(raster_frame.info.job, raster_id); + assert_eq!(raytrace_frame.info.job, raytrace_id); + assert_eq!(raster_frame.info.scene_generation, 100); + assert_eq!(raytrace_frame.info.scene_generation, 200); + assert_eq!(raster_frame.info.executor.as_str(), "cpu-product"); + assert_eq!(raytrace_frame.info.executor.as_str(), "cpu-raytrace"); + let both = host.admitted_bytes(); + assert!(both > 0); + drop(raster); + drop(raytrace); + assert_eq!(host.admitted_bytes(), both, "external frames retain both leases"); + drop(raster_frame); + assert!(host.admitted_bytes() > 0 && host.admitted_bytes() < both); + drop(raytrace_frame); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(feature = "raytrace-cpu")] +#[test] +fn cancelled_raytrace_task_never_returns_a_frame() { + let cancel = CancelToken::default(); + let scene = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let mut task = crate::raytrace::image::ImageTask::new(scene, request(Integrator::Raytrace), cancel.clone(), RaytraceOptions::default()).unwrap(); + cancel.cancel(); + assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled); +} + +#[cfg(feature = "raytrace-cpu")] +#[test] +fn completed_raytrace_task_releases_captured_mesh_before_returning_png() { + let mesh = Arc::new(solidcraft_geom::Mesh::default()); + let captured = Arc::downgrade(&mesh); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { name: "Lease probe".into(), mesh, color: [0; 3], opacity: 1.0, surface: None, faces: Vec::new() }], + bounds: Aabb3::EMPTY, + }; + let mut task = + crate::raytrace::image::ImageTask::new(scene, request(Integrator::Raytrace), CancelToken::default(), RaytraceOptions::default()).unwrap(); + assert!(captured.upgrade().is_some()); + let mut completed = false; + for _ in 0..10_000 { + if let TaskPoll::Complete(png) = task.step(4).unwrap() { + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); + completed = true; + break; + } + } + assert!(completed, "bounded empty-scene fixture must complete"); + assert!(captured.upgrade().is_none(), "the host may shrink the lease as soon as Complete is returned, even while the task remains alive"); + assert_eq!(task.progress().phase, Phase::Completed); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 0e12a95a0..70af2c639 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5,13 +5,17 @@ #![forbid(unsafe_code)] mod analysis; +pub mod anisotropic_surface; mod backend; mod camera; mod curve_display; +mod gif; pub mod job; pub mod lighting; mod product; mod raster; +#[cfg(feature = "raytrace-cpu")] +pub mod raytrace; mod scene; pub mod studio; pub mod surface; @@ -28,6 +32,7 @@ pub use backend::{ }; pub use camera::{Camera, CameraAnim, Mat4, Quat, StandardView, UpAxis, ease_in_out}; pub use curve_display::{PixelCurveView, SampledPath, SamplingBudget, SamplingQuality, sample_segment, sample_segment_unclipped}; +pub use gif::gif; pub use product::{FaceAppearance, ProductMesh, ProductScene}; pub use raster::{Canvas, render, render_png, render_transparent}; pub use scene::{Rgb, SECTION_CAP, Scene, SceneLine, SceneMesh, png}; diff --git a/crates/render/src/lighting/environment_input.rs b/crates/render/src/lighting/environment_input.rs new file mode 100644 index 000000000..d6a16e5dd --- /dev/null +++ b/crates/render/src/lighting/environment_input.rs @@ -0,0 +1,115 @@ +//! Captured existing HDR source, moved through a job under its ONE work lease. +#[cfg(feature = "raytrace-cpu")] +use super::environment_sampling::Environment; +use serde::Serialize; +use sha2::{Digest, Sha256}; + +#[derive(Clone, Debug, Serialize)] +pub struct EnvironmentInfo { + pub source_sha256: [u8; 32], + pub header: super::HdrInfo, + pub rotation_radians: f64, + pub intensity: f64, + pub samples: u32, + pub color_policy: EnvironmentColorPolicy, +} +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum EnvironmentColorPolicy { + ExplicitLinearSrgbD65, +} + +#[cfg(feature = "raytrace-cpu")] +use super::{DecodedHdr, HdrDecodeTask, HdrTaskPoll}; +use super::{HdrError, HdrErrorCode, HdrSource, Result}; + +/// Transient captured input, never serialized into status or saved design data. +pub struct EnvironmentInput { + source: HdrSource, + info: EnvironmentInfo, +} +impl EnvironmentInput { + pub fn new(source: HdrSource, rotation: f64, intensity: f64, samples: u32) -> Result { + if !rotation.is_finite() || !intensity.is_finite() || !(0.0..=64.0).contains(&intensity) || !matches!(samples, 1 | 4 | 16 | 64) { + return Err(HdrError::new(HdrErrorCode::InvalidInput, "invalid environment controls")); + } + if source.info().primaries != Some([0.64, 0.33, 0.30, 0.60, 0.15, 0.06, 0.3127, 0.3290]) { + return Err(HdrError::new(HdrErrorCode::InvalidInput, "environment requires explicit sRGB/D65 primaries")); + } + let info = EnvironmentInfo { + source_sha256: Sha256::digest(source.encoded_bytes()).into(), + header: source.info().clone(), + rotation_radians: rotation, + intensity, + samples, + color_policy: EnvironmentColorPolicy::ExplicitLinearSrgbD65, + }; + Ok(Self { source, info }) + } + pub fn metadata(&self) -> EnvironmentInfo { + self.info.clone() + } + + /// Source capacity + exact decoded allocation + scanline + conservative task state. + /// The host adds this BEFORE reserving; this is no separate memory pool. + pub fn required_bytes(&self) -> Result { + self.source + .retained_encoded_bytes() + .checked_add(self.source.info().decoded_rgb_bytes) + .and_then(|v| v.checked_add(u64::from(self.source.info().width) * 4)) + .and_then(|v| v.checked_add(8192)) + .ok_or_else(|| HdrError::new(HdrErrorCode::LimitExceeded, "environment admission overflow")) + } + #[cfg(feature = "raytrace-cpu")] + pub(crate) fn begin(self) -> Result { + if std::mem::size_of::() > 4096 { + return Err(HdrError::new(HdrErrorCode::LimitExceeded, "HDR decoder state exceeds admission")); + } + let mut decoder = Vec::new(); + decoder.try_reserve_exact(1).map_err(|_| HdrError::new(HdrErrorCode::AllocationFailed, "HDR decoder state allocation failed"))?; + if decoder.capacity() != 1 { + return Err(HdrError::new(HdrErrorCode::LimitExceeded, "HDR decoder state capacity exceeds admission")); + } + decoder.push(HdrDecodeTask::new(self.source)?); + Ok(EnvironmentState { + decoder, + decoded: None, + rotation: self.info.rotation_radians, + intensity: self.info.intensity, + samples: self.info.samples, + }) + } +} + +#[cfg(feature = "raytrace-cpu")] +pub(crate) struct EnvironmentState { + decoder: Vec, + decoded: Option, + rotation: f64, + intensity: f64, + pub samples: u32, +} +#[cfg(feature = "raytrace-cpu")] +impl EnvironmentState { + pub fn ready(&self) -> bool { + self.decoded.is_some() + } + /// Caller debits one shared unit before each invocation; decoder also observes cancellation. + pub fn prepare_one(&mut self, cancelled: impl Fn() -> bool) -> Result<()> { + let decoder = self.decoder.first_mut().ok_or_else(|| HdrError::new(HdrErrorCode::Consumed, "environment decoder consumed"))?; + if let HdrTaskPoll::Complete(decoded) = decoder.step(1, cancelled)? { + let expected = decoded.info().decoded_rgb_bytes; + if decoded.retained_pixel_bytes()? != expected { + return Err(HdrError::new(HdrErrorCode::LimitExceeded, "environment decoded capacity exceeds admission")); + } + Environment::from_decoder_output(&decoded, self.rotation, self.intensity)?.require_linear_srgb()?; + self.decoded = Some(decoded); + self.decoder = Vec::new(); + } + Ok(()) + } + pub fn view(&self) -> Result> { + let decoded = self.decoded.as_ref().ok_or_else(|| HdrError::new(HdrErrorCode::Consumed, "environment not ready"))?; + Environment::from_decoder_output(decoded, self.rotation, self.intensity) + } +} diff --git a/crates/render/src/lighting/environment_input_tests.rs b/crates/render/src/lighting/environment_input_tests.rs new file mode 100644 index 000000000..606a5e65e --- /dev/null +++ b/crates/render/src/lighting/environment_input_tests.rs @@ -0,0 +1,39 @@ +//! White-box hostile decoded input tests; production has no unchecked constructor. +use super::*; +use crate::lighting::environment_sampling::EnvironmentPreparation; + +fn info() -> HdrInfo { + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y 2 +X 4\n".to_vec(); + bytes.extend_from_slice(&[128, 64, 32, 129]); + HdrSource::new(bytes).unwrap().info().clone() +} + +#[test] +fn malformed_decoded_dimensions_lengths_and_original_capacity_refuse() { + for dimensions in [(0, 2), (4, 0), (3, 2), (4096, 2048)] { + let mut metadata = info(); + metadata.width = dimensions.0; + metadata.height = dimensions.1; + let decoded = DecodedHdr { info: metadata, pixels: vec![[1.0; 3]; 8] }; + assert!(EnvironmentPreparation::new(&decoded, 0.0, 1.0).is_err()); + } + let decoded = DecodedHdr { info: info(), pixels: vec![[1.0; 3]; 7] }; + assert!(EnvironmentPreparation::new(&decoded, 0.0, 1.0).is_err()); + let mut pixels = Vec::with_capacity(MAX_HDR_PIXELS as usize + 1); + pixels.resize(8, [1.0; 3]); + let decoded = DecodedHdr { info: info(), pixels }; + assert!(decoded.retained_pixel_bytes().unwrap() > MAX_HDR_PIXELS * 12); + assert!(EnvironmentPreparation::new(&decoded, 0.0, 1.0).is_err()); +} + +#[test] +fn invalid_source_radiance_consumes_preparation_before_exposing_lookup() { + for channel in [f32::NAN, f32::INFINITY, -1.0, 1e9] { + let mut pixels = vec![[1.0; 3]; 8]; + pixels[3][1] = channel; + let decoded = DecodedHdr { info: info(), pixels }; + let mut preparation = EnvironmentPreparation::new(&decoded, 0.0, 1.0).unwrap(); + assert_eq!(preparation.step(8, || Ok(())).unwrap_err().code, HdrErrorCode::InvalidInput); + assert!(preparation.finish().is_err()); + } +} diff --git a/crates/render/src/lighting/environment_sampling.rs b/crates/render/src/lighting/environment_sampling.rs new file mode 100644 index 000000000..06e5c9187 --- /dev/null +++ b/crates/render/src/lighting/environment_sampling.rs @@ -0,0 +1,205 @@ +//! Original Z-up equirectangular sampling; RGB remains in the decoded SOURCE space. +//! Uniform solid-angle sampling deliberately has no luminance CDF or extra pixel copy. + +use super::{DecodedHdr, HdrError, HdrErrorCode, MAX_HDR_HEIGHT, MAX_HDR_PIXELS, MAX_HDR_WIDTH, Result}; +use solidcraft_geom::Vec3; +use std::f64::consts::{PI, TAU}; + +fn invalid(message: &str) -> HdrError { + HdrError::new(HdrErrorCode::InvalidInput, message) +} + +/// Borrowed decoded storage. Its owner and existing admission lease must outlive this view. +/// This is not a declaration that source RGB is linear sRGB. +pub struct Environment<'a> { + decoded: &'a DecodedHdr, + rotation: f64, + intensity: f64, +} + +/// Incident SOURCE-space linear RGB and a density with respect to steradians. +#[derive(Clone, Copy, Debug)] +pub struct EnvironmentSample { + pub direction: Vec3, + pub radiance_source_rgb: Vec3, + pub pdf_solid_angle: f64, +} + +/// One unoccluded linear-sRGB direct-light estimate. The consumer owns visibility +/// and averages these estimates once; no display transfer or sample-count division. +pub struct EnvironmentDirectSample { + pub direction: Vec3, + pub contribution_linear_srgb: Vec3, + pub pdf_solid_angle: f64, +} + +/// Cooperative validation with no allocations. The caller charges each inspected texel +/// to its existing cumulative budget, and can return a typed cancellation/limit error. +pub struct EnvironmentPreparation<'a> { + environment: Option>, + inspected: usize, +} + +impl<'a> EnvironmentPreparation<'a> { + pub fn new(decoded: &'a DecodedHdr, rotation_radians: f64, intensity: f64) -> Result { + let info = decoded.info(); + let count = u64::from(info.width).checked_mul(u64::from(info.height)); + if info.width == 0 + || info.height == 0 + || info.width > MAX_HDR_WIDTH + || info.height > MAX_HDR_HEIGHT + || info.width != info.height.saturating_mul(2) + || count.is_none_or(|n| n > MAX_HDR_PIXELS || n != decoded.pixels().len() as u64) + || decoded.retained_pixel_bytes()? > MAX_HDR_PIXELS * 12 + { + return Err(invalid("invalid bounded decoded environment dimensions or retained capacity")); + } + if !rotation_radians.is_finite() || !intensity.is_finite() || !(0.0..=64.0).contains(&intensity) { + return Err(invalid("environment rotation must be finite and intensity within 0..64")); + } + Ok(Self { environment: Some(Environment { decoded, rotation: rotation_radians.rem_euclid(TAU), intensity }), inspected: 0 }) + } + + /// Returns true when validated. Any error consumes preparation; no partial view escapes. + pub fn step(&mut self, units: usize, mut charge_and_check_cancel: impl FnMut() -> Result<()>) -> Result { + let result = self.advance(units, &mut charge_and_check_cancel); + if result.is_err() { + self.environment = None; + } + result + } + + fn advance(&mut self, units: usize, charge: &mut impl FnMut() -> Result<()>) -> Result { + let environment = self.environment.as_ref().ok_or_else(|| HdrError::new(HdrErrorCode::Consumed, "environment preparation consumed"))?; + // Even an already-complete poll observes cancellation without inspecting more texels. + for _ in 0..units.clamp(1, 16384) { + charge()?; + let Some(pixel) = environment.decoded.pixels().get(self.inspected) else { + return Ok(true); + }; + if pixel.iter().any(|c| !c.is_finite() || !(0.0..=1e8).contains(c)) { + return Err(invalid("environment source radiance must be finite and within 0..1e8")); + } + self.inspected += 1; + if self.inspected == environment.decoded.pixels().len() { + return Ok(true); + } + } + Ok(false) + } + + pub fn finish(mut self) -> Result> { + let environment = self.environment.take().ok_or_else(|| HdrError::new(HdrErrorCode::Consumed, "environment preparation consumed"))?; + if self.inspected != environment.decoded.pixels().len() { + return Err(invalid("environment preparation is incomplete")); + } + Ok(environment) + } +} + +impl Environment<'_> { + /// Only decoder-owned output can reach this internal consumer fast path. + /// HdrDecodeTask already validates every corrected texel incrementally. + #[cfg(feature = "raytrace-cpu")] + pub(crate) fn from_decoder_output(decoded: &DecodedHdr, rotation: f64, intensity: f64) -> Result> { + let mut preparation = EnvironmentPreparation::new(decoded, rotation, intensity)?; + preparation.inspected = decoded.pixels().len(); + preparation.finish() + } + /// First lighting adapter policy: only explicitly declared sRGB/D65 primaries. + /// Missing Radiance primaries are NOT assumed to be sRGB; other gamuts need + /// an independently validated conversion before this adapter can admit them. + pub fn require_linear_srgb(&self) -> Result<()> { + if self.decoded.info().primaries != Some([0.64, 0.33, 0.30, 0.60, 0.15, 0.06, 0.3127, 0.3290]) { + return Err(invalid("environment lighting requires explicit sRGB/D65 primaries; source gamut conversion is not supported yet")); + } + Ok(()) + } + + pub fn radiance_linear_srgb(&self, direction: Vec3) -> Result { + self.require_linear_srgb()?; + self.radiance_source_rgb(direction) + } + + pub fn direct_sample_linear_srgb( + &self, + u: [f64; 2], + surface: crate::surface::OpaqueSurface, + shading_normal: Vec3, + geometric_normal: Vec3, + view: Vec3, + ) -> Result { + self.require_linear_srgb()?; + let sample = self.sample(u)?; + let normal = normalized(shading_normal)?; + let geometric = normalized(geometric_normal)?; + let view = normalized(view)?; + let brdf = surface.brdf(normal, view, sample.direction).map_err(|_| invalid("invalid environment BRDF directions"))?; + let cosine = if geometric.dot(sample.direction) > 0.0 && geometric.dot(view) > 0.0 { normal.dot(sample.direction).max(0.0) } else { 0.0 }; + let li = sample.radiance_source_rgb; + let contribution = Vec3::new(brdf.x * li.x, brdf.y * li.y, brdf.z * li.z) * (cosine / sample.pdf_solid_angle); + if !contribution.is_finite() || [contribution.x, contribution.y, contribution.z].iter().any(|c| !(0.0..=1e12).contains(c)) { + return Err(invalid("environment direct contribution exceeds finite radiance bounds")); + } + Ok(EnvironmentDirectSample { direction: sample.direction, contribution_linear_srgb: contribution, pdf_solid_angle: sample.pdf_solid_angle }) + } + + /// Original allocation capacity, not logical slice length; charge the owner only once. + pub fn retained_pixel_bytes(&self) -> Result { + self.decoded.retained_pixel_bytes() + } + + /// +Z north; phi=atan2(y,x), u=phi/2pi wrapped; v=acos(z)/pi. + /// Positive rotation turns the environment about +Z toward +Y (inverse for lookup). + /// Nearest texel uses half-open angular cells, centres ((x+.5)/W,(y+.5)/H). + /// The seam wraps, south clamps to the last row; exact poles choose longitude zero. + pub fn uv(&self, direction: Vec3) -> Result<[f64; 2]> { + let d = normalized(direction)?; + let phi = if d.x == 0.0 && d.y == 0.0 { 0.0 } else { d.y.atan2(d.x) }; + Ok([((phi - self.rotation) / TAU).rem_euclid(1.0), d.z.clamp(-1.0, 1.0).acos() / PI]) + } + + /// Exposure/color-correction were applied by the decoder; do not repeat them. + /// No gamut conversion, tone mapping or background interpretation takes place here. + pub fn radiance_source_rgb(&self, direction: Vec3) -> Result { + let [u, v] = self.uv(direction)?; + let info = self.decoded.info(); + let x = ((u * f64::from(info.width)) as usize).min(info.width as usize - 1); + let y = ((v * f64::from(info.height)) as usize).min(info.height as usize - 1); + let index = y.checked_mul(info.width as usize).and_then(|n| n.checked_add(x)).ok_or_else(|| invalid("environment index overflow"))?; + let [r, g, b] = *self.decoded.pixels().get(index).ok_or_else(|| invalid("missing environment texel"))?; + Ok(Vec3::new(f64::from(r), f64::from(g), f64::from(b)) * self.intensity) + } + + pub fn pdf_solid_angle(&self, direction: Vec3) -> Result { + normalized(direction)?; + Ok(1.0 / (4.0 * PI)) + } + + /// Open variates avoid mathematical boundary samples (f64 may still round to a pole). + /// z is uniform on (-1,1), phi on (0,2pi): dOmega=dphi dz, PDF=1/(4pi). + /// Black and constant maps have the same normalized PDF; there is no zero-total CDF. + pub fn sample(&self, u: [f64; 2]) -> Result { + if u.iter().any(|v| !v.is_finite() || *v <= 0.0 || *v >= 1.0) { + return Err(invalid("environment variates must be finite and strictly between zero and one")); + } + let z = 1.0 - 2.0 * u[0]; + let radius = ((1.0 - z) * (1.0 + z)).max(0.0).sqrt(); + let phi = TAU * u[1]; + let direction = Vec3::new(radius * phi.cos(), radius * phi.sin(), z); + Ok(EnvironmentSample { direction, radiance_source_rgb: self.radiance_source_rgb(direction)?, pdf_solid_angle: 1.0 / (4.0 * PI) }) + } +} + +fn normalized(direction: Vec3) -> Result { + let scale = direction.x.abs().max(direction.y.abs()).max(direction.z.abs()); + if !direction.is_finite() || scale <= 0.0 { + return Err(invalid("environment direction must be finite and nonzero")); + } + let scaled = direction / scale; + Ok(scaled / scaled.len()) +} + +#[cfg(test)] +#[path = "environment_sampling_tests.rs"] +mod tests; diff --git a/crates/render/src/lighting/environment_sampling_tests.rs b/crates/render/src/lighting/environment_sampling_tests.rs new file mode 100644 index 000000000..39d30c1cc --- /dev/null +++ b/crates/render/src/lighting/environment_sampling_tests.rs @@ -0,0 +1,157 @@ +use super::*; +use crate::lighting::{HdrDecodeTask, HdrSource, HdrTaskPoll}; + +fn decoded(pixels: [[u8; 4]; 8], header: &str) -> DecodedHdr { + let mut bytes = format!("#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n{header}\n-Y 2 +X 4\n").into_bytes(); + for pixel in pixels { + bytes.extend_from_slice(&pixel); + } + let mut task = HdrDecodeTask::new(HdrSource::new(bytes).unwrap()).unwrap(); + for _ in 0..100 { + if let HdrTaskPoll::Complete(decoded) = task.step(100, || false).unwrap() { + return decoded; + } + } + panic!("bounded fixture failed to decode"); +} +fn prepared(decoded: &DecodedHdr, rotation: f64, intensity: f64) -> Environment<'_> { + let mut task = EnvironmentPreparation::new(decoded, rotation, intensity).unwrap(); + while !task.step(1, || Ok(())).unwrap() {} + task.finish().unwrap() +} + +#[test] +fn constant_source_has_uniform_solid_angle_pdf_and_exact_radiance_integral() { + let data = decoded([[128, 64, 32, 129]; 8], ""); + let env = prepared(&data, 0.0, 2.0); + let expected = Vec3::new(2.0, 1.0, 0.5); + let mut integral = Vec3::ZERO; + for i in 0..64 { + let sample = env.sample([(f64::from(i) + 0.5) / 64.0, 0.37]).unwrap(); + assert!((sample.direction.len() - 1.0).abs() < 1e-14); + assert_eq!(sample.radiance_source_rgb, expected); + assert_eq!(env.pdf_solid_angle(sample.direction).unwrap(), sample.pdf_solid_angle); + integral += sample.radiance_source_rgb / sample.pdf_solid_angle / 64.0; + } + assert!((integral - expected * (4.0 * PI)).len() < 1e-12); + assert!((env.pdf_solid_angle(Vec3::Z).unwrap() * 4.0 * PI - 1.0).abs() < 1e-15); +} + +#[test] +fn z_up_uv_centres_seam_poles_and_positive_rotation_are_explicit() { + let data = decoded([[128, 0, 0, 129]; 8], ""); + let env = prepared(&data, 0.0, 1.0); + assert_eq!(env.uv(Vec3::X).unwrap(), [0.0, 0.5]); + assert_eq!(env.uv(Vec3::Y).unwrap(), [0.25, 0.5]); + assert_eq!(env.uv(Vec3::Z).unwrap(), [0.0, 0.0]); + assert_eq!(env.uv(-Vec3::Z).unwrap(), [0.0, 1.0]); + let rotated = prepared(&data, PI / 2.0, 1.0); + assert_eq!(rotated.uv(Vec3::Y).unwrap(), [0.0, 0.5]); + assert!(env.uv(Vec3::new(1.0, -1e-8, 0.0)).unwrap()[0] > 0.99); + let theta = PI / 4.0; + let phi = PI / 4.0; + let centre = Vec3::new(theta.sin() * phi.cos(), theta.sin() * phi.sin(), theta.cos()); + let uv = env.uv(centre).unwrap(); + assert!((uv[0] - 0.125).abs() < 1e-14 && (uv[1] - 0.25).abs() < 1e-14); +} + +#[test] +fn bright_texel_integral_matches_its_independent_spherical_cell_area() { + let mut pixels = [[0; 4]; 8]; + pixels[0] = [128, 0, 0, 129]; + let data = decoded(pixels, ""); + let env = prepared(&data, 0.0, 1.0); + let mut integral = 0.0; + // 4x2: first cell has phi width pi/2 and z width 1, solid angle pi/2. + for y in 0..8 { + for x in 0..8 { + let sample = env.sample([(f64::from(y) + 0.5) / 8.0, (f64::from(x) + 0.5) / 8.0]).unwrap(); + integral += sample.radiance_source_rgb.x / sample.pdf_solid_angle / 64.0; + } + } + assert!((integral - PI / 2.0).abs() < 1e-14); + let black = decoded([[0; 4]; 8], ""); + let env = prepared(&black, 0.0, 1.0); + let sample = env.sample([0.3, 0.7]).unwrap(); + assert_eq!(sample.radiance_source_rgb, Vec3::ZERO); + assert_eq!(sample.pdf_solid_angle, 1.0 / (4.0 * PI)); +} + +#[test] +fn caller_budget_cancellation_consumes_preparation_and_preserves_owner_capacity() { + let data = decoded([[128, 0, 0, 129]; 8], ""); + let bytes = data.retained_pixel_bytes().unwrap(); + let mut task = EnvironmentPreparation::new(&data, 0.0, 1.0).unwrap(); + let mut charged = 0; + assert!( + !task + .step(3, || { + charged += 1; + Ok(()) + }) + .unwrap() + ); + assert_eq!(charged, 3); + assert_eq!(task.step(1, || Err(HdrError::new(HdrErrorCode::Cancelled, "cancel"))).unwrap_err().code, HdrErrorCode::Cancelled); + assert!(task.finish().is_err()); + assert_eq!(data.retained_pixel_bytes().unwrap(), bytes); + let mut task = EnvironmentPreparation::new(&data, 0.0, 1.0).unwrap(); + assert_eq!(task.step(1, || Err(HdrError::new(HdrErrorCode::LimitExceeded, "shared work"))).unwrap_err().code, HdrErrorCode::LimitExceeded); + assert!(task.finish().is_err()); +} + +#[test] +fn source_colour_is_not_assumed_srgb_and_decoder_corrections_are_not_reapplied() { + let raw = decoded([[128, 64, 32, 129]; 8], "EXPOSURE=2\nCOLORCORR=2 1 1\n"); + let env = prepared(&raw, 0.0, 1.0); + assert_eq!(env.radiance_source_rgb(Vec3::X).unwrap(), Vec3::new(0.25, 0.25, 0.125)); + assert!(env.radiance_linear_srgb(Vec3::X).is_err()); + for header in ["PRIMARIES=0.64 0.33 0.29 0.60 0.15 0.06 0.3333 0.3333\n", "PRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n"] { + let data = decoded([[128, 0, 0, 129]; 8], header); + let env = prepared(&data, 0.0, 1.0); + assert_eq!(env.require_linear_srgb().is_ok(), data.info().primaries == Some([0.64, 0.33, 0.30, 0.60, 0.15, 0.06, 0.3127, 0.3290])); + } +} + +#[test] +fn hostile_options_variates_and_directions_refuse_without_panics() { + let data = decoded([[128, 0, 0, 129]; 8], ""); + for (rotation, intensity) in [(f64::NAN, 1.0), (0.0, f64::INFINITY), (0.0, -1.0), (0.0, 65.0)] { + assert!(EnvironmentPreparation::new(&data, rotation, intensity).is_err()); + } + assert!(EnvironmentPreparation::new(&data, 0.0, 1.0).unwrap().finish().is_err()); + let env = prepared(&data, 0.0, 0.0); + for u in [[0.0, 0.5], [1.0, 0.5], [f64::NAN, 0.5]] { + assert!(env.sample(u).is_err()); + } + for d in [Vec3::ZERO, Vec3::new(f64::INFINITY, 0.0, 0.0)] { + assert!(env.uv(d).is_err()); + assert!(env.pdf_solid_angle(d).is_err()); + } + assert_eq!(env.radiance_source_rgb(Vec3::new(f64::MAX, f64::MAX, 0.0)).unwrap(), Vec3::ZERO); +} + +#[test] +fn direct_conductor_estimates_average_once_and_do_not_cross_geometry() { + let data = decoded([[128, 64, 32, 129]; 8], "PRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n"); + let env = prepared(&data, 0.0, 1.0); + let surface = crate::surface::OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap(); + let mut mean = Vec3::ZERO; + for i in 0..4096 { + let u = [(f64::from(i) + 0.5) / 4096.0, 0.375]; + let sample = env.direct_sample_linear_srgb(u, surface, Vec3::Z, Vec3::Z, Vec3::Z).unwrap(); + mean += sample.contribution_linear_srgb / 4096.0; + } + // Independent white-conductor roughness=1 normal-view integral: + // 2*pi*integral_0^1 z/(2*pi*(1+z)) dz = 1-ln(2). + assert!((mean - Vec3::new(1.0, 0.5, 0.25) * (1.0 - 2.0_f64.ln())).len() < 3e-8); + let blocked = env.direct_sample_linear_srgb([0.25, 0.375], surface, Vec3::Z, -Vec3::Z, Vec3::Z).unwrap(); + assert_eq!(blocked.contribution_linear_srgb, Vec3::ZERO); + for view in [Vec3::new(0.99, 0.0, -0.1), Vec3::X] { + let crossed = env.direct_sample_linear_srgb([0.25, 0.01], surface, Vec3::new(0.8, 0.0, 0.6), Vec3::Z, view).unwrap(); + assert_eq!(crossed.contribution_linear_srgb, Vec3::ZERO); + } + assert!(env.direct_sample_linear_srgb([0.25, 0.01], surface, Vec3::Z, Vec3::Z, Vec3::ZERO).is_err()); + let unknown = decoded([[128, 0, 0, 129]; 8], ""); + assert!(prepared(&unknown, 0.0, 1.0).direct_sample_linear_srgb([0.25, 0.375], surface, Vec3::Z, Vec3::Z, Vec3::Z).is_err()); +} diff --git a/crates/render/src/lighting/hdr.rs b/crates/render/src/lighting/hdr.rs index 3d245375d..74a4a8692 100644 --- a/crates/render/src/lighting/hdr.rs +++ b/crates/render/src/lighting/hdr.rs @@ -122,6 +122,9 @@ impl HdrSource { pub fn encoded_bytes(&self) -> &[u8] { &self.bytes } + pub fn retained_encoded_bytes(&self) -> u64 { + self.bytes.capacity() as u64 + } pub fn validate(&self, cancelled: impl Fn() -> bool) -> Result<()> { check_cancelled(&cancelled)?; let mut rows = Rows::new(self.clone())?; @@ -173,6 +176,9 @@ impl Rows { pixels .try_reserve_exact(source.info.width as usize) .map_err(|_| HdrError::new(ErrorCode::AllocationFailed, "could not reserve HDR scanline"))?; + if pixels.capacity() != source.info.width as usize { + return Err(limit("HDR scanline capacity exceeds admission")); + } pixels.resize(source.info.width as usize, [0; 4]); Ok(Self { offset: source.info.offset, diff --git a/crates/render/src/lighting/mod.rs b/crates/render/src/lighting/mod.rs index 8ff4403a2..8d80ef43a 100644 --- a/crates/render/src/lighting/mod.rs +++ b/crates/render/src/lighting/mod.rs @@ -1,5 +1,7 @@ //! Device-independent, bounded linear HDR input preparation. +pub mod environment_input; +pub mod environment_sampling; mod hdr; mod task; pub use hdr::{HdrInfo, HdrSource, MAX_HDR_BYTES, MAX_HDR_HEIGHT, MAX_HDR_PIXELS, MAX_HDR_WIDTH}; diff --git a/crates/render/src/lighting/task.rs b/crates/render/src/lighting/task.rs index f5c2fdf45..2f5dd171e 100644 --- a/crates/render/src/lighting/task.rs +++ b/crates/render/src/lighting/task.rs @@ -1,5 +1,9 @@ use super::{HdrError, HdrErrorCode, HdrInfo, HdrSource, MAX_HDR_PIXELS, Result, check_cancelled, hdr::Rows}; +#[cfg(test)] +#[path = "environment_input_tests.rs"] +mod environment_input_tests; + /// Linear RGB in the source's colour space, without gamut conversion or tone mapping. pub struct DecodedHdr { info: HdrInfo, @@ -12,6 +16,10 @@ impl DecodedHdr { pub fn pixels(&self) -> &[[f32; 3]] { &self.pixels } + /// Original allocation capacity, including spare retained slots, for caller admission. + pub fn retained_pixel_bytes(&self) -> Result { + (self.pixels.capacity() as u64).checked_mul(12).ok_or_else(|| HdrError::new(HdrErrorCode::LimitExceeded, "decoded HDR capacity overflow")) + } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -37,6 +45,9 @@ impl HdrDecodeTask { let count = usize::try_from(count).map_err(|_| HdrError::new(HdrErrorCode::LimitExceeded, "HDR pixel count overflow"))?; let mut pixels = Vec::new(); pixels.try_reserve_exact(count).map_err(|_| HdrError::new(HdrErrorCode::AllocationFailed, "could not reserve HDR pixels"))?; + if pixels.capacity() != count { + return Err(HdrError::new(HdrErrorCode::LimitExceeded, "HDR decoded capacity exceeds admission")); + } Ok(Self { rows: Some(Rows::new(source)?), pixels, x: 0, work: 0 }) } diff --git a/crates/render/src/raytrace/anisotropic_faces.rs b/crates/render/src/raytrace/anisotropic_faces.rs new file mode 100644 index 000000000..10b739381 --- /dev/null +++ b/crates/render/src/raytrace/anisotropic_faces.rs @@ -0,0 +1,143 @@ +//! Bounded explicit planar-face adapter for anisotropic direct lighting only. +//! Captured ordinal/name and mesh face tag must match. Strict plane equality is +//! conservative: rotated or imported roundoff may refuse instead of guessing. + +use solidcraft_geom::Vec3; + +use crate::{ + ProductScene, + anisotropic_surface::{AnisotropicSurface, VisualFrame}, + job::{self, AnisotropicOrientation, ErrorCode, JobError, RaytraceOptions}, + surface::OpaqueSurface, +}; + +use super::{TraceError, Triangle, lighting::Lighting}; + +const MAX_TARGET_BODY_TRIANGLES: usize = 4096; + +#[derive(Clone, Copy)] +pub(super) struct PlanarTarget { + frame: VisualFrame, + roughness: [f64; 2], +} + +fn invalid(message: &'static str) -> JobError { + JobError::new(ErrorCode::InvalidScene, message) +} + +/// Preflight is bounded to two 4096-triangle selected bodies. Task construction +/// repeats validation under its own cumulative work/cancellation callback. +pub(super) fn prepare( + scene: &ProductScene, + options: &RaytraceOptions, + mut charge: impl FnMut() -> job::Result<()>, +) -> job::Result<[Option; 2]> { + let mut targets = [None; 2]; + for (target, input) in targets.iter_mut().zip(&options.anisotropic_faces) { + let Some(input) = input else { continue }; + let body = scene.meshes.get(input.body_index).ok_or_else(|| invalid("anisotropic captured body ordinal"))?; + if body.name != input.body_name { + return Err(invalid("anisotropic captured body identity changed")); + } + if body.mesh.triangles.len() > MAX_TARGET_BODY_TRIANGLES || body.mesh.tri_face.len() != body.mesh.triangles.len() { + return Err(invalid("anisotropic targets require complete face tags and at most 4096 triangles per body")); + } + let mut plane: Option<(Vec3, Vec3)> = None; + for (indices, face) in body.mesh.triangles.iter().zip(&body.mesh.tri_face) { + charge()?; + if *face != input.face { + continue; + } + let mut vertices = [Vec3::ZERO; 3]; + for (v, index) in vertices.iter_mut().zip(indices) { + *v = *body.mesh.positions.get(*index as usize).ok_or_else(|| invalid("anisotropic face vertex index"))?; + } + let triangle = Triangle::new(vertices).map_err(|_| invalid("anisotropic face triangle"))?; + let normal = triangle.geometric_normal().ok_or_else(|| invalid("anisotropic face must be nondegenerate"))?; + let [anchor, _, _] = vertices; + if let Some((origin, expected)) = plane { + if normal != expected || vertices.into_iter().any(|p| (p - origin).dot(expected) != 0.0) { + return Err(invalid("anisotropic face is curved, inconsistently wound or not exactly planar")); + } + } else { + plane = Some((anchor, normal)); + } + } + let (_, normal) = plane.ok_or_else(|| invalid("anisotropic captured face has no triangles"))?; + let [x, y, z] = input.tangent; + let frame = VisualFrame::new(normal, Vec3::new(x, y, z)) + .map_err(|_| invalid("anisotropic visual tangent is not perpendicular to the planar face"))?; + let tangent = match input.orientation { + AnisotropicOrientation::Zero => frame.tangent(), + AnisotropicOrientation::QuarterTurn => frame.bitangent(), + }; + *target = Some(PlanarTarget { + frame: VisualFrame::new(normal, tangent).map_err(|_| invalid("anisotropic planar frame"))?, + roughness: [input.roughness_x, input.roughness_y], + }); + } + Ok(targets) +} + +pub(super) fn target_index(options: &RaytraceOptions, body_index: usize, face: Option) -> Option { + options.anisotropic_faces.iter().position(|input| input.as_ref().is_some_and(|input| input.body_index == body_index && Some(input.face) == face)) +} + +impl PlanarTarget { + /// Real #1658 path continuation: NDF null events return None unchanged. + /// Equal axes use its existing isotropic sampler and deterministic azimuth, + /// with the target's explicit scalar roughness. No conditional PDF is invented. + pub(super) fn sample( + self, + surface: OpaqueSurface, + geometric: Vec3, + view: Vec3, + u: [f64; 2], + ) -> super::Result> { + let [rx, ry] = self.roughness; + let frame = VisualFrame::new(geometric, self.frame.tangent()).map_err(|_| TraceError::InvalidInput("anisotropic reflection frame"))?; + if rx == ry { + let surface = OpaqueSurface::new(surface.base_color(), surface.metallic(), rx, surface.dielectric_ior()) + .map_err(|_| TraceError::InvalidInput("isotropic reflection surface"))?; + return super::reflection::rough_specular(surface, geometric, view, u); + } + let surface = AnisotropicSurface::new(surface.base_color(), surface.metallic(), rx, ry, surface.dielectric_ior()) + .map_err(|_| TraceError::InvalidInput("anisotropic reflected surface"))?; + surface + .sample_reflection(frame, geometric, view, u) + .map(|sample| sample.map(|s| super::reflection::ReflectionSample { direction: s.direction, weight: s.weight, pdf: s.pdf })) + .map_err(|_| TraceError::InvalidInput("anisotropic reflection sample")) + } + + pub(super) fn shade( + self, + lights: &Lighting, + surface: OpaqueSurface, + geometric: Vec3, + view: Vec3, + mut visible: impl FnMut(usize, Vec3) -> super::Result, + ) -> super::Result { + let frame = VisualFrame::new(geometric, self.frame.tangent()).map_err(|_| TraceError::InvalidInput("anisotropic resolved planar frame"))?; + let [rx, ry] = self.roughness; + let surface = AnisotropicSurface::new(surface.base_color(), surface.metallic(), rx, ry, surface.dielectric_ior()) + .map_err(|_| TraceError::InvalidInput("anisotropic captured surface"))?; + let mut sum = Vec3::ZERO; + for (index, light) in lights.lights().iter().enumerate() { + let cosine = geometric.dot(light.direction()).max(0.0); + if cosine == 0.0 || !visible(index, light.direction())? { + continue; + } + let f = surface.brdf(frame, geometric, view, light.direction()).map_err(|_| TraceError::InvalidInput("anisotropic direct response"))?; + let li = light.color() * (light.intensity() * cosine); + sum += Vec3::new(f.x * li.x, f.y * li.y, f.z * li.z); + if !sum.is_finite() || [sum.x, sum.y, sum.z].into_iter().any(|v| !(0.0..=1e12).contains(&v)) { + return Err(TraceError::InvalidInput("anisotropic direct radiance bound")); + } + } + Ok(sum) + } +} + +#[cfg(test)] +#[path = "anisotropic_faces_tests.rs"] +mod tests; diff --git a/crates/render/src/raytrace/anisotropic_faces_tests.rs b/crates/render/src/raytrace/anisotropic_faces_tests.rs new file mode 100644 index 000000000..361cbcaba --- /dev/null +++ b/crates/render/src/raytrace/anisotropic_faces_tests.rs @@ -0,0 +1,240 @@ +use super::*; +use crate::job::{AnisotropicFaceOptions, CancelToken, ImageRequest, Integrator, TaskPoll}; +use crate::{Camera, ProductMesh, StandardView}; +use solidcraft_geom::Mesh; +use std::sync::Arc; + +fn body(name: &str, x: f64) -> ProductMesh { + ProductMesh { + name: name.into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(x - 2.0, -2.0, 0.0), Vec3::new(x + 2.0, -2.0, 0.0), Vec3::new(x + 2.0, 2.0, 0.0), Vec3::new(x - 2.0, 2.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![7, 7], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.8, 0.8, 0.8), 1.0, 0.5, 1.5).unwrap()), + faces: Vec::new(), + } +} + +fn scene() -> ProductScene { + let meshes = vec![body("left@occurrence", -5.0), body("right@occurrence", 0.0), body("scalar control@occurrence", 5.0)]; + let bounds = meshes.iter().map(|b| b.mesh.bounds()).reduce(|a, b| a.union(&b)).unwrap(); + ProductScene { meshes, bounds } +} + +fn options() -> RaytraceOptions { + let target = |body_index, name: &str, orientation| { + Some(AnisotropicFaceOptions { + body_index, + body_name: name.into(), + face: 7, + tangent: [1.0, 0.0, 0.0], + orientation, + roughness_x: 0.25, + roughness_y: 0.8, + }) + }; + RaytraceOptions { + anisotropic_faces: [ + target(0, "left@occurrence", AnisotropicOrientation::Zero), + target(1, "right@occurrence", AnisotropicOrientation::QuarterTurn), + ], + lights: Some(vec![job::DirectionalLightOptions { direction: [0.6, 0.0, 0.8], color: [1.0; 3], intensity: 1.0 }]), + shadows: false, + ..Default::default() + } +} + +#[test] +fn explicit_capture_identity_face_and_frame_are_required() { + let scene = scene(); + let baseline = options(); + assert!(prepare(&scene, &baseline, || Ok(())).is_ok()); + for change in 0..4 { + let mut options = baseline.clone(); + let target = options.anisotropic_faces[0].as_mut().unwrap(); + match change { + 0 => target.body_name = "wrong occurrence".into(), + 1 => target.body_index = 50, + 2 => target.face = 99, + _ => target.tangent = [0.0, 0.0, 1.0], + } + assert!(prepare(&scene, &options, || Ok(())).is_err()); + } +} + +#[test] +fn curved_inconsistent_missing_and_excessive_target_meshes_refuse() { + for change in 0..4 { + let mut scene = scene(); + let mesh = Arc::make_mut(&mut scene.meshes[0].mesh); + match change { + 0 => mesh.positions[3].z = 0.1, + 1 => mesh.triangles[1].swap(1, 2), + 2 => mesh.tri_face.clear(), + _ => { + mesh.triangles = vec![[0, 1, 2]; MAX_TARGET_BODY_TRIANGLES + 1]; + mesh.tri_face = vec![7; MAX_TARGET_BODY_TRIANGLES + 1]; + } + } + assert!(prepare(&scene, &options(), || Ok(())).is_err()); + } +} + +#[test] +fn bounded_dto_roundtrip_duplicates_and_original_capacity() { + let options = options(); + assert!(options.validate().is_ok()); + let encoded = serde_json::to_value(&options).unwrap(); + assert_eq!(serde_json::from_value::(encoded.clone()).unwrap(), options); + let expected = options.anisotropic_faces.iter().flatten().map(|t| t.body_name.capacity() as u64).sum::() + + options.lights.as_ref().unwrap().capacity() as u64 * std::mem::size_of::() as u64; + assert_eq!(options.retained_bytes().unwrap(), expected); + let mut duplicate = options.clone(); + duplicate.anisotropic_faces[1] = duplicate.anisotropic_faces[0].clone(); + assert!(duplicate.validate().is_err()); + let mut excessive_capacity = options.clone(); + let target = excessive_capacity.anisotropic_faces[0].as_mut().unwrap(); + let mut name = String::with_capacity(2048); + name.push_str(&target.body_name); + target.body_name = name; + assert!(excessive_capacity.retained_bytes().is_err()); + let mut excessive_array = encoded; + excessive_array["anisotropic_faces"] = serde_json::json!([null, null, null]); + assert!(serde_json::from_value::(excessive_array).is_err()); + assert!(serde_json::from_value::(serde_json::json!({"anisotropic_faces":[{"body_index":0,"body_name":"x".repeat(1025),"face":7,"tangent":[1,0,0],"orientation":"zero","roughness_x":0.25,"roughness_y":0.8},null]})).is_err()); + assert!(serde_json::from_value::(serde_json::json!({"environment":{}})).is_err()); +} + +#[test] +fn target_certification_uses_caller_work_and_cancellation() { + let mut charged = 0; + prepare(&scene(), &options(), || { + charged += 1; + Ok(()) + }) + .unwrap(); + assert_eq!(charged, 4); + let error = prepare(&scene(), &options(), || Err(JobError::new(ErrorCode::Cancelled, "cancelled"))).err().unwrap(); + assert_eq!(error.code, ErrorCode::Cancelled); + let error = prepare(&scene(), &options(), || Err(JobError::new(ErrorCode::LimitExceeded, "same work budget"))).err().unwrap(); + assert_eq!(error.code, ErrorCode::LimitExceeded); +} + +#[test] +fn direct_response_respects_geometry_visibility_and_quarter_turn() { + let scene = scene(); + let options = options(); + let targets = prepare(&scene, &options, || Ok(())).unwrap(); + let lights = + Lighting::new(vec![super::super::lighting::DirectionalLight::new(Vec3::new(0.6, 0.0, 0.8), Vec3::new(1.0, 1.0, 1.0), 1.0).unwrap()]).unwrap(); + let surface = scene.meshes[0].surface.unwrap(); + let first = targets[0].unwrap().shade(&lights, surface, Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap(); + let turned = targets[1].unwrap().shade(&lights, surface, Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap(); + assert!(turned.x > first.x + 0.1); + assert_eq!(targets[0].unwrap().shade(&lights, surface, Vec3::Z, Vec3::Z, |_, _| Ok(false)).unwrap(), Vec3::ZERO); + assert_eq!(targets[0].unwrap().shade(&lights, surface, Vec3::Z, -Vec3::Z, |_, _| Ok(true)).unwrap(), Vec3::ZERO); +} + +#[test] +fn decoded_cpu_png_rotates_only_the_two_explicit_planar_targets() { + fn render(scene: ProductScene, camera: Camera, options: RaytraceOptions) -> ::image::RgbaImage { + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(options.clone()), + camera, + width: 64, + height: 32, + background: [10, 20, 30], + transparent_background: false, + }; + let mut task = super::super::image::ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return ::image::load_from_memory(&png).unwrap().to_rgba8(); + } + } + panic!("bounded planar anisotropic PNG fixture failed to finish"); + } + let scene = scene(); + let original = scene.meshes.iter().map(|b| b.mesh.positions.clone()).collect::>(); + let mut camera = Camera::default(); + camera.set_view(StandardView::Top); + camera.fit(&scene.bounds); + let first = render(scene.clone(), camera, options()); + let mut rotated = options(); + rotated.anisotropic_faces[0].as_mut().unwrap().orientation = AnisotropicOrientation::QuarterTurn; + rotated.anisotropic_faces[1].as_mut().unwrap().orientation = AnisotropicOrientation::Zero; + let second = render(scene.clone(), camera, rotated); + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); + for (index, x) in [-5.0, 0.0, 5.0].into_iter().enumerate() { + let (sx, sy, _) = camera.to_screen(Vec3::new(x, 0.0, 0.0), 64.0, 32.0, radius).unwrap(); + let a = first.get_pixel(sx.floor() as u32, sy.floor() as u32).0; + let b = second.get_pixel(sx.floor() as u32, sy.floor() as u32).0; + assert_ne!(a, [10, 20, 30, 255], "target centre missed fixture geometry"); + if index < 2 { + assert!(i16::from(a[0]).abs_diff(i16::from(b[0])) > 20, "selected face failed to rotate: {a:?} {b:?}"); + } else { + assert_eq!(a, b, "unselected scalar control changed"); + } + } + assert_eq!(first.get_pixel(0, 0).0, [10, 20, 30, 255]); + assert_eq!(first.get_pixel(0, 0), second.get_pixel(0, 0)); + assert_eq!(original, scene.meshes.iter().map(|b| b.mesh.positions.clone()).collect::>()); +} + +#[test] +fn reflection_bridge_preserves_anisotropic_pdf_weight_and_visual_rotation() { + let targets = prepare(&scene(), &options(), || Ok(())).unwrap(); + let surface = scene().meshes[0].surface.unwrap(); + let a = targets[0].unwrap().sample(surface, Vec3::Z, Vec3::Z, [0.4, 0.2]).unwrap().unwrap(); + let b = targets[1].unwrap().sample(surface, Vec3::Z, Vec3::Z, [0.4, 0.2]).unwrap().unwrap(); + let core = AnisotropicSurface::new(surface.base_color(), surface.metallic(), 0.25, 0.8, surface.dielectric_ior()).unwrap(); + let reference = core.sample_reflection(VisualFrame::new(Vec3::Z, Vec3::X).unwrap(), Vec3::Z, Vec3::Z, [0.4, 0.2]).unwrap().unwrap(); + assert_eq!(a.direction, reference.direction); + assert_eq!(a.pdf, reference.pdf); + assert_eq!(a.weight, reference.weight); + assert!((b.direction - Vec3::new(-a.direction.y, a.direction.x, a.direction.z)).len() < 1e-13); + assert!((b.pdf - a.pdf).abs() < 1e-13); + assert!( + (core.brdf(VisualFrame::new(Vec3::Z, Vec3::X).unwrap(), Vec3::Z, Vec3::Z, a.direction).unwrap() + - core.brdf(VisualFrame::new(Vec3::Z, Vec3::X).unwrap(), Vec3::Z, a.direction, Vec3::Z).unwrap()) + .len() + < 1e-13 + ); +} + +#[test] +fn equal_axes_use_the_existing_isotropic_samples_and_null_mass() { + let mut options = options(); + for input in options.anisotropic_faces.iter_mut().flatten() { + input.roughness_x = 1.0; + input.roughness_y = 1.0; + } + let targets = prepare(&scene(), &options, || Ok(())).unwrap(); + let surface = scene().meshes[0].surface.unwrap(); + let isotropic = OpaqueSurface::new(surface.base_color(), surface.metallic(), 1.0, surface.dielectric_ior()).unwrap(); + let mut accepted = 0; + for i in 0..1024 { + let u = [(i as f64 + 0.5) / 1024.0, 0.3]; + let a = targets[0].unwrap().sample(surface, Vec3::Z, Vec3::Z, u).unwrap(); + let b = super::super::reflection::rough_specular(isotropic, Vec3::Z, Vec3::Z, u).unwrap(); + match (a, b) { + (Some(a), Some(b)) => { + accepted += 1; + assert_eq!(a.direction, b.direction); + assert_eq!(a.pdf, b.pdf); + assert_eq!(a.weight, b.weight); + assert!((a.pdf - 1.0 / (4.0 * std::f64::consts::PI)).abs() < 1e-13); + } + (None, None) => {} + _ => panic!("isotropic sample/null mismatch"), + } + } + assert_eq!(accepted, 512); // Remaining half is null, never renormalized. +} diff --git a/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs b/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs new file mode 100644 index 000000000..754ac075f --- /dev/null +++ b/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs @@ -0,0 +1,237 @@ +use super::*; +use crate::job::{AnisotropicFaceOptions, AnisotropicOrientation, ReflectionBody, ReflectionMode, ReflectionOptions}; +use crate::{ProductMesh, StandardView}; +use solidcraft_geom::Mesh; +use std::sync::Arc; + +fn scene() -> ProductScene { + let reflector = ProductMesh { + name: "explicit planar reflector".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-20.0, -20.0, -20.0), Vec3::new(20.0, -20.0, -20.0), Vec3::new(20.0, 20.0, 20.0), Vec3::new(-20.0, 20.0, 20.0)], + normals: vec![super::super::unit(Vec3::new(0.0, -1.0, 1.0)).unwrap(); 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![7, 7], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.8, 0.8, 0.8), 1.0, 0.4, 1.5).unwrap()), + faces: Vec::new(), + }; + let object = ProductMesh { + name: "off-axis orange object".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-3.0, -12.0, 10.0), Vec3::new(-3.0, 12.0, 10.0), Vec3::new(3.0, 12.0, 10.0), Vec3::new(3.0, -12.0, 10.0)], + normals: vec![-Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }), + color: [240, 80, 20], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }; + let meshes = vec![reflector, object]; + let bounds = meshes.iter().map(|b| b.mesh.bounds()).reduce(|a, b| a.union(&b)).unwrap(); + ProductScene { meshes, bounds } +} + +fn request(orientation: AnisotropicOrientation, reflect: bool) -> ImageRequest { + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(StandardView::Front); + let target = AnisotropicFaceOptions { + body_index: 0, + body_name: "explicit planar reflector".into(), + face: 7, + tangent: [1.0, 0.0, 0.0], + orientation, + roughness_x: 0.2, + roughness_y: 0.55, + }; + let options = RaytraceOptions { + anisotropic_faces: [Some(target), None], + reflections: reflect.then(|| ReflectionOptions { + bodies: vec![ReflectionBody { body: "explicit planar reflector".into(), mode: ReflectionMode::RoughSpecular }], + max_bounces: 1, + samples: 64, + }), + lights: Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, -1.0], color: [1.0; 3], intensity: 2.0 }]), + shadows: false, + ..Default::default() + }; + ImageRequest { + integrator: job::Integrator::Raytrace, + raytrace: Some(options), + camera, + width: 1, + height: 1, + background: [13, 27, 41], + transparent_background: false, + } +} + +fn render(request: ImageRequest) -> [u8; 4] { + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new(scene(), request, CancelToken::default(), options).unwrap(); + for _ in 0..200_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return ::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0; + } + } + panic!("bounded reflected scene PNG did not finish"); +} + +#[test] +fn actual_reflected_object_changes_with_the_selected_planar_orientation() { + let baseline = render(request(AnisotropicOrientation::Zero, false)); + assert_eq!(baseline, [0, 0, 0, 255]); // Light is below the reflector; no direct term. + let a = render(request(AnisotropicOrientation::Zero, true)); + let b = render(request(AnisotropicOrientation::QuarterTurn, true)); + assert!(a[0] > a[1] && a[1] > a[2], "actual orange object must contribute via a secondary hit: {a:?}"); + assert_ne!(a, b, "rotation must affect actual reflected scene transport"); + assert_eq!(a, render(request(AnisotropicOrientation::Zero, true))); +} + +#[test] +fn equal_axes_in_the_image_consumer_match_isotropic_reflection_bytes() { + let mut isotropic = request(AnisotropicOrientation::Zero, true); + isotropic.raytrace.as_mut().unwrap().anisotropic_faces = [None, None]; + let expected = render(isotropic); + for orientation in [AnisotropicOrientation::Zero, AnisotropicOrientation::QuarterTurn] { + let mut explicit = request(orientation, true); + let target = explicit.raytrace.as_mut().unwrap().anisotropic_faces[0].as_mut().unwrap(); + target.roughness_x = 0.4; + target.roughness_y = 0.4; + assert_eq!(render(explicit), expected); + } +} + +#[test] +fn mirrors_missing_or_ambiguous_reflection_targets_refuse_before_pixels() { + for kind in 0..3 { + let mut scene = scene(); + let mut request = request(AnisotropicOrientation::Zero, true); + let reflection = &mut request.raytrace.as_mut().unwrap().reflections.as_mut().unwrap().bodies[0]; + match kind { + 0 => reflection.mode = ReflectionMode::Mirror, + 1 => reflection.body = "missing".into(), + _ => scene.meshes[1].name = "explicit planar reflector".into(), + } + assert!(admit(&scene, &request, request.raytrace.as_ref().unwrap()).is_err()); + } +} + +#[test] +fn secondary_anisotropic_traversal_shares_job_work_and_cancellation() { + for cancel_now in [true, false] { + let request = request(AnisotropicOrientation::Zero, true); + let options = request.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene(), request, cancel.clone(), options).unwrap(); + let mut reached = false; + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.bounce > 0) { + reached = true; + break; + } + } + assert!(reached, "actual consumer never continued the sampled anisotropic ray"); + if cancel_now { + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + } else { + task.work.limit = task.work.used(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + } + } +} + +#[test] +fn primary_last_shadow_and_reflected_continuations_each_charge_at_most_one_unit() { + for shadows in [false, true] { + let mut request = request(AnisotropicOrientation::Zero, true); + request.raytrace.as_mut().unwrap().shadows = shadows; + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new(scene(), request, CancelToken::default(), options).unwrap(); + for _ in 0..10_000 { + if task.bvh.is_some() { + break; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + assert!(task.bvh.is_some()); + let mut primary = false; + let mut last_shadow = false; + let mut secondary = false; + let mut secondary_hit = false; + let mut secondary_terminal = false; + for _ in 0..200_000 { + if task.pixel == 1 { + break; + } + let before_work = task.work.used(); + let before_sample = task.sample; + let before = task.pending.as_ref().map(|p| (p.bounce, p.hit.is_some(), p.light)); + task.pixel_one().unwrap(); + assert!(task.work.used() - before_work <= 1, "one pixel continuation consumed traversal and shading work together"); + let after = task.pending.as_ref().map(|p| (p.bounce, p.hit.is_some(), p.light)); + primary |= matches!(before, Some((0, false, _))) && matches!(after, Some((0, true, _))); + last_shadow |= shadows && matches!(before, Some((_, true, 0))) && matches!(after, Some((_, true, 1))); + secondary |= after.is_some_and(|(bounce, _, _)| bounce > 0); + secondary_hit |= before.is_some_and(|(bounce, hit, _)| bounce > 0 && !hit) && after.is_some_and(|(bounce, hit, _)| bounce > 0 && hit); + secondary_terminal |= before.is_some_and(|(bounce, _, _)| bounce > 0) && (task.sample != before_sample || task.pixel == 1); + } + assert_eq!(task.pixel, 1); + assert!(primary && secondary && secondary_hit && secondary_terminal); + assert!(!shadows || last_shadow); + } + // The public poll groups at most four of those continuations. + let request = request(AnisotropicOrientation::Zero, true); + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new(scene(), request, CancelToken::default(), options).unwrap(); + for _ in 0..10_000 { + if task.bvh.is_some() { + break; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + let mut completed = false; + for _ in 0..200_000 { + let before = task.work.used(); + let poll = task.step(4).unwrap(); + assert!(task.work.used() - before <= 4); + if matches!(poll, TaskPoll::Complete(_)) { + completed = true; + break; + } + } + assert!(completed); +} + +#[test] +fn cancellation_after_last_shadow_is_seen_before_shading_or_sampling() { + for secondary in [false, true] { + let mut request = request(AnisotropicOrientation::Zero, true); + request.raytrace.as_mut().unwrap().shadows = true; + let options = request.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene(), request, cancel.clone(), options).unwrap(); + let mut reached = false; + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.light == task.lights.lights().len() && (p.bounce > 0) == secondary) { + reached = true; + break; + } + } + assert!(reached && task.pixels.is_empty()); + let before_sample = task.sample; + cancel.cancel(); + assert_eq!(task.pixel_one().err().unwrap().code, ErrorCode::Cancelled); + assert_eq!(task.sample, before_sample); + assert!(task.pixels.is_empty()); + } +} diff --git a/crates/render/src/raytrace/bvh.rs b/crates/render/src/raytrace/bvh.rs new file mode 100644 index 000000000..f9a291fc6 --- /dev/null +++ b/crates/render/src/raytrace/bvh.rs @@ -0,0 +1,405 @@ +//! Flat, deterministic binary hierarchy with resumable constant-size build work. +use super::{Bounds, Hit, MAX_BUILD_STEP, MAX_WORK, Ray, Result, TraceError, Triangle, WorkBudget, check_cancel, component}; +use crate::job::CancelToken; +use std::mem::size_of; + +pub const MAX_TRIANGLES: usize = 1_000_000; +pub const MAX_DEPTH: u8 = 48; +pub const MAX_MEMORY_BYTES: u64 = 512 * 1024 * 1024; +const STACK_SLOTS: usize = MAX_DEPTH as usize + 1; + +/// Logical owned-buffer admission. Does not reserve the host pool or promise OS RSS. +#[derive(Clone, Copy, Debug)] +pub struct BuildLimits { + pub max_triangles: usize, + pub max_memory_bytes: u64, + pub max_work: u64, + pub max_depth: u8, + pub leaf_size: usize, +} +impl Default for BuildLimits { + fn default() -> Self { + Self { max_triangles: 100_000, max_memory_bytes: 128 * 1024 * 1024, max_work: 10_000_000, max_depth: 32, leaf_size: 8 } + } +} +impl BuildLimits { + fn validate(self) -> Result<()> { + if self.max_triangles == 0 + || self.max_triangles > MAX_TRIANGLES + || self.max_memory_bytes == 0 + || self.max_memory_bytes > MAX_MEMORY_BYTES + || self.max_work == 0 + || self.max_work > MAX_WORK + || self.max_depth == 0 + || self.max_depth > MAX_DEPTH + || self.leaf_size == 0 + || self.leaf_size > 64 + { + return Err(TraceError::InvalidInput("BVH build limits exceed supported bounds")); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug)] +enum Kind { + Leaf { start: usize, end: usize }, + Branch { left: usize, right: usize }, +} +#[derive(Clone, Copy, Debug)] +struct Node { + bounds: Bounds, + kind: Kind, +} +impl Node { + fn pending() -> Self { + Self { bounds: Bounds::empty(), kind: Kind::Leaf { start: 0, end: 0 } } + } +} +#[derive(Clone, Copy, Debug)] +struct Task { + node: usize, + start: usize, + end: usize, + depth: u8, +} +#[derive(Clone, Copy, Debug)] +enum State { + Loading(usize), + Next, + Bounds { task: Task, cursor: usize, bounds: Bounds, centers: Bounds }, + Partition { task: Task, cursor: usize, split: usize, axis: usize, plane: f64, bounds: Bounds }, + Done, +} + +/// No partial acceleration structure escapes this builder. Each `step` operation +/// handles at most one input ordinal, bound or partition item, or one node transition. +pub struct BvhBuilder { + triangles: Vec, + order: Vec, + nodes: Vec, + pending: Vec, + state: State, + limits: BuildLimits, + work: WorkBudget, + admitted_bytes: u64, +} + +/// Progress is work consumed, not a speculative completion percentage. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BuildProgress { + pub complete: bool, + pub work_used: u64, +} + +fn bytes_for(count: usize, item: usize) -> Result { + let bytes = count.checked_mul(item).ok_or(TraceError::MemoryLimit)?; + u64::try_from(bytes).map_err(|_| TraceError::MemoryLimit) +} + +fn memory(triangles: usize, order: usize, nodes: usize, pending: usize) -> Result { + let mut total = (size_of::() + size_of::() + size_of::<[usize; STACK_SLOTS]>()) as u64; + for amount in [ + bytes_for(triangles, size_of::())?, + bytes_for(order, size_of::())?, + bytes_for(nodes, size_of::())?, + bytes_for(pending, size_of::())?, + ] { + total = total.checked_add(amount).ok_or(TraceError::MemoryLimit)?; + } + Ok(total) +} + +impl BvhBuilder { + /// Includes the supplied input Vec's capacity, maximum nodes, ordinal array, + /// pending tasks and one traversal stack. No hidden full-scene sorting copy. + pub fn required_bytes(triangle_count: usize, input_capacity: usize, limits: BuildLimits) -> Result { + limits.validate()?; + if triangle_count > limits.max_triangles || input_capacity < triangle_count { + return Err(TraceError::InvalidInput("triangle count or input capacity")); + } + let nodes = + if triangle_count == 0 { 0 } else { triangle_count.checked_mul(2).and_then(|n| n.checked_sub(1)).ok_or(TraceError::MemoryLimit)? }; + let amount = memory(input_capacity, triangle_count, nodes, usize::from(limits.max_depth) + 1)?; + if amount > limits.max_memory_bytes { + return Err(TraceError::MemoryLimit); + } + Ok(amount) + } + + /// Takes ownership of already admitted primitives. Checks/reserves before + /// building; copying/initializing one million ordinals is deferred to `step`. + pub fn new(triangles: Vec, limits: BuildLimits, cancel: &CancelToken) -> Result { + check_cancel(cancel)?; + let n = triangles.len(); + Self::required_bytes(n, triangles.capacity(), limits)?; + let node_capacity = if n == 0 { 0 } else { n.checked_mul(2).and_then(|v| v.checked_sub(1)).ok_or(TraceError::MemoryLimit)? }; + let mut order = Vec::new(); + order.try_reserve_exact(n).map_err(|_| TraceError::AllocationFailed)?; + check_cancel(cancel)?; + let mut nodes = Vec::new(); + nodes.try_reserve_exact(node_capacity).map_err(|_| TraceError::AllocationFailed)?; + check_cancel(cancel)?; + let mut pending = Vec::new(); + pending.try_reserve_exact(usize::from(limits.max_depth) + 1).map_err(|_| TraceError::AllocationFailed)?; + let admitted_bytes = memory(triangles.capacity(), order.capacity(), nodes.capacity(), pending.capacity())?; + if admitted_bytes > limits.max_memory_bytes { + return Err(TraceError::MemoryLimit); + } + let state = if n == 0 { + State::Done + } else { + nodes.push(Node::pending()); + pending.push(Task { node: 0, start: 0, end: n, depth: 0 }); + State::Loading(0) + }; + check_cancel(cancel)?; + Ok(Self { triangles, order, nodes, pending, state, limits, work: WorkBudget::new(limits.max_work)?, admitted_bytes }) + } + + pub fn admitted_bytes(&self) -> u64 { + self.admitted_bytes + } + + fn triangle_at(&self, ordinal: usize) -> Result { + let index = *self.order.get(ordinal).ok_or(TraceError::Internal("build ordinal"))?; + self.triangles.get(index).copied().ok_or(TraceError::Internal("build primitive")) + } + + pub fn step(&mut self, operations: usize, cancel: &CancelToken) -> Result { + if operations == 0 || operations > MAX_BUILD_STEP { + return Err(TraceError::InvalidInput("build step outside 1..=MAX_BUILD_STEP")); + } + check_cancel(cancel)?; + for _ in 0..operations { + if matches!(self.state, State::Done) { + break; + } + self.work.tick(cancel)?; + self.state = match self.state { + State::Loading(cursor) => { + if cursor < self.triangles.len() { + self.order.push(cursor); + State::Loading(cursor + 1) + } else { + State::Next + } + } + State::Next => match self.pending.pop() { + Some(task) => State::Bounds { task, cursor: task.start, bounds: Bounds::empty(), centers: Bounds::empty() }, + None => State::Done, + }, + State::Bounds { task, cursor, mut bounds, mut centers } => { + if cursor < task.end { + let triangle = self.triangle_at(cursor)?; + bounds = bounds.include(triangle.bounds()); + centers = centers.include(Bounds::point(triangle.centroid())); + State::Bounds { task, cursor: cursor + 1, bounds, centers } + } else if task.end - task.start <= self.limits.leaf_size || task.depth >= self.limits.max_depth { + let node = self.nodes.get_mut(task.node).ok_or(TraceError::Internal("build leaf"))?; + *node = Node { bounds, kind: Kind::Leaf { start: task.start, end: task.end } }; + State::Next + } else { + let extent = centers.max - centers.min; + let axis = if extent.x >= extent.y && extent.x >= extent.z { + 0 + } else if extent.y >= extent.z { + 1 + } else { + 2 + }; + let plane = component(centers.min, axis) * 0.5 + component(centers.max, axis) * 0.5; + State::Partition { task, cursor: task.start, split: task.start, axis, plane, bounds } + } + } + State::Partition { task, cursor, mut split, axis, plane, bounds } => { + if cursor < task.end { + if component(self.triangle_at(cursor)?.centroid(), axis) < plane { + // `swap` indices are bounded by this private task range, + // but still check rather than panic if an invariant breaks. + let value = *self.order.get(cursor).ok_or(TraceError::Internal("partition cursor"))?; + let other = *self.order.get(split).ok_or(TraceError::Internal("partition split"))?; + *self.order.get_mut(cursor).ok_or(TraceError::Internal("partition cursor"))? = other; + *self.order.get_mut(split).ok_or(TraceError::Internal("partition split"))? = value; + split += 1; + } + State::Partition { task, cursor: cursor + 1, split, axis, plane, bounds } + } else { + // Coincident centroids still make progress, in existing input + // order. Never recurse or retry an empty partition forever. + if split == task.start || split == task.end { + split = task.start + (task.end - task.start) / 2; + } + let left = self.nodes.len(); + let right = left.checked_add(1).ok_or(TraceError::Internal("node count"))?; + if self.nodes.capacity() - self.nodes.len() < 2 || self.pending.capacity() - self.pending.len() < 2 { + return Err(TraceError::Internal("reserved BVH capacity")); + } + self.nodes.push(Node::pending()); + self.nodes.push(Node::pending()); + let parent = self.nodes.get_mut(task.node).ok_or(TraceError::Internal("build branch"))?; + *parent = Node { bounds, kind: Kind::Branch { left, right } }; + self.pending.push(Task { node: right, start: split, end: task.end, depth: task.depth + 1 }); + self.pending.push(Task { node: left, start: task.start, end: split, depth: task.depth + 1 }); + State::Next + } + } + State::Done => State::Done, + }; + } + check_cancel(cancel)?; + Ok(BuildProgress { complete: matches!(self.state, State::Done), work_used: self.work.used() }) + } + + pub fn finish(self) -> Result { + if !matches!(self.state, State::Done) { + return Err(TraceError::BuildIncomplete); + } + Ok(Bvh { triangles: self.triangles, order: self.order, nodes: self.nodes }) + } +} + +/// Completed owned geometry; no shared cache, host worker or device state. +pub struct Bvh { + triangles: Vec, + order: Vec, + nodes: Vec, +} +impl Bvh { + pub fn primitive_count(&self) -> usize { + self.triangles.len() + } + pub fn node_count(&self) -> usize { + self.nodes.len() + } + pub fn retained_bytes(&self) -> Result { + // Conservatively retains the builder's fixed overhead allowance as well. + memory(self.triangles.capacity(), self.order.capacity(), self.nodes.capacity(), 0) + } + pub const fn traversal_scratch_bytes() -> usize { + size_of::<[usize; STACK_SLOTS]>() + } + + pub fn closest_hit(&self, ray: &Ray, work: &mut WorkBudget, cancel: &CancelToken) -> Result> { + self.trace(ray, false, work, cancel) + } + pub fn any_hit(&self, ray: &Ray, work: &mut WorkBudget, cancel: &CancelToken) -> Result { + self.trace(ray, true, work, cancel).map(|hit| hit.is_some()) + } + + fn trace(&self, ray: &Ray, any: bool, work: &mut WorkBudget, cancel: &CancelToken) -> Result> { + check_cancel(cancel)?; + if self.nodes.is_empty() { + return Ok(None); + } + let mut stack = [0_usize; STACK_SLOTS]; + let mut length = 1; + let mut best: Option = None; + while length != 0 { + work.tick(cancel)?; + length -= 1; + let node_index = *stack.get(length).ok_or(TraceError::Internal("traversal pop"))?; + let node = self.nodes.get(node_index).ok_or(TraceError::Internal("traversal node"))?; + let maximum = best.map_or(ray.max, |hit| hit.geometry.distance); + if node.bounds.clip(ray, maximum).is_none() { + continue; + } + match node.kind { + Kind::Branch { left, right } => { + for child in [right, left] { + *stack.get_mut(length).ok_or(TraceError::Internal("bounded traversal stack"))? = child; + length += 1; + } + } + Kind::Leaf { start, end } => { + for ordinal in start..end { + work.tick(cancel)?; + let index = *self.order.get(ordinal).ok_or(TraceError::Internal("traversal ordinal"))?; + let triangle = self.triangles.get(index).ok_or(TraceError::Internal("traversal primitive"))?; + if let Some(geometry) = triangle.intersect(ray) { + let hit = Hit { primitive_index: index, geometry }; + if any { + check_cancel(cancel)?; + return Ok(Some(hit)); + } + if best.is_none_or(|old| { + geometry.distance < old.geometry.distance + || (geometry.distance == old.geometry.distance && index < old.primitive_index) + }) { + best = Some(hit); + } + } + } + } + } + } + check_cancel(cancel)?; + Ok(best) + } +} +/// Resumable traversal used by image jobs. Each step visits one node or primitive. +/// The fixed stack is included in image admission; no per-ray heap allocation. +pub(crate) struct TraceCursor { + ray: Ray, + any: bool, + stack: [usize; STACK_SLOTS], + length: usize, + leaf: Option<(usize, usize)>, + best: Option, + done: bool, +} +impl TraceCursor { + pub(crate) fn new(ray: Ray, any: bool) -> Self { + Self { ray, any, stack: [0; STACK_SLOTS], length: 1, leaf: None, best: None, done: false } + } + pub(crate) fn step(&mut self, bvh: &Bvh, work: &mut WorkBudget, cancel: &CancelToken) -> Result>> { + work.tick(cancel)?; + if self.done { + return Err(TraceError::Internal("completed traversal cursor")); + } + if bvh.nodes.is_empty() { + self.done = true; + return Ok(Some(None)); + } + if let Some((ordinal, end)) = self.leaf { + if ordinal < end { + self.leaf = Some((ordinal + 1, end)); + let index = *bvh.order.get(ordinal).ok_or(TraceError::Internal("cursor ordinal"))?; + let triangle = bvh.triangles.get(index).ok_or(TraceError::Internal("cursor primitive"))?; + if let Some(geometry) = triangle.intersect(&self.ray) { + let hit = Hit { primitive_index: index, geometry }; + if self.any { + self.done = true; + return Ok(Some(Some(hit))); + } + if self.best.is_none_or(|old| { + geometry.distance < old.geometry.distance || (geometry.distance == old.geometry.distance && index < old.primitive_index) + }) { + self.best = Some(hit); + } + } + return Ok(None); + } + self.leaf = None; + } + if self.length == 0 { + self.done = true; + return Ok(Some(self.best)); + } + self.length -= 1; + let node_index = *self.stack.get(self.length).ok_or(TraceError::Internal("cursor pop"))?; + let node = bvh.nodes.get(node_index).ok_or(TraceError::Internal("cursor node"))?; + if node.bounds.clip(&self.ray, self.best.map_or(self.ray.max, |hit| hit.geometry.distance)).is_some() { + match node.kind { + Kind::Leaf { start, end } => self.leaf = Some((start, end)), + Kind::Branch { left, right } => { + for child in [right, left] { + *self.stack.get_mut(self.length).ok_or(TraceError::Internal("cursor stack"))? = child; + self.length += 1; + } + } + } + } + Ok(None) + } +} diff --git a/crates/render/src/raytrace/deterministic_primary_tests.rs b/crates/render/src/raytrace/deterministic_primary_tests.rs new file mode 100644 index 000000000..3e7f3f5b9 --- /dev/null +++ b/crates/render/src/raytrace/deterministic_primary_tests.rs @@ -0,0 +1,208 @@ +use super::*; +use crate::job::{ReflectionBody, ReflectionMode, ReflectionOptions}; +use crate::lighting::{HdrSource, environment_input::EnvironmentInput}; +use solidcraft_geom::{Aabb3, Mesh}; +use std::sync::Arc; + +fn environment() -> EnvironmentInput { + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 64, 32, 129]); + } + EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.0, 1.0, 4).unwrap() +} + +fn scene(face_override: bool) -> ProductScene { + let mut meshes = Vec::new(); + for (name, x) in [("Visible", 0.0), ("Hidden", 1000.0)] { + let mesh = Mesh { + positions: vec![ + Vec3::new(x - 20.0, -20.0, 0.0), + Vec3::new(x + 20.0, -20.0, 0.0), + Vec3::new(x + 20.0, 20.0, 0.0), + Vec3::new(x - 20.0, 20.0, 0.0), + ], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }; + meshes.push(crate::ProductMesh { + name: name.into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap()), + faces: Vec::new(), + }); + } + if face_override { + meshes[0].faces.push(crate::FaceAppearance { + face: 0, + color: [0; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 1.0, 1.0, 1.5).unwrap()), + }); + } + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + ProductScene { meshes, bounds } +} + +fn task(samples: u8, selected: bool, face_override: bool, shadows: bool) -> ImageTask { + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + let options = RaytraceOptions { + lights: Some(Vec::new()), + shadows, + reflections: Some(ReflectionOptions { + bodies: vec![ReflectionBody { body: if selected { "Visible" } else { "Hidden" }.into(), mode: ReflectionMode::RoughSpecular }], + max_bounces: 2, + samples, + }), + ..Default::default() + }; + let request = ImageRequest { + integrator: job::Integrator::Raytrace, + raytrace: Some(options.clone()), + camera, + width: 1, + height: 1, + background: [13, 27, 41], + transparent_background: false, + }; + ImageTask::new_with_environment(scene(face_override), request, CancelToken::default(), options, Some(environment())).unwrap() +} + +fn render(mut task: ImageTask, revoke_fixed_primary_proof: bool) -> (Vec, u64, usize) { + let mut primaries = 0; + for _ in 0..200_000 { + // Test-only reference: revoking the generator proof keeps the original R + // path/accumulation. No product switch, sampler, work limit or input changes. + if revoke_fixed_primary_proof && let Some(p) = task.pending.as_mut() { + p.repeatable_primary = false; + } + let absent = task.pending.is_none(); + match task.step(1).unwrap() { + TaskPoll::Complete(png) => return (png, task.work.used(), primaries), + TaskPoll::Pending(_) => { + if absent && task.pending.is_some() { + primaries += 1; + } + } + } + } + panic!("bounded single-pixel fixture did not finish"); +} + +#[test] +fn nonselected_fixed_primary_matches_analytic_color_and_legacy_r_with_less_work() { + for samples in [1, 4, 16, 64] { + for shadows in [false, true] { + let (fast, work, primaries) = render(task(samples, false, false, shadows), false); + let (legacy, legacy_work, legacy_primaries) = render(task(samples, false, false, shadows), true); + assert_eq!(fast, legacy, "same radiance without repeated identical primary samples"); + assert_eq!(primaries, 1); + assert_eq!(legacy_primaries, usize::from(samples)); + if samples == 1 { + assert_eq!(work, legacy_work); + } else { + assert!(work < legacy_work); + } + if !shadows { + // White roughness-one conductor, constant RGB(1,.5,.25), fixed + // 2x2 solid-angle strata: two z=.5 contributions average to1/3. + let expected = [1.0 / 3.0, 1.0 / 6.0, 1.0 / 12.0].map(|v| encode(v / (1.0 + v))); + let image = ::image::load_from_memory(&fast).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]); + } + } + } +} + +#[test] +fn selected_rough_primary_retains_every_sample_including_null_attempts() { + for samples in [4, 16, 64] { + let (actual, work, primaries) = render(task(samples, true, false, false), false); + let (reference, reference_work, reference_primaries) = render(task(samples, true, false, false), true); + assert_eq!(actual, reference); + assert_eq!(work, reference_work); + assert_eq!(primaries, usize::from(samples)); + assert_eq!(primaries, reference_primaries); + } +} + +#[test] +fn captured_face_override_is_resolved_before_nonselected_fast_path_finishes() { + let (png, work, count) = render(task(64, false, true, false), false); + let (reference, reference_work, reference_count) = render(task(64, false, true, false), true); + assert_eq!(png, reference); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [0, 0, 0, 255]); + assert!(work < reference_work); + assert_eq!(count, 1); + assert_eq!(reference_count, 64); +} + +#[test] +fn nonselected_visibility_keeps_shared_cancel_and_work_limit_refusal() { + for cancel_now in [false, true] { + let mut task = task(64, false, false, true); + for _ in 0..10000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some()) { + break; + } + } + assert!(task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some())); + if cancel_now { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step(1).err().unwrap().code, if cancel_now { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert!(!task.done); + } +} + +#[test] +fn selected_sampling_cancellation_does_not_turn_partial_samples_into_png() { + let mut task = task(64, true, false, false); + for _ in 0..10000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.sample >= 1 { + break; + } + } + assert!(task.sample >= 1 && task.sample < 64); + task.cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + assert!(!task.done); +} + +#[test] +fn reused_shading_preserves_original_per_add_radiance_bound() { + let mut task = task(64, false, false, false); + for _ in 0..10000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.repeatable_primary) { + break; + } + } + assert!(task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.repeatable_primary)); + let error = task.finish_sample(Vec3::new(1e12 / 32.0, 0.0, 0.0)).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidScene); + assert_eq!(task.sample, 32); + assert!(!task.done); + assert!(task.pixels.is_empty()); +} + +#[test] +fn request_admission_and_task_slot_caps_are_not_expanded() { + let fast = task(64, false, false, false); + let legacy = task(64, false, false, false); + assert_eq!(fast.options, legacy.options); + assert_eq!(fast.admission.estimated_total_bytes, legacy.admission.estimated_total_bytes); + assert_eq!(fast.options.reflections.as_ref().unwrap().samples, 64); + assert!(std::mem::size_of::() <= 4096); + assert_eq!(MAX_WORK, 1_000_000_000); + assert_eq!(job::image::MAX_JOB_BYTES, 384 * 1024 * 1024); +} diff --git a/crates/render/src/raytrace/environment_image_tests.rs b/crates/render/src/raytrace/environment_image_tests.rs new file mode 100644 index 000000000..54ff3f8c1 --- /dev/null +++ b/crates/render/src/raytrace/environment_image_tests.rs @@ -0,0 +1,181 @@ +use super::*; +use crate::lighting::{HdrSource, environment_input::EnvironmentInput}; +use solidcraft_geom::{Aabb3, Mesh}; +use std::sync::Arc; + +fn input() -> EnvironmentInput { + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 64, 32, 129]); + } + EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.0, 1.0, 64).unwrap() +} +fn scene() -> ProductScene { + let mesh = Arc::new(Mesh { + positions: vec![Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 0.0), Vec3::new(-10.0, 10.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }); + ProductScene { + bounds: mesh.bounds(), + meshes: vec![crate::ProductMesh { + name: "Original conductor plate".into(), + mesh, + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap()), + faces: Vec::new(), + }], + } +} +fn request() -> ImageRequest { + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + ImageRequest { + integrator: job::Integrator::Raytrace, + raytrace: Some(RaytraceOptions { lights: Some(Vec::new()), ..Default::default() }), + camera, + width: 9, + height: 9, + background: [13, 27, 41], + transparent_background: false, + } +} +fn png(source: ProductScene, environment: Option) -> Vec { + let request = request(); + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new_with_environment(source, request, CancelToken::default(), options, environment).unwrap(); + for _ in 0..200_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return png; + } + } + panic!("bounded environment fixture did not complete"); +} + +#[test] +fn real_cpu_png_conductor_matches_independent_environment_quadrature_once() { + let baseline = ::image::load_from_memory(&png(scene(), None)).unwrap().to_rgba8(); + let rendered = png(scene(), Some(input())); + assert_eq!(rendered, png(scene(), Some(input()))); + let image = ::image::load_from_memory(&rendered).unwrap().to_rgba8(); + // Independent roughness-one white-conductor f*cos= z/(2*pi*(1+z)). + // The fixed 8x8 solid-angle strata integrate 4 positive z rows, each 8 samples. + let factor = [0.125, 0.375, 0.625, 0.875].into_iter().map(|z| z / (1.0 + z)).sum::() / 4.0; + let expected = [factor, factor * 0.5, factor * 0.25].map(|r| encode(r / (1.0 + r))); + assert_eq!(image.get_pixel(4, 4).0, [expected[0], expected[1], expected[2], 255]); + assert_eq!(baseline.get_pixel(4, 4).0, [0, 0, 0, 255]); + let empty = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let background = ::image::load_from_memory(&png(empty, Some(input()))).unwrap().to_rgba8(); + assert!(background.pixels().all(|p| p.0 == [13, 27, 41, 255])); +} + +#[test] +fn environment_decode_and_secondary_visibility_share_cancellation_and_work_budget() { + for during_visibility in [false, true] { + let request = request(); + let options = request.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new_with_environment(scene(), request, cancel.clone(), options, Some(input())).unwrap(); + if during_visibility { + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some()) { + break; + } + } + assert!(task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some())); + } + // Cancellation must win before any image publication, including decode preparation. + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + } + let request = request(); + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new_with_environment(scene(), request, CancelToken::default(), options, Some(input())).unwrap(); + task.work = WorkBudget::new(1).unwrap(); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_host_captured_source_completes_and_releases_work_lease() { + let host = job::CpuHost::for_platform().unwrap(); + assert!(host.descriptor_for(job::Integrator::Raytrace).unwrap().profiles[0].features.contains(&crate::RenderFeature::Hdri)); + assert!(!host.descriptor_for(job::Integrator::Raster).unwrap().profiles[0].features.contains(&crate::RenderFeature::Hdri)); + let handle = host.submit_with_environment(job::JobId { session: 1693, serial: 1, generation: 1 }, 1, scene(), request(), Some(input())).unwrap(); + assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + let frame = handle.frame().unwrap().unwrap(); + assert!(host.admitted_bytes() >= frame.png().len() as u64 + 1024); + drop(host); + drop(frame); + drop(handle); +} + +#[test] +fn environment_visibility_respects_four_work_units_per_quantum_and_cancel() { + let request = request(); + let options = request.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new_with_environment(scene(), request, cancel.clone(), options, Some(input())).unwrap(); + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some()) { + break; + } + } + assert!(task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some())); + for _ in 0..32 { + let before = task.work.used(); + assert!(matches!(task.step(4).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() - before <= 4, "visibility continuation double-charged shading and traversal"); + } + cancel.cancel(); + assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled); +} + +#[test] +fn all_pixel_traversal_to_shading_transitions_debit_at_most_one_unit() { + for (directional, shadows) in [(false, true), (true, true), (true, false)] { + let mut request = request(); + let mut options = request.raytrace.clone().unwrap(); + options.shadows = shadows; + if directional { + options.lights = Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }]); + } + request.raytrace = Some(options.clone()); + let cancel = CancelToken::default(); + let mut task = ImageTask::new_with_environment(scene(), request, cancel.clone(), options, Some(input())).unwrap(); + while task.bvh.is_none() { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + let mut primary_transitions = 0; + let mut directional_transitions = 0; + for _ in 0..200_000 { + if task.pixel == 81 { + break; + } + let primary = task.pending.as_ref().is_some_and(|p| p.hit.is_none()); + let light_before = task.pending.as_ref().map(|p| p.light); + let before = task.work.used(); + task.pixel_one().unwrap(); + assert!(task.work.used() - before <= 1, "traversal completion must yield before shading/sample debit"); + if primary && task.pending.as_ref().is_some_and(|p| p.hit.is_some()) { + primary_transitions += 1; + } + if light_before == Some(0) && task.pending.as_ref().is_some_and(|p| p.light == 1) { + directional_transitions += 1; + } + } + assert_eq!(task.pixel, 81); + assert!(primary_transitions > 0); + if directional && shadows { + assert!(directional_transitions > 0); + } + cancel.cancel(); + assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled); + } +} diff --git a/crates/render/src/raytrace/environment_reflection_tests.rs b/crates/render/src/raytrace/environment_reflection_tests.rs new file mode 100644 index 000000000..d821a72a2 --- /dev/null +++ b/crates/render/src/raytrace/environment_reflection_tests.rs @@ -0,0 +1,242 @@ +use super::*; +use crate::job::{ReflectionBody, ReflectionMode, ReflectionOptions}; +use crate::lighting::{HdrSource, environment_input::EnvironmentInput}; +use solidcraft_geom::Mesh; +use std::sync::Arc; + +fn environment(bright: bool, rotation: f64) -> EnvironmentInput { + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for i in 0..8 { + bytes.extend_from_slice(&if bright { if i == 0 { [128, 64, 16, 133] } else { [0; 4] } } else { [128, 64, 32, 129] }); + } + EnvironmentInput::new(HdrSource::new(bytes).unwrap(), rotation, 1.0, 64).unwrap() +} +fn scene(normal: Vec3) -> ProductScene { + let normal = normal / normal.len(); + let u = normal.cross(Vec3::X); + let u = u / u.len() * 10.0; + let v = normal.cross(u); + let mesh = Arc::new(Mesh { + positions: vec![-u - v, u - v, u + v, -u + v], + normals: vec![normal; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }); + ProductScene { + bounds: mesh.bounds(), + meshes: vec![crate::ProductMesh { + name: "Metal".into(), + mesh, + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap()), + faces: Vec::new(), + }], + } +} +fn request(mode: ReflectionMode) -> ImageRequest { + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + ImageRequest { + integrator: job::Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + lights: Some(Vec::new()), + reflections: Some(ReflectionOptions { bodies: vec![ReflectionBody { body: "Metal".into(), mode }], max_bounces: 1, samples: 64 }), + ..Default::default() + }), + camera, + width: 9, + height: 9, + background: [13, 27, 41], + transparent_background: false, + } +} +fn render(scene: ProductScene, request: ImageRequest, input: Option) -> Vec { + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new_with_environment(scene, request, CancelToken::default(), options, input).unwrap(); + for _ in 0..200_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return png; + } + } + panic!("bounded environment reflection did not finish"); +} +fn centre(bytes: &[u8]) -> [u8; 4] { + ::image::load_from_memory(bytes).unwrap().to_rgba8().get_pixel(4, 4).0 +} +fn expected(radiance: [f64; 3]) -> [u8; 4] { + let c = radiance.map(|v| encode(v / (1.0 + v))); + [c[0], c[1], c[2], 255] +} + +#[test] +fn ideal_metal_mirror_receives_environment_once_and_camera_background_stays_independent() { + let req = request(ReflectionMode::Mirror); + assert_eq!(centre(&render(scene(Vec3::Z), req.clone(), None)), [0, 0, 0, 255]); + assert_eq!(centre(&render(scene(Vec3::Z), req.clone(), Some(environment(false, 0.0)))), expected([1.0, 0.5, 0.25])); + let mut empty = req; + empty.raytrace.as_mut().unwrap().reflections = Some(ReflectionOptions::default()); + let image = ::image::load_from_memory(&render( + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + empty, + Some(environment(false, 0.0)), + )) + .unwrap() + .to_rgba8(); + assert!(image.pixels().all(|p| p.0 == [13, 27, 41, 255])); +} + +#[test] +fn rough_metal_environment_matches_independent_sample_weights_without_extra_nee() { + let mut factor = 0.0; + // Normal-view white conductor at roughness1: null for z<=0, weight=2z/(1+z). + // Only the deterministic variate key is shared; no BRDF/PDF implementation is reused. + for sample in 0..64 { + let u = reflection::variates(40, sample, 0, 64).unwrap(); + let z = 1.0 - 2.0 * u[0]; + if z > 0.0 { + factor += 2.0 * z / (1.0 + z) / 64.0; + } + } + let req = request(ReflectionMode::RoughSpecular); + let png = render(scene(Vec3::Z), req.clone(), Some(environment(false, 0.0))); + assert_eq!(centre(&png), expected([factor, factor * 0.5, factor * 0.25])); + assert_eq!(png, render(scene(Vec3::Z), req, Some(environment(false, 0.0)))); +} + +#[test] +fn mirror_bright_cell_rotates_in_world_space_without_changing_background() { + let reflected = Vec3::new(0.5, 0.5, 0.5_f64.sqrt()); + let normal = Vec3::Z + reflected; + let req = request(ReflectionMode::Mirror); + assert_eq!(centre(&render(scene(normal), req.clone(), Some(environment(true, 0.0)))), expected([16.0, 8.0, 2.0])); + assert_eq!(centre(&render(scene(normal), req, Some(environment(true, std::f64::consts::FRAC_PI_2)))), [0, 0, 0, 255]); +} + +#[test] +fn unsupported_diffuse_rough_hdr_refuses_and_selector_capacities_remain_accounted() { + let req = request(ReflectionMode::RoughSpecular); + let options = req.raytrace.clone().unwrap(); + let mut invalid = scene(Vec3::Z); + invalid.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.5, 1.0, 1.5).unwrap()); + assert!(ImageTask::new_with_environment(invalid, req.clone(), CancelToken::default(), options.clone(), Some(environment(false, 0.0))).is_err()); + let mut invalid = scene(Vec3::Z); + invalid.meshes[0].faces.push(crate::FaceAppearance { face: 0, color: [255; 3], opacity: 1.0, surface: None }); + assert!(options.validate_environment_reflections(&invalid).is_err()); + let selectors = options.reflections.as_ref().unwrap(); + assert_eq!( + options.retained_bytes().unwrap(), + (selectors.bodies.capacity() * std::mem::size_of::() + selectors.bodies[0].body.capacity()) as u64 + ); + assert!(std::mem::size_of::() <= 4096, "combined task state must fit the host's admitted slot"); +} + +#[test] +fn secondary_environment_miss_obeys_shared_work_limit_and_cancel() { + for cancel_now in [false, true] { + let req = request(ReflectionMode::Mirror); + let options = req.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new_with_environment(scene(Vec3::Z), req, cancel.clone(), options, Some(environment(false, 0.0))).unwrap(); + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.bounce > 0) { + break; + } + } + assert!(task.pending.as_ref().is_some_and(|p| p.bounce > 0)); + if cancel_now { + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + } else { + task.work.limit = task.work.used(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + } + } +} + +fn anisotropic_request(mode: ReflectionMode, equal_axes: bool) -> ImageRequest { + let mut request = request(mode); + request.raytrace.as_mut().unwrap().anisotropic_faces = [ + Some(job::AnisotropicFaceOptions { + body_index: 0, + body_name: "Metal".into(), + face: 0, + tangent: [1.0, 0.0, 0.0], + orientation: job::AnisotropicOrientation::Zero, + roughness_x: if equal_axes { 1.0 } else { 0.2 }, + roughness_y: if equal_axes { 1.0 } else { 0.6 }, + }), + None, + ]; + request +} + +#[test] +fn hdr_equal_anisotropic_axes_match_isotropic_reflected_environment_bytes() { + let plain = render(scene(Vec3::Z), request(ReflectionMode::RoughSpecular), Some(environment(false, 0.0))); + let request = anisotropic_request(ReflectionMode::RoughSpecular, true); + assert_eq!(plain, render(scene(Vec3::Z), request, Some(environment(false, 0.0)))); +} + +#[test] +fn hdr_anisotropic_direct_and_mirror_combinations_refuse_before_pixels() { + for kind in 0..2 { + let mut request = anisotropic_request(ReflectionMode::RoughSpecular, false); + if kind == 0 { + request.raytrace.as_mut().unwrap().reflections = None; + } else { + request.raytrace.as_mut().unwrap().reflections.as_mut().unwrap().bodies[0].mode = ReflectionMode::Mirror; + } + let options = request.raytrace.clone().unwrap(); + assert!(ImageTask::new_with_environment(scene(Vec3::Z), request, CancelToken::default(), options, Some(environment(false, 0.0))).is_err()); + } +} + +#[test] +fn hdr_anisotropic_secondary_hit_yields_before_another_debit_and_observes_cancel() { + let mut source = scene(Vec3::new(0.0, -1.0, 1.0)); + // Original planar reflector z=y, with a broad separate horizontal receiver. + let mesh = Arc::new(Mesh { + positions: vec![ + Vec3::new(-100.0, -100.0, 10.0), + Vec3::new(-100.0, 100.0, 10.0), + Vec3::new(100.0, 100.0, 10.0), + Vec3::new(100.0, -100.0, 10.0), + ], + normals: vec![-Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }); + source.bounds = source.bounds.union(&mesh.bounds()); + source.meshes.push(crate::ProductMesh { name: "Receiver".into(), mesh, color: [240, 80, 20], opacity: 1.0, surface: None, faces: Vec::new() }); + let mut request = anisotropic_request(ReflectionMode::RoughSpecular, false); + request.camera.set_view(crate::StandardView::Front); + request.width = 1; + request.height = 1; + let options = request.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new_with_environment(source, request, cancel.clone(), options, Some(environment(false, 0.0))).unwrap(); + while task.bvh.is_none() { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + let mut secondary_hit = false; + for _ in 0..200_000 { + let tracing_secondary = task.pending.as_ref().is_some_and(|p| p.bounce > 0 && p.hit.is_none()); + let before = task.work.used(); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() - before <= 1, "secondary hit completion fell through into shading"); + if tracing_secondary && task.pending.as_ref().is_some_and(|p| p.hit.is_some()) { + secondary_hit = true; + break; + } + } + assert!(secondary_hit); + let before = task.work.used(); + assert!(matches!(task.step(4).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() - before <= 4); + cancel.cancel(); + assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled); +} diff --git a/crates/render/src/raytrace/image.rs b/crates/render/src/raytrace/image.rs new file mode 100644 index 000000000..1e0affc3f --- /dev/null +++ b/crates/render/src/raytrace/image.rs @@ -0,0 +1,659 @@ +//! Opt-in opaque direct image integration; immutable world geometry, one host reservation. +use super::anisotropic_faces::{self, PlanarTarget}; +use super::bvh::TraceCursor; +use super::lighting::{DirectionalLight, Lighting, StudioPreset, map_to_display}; +use super::prepared::{PreparedPrimitive, PreparedScene}; +use super::reflection; +use super::{BuildLimits, Bvh, BvhBuilder, MAX_WORK, Ray, TraceError, Triangle, WorkBudget}; +use crate::job::{self, Admission, CancelToken, ErrorCode, ImageRequest, JobError, Phase, Progress, RaytraceOptions, TaskPoll}; +use crate::{ + ProductScene, + surface::{OpaqueSurface, srgb8_to_linear}, +}; +use solidcraft_geom::Vec3; + +#[cfg(test)] +#[path = "environment_image_tests.rs"] +mod environment_image_tests; + +#[cfg(test)] +#[path = "environment_reflection_tests.rs"] +mod environment_reflection_tests; + +#[cfg(test)] +#[path = "anisotropic_reflection_image_tests.rs"] +mod anisotropic_reflection_tests; + +fn error(e: TraceError) -> JobError { + let code = match e { + TraceError::Cancelled => ErrorCode::Cancelled, + TraceError::MemoryLimit | TraceError::WorkLimit => ErrorCode::LimitExceeded, + TraceError::AllocationFailed => ErrorCode::AllocationFailed, + TraceError::InvalidInput(_) => ErrorCode::InvalidScene, + _ => ErrorCode::Internal, + }; + JobError::new(code, e.to_string()) +} +fn invalid(message: &'static str) -> JobError { + JobError::new(ErrorCode::InvalidScene, message) +} +fn limits() -> BuildLimits { + BuildLimits { max_triangles: 262_144, max_memory_bytes: 384 * 1024 * 1024, max_work: MAX_WORK, ..Default::default() } +} +fn lighting(options: &RaytraceOptions) -> job::Result { + options.validate()?; + if let Some(preset) = options.preset { + let preset = match preset { + job::LightingPreset::Neutral => StudioPreset::Neutral, + job::LightingPreset::WarmCool => StudioPreset::WarmCool, + job::LightingPreset::KeyRim => StudioPreset::KeyRim, + }; + return Lighting::preset(preset).map_err(error); + } + match &options.lights { + None => Ok(Lighting::studio_default()), + Some(inputs) => { + let mut lights = Vec::new(); + lights.try_reserve_exact(inputs.len()).map_err(|_| error(TraceError::AllocationFailed))?; + for l in inputs { + lights.push( + DirectionalLight::new( + Vec3::new(l.direction[0], l.direction[1], l.direction[2]), + Vec3::new(l.color[0], l.color[1], l.color[2]), + l.intensity, + ) + .map_err(error)?, + ); + } + Lighting::new(lights).map_err(error) + } + } +} +type Look = PreparedPrimitive; + +pub fn admit(scene: &ProductScene, request: &ImageRequest, options: &RaytraceOptions) -> job::Result { + options.validate()?; + if let Some(original) = &request.raytrace { + original.validate()?; + } + if request.raytrace.as_ref().unwrap_or(&RaytraceOptions::default()) != options { + return Err(JobError::new(ErrorCode::InvalidRequest, "raytrace options disagree with image request")); + } + if request.integrator != job::Integrator::Raytrace { + return Err(JobError::new(ErrorCode::InvalidRequest, "raytrace task requires raytrace integrator")); + } + if request.transparent_background { + return Err(invalid("raytrace supports opaque backgrounds only")); + } + let mut a = job::image::admit_base(scene, request)?; + for body in &scene.meshes { + if body.opacity != 1.0 || body.faces.iter().any(|f| f.opacity != 1.0) { + return Err(invalid("raytrace requires opaque body and face appearances")); + } + } + if let Some(reflections) = &options.reflections { + for override_ in &reflections.bodies { + let count = scene.meshes.iter().filter(|body| body.name == override_.body).count(); + if count != 1 { + return Err(JobError::new(ErrorCode::InvalidRequest, "reflection body must resolve to exactly one captured body")); + } + } + } + anisotropic_faces::prepare(scene, options, || Ok(()))?; + let n = usize::try_from(a.triangles).map_err(|_| error(TraceError::MemoryLimit))?; + let extra = BvhBuilder::required_bytes(n, n, limits()) + .map_err(error)? + .checked_add(a.triangles.checked_mul(std::mem::size_of::() as u64).ok_or_else(|| error(TraceError::MemoryLimit))?) + .and_then(|v| { + v.checked_add(8192 + if options.reflections.is_some() || options.anisotropic_faces.iter().any(Option::is_some) { 32768 } else { 0 }) + }) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + // Keep the conservative raster pixel/codec estimate; add every new owned buffer. + a.preparation_bytes = a.preparation_bytes.checked_add(extra).ok_or_else(|| error(TraceError::MemoryLimit))?; + a.estimated_total_bytes = a.estimated_total_bytes.checked_add(extra).ok_or_else(|| error(TraceError::MemoryLimit))?; + if a.estimated_total_bytes > 384 * 1024 * 1024 { + return Err(error(TraceError::MemoryLimit)); + } + Ok(a) +} + +struct PendingPixel { + /// Proof from the primary generator, revoked for any selected reflector. + /// A jittered/time-varying primary generator MUST supply false. + repeatable_primary: bool, + environment_sample: u32, + environment_sum: Vec3, + environment_cursor: Option, + environment_value: Vec3, + ray: Ray, + cursor: TraceCursor, + hit: Option, + visibility: [bool; 8], + light: usize, + bounce: u8, + throughput: Vec3, + radiance: Vec3, +} + +pub struct ImageTask { + anisotropic_targets: [Option; 2], + environment: Option, + scene: ProductScene, + request: ImageRequest, + options: RaytraceOptions, + cancel: CancelToken, + admission: Admission, + lights: Lighting, + work: WorkBudget, + clip: (f64, f64), + triangles: Vec, + looks: Vec, + body: usize, + triangle: usize, + face_cursor: usize, + chosen: Option, + builder: Option, + bvh: Option, + build_used: u64, + pixels: Vec, + pixel: usize, + sample: u8, + pixel_radiance: Vec3, + pending: Option, + encoder: Option, + done: bool, +} +impl ImageTask { + pub fn new(scene: ProductScene, request: ImageRequest, cancel: CancelToken, options: RaytraceOptions) -> job::Result { + Self::new_with_environment(scene, request, cancel, options, None) + } + pub fn new_with_environment( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + input: Option, + ) -> job::Result { + cancel.check()?; + let mut admission = admit(&scene, &request, &options)?; + if input.is_some() { + options.validate_environment_reflections(&scene)?; + } + let extra = input.as_ref().map_or(Ok(0), |e| e.required_bytes()).map_err(environment_error)?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(extra) + .filter(|v| *v <= job::image::MAX_JOB_BYTES) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + admission.preparation_bytes = admission.preparation_bytes.checked_add(extra).ok_or_else(|| error(TraceError::MemoryLimit))?; + let environment = input.map(|e| e.begin()).transpose().map_err(environment_error)?; + let lights = lighting(&options)?; + let mut work = WorkBudget::new(MAX_WORK).map_err(error)?; + let anisotropic_targets = anisotropic_faces::prepare(&scene, &options, || work.tick(&cancel).map_err(error))?; + let radius = + if scene.meshes.is_empty() { 10.0 } else { scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(request.camera.target) }; + if !radius.is_finite() { + return Err(invalid("invalid product bounds")); + } + let clip = request.camera.clip(radius); + let mut triangles = Vec::new(); + let mut looks = Vec::new(); + let mut pixels = Vec::new(); + triangles.try_reserve_exact(admission.triangles as usize).map_err(|_| error(TraceError::AllocationFailed))?; + looks.try_reserve_exact(admission.triangles as usize).map_err(|_| error(TraceError::AllocationFailed))?; + pixels.try_reserve_exact(request.width as usize * request.height as usize * 4).map_err(|_| error(TraceError::AllocationFailed))?; + // Allocator capacities are checked, not assumed equal to requested capacities. + let actual = BvhBuilder::required_bytes(admission.triangles as usize, triangles.capacity(), limits()).map_err(error)?; + if actual != BvhBuilder::required_bytes(admission.triangles as usize, admission.triangles as usize, limits()).map_err(error)? + || looks.capacity() != admission.triangles as usize + || pixels.capacity() != request.width as usize * request.height as usize * 4 + { + return Err(error(TraceError::MemoryLimit)); + } + Ok(Self { + anisotropic_targets, + environment, + scene, + request, + options, + cancel, + admission, + lights, + clip, + work, + triangles, + looks, + body: 0, + triangle: 0, + face_cursor: 0, + chosen: None, + builder: None, + bvh: None, + build_used: 0, + pixels, + pixel: 0, + sample: 0, + pixel_radiance: Vec3::ZERO, + pending: None, + encoder: None, + done: false, + }) + } + pub fn progress(&self) -> Progress { + let (phase, done, total) = if self.done { + (Phase::Completed, 1, 1) + } else if let Some(e) = &self.encoder { + (Phase::Encoding, e.row() as u64, self.request.height as u64) + } else if self.bvh.is_some() { + (Phase::Running, self.pixel as u64, self.request.width as u64 * self.request.height as u64) + } else { + (Phase::Preparing, self.triangles.len() as u64, self.admission.triangles) + }; + Progress { phase, done, total } + } + fn prepare_one(&mut self) -> job::Result<()> { + self.work.tick(&self.cancel).map_err(error)?; + let Some(body) = self.scene.meshes.get(self.body) else { + let triangles = std::mem::take(&mut self.triangles); + let expected = BvhBuilder::required_bytes(triangles.len(), triangles.capacity(), limits()).map_err(error)?; + let builder = BvhBuilder::new(triangles, limits(), &self.cancel).map_err(error)?; + if builder.admitted_bytes() > expected { + return Err(error(TraceError::MemoryLimit)); + } + self.builder = Some(builder); + return Ok(()); + }; + let Some(indices) = body.mesh.triangles.get(self.triangle) else { + self.body += 1; + self.triangle = 0; + return Ok(()); + }; + let mut vertices = [Vec3::ZERO; 3]; + let mut normals = [Vec3::ZERO; 3]; + for ((p, n), i) in vertices.iter_mut().zip(normals.iter_mut()).zip(indices) { + *p = *body.mesh.positions.get(*i as usize).ok_or_else(|| invalid("triangle vertex index"))?; + *n = body.mesh.normals.get(*i as usize).copied().unwrap_or(Vec3::ZERO); + } + let face = body.mesh.tri_face.get(self.triangle).copied(); + let mut color = body.color; + let mut surface = body.surface; + if let Some(look) = body.faces.get(self.face_cursor) { + self.face_cursor += 1; + if Some(look.face) == face { + self.chosen = Some(look.clone()); + self.face_cursor = body.faces.len(); + } else { + return Ok(()); + } + } + if let Some(look) = self.chosen.take() { + color = look.color; + surface = look.surface; + } + self.face_cursor = 0; + let surface = match surface { + Some(s) => s, + None => OpaqueSurface::new(Vec3::new(srgb8_to_linear(color[0]), srgb8_to_linear(color[1]), srgb8_to_linear(color[2])), 0.0, 0.7, 1.5) + .map_err(|_| invalid("invalid scalar surface"))?, + }; + self.triangles.push(Triangle::new(vertices).map_err(error)?); + self.looks.push(Look { body_index: self.body, face, surface, normals, vertices }); + self.triangle += 1; + Ok(()) + } + fn sample_count(&self) -> u8 { + self.options.reflections.as_ref().filter(|r| !r.bodies.is_empty()).map_or(1, |r| r.samples) + } + fn finish_sample(&mut self, radiance: Vec3) -> job::Result<()> { + // Only the current fixed-centre, nonselected primary path is identical + // across reflection samples: directional inputs and the environment's + // fixed u-grid do not depend on self.sample, and this path never bounces. + // Secondary nonselected hits and selected null samples still require R. + let repeats = + if self.sample == 0 && self.pending.as_ref().is_some_and(|p| p.repeatable_primary && p.bounce == 0) { self.sample_count() } else { 1 }; + // Reuse the shading result, but retain the original addition order, + // per-add bound and final divisor exactly. At most64 scalar additions, + // no repeated BVH/BSDF/environment work or new allocation/work budget. + for _ in 0..repeats { + self.pixel_radiance += radiance; + if !self.pixel_radiance.is_finite() + || [self.pixel_radiance.x, self.pixel_radiance.y, self.pixel_radiance.z].into_iter().any(|v| v < 0.0 || v > 1e12) + { + return Err(invalid("reflection radiance exceeds finite transport bound")); + } + self.sample += 1; + } + self.pending = None; + if self.sample == self.sample_count() { + let display = map_to_display(self.pixel_radiance / self.sample as f64, self.options.exposure_ev).map_err(error)?; + self.pixels.extend_from_slice(&[encode(display.x), encode(display.y), encode(display.z), 255]); + self.pixel += 1; + self.sample = 0; + self.pixel_radiance = Vec3::ZERO; + } + Ok(()) + } + fn pixel_one(&mut self) -> job::Result<()> { + let bvh = self.bvh.as_ref().ok_or_else(|| invalid("missing image BVH"))?; + if self.pending.is_none() { + self.work.tick(&self.cancel).map_err(error)?; + let width = self.request.width as usize; + // This proof bit belongs to this fixed-centre generator, not to the + // camera or request globally. Future jitter/AA must return false. + let (ray, repeatable_primary) = + (primary_ray(&self.request, (self.pixel % width) as f64 + 0.5, (self.pixel / width) as f64 + 0.5, self.clip).map_err(error)?, true); + self.pending = Some(PendingPixel { + repeatable_primary, + environment_sample: 0, + environment_sum: Vec3::ZERO, + environment_cursor: None, + environment_value: Vec3::ZERO, + ray, + cursor: TraceCursor::new(ray, false), + hit: None, + visibility: [true; 8], + light: 0, + bounce: 0, + throughput: Vec3::new(1.0, 1.0, 1.0), + radiance: Vec3::ZERO, + }); + return Ok(()); + } + let scene = PreparedScene { bvh, primitives: &self.looks, source: &self.scene }; + let pending = self.pending.as_mut().ok_or_else(|| invalid("missing pixel state"))?; + if pending.hit.is_none() { + let Some(hit) = pending.cursor.step(bvh, &mut self.work, &self.cancel).map_err(error)? else { + return Ok(()); + }; + let Some(hit) = hit else { + if pending.bounce == 0 { + let [r, g, b] = self.request.background; + self.pixels.extend_from_slice(&[r, g, b, 255]); + self.pixel += 1; + self.sample = 0; + self.pixel_radiance = Vec3::ZERO; + self.pending = None; + return Ok(()); + } + if let Some(environment) = &self.environment { + let emitted = + environment.view().map_err(environment_error)?.radiance_linear_srgb(pending.ray.direction()).map_err(environment_error)?; + pending.radiance += multiply(pending.throughput, emitted); + } + let radiance = pending.radiance; + return self.finish_sample(radiance); + }; + pending.hit = Some(hit); + pending.light = 0; + let shared = scene.resolve_hit(pending.ray, hit).map_err(error)?; + let mode = + self.options.reflections.as_ref().and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + pending.repeatable_primary &= pending.bounce == 0 && mode.is_none(); + if self.options.shadows && !self.lights.lights().is_empty() && mode != Some(job::ReflectionMode::Mirror) { + let light = self.lights.lights().first().ok_or_else(|| invalid("missing first light"))?; + pending.cursor = TraceCursor::new(shared.spawn(light.direction()).map_err(error)?, true); + return Ok(()); + } + pending.light = self.lights.lights().len(); + return Ok(()); + } else if pending.light < self.lights.lights().len() { + let Some(shadow) = pending.cursor.step(bvh, &mut self.work, &self.cancel).map_err(error)? else { + return Ok(()); + }; + *pending.visibility.get_mut(pending.light).ok_or_else(|| invalid("light visibility index"))? = shadow.is_none(); + pending.light += 1; + if let Some(light) = self.lights.lights().get(pending.light) { + let shared = scene.resolve_hit(pending.ray, pending.hit.ok_or_else(|| invalid("missing shadow hit"))?).map_err(error)?; + pending.cursor = TraceCursor::new(shared.spawn(light.direction()).map_err(error)?, true); + return Ok(()); + } + return Ok(()); + } + if let Some(cursor) = &mut pending.environment_cursor { + let Some(blocker) = cursor.step(bvh, &mut self.work, &self.cancel).map_err(error)? else { + return Ok(()); + }; + if blocker.is_none() { + pending.environment_sum += pending.environment_value; + } + pending.environment_cursor = None; + pending.environment_sample += 1; + return Ok(()); + } + if pending.light == self.lights.lights().len() { + self.work.tick(&self.cancel).map_err(error)?; + let shared = scene.resolve_hit(pending.ray, pending.hit.ok_or_else(|| invalid("missing shading hit"))?).map_err(error)?; + let mode = + self.options.reflections.as_ref().and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + let view = -pending.ray.direction(); + let geometric = shared.oriented_geometric_normal(); + // Disjoint estimators: selected reflectors use BSDF transport to the environment; + // only nonselected opaque hits use environment next-event estimates. + if mode.is_none() + && let Some(environment) = &self.environment + { + if pending.environment_sample < environment.samples { + let side = match environment.samples { + 1 => 1, + 4 => 2, + 16 => 4, + _ => 8, + }; + let i = pending.environment_sample; + let u = if side == 1 { + [0.25, 0.375] + } else { + [(f64::from(i / side) + 0.5) / f64::from(side), (f64::from(i % side) + 0.5) / f64::from(side)] + }; + let sample = environment + .view() + .map_err(environment_error)? + .direct_sample_linear_srgb(u, shared.surface, shared.shading_normal, geometric, view) + .map_err(environment_error)?; + pending.environment_value = sample.contribution_linear_srgb; + if self.options.shadows && sample.contribution_linear_srgb.len2() > 0.0 { + pending.environment_cursor = Some(TraceCursor::new(shared.spawn(sample.direction).map_err(error)?, true)); + } else { + pending.environment_sum += pending.environment_value; + pending.environment_sample += 1; + } + return Ok(()); + } + pending.radiance += multiply(pending.throughput, pending.environment_sum / f64::from(environment.samples)); + } + let face = self.looks.get(shared.primitive_index).ok_or_else(|| invalid("missing captured face"))?.face; + let target_index = anisotropic_faces::target_index(&self.options, shared.body_index, face); + if mode != Some(job::ReflectionMode::Mirror) { + let visible = |index: usize, light: Vec3| { + Ok(geometric.dot(light) > 0.0 && *pending.visibility.get(index).ok_or(TraceError::Internal("light visibility"))?) + }; + let direct = if let Some(index) = target_index { + self.anisotropic_targets + .get(index) + .copied() + .flatten() + .ok_or_else(|| invalid("missing certified anisotropic face"))? + .shade(&self.lights, shared.surface, geometric, view, visible) + .map_err(error)? + } else { + self.lights.shade_linear(shared.surface, shared.shading_normal, view, visible).map_err(error)? + }; + pending.radiance += multiply(pending.throughput, direct); + } + let max_bounces = self.options.reflections.as_ref().map_or(0, |r| r.max_bounces); + if let Some(mode) = mode.filter(|_| pending.bounce < max_bounces) { + let samples = self.options.reflections.as_ref().map_or(1, |r| u64::from(r.samples)); + let u = reflection::variates(self.pixel as u64, self.sample as u64, pending.bounce as u64, samples).map_err(error)?; + let sampled = match (mode, target_index) { + (job::ReflectionMode::Mirror, _) => reflection::mirror(shared.surface, shared.shading_normal, view), + (job::ReflectionMode::RoughSpecular, Some(index)) => self + .anisotropic_targets + .get(index) + .copied() + .flatten() + .ok_or_else(|| invalid("missing anisotropic reflection target"))? + .sample(shared.surface, geometric, view, u), + (job::ReflectionMode::RoughSpecular, None) => reflection::rough_specular(shared.surface, shared.shading_normal, view, u), + } + .map_err(error)?; + if let Some(sample) = sampled.filter(|s| s.direction.dot(geometric) > 0.0) { + pending.throughput = multiply(pending.throughput, sample.weight); + if !pending.throughput.is_finite() { + return Err(invalid("nonfinite reflection throughput")); + } + if pending.throughput.len2() > 0.0 { + pending.ray = shared.spawn(sample.direction).map_err(error)?; + pending.cursor = TraceCursor::new(pending.ray, false); + pending.hit = None; + pending.light = 0; + pending.visibility = [true; 8]; + pending.environment_sample = 0; + pending.environment_sum = Vec3::ZERO; + pending.environment_cursor = None; + pending.environment_value = Vec3::ZERO; + pending.bounce += 1; + return Ok(()); + } + } + } + let radiance = pending.radiance; + return self.finish_sample(radiance); + } + Ok(()) + } + pub fn step(&mut self, units: usize) -> job::Result { + self.cancel.check()?; + if units == 0 || units > 16384 || self.done { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid raytrace step or completed task")); + } + for _ in 0..units.min(4) { + if let Some(encoder) = &mut self.encoder { + if let Some(png) = encoder.step(&self.pixels)? { + self.cancel.check()?; + self.done = true; + self.anisotropic_targets = [None, None]; + self.options.anisotropic_faces = [None, None]; + self.environment = None; + self.scene.meshes = Vec::new(); + self.looks = Vec::new(); + self.bvh = None; + self.builder = None; + self.triangles = Vec::new(); + self.pixels = Vec::new(); + self.pending = None; + self.request.raytrace = None; + self.options.lights = None; + self.options.reflections = None; + self.lights = Lighting::new(Vec::new()).map_err(error)?; + self.encoder = None; + return Ok(TaskPoll::Complete(png)); + } + } else if self.environment.as_ref().is_some_and(|e| !e.ready()) { + self.work.tick(&self.cancel).map_err(error)?; + self.environment + .as_mut() + .ok_or_else(|| invalid("missing environment preparation"))? + .prepare_one(|| self.cancel.is_cancelled()) + .map_err(environment_error)?; + } else if self.bvh.is_some() { + if self.pixel == self.request.width as usize * self.request.height as usize { + self.encoder = Some(job::encoding::PngEncoding::new( + self.request.width, + self.request.height, + self.admission.encoded_limit, + self.cancel.clone(), + )?); + } else { + self.pixel_one()?; + } + } else if let Some(builder) = &mut self.builder { + let progress = builder.step(1, &self.cancel).map_err(error)?; + for _ in self.build_used..progress.work_used { + self.work.tick(&self.cancel).map_err(error)?; + } + self.build_used = progress.work_used; + if progress.complete { + self.bvh = Some(self.builder.take().ok_or_else(|| invalid("missing builder"))?.finish().map_err(error)?); + } + } else { + self.prepare_one()?; + } + } + Ok(TaskPoll::Pending(self.progress())) + } +} +fn multiply(a: Vec3, b: Vec3) -> Vec3 { + Vec3::new(a.x * b.x, a.y * b.y, a.z * b.z) +} +fn encode(c: f64) -> u8 { + let s = if c <= 0.0031308 { 12.92 * c } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 }; + (s.clamp(0.0, 1.0) * 255.0).round() as u8 +} + +#[cfg(test)] +fn shadow_ray(ray: Ray, hit: super::Hit, light: Vec3, vertices: [Vec3; 3]) -> super::Result { + let mut n = hit.geometry.geometric_normal; + if n.dot(light) < 0.0 { + n = -n; + } + let [a, b, c] = hit.geometry.barycentric; + let [va, vb, vc] = vertices; + // Reconstruct from captured vertices, not a distant camera. Component-wise + // rounding bounds avoid an unrelated large X translation displacing a Z plane. + let p = va * a + vb * b + vc * c; + let magnitude = |x: f64, y: f64, z: f64| x.abs() * a.abs() + y.abs() * b.abs() + z.abs() * c.abs(); + let e = Vec3::new(magnitude(va.x, vb.x, vc.x), magnitude(va.y, vb.y, vc.y), magnitude(va.z, vb.z, vc.z)) * (8.0 * f64::EPSILON); + let distance = n.x.abs() * e.x + n.y.abs() * e.y + n.z.abs() * e.z; + let shifted = p + n * distance; + let outward = |v: f64, n: f64| { + if n > 0.0 { + v.next_up() + } else if n < 0.0 { + v.next_down() + } else { + v + } + }; + let _ = ray; // hit position comes from geometry, independent of camera distance. + Ray::new(Vec3::new(outward(shifted.x, n.x), outward(shifted.y, n.y), outward(shifted.z, n.z)), light, 0.0_f64.next_up(), super::MAX_DISTANCE_MM) +} + +fn primary_ray(request: &ImageRequest, x: f64, y: f64, clip: (f64, f64)) -> super::Result { + let camera = &request.camera; + let (mut origin, direction) = camera.ray(x, y, request.width as f64, request.height as f64); + if camera.fov == 0.0 { + origin -= camera.back() * (camera.distance * 3.0); + } + let forward = -camera.back(); + let cosine = direction.dot(forward); + if !cosine.is_finite() || cosine <= 0.0 { + return Err(TraceError::InvalidInput("camera ray direction")); + } + let depth = (origin - camera.eye()).dot(forward); + let start = (clip.0 - depth) / cosine; + let length = (clip.1 - clip.0) / cosine; + Ray::new(origin + direction * start, direction, 0.0, length) +} + +#[cfg(test)] +#[path = "image_tests.rs"] +mod tests; + +#[cfg(test)] +#[path = "deterministic_primary_tests.rs"] +mod deterministic_primary_tests; + +#[cfg(test)] +#[path = "reflection_image_tests.rs"] +mod reflection_tests; + +fn environment_error(e: crate::lighting::HdrError) -> JobError { + use crate::lighting::HdrErrorCode; + let code = match e.code { + HdrErrorCode::Cancelled => ErrorCode::Cancelled, + HdrErrorCode::LimitExceeded => ErrorCode::LimitExceeded, + HdrErrorCode::AllocationFailed => ErrorCode::AllocationFailed, + _ => ErrorCode::InvalidRequest, + }; + JobError::new(code, e.to_string()) +} diff --git a/crates/render/src/raytrace/image_tests.rs b/crates/render/src/raytrace/image_tests.rs new file mode 100644 index 000000000..0b334e8fd --- /dev/null +++ b/crates/render/src/raytrace/image_tests.rs @@ -0,0 +1,253 @@ +use super::*; +use solidcraft_geom::Aabb3; +fn request() -> ImageRequest { + ImageRequest { + integrator: job::Integrator::Raytrace, + raytrace: None, + camera: Default::default(), + width: 8, + height: 8, + background: [10, 20, 30], + transparent_background: false, + } +} +#[test] +fn image_work_exhaustion_is_typed_and_never_publishes_partial_png() { + let mut task = + ImageTask::new(ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }, request(), CancelToken::default(), Default::default()).unwrap(); + task.work = WorkBudget::new(2).unwrap(); + let mut previous = 0; + for _ in 0..20 { + match task.step(1) { + Ok(TaskPoll::Pending(_)) => { + assert!(task.work.used() >= previous); + previous = task.work.used(); + } + Ok(TaskPoll::Complete(_)) => panic!("exhausted task published a frame"), + Err(e) => { + assert_eq!(e.code, ErrorCode::LimitExceeded); + assert_eq!(task.work.used(), 2); + return; + } + } + } + panic!("tiny budget did not stop image"); +} +#[test] +fn thin_shadow_occluder_survives_large_unrelated_translation() { + for x in [0.0, 1.0e12 - 100.0] { + let vertices = [Vec3::new(x, 0.0, 0.0), Vec3::new(x + 20.0, 0.0, 0.0), Vec3::new(x, 20.0, 0.0)]; + let receiver = Triangle::new(vertices).unwrap(); + let primary = Ray::new(Vec3::new(x + 5.0, 5.0, 10.0), -Vec3::Z, 0.0, 20.0).unwrap(); + let geometry = receiver.intersect(&primary).unwrap(); + let shadow = shadow_ray(primary, super::super::Hit { primitive_index: 0, geometry }, Vec3::Z, vertices).unwrap(); + assert!(shadow.interval()[0] > 0.0, "secondary rays exclude signed-zero distance after underflow"); + assert!(receiver.intersect(&shadow).is_none(), "self-shadow at translation {x}"); + let occluder = Triangle::new(vertices.map(|v| v + Vec3::Z * 0.005)).unwrap(); + assert!(occluder.intersect(&shadow).is_some(), "thin blocker was skipped at translation {x}"); + } +} +#[test] +fn primary_intervals_follow_camera_clip_planes_for_both_projections_and_up_axes() { + for fov in [0.0, 0.7] { + for up in [crate::UpAxis::Z, crate::UpAxis::Y] { + let mut request = request(); + request.camera.fov = fov; + request.camera.up = up; + let clip = request.camera.clip(20.0); + let ray = primary_ray(&request, 4.0, 4.0, clip).unwrap(); + let forward = -request.camera.back(); + let near_depth = (ray.origin() - request.camera.eye()).dot(forward); + let far_depth = (ray.at(ray.interval()[1]).unwrap() - request.camera.eye()).dot(forward); + assert!((near_depth - clip.0).abs() < 1e-9); + assert!((far_depth - clip.1).abs() < 1e-9); + } + } +} +#[test] +fn resumable_cursor_matches_original_visibility_and_charges_each_unit() { + let cancel = CancelToken::default(); + let triangle = Triangle::new([Vec3::ZERO, Vec3::X, Vec3::Y]).unwrap(); + let mut builder = BvhBuilder::new(vec![triangle], limits(), &cancel).unwrap(); + while !builder.step(1, &cancel).unwrap().complete {} + let bvh = builder.finish().unwrap(); + let ray = Ray::new(Vec3::new(0.2, 0.2, 1.0), -Vec3::Z, 0.0, 2.0).unwrap(); + let expected = bvh.closest_hit(&ray, &mut WorkBudget::new(100).unwrap(), &cancel).unwrap(); + let mut cursor = TraceCursor::new(ray, false); + let mut work = WorkBudget::new(100).unwrap(); + for _ in 0..100 { + let before = work.used(); + let result = cursor.step(&bvh, &mut work, &cancel).unwrap(); + assert_eq!(work.used(), before + 1); + if let Some(actual) = result { + assert_eq!(actual, expected); + return; + } + } + panic!("cursor failed to finish"); +} +#[test] +fn actual_png_has_analytic_lit_and_cast_shadow_pixels() { + use crate::ProductMesh; + use solidcraft_geom::Mesh; + use std::sync::Arc; + fn plane(z: f64, x0: f64, x1: f64) -> ProductMesh { + let mesh = Mesh { + positions: vec![Vec3::new(x0, -10.0, z), Vec3::new(x1, -10.0, z), Vec3::new(x1, 10.0, z), Vec3::new(x0, 10.0, z)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }; + ProductMesh { + name: format!("plane {z}"), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap()), + faces: Vec::new(), + } + } + let meshes = vec![plane(0.0, -20.0, 20.0), plane(5.0, -5.0, 5.0)]; + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let scene = ProductScene { meshes, bounds }; + let mut request = request(); + request.width = 40; + request.height = 40; + request.camera.distance = 50.0; + request.camera.set_view(crate::StandardView::Top); + let options = RaytraceOptions { + lights: Some(vec![job::DirectionalLightOptions { direction: [-1.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }]), + ..Default::default() + }; + fn render(scene: ProductScene, mut request: ImageRequest, options: RaytraceOptions) -> ::image::RgbaImage { + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return ::image::load_from_memory(&png).unwrap().to_rgba8(); + } + } + panic!("small analytic render did not complete"); + } + let shadowed = render(scene.clone(), request.clone(), options.clone()); + let lit = render(scene, request, RaytraceOptions { shadows: false, ..options }); + // Top view: screen x maps world x, width40 spans[-20,20]. Blocker[-5,5] + // at z5 casts a footprint[0,10] for the light toward(-1,0,+1). + let shadow = shadowed.get_pixel(27, 20).0; + let unshadowed = lit.get_pixel(27, 20).0; + assert_eq!(shadow, [0, 0, 0, 255]); + // White fully rough conductor: F=1, D=1/pi, Smith visibility + // at normal view yields BRDF=1/[2*pi*(1+cosL)]. + let cosine = (0.5_f64).sqrt(); + let radiance = cosine / (2.0 * std::f64::consts::PI * (1.0 + cosine)); + let expected = encode(radiance / (1.0 + radiance)); + assert_eq!(unshadowed, [expected, expected, expected, 255]); + assert_eq!(shadowed.get_pixel(7, 20), lit.get_pixel(7, 20), "unoccluded receiver changes when toggling shadows"); +} +fn triangle_task(cancel: CancelToken) -> ImageTask { + use std::sync::Arc; + let mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(-20.0, -20.0, 0.0), Vec3::new(20.0, -20.0, 0.0), Vec3::new(0.0, 20.0, 0.0)], + normals: vec![Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { + name: "work fixture".into(), + mesh: Arc::new(mesh), + color: [220; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }], + bounds, + }; + let mut request = request(); + request.camera.distance = 50.0; + request.camera.set_view(crate::StandardView::Top); + ImageTask::new(scene, request, cancel, Default::default()).unwrap() +} +#[test] +fn build_primary_and_shadows_share_cumulative_work_and_exhaust_atomically() { + let mut task = triangle_task(CancelToken::default()); + let mut previous = 0; + let mut built = false; + for _ in 0..10_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() >= previous); + previous = task.work.used(); + built |= task.builder.is_some(); + if task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.light < task.lights.lights().len()) { + assert!(built); + assert!(task.build_used > 0); + assert!(task.work.used() > task.build_used); + task.work.limit = task.work.used() + 1; + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + return; + } + } + panic!("triangle fixture never reached shadow traversal"); +} +#[test] +fn cancellation_is_observed_in_every_ray_image_phase() { + for phase in 0..5 { + let cancel = CancelToken::default(); + let mut task = triangle_task(cancel.clone()); + let mut reached = false; + for _ in 0..100_000 { + let current = match phase { + 0 => task.builder.is_none() && task.bvh.is_none(), + 1 => task.builder.is_some(), + 2 => task.pending.as_ref().is_some_and(|p| p.hit.is_none()), + 3 => task.pending.as_ref().is_some_and(|p| p.hit.is_some()), + _ => task.encoder.is_some(), + }; + if current { + reached = true; + break; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + assert!(reached, "phase {phase}"); + cancel.cancel(); + assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled); + } +} +#[test] +fn runtime_presets_reach_the_lighting_consumer() { + for (runtime, expected) in [ + (job::LightingPreset::Neutral, StudioPreset::Neutral), + (job::LightingPreset::WarmCool, StudioPreset::WarmCool), + (job::LightingPreset::KeyRim, StudioPreset::KeyRim), + ] { + let options = RaytraceOptions { preset: Some(runtime), ..Default::default() }; + assert_eq!(lighting(&options).unwrap(), Lighting::preset(expected).unwrap()); + } + let conflict = RaytraceOptions { preset: Some(job::LightingPreset::Neutral), lights: Some(Vec::new()), ..Default::default() }; + assert_eq!(lighting(&conflict).err().unwrap().code, ErrorCode::InvalidRequest); +} +#[test] +fn warm_cool_preset_changes_actual_triangle_png() { + fn render(preset: job::LightingPreset) -> Vec { + let initial = triangle_task(CancelToken::default()); + let options = RaytraceOptions { preset: Some(preset), ..Default::default() }; + let mut request = initial.request.clone(); + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(initial.scene.clone(), request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let TaskPoll::Complete(bytes) = task.step(16384).unwrap() { + return bytes; + } + } + panic!("preset render did not complete"); + } + let neutral = ::image::load_from_memory(&render(job::LightingPreset::Neutral)).unwrap().to_rgba8(); + let warm = ::image::load_from_memory(&render(job::LightingPreset::WarmCool)).unwrap().to_rgba8(); + assert_ne!(neutral.get_pixel(4, 4), warm.get_pixel(4, 4)); + assert_eq!(neutral.get_pixel(0, 0), warm.get_pixel(0, 0), "background must remain independent of lighting preset"); +} diff --git a/crates/render/src/raytrace/lighting.rs b/crates/render/src/raytrace/lighting.rs new file mode 100644 index 000000000..dadc9e222 --- /dev/null +++ b/crates/render/src/raytrace/lighting.rs @@ -0,0 +1,161 @@ +//! Bounded direct lighting for RT2. World directions point from a hit towards each light. +//! Colours are linear sRGB; intensity is relative radiance, not watts or illuminance. +//! Visibility is supplied separately for every light by the ray-tracing consumer. + +use solidcraft_geom::Vec3; + +use crate::surface::{OpaqueSurface, unit_direction}; + +use super::{Result, TraceError}; + +pub const MAX_LIGHTS: usize = 8; +pub const MAX_LIGHT_INTENSITY: f64 = 64.0; +/// Refuse unrepresentable or excessive output rather than silently clip the transport. +pub const MAX_LINEAR_RADIANCE: f64 = 1.0e12; +pub const MAX_EXPOSURE_EV: f64 = 16.0; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DirectionalLight { + direction: Vec3, + color: Vec3, + intensity: f64, +} + +impl DirectionalLight { + pub fn new(direction: Vec3, linear_color: Vec3, intensity: f64) -> Result { + let direction = unit_direction(direction).map_err(|_| TraceError::InvalidInput("finite nonzero light direction required"))?; + if !linear_color.is_finite() || !channels(linear_color).into_iter().all(|c| (0.0..=1.0).contains(&c)) { + return Err(TraceError::InvalidInput("light colour must be finite linear sRGB in [0, 1]")); + } + if !intensity.is_finite() || !(0.0..=MAX_LIGHT_INTENSITY).contains(&intensity) { + return Err(TraceError::InvalidInput("light intensity must be finite relative radiance in [0, 64]")); + } + Ok(Self { direction, color: linear_color, intensity }) + } + + pub fn direction(self) -> Vec3 { + self.direction + } + + pub fn color(self) -> Vec3 { + self.color + } + + pub fn intensity(self) -> f64 { + self.intensity + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StudioPreset { + /// The existing three neutral lights, with unchanged directions and intensities. + Neutral, + /// Original warm key / cool fill colour composition, without a Kelvin claim. + WarmCool, + /// Original opposing key / rim composition. These are hard directional lights. + KeyRim, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Lighting { + lights: Vec, +} + +impl Default for Lighting { + fn default() -> Self { + Self::studio_default() + } +} + +impl Lighting { + pub fn new(lights: Vec) -> Result { + if lights.len() > MAX_LIGHTS || lights.capacity() > MAX_LIGHTS { + return Err(TraceError::InvalidInput("RT2 admits at most eight directional lights and eight reserved light slots")); + } + // An empty list deliberately means no direct illumination. + Ok(Self { lights }) + } + + pub fn studio_default() -> Self { + Self { + lights: crate::studio::LIGHTS + .into_iter() + .map(|(direction, intensity)| DirectionalLight { direction, color: Vec3::new(1.0, 1.0, 1.0), intensity }) + .collect(), + } + } + + pub fn preset(preset: StudioPreset) -> Result { + match preset { + StudioPreset::Neutral => Ok(Self::studio_default()), + StudioPreset::WarmCool => Self::new(vec![ + DirectionalLight::new(Vec3::new(0.6, 0.0, 0.8), Vec3::new(1.0, 0.72, 0.48), 3.0)?, + DirectionalLight::new(Vec3::new(-0.8, 0.0, 0.6), Vec3::new(0.45, 0.65, 1.0), 1.0)?, + DirectionalLight::new(Vec3::new(0.0, -0.6, 0.8), Vec3::new(1.0, 1.0, 1.0), 1.5)?, + ]), + StudioPreset::KeyRim => Self::new(vec![ + DirectionalLight::new(Vec3::new(0.6, -0.4, 0.8), Vec3::new(1.0, 1.0, 1.0), 3.0)?, + DirectionalLight::new(Vec3::new(-0.6, 0.4, 0.8), Vec3::new(0.6, 0.8, 1.0), 2.0)?, + ]), + } + } + + pub fn lights(&self) -> &[DirectionalLight] { + &self.lights + } + + /// Sum BRDF * cosine * incident colour/intensity for independently visible lights. + /// `visible` returns true for an unobstructed shadow ray; its errors propagate. + /// No ambient term, exposure, tone map, display encoding or indirect bounce occurs here. + pub fn shade_linear( + &self, + surface: OpaqueSurface, + normal: Vec3, + view: Vec3, + mut visible: impl FnMut(usize, Vec3) -> Result, + ) -> Result { + let n = unit_direction(normal).map_err(|_| TraceError::InvalidInput("finite nonzero shading normal required"))?; + let v = unit_direction(view).map_err(|_| TraceError::InvalidInput("finite nonzero shading view required"))?; + let mut sum = Vec3::ZERO; + if n.dot(v) <= 0.0 { + return Ok(sum); + } + for (index, light) in self.lights.iter().enumerate() { + let cosine = n.dot(light.direction).max(0.0); + if cosine == 0.0 || light.intensity == 0.0 || light.color == Vec3::ZERO || !visible(index, light.direction)? { + continue; + } + let brdf = surface.brdf(n, v, light.direction).map_err(|_| TraceError::InvalidInput("invalid opaque surface lighting directions"))?; + let weight = light.intensity * cosine; + sum += Vec3::new(brdf.x * light.color.x, brdf.y * light.color.y, brdf.z * light.color.z) * weight; + validate_radiance(sum)?; + } + Ok(sum) + } +} + +fn channels(v: Vec3) -> [f64; 3] { + [v.x, v.y, v.z] +} + +fn validate_radiance(radiance: Vec3) -> Result<()> { + if !radiance.is_finite() || !channels(radiance).into_iter().all(|c| (0.0..=MAX_LINEAR_RADIANCE).contains(&c)) { + return Err(TraceError::InvalidInput("RT2 linear radiance must be finite and in [0, 1e12]")); + } + Ok(()) +} + +/// The output boundary applies exposure once, then Reinhard once. The returned value +/// is still linear sRGB: the image consumer must encode sRGB exactly once afterwards. +/// Call this once after summing all direct lighting, never once per light. +pub fn map_to_display(radiance: Vec3, exposure_ev: f64) -> Result { + validate_radiance(radiance)?; + if !exposure_ev.is_finite() || !(-MAX_EXPOSURE_EV..=MAX_EXPOSURE_EV).contains(&exposure_ev) { + return Err(TraceError::InvalidInput("RT2 exposure must be finite and in [-16, 16] EV")); + } + crate::studio::tone_map(radiance * exposure_ev.exp2()).map_err(|_| TraceError::InvalidInput("invalid exposed radiance")) +} + +#[cfg(test)] +#[path = "lighting_tests.rs"] +mod tests; diff --git a/crates/render/src/raytrace/lighting_tests.rs b/crates/render/src/raytrace/lighting_tests.rs new file mode 100644 index 000000000..246ec57d7 --- /dev/null +++ b/crates/render/src/raytrace/lighting_tests.rs @@ -0,0 +1,134 @@ +use super::*; +use std::f64::consts::PI; + +fn lambert() -> OpaqueSurface { + // At normal incidence IOR 1 gives f = base_colour / pi exactly. + OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.25), 0.0, 1.0, 1.0).unwrap() +} + +#[test] +fn analytic_lambert_separates_linear_colour_intensity_and_cosine() { + let light = DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 0.5, 0.25), 2.0).unwrap(); + let lights = Lighting::new(vec![light]).unwrap(); + let actual = lights.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap(); + let expected = Vec3::new(0.8, 0.25, 0.0625) * (2.0 / PI); + assert!((actual - expected).len() < 1e-14); + let twice = Lighting::new(vec![DirectionalLight::new(light.direction(), light.color(), 4.0).unwrap()]).unwrap(); + assert!((twice.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap() - actual * 2.0).len() < 1e-14); + // White, fully rough conductor has f = 1 / (2*pi*(1+cos(theta))) + // at a normal view. This independently checks the incident cosine. + let conductor = OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap(); + let angled = Lighting::new(vec![DirectionalLight::new(Vec3::new(0.6, 0.0, 0.8), light.color(), 2.0).unwrap()]).unwrap(); + let actual = angled.shade_linear(conductor, Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap(); + assert!((actual - light.color() * (0.8 / (1.8 * PI))).len() < 1e-14); +} + +#[test] +fn shadow_visibility_is_independent_for_each_coloured_light() { + let lights = Lighting::new(vec![ + DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 0.0, 0.0), 2.0).unwrap(), + DirectionalLight::new(Vec3::Z, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap(), + ]) + .unwrap(); + let mut visited = Vec::new(); + let blue = lights + .shade_linear(lambert(), Vec3::Z, Vec3::Z, |i, direction| { + visited.push((i, direction)); + Ok(i == 1) + }) + .unwrap(); + assert_eq!(visited, vec![(0, Vec3::Z), (1, Vec3::Z)]); + assert!((blue - Vec3::new(0.0, 0.0, 0.75 / PI)).len() < 1e-14); + assert_eq!(lights.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(false)).unwrap(), Vec3::ZERO); + for error in [TraceError::Cancelled, TraceError::WorkLimit, TraceError::MemoryLimit] { + assert_eq!(lights.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Err(error)), Err(error)); + } +} + +#[test] +fn neutral_default_preserves_existing_studio_linear_response() { + let lighting = Lighting::studio_default(); + assert_eq!(lighting.lights().len(), 3); + for (light, (direction, intensity)) in lighting.lights().iter().zip(crate::studio::LIGHTS) { + assert_eq!(light.direction(), direction); + assert_eq!(light.intensity(), intensity); + assert_eq!(light.color(), Vec3::new(1.0, 1.0, 1.0)); + } + for metallic in [0.0, 0.5, 1.0] { + let surface = OpaqueSurface::new(Vec3::new(0.8, 0.3, 0.2), metallic, 0.5, 1.5).unwrap(); + let expected = crate::studio::shade(surface, Vec3::Z, Vec3::Z).unwrap(); + let actual = lighting.shade_linear(surface, Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap(); + assert!((expected - actual).len() < 1e-12); + } +} + +#[test] +fn exposure_is_applied_after_the_sum_before_one_tone_map() { + let linear = Vec3::new(0.25, 0.5, 1.0); + let mapped = map_to_display(linear, 1.0).unwrap(); + assert!((mapped - Vec3::new(1.0 / 3.0, 0.5, 2.0 / 3.0)).len() < 1e-14); + assert_eq!(map_to_display(Vec3::ZERO, -16.0).unwrap(), Vec3::ZERO); + assert_eq!(map_to_display(linear, 0.0).unwrap(), crate::studio::tone_map(linear).unwrap()); + let high = map_to_display(Vec3::new(MAX_LINEAR_RADIANCE, MAX_LINEAR_RADIANCE, MAX_LINEAR_RADIANCE), 16.0).unwrap(); + assert!(high.is_finite() && high.x <= 1.0); +} + +#[test] +fn dark_backfacing_and_unlit_surfaces_do_not_trace_shadow_rays() { + let muted = DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 1.0, 1.0), 0.0).unwrap(); + let behind = DirectionalLight::new(-Vec3::Z, Vec3::new(1.0, 1.0, 1.0), 1.0).unwrap(); + let black = DirectionalLight::new(Vec3::Z, Vec3::ZERO, 1.0).unwrap(); + let lighting = Lighting::new(vec![muted, behind, black]).unwrap(); + assert_eq!(lighting.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| panic!("no contributing light")).unwrap(), Vec3::ZERO); + assert_eq!(Lighting::default().shade_linear(lambert(), Vec3::Z, -Vec3::Z, |_, _| panic!("backfacing view")).unwrap(), Vec3::ZERO); + assert_eq!(Lighting::new(Vec::new()).unwrap().shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| panic!("no lights")).unwrap(), Vec3::ZERO); +} + +#[test] +fn invalid_inputs_are_refused_and_extreme_direction_scales_normalize() { + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.01, 64.01] { + assert!(DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 1.0, 1.0), bad).is_err()); + } + for bad in [f64::NAN, f64::INFINITY, -0.01, 1.01] { + assert!(DirectionalLight::new(Vec3::Z, Vec3::new(bad, 1.0, 1.0), 1.0).is_err()); + } + for bad in [Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 1.0)] { + assert!(DirectionalLight::new(bad, Vec3::ZERO, 1.0).is_err()); + assert!(Lighting::default().shade_linear(lambert(), bad, Vec3::Z, |_, _| Ok(true)).is_err()); + assert!(Lighting::default().shade_linear(lambert(), Vec3::Z, bad, |_, _| Ok(true)).is_err()); + } + let white = Vec3::new(1.0, 1.0, 1.0); + for magnitude in [1e-300, 1e308] { + let direction = DirectionalLight::new(Vec3::new(magnitude, magnitude, magnitude), white, 1.0).unwrap().direction(); + assert!((direction.len() - 1.0).abs() < 1e-14); + } + let light = DirectionalLight::new(Vec3::Z, white, MAX_LIGHT_INTENSITY).unwrap(); + assert!(Lighting::new(vec![light; MAX_LIGHTS]).is_ok()); + assert!(Lighting::new(vec![light; MAX_LIGHTS + 1]).is_err()); + let excess_capacity = Vec::::with_capacity(MAX_LIGHTS + 1); + assert_eq!(excess_capacity.len(), 0); + assert!(Lighting::new(excess_capacity).is_err(), "empty vectors cannot retain an unbounded light allocation"); + for bad in [f64::NAN, f64::INFINITY, -16.01, 16.01] { + assert!(map_to_display(Vec3::ZERO, bad).is_err()); + } + for bad in [f64::NAN, f64::INFINITY, -1.0, MAX_LINEAR_RADIANCE * 2.0] { + assert!(map_to_display(Vec3::new(bad, 0.0, 0.0), 0.0).is_err()); + } +} + +#[test] +fn original_presets_have_distinct_bounded_real_direct_responses() { + let white = Lighting::preset(StudioPreset::Neutral).unwrap(); + assert_eq!(white, Lighting::default()); + let warm = Lighting::preset(StudioPreset::WarmCool).unwrap(); + let rim = Lighting::preset(StudioPreset::KeyRim).unwrap(); + for lights in [&white, &warm, &rim] { + assert!(lights.lights().len() <= MAX_LIGHTS); + let response = lights.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap(); + assert!(response.is_finite() && response.x > 0.0 && response.y > 0.0 && response.z > 0.0); + } + assert_ne!( + white.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap(), + warm.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap() + ); +} diff --git a/crates/render/src/raytrace/mod.rs b/crates/render/src/raytrace/mod.rs new file mode 100644 index 000000000..4a4b4c36b --- /dev/null +++ b/crates/render/src/raytrace/mod.rs @@ -0,0 +1,320 @@ +//! Optional original CPU visibility core and opaque direct-image integration. +//! +//! Original Rust implementation from elementary slab, barycentric and binary-tree +//! mathematics. Geometry is already world-space, in millimetres. No B-rep kernel +//! or third-party ray-tracer implementation is used. See `docs/render-raytrace-core.md`. + +use crate::job::CancelToken; +use solidcraft_geom::Vec3; + +mod anisotropic_faces; +mod bvh; +pub mod image; +pub mod lighting; +pub mod prepared; +pub mod reflection; +pub use bvh::{BuildLimits, BuildProgress, Bvh, BvhBuilder, MAX_DEPTH, MAX_MEMORY_BYTES, MAX_TRIANGLES}; + +/// Finite coordinate admission, not a CAD accuracy guarantee. +pub const MAX_COORDINATE_MM: f64 = 1e12; +/// Maximum finite ray interval endpoint in millimetres. +pub const MAX_DISTANCE_MM: f64 = 4e12; +/// Maximum work charged to one explicitly owned budget. +pub const MAX_WORK: u64 = 1_000_000_000; +/// Maximum incremental builder operations in one call. +pub const MAX_BUILD_STEP: usize = 4096; + +/// Structured failures; exhausting work never returns a truncated hit result. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TraceError { + InvalidInput(&'static str), + MemoryLimit, + AllocationFailed, + WorkLimit, + Cancelled, + BuildIncomplete, + Internal(&'static str), +} + +impl std::fmt::Display for TraceError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::InvalidInput(reason) => write!(f, "invalid ray tracing input: {reason}"), + Self::MemoryLimit => f.write_str("ray tracing memory admission exceeded"), + Self::AllocationFailed => f.write_str("ray tracing allocation failed"), + Self::WorkLimit => f.write_str("ray tracing work budget exhausted"), + Self::Cancelled => f.write_str("ray tracing cancelled"), + Self::BuildIncomplete => f.write_str("ray tracing BVH build is incomplete"), + Self::Internal(reason) => write!(f, "invalid ray tracing internal state: {reason}"), + } + } +} +impl std::error::Error for TraceError {} +pub type Result = std::result::Result; + +fn check_cancel(cancel: &CancelToken) -> Result<()> { + if cancel.is_cancelled() { Err(TraceError::Cancelled) } else { Ok(()) } +} + +/// Caller-owned cumulative work; can span many rays in one image job. +#[derive(Debug)] +pub struct WorkBudget { + limit: u64, + used: u64, +} + +impl WorkBudget { + pub fn new(limit: u64) -> Result { + if limit == 0 || limit > MAX_WORK { + return Err(TraceError::InvalidInput("work limit outside 1..=MAX_WORK")); + } + Ok(Self { limit, used: 0 }) + } + pub fn used(&self) -> u64 { + self.used + } + pub fn remaining(&self) -> u64 { + self.limit - self.used + } + fn tick(&mut self, cancel: &CancelToken) -> Result<()> { + check_cancel(cancel)?; + if self.used == self.limit { + return Err(TraceError::WorkLimit); + } + self.used += 1; + Ok(()) + } +} + +fn bounded(point: Vec3) -> bool { + point.is_finite() && [point.x, point.y, point.z].into_iter().all(|v| v.abs() <= MAX_COORDINATE_MM) +} + +fn unit(vector: Vec3) -> Option { + let scale = vector.x.abs().max(vector.y.abs()).max(vector.z.abs()); + if !vector.is_finite() || scale == 0.0 { + return None; + } + let scaled = vector / scale; + Some(scaled / scaled.len2().sqrt()) +} + +fn component(vector: Vec3, axis: usize) -> f64 { + match axis { + 0 => vector.x, + 1 => vector.y, + _ => vector.z, + } +} + +/// Admitted ray with a unit direction and closed finite distance interval. +/// No implicit origin offset, back-face culling or fixed world-space epsilon. +#[derive(Clone, Copy, Debug)] +pub struct Ray { + origin: Vec3, + direction: Vec3, + min: f64, + max: f64, +} + +impl Ray { + pub fn new(origin: Vec3, direction: Vec3, min: f64, max: f64) -> Result { + if !bounded(origin) || !min.is_finite() || !max.is_finite() || min < 0.0 || min > max || max > MAX_DISTANCE_MM { + return Err(TraceError::InvalidInput("ray origin or distance interval")); + } + let direction = unit(direction).ok_or(TraceError::InvalidInput("finite nonzero ray direction required"))?; + Ok(Self { origin, direction, min, max }) + } + pub fn origin(self) -> Vec3 { + self.origin + } + pub fn direction(self) -> Vec3 { + self.direction + } + pub fn interval(self) -> [f64; 2] { + [self.min, self.max] + } + pub fn at(self, distance: f64) -> Result { + if !distance.is_finite() || distance < self.min || distance > self.max { + return Err(TraceError::InvalidInput("distance outside admitted ray interval")); + } + Ok(self.origin + self.direction * distance) + } +} + +/// Conservative world-space box; empty boxes exist only inside the builder. +#[derive(Clone, Copy, Debug)] +pub struct Bounds { + min: Vec3, + max: Vec3, +} + +impl Bounds { + pub fn new(min: Vec3, max: Vec3) -> Result { + if !bounded(min) || !bounded(max) || min.x > max.x || min.y > max.y || min.z > max.z { + return Err(TraceError::InvalidInput("finite ordered bounding box required")); + } + Ok(Self { min, max }) + } + pub fn min(self) -> Vec3 { + self.min + } + pub fn max(self) -> Vec3 { + self.max + } + fn empty() -> Self { + Self { min: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), max: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY) } + } + fn include(self, other: Self) -> Self { + Self { min: self.min.min(other.min), max: self.max.max(other.max) } + } + fn point(point: Vec3) -> Self { + Self { min: point, max: point } + } + + /// Closed slab overlap. Parallel (including signed-zero) components never divide. + pub fn intersect(self, ray: &Ray) -> Option<[f64; 2]> { + self.clip(ray, ray.max) + } + + fn clip(self, ray: &Ray, maximum: f64) -> Option<[f64; 2]> { + let (mut near, mut far) = (ray.min, ray.max.min(maximum)); + for axis in 0..3 { + let (lo, hi, origin, direction) = + (component(self.min, axis), component(self.max, axis), component(ray.origin, axis), component(ray.direction, axis)); + if direction == 0.0 { + if origin < lo || origin > hi { + return None; + } + } else { + // Division may produce infinity for an almost-parallel ray; the + // finite caller interval clips it. No reciprocal times zero. + let a = (lo - origin) / direction; + let b = (hi - origin) / direction; + near = near.max(a.min(b)); + far = far.min(a.max(b)); + if near > far { + return None; + } + } + } + Some([near, far]) + } +} + +/// Validated triangle. Coincident/collinear vertices are retained but never hit. +#[derive(Clone, Copy, Debug)] +pub struct Triangle { + vertices: [Vec3; 3], + normal: Option, +} + +impl Triangle { + pub fn new(vertices: [Vec3; 3]) -> Result { + if !vertices.into_iter().all(bounded) { + return Err(TraceError::InvalidInput("triangle vertex coordinates")); + } + let [a, b, c] = vertices; + let ab = b - a; + let ac = c - a; + let scale = [ab.x, ab.y, ab.z, ac.x, ac.y, ac.z].into_iter().map(f64::abs).fold(0.0, f64::max); + let normal = if scale == 0.0 { None } else { unit((ab / scale).cross(ac / scale)) }; + Ok(Self { vertices, normal }) + } + pub fn vertices(self) -> [Vec3; 3] { + self.vertices + } + pub fn geometric_normal(self) -> Option { + self.normal + } + pub fn bounds(self) -> Bounds { + let [a, b, c] = self.vertices; + let min = a.min(b).min(c); + let max = a.max(b).max(c); + // One representable outward step, not a fixed millimetre epsilon. + Bounds { + min: Vec3::new(min.x.next_down(), min.y.next_down(), min.z.next_down()), + max: Vec3::new(max.x.next_up(), max.y.next_up(), max.z.next_up()), + } + } + fn centroid(self) -> Vec3 { + let [a, b, c] = self.vertices; + a / 3.0 + b / 3.0 + c / 3.0 + } + + /// Two-sided closed-edge barycentric intersection by dominant-direction shear. + /// At equal distance the BVH's input ordinal resolves the tie. Zero projected + /// area is a miss, including geometry collapsed by f64 arithmetic. + pub fn intersect(self, ray: &Ray) -> Option { + let normal = self.normal?; + let d = ray.direction; + let kz = if d.x.abs() >= d.y.abs() && d.x.abs() >= d.z.abs() { + 0 + } else if d.y.abs() >= d.z.abs() { + 1 + } else { + 2 + }; + let kx = (kz + 1) % 3; + let ky = (kx + 1) % 3; + let dominant = component(d, kz); + let sx = component(d, kx) / dominant; + let sy = component(d, ky) / dominant; + let projected = self.vertices.map(|v| { + let delta = v - ray.origin; + let z = component(delta, kz); + [component(delta, kx) - sx * z, component(delta, ky) - sy * z, z / dominant] + }); + let [[ax, ay, az], [bx, by, bz], [cx, cy, cz]] = projected; + let weights = [bx * cy - by * cx, cx * ay - cy * ax, ax * by - ay * bx]; + let [u, v, w] = weights; + if (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0) { + return None; + } + let determinant = u + v + w; + if determinant == 0.0 { + return None; + } + let barycentric = weights.map(|value| value / determinant); + let [u, v, w] = barycentric; + // Divide before multiplying by depth: very small triangle areas need not + // underflow their otherwise well-represented hit distance. + // An exact coordinate plane has a direct depth equation. Summing + // depths along another dominant ray axis can cancel large tangential + // terms into a false positive. No interval or edge policy changes. + let axis_plane = (0..3).find_map(|axis| { + let [a, b, c] = self.vertices.map(|point| component(point, axis)); + (a == b && b == c).then_some((axis, a)) + }); + let distance = if let Some((axis, coordinate)) = axis_plane { + (coordinate - component(ray.origin, axis)) / component(d, axis) + } else { + u * az + v * bz + w * cz + }; + if !distance.is_finite() || distance < ray.min || distance > ray.max { + return None; + } + Some(TriangleHit { distance, barycentric, geometric_normal: normal, front_face: d.dot(normal) < 0.0 }) + } +} + +/// Geometric hit, without material/shading-normal or persistent topology identity. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TriangleHit { + pub distance: f64, + pub barycentric: [f64; 3], + pub geometric_normal: Vec3, + pub front_face: bool, +} + +/// Captured input ordinal, not a CAD face identifier. RT2 owns the appearance mapping. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Hit { + pub primitive_index: usize, + pub geometry: TriangleHit, +} + +#[cfg(test)] +mod planar_shadow_tests; +#[cfg(test)] +mod tests; diff --git a/crates/render/src/raytrace/planar_shadow_tests.rs b/crates/render/src/raytrace/planar_shadow_tests.rs new file mode 100644 index 000000000..bfc44cf48 --- /dev/null +++ b/crates/render/src/raytrace/planar_shadow_tests.rs @@ -0,0 +1,125 @@ +//! Proposed regressions, not compiled or run; install only with the reviewed depth change. +use super::*; +use prepared::SharedHit; + +fn floor() -> [Vec3; 3] { + [Vec3::new(-180.0, -180.0, 0.0), Vec3::new(180.0, -180.0, 0.0), Vec3::new(180.0, 180.0, 0.0)] +} +fn permute(v: Vec3, axis: usize) -> Vec3 { + match axis { + 0 => Vec3::new(v.z, v.x, v.y), + 1 => Vec3::new(v.y, v.z, v.x), + _ => v, + } +} +fn spawned(triangle: Triangle, point: Vec3, scale: f64, direction: Vec3) -> Ray { + let normal = triangle.geometric_normal().unwrap(); + let primary = Ray::new(point + normal * (10.0 * scale), -normal, 0.0, 20.0 * scale).unwrap(); + let hit = triangle.intersect(&primary).unwrap(); + let [a, b, c] = hit.barycentric; + let [va, vb, vc] = triangle.vertices(); + SharedHit { + body_index: 0, + body_name: "Floor", + primitive_index: 0, + distance_mm: hit.distance, + position: va * a + vb * b + vc * c, + geometric_normal: normal, + front_face: hit.front_face, + shading_normal: normal, + surface: crate::surface::OpaqueSurface::new(Vec3::new(0.5, 0.5, 0.5), 0.0, 0.7, 1.5).unwrap(), + vertices: triangle.vertices(), + barycentric: hit.barycentric, + } + .spawn(direction) + .unwrap() +} +fn build(triangles: Vec, leaf_size: usize) -> Bvh { + let cancel = CancelToken::default(); + let mut builder = BvhBuilder::new(triangles, BuildLimits { leaf_size, ..Default::default() }, &cancel).unwrap(); + while !builder.step(1, &cancel).unwrap().complete {} + builder.finish().unwrap() +} + +#[test] +fn zero_plane_outgoing_ray_never_gets_positive_depth_from_shear_cancellation() { + let triangle = Triangle::new(floor()).unwrap(); + let ray = Ray::new(Vec3::new(73.17, -21.19, 0.0_f64.next_up()), Vec3::new(0.7, -1.0, 0.2), 0.0_f64.next_up(), MAX_DISTANCE_MM).unwrap(); + // Exact plane equation has negative depth: the ray starts above and leaves the plane. + // The previous dominant-Y weighted-depth sum can instead yield +1.4210854715202004e-14. + assert!(triangle.intersect(&ray).is_none()); +} + +#[test] +fn mixed_leaf_and_input_order_cannot_turn_the_departed_floor_into_an_occluder() { + let floor = Triangle::new(floor()).unwrap(); + let far = Triangle::new([Vec3::new(-1200.0, -1200.0, 1.0), Vec3::new(-1000.0, -1200.0, 1.0), Vec3::new(-1000.0, -1000.0, 1.0)]).unwrap(); + let ray = Ray::new(Vec3::new(73.17, -21.19, 0.0_f64.next_up()), Vec3::new(0.7, -1.0, 0.2), 0.0_f64.next_up(), MAX_DISTANCE_MM).unwrap(); + for leaf_size in [1, 2, 8] { + for triangles in [vec![floor, far], vec![far, floor]] { + let bvh = build(triangles, leaf_size); + let cancel = CancelToken::default(); + assert!(bvh.closest_hit(&ray, &mut WorkBudget::new(MAX_WORK).unwrap(), &cancel).unwrap().is_none()); + let mut cursor = bvh::TraceCursor::new(ray, true); + let mut work = WorkBudget::new(MAX_WORK).unwrap(); + loop { + if let Some(hit) = cursor.step(&bvh, &mut work, &cancel).unwrap() { + assert!(hit.is_none(), "any-hit traversal must agree for the mixed leaf"); + break; + } + } + } + } +} + +#[test] +fn shared_spawn_preserves_close_real_blockers_across_axes_scales_placement_and_winding() { + for axis in 0..3 { + for scale in [1e-6, 1.0, 1e6] { + for translated in [false, true] { + let translation = if translated { Vec3::new(1e8, -2e8, 11.0 * scale) } else { Vec3::ZERO }; + let transform = |v| permute(v * scale + translation, axis); + let original = floor().map(transform); + for reverse in [false, true] { + let [a, b, c] = original; + let triangle = Triangle::new(if reverse { [a, c, b] } else { [a, b, c] }).unwrap(); + for direction in [Vec3::new(0.7, -1.0, 0.2), Vec3::new(-1.0, 0.3, 1e-6)] { + for sign in [-1.0, 1.0] { + let ray = spawned(triangle, transform(Vec3::new(73.17, -21.19, 0.0)), scale, permute(direction * sign, axis)); + assert!(triangle.intersect(&ray).is_none()); + // The blocker is placed at the actual ray's positive plane crossing, + // so grazing direction does not make a finite fixture miss its target. + let height = 0.005 * scale; + let component = component(ray.direction(), axis); + let distance = height / component.abs(); + let center = ray.at(distance).unwrap(); + let [a, b, c] = [Vec3::new(-180.0, -180.0, 0.0), Vec3::new(180.0, -180.0, 0.0), Vec3::new(0.0, 180.0, 0.0)] + .map(|v| permute(v * scale, axis) + center); + let blocker = Triangle::new([a, b, c]).unwrap(); + assert!(blocker.intersect(&ray).is_some(), "a different close triangle remains visible"); + } + } + } + } + } + } +} + +#[test] +fn exact_coordinate_plane_depth_keeps_closed_intervals_signed_zero_and_oblique_path() { + let plane = Triangle::new(floor().map(|v| v + Vec3::Z * 4.0)).unwrap(); + let origin = Vec3::new(73.17, -21.19, 0.0); + assert_eq!(plane.intersect(&Ray::new(origin, Vec3::Z, 4.0, 4.0).unwrap()).unwrap().distance, 4.0); + assert!(plane.intersect(&Ray::new(origin, Vec3::Z, 4.0_f64.next_up(), 8.0).unwrap()).is_none()); + assert!(plane.intersect(&Ray::new(origin, Vec3::Z, 0.0, 4.0_f64.next_down()).unwrap()).is_none()); + let point = origin + Vec3::Z * 4.0; + for z in [0.0, -0.0] { + assert!(plane.intersect(&Ray::new(point, Vec3::new(1.0, 0.3, z), 0.0, 8.0).unwrap()).is_none()); + } + for direction in [Vec3::Z, -Vec3::Z] { + assert_eq!(plane.intersect(&Ray::new(point, direction, 0.0, 8.0).unwrap()).unwrap().distance, 0.0); + assert!(plane.intersect(&Ray::new(point, direction, 0.0_f64.next_up(), 8.0).unwrap()).is_none()); + } + let oblique = Triangle::new([Vec3::new(-4.0, -4.0, -4.0), Vec3::new(4.0, -4.0, 4.0), Vec3::new(4.0, 4.0, 4.0)]).unwrap(); + assert_eq!(oblique.intersect(&Ray::new(Vec3::new(1.0, 1.0, 9.0), -Vec3::Z, 0.0, 10.0).unwrap()).unwrap().distance, 8.0); +} diff --git a/crates/render/src/raytrace/prepared.rs b/crates/render/src/raytrace/prepared.rs new file mode 100644 index 000000000..14cd870ac --- /dev/null +++ b/crates/render/src/raytrace/prepared.rs @@ -0,0 +1,108 @@ +//! Borrowed prepared-scene contract shared by bounded transport consumers. +use super::{Bvh, Hit, MAX_DISTANCE_MM, Ray, Result, TraceError}; +use crate::{ProductScene, surface::OpaqueSurface}; +use solidcraft_geom::Vec3; + +#[derive(Clone, Copy)] +pub struct PreparedPrimitive { + pub body_index: usize, + /// Authoritative captured mesh face tag; never inferred from a plane. + pub face: Option, + pub vertices: [Vec3; 3], + pub normals: [Vec3; 3], + pub surface: OpaqueSurface, +} +pub struct PreparedScene<'a> { + pub bvh: &'a Bvh, + pub primitives: &'a [PreparedPrimitive], + pub source: &'a ProductScene, +} +#[derive(Clone, Copy)] +pub struct SharedHit<'a> { + pub body_index: usize, + pub body_name: &'a str, + pub primitive_index: usize, + pub distance_mm: f64, + pub position: Vec3, + /// Original captured winding; never orient this destructively for shading. + pub geometric_normal: Vec3, + pub front_face: bool, + pub shading_normal: Vec3, + pub surface: OpaqueSurface, + pub vertices: [Vec3; 3], + pub barycentric: [f64; 3], +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BoundaryStatus { + Unknown, +} +impl<'a> PreparedScene<'a> { + pub fn boundary_status(&self, _body_index: usize) -> BoundaryStatus { + BoundaryStatus::Unknown + } + pub fn resolve_hit(&self, ray: Ray, hit: Hit) -> Result> { + let primitive = self.primitives.get(hit.primitive_index).ok_or(TraceError::Internal("prepared primitive"))?; + let body = self.source.meshes.get(primitive.body_index).ok_or(TraceError::Internal("prepared body"))?; + let interval = ray.interval(); + if !hit.geometry.distance.is_finite() + || hit.geometry.distance < interval[0] + || hit.geometry.distance > interval[1] + || !hit.geometry.barycentric.into_iter().all(|w| w.is_finite() && (0.0..=1.0).contains(&w)) + || (hit.geometry.barycentric.into_iter().sum::() - 1.0).abs() > 1e-12 + { + return Err(TraceError::InvalidInput("prepared hit interval or barycentrics")); + } + let geometric = super::Triangle::new(primitive.vertices)?.geometric_normal().ok_or(TraceError::InvalidInput("degenerate prepared hit"))?; + let front_face = ray.direction().dot(geometric) < 0.0; + let [a, b, c] = hit.geometry.barycentric; + let [va, vb, vc] = primitive.vertices; + let [na, nb, nc] = primitive.normals; + let mut normal = super::unit(na * a + nb * b + nc * c).unwrap_or(geometric); + if normal.dot(geometric) < 0.0 { + normal = -normal; + } + if !front_face { + normal = -normal; + } + Ok(SharedHit { + body_index: primitive.body_index, + body_name: &body.name, + primitive_index: hit.primitive_index, + distance_mm: hit.geometry.distance, + position: va * a + vb * b + vc * c, + geometric_normal: geometric, + front_face, + shading_normal: normal, + surface: primitive.surface, + vertices: primitive.vertices, + barycentric: hit.geometry.barycentric, + }) + } +} +impl SharedHit<'_> { + pub fn oriented_geometric_normal(self) -> Vec3 { + if self.front_face { self.geometric_normal } else { -self.geometric_normal } + } + /// Component-wise position error projected onto the original geometric normal. + pub fn spawn(self, direction: Vec3) -> Result { + let mut n = self.geometric_normal; + if n.dot(direction) < 0.0 { + n = -n; + } + let [a, b, c] = self.barycentric; + let [va, vb, vc] = self.vertices; + let magnitude = |x: f64, y: f64, z: f64| x.abs() * a.abs() + y.abs() * b.abs() + z.abs() * c.abs(); + let e = Vec3::new(magnitude(va.x, vb.x, vc.x), magnitude(va.y, vb.y, vc.y), magnitude(va.z, vb.z, vc.z)) * (8.0 * f64::EPSILON); + let shifted = self.position + n * (n.x.abs() * e.x + n.y.abs() * e.y + n.z.abs() * e.z); + let outward = |v: f64, n: f64| { + if n > 0.0 { + v.next_up() + } else if n < 0.0 { + v.next_down() + } else { + v + } + }; + Ray::new(Vec3::new(outward(shifted.x, n.x), outward(shifted.y, n.y), outward(shifted.z, n.z)), direction, 0.0_f64.next_up(), MAX_DISTANCE_MM) + } +} diff --git a/crates/render/src/raytrace/reflection.rs b/crates/render/src/raytrace/reflection.rs new file mode 100644 index 000000000..7b5eaf82a --- /dev/null +++ b/crates/render/src/raytrace/reflection.rs @@ -0,0 +1,156 @@ +//! Original bounded specular sampling. All values are linear-light quantities. +use super::{Result, TraceError}; +use crate::surface::{OpaqueSurface, unit_direction}; +use solidcraft_geom::Vec3; +use std::f64::consts::{PI, TAU}; +#[derive(Clone, Copy, Debug)] +pub struct ReflectionSample { + pub direction: Vec3, + pub weight: Vec3, + pub pdf: f64, +} +fn fresnel(surface: OpaqueSurface, cosine: f64) -> Vec3 { + let f0 = surface.normal_reflectance(); + f0 + (Vec3::new(1.0, 1.0, 1.0) - f0) * (1.0 - cosine.clamp(0.0, 1.0)).powi(5) +} +pub fn mirror(surface: OpaqueSurface, normal: Vec3, view: Vec3) -> Result> { + let n = unit_direction(normal).map_err(|_| TraceError::InvalidInput("mirror normal"))?; + let v = unit_direction(view).map_err(|_| TraceError::InvalidInput("mirror view"))?; + let nv = n.dot(v); + if nv <= 0.0 { + return Ok(None); + } + Ok(Some(ReflectionSample { direction: n * (2.0 * nv) - v, weight: fresnel(surface, nv), pdf: 1.0 })) +} +/// GGX normal-distribution sampling; rejected below-surface events contribute zero. +/// PDF is D(h)*n.h/(4*v.h), matching this sampler, without retry/renormalization. +pub fn rough_specular(surface: OpaqueSurface, normal: Vec3, view: Vec3, u: [f64; 2]) -> Result> { + if !u.into_iter().all(|v| v.is_finite() && (0.0..1.0).contains(&v)) { + return Err(TraceError::InvalidInput("GGX variates outside [0,1)")); + } + let n = unit_direction(normal).map_err(|_| TraceError::InvalidInput("GGX normal"))?; + let v = unit_direction(view).map_err(|_| TraceError::InvalidInput("GGX view"))?; + let nv = n.dot(v); + if nv <= 0.0 { + return Ok(None); + } + let alpha = surface.roughness().powi(2); + let a2 = alpha * alpha; + let cos = ((1.0 - u[0]) / (1.0 + (a2 - 1.0) * u[0])).sqrt(); + let sin = (1.0 - cos * cos).max(0.0).sqrt(); + let phi = TAU * u[1]; + let axis = if n.z.abs() < 0.9 { Vec3::Z } else { Vec3::X }; + let tangent = unit_direction(axis.cross(n)).map_err(|_| TraceError::InvalidInput("GGX tangent"))?; + let bitangent = n.cross(tangent); + let h = unit_direction(tangent * (sin * phi.cos()) + bitangent * (sin * phi.sin()) + n * cos) + .map_err(|_| TraceError::InvalidInput("GGX half vector"))?; + let vh = v.dot(h); + if vh <= 0.0 { + return Ok(None); + } + let direction = h * (2.0 * vh) - v; + let nl = n.dot(direction); + if nl <= 0.0 { + return Ok(None); + } + let nh = n.dot(h).clamp(0.0, 1.0); + let denominator = (1.0 - nh * nh) + nh * nh * a2; + let distribution = a2 / (PI * denominator * denominator); + let pdf = distribution * nh / (4.0 * vh); + let visibility = |c: f64| 2.0 / (c + (a2 + (1.0 - a2) * c * c).sqrt()); + let specular = distribution * 0.25 * visibility(nv) * visibility(nl); + let weight = fresnel(surface, vh) * (specular * nl / pdf); + if !pdf.is_finite() || pdf <= 0.0 || !weight.is_finite() { + return Err(TraceError::InvalidInput("nonfinite GGX sample")); + } + Ok(Some(ReflectionSample { direction, weight, pdf })) +} +/// Bounded stratified reflection sequence, keyed by captured pixel/bounce identity. +/// The first coordinate visits each of R radial strata exactly once. The second +/// uses a digitally shifted base-two radical inverse: exact dyadic coverage only +/// for power-of-two R. This is not a progressive prefix or a variance guarantee. +/// BSDF/PDF, null-event accounting, R-attempt and bounce bounds are unchanged. +/// Actual outgoing paths, null samples and work can differ with the directions. +pub fn variates(pixel: u64, sample: u64, bounce: u64, samples: u64) -> Result<[f64; 2]> { + if !(1..=64).contains(&samples) || sample >= samples { + return Err(TraceError::InvalidInput("reflection sample ordinal/count outside 1..64 strata")); + } + fn mix(mut x: u64) -> u64 { + x ^= x >> 30; + x = x.wrapping_mul(0xbf58476d1ce4e5b9); + x ^= x >> 27; + x = x.wrapping_mul(0x94d049bb133111eb); + x ^ (x >> 31) + } + let key = pixel.wrapping_mul(0x9e3779b97f4a7c15) ^ bounce.wrapping_mul(0x632be59bd9b4e019); + // A 32-bit midpoint jitter stays at least 2^-33 from either radial-cell + // edge. Even adding ordinal63 and dividing by64 cannot round to an edge. + let radial_jitter = ((mix(key) >> 32) as f64 + 0.5) / (1u64 << 32) as f64; + let radial = (sample as f64 + radial_jitter) / samples as f64; + let azimuth_bits = (sample.reverse_bits() >> 12) ^ (mix(key ^ 0xa0761d6478bd642f) >> 12); + let azimuth = (azimuth_bits as f64 + 0.5) / (1u64 << 52) as f64; + Ok([radial, azimuth]) +} + +// Preserve the original hashed sequence as a test-only comparison control. +#[cfg(test)] +fn hash_variates(pixel: u64, sample: u64, bounce: u64) -> [f64; 2] { + fn mix(mut x: u64) -> u64 { + x ^= x >> 30; + x = x.wrapping_mul(0xbf58476d1ce4e5b9); + x ^= x >> 27; + x = x.wrapping_mul(0x94d049bb133111eb); + x ^ (x >> 31) + } + let key = pixel.wrapping_mul(0x9e3779b97f4a7c15) ^ sample.wrapping_mul(0xd1b54a32d192ed03) ^ bounce.wrapping_mul(0x632be59bd9b4e019); + let value = |x: u64| ((mix(x) >> 12) as f64 + 0.5) / (1u64 << 52) as f64; + [value(key), value(key ^ 0xa0761d6478bd642f)] +} + +#[cfg(test)] +#[path = "reflection_stratified_tests.rs"] +mod stratified_tests; +#[cfg(test)] +mod tests { + use super::{OpaqueSurface, PI, Vec3, hash_variates as variates, mirror, rough_specular}; + fn white() -> OpaqueSurface { + OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap() + } + #[test] + fn mirror_is_explicit_delta_with_normal_fresnel_and_reflection_law() { + let surface = OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.2), 0.0, 0.045, 1.5).unwrap(); + let sample = mirror(surface, Vec3::Z, Vec3::Z).unwrap().unwrap(); + assert_eq!(sample.direction, Vec3::Z); + assert!((sample.weight.x - 0.04).abs() < 1e-14); + let view = Vec3::new(0.6, 0.0, 0.8); + let sample = mirror(surface, Vec3::Z, view).unwrap().unwrap(); + assert!((sample.direction - Vec3::new(-0.6, 0.0, 0.8)).len() < 1e-14); + assert!(rough_specular(surface, Vec3::Z, view, [0.4, 0.1]).unwrap().is_some()); + } + #[test] + fn fully_rough_conductor_has_analytic_pdf_weight_and_null_probability() { + let sample = rough_specular(white(), Vec3::Z, Vec3::Z, [0.25, 0.2]).unwrap().unwrap(); + assert!((sample.direction.z - 0.5).abs() < 1e-14); + assert!((sample.pdf - 1.0 / (4.0 * PI)).abs() < 1e-14); + assert!((sample.weight.x - 2.0 / 3.0).abs() < 1e-14); + assert!(rough_specular(white(), Vec3::Z, Vec3::Z, [0.75, 0.2]).unwrap().is_none()); + let mut reflectance = 0.0; + for i in 0..4096 { + reflectance += rough_specular(white(), Vec3::Z, Vec3::Z, [(i as f64 + 0.5) / 4096.0, 0.3]).unwrap().map_or(0.0, |s| s.weight.x); + } + // Independent exact hemispherical integral for alpha=1, F=1, normal view. + assert!((reflectance / 4096.0 - (1.0 - 2.0_f64.ln())).abs() < 1e-6); + } + #[test] + fn invalid_variates_directions_and_deterministic_open_samples() { + for bad in [f64::NAN, f64::INFINITY, -0.1, 1.0] { + assert!(rough_specular(white(), Vec3::Z, Vec3::Z, [bad, 0.2]).is_err()); + } + assert!(mirror(white(), Vec3::ZERO, Vec3::Z).is_err()); + for pixel in 0..100 { + let u = variates(pixel, 17, 4); + assert_eq!(u, variates(pixel, 17, 4)); + assert!(u.into_iter().all(|v| v > 0.0 && v < 1.0)); + } + } +} diff --git a/crates/render/src/raytrace/reflection_image_tests.rs b/crates/render/src/raytrace/reflection_image_tests.rs new file mode 100644 index 000000000..6aeac0c65 --- /dev/null +++ b/crates/render/src/raytrace/reflection_image_tests.rs @@ -0,0 +1,179 @@ +use super::*; +use crate::ProductMesh; +use crate::job::{ReflectionBody, ReflectionMode, ReflectionOptions}; +use solidcraft_geom::Mesh; +use std::sync::Arc; +fn scene() -> ProductScene { + fn quad(name: &str, positions: Vec, normal: Vec3, color: [u8; 3], surface: Option) -> ProductMesh { + ProductMesh { + name: name.into(), + mesh: Arc::new(Mesh { + positions, + normals: vec![normal; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }), + color, + opacity: 1.0, + surface, + faces: Vec::new(), + } + } + let mirror = quad( + "Mirror", + vec![Vec3::new(-20.0, -20.0, -20.0), Vec3::new(20.0, -20.0, -20.0), Vec3::new(20.0, 20.0, 20.0), Vec3::new(-20.0, 20.0, 20.0)], + Vec3::new(0.0, -1.0, 1.0), + [255; 3], + Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 0.2, 1.5).unwrap()), + ); + let object = quad( + "Orange target", + vec![Vec3::new(-8.0, -8.0, 10.0), Vec3::new(-8.0, 8.0, 10.0), Vec3::new(8.0, 8.0, 10.0), Vec3::new(8.0, -8.0, 10.0)], + -Vec3::Z, + [240, 80, 20], + None, + ); + let meshes = vec![mirror, object]; + let bounds = meshes.iter().fold(solidcraft_geom::Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + ProductScene { meshes, bounds } +} +fn request(reflections: Option) -> ImageRequest { + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Front); + ImageRequest { + integrator: job::Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + reflections, + shadows: false, + lights: Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, -1.0], color: [1.0; 3], intensity: 2.0 }]), + ..Default::default() + }), + camera, + width: 9, + height: 9, + background: [13, 27, 41], + transparent_background: false, + } +} +fn reflection_options(mode: ReflectionMode) -> ReflectionOptions { + ReflectionOptions { bodies: vec![ReflectionBody { body: "Mirror".into(), mode }], max_bounces: 2, samples: 16 } +} +fn render(request: ImageRequest) -> Vec { + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new(scene(), request, CancelToken::default(), options).unwrap(); + for _ in 0..200_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return png; + } + } + panic!("bounded reflection fixture did not complete"); +} +#[test] +fn mirror_png_contains_other_body_and_rough_transport_is_reproducible() { + let baseline = ::image::load_from_memory(&render(request(None))).unwrap().to_rgba8(); + let mirrored = ::image::load_from_memory(&render(request(Some(reflection_options(ReflectionMode::Mirror))))).unwrap().to_rgba8(); + let b = baseline.get_pixel(4, 4).0; + let p = mirrored.get_pixel(4, 4).0; + assert!(p[0] > p[1] && p[1] > p[2], "actual orange object must be reflected: {p:?}"); + assert_ne!(p, b, "reflection must change the scene image, not only metadata"); + let rough = request(Some(reflection_options(ReflectionMode::RoughSpecular))); + assert_eq!(render(rough.clone()), render(rough)); +} +#[test] +fn explicit_empty_overrides_preserve_baseline_bytes_and_validate_names_atomically() { + assert_eq!(render(request(None)), render(request(Some(ReflectionOptions::default())))); + let mut options = reflection_options(ReflectionMode::Mirror); + options.bodies[0].body = "missing".into(); + let request = request(Some(options)); + assert_eq!(admit(&scene(), &request, request.raytrace.as_ref().unwrap()).err().unwrap().code, ErrorCode::InvalidRequest); + let hostile = ReflectionOptions { bodies: Vec::with_capacity(65), ..ReflectionOptions::default() }; + assert!(hostile.validate().is_err()); +} +#[test] +fn reflection_cancel_and_work_exhaustion_never_publish_partial_frame() { + for mode in [ReflectionMode::Mirror, ReflectionMode::RoughSpecular] { + for cancel_now in [false, true] { + let request = request(Some(reflection_options(mode))); + let options = request.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene(), request, cancel.clone(), options).unwrap(); + let mut reached = false; + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.bounce > 0) { + reached = true; + break; + } + } + assert!(reached); + if cancel_now { + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + } else { + task.work.limit = task.work.used(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + } + } + } +} +#[test] +fn prepared_hit_preserves_original_winding_identity_and_never_certifies_glass() { + let source = scene(); + let primitive = &source.meshes[0]; + let indices = primitive.mesh.triangles[0]; + let vertices = indices.map(|i| primitive.mesh.positions[i as usize]); + let triangle = Triangle::new(vertices).unwrap(); + let ray = Ray::new(Vec3::new(2.0, -50.0, 0.0), Vec3::Y, 0.0, 100.0).unwrap(); + let geometry = triangle.intersect(&ray).unwrap(); + let cancel = CancelToken::default(); + let mut builder = BvhBuilder::new(vec![triangle], limits(), &cancel).unwrap(); + while !builder.step(1, &cancel).unwrap().complete {} + let bvh = builder.finish().unwrap(); + let primitives = + [PreparedPrimitive { body_index: 0, face: Some(0), vertices, normals: [geometry.geometric_normal; 3], surface: primitive.surface.unwrap() }]; + let prepared = PreparedScene { bvh: &bvh, primitives: &primitives, source: &source }; + let shared = prepared.resolve_hit(ray, super::super::Hit { primitive_index: 0, geometry }).unwrap(); + assert_eq!(shared.body_name, "Mirror"); + assert_eq!(shared.geometric_normal, geometry.geometric_normal); + assert_eq!(shared.front_face, geometry.front_face); + assert_eq!(prepared.boundary_status(0), super::super::prepared::BoundaryStatus::Unknown); +} +#[test] +fn shared_spawn_excludes_signed_zero_self_hit_without_skipping_thin_blockers() { + for x in [0.0, 1e12 - 100.0] { + let vertices = [Vec3::new(x, 0.0, 0.0), Vec3::new(x + 20.0, 0.0, 0.0), Vec3::new(x, 20.0, 0.0)]; + let triangle = Triangle::new(vertices).unwrap(); + let ray = Ray::new(Vec3::new(x + 5.0, 5.0, 10.0), -Vec3::Z, 0.0, 20.0).unwrap(); + let geometry = triangle.intersect(&ray).unwrap(); + let primitive = PreparedPrimitive { + body_index: 0, + face: Some(0), + vertices, + normals: [Vec3::Z; 3], + surface: OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.0, 0.7, 1.5).unwrap(), + }; + let source = ProductScene { + meshes: vec![ProductMesh { + name: "Plane".into(), + mesh: Arc::new(Mesh::default()), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }], + bounds: Default::default(), + }; + let cancel = CancelToken::default(); + let mut builder = BvhBuilder::new(vec![triangle], limits(), &cancel).unwrap(); + while !builder.step(1, &cancel).unwrap().complete {} + let bvh = builder.finish().unwrap(); + let primitives = [primitive]; + let prepared = PreparedScene { bvh: &bvh, primitives: &primitives, source: &source }; + let hit = prepared.resolve_hit(ray, super::super::Hit { primitive_index: 0, geometry }).unwrap(); + let secondary = hit.spawn(Vec3::Z).unwrap(); + assert!(secondary.interval()[0] > 0.0); + assert!(triangle.intersect(&secondary).is_none()); + assert!(Triangle::new(vertices.map(|v| v + Vec3::Z * 0.005)).unwrap().intersect(&secondary).is_some()); + } +} diff --git a/crates/render/src/raytrace/reflection_stratified_tests.rs b/crates/render/src/raytrace/reflection_stratified_tests.rs new file mode 100644 index 000000000..d830b0758 --- /dev/null +++ b/crates/render/src/raytrace/reflection_stratified_tests.rs @@ -0,0 +1,83 @@ +use super::*; +use std::collections::BTreeSet; + +#[test] +fn radial_strata_and_open_domains_hold_for_every_supported_count_and_extreme_keys() { + for samples in 1..=64 { + for pixel in [0, 17, u64::MAX] { + for bounce in [0, 3, u64::MAX] { + for sample in 0..samples { + let u = variates(pixel, sample, bounce, samples).unwrap(); + assert!(u.into_iter().all(|v| v.is_finite() && v > 0.0 && v < 1.0)); + assert_eq!((u[0] * samples as f64).floor() as u64, sample); + assert_eq!(u, variates(pixel, sample, bounce, samples).unwrap()); + } + } + } + } +} + +#[test] +fn azimuth_visits_each_dyadic_bin_and_scramble_changes_with_pixel_and_bounce() { + for samples in [1, 2, 4, 8, 16, 32, 64] { + for (pixel, bounce) in [(0, 0), (73, 2), (u64::MAX, u64::MAX)] { + let bins: BTreeSet<_> = (0..samples).map(|i| (variates(pixel, i, bounce, samples).unwrap()[1] * samples as f64).floor() as u64).collect(); + assert_eq!(bins, (0..samples).collect::>()); + } + } + let original = variates(0, 0, 0, 16).unwrap(); + assert_ne!(original, variates(1, 0, 0, 16).unwrap()); + assert_ne!(original, variates(0, 0, 1, 16).unwrap()); + assert_ne!(original, variates(0, 0, 0, 32).unwrap(), "R is part of the sequence, not a progressive-prefix contract"); +} + +#[test] +fn malformed_count_or_ordinal_refuses_without_wrapping_or_retrying() { + for count in [0, 65, u64::MAX] { + assert_eq!(variates(0, 0, 0, count), Err(TraceError::InvalidInput("reflection sample ordinal/count outside 1..64 strata"))); + } + for count in 1..=64 { + for sample in [count, u64::MAX] { + assert!(variates(u64::MAX, sample, u64::MAX, count).is_err()); + } + } +} + +#[test] +fn analytic_white_furnace_mean_second_moment_and_null_events_keep_full_sample_divisor() { + let white = OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap(); + // At n=v, alpha=F=1: W(u)=2-1/(1-u) for u<1/2, zero otherwise. + // Independent integrals: E[W]=1-ln2; E[W^2]=3-4ln2. Both integrands + // decrease from1 to0: one point per equal stratum brackets the integral + // between left/right Riemann sums, whose difference is exactly1/R. + let expected_mean = 1.0 - 2.0_f64.ln(); + let expected_second = 3.0 - 4.0 * 2.0_f64.ln(); + for samples in [2, 4, 8, 16, 32, 64] { + for (pixel, bounce) in [(0, 0), (19, 3), (u64::MAX, 7)] { + let (mut sum, mut square_sum, mut nulls) = (0.0, 0.0, 0); + for i in 0..samples { + match rough_specular(white, Vec3::Z, Vec3::Z, variates(pixel, i, bounce, samples).unwrap()).unwrap() { + Some(sample) => { + sum += sample.weight.x; + square_sum += sample.weight.x * sample.weight.x; + } + None => nulls += 1, + } + } + assert_eq!(nulls, samples / 2, "null events are retained, not retried"); + let bound = 1.0 / samples as f64; + assert!((sum / samples as f64 - expected_mean).abs() < bound); + assert!((square_sum / samples as f64 - expected_second).abs() < bound); + } + } +} + +#[test] +fn original_hashed_sequence_remains_a_distinct_comparison_control() { + for (pixel, sample, bounce) in [(0, 0, 0), (73, 7, 2), (u64::MAX, 63, u64::MAX)] { + let old = hash_variates(pixel, sample, bounce); + assert_eq!(old, hash_variates(pixel, sample, bounce)); + assert!(old.into_iter().all(|v| v > 0.0 && v < 1.0)); + assert_ne!(old, variates(pixel, sample, bounce, 64).unwrap()); + } +} diff --git a/crates/render/src/raytrace/tests.rs b/crates/render/src/raytrace/tests.rs new file mode 100644 index 000000000..79ff9d0d2 --- /dev/null +++ b/crates/render/src/raytrace/tests.rs @@ -0,0 +1,261 @@ +use super::*; + +fn triangle(z: f64) -> Triangle { + Triangle::new([Vec3::new(0., 0., z), Vec3::new(2., 0., z), Vec3::new(0., 2., z)]).unwrap() +} +fn ray(origin: Vec3, direction: Vec3) -> Ray { + Ray::new(origin, direction, 0., 100.).unwrap() +} +fn build(triangles: Vec, limits: BuildLimits, chunk: usize) -> Bvh { + let cancel = CancelToken::default(); + let mut builder = BvhBuilder::new(triangles, limits, &cancel).unwrap(); + while !builder.step(chunk, &cancel).unwrap().complete {} + builder.finish().unwrap() +} +fn closest(bvh: &Bvh, ray: &Ray) -> Option { + bvh.closest_hit(ray, &mut WorkBudget::new(MAX_WORK).unwrap(), &CancelToken::default()).unwrap() +} +fn brute(triangles: &[Triangle], ray: &Ray) -> Option { + let mut best: Option = None; + for (primitive_index, triangle) in triangles.iter().enumerate() { + if let Some(geometry) = triangle.intersect(ray) + && best.is_none_or(|old| { + geometry.distance < old.geometry.distance || (geometry.distance == old.geometry.distance && primitive_index < old.primitive_index) + }) + { + best = Some(Hit { primitive_index, geometry }); + } + } + best +} +fn close(actual: f64, expected: f64) { + assert!((actual - expected).abs() <= 1e-12 * expected.abs().max(f64::MIN_POSITIVE), "{actual} != {expected}"); +} + +#[test] +fn ray_admission_normalizes_without_overflow_or_tiny_vector_cutoff() { + for scale in [f64::from_bits(1), 1e-200, 1., 1e200, f64::MAX] { + let r = ray(Vec3::ZERO, Vec3::new(scale, 0., 0.)); + assert_eq!(r.direction(), Vec3::X); + assert_eq!(r.at(2.).unwrap(), Vec3::new(2., 0., 0.)); + } + for direction in [Vec3::ZERO, Vec3::new(f64::NAN, 0., 1.), Vec3::new(0., f64::INFINITY, 1.)] { + assert!(Ray::new(Vec3::ZERO, direction, 0., 1.).is_err()); + } + for (min, max) in [(-1., 1.), (2., 1.), (0., f64::INFINITY), (f64::NAN, 1.), (0., MAX_DISTANCE_MM.next_up())] { + assert!(Ray::new(Vec3::ZERO, Vec3::Z, min, max).is_err()); + } + assert!(Ray::new(Vec3::new(MAX_COORDINATE_MM.next_up(), 0., 0.), Vec3::Z, 0., 1.).is_err()); + assert!(ray(Vec3::ZERO, Vec3::Z).at(f64::NAN).is_err()); +} + +#[test] +fn analytic_triangle_distance_barycentrics_normal_and_two_sides() { + let t = triangle(0.); + let hit = t.intersect(&ray(Vec3::new(0.5, 0.5, 2.), -Vec3::Z)).unwrap(); + assert_eq!(hit.distance, 2.); + assert_eq!(hit.barycentric, [0.5, 0.25, 0.25]); + assert_eq!(hit.geometric_normal, Vec3::Z); + assert!(hit.front_face); + let back = t.intersect(&ray(Vec3::new(0.5, 0.5, -2.), Vec3::Z)).unwrap(); + assert_eq!(back.distance, 2.); + assert!(!back.front_face); + let boundary = Ray::new(Vec3::new(0.5, 0.5, 2.), -Vec3::Z, 2., 2.).unwrap(); + assert!(t.intersect(&boundary).is_some()); + assert!(t.intersect(&Ray::new(boundary.origin(), boundary.direction(), 0., 1.99).unwrap()).is_none()); + assert!(t.intersect(&ray(Vec3::new(2., 2., 2.), -Vec3::Z)).is_none()); +} + +#[test] +fn tiny_and_huge_geometry_have_no_fixed_world_epsilon() { + for scale in [1e-120, 1e-12, 1., 1e11] { + let t = Triangle::new([Vec3::ZERO, Vec3::X * (2. * scale), Vec3::Y * (2. * scale)]).unwrap(); + let r = Ray::new(Vec3::new(0.5 * scale, 0.5 * scale, 2. * scale), -Vec3::Z, 0., 4. * scale).unwrap(); + let hit = t.intersect(&r).unwrap(); + close(hit.distance, 2. * scale); + close(hit.barycentric[0], 0.5); + let bvh = build(vec![t], BuildLimits::default(), 1); + assert_eq!(closest(&bvh, &r).unwrap().geometry, hit); + } +} + +#[test] +fn shared_edges_vertices_and_equal_distance_use_lowest_input_ordinal() { + let a = Triangle::new([Vec3::ZERO, Vec3::X, Vec3::Y]).unwrap(); + let b = Triangle::new([Vec3::new(1., 1., 0.), Vec3::Y, Vec3::X]).unwrap(); + for triangles in [vec![a, b], vec![b, a], vec![a, a]] { + let bvh = build(triangles.clone(), BuildLimits { leaf_size: 1, ..Default::default() }, 1); + for point in [Vec3::new(0.5, 0.5, 1.), Vec3::new(1., 0., 1.)] { + let r = ray(point, -Vec3::Z); + assert_eq!(closest(&bvh, &r), brute(&triangles, &r)); + assert_eq!(closest(&bvh, &r).unwrap().primitive_index, 0); + } + } +} + +#[test] +fn degenerate_parallel_coplanar_and_grazing_cases_are_explicit() { + for vertices in [[Vec3::ZERO; 3], [Vec3::ZERO, Vec3::X, Vec3::X * 2.]] { + let t = Triangle::new(vertices).unwrap(); + assert!(t.geometric_normal().is_none()); + assert!(t.intersect(&ray(Vec3::new(0., 0., 1.), -Vec3::Z)).is_none()); + } + let t = triangle(0.); + assert!(t.intersect(&ray(Vec3::new(0.5, 0.5, 1.), Vec3::X)).is_none()); + assert!(t.intersect(&ray(Vec3::new(0.5, 0.5, 0.), Vec3::X)).is_none()); + let hit = t.intersect(&ray(Vec3::new(-1., 0.25, 1e-9), Vec3::new(1., 0., -1e-9))).unwrap(); + close(hit.distance, 1.); + assert!(t.intersect(&ray(Vec3::new(0.5, 0.5, 0.), Vec3::Z)).is_some(), "closed t=0 is a caller policy, not silently offset"); +} + +#[test] +fn slab_intervals_handle_signed_zero_boundaries_and_almost_parallel_components() { + let b = Bounds::new(Vec3::new(1., 1., 1.), Vec3::new(2., 2., 2.)).unwrap(); + assert_eq!(b.intersect(&ray(Vec3::new(1., 1., 0.), Vec3::new(-0., 0., 1.))), Some([1., 2.])); + assert!(b.intersect(&ray(Vec3::new(0., 1., 0.), Vec3::Z)).is_none()); + assert_eq!(b.intersect(&ray(Vec3::new(1.5, 1.5, 0.), Vec3::new(f64::from_bits(1), 0., 1.))), Some([1., 2.])); + assert!(b.intersect(&ray(Vec3::new(0., 1.5, 0.), Vec3::new(f64::from_bits(1), 0., 1.))).is_none()); + assert!(Bounds::new(Vec3::X, Vec3::ZERO).is_err()); + assert!(Bounds::new(Vec3::new(f64::NAN, 0., 0.), Vec3::X).is_err()); +} + +#[test] +fn builder_steps_are_bounded_and_results_do_not_depend_on_chunk_size() { + let triangles = (0..31).map(|i| triangle(f64::from(i))).collect::>(); + let cancel = CancelToken::default(); + let limits = BuildLimits { leaf_size: 1, ..Default::default() }; + let mut builder = BvhBuilder::new(triangles.clone(), limits, &cancel).unwrap(); + let mut used = 0; + loop { + let progress = builder.step(1, &cancel).unwrap(); + assert!(progress.work_used - used <= 1); + used = progress.work_used; + if progress.complete { + break; + } + } + let a = builder.finish().unwrap(); + let b = build(triangles.clone(), limits, MAX_BUILD_STEP); + assert_eq!(a.node_count(), b.node_count()); + assert!(a.node_count() < 2 * triangles.len()); + assert!(a.retained_bytes().unwrap() <= limits.max_memory_bytes); + for z in [0.5, 5.5, 50.] { + let r = ray(Vec3::new(0.5, 0.5, z), -Vec3::Z); + assert_eq!(closest(&a, &r), brute(&triangles, &r)); + assert_eq!(closest(&a, &r), closest(&b, &r)); + } +} + +#[test] +fn coincident_centroids_and_depth_cap_terminate_without_recursion() { + let triangles = vec![triangle(0.); 129]; + for depth in [1, MAX_DEPTH] { + let bvh = build(triangles.clone(), BuildLimits { max_depth: depth, leaf_size: 1, ..Default::default() }, 3); + let r = ray(Vec3::new(0.5, 0.5, 1.), -Vec3::Z); + assert_eq!(closest(&bvh, &r), brute(&triangles, &r)); + assert_eq!(closest(&bvh, &r).unwrap().primitive_index, 0); + } +} + +#[test] +fn empty_scene_and_incomplete_build_are_distinct() { + let empty = build(Vec::new(), BuildLimits::default(), 1); + assert_eq!(empty.primitive_count(), 0); + assert_eq!(empty.node_count(), 0); + assert!(closest(&empty, &ray(Vec3::ZERO, Vec3::Z)).is_none()); + let builder = BvhBuilder::new(vec![triangle(0.)], BuildLimits::default(), &CancelToken::default()).unwrap(); + assert!(matches!(builder.finish(), Err(TraceError::BuildIncomplete))); +} + +#[test] +fn work_limit_is_an_error_not_a_partial_hit_and_can_span_many_rays() { + let bvh = build(vec![triangle(0.)], BuildLimits::default(), 1); + let cancel = CancelToken::default(); + let r = ray(Vec3::new(0.5, 0.5, 1.), -Vec3::Z); + assert_eq!(bvh.closest_hit(&r, &mut WorkBudget::new(1).unwrap(), &cancel), Err(TraceError::WorkLimit)); + let mut work = WorkBudget::new(2).unwrap(); + assert!(bvh.any_hit(&r, &mut work, &cancel).unwrap()); + assert_eq!(work.used(), 2); + assert_eq!(work.remaining(), 0); + assert_eq!(bvh.any_hit(&r, &mut work, &cancel), Err(TraceError::WorkLimit)); + let mut builder = BvhBuilder::new(vec![triangle(0.); 20], BuildLimits { max_work: 1, ..Default::default() }, &cancel).unwrap(); + assert_eq!(builder.step(2, &cancel), Err(TraceError::WorkLimit)); +} + +#[test] +fn cancellation_covers_admission_mid_build_and_both_traversals() { + let cancel = CancelToken::default(); + let mut builder = BvhBuilder::new(vec![triangle(0.); 20], BuildLimits::default(), &cancel).unwrap(); + builder.step(2, &cancel).unwrap(); + cancel.cancel(); + assert_eq!(builder.step(1, &cancel), Err(TraceError::Cancelled)); + assert!(matches!(BvhBuilder::new(vec![triangle(0.)], BuildLimits::default(), &cancel), Err(TraceError::Cancelled))); + let bvh = build(vec![triangle(0.)], BuildLimits::default(), 1); + let r = ray(Vec3::new(0.5, 0.5, 1.), -Vec3::Z); + assert_eq!(bvh.closest_hit(&r, &mut WorkBudget::new(10).unwrap(), &cancel), Err(TraceError::Cancelled)); + assert_eq!(bvh.any_hit(&r, &mut WorkBudget::new(10).unwrap(), &cancel), Err(TraceError::Cancelled)); +} + +#[test] +fn memory_counts_input_capacity_and_hostile_limits_refuse_before_own_allocations() { + let defaults = BuildLimits::default(); + let normal = BvhBuilder::required_bytes(1, 1, defaults).unwrap(); + assert!(BvhBuilder::required_bytes(1, 100, defaults).unwrap() > normal); + assert_eq!(BvhBuilder::required_bytes(1, usize::MAX, defaults), Err(TraceError::MemoryLimit)); + assert_eq!(BvhBuilder::required_bytes(1, 1, BuildLimits { max_memory_bytes: 1, ..defaults }), Err(TraceError::MemoryLimit)); + for limits in [ + BuildLimits { max_depth: MAX_DEPTH + 1, ..defaults }, + BuildLimits { leaf_size: 0, ..defaults }, + BuildLimits { max_triangles: MAX_TRIANGLES + 1, ..defaults }, + BuildLimits { max_memory_bytes: MAX_MEMORY_BYTES + 1, ..defaults }, + BuildLimits { max_work: MAX_WORK + 1, ..defaults }, + ] { + assert!(BvhBuilder::required_bytes(1, 1, limits).is_err()); + } + assert!(WorkBudget::new(0).is_err()); + let mut builder = BvhBuilder::new(vec![triangle(0.)], defaults, &CancelToken::default()).unwrap(); + assert!(builder.step(0, &CancelToken::default()).is_err()); + assert!(builder.step(MAX_BUILD_STEP + 1, &CancelToken::default()).is_err()); +} + +struct Seed(u64); +impl Seed { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + self.0 + } + fn scalar(&mut self) -> f64 { + (self.next() >> 11) as f64 / ((1_u64 << 53) as f64) + } + fn point(&mut self) -> Vec3 { + Vec3::new(self.scalar() * 20. - 10., self.scalar() * 20. - 10., self.scalar() * 20. - 10.) + } +} + +#[test] +fn seeded_bvh_vs_brute_force_closest_and_any_hit() { + let mut seed = Seed(0x1368_0001); + for _ in 0..16 { + let triangles = (0..64).map(|_| Triangle::new([seed.point(), seed.point(), seed.point()]).unwrap()).collect::>(); + let bvh = build(triangles.clone(), BuildLimits { leaf_size: 2, ..Default::default() }, 7); + for _ in 0..128 { + let r = ray(seed.point(), seed.point()); + let expected = brute(&triangles, &r); + assert_eq!(closest(&bvh, &r), expected); + let any = bvh.any_hit(&r, &mut WorkBudget::new(MAX_WORK).unwrap(), &CancelToken::default()).unwrap(); + assert_eq!(any, expected.is_some()); + } + } +} + +#[test] +fn seeded_hostile_float_admission_never_publishes_nonfinite_geometry() { + let mut seed = Seed(0x1368_badd); + for _ in 0..2048 { + let value = f64::from_bits(seed.next()); + let p = Vec3::new(value, 0., 0.); + let accepted = value.is_finite() && value.abs() <= MAX_COORDINATE_MM; + assert_eq!(Ray::new(p, Vec3::Z, 0., 1.).is_ok(), accepted); + assert_eq!(Triangle::new([p; 3]).is_ok(), accepted); + } +} diff --git a/crates/ui-egui/src/agent_chat/agents.rs b/crates/ui-egui/src/agent_chat/agents.rs index 865f7c47a..d2a65d198 100644 --- a/crates/ui-egui/src/agent_chat/agents.rs +++ b/crates/ui-egui/src/agent_chat/agents.rs @@ -1,5 +1,5 @@ //! The agents the chat can use: the installed ones it finds by itself (Claude Code, Codex, -//! Gemini CLI, OpenCode, …) and the ones the user adds (another ACP command, or an +//! Antigravity, OpenCode, …) and the ones the user adds (another ACP command, or an //! OpenAI-compatible endpoint such as Ollama, LM Studio or OpenAI). Also the permission modes. //! Preferences only: no design data, no keys (those are in the system keychain). diff --git a/crates/ui-egui/src/agent_chat/discover.rs b/crates/ui-egui/src/agent_chat/discover.rs index 3b028ca24..07bfa6a36 100644 --- a/crates/ui-egui/src/agent_chat/discover.rs +++ b/crates/ui-egui/src/agent_chat/discover.rs @@ -24,6 +24,11 @@ pub struct Known { pub config_dir_var: Option<(&'static str, &'static str)>, /// Variables holding a key it uses instead of a login. pub key_vars: &'static [&'static str], + /// Retired by its maker: still used when it is installed, never offered for install. + pub retired: bool, + /// Whether `--version` prints its version. Antigravity's server prints its build date and takes + /// seconds to start, so it is not asked. + pub reports_version: bool, } /// The agents shown in the picker. The first one found is the default. @@ -37,6 +42,8 @@ pub const KNOWN: &[Known] = &[ credentials: Some(".claude/.credentials.json"), config_dir_var: Some(("CLAUDE_CONFIG_DIR", ".credentials.json")), key_vars: &["ANTHROPIC_API_KEY"], + retired: false, + reports_version: true, }, Known { id: "codex", @@ -47,7 +54,25 @@ pub const KNOWN: &[Known] = &[ credentials: Some(".codex/auth.json"), config_dir_var: Some(("CODEX_HOME", "auth.json")), key_vars: &["OPENAI_API_KEY", "CODEX_API_KEY"], + retired: false, + reports_version: true, }, + // Google's `agy` command line has no ACP mode; its ACP server is a separate download that the + // ACP registry lists (`agy_acp_server.par`, `agy_acp_server.exe` on Windows). + Known { + id: "antigravity", + name: "Google Antigravity", + programs: &["agy_acp_server.par", "agy_acp_server"], + args: &[], + install: "download the Antigravity ACP server for your system (see agentclientprotocol.com/registry), unzip it and put agy_acp_server.par on your PATH", + credentials: Some(".gemini/antigravity-acp/acp_token.json"), + config_dir_var: None, + key_vars: &["GEMINI_API_KEY"], + retired: false, + reports_version: false, + }, + // Google retired it on 18 June 2026 in favour of Antigravity (#1790). Enterprise licences may + // still work, so an installed one is found, but nobody is sent to install it. Known { id: "gemini", name: "Gemini CLI", @@ -57,6 +82,8 @@ pub const KNOWN: &[Known] = &[ credentials: Some(".gemini/oauth_creds.json"), config_dir_var: None, key_vars: &["GEMINI_API_KEY", "GOOGLE_API_KEY"], + retired: true, + reports_version: true, }, Known { id: "opencode", @@ -67,6 +94,8 @@ pub const KNOWN: &[Known] = &[ credentials: Some(".local/share/opencode/auth.json"), config_dir_var: None, key_vars: &[], + retired: false, + reports_version: true, }, Known { id: "grok", @@ -77,6 +106,8 @@ pub const KNOWN: &[Known] = &[ credentials: Some(".grok/auth.json"), config_dir_var: None, key_vars: &["XAI_API_KEY"], + retired: false, + reports_version: true, }, Known { id: "copilot", @@ -87,6 +118,8 @@ pub const KNOWN: &[Known] = &[ credentials: None, config_dir_var: None, key_vars: &["GH_TOKEN", "GITHUB_TOKEN"], + retired: false, + reports_version: true, }, Known { id: "qwen", @@ -97,6 +130,8 @@ pub const KNOWN: &[Known] = &[ credentials: Some(".qwen/oauth_creds.json"), config_dir_var: None, key_vars: &["DASHSCOPE_API_KEY"], + retired: false, + reports_version: true, }, Known { id: "goose", @@ -107,6 +142,8 @@ pub const KNOWN: &[Known] = &[ credentials: None, config_dir_var: None, key_vars: &[], + retired: false, + reports_version: true, }, ]; @@ -292,19 +329,24 @@ fn login_of(k: &Known, home: Option<&Path>) -> Login { /// Look for every known agent. Blocking (each probe has a time limit): run it off the UI thread. pub fn detect() -> Detection { + detect_in(&search_dirs(), home().as_deref()) +} + +fn detect_in(dirs: &[PathBuf], home: Option<&Path>) -> Detection { let t0 = Instant::now(); - let dirs = search_dirs(); - let home = home(); let mut d = Detection::default(); for k in KNOWN { - let Some(path) = k.programs.iter().find_map(|p| find_in(p, &dirs)) else { - d.missing.push(Missing { id: k.id, name: k.name, install: k.install }); + let Some(path) = k.programs.iter().find_map(|p| find_in(p, dirs)) else { + if !k.retired { + d.missing.push(Missing { id: k.id, name: k.name, install: k.install }); + } continue; }; - let login = login_of(k, home.as_deref()); + let login = login_of(k, home); let mut argv = vec![path.to_string_lossy().into_owned()]; argv.extend(k.args.iter().map(|a| a.to_string())); - d.found.push(Found { id: k.id, name: k.name, version: version(&path, Duration::from_secs(3)), argv, login }); + let version = if k.reports_version { version(&path, Duration::from_secs(3)) } else { None }; + d.found.push(Found { id: k.id, name: k.name, version, argv, login }); } d.took_ms = u64::try_from(t0.elapsed().as_millis()).unwrap_or(u64::MAX); d @@ -376,6 +418,14 @@ mod tests { if std::env::var_os("XAI_API_KEY").is_none() { assert_eq!(login_of(grok, Some(&home)), Login::NotLoggedIn); } + // Antigravity's server keeps its own login, apart from the retired Gemini CLI's. + let agy = KNOWN.iter().find(|k| k.id == "antigravity").unwrap(); + if std::env::var_os("GEMINI_API_KEY").is_none() { + assert_eq!(login_of(agy, Some(&home)), Login::NotLoggedIn, "the Gemini CLI's file is not its login"); + } + std::fs::create_dir_all(home.join(".gemini/antigravity-acp")).unwrap(); + std::fs::write(home.join(".gemini/antigravity-acp/acp_token.json"), "not credential data").unwrap(); + assert_eq!(login_of(agy, Some(&home)), Login::LooksLoggedIn); std::fs::create_dir_all(home.join(".grok")).unwrap(); // Discovery checks only for the file; it never needs to parse the user's tokens. std::fs::write(home.join(".grok/auth.json"), "not credential data").unwrap(); @@ -383,6 +433,42 @@ mod tests { let _ = std::fs::remove_dir_all(home); } + /// Google retired the Gemini CLI (#1790): one that is installed is still found, but nobody is + /// told to install it. Antigravity's ACP server is offered, and found under its file name. + #[test] + #[cfg(unix)] + fn a_retired_agent_is_found_but_not_offered_and_antigravity_is() { + use std::os::unix::fs::PermissionsExt; + let root = std::env::temp_dir().join(format!("sc-agent-retired-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let run = |name: &str, body: &str| { + let path = root.join(name); + std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + }; + let ids = |d: &Detection| (d.found.iter().map(|f| f.id).collect::>(), d.missing.iter().map(|m| m.id).collect::>()); + + let none = detect_in(std::slice::from_ref(&root), None); + let (found, missing) = ids(&none); + assert!(found.is_empty()); + assert!(missing.contains(&"antigravity") && !missing.contains(&"gemini"), "{missing:?}"); + let hint = none.missing.iter().find(|m| m.id == "antigravity").map(|m| m.install).unwrap_or_default(); + assert!(hint.contains("agy_acp_server.par") && !hint.contains("npm"), "{hint}"); + + run("gemini", "echo gemini 0.64.0"); + // A server that would take seconds to answer `--version`, which Antigravity is never asked. + run("agy_acp_server.par", "sleep 30"); + let both = detect_in(std::slice::from_ref(&root), None); + let (found, missing) = ids(&both); + assert_eq!(found, ["antigravity", "gemini"]); + assert!(!missing.contains(&"antigravity") && !missing.contains(&"gemini"), "{missing:?}"); + let agy = both.found.iter().find(|f| f.id == "antigravity"); + assert_eq!(agy.map(|f| f.version.clone()), Some(None), "its --version is a build date, not asked"); + assert_eq!(agy.and_then(|f| f.argv.get(1)), None, "the registry starts it without arguments"); + assert!(both.took_ms < 5000, "Antigravity's server was started to read a version"); + let _ = std::fs::remove_dir_all(root); + } + #[test] fn every_known_agent_has_a_program_and_an_install_hint() { for k in KNOWN { diff --git a/crates/ui-egui/src/agent_chat/markdown.rs b/crates/ui-egui/src/agent_chat/markdown.rs new file mode 100644 index 000000000..62710c5fd --- /dev/null +++ b/crates/ui-egui/src/agent_chat/markdown.rs @@ -0,0 +1,395 @@ +//! A small Markdown reader for assistant replies: paragraphs, headings, lists, quotes, fenced +//! code, rules, and bold, italic, code and link spans. Tables are kept as preformatted text. +//! +//! It takes untrusted text and never fails: anything it does not understand stays text, and the +//! amount of work and output is bounded. + +/// Longest input parsed; the rest is ignored. +pub const MAX_INPUT: usize = 256 * 1024; +/// Most blocks produced. +pub const MAX_BLOCKS: usize = 4000; +/// Longest link target kept. +const MAX_URL: usize = 2048; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Span { + Text(String), + Bold(String), + Italic(String), + Code(String), + /// A link with an `http` or `https` target; any other target is shown as its label only. + Link { + label: String, + url: String, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Block { + Paragraph(Vec), + Heading { + level: u8, + spans: Vec, + }, + Code { + lang: String, + text: String, + }, + List { + ordered: bool, + start: u64, + items: Vec>, + }, + Quote(Vec), + /// Preformatted text (tables). + Pre(String), + Rule, +} + +/// Parse `src` into blocks. +pub fn parse(src: &str) -> Vec { + let src = cut(src, MAX_INPUT); + let lines: Vec<&str> = src.lines().collect(); + let mut out: Vec = Vec::new(); + let mut i = 0; + let mut para: Vec<&str> = Vec::new(); + macro_rules! flush { + () => { + if !para.is_empty() { + out.push(Block::Paragraph(spans(¶.join(" ")))); + para.clear(); + } + }; + } + while i < lines.len() && out.len() < MAX_BLOCKS { + let line = lines[i]; + let t = line.trim_start(); + if let Some(fence) = fence_of(t) { + flush!(); + let lang = t[fence.len()..].trim().to_string(); + let mut body = Vec::new(); + i += 1; + while i < lines.len() && !lines[i].trim_start().starts_with(&fence) { + body.push(lines[i]); + i += 1; + } + i += 1; + out.push(Block::Code { lang, text: body.join("\n") }); + continue; + } + if t.is_empty() { + flush!(); + i += 1; + continue; + } + if is_rule(t) { + flush!(); + out.push(Block::Rule); + i += 1; + continue; + } + if let Some((level, rest)) = heading(t) { + flush!(); + out.push(Block::Heading { level, spans: spans(rest) }); + i += 1; + continue; + } + if t.starts_with('|') { + flush!(); + let mut rows = Vec::new(); + while i < lines.len() && lines[i].trim_start().starts_with('|') { + rows.push(lines[i].trim_end()); + i += 1; + } + out.push(Block::Pre(rows.join("\n"))); + continue; + } + if let Some(rest) = t.strip_prefix('>') { + flush!(); + let mut q = vec![rest.trim()]; + i += 1; + while i < lines.len() && lines[i].trim_start().starts_with('>') { + q.push(lines[i].trim_start()[1..].trim()); + i += 1; + } + out.push(Block::Quote(spans(&q.join(" ")))); + continue; + } + if let Some((ordered, n, rest)) = list_item(t) { + flush!(); + let mut items = vec![spans(rest)]; + i += 1; + while i < lines.len() { + let l = lines[i].trim_start(); + match list_item(l) { + Some((o, _, r)) if o == ordered => { + items.push(spans(r)); + i += 1; + } + // A wrapped line of the previous item. + None if !l.is_empty() && lines[i].starts_with(' ') && fence_of(l).is_none() && !l.starts_with('|') => { + if let Some(last) = items.last_mut() { + last.push(Span::Text(" ".into())); + last.extend(spans(l)); + } + i += 1; + } + _ => break, + } + if items.len() >= MAX_BLOCKS { + break; + } + } + out.push(Block::List { ordered, start: n, items }); + continue; + } + para.push(t); + i += 1; + } + flush!(); + out +} + +fn cut(s: &str, max: usize) -> &str { + if s.len() <= max { + return s; + } + let mut e = max; + while e > 0 && !s.is_char_boundary(e) { + e -= 1; + } + &s[..e] +} + +fn fence_of(t: &str) -> Option { + let c = t.chars().next().filter(|c| *c == '`' || *c == '~')?; + let n = t.chars().take_while(|x| *x == c).count(); + (n >= 3).then(|| c.to_string().repeat(n)) +} + +fn is_rule(t: &str) -> bool { + let s: String = t.chars().filter(|c| !c.is_whitespace()).collect(); + s.len() >= 3 && (s.chars().all(|c| c == '-') || s.chars().all(|c| c == '*') || s.chars().all(|c| c == '_')) +} + +fn heading(t: &str) -> Option<(u8, &str)> { + let n = t.chars().take_while(|c| *c == '#').count(); + if (1..=6).contains(&n) && t[n..].starts_with(' ') { Some((n as u8, t[n..].trim())) } else { None } +} + +fn list_item(t: &str) -> Option<(bool, u64, &str)> { + for m in ["- ", "* ", "+ "] { + if let Some(r) = t.strip_prefix(m) { + return Some((false, 1, r.trim())); + } + } + let digits = t.chars().take_while(char::is_ascii_digit).count(); + if (1..=9).contains(&digits) { + let rest = &t[digits..]; + if let Some(r) = rest.strip_prefix(". ").or_else(|| rest.strip_prefix(") ")) { + return Some((true, t[..digits].parse().unwrap_or(1), r.trim())); + } + } + None +} + +/// Inline spans of `s`. +pub fn spans(s: &str) -> Vec { + let c: Vec = s.chars().collect(); + let mut out: Vec = Vec::new(); + let mut text = String::new(); + let mut i = 0; + fn flush(out: &mut Vec, text: &mut String) { + if !text.is_empty() { + out.push(Span::Text(std::mem::take(text))); + } + } + while i < c.len() { + let rest = &c[i..]; + // Inline code. + if c[i] == '`' { + let n = rest.iter().take_while(|x| **x == '`').count(); + if let Some(end) = find_run(&c, i + n, '`', n) { + flush(&mut out, &mut text); + out.push(Span::Code(c[i + n..end].iter().collect::().trim().to_string())); + i = end + n; + continue; + } + } + // Bold. + if (rest.starts_with(&['*', '*']) || rest.starts_with(&['_', '_'])) && rest.len() > 4 { + let d = c[i]; + if let Some(end) = find_pair(&c, i + 2, d) + && end > i + 2 + { + flush(&mut out, &mut text); + out.push(Span::Bold(c[i + 2..end].iter().collect())); + i = end + 2; + continue; + } + } + // Italic (not inside words for `_`, so snake_case stays text). + if (c[i] == '*' || (c[i] == '_' && (i == 0 || !c[i - 1].is_alphanumeric()))) && rest.len() > 2 && !rest[1].is_whitespace() { + let d = c[i]; + let closes = |j: &usize| c[*j] == d && !c[*j - 1].is_whitespace() && (d == '*' || c.get(*j + 1).is_none_or(|n| !n.is_alphanumeric())); + if let Some(end) = (i + 1..c.len()).find(closes) + && end > i + 1 + { + flush(&mut out, &mut text); + out.push(Span::Italic(c[i + 1..end].iter().collect())); + i = end + 1; + continue; + } + } + // Link. + if c[i] == '[' + && let Some(close) = c[i + 1..].iter().position(|x| *x == ']').map(|p| p + i + 1) + && c.get(close + 1) == Some(&'(') + && let Some(end) = c[close + 2..].iter().position(|x| *x == ')').map(|p| p + close + 2) + { + let label: String = c[i + 1..close].iter().collect(); + let url: String = c[close + 2..end].iter().collect::().trim().to_string(); + flush(&mut out, &mut text); + let lower = url.to_ascii_lowercase(); + let web = lower.starts_with("https://") || lower.starts_with("http://"); + if web && url.len() <= MAX_URL && !url.chars().any(|ch| ch.is_whitespace() || ch.is_control()) { + out.push(Span::Link { label, url }); + } else { + out.push(Span::Text(label)); + } + i = end + 1; + continue; + } + // A backslash escapes the next marker. + if c[i] == '\\' && c.get(i + 1).is_some_and(|n| "\\`*_[]()#-".contains(*n)) { + text.push(c[i + 1]); + i += 2; + continue; + } + text.push(c[i]); + i += 1; + } + flush(&mut out, &mut text); + out +} + +/// The index of the next run of exactly `n` `ch` at or after `from`. +fn find_run(c: &[char], from: usize, ch: char, n: usize) -> Option { + let mut j = from; + while j < c.len() { + if c[j] == ch { + let run = c[j..].iter().take_while(|x| **x == ch).count(); + if run == n { + return Some(j); + } + j += run; + } else { + j += 1; + } + } + None +} + +fn find_pair(c: &[char], from: usize, d: char) -> Option { + (from..c.len().saturating_sub(1)).find(|&j| c[j] == d && c[j + 1] == d) +} + +/// The plain text of spans, for copying and for exports. +pub fn plain(spans: &[Span]) -> String { + spans + .iter() + .map(|s| match s { + Span::Text(t) | Span::Bold(t) | Span::Italic(t) | Span::Code(t) => t.clone(), + Span::Link { label, url } => format!("{label} ({url})"), + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn t(s: &str) -> Span { + Span::Text(s.into()) + } + + #[test] + fn blocks() { + let md = "# Title\n\nSome *emphasis* and **bold** with `code`.\nSecond line.\n\n- one\n- two\n wrapped\n\n1. a\n2. b\n\n> quoted\n\n---\n\n```rust\nlet x = 1;\n```\n\n| a | b |\n|---|---|\n| 1 | 2 |\n"; + let b = parse(md); + assert_eq!(b[0], Block::Heading { level: 1, spans: vec![t("Title")] }); + assert_eq!( + b[1], + Block::Paragraph(vec![ + t("Some "), + Span::Italic("emphasis".into()), + t(" and "), + Span::Bold("bold".into()), + t(" with "), + Span::Code("code".into()), + t(". Second line.") + ]) + ); + assert_eq!(b[2], Block::List { ordered: false, start: 1, items: vec![vec![t("one")], vec![t("two"), t(" "), t("wrapped")]] }); + assert_eq!(b[3], Block::List { ordered: true, start: 1, items: vec![vec![t("a")], vec![t("b")]] }); + assert_eq!(b[4], Block::Quote(vec![t("quoted")])); + assert_eq!(b[5], Block::Rule); + assert_eq!(b[6], Block::Code { lang: "rust".into(), text: "let x = 1;".into() }); + assert!(matches!(&b[7], Block::Pre(s) if s.lines().count() == 3)); + assert_eq!(b.len(), 8); + } + + #[test] + fn snake_case_and_stray_markers_stay_text() { + assert_eq!(spans("use set_parameter and body_topology"), vec![t("use set_parameter and body_topology")]); + assert_eq!(spans("2 * 3 * 4"), vec![t("2 * 3 * 4")]); + assert_eq!(spans("unclosed **bold"), vec![t("unclosed **bold")]); + assert_eq!(spans("a `b"), vec![t("a `b")]); + assert_eq!(spans(r"\*not italic\*"), vec![t("*not italic*")]); + } + + #[test] + fn only_web_links_are_links() { + assert_eq!(spans("[docs](https://example.com/a)"), vec![Span::Link { label: "docs".into(), url: "https://example.com/a".into() }]); + for bad in ["[x](javascript:alert(1))", "[x](file:///etc/passwd)", "[x](ftp://a)", "[x](/relative)", "[x](https://a b)"] { + let s = spans(bad); + assert_eq!(s[0], t("x"), "{bad}"); + assert!(!s.iter().any(|x| matches!(x, Span::Link { .. })), "{bad}"); + } + } + + #[test] + fn code_blocks_keep_everything() { + let b = parse("```\n# not a heading\n- not a list\n```"); + assert_eq!(b, vec![Block::Code { lang: String::new(), text: "# not a heading\n- not a list".into() }]); + // An unterminated fence runs to the end. + let b = parse("```\nstill code"); + assert_eq!(b, vec![Block::Code { lang: String::new(), text: "still code".into() }]); + } + + #[test] + fn hostile_input_is_bounded_and_never_panics() { + let mut seed = 0x1234_5678_u32; + let alphabet: Vec = "*_`[]()#->|\\~ \n\t1.ä🌍a".chars().collect(); + for _ in 0..300 { + let mut s = String::new(); + for _ in 0..200 { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + s.push(alphabet[(seed >> 16) as usize % alphabet.len()]); + } + let _ = parse(&s); + } + let huge = "- x\n".repeat(MAX_INPUT); + let blocks = parse(&huge); + assert!(blocks.len() <= MAX_BLOCKS); + let nested = "*".repeat(100_000); + let _ = parse(&nested); + let _ = parse(&"[".repeat(100_000)); + let _ = parse(&"`a".repeat(50_000)); + } + + #[test] + fn plain_text_of_spans() { + assert_eq!(plain(&spans("**a** [b](https://c.d) `e`")), "a b (https://c.d) e"); + } +} diff --git a/crates/ui-egui/src/agent_chat/markdown_view.rs b/crates/ui-egui/src/agent_chat/markdown_view.rs new file mode 100644 index 000000000..2d8d6ebfb --- /dev/null +++ b/crates/ui-egui/src/agent_chat/markdown_view.rs @@ -0,0 +1,138 @@ +//! An assistant's text as the panel shows it: Markdown (paragraphs, headings, lists, quotes, +//! fenced code, bold, italic, code, links), parsed by [`super::markdown`]. +//! +//! Parsing and laying out a long reply every frame would show in the frame time while it streams, +//! so the parsed blocks are kept per conversation item and parsed again only when its text +//! changes. + +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use super::markdown::{self, Block, Span}; +use egui::text::{LayoutJob, TextFormat}; +use egui::{Color32, FontId, Margin, RichText, Stroke, vec2}; + +use crate::i18n::tr; +use crate::theme::Tokens; + +/// The parsed blocks of `src`, kept in the context's temporary memory under `slot` (the item's +/// index) and replaced when the text changes. +fn blocks(ctx: &egui::Context, slot: usize, src: &str) -> Arc> { + let mut h = std::collections::hash_map::DefaultHasher::new(); + src.hash(&mut h); + let key = h.finish(); + let id = egui::Id::new(("agent_chat_markdown", slot)); + if let Some((k, b)) = ctx.data(|d| d.get_temp::<(u64, Arc>)>(id)) + && k == key + { + return b; + } + let parsed = Arc::new(markdown::parse(src)); + ctx.data_mut(|d| d.insert_temp(id, (key, parsed.clone()))); + parsed +} + +fn job(ui: &egui::Ui, spans: &[Span], size: f32, color: Color32) -> LayoutJob { + let t = Tokens::get(); + let mut j = LayoutJob::default(); + j.wrap.max_width = ui.available_width(); + let base = FontId::proportional(size); + for s in spans { + let plain = TextFormat { font_id: base.clone(), color, ..Default::default() }; + match s { + Span::Text(x) => j.append(x, 0.0, plain), + Span::Bold(x) => j.append(x, 0.0, TextFormat { color: t.text, ..plain }), + Span::Italic(x) => j.append(x, 0.0, TextFormat { italics: true, ..plain }), + Span::Code(x) => j.append(x, 0.0, TextFormat { font_id: FontId::monospace(size - 1.0), background: t.field, ..plain }), + Span::Link { label, .. } => j.append(label, 0.0, TextFormat { color: t.accent, underline: Stroke::new(1.0, t.accent), ..plain }), + } + } + j +} + +/// The host of a web address: `example.com` for `https://example.com/a?b`. +fn host(url: &str) -> &str { + let rest = url.split_once("://").map_or(url, |(_, r)| r); + rest.split(['/', '?', '#']).next().unwrap_or(rest) +} + +/// A paragraph's text, then its links as buttons (a laid-out text cannot be clicked in parts). +fn spans(ui: &mut egui::Ui, spans: &[Span], size: f32, color: Color32) { + ui.add(egui::Label::new(job(ui, spans, size, color)).selectable(true).wrap()); + let links: Vec<(&str, &str)> = + spans.iter().filter_map(|s| if let Span::Link { label, url } = s { Some((label.as_str(), url.as_str())) } else { None }).collect(); + if !links.is_empty() { + ui.horizontal_wrapped(|ui| { + for (label, url) in links { + // The text above already shows the label; the button says where it goes. + let to = format!("↗ {}", host(url)); + ui.hyperlink_to(RichText::new(to).size(size - 1.0), url).on_hover_text(format!("{label}: {url}")); + } + }); + } +} + +/// Draw `src` as Markdown. `slot`: the conversation item it belongs to. +pub fn show(ui: &mut egui::Ui, slot: usize, src: &str) { + let t = Tokens::get(); + let size = 13.0; + let parsed = blocks(ui.ctx(), slot, src); + for block in parsed.iter() { + match block { + Block::Paragraph(s) => spans(ui, s, size, t.text), + Block::Heading { level, spans: s } => { + let size = match level { + 1 => 17.0, + 2 => 15.0, + _ => 14.0, + }; + ui.add_space(4.0); + ui.add(egui::Label::new(RichText::new(markdown::plain(s)).size(size).strong().color(t.text)).selectable(true).wrap()); + } + Block::Code { text, .. } => { + egui::Frame::NONE.fill(t.field).corner_radius(4.0).inner_margin(Margin::same(6)).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.add(egui::Label::new(RichText::new(text).monospace().size(size - 1.0).color(t.text)).selectable(true).wrap()); + if ui.small_button(tr("ui.agent_chat_copy")).clicked() { + ui.ctx().copy_text(text.clone()); + } + }); + } + Block::List { ordered, start, items } => { + for (i, item) in items.iter().enumerate() { + ui.horizontal_top(|ui| { + let mark = if *ordered { format!("{}.", start.saturating_add(i as u64)) } else { "•".to_string() }; + ui.label(RichText::new(mark).size(size).color(t.text_dim)); + ui.vertical(|ui| spans(ui, item, size, t.text)); + }); + } + } + Block::Quote(s) => { + ui.horizontal_top(|ui| { + let (bar, _) = ui.allocate_exact_size(vec2(3.0, 16.0), egui::Sense::hover()); + ui.painter().rect_filled(bar, 1.0, t.border); + ui.vertical(|ui| spans(ui, s, size, t.text_dim)); + }); + } + Block::Pre(text) => { + egui::ScrollArea::horizontal().id_salt(("agent_chat_pre", slot, text.len())).show(ui, |ui| { + ui.add(egui::Label::new(RichText::new(text).monospace().size(size - 2.0).color(t.text)).selectable(true)); + }); + } + Block::Rule => { + ui.separator(); + } + } + ui.add_space(3.0); + } +} + +#[cfg(test)] +mod tests { + #[test] + fn a_link_button_names_the_host() { + assert_eq!(super::host("https://example.com/a?b#c"), "example.com"); + assert_eq!(super::host("http://localhost:8080/x"), "localhost:8080"); + assert_eq!(super::host("https://a.b"), "a.b"); + } +} diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index e4be8689c..2734ccfc8 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -1,5 +1,5 @@ //! Agent chat: a side panel that talks to a coding agent the user already has (Claude Code, -//! Codex, Gemini CLI, OpenCode, …) over the Agent Client Protocol, and gives that agent +//! Codex, Antigravity, OpenCode, …) over the Agent Client Protocol, and gives that agent //! SolidCraft's MCP server, bridged to this window, as its way to read and change the open design //! (docs/agent-chat.md, docs/design/in-app-agent-chat.md). //! @@ -26,6 +26,8 @@ pub mod backend; #[cfg(not(target_arch = "wasm32"))] pub mod discover; pub mod gate; +mod markdown; +mod markdown_view; mod panel; #[cfg(not(target_arch = "wasm32"))] mod process; diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 087a26dc0..ad70ac132 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -639,8 +639,11 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { }); } Item::Agent { thought, text } => { - let rt = if *thought { RichText::new(text).italics().color(t.text_dim) } else { RichText::new(text).color(t.text) }; - ui.add(egui::Label::new(rt).selectable(true).wrap()); + if *thought { + ui.add(egui::Label::new(RichText::new(text).italics().color(t.text_dim)).selectable(true).wrap()); + } else { + super::markdown_view::show(ui, n, text); + } } Item::Tool { title, kind, status, output, .. } => { tool_card(ui, n, title, kind, *status, output.as_deref()); diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 52eb2a90f..fb380f0f1 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -756,3 +756,22 @@ done disconnect(&mut app); let _ = std::fs::remove_dir_all(&dir); } + +/// An agent's text is Markdown: a code block shows with its Copy button and a link is a button +/// of its own, instead of the raw markers. +#[test] +fn an_agents_markdown_is_drawn_as_blocks() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.agent_chat", json!({"open": true})); + h.frames(3); + h.app.agent_chat.items.push(Item::Agent { + thought: false, + text: "# Result\n\n- a **bold** point\n- another\n\n```\nlet x = 1;\n```\n\nSee [the docs](https://example.com/a).".into(), + }); + h.frames(3); + assert!(h.widget("Copy").is_some(), "the code block has its Copy button"); + assert!(h.widget("↗ example.com").is_some(), "the link is a button that names where it goes"); + // A hostile reply draws too (no panic, bounded work). + h.app.agent_chat.items.push(Item::Agent { thought: false, text: "*".repeat(50_000) + &"[".repeat(5_000) + &"`a".repeat(5_000) }); + h.frames(3); +} diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 39df45a20..ea104ed9b 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -10,6 +10,13 @@ #[path = "occurrence_ui_tests.rs"] mod occurrence_ui_tests; +#[path = "browser_model.rs"] +mod model; + +#[cfg(test)] +#[path = "browser_model_tests.rs"] +mod model_tests; + use crate::icons::glyphs::badge; use std::collections::BTreeSet; @@ -42,6 +49,8 @@ pub fn drawn_occurrences() -> Vec<(Vec, String, Rect, bool)> { /// Browser state kept between frames. #[derive(Default)] pub struct TreeState { + /// Geometry and assembly queries, independent of the camera, selection and row visibility. + model: Option, /// Folders closed by the user (keys like `c0/bodies`). pub collapsed: BTreeSet, /// Folders opened by the user (folders that start closed). @@ -547,7 +556,60 @@ fn browser_contents(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions) { browser_rows(app, ui, acts); } +fn prepare_model(app: &mut SolveApp) { + if app.tree.model.as_ref().is_none_or(|model| !model.matches(&app.session)) { + app.tree.model = Some(model::Model::new(&app.session)); + } +} + +fn model_placement(app: &mut SolveApp, path: &[u64]) -> Option> { + prepare_model(app); + app.tree.model.as_mut()?.placement(&app.session, path) +} + +fn model_children(app: &SolveApp, component: u64) -> Vec { + match app.tree.model.as_ref().filter(|model| model.matches(&app.session)) { + Some(model) => model.children.get(&component).cloned().unwrap_or_default(), + None => app.session.doc.occurrences.iter().filter(|o| o.parent == component).map(|o| o.id).collect(), + } +} + +fn model_body_indices(app: &SolveApp, component: u64) -> Vec { + match app.tree.model.as_ref().filter(|model| model.matches(&app.session)) { + Some(model) => model.bodies.get(&component).cloned().unwrap_or_default(), + None => app + .session + .model + .state() + .bodies + .iter() + .enumerate() + .filter(|(_, b)| app.session.doc.model_body_component(b) == component) + .map(|(i, _)| i) + .collect(), + } +} + +fn model_feature_indices(app: &SolveApp, component: u64, sketches: bool) -> Vec { + match app.tree.model.as_ref().filter(|model| model.matches(&app.session)) { + Some(model) => (if sketches { &model.sketches } else { &model.planes }).get(&component).cloned().unwrap_or_default(), + None => app + .session + .doc + .features + .iter() + .enumerate() + .filter_map(|(i, f)| { + let kind = + if sketches { matches!(f.kind, FeatureKind::Sketch { .. }) } else { matches!(f.kind, FeatureKind::ConstructionPlane { .. }) }; + (f.component == component && kind).then_some(i) + }) + .collect(), + } +} + fn browser_rows(app: &mut SolveApp, ui: &mut egui::Ui, acts: &mut Actions) { + prepare_model(app); egui::ScrollArea::vertical() .auto_shrink([false, false]) .scroll_source(egui::scroll_area::ScrollSource { scroll_bar: true, mouse_wheel: true, ..egui::scroll_area::ScrollSource::NONE }) @@ -668,7 +730,7 @@ fn component_rows(app: &mut SolveApp, ui: &mut egui::Ui, id: u64, depth: usize, if id == 0 { crate::dialogs_assembly::browser_joints(app, ui, d); } - let children: Vec = app.session.doc.occurrences.iter().filter(|o| o.parent == id).map(|o| o.id).collect(); + let children = model_children(app, id); for occurrence in children { occurrence_rows(app, ui, vec![occurrence], d, acts); } @@ -681,7 +743,7 @@ fn occurrence_key(path: &[u64]) -> String { /// A placement, rather than a component definition: repeated child IDs remain distinct /// because their complete paths are the selection and row identity. fn occurrence_rows(app: &mut SolveApp, ui: &mut egui::Ui, path: Vec, depth: usize, acts: &mut Actions) { - let Ok(placement) = app.session.occurrence_placement(&path) else { return }; + let Some(placement) = model_placement(app, &path) else { return }; let key = occurrence_key(&path); let open = is_open(app, &key, true); let active = app.session.active_occurrence_path.as_deref() == Some(path.as_slice()) @@ -765,7 +827,7 @@ fn occurrence_rows(app: &mut SolveApp, ui: &mut egui::Ui, path: Vec, depth: for folder in ["bodies", "sketches", "construction"] { occurrence_folder_rows(app, ui, placement.component, &path, folder, depth + 1, acts); } - let children: Vec = app.session.doc.occurrences.iter().filter(|o| o.parent == placement.component).map(|o| o.id).collect(); + let children = model_children(app, placement.component); if path.len() < 64 { for occurrence in children { let mut child = path.clone(); @@ -1246,14 +1308,12 @@ fn entries(app: &SolveApp, comp: u64, folder: &str) -> Vec { let t = Tokens::get(); let doc = &app.session.doc; let sel = &app.session.selection; + let state = app.session.model.state(); match folder { - "bodies" => app - .session - .model - .state() - .bodies - .iter() - .filter(|b| doc.model_body_component(b) == comp && !app.session.body_removed_later(&b.name)) + "bodies" => model_body_indices(app, comp) + .into_iter() + .filter_map(|i| state.bodies.get(i)) + .filter(|b| !app.session.body_removed_later(&b.name)) .map(|b| Entry { key: b.name.clone(), row_key: format!("b:{}", b.name), @@ -1268,10 +1328,9 @@ fn entries(app: &SolveApp, comp: u64, folder: &str) -> Vec { bodies: vec![b.name.clone()], }) .collect(), - "sketches" => doc - .features - .iter() - .filter(|f| f.component == comp && matches!(f.kind, FeatureKind::Sketch { .. })) + "sketches" => model_feature_indices(app, comp, true) + .into_iter() + .filter_map(|i| doc.features.get(i)) .map(|f| { let active = app.session.active_sketch == Some(f.id); let lost = app.session.model.result(f.id).is_some_and(|result| result.error.is_some()) @@ -1297,10 +1356,9 @@ fn entries(app: &SolveApp, comp: u64, folder: &str) -> Vec { } }) .collect(), - _ => doc - .features - .iter() - .filter(|f| f.component == comp && matches!(f.kind, FeatureKind::ConstructionPlane { .. })) + _ => model_feature_indices(app, comp, false) + .into_iter() + .filter_map(|i| doc.features.get(i)) .map(|f| Entry { key: f.id.to_string(), row_key: format!("p:{}", f.id), @@ -1396,7 +1454,7 @@ fn folder_rows_at(app: &mut SolveApp, ui: &mut egui::Ui, comp: u64, path: Option let mut all = entries(app, comp, folder); let prefix = path.map(occurrence_key).unwrap_or_else(|| format!("c{comp}")); if let Some(path) = path { - let Ok(placement) = app.session.occurrence_placement(path) else { return }; + let Some(placement) = model_placement(app, path) else { return }; // Each row's placed body by its definition's name (a search per row was quadratic in a // component's bodies, every frame). let mut placed: std::collections::HashMap<&str, &_> = std::collections::HashMap::with_capacity(placement.bodies.len()); diff --git a/crates/ui-egui/src/browser_model.rs b/crates/ui-egui/src/browser_model.rs new file mode 100644 index 000000000..5505d8175 --- /dev/null +++ b/crates/ui-egui/src/browser_model.rs @@ -0,0 +1,64 @@ +//! Model-only browser queries, reused while navigating. Resolving a placement walks the +//! definition's bodies; doing that for every offscreen row and folder made large imports +//! quadratic on every frame. Keep the document and evaluated state alive with the index so +//! neither a new document nor a later allocation can accidentally reuse its answers. + +use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; + +use solidcraft_engine::Session; +use solidcraft_engine::doc::{Document, FeatureKind, Mat, ModelState}; +use solidcraft_engine::occurrences::OccurrencePlacement; + +pub(super) struct Model { + doc: Arc, + state: Arc, + pending_moves: BTreeMap, + pub bodies: HashMap>, + pub sketches: HashMap>, + pub planes: HashMap>, + pub children: HashMap>, + placements: HashMap, Option>>, +} + +impl Model { + pub fn new(session: &Session) -> Self { + let state = session.model.state(); + let mut bodies: HashMap> = HashMap::new(); + for (i, body) in state.bodies.iter().enumerate() { + bodies.entry(session.doc.model_body_component(body)).or_default().push(i); + } + let mut sketches: HashMap> = HashMap::new(); + let mut planes: HashMap> = HashMap::new(); + for (i, feature) in session.doc.features.iter().enumerate() { + let index = match feature.kind { + FeatureKind::Sketch { .. } => &mut sketches, + FeatureKind::ConstructionPlane { .. } => &mut planes, + _ => continue, + }; + index.entry(feature.component).or_default().push(i); + } + let mut children: HashMap> = HashMap::new(); + for occurrence in &session.doc.occurrences { + children.entry(occurrence.parent).or_default().push(occurrence.id); + } + Self { + doc: session.doc.clone(), + state, + pending_moves: session.pending_moves.clone(), + bodies, + sketches, + planes, + children, + placements: HashMap::new(), + } + } + + pub fn matches(&self, session: &Session) -> bool { + Arc::ptr_eq(&self.doc, &session.doc) && Arc::ptr_eq(&self.state, &session.model.state()) && self.pending_moves == session.pending_moves + } + + pub fn placement(&mut self, session: &Session, path: &[u64]) -> Option> { + self.placements.entry(path.to_vec()).or_insert_with(|| session.occurrence_placement(path).ok().map(Arc::new)).clone() + } +} diff --git a/crates/ui-egui/src/browser_model_tests.rs b/crates/ui-egui/src/browser_model_tests.rs new file mode 100644 index 000000000..8f4ceadc6 --- /dev/null +++ b/crates/ui-egui/src/browser_model_tests.rs @@ -0,0 +1,93 @@ +use std::sync::Arc; + +use serde_json::json; +use solidcraft_engine::Sel; + +use crate::scenario::Harness; + +fn fixture() -> (Harness, u64, u64) { + let mut h = Harness::new(); + let part = h.app.run("component.create", json!({"name":"Block"})).unwrap(); + let component = part["component"].as_u64().unwrap(); + let occurrence = part["occurrence"].as_u64().unwrap(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + (h, component, occurrence) +} + +#[test] +fn navigating_and_selecting_reuse_placements_but_rows_read_live_view_state() { + let (mut h, component, occurrence) = fixture(); + let first = super::model_placement(&mut h.app, &[occurrence]).unwrap(); + h.app.cam.yaw += 0.25; + h.app.run("select.set", json!({"items":[Sel::Body{name:"Body1".into()}]})).unwrap(); + h.app.session.visibility.hidden_bodies.push("Body1".into()); + h.app.ui.locked_bodies.push("Body1".into()); + let after = super::model_placement(&mut h.app, &[occurrence]).unwrap(); + assert!(Arc::ptr_eq(&first, &after), "view-only changes resolved the same placement again"); + let rows = super::entries(&h.app, component, "bodies"); + assert_eq!(rows.len(), 1); + assert!(rows[0].selected && rows[0].locked && !rows[0].visible); + h.frames(2); + assert!(Arc::ptr_eq(&after, &super::model_placement(&mut h.app, &[occurrence]).unwrap())); +} + +#[test] +fn pending_and_reverted_moves_replace_cached_transforms() { + let (mut h, _, occurrence) = fixture(); + let first = super::model_placement(&mut h.app, &[occurrence]).unwrap(); + h.app.run("occurrence.move", json!({"occurrence":occurrence,"translate":[20,0,0],"capture":false})).unwrap(); + let moved = super::model_placement(&mut h.app, &[occurrence]).unwrap(); + assert!(!Arc::ptr_eq(&first, &moved)); + assert!((solidcraft_engine::doc::apply_point(&moved.world, solidcraft_engine::geom::Vec3::ZERO).x - 20.0).abs() < 1e-9); + h.app.run("component.revert_position", json!({"occurrences":[occurrence]})).unwrap(); + let reverted = super::model_placement(&mut h.app, &[occurrence]).unwrap(); + assert!(!Arc::ptr_eq(&moved, &reverted)); + assert_eq!(first.world, reverted.world); +} + +#[test] +fn feature_indices_follow_component_edits_and_undo() { + let (mut h, component, _) = fixture(); + super::prepare_model(&mut h.app); + assert!(super::model_feature_indices(&h.app, 0, true).is_empty()); + h.app.run("sketch.create", json!({"plane":"XY", "name":"Root sketch"})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + super::prepare_model(&mut h.app); + assert_eq!(super::entries(&h.app, 0, "sketches")[0].label, "Root sketch"); + assert!(super::entries(&h.app, component, "sketches").is_empty()); + h.app.run("component.activate", json!({"component":component})).unwrap(); + h.app.run("sketch.create", json!({"plane":"YZ", "name":"Part sketch"})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + super::prepare_model(&mut h.app); + assert_eq!(super::entries(&h.app, component, "sketches")[0].label, "Part sketch"); + assert_eq!(super::entries(&h.app, 0, "sketches").len(), 1); + h.app.run("edit.undo", json!({})).unwrap(); + super::prepare_model(&mut h.app); + assert!(super::entries(&h.app, component, "sketches").is_empty()); + assert_eq!(super::entries(&h.app, 0, "sketches").len(), 1); +} + +#[test] +fn body_index_and_placements_follow_geometry_undo_and_document_identity() { + let (mut h, component, occurrence) = fixture(); + let first = super::model_placement(&mut h.app, &[occurrence]).unwrap(); + let copy = h.app.run("occurrence.copy", json!({"occurrence":occurrence,"translate":[50,0,0]})).unwrap()["occurrence"].as_u64().unwrap(); + let second = super::model_placement(&mut h.app, &[copy]).unwrap(); + assert_ne!(first.path, second.path); + assert_ne!(first.bodies[0].world, second.bodies[0].world); + assert_eq!(super::model_children(&h.app, 0), [occurrence, copy]); + h.app.run("component.activate", json!({"component":component})).unwrap(); + h.app.run("solid.box", json!({"length":2,"width":2,"height":2,"corner":[20,0,0]})).unwrap(); + let changed = super::model_placement(&mut h.app, &[occurrence]).unwrap(); + assert_eq!(changed.bodies.len(), 2); + assert_eq!(super::entries(&h.app, component, "bodies").len(), 2); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(super::model_placement(&mut h.app, &[occurrence]).unwrap().bodies.len(), 1); + assert_eq!(super::entries(&h.app, component, "bodies").len(), 1); + // A separate session can have the same revision and the same occurrence ids. + h.app.session = solidcraft_engine::Session::default(); + assert!(super::model_placement(&mut h.app, &[occurrence]).is_none()); + assert!(super::model_children(&h.app, 0).is_empty()); + assert!(super::entries(&h.app, component, "bodies").is_empty()); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 300a5d459..52c677f8b 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -522,8 +522,20 @@ fn value_box(ui: &mut egui::Ui, label: &str, value: &mut String, at: Pos2, selec }); } +/// How far (logical points) from an arrow's stem a press still takes the arrow. +const ARROW_STEM_REACH: f32 = 6.0; + +/// The distance from `p` to the segment from `a` to `b` on screen. +fn to_segment(p: Pos2, a: Pos2, b: Pos2) -> f32 { + let v = b - a; + let t = if v.length_sq() > 0.0 { ((p - a).dot(v) / v.length_sq()).clamp(0.0, 1.0) } else { 0.0 }; + p.distance(a + v * t) +} + /// A draggable arrow from `base` along `n` showing `l` (at least a short stub); dragging writes -/// the snapped length into `value`. Returns the tip's screen position. +/// the snapped length into `value`. The tip and the stem take the drag (#1740): pressed on the +/// stem, the arrow keeps its length until the pointer moves, and then moves with it as far as the +/// pointer does. Returns the tip's screen position. #[allow(clippy::too_many_arguments)] fn drag_arrow( ui: &mut egui::Ui, @@ -545,11 +557,28 @@ fn drag_arrow( proj.to_screen(base + n * shown) }; let mut ts = tip(l)?; - let r = ui.interact(egui::Rect::from_center_size(ts, vec2(20.0, 20.0)), id, egui::Sense::drag()); + let at_tip = egui::Rect::from_center_size(ts, vec2(20.0, 20.0)); + // Over the stem, the arrow answers where the pointer is. + let on_stem = ui.input(|i| i.pointer.hover_pos()).filter(|p| !at_tip.contains(*p) && to_segment(*p, bs, ts) <= ARROW_STEM_REACH); + let area = on_stem.map_or(at_tip, |p| egui::Rect::from_center_size(p, vec2(2.0 * ARROW_STEM_REACH, 2.0 * ARROW_STEM_REACH))); + let r = ui.interact(area, id, egui::Sense::drag()); + // How far along the arrow the press was short of its end: the drag keeps that gap. + let grab = id.with("stem grab"); + if r.drag_started() { + let gap = on_stem.zip(r.interact_pointer_pos()).and_then(|(_, p)| along(proj, p, base, n)).map(|v| v - l); + ui.data_mut(|d| { + if let Some(g) = gap.filter(|g| g.is_finite()) { + d.insert_temp(grab, g); + } else { + d.remove::(grab); + } + }); + } if r.dragged() && let Some(p) = r.interact_pointer_pos() && let Some(v) = along(proj, p, base, n) { + let v = v - ui.data(|d| d.get_temp::(grab)).unwrap_or(0.0); let free = ui.input(|i| i.modifiers.alt || i.modifiers.ctrl || i.modifiers.command); let step = snap_step(half_height); let mut v = if free { v } else { (v / step).round() * step }; diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index f7cb7ebe9..8601a3bb1 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -187,7 +187,7 @@ pub(crate) fn view_scene(app: &SolveApp, guides: solidcraft_engine::view::Guides } /// The grid and the origin's axes as the window shows them (the Grid and Origin switches). -fn window_guides(app: &SolveApp) -> solidcraft_engine::view::Guides { +pub(crate) fn window_guides(app: &SolveApp) -> solidcraft_engine::view::Guides { solidcraft_engine::view::Guides { grid: app.ui.show_grid && !crate::viewport::active_view(app).hide_grid, axes: app.origin_visible() } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 102191464..139e10a46 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -137,6 +137,11 @@ pub enum Kind { Thread { designation: String, length: String, + /// The last automatic size; a different value is a manual override. Keep automatic + /// features automatic when applying, even though their resolved size is visible. + suggested: Option, + /// The picks used for the suggestion, so an unchanged dialog does no geometry work. + of: Vec, }, /// A rib (one wall along open curves) or a web (a wall per curve). Rib { @@ -260,6 +265,7 @@ pub enum Kind { SaveMesh(crate::dialogs_save_mesh::SaveMesh), ViewDxf { dashed: bool, + tolerance: f64, }, /// Plastic features (`dialogs_plastic`). Plastic(crate::dialogs_plastic::Pl), @@ -528,9 +534,10 @@ impl Dialog { ), "solid.scale" => Dialog::new(Kind::Scale { factor: "2".into() }, vec![SelInput::new("Bodies", BODIES, true)]), "solid.offset_face" => Dialog::new(Kind::OffsetFaces { distance: "2 mm".into() }, vec![SelInput::new("Faces", PLANAR_FACES, true)]), - "solid.thread" => { - Dialog::new(Kind::Thread { designation: String::new(), length: String::new() }, vec![SelInput::new("Cylindrical face", FACES, false)]) - } + "solid.thread" => Dialog::new( + Kind::Thread { designation: String::new(), length: String::new(), suggested: None, of: Vec::new() }, + vec![SelInput::new("Cylindrical face", FACES, false)], + ), "material.assign" => Dialog::new(Kind::Material { index: 1 }, vec![SelInput::new("Bodies", BODIES, true)]), "inspect.section" => { Dialog::new(Kind::Section { offset: "0 mm".into(), flip: false }, vec![SelInput::new("Plane", PLANES | PLANAR_FACES, false)]) @@ -699,10 +706,30 @@ impl Dialog { { inp.items = default_profiles(s); } + d.sync_thread(s); d.advance(); Some(d) } + /// Resolve a newly selected face without replacing an authored size or changing the + /// document. Clearing the face also clears a suggestion that no longer applies. + fn sync_thread(&mut self, s: &Session) { + let Kind::Thread { designation, suggested, of, .. } = &mut self.kind else { return }; + if !designation.trim().is_empty() && suggested.as_deref() != Some(designation.as_str()) { + return; + } + let picks = self.inputs.first().map(|i| i.items.as_slice()).unwrap_or_default(); + if picks == of.as_slice() { + return; + } + *of = picks.to_vec(); + *suggested = picks.first().and_then(|sel| match sel { + Sel::Face { point, .. } => solidcraft_engine::doc::suggested_thread(&s.world_state(), *point).ok(), + _ => None, + }); + *designation = suggested.clone().unwrap_or_default(); + } + pub fn rename(feature: u64, name: &str) -> Dialog { Dialog::new(Kind::Rename { feature, name: name.to_string() }, vec![]) } @@ -945,6 +972,7 @@ impl Dialog { self.advance(); } self.error = None; + self.sync_thread(s); } /// Box selection result: replace (or add to) the active input. @@ -975,6 +1003,7 @@ impl Dialog { inp.items.push(x); } } + self.sync_thread(s); } } @@ -1711,6 +1740,7 @@ fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std:: } d.active = i; } + d.sync_thread(s); } /// Each live reference sits with the independent values it drives. @@ -2109,6 +2139,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { return; } auto_operation(app, &mut d); + d.sync_thread(&app.session); update_measure(app, &mut d); update_fill_cells(app, &mut d); // A refused OK's error is about the inputs it ran with (#641). Once a value (in the dialog, @@ -2749,22 +2780,23 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { enter |= field(ui, distance); ui.end_row(); } - Kind::Thread { designation, length } => { - // Fusion's order: Modeled, Full Length, then the size; a length only when not - // full. + Kind::Thread { designation, length, suggested, of } => { row_label(ui, "Modeled"); extra_check(ui, &mut d.extra, "modeled"); ui.end_row(); row_label(ui, "Full Length"); let mut full = length.trim().is_empty(); - if ui.checkbox(&mut full, "").changed() { + let response = ui.checkbox(&mut full, ""); + publish_row(&response); + if response.changed() { *length = if full { String::new() } else { "10 mm".into() }; } ui.end_row(); - row_label(ui, "Size"); - let r = ui.add(egui::TextEdit::singleline(designation).hint_text(tr("fits the face, e.g. M8"))); - enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); - ui.end_row(); + let (submitted, reset) = crate::dialogs_thread::rows(ui, designation, suggested); + enter |= submitted; + if reset { + of.clear(); + } if !full { row_label(ui, "Length"); enter |= field(ui, length); @@ -2948,7 +2980,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { Kind::Surface(k) => enter |= crate::dialogs_surface::rows(ui, k), Kind::SketchModify(k) => enter |= crate::sketch_modify_ui::rows(ui, k), Kind::SaveMesh(k) => enter |= crate::dialogs_save_mesh::rows(app, ui, k), - Kind::ViewDxf { dashed } => crate::dialogs_view_dxf::rows(app, ui, dashed), + Kind::ViewDxf { dashed, tolerance } => crate::dialogs_view_dxf::rows(app, ui, dashed, tolerance), Kind::Plastic(k) => enter |= crate::dialogs_plastic::rows(app, ui, k, &d.inputs), Kind::Appearance(k) => enter |= crate::dialogs_appearance::rows(app, ui, k, &mut d.inputs), Kind::Motion(k) => enter |= crate::dialogs_motion::rows(app, ui, k, &mut d.inputs), @@ -3477,8 +3509,8 @@ fn sels(d: &Dialog, i: usize) -> &[Sel] { } pub(crate) fn run_dialog(app: &mut SolveApp, d: &Dialog) -> Result<(), String> { - if let Kind::ViewDxf { dashed } = &d.kind { - return crate::dialogs_view_dxf::run(app, *dashed); + if let Kind::ViewDxf { dashed, tolerance } = &d.kind { + return crate::dialogs_view_dxf::run(app, *dashed, *tolerance); } // Saving asks for a file name first; `Err("")` is the user backing out of that. if let Kind::SaveMesh(k) = &d.kind { @@ -4029,10 +4061,10 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S need(0, "planar faces")?; ("solid.offset_face", json!({"faces": face_points(0), "distance": distance})) } - Kind::Thread { designation, length } => { + Kind::Thread { designation, length, suggested, .. } => { need(0, "a cylindrical face")?; let mut p = json!({"face": face_points(0).into_iter().next().unwrap_or(Value::Null)}); - if !designation.trim().is_empty() { + if !designation.trim().is_empty() && suggested.as_deref() != Some(designation.as_str()) { p["designation"] = json!(designation.trim()); } if !length.trim().is_empty() { @@ -4109,7 +4141,8 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S continue; } taken.extend(crate::viewport::grouped_selection(s, x)); - places.extend(face_point(x).map(|p| json!({ "position": p }))); + let kept = d.extra.get("position_exprs").filter(|k| face_point(x).is_some_and(|p| p == k["point"])).map(|k| k["at"].clone()); + places.extend(face_point(x).map(|p| json!({ "position": kept.unwrap_or(p) }))); } } let mut out = Vec::new(); @@ -4697,7 +4730,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + FeatureKind::Hole { position, at, direction, diameter, depth, hole, points, thread, to } => { let mut d = start("solid.hole")?; let mut k = hole_defaults(); if let Kind::Hole { diameter: dia, depth: dep, kind, cb_diameter, cb_depth, cs_diameter, cs_angle, opts } = &mut k { @@ -4745,6 +4778,12 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option = at.iter().map(|e| e.as_str()).collect(); + d.extra.insert("position_exprs".into(), json!({"at": exprs, "point": pt3(position.0)})); + } } } if to.is_some() { @@ -5050,10 +5089,13 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 7a51992fd..05fe187d8 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -1,5 +1,5 @@ //! Assembly dialogs: New Component, Joint, As-built Joint, Joint Origin, Rigid Group, Drive -//! Joints, Motion Link, Gear, Rack and Pinion, Screw (`dialogs_coupling`) and Interference. Joint origins are picked by hovering geometry: a face +//! Joints, Motion Link, Gear, Rack and Pinion, Screw, Cam (`dialogs_coupling`) and Interference. Joint origins are picked by hovering geometry: a face //! snaps to its centre (or a round face to the centre of its nearer end), an edge to its middle //! (a round edge to its centre), a vertex to itself; the snap shows as a glyph with its z axis //! before the click. Joints and drives preview on the placed (world) model: the moving @@ -31,7 +31,7 @@ const TYPE_LABELS: [&str; 7] = ["Rigid", "Revolute", "Slider", "Cylindrical", "P /// What a joint origin input accepts (snaps on faces, edges and vertices). const SNAPS: u16 = FACES | EDGES | VERTICES; /// Commands whose effect is where occurrences sit (previewed on the placed model). -const MOVES: [&str; 11] = [ +const MOVES: [&str; 12] = [ "joint.create", "joint.as_built", "joint.drive", @@ -41,6 +41,7 @@ const MOVES: [&str; 11] = [ "joint.gear", "joint.rack_pinion", "joint.screw", + "joint.cam", "parts.insert", "parts.fastener", ]; @@ -72,6 +73,7 @@ pub enum Asm { offset: String, }, Coupling(Box), + Cam(Box), Interference { result: Option, overlaps: Vec, @@ -151,13 +153,14 @@ impl Asm { "joint.rack_pinion" => "RACK AND PINION", _ => "SCREW", }, + Asm::Cam(_) => "CAM", Asm::Interference { .. } => "INTERFERENCE", Asm::Trace(_) => "MOTION TRACE", } } pub fn previews(&self) -> bool { - matches!(self, Asm::Joint(_) | Asm::Drive { .. } | Asm::RigidGroup | Asm::Coupling(_)) + matches!(self, Asm::Joint(_) | Asm::Drive { .. } | Asm::RigidGroup | Asm::Coupling(_) | Asm::Cam(_)) } } @@ -185,6 +188,7 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { (Asm::MotionLink { a: 0, b, ia: 0, ib: 0, ratio: "1".into(), offset: "0".into() }, vec![]) } "joint.gear" | "joint.rack_pinion" | "joint.screw" => crate::dialogs_coupling::start(app, id)?, + "joint.cam" => crate::dialogs_coupling::cam::start(app), "inspect.interference" => { (Asm::Interference { result: None, overlaps: Vec::new(), of: Vec::new() }, vec![SelInput::new("Bodies (all if none)", BODIES, true)]) } @@ -686,6 +690,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se ui.end_row(); } Asm::Coupling(f) => enter |= crate::dialogs_coupling::rows(app, ui, f, inputs), + Asm::Cam(f) => enter |= crate::dialogs_coupling::cam::rows(app, ui, f, inputs), Asm::Interference { result, overlaps, of } => { let picked: Vec = inputs.first().map(|i| i.items.clone()).unwrap_or_default(); row_label(ui, ""); @@ -914,6 +919,7 @@ pub fn commands(app: &SolveApp, k: &Asm, inputs: &[SelInput]) -> Result return crate::dialogs_coupling::commands(app, f, inputs), + Asm::Cam(f) => return crate::dialogs_coupling::cam::commands(app, f, inputs), // The check runs from its Compute button; OK only closes. Asm::Interference { .. } => Vec::new(), Asm::Trace(f) => cmd("motion.trace.keep", trace::params(s, f, inputs)?), @@ -925,6 +931,9 @@ pub fn animate(app: &SolveApp, k: &Asm, cmds: &mut Vec<(String, Value)>) { if let Asm::Coupling(f) = k { crate::dialogs_coupling::animate(&app.session, f, cmds); } + if let Asm::Cam(f) = k { + crate::dialogs_coupling::cam::animate(&app.session, f, cmds); + } let Asm::Joint(f) = k else { return }; if !f.animate { return; diff --git a/crates/ui-egui/src/dialogs_cam.rs b/crates/ui-egui/src/dialogs_cam.rs new file mode 100644 index 000000000..983e87795 --- /dev/null +++ b/crates/ui-egui/src/dialogs_cam.rs @@ -0,0 +1,197 @@ +//! The Cam dialog (`joint.cam`): a cam turning on a revolute joint drives a follower, a slider or +//! a revolute, along the cam's profile (a closed sketch profile, or edges of the cam's body). The +//! follower is a knife edge, a roller (its radius typed, or its round face picked, which is also +//! where it touches) or a flat face. Picking the profile on a part chooses the joint that part +//! turns on. Play turns the cam a full turn so the follower shows its motion before OK. + +use egui::RichText; +use serde_json::{Value, json}; +use solidcraft_engine::Sel; +use solidcraft_engine::Session; +use solidcraft_engine::doc::joints::JointKind; + +use super::{ROUND, joint_row, occurrence, pick, picked_radius, trim, turn}; +use crate::SolveApp; +use crate::dialogs::{check, combo, field, row_label}; +use crate::dialogs_assembly::Asm; +use crate::selection::{EDGES, FACES, PROFILES, SelInput, VERTICES}; +use crate::theme::Tokens; + +/// The follower types, as `joint.cam` takes them, and their labels. +const FOLLOWERS: [&str; 3] = ["knife", "roller", "flat"]; +const FOLLOWER_LABELS: [&str; 3] = ["Knife edge", "Roller", "Flat face"]; + +/// The inputs: the cam's profile, the roller's round face, the follower's tip. +const PROFILE: usize = 0; +const ROLLER: usize = 1; +const TIP: usize = 2; + +#[derive(Clone, Debug)] +pub struct CamForm { + /// The cam's joint and the follower's (ids). + pub a: u64, + pub b: u64, + /// Index into `FOLLOWERS`. + pub follower: usize, + /// The roller's radius, used where no round face is picked. + pub radius: String, + /// Ride the cam from the other side. + pub flip: bool, + /// The body of the profile pick the cam's joint was last chosen from, so a pick chooses once. + pub picked: Option, + pub animate: bool, + /// Animation phase, 0…1. + pub phase: f64, +} + +/// Joints of a kind: (id, label). +fn joints_of(s: &Session, kinds: &[JointKind]) -> Vec<(u64, String)> { + s.doc.assembly.joints.iter().filter(|j| kinds.contains(&j.kind)).map(|j| (j.id, format!("{} ({:?})", j.name, j.kind))).collect() +} + +pub fn start(app: &SolveApp) -> (Asm, Vec) { + let s = &app.session; + let cams = joints_of(s, &[JointKind::Revolute]); + let followers = joints_of(s, &[JointKind::Slider, JointKind::Revolute]); + let a = cams.first().map(|j| j.0).unwrap_or(0); + // A slider first, else another revolute than the cam's. + let b = followers.iter().find(|j| j.0 != a).map(|j| j.0).unwrap_or(0); + let f = CamForm { a, b, follower: 0, radius: "5 mm".into(), flip: false, picked: None, animate: false, phase: 0.0 }; + let inputs = vec![ + SelInput::new("Profile", PROFILES | EDGES, true), + SelInput::new("Roller (optional)", ROUND, false), + SelInput::new("Tip (optional)", FACES | EDGES | VERTICES, false), + ]; + (Asm::Cam(Box::new(f)), inputs) +} + +/// The occurrence the profile picked in `inputs` is on: an edge's body's, or a sketch's component's +/// first. +fn profile_occurrence(s: &Session, inputs: &[SelInput]) -> Option<(String, u64)> { + match inputs.get(PROFILE)?.items.first()? { + Sel::Edge { body, .. } => Some((body.clone(), occurrence(s, body)?)), + Sel::Profile { sketch, .. } => { + let comp = s.doc.feature(*sketch).map(|f| f.component)?; + let occ = if comp == 0 { 0 } else { s.doc.occurrence_of(comp)?.id }; + Some((format!("sketch {sketch}"), occ)) + } + _ => None, + } +} + +/// The dialog's rows; true when Enter was pressed in a value. +pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, f: &mut CamForm, inputs: &[SelInput]) -> bool { + let t = Tokens::get(); + let s = &app.session; + let (cams, followers) = (joints_of(s, &[JointKind::Revolute]), joints_of(s, &[JointKind::Slider, JointKind::Revolute])); + if cams.is_empty() || followers.len() < 2 && followers.iter().all(|j| cams.iter().any(|c| c.0 == j.0)) { + row_label(ui, ""); + ui.label(RichText::new(crate::i18n::tr_label("needs a joint that turns and one that slides or swings")).color(t.text_dim)); + ui.end_row(); + return false; + } + // A profile picked on a part chooses the joint that part turns on, once. + let at = profile_occurrence(s, inputs); + if at.as_ref().map(|x| &x.0) != f.picked.as_ref() { + if let Some(j) = at.as_ref().and_then(|(_, o)| { + let turning = s.doc.assembly.joints.iter().filter(|j| j.kind == JointKind::Revolute); + turning.clone().find(|j| j.b.occurrence == *o).or(turning.clone().find(|j| j.a.occurrence == *o)) + }) { + f.a = j.id; + if f.b == f.a { + f.b = followers.iter().find(|x| x.0 != f.a).map(|x| x.0).unwrap_or(0); + } + } + f.picked = at.map(|x| x.0); + } + let mut enter = false; + joint_row(ui, "Cam", "cam_a", &cams, &mut f.a); + joint_row(ui, "Follower", "cam_b", &followers, &mut f.b); + row_label(ui, "Type"); + let labels: Vec<&str> = FOLLOWER_LABELS.iter().map(|l| crate::i18n::tr_label(l)).collect(); + combo(ui, "cam_follower", &labels, &mut f.follower); + ui.end_row(); + if FOLLOWERS.get(f.follower) == Some(&"roller") { + row_label(ui, "Radius"); + match (pick(inputs, ROLLER), picked_radius(s, inputs, ROLLER)) { + (_, Some(r)) => { + ui.label(format!("{} mm ({})", trim(r), crate::i18n::tr_label("picked"))); + } + (Some(_), None) => { + ui.label(RichText::new(crate::i18n::tr_label("not a round face")).color(t.warning)); + } + (None, None) => enter |= field(ui, &mut f.radius), + } + ui.end_row(); + } + row_label(ui, "Other side"); + check(ui, &mut f.flip); + ui.end_row(); + row_label(ui, "Animate"); + let label = if f.animate { "■ Stop" } else { "▶ Play" }; + let r = ui.button(label).on_hover_text(crate::i18n::tr_label("Play the joint's motion in the view")); + crate::scenario::publish_handle("dialog:Animate", r.rect.center()); + if r.clicked() { + f.animate = !f.animate; + } + ui.end_row(); + if f.animate { + let now = ui.input(|i| i.time); + // 72 steps over 6 s: each one a preview. + f.phase = ((now / 6.0).fract() * 72.0).floor() / 72.0; + ui.ctx().request_repaint_after(std::time::Duration::from_millis(30)); + } + enter +} + +/// The command OK runs. +pub fn commands(app: &SolveApp, f: &CamForm, inputs: &[SelInput]) -> Result, String> { + let s = &app.session; + let joint = |id: u64| { + s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.id).ok_or_else(|| "choose the cam's and the follower's joints".to_string()) + }; + let (a, b) = (joint(f.a)?, joint(f.b)?); + let items = inputs.get(PROFILE).map(|i| i.items.as_slice()).unwrap_or_default(); + let profile = match items.first() { + Some(Sel::Profile { sketch, index }) => json!({"sketch": sketch, "index": index}), + Some(Sel::Edge { body, .. }) => { + let pts: Vec = + items.iter().filter_map(|x| if let Sel::Edge { point, .. } = x { Some(json!([point.x, point.y, point.z])) } else { None }).collect(); + let mut p = json!({ "edges": pts }); + if let Some(o) = occurrence(s, body) { + p["occurrence"] = json!(o); + } + p + } + _ => return Err("select the cam's profile (a sketch profile or the cam's edges)".into()), + }; + let follower = FOLLOWERS.get(f.follower).copied().unwrap_or("knife"); + let mut p = json!({"a": a, "b": b, "profile": profile, "follower": follower, "flip": f.flip}); + if follower == "roller" { + p["radius"] = match pick(inputs, ROLLER) { + Some((body, at)) => { + let mut v = json!({"circle": [at.x, at.y, at.z]}); + if let Some(o) = occurrence(s, body) { + v["occurrence"] = json!(o); + } + v + } + None => json!(f.radius.trim()), + }; + } + if let Some(snap) = inputs.get(TIP).and_then(|i| i.items.first()).and_then(|x| crate::dialogs_assembly::snap_of(s, x)) { + p["tip"] = snap.param; + } + Ok(vec![("joint.cam".to_string(), p)]) +} + +/// While animating, the preview turns the cam a full turn. +pub fn animate(s: &Session, f: &CamForm, cmds: &mut Vec<(String, Value)>) { + if f.animate { + turn(s, f.a, f.phase, cmds); + } +} + +#[cfg(test)] +#[path = "dialogs_cam_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/dialogs_cam_tests.rs b/crates/ui-egui/src/dialogs_cam_tests.rs new file mode 100644 index 000000000..dd8808e72 --- /dev/null +++ b/crates/ui-egui/src/dialogs_cam_tests.rs @@ -0,0 +1,112 @@ +use serde_json::json; +use solidcraft_engine::Session; +use solidcraft_engine::geom::Vec3; + +use super::*; +use crate::Services; +use crate::dialogs::{Kind, apply_commands, preview_commands}; + +/// A grounded base, a cam (a disc of radius 30 about (10, 0)) turning on a revolute joint about +Z +/// through the origin, a tappet on a slider along +X, its end on the cam, and a spare part on a +/// revolute joint of its own. +fn valve() -> SolveApp { + let mut s = Session::default(); + let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + run("component.create", json!({"name": "Base"})); + run("solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [-80, -80, -20]})); + run("component.activate", json!({"component": "root"})); + run("component.create", json!({"name": "Cam"})); + run("solid.cylinder", json!({"base": [10, 0, 0], "axis": [0, 0, 1], "radius": 30, "height": 5})); + run("component.activate", json!({"component": "root"})); + run("component.create", json!({"name": "Tappet"})); + run("solid.box", json!({"length": 20, "width": 4, "height": 5, "corner": [40, -2, 0]})); + run("component.activate", json!({"component": "root"})); + run("component.create", json!({"name": "Spare"})); + run("solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [-80, 60, 0]})); + run("component.activate", json!({"component": "root"})); + run("occurrence.ground", json!({"occurrence": "Base:1", "grounded": true})); + for (kind, name, z) in [("revolute", "Cam", [0, 0, 1]), ("slider", "Tappet", [1, 0, 0]), ("revolute", "Spare", [0, 0, 1])] { + let at = |o: &str| json!({"occurrence": o, "point": [0, 0, 2.5], "z": z}); + run("joint.create", json!({"type": kind, "a": at("Base"), "b": at(name), "flip": true, "name": name})); + } + SolveApp::new(s, Services::default()) +} + +/// A pick of the mesh edge nearest a point. +fn edge(app: &SolveApp, p: Vec3) -> Sel { + let st = app.session.world_state(); + let mut best: Option<(f64, Sel)> = None; + for b in &st.bodies { + for (index, e) in b.mesh().edges.iter().enumerate() { + let d = e.windows(2).filter_map(|w| Some(p.dist_to_segment(*w.first()?, *w.get(1)?))).fold(f64::MAX, f64::min); + if best.as_ref().is_none_or(|(bd, _)| d < *bd) { + best = Some((d, Sel::Edge { body: b.name.clone(), index, point: p })); + } + } + } + best.map(|x| x.1).unwrap() +} + +fn joint(app: &SolveApp, name: &str) -> u64 { + app.session.doc.assembly.joints.iter().find(|j| j.name == name).map(|j| j.id).unwrap_or(0) +} + +/// Picking the cam's edge chooses the joint it turns on; OK makes the cam, and Play turns the cam +/// in the preview. +#[test] +fn a_picked_cam_edge_makes_the_cam() { + let mut app = valve(); + app.start("joint.cam"); + let mut d = app.dialog.take().unwrap(); + // A second revolute joint for the cam to start on: the pick puts the cam right. + if let Kind::Assembly(Asm::Cam(f)) = &mut d.kind { + (f.a, f.b) = (joint(&app, "Spare"), joint(&app, "Tappet")); + } + d.active = 0; + // The far side of the cam's top edge (its near side touches the tappet). + let pick = edge(&app, Vec3::new(-20.0, 0.0, 5.0)); + d.pick(&app.session, pick); + app.dialog = Some(d); + let ctx = egui::Context::default(); + for _ in 0..3 { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + } + let mut d = app.dialog.clone().expect("the dialog stays open"); + if let Kind::Assembly(Asm::Cam(f)) = &mut d.kind { + // The joint the picked part turns on, and a follower that is another joint. + assert_eq!((f.a, f.b), (joint(&app, "Cam"), joint(&app, "Tappet"))); + (f.follower, f.radius) = (1, "4 mm".into()); + } + let c = apply_commands(&app, &d).unwrap(); + let (id, p) = &c[0]; + assert_eq!((id.as_str(), p["follower"].clone(), p["radius"].clone()), ("joint.cam", json!("roller"), json!("4 mm")), "{p}"); + assert!(p["profile"]["edges"][0].is_array() && p["profile"]["occurrence"].is_u64(), "{p}"); + if let Kind::Assembly(Asm::Cam(f)) = &mut d.kind { + (f.follower, f.animate, f.phase) = (0, true, 0.25); + } + let cmds = preview_commands(&app, &d).unwrap(); + assert_eq!(cmds.get(1).map(|c| (c.0.as_str(), c.1["values"].clone())), Some(("joint.drive", json!(["90 deg"]))), "{cmds:?}"); + let c = apply_commands(&app, &d).unwrap(); + for (id, p) in c { + app.run(&id, p).unwrap(); + } + let l = app.session.doc.assembly.links.first().cloned().unwrap(); + assert_eq!(l.lift.len(), 360); + // A quarter turn lowers the knife tappet from 40 to √(30² − 10²). + app.run("joint.drive", json!({"joint": "Cam", "value": 90})).unwrap(); + let v = solidcraft_engine::doc::joints::joint_values(&app.session.doc.assembly).get(&joint(&app, "Tappet")).cloned().unwrap_or_default(); + assert!((v.first().copied().unwrap_or(f64::NAN) - (800f64.sqrt() - 40.0)).abs() < 1e-3, "{v:?}"); +} + +/// The dialog's rows pass their English text, which the catalogs translate by its key. +#[test] +fn the_cam_dialog_labels_translate() { + let de = crate::i18n::Locale::for_language("de"); + for (english, german) in [("Cam", "Nocken"), ("Follower", "Stößel"), ("Roller", "Rolle"), ("Tip (optional)", "Spitze (optional)")] { + assert_eq!(de.label(english), german); + } + assert_eq!(crate::i18n::Locale::for_language("zh").label("Knife edge"), "尖顶"); +} diff --git a/crates/ui-egui/src/dialogs_coupling.rs b/crates/ui-egui/src/dialogs_coupling.rs index 2cda97f64..bcb03d6bf 100644 --- a/crates/ui-egui/src/dialogs_coupling.rs +++ b/crates/ui-egui/src/dialogs_coupling.rs @@ -1,5 +1,5 @@ //! The Gear, Rack and Pinion and Screw dialogs: two joints coupled by radii or a pitch -//! (`joint.gear`, `joint.rack_pinion`, `joint.screw`). A radius is typed, or comes from the round +//! (`joint.gear`, `joint.rack_pinion`, `joint.screw`); the Cam dialog is `dialogs_cam.rs`. A radius is typed, or comes from the round //! face picked on the part, and then follows that face when the design changes. Picking a gear's //! face also picks the joint it turns on. Play turns the driving joint so the coupling shows its //! motion before OK. @@ -259,21 +259,31 @@ pub fn commands(app: &SolveApp, f: &CouplingForm, inputs: &[SelInput]) -> Result Ok(vec![(f.command.to_string(), p)]) } -/// While animating, the preview turns the driving joint a full turn: its first value that turns -/// (a planar joint's is its third), the values before it as they are. +/// While animating, the preview turns the driving joint a full turn. pub fn animate(s: &Session, f: &CouplingForm, cmds: &mut Vec<(String, Value)>) { - let Some(j) = s.doc.assembly.joints.iter().find(|j| j.id == f.a).filter(|_| f.animate) else { return }; + if f.animate { + turn(s, f.a, f.phase, cmds); + } +} + +/// Drive `joint` to `phase` of a full turn: its first value that turns (a planar joint's is its +/// third), the values before it as they are. +fn turn(s: &Session, joint: u64, phase: f64, cmds: &mut Vec<(String, Value)>) { + let Some(j) = s.doc.assembly.joints.iter().find(|j| j.id == joint) else { return }; let Some(turn) = (0..j.kind.dofs().len()).find(|i| j.kind.is_angle(*i)) else { return }; let values: Vec = (0..=turn) .map(|i| match j.values.get(i).copied().unwrap_or(0.0) { - _ if i == turn => format!("{} deg", f.phase * 360.0), + _ if i == turn => format!("{} deg", phase * 360.0), v if j.kind.is_angle(i) => format!("{} deg", v.to_degrees()), v => format!("{v} mm"), }) .collect(); - cmds.push(("joint.drive".into(), json!({"joint": f.a, "values": values}))); + cmds.push(("joint.drive".into(), json!({"joint": joint, "values": values}))); } +#[path = "dialogs_cam.rs"] +pub mod cam; + #[cfg(test)] #[path = "dialogs_coupling_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/dialogs_motion.rs b/crates/ui-egui/src/dialogs_motion.rs index 523d8c683..3bb4f9c26 100644 --- a/crates/ui-egui/src/dialogs_motion.rs +++ b/crates/ui-egui/src/dialogs_motion.rs @@ -326,6 +326,34 @@ fn study_pose(app: &SolveApp, params: &Value, step: u32) -> Result app.set_status(crate::i18n::format("ui.saved_to", &[("path", &path)]), false), + Err(e) => app.set_status(e.to_string(), true), + } + }); +} + /// The explosion at `scale`, computed on a scratch copy. fn explode_pose(app: &SolveApp, scale: f64) -> Result, String> { let mut sc = app.session.scratch(); @@ -532,15 +560,28 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs: &mut [Sel tracks.remove(i); } row_label(ui, ""); - if ui.button(crate::i18n::tr_label("Add Key")).on_hover_text(crate::i18n::tr_label("Key a joint's value at this step")).clicked() - && let Some((ji, _, kind)) = moving.first() - { - let unit = if kind.is_angle(0) { "deg" } else { "mm" }; - tracks.push(Track { joint: *ji, index: 0, points: vec![(now, format!("0 {unit}"))] }); - } + let mut export = false; + ui.horizontal(|ui| { + if ui.button(crate::i18n::tr_label("Add Key")).on_hover_text(crate::i18n::tr_label("Key a joint's value at this step")).clicked() + && let Some((ji, _, kind)) = moving.first() + { + let unit = if kind.is_angle(0) { "deg" } else { "mm" }; + tracks.push(Track { joint: *ji, index: 0, points: vec![(now, format!("0 {unit}"))] }); + } + export = ui + .button(crate::i18n::tr_label("Export Animation…")) + .on_hover_text(crate::i18n::tr_label("Save the study as an animated GIF, seen as the viewport shows it")) + .clicked(); + }); ui.end_row(); // Show the pose at this step (again when the step or the keys change). let params = study_params(&app.session, name, study.as_deref(), steps, tracks); + if export { + match ¶ms { + Ok(p) => export_animation(app, p.clone(), name), + Err(e) => *error = Some(e.clone()), + } + } let key = { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); @@ -1276,6 +1317,48 @@ mod tests { } } + /// Export Animation saves the study the dialog shows (its keys need not be saved) as a GIF, + /// also when the name is typed without `.gif`, and the design keeps no study. + #[test] + fn export_animation_saves_the_dialogs_study_as_a_gif() { + // Drawn as the CLI draws (the headless device), as scenario shots are. + #[cfg(not(target_arch = "wasm32"))] + if solidcraft_engine::capture::installed().is_none() { + solidcraft_engine::capture::install(std::sync::Arc::new(|scene, cam, w, h| { + let (rgba, renderer) = solidcraft_gpu::capture::headless_rgba(scene, cam, w, h)?; + Ok(solidcraft_engine::capture::Picture { rgba, renderer }) + })); + } + let mut h = crate::scenario::Harness::new(); + for (name, x) in [("A", 0), ("B", 30)] { + h.app.run("component.activate", json!({"component": "root"})).unwrap(); + h.app.run("component.create", json!({ "name": name })).unwrap(); + h.app.run("solid.box", json!({"length": 20, "width": 20, "height": 10, "corner": [x, 0, 0]})).unwrap(); + } + let a = json!({"occurrence": "A:1", "face": [10, 10, 10]}); + h.app.run("joint.create", json!({"type": "revolute", "a": a, "b": {"occurrence": "B:1", "face": [40, 10, 0]}})).unwrap(); + h.app.start("motion.study"); + h.frames(3); + let Some(Kind::Motion(Mo::MotionStudy { name, steps, tracks, .. })) = h.app.dialog.as_mut().map(|d| &mut d.kind) else { + panic!("no Motion Study dialog"); + }; + *name = "Swing".into(); + *steps = "4".into(); + *tracks = vec![Track { joint: 0, index: 0, points: vec![(0, "0 deg".into()), (4, "90 deg".into())] }]; + let dir = h.dir.clone(); + h.app.services.pick_save = Some(Box::new(move |name, extensions| { + assert_eq!((name, extensions), ("Swing.gif", &["gif"][..])); + Box::pin(std::future::ready(Some(dir.join("swing").to_string_lossy().into_owned()))) + })); + h.frames(2); + h.step(&json!({"widget": "Export Animation…"})).unwrap(); + h.frames(3); + let gif = std::fs::read(h.dir.join("swing.gif")).unwrap(); + assert!(gif.starts_with(b"GIF89a"), "{:?}", h.app.status); + assert!(h.app.status.as_ref().is_some_and(|s| !s.2), "{:?}", h.app.status); + assert!(h.app.session.doc.assembly.studies.is_empty(), "exporting saves no study"); + } + #[test] fn study_keys_by_joint_id() { let mut s = Session::default(); diff --git a/crates/ui-egui/src/dialogs_thread.rs b/crates/ui-egui/src/dialogs_thread.rs new file mode 100644 index 000000000..b9d0cdf1d --- /dev/null +++ b/crates/ui-egui/src/dialogs_thread.rs @@ -0,0 +1,95 @@ +//! Metric thread choices use the document's sizing table and the existing designation +//! parameter. Browsing choices does not edit the model or freeze an automatic feature. + +use solidcraft_engine::doc::{metric_thread_sizes, parse_metric_thread}; + +use crate::dialogs::{check, combo, row_label}; +use crate::i18n::tr; + +/// Common pitch presets, not an exhaustive catalogue of standard diameter/pitch pairs. +/// The coarse and current pitches are included separately; custom pairs remain editable. +const PITCHES: &[f64] = &[0.2, 0.25, 0.35, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0]; + +/// Returns (Enter pressed, automatic sizing requested). +pub(crate) fn rows(ui: &mut egui::Ui, designation: &mut String, suggested: &mut Option) -> (bool, bool) { + row_label(ui, "Profile"); + ui.label(tr("ISO metric")); + ui.end_row(); + + row_label(ui, "Automatic size"); + let before = designation.trim().is_empty() || suggested.as_deref() == Some(designation.as_str()); + let mut automatic = before; + ui.add_enabled_ui(!designation.trim().is_empty(), |ui| check(ui, &mut automatic)); + let reset = automatic && !before; + if automatic != before { + *suggested = None; + if automatic { + designation.clear(); + } + } + ui.end_row(); + + let current = parse_metric_thread(designation); + let mut diameters: Vec = metric_thread_sizes().iter().map(|(d, _)| *d).collect(); + if let Some((d, _)) = current + && !diameters.contains(&d) + { + diameters.push(d); + diameters.sort_by(f64::total_cmp); + } + row_label(ui, "Size"); + let labels: Vec = diameters.iter().map(|d| format!("{d} mm")).collect(); + let mut selected = current.and_then(|(d, _)| diameters.iter().position(|n| *n == d)).unwrap_or(diameters.len()); + let before = selected; + let mut labels: Vec<&str> = labels.iter().map(String::as_str).collect(); + if current.is_none() { + labels.push("Select size"); + } + combo(ui, "thread_diameter", &labels, &mut selected); + // A new diameter starts with its coarse pitch. The current custom diameter, if any, + // is already selected and retains its explicit pitch. + if selected != before + && let Some(d) = diameters.get(selected) + && let Some((_, coarse)) = metric_thread_sizes().iter().find(|(n, _)| n == d) + { + *designation = format!("M{d}x{coarse}"); + *suggested = None; + } + ui.end_row(); + + let current = parse_metric_thread(designation); + row_label(ui, "Pitch"); + ui.add_enabled_ui(current.is_some(), |ui| { + let mut pitches = Vec::new(); + if let Some((d, p)) = current { + let coarse = metric_thread_sizes().iter().find(|(n, _)| *n == d).map(|(_, p)| *p); + pitches.extend(PITCHES.iter().copied().filter(|p| *p < d && *p <= coarse.unwrap_or(d))); + pitches.extend(coarse); + pitches.push(p); + } + pitches.sort_by(|a, b| b.total_cmp(a)); + pitches.dedup(); + let labels: Vec = pitches.iter().map(|p| format!("{p} mm")).collect(); + let labels: Vec<&str> = labels.iter().map(String::as_str).collect(); + let mut selected = current.and_then(|(_, p)| pitches.iter().position(|n| *n == p)).unwrap_or(0); + let before = selected; + combo(ui, "thread_pitch", &labels, &mut selected); + if selected != before + && let (Some((d, _)), Some(p)) = (current, pitches.get(selected)) + { + *designation = format!("M{d}x{p}"); + *suggested = None; + } + }); + ui.end_row(); + + row_label(ui, "Designation"); + let response = ui.add(egui::TextEdit::singleline(designation).hint_text(tr("fits the face, e.g. M8"))); + crate::scenario::publish_handle("dialog:thread_size", response.rect.center()); + if response.changed() { + *suggested = None; + } + let enter = response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + ui.end_row(); + (enter, reset) +} diff --git a/crates/ui-egui/src/dialogs_view_dxf.rs b/crates/ui-egui/src/dialogs_view_dxf.rs index cbf0222b1..7a7a757cb 100644 --- a/crates/ui-egui/src/dialogs_view_dxf.rs +++ b/crates/ui-egui/src/dialogs_view_dxf.rs @@ -3,10 +3,14 @@ use crate::{SolveApp, dialogs::Kind, selection::SelInput}; use serde_json::json; pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { - (id == "file.export_view_dxf").then(|| (Kind::ViewDxf { dashed: app.preferences.view_dxf_dashed }, Vec::new())) + (id == "file.export_view_dxf").then(|| { + let tolerance = app.preferences.view_dxf_tolerance; + let tolerance = if tolerance.is_finite() && (0.0001..=1.0).contains(&tolerance) { tolerance } else { 0.01 }; + (Kind::ViewDxf { dashed: app.preferences.view_dxf_dashed, tolerance }, Vec::new()) + }) } -pub fn rows(app: &SolveApp, ui: &mut egui::Ui, dashed: &mut bool) { +pub fn rows(app: &SolveApp, ui: &mut egui::Ui, dashed: &mut bool, tolerance: &mut f64) { crate::dialogs::row_label(ui, "Hidden edges"); ui.vertical(|ui| { let r = ui.radio_value(dashed, false, app.tr_label("Do not export hidden edges")); @@ -15,34 +19,54 @@ pub fn rows(app: &SolveApp, ui: &mut egui::Ui, dashed: &mut bool) { crate::scenario::publish_handle("dialog:dxf:dashed", r.rect.center()); }); ui.end_row(); + crate::dialogs::row_label(ui, "dxf.tolerance"); + let r = ui.add(egui::DragValue::new(tolerance).range(0.0001..=1.0).speed(0.001).max_decimals(4).suffix(" mm")); + crate::scenario::publish_handle("dialog:dxf:tolerance", r.rect.center()); + ui.end_row(); crate::dialogs::row_label(ui, "Projection"); ui.label(app.tr_label(if app.cam.fov > 0.0 { "Current perspective view" } else { "Current orthographic view (1:1 mm)" })); ui.end_row(); crate::dialogs::row_label(ui, ""); - ui.label(app.tr_label("Visible bodies only. Curves use line segments (0.01 mm tolerance).")); + ui.add(egui::Label::new(app.tr_label("dxf.tolerance_help")).wrap()); ui.end_row(); } -pub fn run(app: &mut SolveApp, dashed: bool) -> Result<(), String> { +pub fn run(app: &mut SolveApp, dashed: bool, tolerance: f64) -> Result<(), String> { if crate::viewport::section_plane(app).is_some() { return Err(app.tr_label("Turn off section analysis before exporting the view.").into()); } - if !app.session.world_state().bodies.iter().any(|b| app.session.body_visible(&b.name)) { + if app.session.model.state().bodies.is_empty() { return Err(app.tr_label("No visible bodies to export.").into()); } + if !tolerance.is_finite() || !(0.0001..=1.0).contains(&tolerance) { + return Err(app.tr_label("dxf.invalid_tolerance").into()); + } app.preferences.view_dxf_dashed = dashed; + app.preferences.view_dxf_tolerance = tolerance; let camera = app.cam; app.pick_save(&format!("{}-view.dxf", app.session.doc.name), &["dxf"], move |app, path| { if let Some(path) = path { - let params = json!({"camera":camera,"hidden":if dashed {"dashed"} else {"omit"},"path":path}); - if app.run("file.export_view_dxf", params).is_ok() { - app.set_status(crate::i18n::format("ui.saved_to", &[("path", &path)]), false); - } + let params = json!({"camera":camera,"hidden":if dashed {"dashed"} else {"omit"},"tolerance":tolerance,"path":path}); + let mut request = crate::file_load::Request::new(&path, crate::file_load::Kind::ExportDxf); + request.options = params.as_object().cloned().unwrap_or_default(); + let _ = crate::file_load::begin_request(app, request); } }); Ok(()) } +pub(crate) fn progress_text(work: Option<(&str, usize, usize)>) -> String { + let (stage, done, total) = work.unwrap_or(("dxf_meshes", 0, 1)); + let label = match stage { + "dxf_index" => "dxf.progress.index", + "dxf_projection" => "dxf.progress.projection", + "dxf_occlusion" => "dxf.progress.occlusion", + "dxf_write" => "dxf.progress.write", + _ => "dxf.progress.meshes", + }; + format!("{}: {done}/{total}", crate::i18n::tr_label(label)) +} + #[cfg(test)] mod tests { use super::*; @@ -58,7 +82,11 @@ mod tests { h.frames(3); h.step(&json!({"click":{"handle":"appbar:folder"}})).unwrap(); h.step(&json!({"widget":"Export Current View as DXF…"})).unwrap(); - assert!(matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(Kind::ViewDxf { dashed: false }))); + assert!(matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(Kind::ViewDxf { dashed: false, .. }))); + h.step(&json!({"click":{"handle":"dialog:dxf:tolerance"},"double":true})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"0.1"})).unwrap(); + h.step(&json!({"key":"Tab"})).unwrap(); h.step(&json!({"click":{"handle":"dialog:dxf:dashed"}})).unwrap(); let dir = h.dir.clone(); h.app.services.pick_save = Some(Box::new(move |name, extensions| { @@ -67,7 +95,7 @@ mod tests { Box::pin(std::future::ready(Some(dir.join("view.dxf").to_string_lossy().into_owned()))) })); h.step(&json!({"click":{"handle":"dialog:Export DXF…"}})).unwrap(); - h.frames(3); + wait_for_export(&mut h); let text = std::fs::read_to_string(h.dir.join("view.dxf")).unwrap(); assert!(text.contains("LWPOLYLINE") && text.contains("HIDDEN")); assert!(h.app.dialog.is_none() && h.app.preferences.view_dxf_dashed); @@ -75,14 +103,27 @@ mod tests { let mut restored = SolveApp::new(Default::default(), Default::default()); restored.load_prefs(&saved); assert!(restored.preferences.view_dxf_dashed); + assert_eq!(restored.preferences.view_dxf_tolerance, 0.1); h.app.start("file.export_view_dxf"); h.frames(3); - assert!(matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(Kind::ViewDxf { dashed: true }))); + assert!(matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(Kind::ViewDxf { dashed: true, tolerance: 0.1 }))); h.step(&json!({"click":{"handle":"dialog:dxf:omit"}})).unwrap(); h.step(&json!({"click":{"handle":"dialog:Export DXF…"}})).unwrap(); - h.frames(3); + wait_for_export(&mut h); let text = std::fs::read_to_string(h.dir.join("view.dxf")).unwrap(); assert!(!text.contains("LWPOLYLINE") && !text.contains("HIDDEN")); assert!(!h.app.preferences.view_dxf_dashed); } + + fn wait_for_export(h: &mut crate::scenario::Harness) { + let began = std::time::Instant::now(); + loop { + h.frames(1); + if h.app.file_load.idle() && !h.app.file_picker_busy() { + break; + } + assert!(began.elapsed().as_secs() < 10, "export did not finish"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } } diff --git a/crates/ui-egui/src/extrude_edit_tests.rs b/crates/ui-egui/src/extrude_edit_tests.rs index 5064292bb..739631c34 100644 --- a/crates/ui-egui/src/extrude_edit_tests.rs +++ b/crates/ui-egui/src/extrude_edit_tests.rs @@ -394,3 +394,62 @@ fn extrusion_arrow_tracks_the_current_drag_frame() { assert!((drawn[0] - expected[0]).hypot(drawn[1] - expected[1]) < 0.1, "arrow {drawn:?} trails current value {expected:?}"); } } + +/// The world point `at` mm along the open extrude's arrow. +fn on_arrow(h: &Harness, at: f64) -> Value { + let d = h.app.dialog.as_ref().unwrap(); + let (base, normal) = crate::canvas::anchor(&h.app, d).unwrap(); + let p = base + normal.unwrap() * at; + json!({"world":[p.x, p.y, p.z]}) +} + +fn dialog_distance(h: &Harness) -> f64 { + let d = h.app.dialog.as_ref().unwrap(); + let crate::dialogs::Kind::Extrude { distance, .. } = &d.kind else { panic!("extrude") }; + h.app.session.doc.eval(distance, solidcraft_engine::doc::expr::Kind::Length).unwrap() +} + +/// The arrow's stem takes the drag as its tip does (#1740): pressed 4 mm along a 10 mm arrow and +/// moved to 9 mm, it grows by the 5 mm the pointer moved, not to where the pointer is. +#[test] +fn the_extrude_arrow_drags_from_its_stem() { + let mut h = make(json!({"distance":10})); + open(&mut h); + let (from, to) = (on_arrow(&h, 4.0), on_arrow(&h, 9.0)); + h.step(&json!({"drag":[from, to]})).unwrap(); + assert!((dialog_distance(&h) - 15.0).abs() < 1e-9, "{}", dialog_distance(&h)); + h.step(&json!({"widget":"OK"})).unwrap(); + let bounds = h.app.session.world_state().body("Main").unwrap().mesh().bounds(); + assert!((bounds.max.z - 15.0).abs() < 1e-7, "{bounds:?}"); +} + +/// A click on the arrow's stem is the arrow's (#1740): a new extrude of a square sketched on a +/// block keeps its profile picked and its distance. Before, the click went through to the square +/// under the stem and unpicked it. +#[test] +fn a_click_on_the_extrude_arrow_stem_keeps_the_profile() { + let mut h = Harness::new(); + h.app.home.open = false; + for (id, p) in [ + ("sketch.create", json!({"plane": "XY"})), + ("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [60, 20]})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"distance": 10})), + ("sketch.create", json!({"plane": {"origin": [0, 0, 10], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})), + ("sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [15, 15]})), + ] { + h.app.run(id, p).unwrap(); + } + h.app.finish_sketch(); + h.app.start("solid.extrude"); + h.frames(4); + let picked = |h: &Harness| h.app.dialog.as_ref().unwrap().inputs.iter().map(|i| i.items.len()).collect::>(); + let before = picked(&h); + assert!(before.iter().any(|n| *n > 0), "{before:?}"); + let distance = dialog_distance(&h); + let at = on_arrow(&h, distance * 0.3); + h.step(&json!({"click": at})).unwrap(); + h.frames(2); + assert_eq!(picked(&h), before); + assert!((dialog_distance(&h) - distance).abs() < 1e-9, "{} for {distance}", dialog_distance(&h)); +} diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index bfe3b711e..f9dc3cca3 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -29,6 +29,8 @@ pub enum Kind { Insert, /// Open a design an earlier run autosaved before it closed. Recover { id: String, dir: Option }, + /// Export a snapshot of the current design without adopting the worker's session. + ExportDxf, } pub struct Request { @@ -63,6 +65,7 @@ impl Request { Kind::Insert if solidcraft_engine::io::is_mesh_path(&self.path) => ("file.insert_mesh", json!({"path": self.path})), Kind::Insert => ("file.insert_step", self.params()), Kind::Recover { id, dir } => ("doc.recover", json!({"id": id, "dir": dir})), + Kind::ExportDxf => ("file.export_view_dxf", Value::Object(self.options.clone())), } } fn answer(&self, r: Result) { @@ -99,6 +102,14 @@ struct Running { staged: Option, } +impl Drop for Running { + fn drop(&mut self) { + if self.request.kind == Kind::ExportDxf { + self.progress.cancel(); + } + } +} + /// A STEP import done a piece per frame, for the web app: it has one thread, which must keep /// drawing (and offer Cancel) while a large file comes in. The file is parsed in one frame, /// then its solids are converted a few at a time, each frame for about [`STAGED_FRAME_MS`]; @@ -208,6 +219,14 @@ pub fn begin_request(app: &mut SolveApp, request: Request) -> Result<(), String> } r } + Kind::ExportDxf => { + let (command, params) = request.command(); + let r = app.run(command, params); + if r.is_ok() && !request.path.is_empty() { + app.set_status(crate::i18n::format("ui.saved_to", &[("path", &request.path)]), false); + } + r + } }; request.answer(r); Ok(()) @@ -236,10 +255,15 @@ pub fn control(app: &mut SolveApp, req: crate::control::ControlRequest) -> Optio let kind = match command { Some("doc.open") => Kind::Open, Some("file.insert_step" | "file.insert_mesh") => Kind::Insert, + Some("file.export_view_dxf") => Kind::ExportDxf, _ => return Some(req), }; let params = req.params.get("params"); - let Some(path) = params.and_then(|p| p.get("path")).and_then(Value::as_str) else { return Some(req) }; + let path = match params.and_then(|p| p.get("path")).and_then(Value::as_str) { + Some(path) => path, + None if kind == Kind::ExportDxf => "", + None => return Some(req), + }; let scope = match crate::control::request_scope(app, &req.params) { Ok(scope) => scope, Err(e) => { @@ -247,7 +271,11 @@ pub fn control(app: &mut SolveApp, req: crate::control::ControlRequest) -> Optio return None; } }; - let options = ["up", "names"].iter().filter_map(|k| Some((k.to_string(), params?.get(*k).filter(|v| !v.is_null())?.clone()))).collect(); + let options = if kind == Kind::ExportDxf { + params.and_then(Value::as_object).cloned().unwrap_or_default() + } else { + ["up", "names"].iter().filter_map(|k| Some((k.to_string(), params?.get(*k).filter(|v| !v.is_null())?.clone()))).collect() + }; let _ = begin_request(app, Request { path: path.into(), kind, reply: Some(req.reply.clone()), scope, options }); None } @@ -281,7 +309,10 @@ fn start(app: &mut SolveApp) { return; } let Some(request) = app.file_load.queued.pop_front() else { return }; - if !request.insert() && app.docs.count() >= crate::documents::MAX_OPEN && !crate::documents::active_is_blank(app) { + if matches!(request.kind, Kind::Open | Kind::Recover { .. }) + && app.docs.count() >= crate::documents::MAX_OPEN + && !crate::documents::active_is_blank(app) + { let e = "too many open designs; close a tab before opening another"; app.set_status(e, true); request.answer(Err(e.into())); @@ -289,7 +320,7 @@ fn start(app: &mut SolveApp) { } let insert = request.insert(); let before = if insert { app.session.world_state().bodies.iter().map(|b| b.name.clone()).collect() } else { Vec::new() }; - let mut scratch = if insert { app.session.scratch() } else { Session::default() }; + let mut scratch = if insert || request.kind == Kind::ExportDxf { app.session.scratch() } else { Session::default() }; if insert { scratch.selection = app.session.selection.clone(); } @@ -679,6 +710,11 @@ fn compute( let result = solidcraft_engine::io::vfs::scoped(scope, || solidcraft_engine::doc::progress::watch(progress.clone(), || session.execute(command, params))) .map_err(|e| e.to_string())?; + if command == "file.export_view_dxf" { + // A successful export has already published its complete file. A Cancel arriving + // after that commit must not turn a completed save into a misleading cancellation. + return Ok(Made { session, result, image: None }); + } if progress.is_cancelled() { return cancelled(); } @@ -739,6 +775,12 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { { let request = &running.request; match job { + Ok(made) if request.kind == Kind::ExportDxf => { + if !request.path.is_empty() { + app.set_status(crate::i18n::format("ui.saved_to", &[("path", &request.path)]), false); + } + request.answer(Ok(made.result)); + } _ if running.cancelled() => request.answer(Err("file operation cancelled".into())), Ok(made) if running.matches(&app.session) => { if request.insert() { @@ -813,7 +855,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let phase = r.phase.load(Ordering::Relaxed); let (done, total) = r.progress.features(); // Long work inside one feature (a large STEP file) has progress of its own. - let work = r.progress.work().filter(|(_, d, t)| phase == 0 && d < t); + let export = r.request.kind == Kind::ExportDxf; + let work = r.progress.work().filter(|(_, d, t)| export || (phase == 0 && d < t)); let screen = ctx.content_rect(); // Leave the title bar to the window. The resize edges are a foreground layer above this. let cover = egui::Rect::from_min_max(egui::pos2(screen.left(), screen.top() + crate::toolbar::APP_BAR_HEIGHT), screen.max); @@ -848,20 +891,23 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui.set_width(width - 16.0); ui.horizontal(|ui| { ui.label( - egui::RichText::new(if cancelled { + egui::RichText::new(if cancelled && export { + crate::i18n::tr_label("dxf.cancelling") + } else if cancelled { "Waiting for file operation" } else { match r.request.kind { Kind::Insert => "Inserting geometry", Kind::Open => "Opening design", Kind::Recover { .. } => "Recovering design", + Kind::ExportDxf => crate::i18n::tr_label("dxf.exporting"), } }) .strong() .size(14.0), ); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let b = ui.button("Cancel"); + let b = ui.button(crate::i18n::tr("ui.cancel")); crate::scenario::publish_handle("file_loading:cancel", b.rect.center()); cancel |= b.clicked(); }); @@ -879,10 +925,13 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui.add_space(4.0); ui.horizontal(|ui| { ui.spinner(); - ui.label(if cancelled { + ui.label(if cancelled && export { + crate::i18n::tr_label("dxf.cancel_wait").to_string() + } else if cancelled { "Waiting for the previous operation to stop...".to_string() } else { match (phase, work) { + (_, work) if r.request.kind == Kind::ExportDxf => crate::dialogs_view_dxf::progress_text(work), (_, Some(("reading", d, t))) => format!("Reading the file... {}%", d * 100 / t.max(1)), (_, Some((_, d, t))) => format!("Converting solid {} of {t}", d + 1), (1, _) => "Preparing the view...".into(), @@ -912,7 +961,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { // import to overlap it in memory. The rebuild stops at its next feature and the // current design stays as it was. app.file_load.cancel(); - app.set_status("file operation cancelled", false); + app.set_status(if export { crate::i18n::tr_label("dxf.cancelled") } else { "file operation cancelled" }, false); } } @@ -920,6 +969,77 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { mod tests { use super::*; + #[test] + fn dxf_export_progress_keeps_frames_alive_and_never_adopts_a_worker_document() { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.frames(3); + let base = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let cam = h.app.cam; + let progress = Arc::new(Progress::default()); + solidcraft_engine::doc::progress::watch(progress.clone(), || { + solidcraft_engine::kernel::watch::current().unwrap().progress("dxf_occlusion", 64, 128); + }); + let (tx, rx) = std::sync::mpsc::channel(); + h.app.file_load.running = Some(Running { + request: Request::new("drawing.dxf", Kind::ExportDxf), + base: base.clone(), + base_revision: h.app.session.revision, + before: Vec::new(), + rx, + phase: Arc::new(AtomicU8::new(0)), + progress: progress.clone(), + preview_rx: None, + preview: None, + partial_rx: None, + built: None, + staged: None, + }); + // No worker result is available: drawing a frame must not wait for one. + h.frames(4); + assert!(h.app.file_load.busy()); + let at = crate::scenario::handle_at("file_loading:cancel").unwrap(); + let (request, _reply) = crate::control::ControlRequest::new("ui.click", json!({"x":at.x,"y":at.y})); + let _ = crate::control::handle(&mut h.app, &h.ctx, &request); + h.frames(4); + assert!(progress.is_cancelled()); + tx.send(Err("DXF export cancelled".into())).unwrap(); + h.frames(2); + assert!(h.app.file_load.idle()); + assert!(Arc::ptr_eq(&base, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, cam); + + // The success path is equally read-only, even if the worker has another session. + let mut other = Session::default(); + other.execute("file.new", &json!({"name":"Worker must not replace the current design"})).unwrap(); + let mut request = Request::new("drawing.dxf", Kind::ExportDxf); + let (reply_tx, reply_rx) = std::sync::mpsc::channel(); + request.reply = Some(reply_tx); + let (tx, rx) = std::sync::mpsc::channel(); + h.app.file_load.running = Some(Running { + request, + base: base.clone(), + base_revision: h.app.session.revision, + before: Vec::new(), + rx, + phase: Arc::new(AtomicU8::new(0)), + progress: Arc::new(Progress::default()), + preview_rx: None, + preview: None, + partial_rx: None, + built: None, + staged: None, + }); + tx.send(Ok(Made { session: other, result: json!({"visible":12}), image: None })).unwrap(); + h.frames(2); + assert_eq!(reply_rx.try_recv().unwrap()["result"]["visible"], 12); + assert!(Arc::ptr_eq(&base, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, cam); + } + #[test] fn opening_result_and_preview_cannot_overwrite_a_newer_design() { for (insert, change_document) in [(false, true), (true, true), (false, false)] { diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 83e2e3f85..9c072c7e3 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -136,7 +136,7 @@ pub(crate) fn offscreen_backends() -> wgpu::Backends { /// A device of its own for an offscreen render or check (`None` without a GPU adapter), on /// [`offscreen_backends`]. #[cfg(all(test, not(target_arch = "wasm32")))] -fn offscreen_device() -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> { +pub(crate) fn offscreen_device() -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> { let mut desc = wgpu::InstanceDescriptor::new_without_display_handle_from_env(); desc.backends = offscreen_backends(); let instance = wgpu::Instance::new(desc); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index ff8ac778f..75200e747 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -34,8 +34,11 @@ impl Catalog { static ENGLISH: Catalog = Catalog::new("en", "English", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/en.json"))); static GERMAN: Catalog = Catalog::new("de", "Deutsch", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/de.json"))); static FRENCH: Catalog = Catalog::new("fr", "Français", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/fr.json"))); +static GALICIAN: Catalog = Catalog::new("gl", "Galego", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/gl.json"))); static JAPANESE: Catalog = Catalog::new("ja", "日本語", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ja.json"))); static KOREAN: Catalog = Catalog::new("ko", "한국어", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ko.json"))); +static PORTUGUESE_BR: Catalog = + Catalog::new("pt-BR", "Português (Brasil)", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/pt-BR.json"))); static RUSSIAN: Catalog = Catalog::new("ru", "Русский", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/ru.json"))); static TURKISH: Catalog = Catalog::new("tr", "Türkçe", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/tr.json"))); static UKRAINIAN: Catalog = Catalog::new("uk", "Українська", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/uk.json"))); @@ -47,8 +50,10 @@ pub const LOCALES: &[&Catalog] = &[ &ENGLISH, &GERMAN, &FRENCH, + &GALICIAN, &JAPANESE, &KOREAN, + &PORTUGUESE_BR, &RUSSIAN, &TURKISH, &UKRAINIAN, @@ -542,6 +547,29 @@ mod tests { assert_eq!(tr.label("NonExistentKey"), "NonExistentKey"); } + #[test] + fn brazilian_portuguese_catalog_is_registered_and_translates_keys() { + let pt = Locale::for_language("pt-BR"); + assert_eq!(pt.name(), "Português (Brasil)"); + assert!(is_supported("pt-BR")); + assert_eq!(pt.text("ui.preferences"), "Preferências"); + assert_eq!(pt.format("document.save_changes", &[("name", "My {design}")]), "Salvar as alterações em My {design}?"); + assert_eq!(pt.format("dialog.selected_count", &[("count", "2")]), "↖ 2 selecionados"); + assert_eq!(pt.label("NonExistentKey"), "NonExistentKey"); + } + + #[test] + fn galician_catalog_is_registered_and_translates_keys() { + let gl = Locale::for_language("gl"); + assert_eq!(gl.name(), "Galego"); + assert!(is_supported("gl")); + assert_eq!(gl.text("ui.preferences"), "Preferencias"); + assert_eq!(gl.format("document.save_changes", &[("name", "My {design}")]), "Gardar os cambios en My {design}?"); + assert_eq!(gl.format("dialog.selected_count", &[("count", "2")]), "↖ 2 seleccionados"); + assert_eq!(gl.label("Fillet"), "Arredondamento"); + assert_eq!(gl.label("NonExistentKey"), "NonExistentKey"); + } + #[test] fn ukrainian_catalog_translates_keys_labels_and_browser_patterns() { let uk = Locale::for_language("uk"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 60aec6bf2..906ef0d9b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -36,6 +36,7 @@ pub mod dialogs_save_mesh; pub mod dialogs_sheet; pub mod dialogs_surface; pub mod dialogs_sweep; +mod dialogs_thread; pub mod dialogs_view_dxf; pub mod dim_view; #[cfg(test)] @@ -111,6 +112,8 @@ mod fillet_spline_handle_tests; pub(crate) mod navigation; pub mod palette; pub mod params_dialog; +pub(crate) mod pick_buffer; +pub(crate) mod pick_index; pub mod prefs; #[cfg(test)] mod preselect_tests; @@ -958,13 +961,16 @@ impl SolveApp { v } - /// Is the origin widget shown (always while picking a sketch plane)? - /// Origin planes and axes are drawn and pickable. Hidden ones only come back while Create - /// Sketch has nothing else to offer (no body shown). + /// Is the origin widget shown? Origin planes and axes are drawn and pickable. While Create + /// Sketch picks its plane the Origin is always shown, drawn through the model (a plane + /// inside a body stays visible), even when the browser hides it. pub fn origin_visible(&self) -> bool { - self.ui.show_origin - || (self.dialog.as_ref().is_some_and(|d| matches!(d.kind, dialogs::Kind::Sketch)) - && !self.session.world_state().bodies.iter().any(|b| self.session.body_visible(&b.name))) + self.ui.show_origin || self.picking_sketch_plane() + } + + /// Is Create Sketch open, waiting for its plane? + pub fn picking_sketch_plane(&self) -> bool { + self.dialog.as_ref().is_some_and(|d| matches!(d.kind, dialogs::Kind::Sketch)) } pub fn set_status(&mut self, s: impl Into, error: bool) { @@ -1445,6 +1451,11 @@ impl SolveApp { control::Outcome::Done(v) => { let _ = reply.send(v); } + // A window that is minimised or covered (another macOS Space) presents no frame: + // say so at once rather than after the deadline (#1677). + control::Outcome::Screenshot { .. } if window_hidden(ctx) => { + let _ = reply.send(json!({"ok": false, "hidden": true, "error": "no frame was presented (window hidden?); use ui.render"})); + } control::Outcome::Screenshot { path } => { self.shot_token += 1; let token = self.shot_token; @@ -1498,8 +1509,10 @@ impl SolveApp { } } let now = now_ms(); + // Hidden while waiting: no frame is coming. + let hidden = window_hidden(ctx); self.pending_shots.retain(|(_, _, reply, deadline)| { - if now < *deadline { + if now < *deadline && !hidden { return true; } let _ = reply.send(json!({"ok": false, "error": "no frame was presented (window hidden?); use ui.render"})); @@ -1508,6 +1521,12 @@ impl SolveApp { } } +/// The window is minimised or fully covered, so it presents no frames (#1677). Unknown counts as +/// shown: the screenshot deadline still ends a wait for a frame that never comes. +fn window_hidden(ctx: &egui::Context) -> bool { + ctx.input(|i| i.viewport().visible()) == Some(false) +} + /// A command's name as people see it (its label), for the status bar. pub fn command_label(id: &str) -> &str { solidcraft_engine::find_command(id).map_or(id, |c| c.label) diff --git a/crates/ui-egui/src/pick_buffer.rs b/crates/ui-egui/src/pick_buffer.rs new file mode 100644 index 000000000..373018f29 --- /dev/null +++ b/crates/ui-egui/src/pick_buffer.rs @@ -0,0 +1,259 @@ +//! The GPU pick buffer in the viewport ([`solidcraft_gpu::pick`]): which model edges are seen at +//! each pixel, so a pick over a large model tests only the edges near the cursor that are not +//! hidden, instead of every edge the cursor's ray passes near. +//! +//! The pass is drawn for a view once it holds still (the same view two frames running), and a +//! tile around the cursor is read back; the tile arrives a frame or two later, and until it +//! does (and while the view moves) the picker answers from the CPU indexes +//! ([`crate::pick_index`]). The tile only narrows the candidates: the picker's exact tests +//! still decide. Not used for Select Other (every target along the ray), in wireframe (nothing +//! hides an edge there), without a GPU, or for a model past [`MAX_TRIANGLES`]. + +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::sync::{Arc, Mutex}; + +use egui::Pos2; +use solidcraft_engine::doc::ModelState; +use solidcraft_gpu::pick::{PickBuffer, PickOut, PickScene, PickView}; + +use crate::SolveApp; +use crate::viewport::Proj; + +/// Most surface triangles the pass draws (beyond them the CPU indexes answer alone). +pub const MAX_TRIANGLES: usize = 6_000_000; +/// How near the cursor an edge's pixels are looked for (points): vertices pick within 7, edges 6. +const WINDOW: f32 = 8.0; +/// Frames kept coming after a tile is asked for, so its read-back lands. +const FRAMES: u8 = 4; + +/// The pass's scene for one model state: the ids it draws stand for (body, edge). +struct Scene { + state: Arc, + key: u64, + scene: Arc, + /// Per id − 1: (body index in the state, edge index). + edges: Vec<(u32, u32)>, + /// One-point edges (no line to draw): always candidates. + points: Vec<(u32, u32)>, +} + +#[derive(Default)] +pub(crate) struct State { + scene: Mutex>>, + out: PickOut, + /// A pick found no tile for its cursor: the view it was in and the pixel. + want: Mutex>, + /// The view of the last frame (the pass is drawn for a view that held still). + last_view: u64, + /// Frames still to request so read-backs land. + frames: u8, +} + +/// The edges a tile names near the cursor, per body index of the world state. +pub(crate) struct NearEdges { + by_body: HashMap>, +} + +impl NearEdges { + /// Every segment of the named edges of body `index` of `mesh`, as (edge, first point), in + /// edge order. + pub(crate) fn segments(&self, index: usize, mesh: &solidcraft_engine::geom::Mesh) -> Vec<(usize, usize)> { + let mut v = Vec::new(); + for &ei in self.by_body.get(&index).map_or(&[][..], |e| &e[..]) { + let n = mesh.edges.get(ei).map_or(0, |e| e.len().max(2) - 1); + v.extend((0..n).map(|si| (ei, si))); + } + v + } +} + +/// What the pass's scene depends on: the world state, and which bodies show. +fn model_key(app: &SolveApp, st: &Arc) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + (Arc::as_ptr(st) as usize).hash(&mut h); + app.session.revision.hash(&mut h); + app.session.visibility.hidden_bodies.hash(&mut h); + app.session.visibility.hidden_occurrences.hash(&mut h); + h.finish() +} + +/// The view's pixels: the viewport's size in physical pixels. +fn view_size(app: &SolveApp, proj: &Proj) -> [u32; 2] { + let ppp = app.viewport.pixels_per_point(); + [(proj.rect.width() * ppp).round().max(0.0) as u32, (proj.rect.height() * ppp).round().max(0.0) as u32] +} + +/// How far edges are lifted toward the eye: the picker's slack for an edge behind a face. +fn lift(app: &SolveApp) -> f64 { + crate::viewport::scene_radius(app) * 0.02 +} + +/// Everything the drawn ids depend on. +fn view_key(app: &SolveApp, proj: &Proj, model: u64) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + model.hash(&mut h); + for col in proj.vp.to_f32() { + for x in col { + x.to_bits().hash(&mut h); + } + } + view_size(app, proj).hash(&mut h); + lift(app).to_bits().hash(&mut h); + h.finish() +} + +fn usable(app: &SolveApp) -> bool { + app.viewport.gpu.is_some() && app.ui.visual_style != 2 +} + +/// The edges seen within reach of `pos`, when a tile of this view is in; otherwise `None`, and +/// a tile around `pos` is asked for. +pub(crate) fn edges_near(app: &SolveApp, proj: &Proj, pos: Pos2, st: &Arc) -> Option { + if !usable(app) { + return None; + } + let model = model_key(app, st); + let scene = app.viewport.pick_buffer.scene.lock().ok()?.clone().filter(|s| s.key == model && Arc::ptr_eq(&s.state, st)); + let key = view_key(app, proj, model); + let size = view_size(app, proj); + let ppp = app.viewport.pixels_per_point(); + let (x, y) = ((pos.x - proj.rect.left()) * ppp, (pos.y - proj.rect.top()) * ppp); + if !(x >= 0.0 && y >= 0.0 && x < size[0] as f32 && y < size[1] as f32) { + return None; + } + let (x, y) = (x as i64, y as i64); + let r = (WINDOW * ppp).ceil() as i64; + let window = [x - r, y - r, x + r, y + r]; + let ids = scene.as_ref().and_then(|_| app.viewport.pick_buffer.out.lock().ok()?.tile(key, size, window).map(|t| t.ids_in(window))); + let (Some(scene), Some(ids)) = (scene, ids) else { + if let Ok(mut w) = app.viewport.pick_buffer.want.lock() { + *w = Some((key, [x as u32, y as u32])); + } + return None; + }; + let mut by_body: HashMap> = HashMap::new(); + for (b, e) in ids.iter().filter_map(|id| scene.edges.get((*id as usize).checked_sub(1)?)).chain(&scene.points) { + by_body.entry(*b as usize).or_default().push(*e as usize); + } + for v in by_body.values_mut() { + v.sort_unstable(); + v.dedup(); + } + Some(NearEdges { by_body }) +} + +/// The pass's scene for the world state: visible bodies' triangles, and their pickable edges. +/// `None` past [`MAX_TRIANGLES`] or without edges. +fn scene(app: &SolveApp, st: &Arc, key: u64) -> Option> { + let f = |p: solidcraft_engine::geom::Vec3| [p.x as f32, p.y as f32, p.z as f32]; + let mut scene = PickScene::default(); + let (mut edges, mut points, mut triangles) = (Vec::new(), Vec::new(), 0usize); + for (bi, b) in st.bodies.iter().enumerate() { + if !app.session.body_visible(&b.name) { + continue; + } + let m = b.mesh(); + triangles += m.triangles.len(); + if triangles > MAX_TRIANGLES { + return None; + } + for t in &m.triangles { + if let Some([a, b, c]) = m.tri(t) { + scene.triangle([f(a), f(b), f(c)]); + } + } + for (ei, e) in m.edges.iter().enumerate() { + if !m.edge_pickable(ei) || edges.len() >= u32::MAX as usize - 1 { + continue; + } + if e.len() == 1 { + points.push((bi as u32, ei as u32)); + continue; + } + edges.push((bi as u32, ei as u32)); + let id = edges.len() as u32; + for w in e.windows(2) { + scene.segment(f(w[0]), f(w[1]), id); + } + } + } + (!scene.is_empty()).then(|| Arc::new(Scene { state: st.clone(), key, scene: Arc::new(scene), edges, points })) +} + +/// In the frame's GPU paint: draw the pass for a view that held still when a pick asked for a +/// tile, and keep frames coming until the read-back lands. +pub(crate) fn paint(app: &mut SolveApp, ctx: &egui::Context, painter: &egui::Painter, proj: &Proj) { + if !usable(app) { + return; + } + let st = app.session.world_state(); + let model = model_key(app, &st); + let key = view_key(app, proj, model); + let state = &mut app.viewport.pick_buffer; + let still = std::mem::replace(&mut state.last_view, key) == key; + let want = state.want.lock().ok().and_then(|mut w| w.take()).filter(|(k, _)| *k == key && still); + if want.is_none() && state.frames == 0 { + return; + } + state.frames = if want.is_some() { FRAMES } else { state.frames.saturating_sub(1) }; + let cached = state.scene.lock().ok().and_then(|s| s.clone()).filter(|s| s.key == model && Arc::ptr_eq(&s.state, &st)); + let scene = match cached { + Some(s) => s, + None => { + let Some(s) = scene(app, &st, model) else { return }; + if let Ok(mut slot) = app.viewport.pick_buffer.scene.lock() { + *slot = Some(s.clone()); + } + s + } + }; + let e = proj.cam.eye().to_f32(); + let view = PickView { + key, + view_proj: proj.vp.to_f32(), + eye: [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }], + back: proj.cam.back().to_f32(), + lift: lift(app) as f32, + size: view_size(app, proj), + }; + let cb = + PickCallback { scene_key: scene.key, scene: scene.scene.clone(), view, centre: want.map(|w| w.1), out: app.viewport.pick_buffer.out.clone() }; + painter.add(egui_wgpu::Callback::new_paint_callback(proj.rect, cb)); + ctx.request_repaint(); +} + +/// The pass as an egui paint callback: all its work is in `prepare` (it draws into its own +/// textures, not the frame). +struct PickCallback { + scene_key: u64, + scene: Arc, + view: PickView, + centre: Option<[u32; 2]>, + out: PickOut, +} + +impl egui_wgpu::CallbackTrait for PickCallback { + fn prepare( + &self, + device: &egui_wgpu::wgpu::Device, + queue: &egui_wgpu::wgpu::Queue, + _screen: &egui_wgpu::ScreenDescriptor, + encoder: &mut egui_wgpu::wgpu::CommandEncoder, + resources: &mut egui_wgpu::CallbackResources, + ) -> Vec { + if resources.get::().is_none() { + resources.insert(PickBuffer::new(device)); + } + if let Some(pb) = resources.get_mut::() { + pb.prepare(device, queue, encoder, self.scene_key, &self.scene, &self.view, self.centre, &self.out); + } + Vec::new() + } + + fn paint(&self, _info: egui::PaintCallbackInfo, _pass: &mut egui_wgpu::wgpu::RenderPass<'static>, _resources: &egui_wgpu::CallbackResources) {} +} + +#[cfg(test)] +#[path = "pick_buffer_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/pick_buffer_tests.rs b/crates/ui-egui/src/pick_buffer_tests.rs new file mode 100644 index 000000000..393c9498e --- /dev/null +++ b/crates/ui-egui/src/pick_buffer_tests.rs @@ -0,0 +1,141 @@ +use egui::{Rect, pos2}; +use serde_json::json; +use solidcraft_engine::geom::Vec3; +use solidcraft_gpu::pick::{PickTile, TILE, tile_around}; + +use super::*; +use crate::viewport::{Hit, pick, projection}; + +fn app() -> SolveApp { + let mut s = solidcraft_engine::Session::default(); + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); + s.execute("solid.fillet", &json!({"edges": [[40, 15, 20]], "radius": 4})).unwrap(); + s.execute("solid.cylinder", &json!({"radius": 8, "height": 35, "base": [10, 10, 0], "operation": "new_body"})).unwrap(); + let mut app = SolveApp::new(s, crate::Services::default()); + app.ui.show_origin = false; + app.cam.target = Vec3::new(20.0, 15.0, 12.0); + app.cam.distance = 110.0; + // A GPU viewport (no device is needed to hand the picker a tile). + app.viewport.gpu = Some(crate::gpu::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); + app +} + +const RECT: Rect = Rect { min: pos2(0.0, 0.0), max: pos2(640.0, 480.0) }; + +/// Installs the pass's scene, as `paint` makes it, and returns the view's key. +fn install_scene(app: &SolveApp, proj: &Proj) -> u64 { + let st = app.session.world_state(); + let model = model_key(app, &st); + let s = scene(app, &st, model).unwrap(); + *app.viewport.pick_buffer.scene.lock().unwrap() = Some(s); + view_key(app, proj, model) +} + +/// A tile only narrows the edges: the edge it names near the cursor is picked as the CPU picks +/// it, an edge it does not name (hidden there) is not, and without a tile the CPU indexes answer +/// and a tile is asked for. +#[test] +fn a_tile_names_the_edges_the_picker_tests() { + let app = app(); + let proj = projection(&app, RECT); + // A point on the box's top front edge (y = 0, z = 20). + let at = proj.to_screen(Vec3::new(20.0, 0.0, 20.0)).unwrap(); + let cpu = pick(&app, &proj, at); + let Some(Hit::Edge { index, body, .. }) = cpu.iter().find(|h| matches!(h, Hit::Edge { .. })).cloned() else { panic!("{cpu:?}") }; + assert!(app.viewport.pick_buffer.want.lock().unwrap().is_some(), "no tile yet: one is asked for"); + let key = install_scene(&app, &proj); + let st = app.session.world_state(); + let bi = st.bodies.iter().position(|b| b.name == body).unwrap(); + let s = app.viewport.pick_buffer.scene.lock().unwrap().clone().unwrap(); + let id = s.edges.iter().position(|&(b, e)| b as usize == bi && e as usize == index).unwrap() as u32 + 1; + let size = view_size(&app, &proj); + let (origin, tsize) = tile_around([at.x as u32, at.y as u32], size); + let tile = |ids: Vec| PickTile { key, origin, size: tsize, ids }; + let n = (tsize[0] * tsize[1]) as usize; + // The edge's id at the cursor's pixel. + let mut ids = vec![0; n]; + ids[((at.y as u32 - origin[1]) * tsize[0] + (at.x as u32 - origin[0])) as usize] = id; + app.viewport.pick_buffer.out.lock().unwrap().tiles = vec![tile(ids)]; + assert_eq!(pick(&app, &proj, at), cpu, "the named edge is picked as the CPU picks it"); + // A tile naming no edge there: no edge or vertex is picked. + app.viewport.pick_buffer.out.lock().unwrap().tiles = vec![tile(vec![0; n])]; + let none = pick(&app, &proj, at); + assert!(!none.iter().any(|h| matches!(h, Hit::Edge { .. } | Hit::Vertex { .. })), "{none:?}"); + assert!(none.iter().any(|h| matches!(h, Hit::Face { .. })), "faces are still picked: {none:?}"); + // A tile of another view does not answer. + app.viewport.pick_buffer.out.lock().unwrap().tiles = vec![PickTile { key: key ^ 1, ..tile(vec![0; n]) }]; + assert_eq!(pick(&app, &proj, at), cpu); + // Wireframe: nothing hides an edge, and the buffer is not used. + let mut wire = app; + wire.ui.visual_style = 2; + wire.viewport.pick_buffer.out.lock().unwrap().tiles = vec![tile(vec![0; n])]; + assert!(edges_near(&wire, &proj, at, &wire.session.world_state()).is_none()); +} + +/// On a real device: the pass drawn for the view, and picks over a grid of the view helped by its +/// tiles answer as the CPU picks (an edge's pixels and the CPU's visibility test can disagree by +/// a pixel at a silhouette, so a few may differ). Skipped without a GPU adapter. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn picks_through_the_pass_match_the_cpu() { + let Some((_, device, queue)) = crate::gpu::offscreen_device() else { + assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "a GPU is required here"); + eprintln!("skipping: no GPU adapter"); + return; + }; + let mut app = app(); + for (perspective, yaw, pitch) in [(false, 0.6, 0.5), (true, 2.4, 0.3)] { + app.ui.perspective = perspective; + app.cam.yaw = yaw; + app.cam.pitch = pitch; + let proj = projection(&app, RECT); + let key = install_scene(&app, &proj); + let s = app.viewport.pick_buffer.scene.lock().unwrap().clone().unwrap(); + let e = proj.cam.eye().to_f32(); + let view = PickView { + key, + view_proj: proj.vp.to_f32(), + eye: [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }], + back: proj.cam.back().to_f32(), + lift: lift(&app) as f32, + size: view_size(&app, &proj), + }; + let mut pb = PickBuffer::new(&device); + let out = app.viewport.pick_buffer.out.clone(); + // Tiles over the whole view. + let mut wanted = Vec::new(); + for ty in (0..view.size[1]).step_by(TILE as usize - 32) { + for tx in (0..view.size[0]).step_by(TILE as usize - 32) { + wanted.push([tx + TILE / 2, ty + TILE / 2]); + } + } + let mut tiles = Vec::new(); + for c in wanted { + for _ in 0..6 { + let mut encoder = device.create_command_encoder(&Default::default()); + pb.prepare(&device, &queue, &mut encoder, s.key, &s.scene, &view, Some(c), &out); + queue.submit([encoder.finish()]); + let _ = device.poll(egui_wgpu::wgpu::PollType::wait_indefinitely()); + } + tiles.append(&mut out.lock().unwrap().tiles); + } + let (mut same, mut differ, mut edges) = (0, 0, 0); + for j in 0..46 { + for i in 0..62 { + let p = pos2(10.0 + i as f32 * 10.0 + (j % 3) as f32, 10.0 + j as f32 * 10.0); + let r = 8i64; + let w = [p.x as i64 - r, p.y as i64 - r, p.x as i64 + r, p.y as i64 + r]; + let Some(t) = tiles.iter().find(|t| t.covers(key, view.size, w)).cloned() else { continue }; + out.lock().unwrap().tiles = vec![t]; + let through = pick(&app, &proj, p); + out.lock().unwrap().tiles.clear(); + let cpu = pick(&app, &proj, p); + edges += usize::from(cpu.iter().any(|h| matches!(h, Hit::Edge { .. }))); + if through == cpu { same += 1 } else { differ += 1 } + } + } + eprintln!("perspective {perspective}: {same} same, {differ} differ, {edges} with an edge"); + assert!(edges > 100, "the grid reaches edges ({edges})"); + assert!(differ * 100 <= same + differ, "{differ} of {} picks differ", same + differ); + } +} diff --git a/crates/ui-egui/src/pick_index.rs b/crates/ui-egui/src/pick_index.rs new file mode 100644 index 000000000..f19c44eaf --- /dev/null +++ b/crates/ui-egui/src/pick_index.rs @@ -0,0 +1,102 @@ +//! Picking without scanning every triangle and edge: each body mesh's [`MeshIndex`] (its +//! triangles and edge segments in hierarchies), made the first time a pick reaches the body and +//! kept while the mesh is. The viewport's picker asks it for the nearest triangle along the +//! cursor's ray and for the edge segments near that ray, then runs its exact screen tests on +//! those alone. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use egui::{Pos2, vec2}; +use solidcraft_engine::geom::{Mesh, MeshIndex, Vec3}; + +use crate::viewport::Proj; + +/// Indexes by mesh address, each with its mesh held (so the address stays its own). +#[derive(Default)] +pub(crate) struct PickIndexes(Mutex, Arc)>>); + +impl PickIndexes { + /// The index of `mesh`, made now when there is none yet. + pub(crate) fn of(&self, mesh: &Arc) -> Arc { + let key = Arc::as_ptr(mesh) as usize; + let Ok(mut map) = self.0.lock() else { return Arc::new(MeshIndex::new(mesh)) }; + if let Some((_, index)) = map.get(&key) { + return index.clone(); + } + let index = Arc::new(MeshIndex::new(mesh)); + map.insert(key, (mesh.clone(), index.clone())); + index + } + + /// Drops the indexes of meshes `keep` no longer names (a new model state). + pub(crate) fn retain(&self, keep: impl Fn(usize) -> bool) { + if let Ok(mut map) = self.0.lock() { + map.retain(|k, _| keep(*k)); + } + } + + #[cfg(test)] + pub(crate) fn len(&self) -> usize { + self.0.lock().map_or(0, |m| m.len()) + } +} + +/// How far from the ray through `pos` a point may lie and still come within `px` points of it on +/// screen: `a + b·t` at distance `t` along the ray (constant for an orthographic view, widening +/// with depth in perspective), with room to spare. +pub(crate) fn reach(proj: &Proj, pos: Pos2, px: f32) -> (f64, f64) { + let (o, d) = proj.ray(pos); + let (mut a, mut b) = (0.0f64, 0.0f64); + for step in [vec2(px, 0.0), vec2(0.0, px), vec2(-px, 0.0), vec2(0.0, -px)] { + let (o2, d2) = proj.ray(pos + step); + a = a.max(o2.dist(o)); + b = b.max(d2.dist(d)); + } + // A screen offset of `px` along a diagonal, and rounding: half again. + (a * 1.5, b * 1.5) +} + +/// The edge segments of `index` that may come within reach of the ray, as (edge, first point), +/// in edge order and then along each edge: the order a scan of every edge would meet them in. +pub(crate) fn segments_near(index: &MeshIndex, mesh: &Mesh, o: Vec3, d: Vec3, (a, b): (f64, f64)) -> Vec<(usize, usize)> { + let mut v = Vec::new(); + if scanning() { + for (ei, e) in mesh.edges.iter().enumerate() { + v.extend((0..e.len().max(2) - 1).map(|si| (ei, si))); + } + return v; + } + index.segments_near(o, d, a, b, |e, s| v.push((e, s))); + v.sort_unstable(); + v +} + +/// The nearest triangle of `mesh` along the ray, through its index. +pub(crate) fn raycast(index: &MeshIndex, mesh: &Mesh, o: Vec3, d: Vec3) -> Option<(f64, usize)> { + if scanning() { + return mesh.raycast(o, d); + } + index.raycast(mesh, o, d) +} + +#[cfg(test)] +thread_local! { + /// Tests: pick by scanning every triangle and edge, as before the indexes, to compare. + pub(crate) static SCAN: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +fn scanning() -> bool { + #[cfg(test)] + { + SCAN.with(|s| s.get()) + } + #[cfg(not(test))] + { + false + } +} + +#[cfg(test)] +#[path = "pick_index_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/pick_index_tests.rs b/crates/ui-egui/src/pick_index_tests.rs new file mode 100644 index 000000000..ed966233a --- /dev/null +++ b/crates/ui-egui/src/pick_index_tests.rs @@ -0,0 +1,122 @@ +use egui::{Rect, pos2, vec2}; +use serde_json::json; + +use crate::SolveApp; +use crate::viewport::{Hit, pick, pick_all, projection}; + +/// Overlapping bodies with flat and curved faces, filleted edges and seams. +fn assembly() -> SolveApp { + let mut s = solidcraft_engine::Session::default(); + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); + s.execute("solid.fillet", &json!({"edges": [[40, 15, 20]], "radius": 4})).unwrap(); + s.execute("solid.cylinder", &json!({"radius": 8, "height": 35, "base": [10, 10, 0], "operation": "new_body"})).unwrap(); + s.execute("solid.sphere", &json!({"radius": 9, "center": [30, 25, 22]})).unwrap(); + let mut app = SolveApp::new(s, crate::Services::default()); + app.ui.show_origin = false; + app +} + +/// Every cursor position on a grid over the view, for each camera: the indexed pick answers what +/// scanning every triangle and edge answers (the nearest of each kind, and Select Other's list). +#[test] +fn indexed_picks_match_the_full_scan() { + let mut app = assembly(); + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(640.0, 480.0)); + let mut compared = (0, 0, 0); + for (perspective, yaw, pitch) in [(false, 0.6, 0.5), (true, 0.6, 0.5), (true, 2.4, -0.3), (false, 0.0, 1.5)] { + app.ui.perspective = perspective; + app.cam.yaw = yaw; + app.cam.pitch = pitch; + app.cam.target = solidcraft_engine::geom::Vec3::new(20.0, 15.0, 12.0); + app.cam.distance = 110.0; + let proj = projection(&app, rect); + for j in 0..48 { + for i in 0..64 { + let p = pos2(5.0 + i as f32 * 10.0 + (j % 3) as f32, 5.0 + j as f32 * 10.0); + let fast = (pick(&app, &proj, p), pick_all(&app, &proj, p)); + super::SCAN.with(|s| s.set(true)); + let scan = (pick(&app, &proj, p), pick_all(&app, &proj, p)); + super::SCAN.with(|s| s.set(false)); + assert_eq!(fast, scan, "at {p:?} (perspective {perspective}, yaw {yaw}, pitch {pitch})"); + compared.0 += usize::from(fast.0.iter().any(|h| matches!(h, Hit::Face { .. }))); + compared.1 += usize::from(fast.0.iter().any(|h| matches!(h, Hit::Edge { .. }))); + compared.2 += usize::from(fast.0.iter().any(|h| matches!(h, Hit::Vertex { .. }))); + } + } + } + // The grid reaches every kind many times over. + assert!(compared.0 > 2000 && compared.1 > 100 && compared.2 > 10, "{compared:?}"); + assert_eq!(app.viewport.pick_index.len(), 3, "one index per body mesh"); +} + +/// A new model state lets go of the indexes of meshes it no longer has. +#[test] +fn indexes_follow_the_model_state() { + let mut app = assembly(); + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(640.0, 480.0)); + app.cam.target = solidcraft_engine::geom::Vec3::new(20.0, 15.0, 12.0); + let proj = projection(&app, rect); + let centre = proj.to_screen(solidcraft_engine::geom::Vec3::new(20.0, 15.0, 10.0)).unwrap(); + pick(&app, &proj, centre); + assert!(app.viewport.pick_index.len() >= 1); + app.session.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "corner": [-20, -20, 0], "operation": "new_body"})).unwrap(); + pick(&app, &proj, centre); + assert!(app.viewport.pick_index.len() <= 4, "indexes of meshes gone with the old state are dropped"); + app.session.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "corner": [-40, -20, 0], "operation": "new_body"})).unwrap(); + pick(&app, &proj, centre); + assert!(app.viewport.pick_index.len() <= 5); +} + +/// Timing, not a check (`cargo test -p solidcraft-ui-egui --lib pick_timing -- --ignored +/// --nocapture`): picks over a grid of the view, scanning every triangle and edge versus through +/// the indexes, on many curved bodies and on one body with many curved faces. +#[test] +#[ignore] +fn pick_timing_on_curved_models() { + let mut many = solidcraft_engine::Session::default(); + for i in 0..12 { + for j in 0..12 { + let (x, y) = (f64::from(i) * 30.0, f64::from(j) * 30.0); + many.execute("solid.cylinder", &json!({"radius": 9, "height": 30, "base": [x, y, 0], "operation": "new_body"})).unwrap(); + many.execute("solid.sphere", &json!({"radius": 8, "center": [x, y, 40], "operation": "new_body"})).unwrap(); + } + } + let mut one = solidcraft_engine::Session::default(); + one.execute("solid.box", &json!({"length": 340, "width": 340, "height": 10, "corner": [-15, -15, -5]})).unwrap(); + for i in 0..8 { + for j in 0..8 { + let (x, y) = (f64::from(i) * 42.0, f64::from(j) * 42.0); + one.execute("solid.cylinder", &json!({"radius": 14, "height": 30, "base": [x, y, 0], "operation": "join"})).unwrap(); + } + } + for (name, s) in [("many bodies", many), ("one body", one)] { + let mut app = SolveApp::new(s, crate::Services::default()); + app.ui.show_origin = false; + app.cam.target = solidcraft_engine::geom::Vec3::new(160.0, 160.0, 15.0); + app.cam.distance = 900.0; + let st = app.session.world_state(); + let (tris, segs) = st + .bodies + .iter() + .map(|b| b.mesh()) + .fold((0, 0), |(t, s), m| (t + m.triangles.len(), s + m.edges.iter().map(|e| e.len().saturating_sub(1)).sum::())); + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(1400.0, 900.0)); + let proj = projection(&app, rect); + let points: Vec<_> = (0..20).flat_map(|j| (0..30).map(move |i| pos2(30.0 + i as f32 * 45.0, 30.0 + j as f32 * 42.0))).collect(); + // Indexes made once, before timing. + for p in &points { + pick(&app, &proj, *p); + } + let time = |scan: bool| { + super::SCAN.with(|s| s.set(scan)); + let t = std::time::Instant::now(); + for p in &points { + std::hint::black_box(pick(&app, &proj, *p)); + } + super::SCAN.with(|s| s.set(false)); + t.elapsed().as_secs_f64() * 1000.0 / points.len() as f64 + }; + let (scan, indexed) = (time(true), time(false)); + eprintln!("{name}: {} bodies, {tris} triangles, {segs} edge segments: scan {scan:.3} ms per pick, indexed {indexed:.3} ms", st.bodies.len()); + } +} diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index c52887920..989c9f2a3 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -332,6 +332,8 @@ pub struct Prefs { pub save_mesh_format: String, /// Hidden edges in the current-view DXF export (false: omit, true: dashed). pub view_dxf_dashed: bool, + /// Model-space chord tolerance for current-view DXF curves, in millimetres. + pub view_dxf_tolerance: f64, pub save_mesh_send: bool, pub save_mesh_slicer: String, pub custom_slicers: Vec, @@ -428,6 +430,7 @@ impl Default for Prefs { update: crate::update::Memo::default(), save_mesh_format: "stl".into(), view_dxf_dashed: false, + view_dxf_tolerance: 0.01, save_mesh_send: false, save_mesh_slicer: String::new(), custom_slicers: Vec::new(), diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index f9433aecd..7df2a8792 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -905,6 +905,235 @@ fn variable_fillet_mid_radii_round_trip() { assert_eq!(p["params"]["mid"], json!([]), "{p}"); } +/// Use an actual mesh point, as a viewport pick does; analytic cylinder points need not lie +/// on the display mesh's facets. +fn thread_face(app: &SolveApp, body: &str) -> Sel { + let state = app.session.world_state(); + let body_state = state.body(body).unwrap(); + let index = solidcraft_engine::doc::naming::face_spots(body_state) + .into_iter() + .enumerate() + .find_map(|(index, spot)| { + spot.filter(|spot| matches!(spot.surface, Some(solidcraft_engine::kernel::FaceSurface::Cylinder { .. }))).map(|_| index) + }) + .unwrap(); + let mesh = body_state.mesh(); + let point = mesh + .triangles + .iter() + .zip(&mesh.tri_face) + .find_map(|(triangle, face)| { + if *face as usize != index { + return None; + } + mesh.tri(triangle).map(|[a, b, c]| (a + b + c) / 3.0) + }) + .unwrap(); + Sel::Face { body: body.into(), index, point } +} + +#[test] +fn thread_size_suggestion_matches_the_feature_for_shafts_and_holes() { + for (diameter, internal, expected) in [(8.0, false, "M8"), (20.0, false, "M20"), (5.0, true, "M6")] { + let mut app = app_with(json!([])); + if internal { + app.run("solid.box", json!({"corner":[-10,-10,0],"length":20,"width":20,"height":10})).unwrap(); + } + app.run("solid.cylinder", json!({"radius":diameter / 2.0,"height":10,"body_name":"Cylinder"})).unwrap(); + if internal { + app.run("solid.combine", json!({"target":"Body1","tools":["Cylinder"],"operation":"cut"})).unwrap(); + } + let pick = thread_face(&app, if internal { "Body1" } else { "Cylinder" }); + let saved = app.session.doc.to_json(); + let d = start(&mut app, vec![pick], "solid.thread"); + assert!(matches!(&d.kind, Kind::Thread { designation, .. } if designation == expected), "{:?}", d.kind); + assert_eq!(app.session.doc.to_json(), saved, "suggesting a size is read-only"); + let (command, params) = apply_commands(&app, &d).unwrap().remove(0); + assert!(params.get("designation").is_none(), "an automatic size stays automatic"); + let result = app.session.execute(&command, ¶ms).unwrap(); + assert_eq!(result["thread"]["designation"], expected); + assert_eq!(result["thread"]["internal"], internal); + } +} + +#[test] +fn thread_size_suggestion_follows_picks_without_overwriting_manual_sizes() { + let mut app = app_with(json!([ + {"command":"solid.cylinder","params":{"radius":4,"height":10}}, + {"command":"solid.cylinder","params":{"base":[30,0,0],"radius":10,"height":10}}, + {"command":"solid.cylinder","params":{"base":[200,0,0],"radius":50,"height":10}} + ])); + let small = thread_face(&app, "Body1"); + let large = thread_face(&app, "Body2"); + let unsupported = thread_face(&app, "Body3"); + let planar = crate::dialogs::face_sel(&app.session, Vec3::new(0.0, 0.0, 10.0)).unwrap(); + let mut d = start(&mut app, vec![], "solid.thread"); + for (pick, expected) in [ + (small.clone(), "M8"), + (large.clone(), "M20"), + (large.clone(), "M20"), + (small.clone(), "M8"), + (unsupported, ""), + (small.clone(), "M8"), + (planar, ""), + ] { + d.pick(&app.session, pick); + assert!(matches!(&d.kind, Kind::Thread { designation, .. } if designation == expected), "{:?}", d.kind); + } + d.take_box(&app.session, vec![], false); + assert!(matches!(&d.kind, Kind::Thread { designation, .. } if designation.is_empty())); + d.take_box(&app.session, vec![small], false); + assert!(matches!(&d.kind, Kind::Thread { designation, .. } if designation == "M8")); + if let Kind::Thread { designation, .. } = &mut d.kind { + *designation = "M8x1".into(); + } + d.pick(&app.session, large); + assert!(matches!(&d.kind, Kind::Thread { designation, .. } if designation == "M8x1")); + assert_eq!(apply_commands(&app, &d).unwrap()[0].1["designation"], "M8x1"); +} + +#[test] +fn thread_size_suggestion_reopens_without_changing_saved_thread_parameters() { + for designation in [None, Some("M8"), Some("M8x1")] { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.cylinder", json!({"radius":4,"height":10})).unwrap(); + let Sel::Face { point, .. } = thread_face(&h.app, "Body1") else { panic!("a face") }; + let mut params = json!({"face":point}); + if let Some(size) = designation { + params["designation"] = json!(size); + } + let id = h.app.run("solid.thread", params).unwrap()["feature"].as_u64().unwrap(); + let before = h.app.session.doc.feature(id).unwrap().kind.clone(); + h.app.edit_feature(id); + h.frames(2); + let d = h.app.dialog.as_ref().unwrap(); + assert!(matches!(&d.kind, Kind::Thread { designation: size, .. } if size == designation.unwrap_or("M8")), "{d:?}"); + let (command, params) = apply_commands(&h.app, d).unwrap().remove(0); + h.app.session.execute(&command, ¶ms).unwrap(); + assert_eq!(h.app.session.doc.feature(id).unwrap().kind, before); + } +} + +#[test] +fn thread_size_suggestion_can_be_cleared_and_edited_in_the_dialog() { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.cylinder", json!({"radius":4,"height":10})).unwrap(); + let pick = thread_face(&h.app, "Body1"); + h.app.session.selection = vec![pick.clone()]; + h.step(&json!({"start":"solid.thread"})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:clear:Cylindrical face"}})).unwrap(); + assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Thread { designation, .. } if designation.is_empty())); + h.app.dialog.as_mut().unwrap().pick(&h.app.session, pick.clone()); + h.frames(2); + h.step(&json!({"click":{"handle":"dialog:thread_size"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + // Even deliberately typing the same size turns it into an explicit override. + h.step(&json!({"text":"M8"})).unwrap(); + let d = h.app.dialog.as_ref().unwrap(); + assert_eq!(apply_commands(&h.app, d).unwrap()[0].1["designation"], "M8"); + h.step(&json!({"click":{"handle":"dialog:clear:Cylindrical face"}})).unwrap(); + h.app.dialog.as_mut().unwrap().pick(&h.app.session, pick); + h.frames(2); + assert_eq!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap()[0].1["designation"], "M8"); +} + +#[test] +fn thread_choices_apply_a_fine_pitch_and_partial_modelled_thread() { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.cylinder", json!({"radius":4,"height":10})).unwrap(); + h.app.session.selection = vec![thread_face(&h.app, "Body1")]; + h.step(&json!({"start":"solid.thread"})).unwrap(); + let saved = h.app.session.doc.to_json(); + for handle in ["dialog:Pitch", "dialog:Pitch:1 mm", "dialog:Full Length", "dialog:Length"] { + h.step(&json!({"click":{"handle":handle}})).unwrap(); + } + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"4 mm"})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Modeled"}})).unwrap(); + let (command, params) = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0); + assert_eq!(params["designation"], "M8x1"); + assert_eq!(params["length"], "4 mm"); + assert_eq!(params["modeled"], true); + assert_eq!(h.app.session.doc.to_json(), saved, "changing options only previews"); + let before = h.app.session.world_state().body("Body1").unwrap().mesh().measure().volume; + let result = h.app.session.execute(&command, ¶ms).unwrap(); + let state = h.app.session.world_state(); + let after = state.body("Body1").unwrap().mesh().measure().volume; + assert!(before - after > 1.0, "the selected fine pitch must cut the shaft"); + let id = result["feature"].as_u64().unwrap(); + let kind = &h.app.session.doc.feature(id).unwrap().kind; + assert!(matches!(kind, solidcraft_engine::doc::FeatureKind::Thread { designation: Some(d), length: Some(l), modeled: true, .. } + if d == "M8x1" && l == "4 mm")); +} + +#[test] +fn thread_choices_reset_to_the_face_and_can_freeze_the_same_size() { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.cylinder", json!({"radius":4,"height":10})).unwrap(); + h.app.session.selection = vec![thread_face(&h.app, "Body1")]; + h.step(&json!({"start":"solid.thread"})).unwrap(); + for handle in ["dialog:Size", "dialog:Size:6 mm", "dialog:Pitch", "dialog:Pitch:0.75 mm"] { + h.step(&json!({"click":{"handle":handle}})).unwrap(); + } + let d = h.app.dialog.as_ref().unwrap(); + assert_eq!(apply_commands(&h.app, d).unwrap()[0].1["designation"], "M6x0.75"); + h.step(&json!({"click":{"handle":"dialog:Automatic size"}})).unwrap(); + h.frames(2); + let d = h.app.dialog.as_ref().unwrap(); + assert!(matches!(&d.kind, Kind::Thread { designation, .. } if designation == "M8")); + assert!(apply_commands(&h.app, d).unwrap()[0].1.get("designation").is_none()); + h.step(&json!({"click":{"handle":"dialog:Automatic size"}})).unwrap(); + assert_eq!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap()[0].1["designation"], "M8"); +} + +#[test] +fn thread_choices_preserve_custom_saved_pairs_and_offer_large_fine_pitches() { + for (diameter, designation) in [(7.3, "M7.3x0.6"), (56.0, "M56")] { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.cylinder", json!({"radius":diameter / 2.0,"height":10})).unwrap(); + let Sel::Face { point, .. } = thread_face(&h.app, "Body1") else { panic!("a face") }; + let id = h.app.run("solid.thread", json!({"face":point,"designation":designation})).unwrap()["feature"].as_u64().unwrap(); + h.app.edit_feature(id); + h.frames(2); + assert!(h.widget(&format!("{diameter} mm")).is_some()); + assert!(h.widget(if diameter == 56.0 { "5.5 mm" } else { "0.6 mm" }).is_some()); + let (_, params) = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0); + assert_eq!(params["params"]["designation"], designation); + if diameter == 56.0 { + for handle in ["dialog:Pitch", "dialog:Pitch:2 mm"] { + h.step(&json!({"click":{"handle":handle}})).unwrap(); + } + let (command, params) = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0); + assert_eq!(params["params"]["designation"], "M56x2"); + h.app.session.execute(&command, ¶ms).unwrap(); + let mut reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + // This test submits the edit command directly; finish the editor's rollback + // before checking the complete saved design. + reopened.marker = None; + let session = Session::new(reopened); + assert_eq!(session.world_state().threads[0].designation, "M56x2"); + } + } +} + +#[test] +fn thread_choices_can_start_without_a_face_and_recover_from_invalid_text() { + let mut h = crate::scenario::Harness::new(); + h.step(&json!({"start":"solid.thread"})).unwrap(); + for handle in ["dialog:Size", "dialog:Size:8 mm", "dialog:thread_size"] { + h.step(&json!({"click":{"handle":handle}})).unwrap(); + } + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"Munknown"})).unwrap(); + h.frames(2); + assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Thread { designation, .. } if designation == "Munknown")); + for handle in ["dialog:Size", "dialog:Size:8 mm"] { + h.step(&json!({"click":{"handle":handle}})).unwrap(); + } + assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Thread { designation, .. } if designation == "M8x1.25")); + assert!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).is_err(), "a face is still required"); +} + #[test] fn newer_options_reach_their_commands() { let mut app = boxed(); diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index f234ab8af..04e00bb34 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -207,6 +207,7 @@ fn motion_key(cmds: &[(String, Value)], revision: u64, colors: Colors) -> Option | "joint.gear" | "joint.rack_pinion" | "joint.screw" + | "joint.cam" ) }) { @@ -856,6 +857,15 @@ mod tests { }; assert!(motion_key(&gear("0 deg"), 7, colors()).is_some()); assert_eq!(motion_key(&gear("0 deg"), 7, colors()), motion_key(&gear("90 deg"), 7, colors())); + // So does a cam dialog turning its cam. + let cam = |angle: &str| { + vec![ + ("joint.cam".to_string(), json!({"a": 1, "b": 2, "profile": {"sketch": 3}})), + ("joint.drive".to_string(), json!({"joint": 1, "values": [angle]})), + ] + }; + assert!(motion_key(&cam("0 deg"), 7, colors()).is_some()); + assert_eq!(motion_key(&cam("0 deg"), 7, colors()), motion_key(&cam("90 deg"), 7, colors())); } /// Combine previews its result (cut, join or intersect between existing bodies) without an diff --git a/crates/ui-egui/src/render_workspace_tests.rs b/crates/ui-egui/src/render_workspace_tests.rs index 4c53f2160..28786bf99 100644 --- a/crates/ui-egui/src/render_workspace_tests.rs +++ b/crates/ui-egui/src/render_workspace_tests.rs @@ -32,7 +32,15 @@ fn opaque_pbr_product_gpu_and_cpu_share_color_and_material_semantics() { let eye = camera.eye().to_f32(); let mut task = ImageTask::new( scene, - ImageRequest { camera, width: SIZE, height: SIZE, background: [255; 3], transparent_background: false }, + ImageRequest { + integrator: Default::default(), + raytrace: None, + camera, + width: SIZE, + height: SIZE, + background: [255; 3], + transparent_background: false, + }, CancelToken::default(), ) .unwrap(); diff --git a/crates/ui-egui/src/update.rs b/crates/ui-egui/src/update.rs index 508f72b46..d46d8931e 100644 --- a/crates/ui-egui/src/update.rs +++ b/crates/ui-egui/src/update.rs @@ -29,8 +29,16 @@ pub const REPO: &str = "bherbruck/solidcraft"; pub const LATEST_API: &str = "https://api.github.com/repos/bherbruck/solidcraft/releases/latest"; /// Where Download goes when no package fits this installation. pub const RELEASES_PAGE: &str = "https://github.com/bherbruck/solidcraft/releases/latest"; -/// Release pages and assets must be on GitHub, under this repository. -const RELEASE_PREFIX: &str = "https://github.com/bherbruck/solidcraft/releases/"; +/// Release pages and assets must be on GitHub, under this repository. The repository is moving +/// to the `tangency-labs` organisation, so releases may name either owner (the API request stays +/// on the old name, which GitHub redirects after a transfer). +const RELEASE_PREFIXES: [&str; 2] = ["https://github.com/bherbruck/solidcraft/releases/", "https://github.com/tangency-labs/solidcraft/releases/"]; + +/// A release page or asset URL: github.com, one of the two owners, exactly `solidcraft`, then +/// `/releases/` (the trailing slash rules out look-alike names such as `solidcraft-evil`). +fn is_release_url(url: &str) -> bool { + RELEASE_PREFIXES.iter().any(|p| url.starts_with(p)) +} /// While the app stays open, automatic checks run once a day (every start checks too). pub const CHECK_INTERVAL_S: f64 = 24.0 * 3600.0; @@ -358,7 +366,7 @@ impl Release { notes.truncate(cut); notes.push_str("\n\n…"); } - let page = Some(s("html_url")).filter(|u| u.starts_with(RELEASE_PREFIX)).unwrap_or_else(|| RELEASES_PAGE.to_string()); + let page = Some(s("html_url")).filter(|u| is_release_url(u)).unwrap_or_else(|| RELEASES_PAGE.to_string()); let assets = v .get("assets") .and_then(Value::as_array) @@ -368,7 +376,7 @@ impl Release { .filter_map(|a| { let name = a.get("name")?.as_str()?.to_string(); let url = a.get("browser_download_url")?.as_str()?.to_string(); - url.starts_with(RELEASE_PREFIX).then(|| Asset { name, url, size: a.get("size").and_then(Value::as_u64).unwrap_or(0) }) + is_release_url(&url).then(|| Asset { name, url, size: a.get("size").and_then(Value::as_u64).unwrap_or(0) }) }) .collect(); Ok(Release { @@ -697,8 +705,13 @@ fn poll_install(app: &mut SolveApp) { app.updater.job = None; match &result { Ok(install::Outcome::Installer(program, args)) => { - // The installer replaces this program: start it once SolidCraft has closed. - app.updater.launch = Some((program.clone(), args.clone())); + // The installer replaces this program: start it once SolidCraft has closed. On + // Windows the installer is followed by the new version (see install::relaunch_after). + app.updater.launch = Some(match std::env::current_exe() { + #[cfg(windows)] + Ok(exe) => install::relaunch_after(program, args, &exe), + _ => (program.clone(), args.clone()), + }); crate::documents::request_quit(app); } Ok(install::Outcome::Opened(dmg)) => { diff --git a/crates/ui-egui/src/update/install.rs b/crates/ui-egui/src/update/install.rs index 8ec8325c8..7f72cc10a 100644 --- a/crates/ui-egui/src/update/install.rs +++ b/crates/ui-egui/src/update/install.rs @@ -107,6 +107,26 @@ pub fn sha256_file(path: &Path) -> Result { Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect()) } +/// The command that runs an installer, waits for it to finish and then starts `exe` (the +/// installed program), so the app comes back after an update. Windows has no `wait && start` in +/// a plain process spawn, so PowerShell does the waiting; the installer's exit code is ignored on +/// purpose: when the user cancels it, the old version is still there to start. +pub fn relaunch_after(installer: &Path, args: &[String], exe: &Path) -> (PathBuf, Vec) { + // PowerShell single-quoted string: only `'` needs doubling. + let q = |s: &str| format!("'{}'", s.replace('\'', "''")); + // msiexec splits its command line itself, so an argument with spaces needs its own quotes. + let list = args.iter().map(|a| if a.contains(' ') { q(&format!("\"{a}\"")) } else { q(a) }).collect::>().join(","); + let script = format!( + "Start-Process -FilePath {} -ArgumentList {list} -Wait; Start-Process -FilePath {}", + q(&installer.to_string_lossy()), + q(&exe.to_string_lossy()) + ); + ( + PathBuf::from("powershell"), + vec!["-NoProfile".into(), "-NonInteractive".into(), "-WindowStyle".into(), "Hidden".into(), "-Command".into(), script], + ) +} + /// `sums` is signed by `key` (minisign, prehashed) with a trusted comment naming `tag`. pub fn verify_signature(sums: &[u8], signature: &str, key: &str, tag: &str) -> Result<(), String> { let key = minisign_verify::PublicKey::from_base64(key.trim()).map_err(|e| format!("update signing key: {e}"))?; diff --git a/crates/ui-egui/src/update/install_tests.rs b/crates/ui-egui/src/update/install_tests.rs index cd1d8bc37..3829203db 100644 --- a/crates/ui-egui/src/update/install_tests.rs +++ b/crates/ui-egui/src/update/install_tests.rs @@ -203,3 +203,18 @@ fn installers_and_disk_images_are_handed_over() { assert_eq!(apply(&Method::Dmg, &pkg).unwrap(), Outcome::Opened(pkg.clone())); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn windows_installer_is_followed_by_the_new_version() { + let args = vec!["/i".to_string(), r"C:\Users\a b\Temp\solidcraft-update\x.msi".to_string(), "/passive".to_string()]; + let (program, out) = relaunch_after(Path::new("msiexec"), &args, Path::new(r"C:\Program Files\SolidCraft\it's.exe")); + assert_eq!(program, PathBuf::from("powershell")); + assert_eq!( + out.last().unwrap(), + &concat!( + r#"Start-Process -FilePath 'msiexec' -ArgumentList '/i','"C:\Users\a b\Temp\solidcraft-update\x.msi"','/passive' -Wait; "#, + r"Start-Process -FilePath 'C:\Program Files\SolidCraft\it''s.exe'" + ) + ); + assert!(out.iter().any(|a| a == "-Command")); +} diff --git a/crates/ui-egui/src/update/tests.rs b/crates/ui-egui/src/update/tests.rs index 9bcab45aa..3b014cdf8 100644 --- a/crates/ui-egui/src/update/tests.rs +++ b/crates/ui-egui/src/update/tests.rs @@ -441,3 +441,32 @@ fn release_notes_read_as_markdown() { } assert_eq!(inline("**[x](y)**"), vec![Span::Strong("x".into())]); } + +#[test] +fn releases_under_either_owner_are_accepted() { + let parse = |owner: &str| { + let base = format!("https://github.com/{owner}/releases"); + Release::parse( + json!({"tag_name": "v1.0.0", "html_url": format!("{base}/tag/v1.0.0"), "assets": [ + {"name": "solidcraft-windows-x64.msi", "browser_download_url": format!("{base}/download/v1.0.0/solidcraft-windows-x64.msi")}, + ]}) + .to_string() + .as_bytes(), + ) + .unwrap() + }; + for owner in ["bherbruck/solidcraft", "tangency-labs/solidcraft"] { + let r = parse(owner); + assert_eq!(r.page, format!("https://github.com/{owner}/releases/tag/v1.0.0")); + assert_eq!(r.assets.len(), 1, "{owner}"); + } + // Any other owner, repository, host or scheme is dropped. + for owner in ["evil/solidcraft", "tangency-labs/solidcraft-evil", "tangency-labs.evil/solidcraft", "bherbruck/other"] { + let r = parse(owner); + assert_eq!(r.page, RELEASES_PAGE, "{owner}"); + assert!(r.assets.is_empty(), "{owner}"); + } + assert!(!is_release_url("http://github.com/tangency-labs/solidcraft/releases/x")); + assert!(!is_release_url("https://github.com.evil.example/tangency-labs/solidcraft/releases/x")); + assert!(!is_release_url("https://github.com/tangency-labs/solidcraft/issues/1")); +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index ac7b5c028..3fb11a41c 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -55,6 +55,11 @@ pub struct ViewportState { lod_view: u64, /// Each body mesh's box (the mesh held, so its address stays its own), from the last state. mesh_bounds: std::sync::Mutex, solidcraft_engine::geom::Aabb3)>>, + /// 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. + pub(crate) pick_index: crate::pick_index::PickIndexes, + /// The GPU pick buffer's scene, read-backs and requests. + pub(crate) pick_buffer: crate::pick_buffer::State, /// The last click in the view was the middle button's (for the middle double-click). pub(crate) middle_clicked: bool, /// The last pick (its key and hits): reused while nothing it depends on changed. @@ -72,6 +77,8 @@ pub struct ViewportState { pub(crate) display: std::sync::Mutex, hl_slot: SceneSlot, hl_key: u64, + /// Browser/timeline body feedback, independent of the camera and reference widget scale. + hover_block: std::sync::Mutex>, pub nav: Option, /// The preset's navigation for the left-button drag under way (Alias: Shift+Alt), taken /// when the button went down, so the drag neither selects nor moves sketch geometry. @@ -886,9 +893,9 @@ pub fn origin_planes(app: &SolveApp) -> Vec<(&'static str, Vec3, [Vec3; 4])> { if !app.origin_visible() { return Vec::new(); } - // While the Origin is hidden, Create Sketch may bring the planes back (empty design): then - // every plane; otherwise only those not hidden one by one. - let creating = !app.ui.show_origin && app.dialog.as_ref().is_some_and(|d| matches!(d.kind, crate::dialogs::Kind::Sketch)); + // While the Origin is hidden, Create Sketch brings the planes back: then every plane; + // otherwise only those not hidden one by one. + let creating = !app.ui.show_origin && app.picking_sketch_plane(); origin_quads(origin_size(app.cam.half_height())) .into_iter() .filter(|(n, _, _)| creating || !app.session.visibility.hidden_origin.iter().any(|h| h == n)) @@ -919,11 +926,16 @@ pub fn origin_axes(app: &SolveApp) -> Vec<(&'static str, Vec3)> { /// past it either side), at least the origin axes' length around the axis's origin: (name, /// from, to). pub fn construction_axis_segments(app: &SolveApp) -> Vec<(String, Vec3, Vec3)> { - let h = origin_size(app.cam.half_height()) * AXIS_LEN; - let bb = view_bounds(app); - solidcraft_engine::view::construction_axes(&app.session) + let axes: Vec<_> = solidcraft_engine::view::construction_axes(&app.session) .into_iter() .filter(|(_, n, _, _)| !app.session.visibility.hidden_origin.contains(n)) + .collect(); + if axes.is_empty() { + return Vec::new(); + } + let h = origin_size(app.cam.half_height()) * AXIS_LEN; + let bb = view_bounds(app); + axes.into_iter() .map(|(_, name, o, d)| { let (mut lo, mut hi) = (-h, h); if !bb.is_empty() { @@ -996,6 +1008,7 @@ fn body_bounds( }) .collect::>(), ); + app.viewport.pick_index.retain(|k| now.contains_key(&k)); if let Ok(mut k) = app.viewport.mesh_bounds.lock() { *k = now; } @@ -1182,7 +1195,6 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool, let s = &app.session; let st = s.world_state(); let bounds = body_bounds(app, &st); - let bound = |name: &str| bounds.iter().find(|(n, _)| n == name).map(|(_, b)| *b); let mut hits = Vec::new(); let (o, d) = proj.ray(pos); // Sketch points of the active sketch (of every shown sketch while a command takes points, @@ -1247,21 +1259,23 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool, // Nearest face along the ray (hides what is behind it); with `all`, every body's nearest. let mut bestf: Option<(f64, Hit)> = None; let mut faces = Near::new(all); - for b in &st.bodies { + // Bounds retain the state's body order. Looking each one up by name made both passes + // quadratic for assemblies with many small parts. + for (i, b) in st.bodies.iter().enumerate() { if !app.session.body_visible(&b.name) { continue; } // Bodies whose box the ray misses (or enters behind the best hit so far) are skipped. - if let Some(bb) = bound(&b.name) { + if let Some((_, bb)) = bounds.get(i) { let pad = bb.diagonal() * 1e-6 + 1e-9; - match ray_box(o, d, &bb, pad) { + match ray_box(o, d, bb, pad) { None => continue, Some(t0) if !all && bestf.as_ref().is_some_and(|(bt, _)| t0 > *bt) => continue, _ => {} } } let m = b.mesh(); - if let Some((t, ti)) = m.raycast(o, d) { + if let Some((t, ti)) = crate::pick_index::raycast(&app.viewport.pick_index.of(&m), &m, o, d) { let fi = m.tri_face.get(ti).copied().unwrap_or(0) as usize; let hit = Hit::Face { body: b.name.clone(), index: fi, point: o + d * t }; if bestf.as_ref().is_none_or(|(bt, _)| t < *bt) { @@ -1276,40 +1290,55 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool, // Wireframe draws no faces, so nothing hides an edge or a vertex. let wireframe = app.ui.visual_style == 2; let visible = |p: Vec3| wireframe || bestf.as_ref().is_none_or(|(t, _)| (p - o).dot(d) <= *t + slack); - // Vertices (edge end points) and edges. + // Vertices (edge end points) and edges, within 7 and 6 points of the cursor. + let reach = crate::pick_index::reach(proj, pos, 8.0); + // The edges seen near the cursor, when the GPU pick buffer has them for this view (Select + // Other wants hidden ones too). + let seen = if all { None } else { crate::pick_buffer::edges_near(app, proj, pos, &st) }; let mut bestv = Near::new(all); let mut beste = Near::new(all); - for b in &st.bodies { + for (i, b) in st.bodies.iter().enumerate() { if !app.session.body_visible(&b.name) { continue; } // Only bodies whose outline on screen is near the cursor can have an edge under it. - if let Some(bb) = bound(&b.name) - && screen_box(proj, &bb, 8.0).is_some_and(|r| !r.contains(pos)) + if let Some((_, bb)) = bounds.get(i) + && screen_box(proj, bb, 8.0).is_some_and(|r| !r.contains(pos)) { continue; } let m = b.mesh(); - for (ei, e) in m.edges.iter().enumerate() { + // Only the segments that can come near the cursor: of the edges the pick buffer sees + // there, else from the index. Either way in the order a scan of every edge would meet + // them, so ties go the same way. + let near = match &seen { + Some(seen) => seen.segments(i, &m), + None => crate::pick_index::segments_near(&app.viewport.pick_index.of(&m), &m, o, d, reach), + }; + let mut last_edge = None; + for (ei, si) in near { + let Some(e) = m.edges.get(ei) else { continue }; if !m.edge_pickable(ei) { continue; } - for v in [e.first(), e.last()].into_iter().flatten() { - if let Some(sp) = proj.to_screen(*v) { - let dd = sp.distance(pos); - if dd < 7.0 && visible(*v) && bestv.wants(dd) { - bestv.offer(dd, Hit::Vertex { body: b.name.clone(), point: *v }); + if last_edge != Some(ei) { + last_edge = Some(ei); + for v in [e.first(), e.last()].into_iter().flatten() { + if let Some(sp) = proj.to_screen(*v) { + let dd = sp.distance(pos); + if dd < 7.0 && visible(*v) && bestv.wants(dd) { + bestv.offer(dd, Hit::Vertex { body: b.name.clone(), point: *v }); + } } } } - for w in e.windows(2) { - let (Some(a), Some(c)) = (proj.to_screen(w[0]), proj.to_screen(w[1])) else { continue }; - let dd = seg_dist(pos, a, c); - // Visible where the cursor is: the edge's point under the cursor, not an end or - // the middle, which can lie deeper than the face the cursor is on. - if dd < 6.0 && beste.wants(dd) && visible(ray_segment_closest(o, d, w[0], w[1])) { - beste.offer(dd, Hit::Edge { body: b.name.clone(), index: ei, mid: polyline_mid(e) }); - } + let (Some(p0), Some(p1)) = (e.get(si), e.get(si + 1)) else { continue }; + let (Some(a), Some(c)) = (proj.to_screen(*p0), proj.to_screen(*p1)) else { continue }; + let dd = seg_dist(pos, a, c); + // Visible where the cursor is: the edge's point under the cursor, not an end or + // the middle, which can lie deeper than the face the cursor is on. + if dd < 6.0 && beste.wants(dd) && visible(ray_segment_closest(o, d, *p0, *p1)) { + beste.offer(dd, Hit::Edge { body: b.name.clone(), index: ei, mid: polyline_mid(e) }); } } } @@ -1728,8 +1757,14 @@ fn edge_of(m: &solidcraft_engine::geom::Mesh, index: usize, point: Vec3) -> Opti } fn face_tris(sc: &mut GpuScene, m: &solidcraft_engine::geom::Mesh, face: usize, col: [u8; 4], lit: bool) { + mesh_tris(sc, m, col, lit, |f| f as usize == face); +} + +/// Emit a set of faces in one mesh pass. Whole-body feedback must not scan every triangle +/// again for each face of a detailed imported part. +fn mesh_tris(sc: &mut GpuScene, m: &solidcraft_engine::geom::Mesh, col: [u8; 4], lit: bool, takes: impl Fn(u32) -> bool) { for (t, f) in m.triangles.iter().zip(&m.tri_face) { - if *f as usize != face { + if !takes(*f) { continue; } for k in t { @@ -1797,22 +1832,35 @@ pub(crate) fn profile_fill(sc: &mut GpuScene, app: &SolveApp, sketch: u64, index } /// An origin or construction plane: reference geometry, which a section does not cut (#1229). -fn quad(sc: &mut GpuScene, q: &[Vec3; 4], fill: Color32, edge: Color32) { +/// A reference plane's square. `through` draws it over the model (Create Sketch: a plane inside +/// a body stays visible and pickable), else it is depth-tested like the rest of the scene. +fn quad(sc: &mut GpuScene, q: &[Vec3; 4], fill: Color32, edge: Color32, through: bool) { let col = c4(fill); for i in [0, 1, 2, 0, 2, 3] { if let Some(p) = q.get(i) { - sc.guide_tri(p.to_f32(), col); + if through { + sc.xray_tri(p.to_f32(), [0.0; 3], col); + } else { + sc.guide_tri(p.to_f32(), col); + } } } for i in 0..4 { - sc.guide_line(q[i].to_f32(), q[(i + 1) % 4].to_f32(), c4(edge), 1.2); + let (a, b) = (q[i].to_f32(), q[(i + 1) % 4].to_f32()); + if through { + sc.line(a, b, c4(edge), 1.2, true); + } else { + sc.guide_line(a, b, c4(edge), 1.2); + } } } -fn highlight_key(app: &SolveApp) -> u64 { +fn highlight_geometry_key(app: &SolveApp) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); + let selected = app.highlighted(); app.session.revision.hash(&mut h); - serde_json::to_string(&app.highlighted()).unwrap_or_default().hash(&mut h); + (std::sync::Arc::as_ptr(&app.session.world_state()) as usize).hash(&mut h); + serde_json::to_string(&selected).unwrap_or_default().hash(&mut h); format!("{:?}", app.viewport.hover).hash(&mut h); app.viewport.hover_feature.hash(&mut h); app.viewport.hover_bodies.hash(&mut h); @@ -1822,19 +1870,41 @@ fn highlight_key(app: &SolveApp) -> u64 { app.session.active_occurrence_path.hash(&mut h); app.ui.visual_style.hash(&mut h); app.ui.pick_bodies.hash(&mut h); + app.session.active_sketch.hash(&mut h); + (app.dialog.is_some(), app.tool.is_some()).hash(&mut h); crate::theme::is_dark().hash(&mut h); crate::theme::vision().hash(&mut h); app.preview.replaced.hash(&mut h); app.origin_visible().hash(&mut h); + app.picking_sketch_plane().hash(&mut h); app.session.visibility.hidden_origin.hash(&mut h); app.session.visibility.hidden_bodies.hash(&mut h); app.session.visibility.hidden_occurrences.hash(&mut h); - app.cam.half_height().to_bits().hash(&mut h); - app.cam.back().x.to_bits().hash(&mut h); - crate::sketch_display::projection_key(&display_proj(app), app.viewport.pixels_per_point()).hash(&mut h); h.finish() } +fn highlight_key(app: &SolveApp) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + highlight_geometry_key(app).hash(&mut h); + let selected = app.highlighted(); + app.cam.half_height().to_bits().hash(&mut h); + // Body triangles and outlines live in world space; the GPU applies the new camera. + // Only sketch feedback needs projected tessellation and the profile's lift toward the eye. + let projected = selected.iter().any(|s| matches!(s, Sel::Profile { .. } | Sel::SketchCurve { .. } | Sel::ExternalSketchCurve { .. })) + || matches!(app.viewport.hover, Some(Hit::Profile { .. })); + if projected { + crate::sketch_display::projection_key(&display_proj(app), app.viewport.pixels_per_point()).hash(&mut h); + } + h.finish() +} + +struct HoverBlock { + key: u64, + state: std::sync::Arc, + doc: std::sync::Arc, + block: crate::gpu::SceneBlock, +} + /// The highlight scene: origin widget, construction planes, selection and hover. fn build_highlight(app: &SolveApp) -> GpuScene { let t = Tokens::get(); @@ -1862,6 +1932,7 @@ fn build_highlight(app: &SolveApp) -> GpuScene { }; let mut planes: Vec<(String, [Vec3; 4], Color32)> = origin_planes(app).into_iter().map(|(n, _, q)| (n.to_string(), q, t.origin_plane)).collect(); planes.extend(construction_quads(app).into_iter().map(|(n, _, q)| (n, q, t.construction_plane))); + let through = app.picking_sketch_plane(); for (name, q, base) in &planes { let (selected, hovered) = plane_state(name); let fill = if hovered { @@ -1871,7 +1942,7 @@ fn build_highlight(app: &SolveApp) -> GpuScene { } else { *base }; - quad(&mut sc, q, fill, if selected { t.sel_edge } else { t.origin_plane_edge }); + quad(&mut sc, q, fill, if selected { t.sel_edge } else { t.origin_plane_edge }, through); } // Origin axes: solid near the origin, dashed beyond. for (name, dir) in origin_axes(app) { @@ -1911,14 +1982,30 @@ fn build_highlight(app: &SolveApp) -> GpuScene { sc.line((p - d * r).to_f32(), (p + d * r).to_f32(), c4(t.construction_geom), 2.0, true); } } + // Reference widgets follow zoom; the often much larger world-space feedback does not. + let projected = sel.iter().any(|s| matches!(s, Sel::Profile { .. } | Sel::SketchCurve { .. } | Sel::ExternalSketchCurve { .. })) + || matches!(hover, Some(Hit::Profile { .. })); + let key = highlight_geometry_key(app); + if !projected + && let Some(block) = app.viewport.hover_block.lock().ok().and_then(|cache| { + cache + .as_ref() + .filter(|c| c.key == key && std::sync::Arc::ptr_eq(&c.state, &st) && std::sync::Arc::ptr_eq(&c.doc, &s.doc)) + .map(|c| c.block.clone()) + }) + { + sc.blocks.push(block); + return sc; + } + let mut feedback = GpuScene::default(); // Selected things. for x in &sel { match x { Sel::Face { body, index, .. } => { // A live preview stands in for the body: its old faces would fight with it. if let Some(b) = st.body(body).filter(|_| app.session.body_visible(body) && !app.preview.replaced.contains(body)) { - face_tris(&mut sc, &shown(b), *index, c4(t.sel_face), false); - hidden_face_outline(&mut sc, &drawn_mesh(app, b), *index, t.sel_edge); + face_tris(&mut feedback, &shown(b), *index, c4(t.sel_face), false); + hidden_face_outline(&mut feedback, &drawn_mesh(app, b), *index, t.sel_edge); } } Sel::Body { name } => { @@ -1926,9 +2013,8 @@ fn build_highlight(app: &SolveApp) -> GpuScene { && app.session.body_visible(name) { let m = shown(b); - for f in 0..b.body.face_count() { - face_tris(&mut sc, &m, f, c4(t.body_selected), true); - } + let count = b.body.face_count(); + mesh_tris(&mut feedback, &m, c4(t.body_selected), true, |f| (f as usize) < count); } } Sel::Edge { body, index, point } => { @@ -1936,10 +2022,10 @@ fn build_highlight(app: &SolveApp) -> GpuScene { && app.session.body_visible(body) && let Some(e) = edge_of(&drawn_mesh(app, b), *index, *point) { - edge_lines(&mut sc, e, t.sel_edge, t.sel_edge_rim, 3.0); + edge_lines(&mut feedback, e, t.sel_edge, t.sel_edge_rim, 3.0); } } - Sel::Profile { sketch, index } => profile_fill(&mut sc, app, *sketch, *index, t.sel_profile, t.sel_profile_edge), + Sel::Profile { sketch, index } => profile_fill(&mut feedback, app, *sketch, *index, t.sel_profile, t.sel_profile_edge), Sel::ExternalSketchCurve { sketch, id } => { if let Some(ss) = st.sketch(*sketch) && let Some(ci) = ss.sketch.curve_index(id) @@ -1947,7 +2033,7 @@ fn build_highlight(app: &SolveApp) -> GpuScene { for pts in &crate::sketch_display::curve_sample(app, *sketch, ci, &ss.plane, &display_proj(app)).parts { let mode = ss.sketch.curves.get(ci).map_or(0, |c| if c.centerline { 2 } else { u8::from(c.construction) }); for (a, b) in sketch_segments(pts, mode, grid_step(app.cam.half_height()).0) { - sc.line(a.to_f32(), b.to_f32(), c4(t.sel_edge), 3.5, true); + feedback.line(a.to_f32(), b.to_f32(), c4(t.sel_edge), 3.5, true); } } } @@ -1957,7 +2043,7 @@ fn build_highlight(app: &SolveApp) -> GpuScene { for ss in st.sketches.iter() { if let Some(w) = ss.sketch.wire_index(id).and_then(|i| ss.sketch.wires.get(i)) { for q in w.pts.windows(2) { - sc.line(q[0].to_f32(), q[1].to_f32(), c4(t.sel_edge), 3.5, true); + feedback.line(q[0].to_f32(), q[1].to_f32(), c4(t.sel_edge), 3.5, true); } } } @@ -1969,7 +2055,7 @@ fn build_highlight(app: &SolveApp) -> GpuScene { for pts in &crate::sketch_display::curve_sample(app, ss.feature, ci, &ss.plane, &display_proj(app)).parts { let mode = ss.sketch.curves.get(ci).map_or(0, |c| if c.centerline { 2 } else { u8::from(c.construction) }); for (a, b) in sketch_segments(pts, mode, grid_step(app.cam.half_height()).0) { - sc.line(a.to_f32(), b.to_f32(), c4(t.sel_edge), 3.5, true); + feedback.line(a.to_f32(), b.to_f32(), c4(t.sel_edge), 3.5, true); } } } @@ -2000,16 +2086,28 @@ fn build_highlight(app: &SolveApp) -> GpuScene { let c = body_rgb(app, &b.name); let m = drawn_mesh(app, b); let lit = shown(b); - for &f in &faces { - if !sel.iter().any(|x| { - matches!(x, Sel::Face { body, index, .. } if body == &b.name && *index == f) || matches!(x, Sel::Body { name } if name == &b.name) - }) { - face_tris(&mut sc, &lit, f, [c.0.saturating_add(k), c.1.saturating_add(k), c.2.saturating_add(k), 255], true); - } + let selected_body = sel.iter().any(|x| matches!(x, Sel::Body { name } if name == &b.name)); + if !selected_body { + let selected_faces: std::collections::HashSet = sel + .iter() + .filter_map(|x| { + if let Sel::Face { body, index, .. } = x + && body == &b.name + { + Some(*index) + } else { + None + } + }) + .collect(); + let hovered_faces: std::collections::HashSet = faces.iter().copied().collect(); + mesh_tris(&mut feedback, &lit, [c.0.saturating_add(k), c.1.saturating_add(k), c.2.saturating_add(k), 255], true, |f| { + hovered_faces.contains(&(f as usize)) && !selected_faces.contains(&(f as usize)) + }); } for (ei, e) in m.edges.iter().enumerate() { if m.edge_pickable(ei) && (whole || m.edge_faces.get(ei).is_some_and(|fs| fs.iter().any(|f| faces.contains(&(*f as usize))))) { - edge_lines(&mut sc, e, t.hover_edge, t.hover_edge_halo, 1.5); + edge_lines(&mut feedback, e, t.hover_edge, t.hover_edge_halo, 1.5); } } } @@ -2021,9 +2119,10 @@ fn build_highlight(app: &SolveApp) -> GpuScene { let k = t.hover_face_lift; let c = body_rgb(app, body); let m = shown(b); - for f in 0..b.body.face_count() { - face_tris(&mut sc, &m, f, [c.0.saturating_add(k), c.1.saturating_add(k), c.2.saturating_add(k), 255], true); - } + let count = b.body.face_count(); + mesh_tris(&mut feedback, &m, [c.0.saturating_add(k), c.1.saturating_add(k), c.2.saturating_add(k), 255], true, |f| { + (f as usize) < count + }); } } Some(Hit::Face { body, index, .. }) @@ -2037,13 +2136,13 @@ fn build_highlight(app: &SolveApp) -> GpuScene { let patch = m.surface_patch(*index); let lit = shown(b); for &f in &patch { - face_tris(&mut sc, &lit, f, [c.0.saturating_add(k), c.1.saturating_add(k), c.2.saturating_add(k), 255], true); + face_tris(&mut feedback, &lit, f, [c.0.saturating_add(k), c.1.saturating_add(k), c.2.saturating_add(k), 255], true); } for (e, _) in m.edge_faces.iter().enumerate().filter(|(_, fs)| fs.iter().any(|f| patch.contains(&(*f as usize)))) { if let Some(p) = m.edges.get(e) && m.edge_pickable(e) { - edge_lines(&mut sc, p, t.hover_edge, t.hover_edge_halo, 1.5); + edge_lines(&mut feedback, p, t.hover_edge, t.hover_edge_halo, 1.5); } } } @@ -2055,7 +2154,7 @@ fn build_highlight(app: &SolveApp) -> GpuScene { for i in m.circular_rim(*index) { let selected = sel.iter().any(|x| matches!(x, Sel::Edge { body: b, index: j, .. } if b == body && *j == i)); if !selected && let Some(e) = if i == *index { edge_of(&m, i, *mid) } else { m.edges.get(i) } { - edge_lines(&mut sc, e, t.hover_edge, t.hover_edge_halo, 2.0); + edge_lines(&mut feedback, e, t.hover_edge, t.hover_edge_halo, 2.0); } } } @@ -2063,10 +2162,32 @@ fn build_highlight(app: &SolveApp) -> GpuScene { Some(Hit::Profile { sketch, index }) if !sel.iter().any(|x| matches!(x, Sel::Profile { sketch: s2, index: i2 } if s2 == sketch && i2 == index)) => { - profile_fill(&mut sc, app, *sketch, *index, t.hover_profile, t.hover_profile_edge); + profile_fill(&mut feedback, app, *sketch, *index, t.hover_profile, t.hover_profile_edge); } _ => {} } + if projected { + sc.tris.append(&mut feedback.tris); + sc.trans.append(&mut feedback.trans); + sc.lines.append(&mut feedback.lines); + sc.hidden.append(&mut feedback.hidden); + sc.overlay.append(&mut feedback.overlay); + } else { + let block = crate::gpu::SceneBlock { + key, + bytes: std::sync::Arc::new(crate::gpu::BlockBytes { + tris: feedback.tris, + lines: feedback.lines, + hidden: feedback.hidden, + ..Default::default() + }), + }; + if let Ok(mut cache) = app.viewport.hover_block.lock() { + *cache = Some(HoverBlock { key, state: st.clone(), doc: s.doc.clone(), block: block.clone() }); + } + sc.blocks.push(block); + } + sc } @@ -2175,6 +2296,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { // Suppress hover for the whole navigation gesture, including frames between pointer // events. Testing delta made the highlight reappear whenever a held drag paused. // Resolve it before rendering so the GPU scene and screen overlays use the same hit. + // A 3D mouse moving the view is not such a gesture: the pointer hand is free, and hover + // and clicks keep picking while the other hand turns the view. let navigating = scroll != 0.0 || pinch != 1.0 || pan != egui::Vec2::ZERO @@ -2275,6 +2398,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { }, }); painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb)); + crate::pick_buffer::paint(app, ui.ctx(), &painter, &proj); } analysis_legend(app, &painter, rect); crate::frame_rate::paint(app, ui.ctx(), &painter, rect); @@ -3557,7 +3681,7 @@ mod tests { let mut render = |tess: bool, hover: Option| { app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess }); app.viewport.hover = hover.map(|index| Hit::Face { body: body.name.clone(), index, point: Vec3::ZERO }); - let (scene, highlight) = (build_scene(&app), build_highlight(&app)); + let (scene, highlight) = (build_scene(&app), build_highlight(&app).merged()); assert_eq!(!scene.planned.is_empty(), tess, "the box is drawn from its plan exactly on the GPU path"); let proj = projection(&app, rect); let e = proj.cam.eye().to_f32(); @@ -3774,14 +3898,14 @@ mod tests { let p = crate::scenario::handle_at("timeline:Blend").unwrap(); h.step(&json!({"move":[p.x,p.y]})).unwrap(); assert_eq!(h.app.viewport.hover_feature, Some(id)); - assert_eq!(build_highlight(&h.app).tris.len(), triangles * 3 * crate::gpu::TRI_SIZE); - assert!(!build_highlight(&h.app).lines.is_empty()); + assert_eq!(build_highlight(&h.app).merged().tris.len(), triangles * 3 * crate::gpu::TRI_SIZE); + assert!(!build_highlight(&h.app).merged().lines.is_empty()); h.step(&json!({"click":[p.x,p.y]})).unwrap(); assert_eq!(h.app.session.selection, vec![Sel::Feature { id }]); // Moving away removes hover but leaves the selected blend highlighted. h.step(&json!({"move":[5,5]})).unwrap(); assert_eq!(h.app.viewport.hover_feature, None); - assert_eq!(build_highlight(&h.app).tris.len(), triangles * 3 * crate::gpu::TRI_SIZE); + assert_eq!(build_highlight(&h.app).merged().tris.len(), triangles * 3 * crate::gpu::TRI_SIZE); let bounds = selection_bounds(&h.app).unwrap(); assert!(bounds.max.x <= 2.01 && bounds.max.y <= 2.01 && bounds.max.z > 19.99, "{bounds:?}"); // Creator features retain whole-body feedback, while hidden bodies stay hidden. @@ -3789,7 +3913,7 @@ mod tests { h.app.session.visibility.hidden_bodies.push(body.clone()); assert!(feature_geometry(&h.app, id).is_empty()); assert!(selection_bounds(&h.app).is_none()); - assert!(build_highlight(&h.app).tris.is_empty()); + assert!(build_highlight(&h.app).merged().tris.is_empty()); } } @@ -4313,6 +4437,50 @@ mod tests { } } + /// Two-handed use: while a 3D mouse turns the view, the pointer still preselects what is + /// under it in the view as it is now, and a click picks it (it neither does nothing nor + /// clears the selection). + #[test] + fn device_navigation_keeps_hover_and_click_picking() { + use crate::space_mouse::{DeviceMotion, Motion}; + for gpu in [false, true] { + let ctx = egui::Context::default(); + let mut s = solidcraft_engine::Session::default(); + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); + let mut app = SolveApp::new(s, crate::Services::default()); + app.ui.show_origin = false; + if gpu { + app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); + } + app.cam.target = Vec3::new(20.0, 15.0, 10.0); + hover_frame(&mut app, &ctx, vec![]); + // The middle of the top face. + let p = projection(&app, app.viewport.rect.unwrap()).to_screen(Vec3::new(20.0, 15.0, 20.0)).unwrap(); + hover_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(p)]); + assert!(matches!(app.viewport.hover, Some(Hit::Face { .. })), "{:?}", app.viewport.hover); + let turn = || Some(DeviceMotion { motion: Motion { translation: [0.0; 3], rotation: [0.0, 0.0, 0.1] }, seconds: 0.016 }); + let mut pick = app.viewport.last_pick.as_ref().unwrap().0; + for _ in 0..3 { + let before = app.cam; + app.viewport.device_motion = turn(); + hover_frame(&mut app, &ctx, vec![]); + assert_ne!(app.cam, before, "the device turns the view"); + assert!(matches!(app.viewport.hover, Some(Hit::Face { .. })), "hover stays on while the device moves the view"); + let now = app.viewport.last_pick.as_ref().unwrap().0; + assert_ne!(now, pick, "the pick follows the turned view"); + pick = now; + } + // A click while the device keeps turning the view selects the face under the pointer. + let button = + |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + app.viewport.device_motion = turn(); + hover_frame(&mut app, &ctx, vec![button(true)]); + app.viewport.device_motion = turn(); + hover_frame(&mut app, &ctx, vec![button(false)]); + assert!(matches!(app.session.selection.as_slice(), [Sel::Face { .. }]), "gpu {gpu}: {:?}", app.session.selection); + } + } + #[test] fn hover_stays_off_during_spin_and_animated_views() { let ctx = egui::Context::default(); @@ -4388,7 +4556,7 @@ mod tests { let mut lit_faces = 0; for index in 0..body.body.face_count() { app.viewport.hover = Some(Hit::Face { body: body.name.clone(), index, point: Vec3::ZERO }); - let lit = tris_of(&build_highlight(&app).tris); + let lit = tris_of(&build_highlight(&app).merged().tris); assert!(!lit.is_empty(), "face {index} lights"); assert!(lit.iter().all(|t| drawn.contains(t)), "face {index}: every lit triangle is a drawn one"); lit_faces += 1; @@ -4405,6 +4573,71 @@ mod tests { app } + #[test] + fn body_highlight_buffers_are_reused_when_the_camera_orbits_or_pans() { + let mut app = cylinder_app(); + app.ui.show_origin = true; + app.viewport.hover_bodies = vec!["Body1".into()]; + let key = highlight_key(&app); + let before = build_highlight(&app).merged(); + assert!(!before.tris.is_empty()); + app.cam.orbit(25.0, 10.0); + app.cam.roll_by(0.3); + app.cam.pan(20.0, -15.0, 600.0); + assert_eq!(highlight_key(&app), key, "world-space feedback must stay resident during navigation"); + let after = build_highlight(&app).merged(); + assert_eq!(before.tris, after.tris); + assert_eq!(before.lines, after.lines); + app.cam.zoom_at(1.2, None); + assert_ne!(highlight_key(&app), key, "reference geometry follows the view's scale"); + + let mut app = hover_app(true); + let sketch = app.session.active_sketch.unwrap(); + app.run("sketch.circle.center", json!({"center":[0,0],"radius":5})).unwrap(); + app.session.selection = vec![Sel::Profile { sketch, index: 0 }]; + let key = highlight_key(&app); + let before = build_highlight(&app).merged(); + assert!(!before.trans.is_empty()); + app.cam.orbit(25.0, 10.0); + assert_ne!(highlight_key(&app), key, "profile feedback still follows the projected curves and lift toward the eye"); + assert_ne!(before.trans, build_highlight(&app).merged().trans); + } + + #[test] + fn world_highlight_block_survives_zoom_and_refreshes_when_bodies_are_hidden() { + let mut app = cylinder_app(); + app.ui.show_origin = true; + app.viewport.hover_bodies = vec!["Body1".into()]; + let before = build_highlight(&app); + let bytes = before.blocks[0].bytes.clone(); + assert!(!bytes.tris.is_empty()); + app.cam.zoom_at(4.0, None); + let after = build_highlight(&app); + assert!(std::sync::Arc::ptr_eq(&bytes, &after.blocks[0].bytes), "zoom must not regenerate or upload body feedback"); + assert_ne!(before.guide_trans, after.guide_trans, "reference planes still resize with the view"); + app.session.visibility.hidden_bodies.push("Body1".into()); + let hidden = build_highlight(&app); + assert!(!std::sync::Arc::ptr_eq(&bytes, &hidden.blocks[0].bytes)); + assert!(hidden.blocks[0].bytes.tris.is_empty(), "hidden bodies must lose their feedback"); + app.session.visibility.hidden_bodies.clear(); + let shown = build_highlight(&app); + assert_eq!(shown.blocks[0].bytes.tris, bytes.tris); + } + + #[test] + fn whole_body_highlight_preserves_each_triangle_and_selected_face_once() { + let mut app = cylinder_app(); + let body = app.session.world_state().bodies[0].clone(); + let expected = shown_mesh(&app, &body, &None).triangles.len() * 3 * crate::gpu::TRI_SIZE; + app.viewport.hover_bodies = vec![body.name.clone()]; + for selected in + [vec![], vec![Sel::Face { body: body.name.clone(), index: 0, point: Vec3::ZERO }], vec![Sel::Body { name: body.name.clone() }]] + { + app.session.selection = selected; + assert_eq!(build_highlight(&app).merged().tris.len(), expected, "whole-body feedback must neither omit nor duplicate selected faces"); + } + } + #[test] fn smooth_wall_display_preserves_wireframe_and_edge_selection() { let mut s = solidcraft_engine::Session::default(); @@ -4440,7 +4673,7 @@ mod tests { assert!(wire.tris.is_empty()); app.ui.visual_style = 0; app.session.selection = vec![Sel::Edge { body: b.name.clone(), index: smooth, point: polyline_mid(&mesh.edges[smooth]) }]; - assert!(!build_highlight(&app).lines.is_empty()); + assert!(!build_highlight(&app).merged().lines.is_empty()); let mut without_display_mask = (*mesh).clone(); without_display_mask.smooth_edges.clear(); assert_eq!(mesh.surface_patch(mesh.edge_faces[smooth][0] as usize), without_display_mask.surface_patch(mesh.edge_faces[smooth][0] as usize)); @@ -4591,7 +4824,7 @@ mod tests { h.app.ui.show_origin = true; h.frames(2); assert!(section_plane(&h.app).is_some()); - let sc = build_highlight(&h.app); + let sc = build_highlight(&h.app).merged(); let planes = origin_planes(&h.app).len(); assert!(planes > 0); assert_eq!(sc.guide_trans.len(), planes * 6 * crate::gpu::TRI_SIZE); @@ -4613,12 +4846,12 @@ mod tests { for &i in &rim { let mid = polyline_mid(&m.edges[i]); app.viewport.hover = Some(Hit::Edge { body: b.name.clone(), index: i, mid }); - assert_eq!(build_highlight(&app).lines.len(), 2 * line_count * crate::gpu::LINE_SIZE); + assert_eq!(build_highlight(&app).merged().lines.len(), 2 * line_count * crate::gpu::LINE_SIZE); let item = hit_sel(app.viewport.hover.as_ref().unwrap()).unwrap(); select(&mut app, Some(item.clone()), false); assert_eq!(app.session.selection.len(), 2); // Selecting both pieces must not draw each highlight twice. - assert_eq!(build_highlight(&app).lines.len(), 2 * line_count * crate::gpu::LINE_SIZE); + assert_eq!(build_highlight(&app).merged().lines.len(), 2 * line_count * crate::gpu::LINE_SIZE); // Ctrl/Shift clicking either half deselects the entire rim. select(&mut app, Some(item.clone()), true); assert!(app.session.selection.is_empty()); @@ -4662,11 +4895,11 @@ mod tests { let [a, c, d] = m.tri(t).unwrap(); let point = (a + c + d) / 3.0; app.viewport.hover = Some(Hit::Face { body: b.name.clone(), index, point }); - assert_eq!(build_highlight(&app).tris.len(), triangle_count * 3 * crate::gpu::TRI_SIZE); + assert_eq!(build_highlight(&app).merged().tris.len(), triangle_count * 3 * crate::gpu::TRI_SIZE); let item = hit_sel(app.viewport.hover.as_ref().unwrap()).unwrap(); select(&mut app, Some(item.clone()), false); assert_eq!(app.session.selection.len(), 2); - assert_eq!(build_highlight(&app).tris.len(), triangle_count * 3 * crate::gpu::TRI_SIZE); + assert_eq!(build_highlight(&app).merged().tris.len(), triangle_count * 3 * crate::gpu::TRI_SIZE); assert_eq!(app.session.selection.first(), Some(&item), "keep the original tool placement point first"); let mut dialog = crate::dialogs::Dialog::for_command(&app, "solid.chamfer").unwrap(); assert_eq!(dialog.items().len(), 2); @@ -5176,10 +5409,10 @@ mod tests { let mut s = solidcraft_engine::Session::default(); s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); let mut app = SolveApp::new(s, crate::Services::default()); - assert!(build_highlight(&app).hidden.is_empty()); + assert!(build_highlight(&app).merged().hidden.is_empty()); // The back face: its outline is drawn (dimmed) where the box hides it. app.session.selection = vec![Sel::Face { body: "Body1".into(), index: 3, point: Vec3::new(20.0, 30.0, 10.0) }]; - assert!(!build_highlight(&app).hidden.is_empty()); + assert!(!build_highlight(&app).merged().hidden.is_empty()); } #[test] @@ -5606,4 +5839,27 @@ mod grid_plane_tests { } } } + + /// Create Sketch shows the Origin even when the browser hides it, and draws its planes + /// through the model so a plane inside a body can be seen and picked; closing it restores + /// the hidden, depth-tested Origin. + #[test] + fn create_sketch_shows_the_origin_planes_through_the_model() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.run("solid.box", json!({"length":40,"width":40,"height":40})).unwrap(); + app.ui.show_origin = false; + assert!(origin_planes(&app).is_empty()); + assert!(build_highlight(&app).xray.is_empty()); + app.start("sketch.create"); + assert!(app.picking_sketch_plane()); + assert_eq!(origin_planes(&app).len(), 3, "every origin plane is offered"); + let sc = build_highlight(&app); + assert_eq!(sc.xray.len(), 3 * 6 * (6 * 4 + 4), "each plane's two triangles are drawn through the model"); + assert!(sc.guide_trans.is_empty()); + app.dialog = None; + assert!(origin_planes(&app).is_empty()); + app.ui.show_origin = true; + let sc = build_highlight(&app); + assert!(sc.xray.is_empty() && !sc.guide_trans.is_empty(), "outside Create Sketch the planes are depth-tested"); + } } diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index 674d14372..ed99b7eb7 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -19,6 +19,7 @@ const ASSEMBLE: &[&str] = &[ "joint.gear", "joint.rack_pinion", "joint.screw", + "joint.cam", "motion.study", "motion.trace", "explode.create", diff --git a/docs/action-matrix.md b/docs/action-matrix.md index f4ae77f63..b15c38552 100644 --- a/docs/action-matrix.md +++ b/docs/action-matrix.md @@ -257,7 +257,7 @@ resolves; it is recorded as `+edit`. ## Causes -Every failure, grouped by cause (5025 in all). Faces that can't take an attached sketch fail four +Every failure, grouped by cause (5013 in all). Faces that can't take an attached sketch fail four actions each (`face.sketch`, `face.offset_plane`, and `face.press_pull` and `face.extrude`, which make a legacy face sketch there). @@ -283,7 +283,6 @@ make a legacy face sketch there). | 56 | #563 | Draft and tapered Extrude drop the faces' sources | `face.extrude` 14, `face.offset_plane` 14, `face.press_pull` 14, `face.sketch` 14 | 3 | oracle/05-taper-extrude `Frustum/F2:start` | | 48 | #564 | The rim a Shell leaves has no source | `face.extrude` 12, `face.offset_plane` 12, `face.press_pull` 12, `face.sketch` 12 | 8 | demo/pi-case `Body1/F2:top` | | 18 | #567 | Axis or tangent plane on a drill tip: no face at NaN | `curved.axis` 9, `curved.tangent_plane` 9 | 3 | oracle/18-hole-features `Plate/F5:face:15` | -| 12 | #565 | Split Body and Combine Intersect drop the faces' sources | `face.offset_plane` 4, `face.sketch` 4, `face.extrude` 2, `face.press_pull` 2 | 1 | oracle/22-split-body `Cyl (1)/F2:bottom` | | 9 | #568 | Construction geometry on model edges, faces and vertices is lost when a parameter moves it | `vertex.plane_three_points+edit` 5, `edge.normal_plane+edit` 2, `face.midplane+edit` 1, `face.shell+edit` 1 | 4 | demo/enclosure_steps `Enclosure/v[F2:top & F4:inner:F2:side:l4 & F4:inner:F3:blend:F2:side:l` | | 9 | | Axis through a face the kernel sees as a cylinder that the command doesn't (sensor enclosure slot ends; not filed yet) | `curved.axis` 9 | 1 | examples/sensor_enclosure `Lid/F15:blend:F14:side:l2\|F14:side:l3` | | 7 | | Other failures in the edit round: the hole cut and blend sizes above, and an extrude from the M0 box's top face whose profile isn't found again (not filed yet) | `face.hole+edit` 3, `face.extrude+edit` 1, `face.press_pull+edit` 1, `edge.chamfer+edit` 1 | 4 | corpus/m0-box-fillet-hole `Body1/F2:top` | @@ -297,5 +296,6 @@ chamfers, pattern and mirror copies, sides a Join merged, revolves, lofts, sweep shell rims, the plastic features' faces and the faces around them, and pieces of a split face (by the piece's own name where Offset Face moved it off the others' plane). Sheet metal panels, their rims and the flat ends of bends attach by name. What still refuses a sketch is what makes faces -without recording their history (some cuts, Split Body, Intersect): press-pull and -extrude-from-face then fall back to a legacy face sketch found again by a point. +without recording their history (some cuts, the face a Split Body cuts with another body's +face): press-pull and extrude-from-face then fall back to a legacy face sketch found again by a +point. diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 5529a94c8..d0bf0fa7e 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -1,7 +1,7 @@ # Agent chat Agent chat is a side panel where you talk to a coding agent you already use (Claude Code, -Codex, Gemini CLI, OpenCode, Grok Build and others), or to a model behind an OpenAI-compatible endpoint you +Codex, Google Antigravity, OpenCode, Grok Build and others), or to a model behind an OpenAI-compatible endpoint you choose (Ollama or LM Studio on your computer, OpenAI, any other URL), and have it work on the design that's open. A coding agent runs on your computer under **your own account** with that agent: SolidCraft doesn't sell or proxy a model and needs no key for it. An endpoint's key, if @@ -88,7 +88,7 @@ the keychain, so SolidCraft doesn't guess there. |---|---| | Claude Code | `npm install -g @agentclientprotocol/claude-agent-acp` (the ACP adapter for Claude Code) | | Codex | `npm install -g @agentclientprotocol/codex-acp` | -| Gemini CLI | `npm install -g @google/gemini-cli` (it speaks ACP itself: `gemini --acp`) | +| Google Antigravity | Google's ACP server, a separate download from Google's `agy` command (which has no ACP mode): take the zip for your system from the [ACP registry](https://agentclientprotocol.com/registry), unzip it and put `agy_acp_server.par` (`agy_acp_server.exe` on Windows) on your `PATH`. The zip also holds `localharness_external`: leave the two together. It signs in itself (browser). | | OpenCode | `npm install -g opencode-ai` (`opencode acp`) | | XAI Grok | [Grok Build installer](https://docs.x.ai/build/overview), then `grok login` (`grok agent stdio` speaks ACP) | | GitHub Copilot CLI, Qwen Code, goose | listed with their install command when missing | @@ -149,6 +149,9 @@ The agent reaches the open design only through SolidCraft's own tools (the a single undo step, named after your message. The conversation shows *N changes, one undo step* with **Undo these changes** while nothing else has happened since. - **Tool cards:** each tool call shows as a card with its state; click it to see what it returned. +- **Formatted text:** the agent's answers show as Markdown: headings, lists, quotes, code blocks + (with **Copy**), bold, italic, `code` and links (web links only; each link is a button that opens + it in your browser). What you type, and the agent's thoughts, stay plain text. - **Attach view:** tick it to send a picture of the current view with your message, for agents that take pictures. diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index f3a1de7fa..975528b4b 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -55,6 +55,33 @@ driven one. A joint follows one link at most, and a coupling that would drive it refused. `joint.list` lists each coupling's definition under `links` with an `error` when it can't be worked out (the picked face is gone); the link then keeps its last ratio. +**Cam** (`joint.cam {a, b, profile}`, on the **ASSEMBLE** panel) makes a follower ride a cam. The +cam turns on a revolute joint (a); the follower is a slider (b, a translating follower such as a +valve tappet) or a revolute joint (b, an oscillating follower such as a rocker arm). The profile +is the cam's outline in a plane square to its axis: a closed profile of a sketch in the cam's +component, or the cam's edges picked on its body (one click on an edge takes the closed loop it is +on in that plane). The follower is: + +- a **Knife edge**: a point on the cam; +- a **Roller** of a radius, typed or taken from the roller's round face (picking that face also + says where the roller is); +- a **Flat face** square to a slider's line, such as a bucket tappet. + +A translating follower's line runs along its slider's axis, through its **Tip** when one is picked +(its knife's point or its roller's centre), so a follower offset from the cam's axis rides the +right flank. An oscillating follower needs its tip, or its roller's face, to know its arm. The +follower rides the cam from the side it is on (**Other side** takes the other one). The follower's +travel over a turn of the cam is worked out from the profile and kept with the link, one value a +degree with a smooth curve between them that never overshoots its samples. It is worked out again +whenever the design changes: change the cam's sketch, a parameter or the roller, and the follower +follows. Like the gears, the new link leaves the follower where it is (model it touching the cam), +and the cam is a motion link: it drives in **Drive Joints**, plays in motion studies, works in +closed loops (a tappet can be the piston of a slider-crank) and stops at contact sets. The profile +may also be on the grounded part, with the follower's guide on a turret that the cam joint turns. +`joint.list` gives a cam's link `lift` (the follower's lowest and highest values and its rise) +instead of a ratio. A profile that is not closed, a line or an arm that misses the cam somewhere, +a follower that would jump, and axes that are not square or parallel are refused. + A joint moves one component against another, so its two picks must be on different components. A STEP file with several parts often comes in as bodies of one component, and picks on two of those bodies make no joint. The Joint and As-built Joint dialogs say so under the picks and offer @@ -122,6 +149,23 @@ study, samples?}`) answers the world points without changing the design, and `motion.trace.keep` with the same parameters (and `name?`) keeps them. A trace takes 2 to 500 samples: 100 by default for a joint, one per step for a study. +**Export Animation…** in the **Motion Study** dialog saves the study as an animated GIF, drawn +from the viewport's camera as the study plays (the keys in the dialog count, even before OK). +`motion.export_animation` does the same for scripts, the CLI and agents, without a window: give a +`study`, or a `joint` with `from` and `to` (and `index?`) to animate a drive, and a `path`. A path +ending in `.gif` gets an animated GIF that loops; any other path is a folder that gets the frames +as `frame-0001.png`, `frame-0002.png`, and so on (made if missing; frames of a longer earlier +export there are removed), for a video tool. The web app writes GIFs only. `samples` is +the number of frames (one per step for a study by default, 100 for a joint), `width` and `height` +their size in pixels (800 × 500 by default, at most 4096 a side), and `fps` the GIF's speed (20 +by default); `grid: false` and `axes: false` leave out the ground grid and the origin's axes. +`camera` takes the reply of the control channel's `ui.camera` (or any of its fields; +the rest come from the view `view.apply` chose, or the home view framing the model). The frames +are drawn by the same renderer as `solidcraft-cli snapshot`, on a copy of the design, which is not +changed. A GIF keeps one palette for all its frames, so colours don't flicker, and stores only +what changed from one frame to the next. Frames are capped: at most 1000, and a GIF holds at most +2^26 pixels of frames (about 160 frames of 800 × 500). + **Insert Design** (`component.insert_design {path, translate?}`, on the **ASSEMBLE** panel and in the **File** menu) adds a component linked to another saved design, so each part can live in its own document. A STEP or mesh file picked there is inserted as **Insert STEP** or **Insert diff --git a/docs/book/src/guide/getting-started.md b/docs/book/src/guide/getting-started.md index e98a158cc..b11b283e1 100644 --- a/docs/book/src/guide/getting-started.md +++ b/docs/book/src/guide/getting-started.md @@ -171,6 +171,7 @@ cargo run --release -p solidcraft-cli -- run examples/bracket.json --out bracket cargo run --release -p solidcraft-cli -- eval examples/bracket.json # volume, area, faces… cargo run --release -p solidcraft-cli -- snapshot examples/bracket.json --out bracket.png cargo run --release -p solidcraft-cli -- exec solid.box '{"length": 20, "width": 10, "height": 5}' +cargo run --release -p solidcraft-cli -- run mechanism.json --in arm.solidcraft # with a motion.export_animation step: a GIF ``` A script is a list of commands: diff --git a/docs/control-protocol.md b/docs/control-protocol.md index ebddf4c34..019701a42 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -144,7 +144,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox. | `ui.scroll` | `x`, `y`, `delta?` | wheel zoom at the cursor | | `ui.key` | `key` (egui key name, `Enter`, `Escape`…), `cmd?`, `shift?` | | | `ui.text` | `text` | typed text | -| `ui.screenshot` | `path?` | PNG of the window (needs a presented frame) | +| `ui.screenshot` | `path?` | PNG of the window (needs a presented frame: a minimised or fully covered window answers at once with `hidden: true` and an error; use `ui.render`) | | `ui.render` | `path`, `width?`, `height?`, `grid?`, `axes?` | Render of the model with the current camera (no window needed), drawn on the app's GPU device with the viewport's pipelines (the reply's `renderer`: `gpu`, or `gpu-software` on a software adapter), in the window's theme (light or dark; `solidcraft-cli snapshot` keeps the light colours); cut by the section the viewport shows (`inspect.section`, an open Section Analysis dialog's preview, a sketch's Slice), with the cut face capped. The ground grid and the origin's axes are drawn as the window shows them (`ui.set` `showGrid` and `showOrigin`, `hiddenOrigin`); `grid` and `axes` (booleans) say otherwise for this render | | `ui.confirm` | `accept?`: bool | answers the Delete confirmation (shown when a delete takes other features with it or makes some fail); without `accept`, what it lists | | `ui.documents` | `action?`: `new`, `switch`, `close`, `quit`; `index?`; `force?` (close without asking); `answer?`: `save`, `dont_save`, `cancel` (answers "save changes?") | the open designs (tabs): names, unsaved flags, the active one, a pending "save changes?" prompt, whether a quit is asking | diff --git a/docs/design/in-app-agent-chat.md b/docs/design/in-app-agent-chat.md index 8db181ba5..8a0739543 100644 --- a/docs/design/in-app-agent-chat.md +++ b/docs/design/in-app-agent-chat.md @@ -8,7 +8,7 @@ Protocol and the agents that speak it, how the chat is built, and what's still o ## Goal A chat panel inside SolidCraft that drives a coding agent **the user already has and is already -signed in to** (Claude Code, Codex, Gemini CLI, …). SolidCraft holds no API keys and no +signed in to** (Claude Code, Codex, Antigravity, …). SolidCraft holds no API keys and no accounts: the agent runs as a child process under the user's own login, and SolidCraft gives it one thing, its MCP server bridged to the open window, so the agent models on the design the user is looking at. @@ -48,7 +48,8 @@ with SolidCraft, the user installs the agent. |---|---|---|---|---| | Claude Code | `claude-agent-acp` adapter (renamed from `@zed-industries/claude-code-acp`, which is now deprecated) | `@agentclientprotocol/claude-agent-acp` 0.90.0, Apache-2.0. It depends on `@anthropic-ai/claude-agent-sdk`, which is under Anthropic's own terms ("SEE LICENSE IN README.md"): fine for the user to install, not something we would vendor. | `--version` prints `0.90.0` | Terminal method. Offered only when the client declares terminal login. On a desktop: "Claude Subscription" = `claude-agent-acp --cli auth login --claudeai`, "Anthropic Console" = `… --cli auth login --console`. Over SSH (no browser) it offers `claude-login` = `… --cli` (the TUI `/login`). The login is Claude Code's own: `~/.claude/.credentials.json` (Linux, Windows) or the macOS keychain. | | Codex | `codex-acp` adapter (`@zed-industries/codex-acp` 0.16 moved to `@agentclientprotocol/codex-acp`) | `@agentclientprotocol/codex-acp` 2.2.2, Apache-2.0 | `--version` (0.16 rejected the flag; 2.x prints it) | Agent method `chat-gpt` (the adapter opens the browser for the ChatGPT login when the client calls `authenticate`), and `api-key` for a key the user configures in Codex. 0.16 also listed `env_var` methods for `CODEX_API_KEY` / `OPENAI_API_KEY`. The login is Codex's own: `~/.codex/auth.json`. | -| Gemini CLI | built in: `gemini --acp` (the ACP registry's current flag; older releases used `--experimental-acp`) | `@google/gemini-cli` 0.64, Apache-2.0 | `--version` | Its own Google login (`~/.gemini/oauth_creds.json`) or a key in the environment. | +| Google Antigravity | a separate server, `agy_acp_server.par` (`.exe` on Windows), from the ACP registry's zip (`agy-acp-server-1.4.0-…`, with `localharness_external` beside it, ~330 MB). The `agy` command (1.4.0) rejects `--acp`; its `--input-format stream-json` print mode is not ACP. Started without arguments (the registry's Linux entry passes an empty `--uid=`, not needed here). | proprietary (Google's terms) | none: `--version` prints a build date and takes about two seconds, so it is not asked | Agent methods `oauth-personal`, `oauth-business`, `gemini-api-key` (`GEMINI_API_KEY`), `agent-platform`; `session/new` answers "Authentication required" until one is chosen. Settings in `~/.gemini/antigravity-acp/settings.json`. | +| Gemini CLI (retired) | `gemini --acp` | `@google/gemini-cli` 0.64, Apache-2.0 | `--version` | Google ended it for consumer accounts on 2026-06-18 in favour of Antigravity. Still found when installed (enterprise licences may keep it working) but no longer offered for install. Its own login `~/.gemini/oauth_creds.json` or a key in the environment. | | OpenCode | built in: `opencode acp` | `opencode-ai` 1.19, MIT | `--version` | Its own providers' logins (`~/.local/share/opencode/auth.json`) or keys in the environment. | | XAI Grok | built in: `grok agent stdio` | [Grok Build](https://github.com/xai-org/grok-build), Apache-2.0; installed separately | `grok --version` prints `grok 1.0.58 (…) [alpha]` (checked 2026-10-15; in-app connection also checked with 1.0.60) | Its own `~/.grok/auth.json` or `XAI_API_KEY`. `grok login` signs in in the browser; ACP advertises `cached_token` and `grok.com` authentication methods. | | Others in the ACP registry | `copilot --acp`, `qwen --acp`, `opencode acp`, `goose acp`, `cline --acp`, `kimi acp`, … | mixed; several are proprietary, one is GPL and one AGPL (we only start them as programs, never link them) | `--version` | each its own | @@ -61,7 +62,7 @@ the picker instead of the hard-coded table. - **SolidCraft never sees a credential.** It doesn't pass API keys, doesn't store tokens and doesn't open login pages by itself. Each agent keeps its own login where its CLI always does - (Claude Code: `~/.claude` or the keychain; Codex: `~/.codex`; Gemini: `~/.gemini`). A user + (Claude Code: `~/.claude` or the keychain; Codex: `~/.codex`; Gemini and Antigravity: `~/.gemini`). A user who already uses the agent in a terminal is already signed in, and the chat simply works. - **Not signed in:** the agent answers "Authentication required". The panel switches to *Sign-in needed* and lists the agent's own `authMethods`: @@ -79,7 +80,7 @@ the picker instead of the hard-coded table. ## How it works ``` -SolidCraft window ──(child process, own process group, ACP over stdio)──> agent (claude-agent-acp, codex-acp, gemini --acp, opencode acp, …) +SolidCraft window ──(child process, own process group, ACP over stdio)──> agent (claude-agent-acp, codex-acp, agy_acp_server, opencode acp, …) ▲ │ starts, per session/new │ the chat's own endpoint (loopback, fresh token, gate) ▼ └──────────────────────────────────────────────────── solidcraft-cli mcp --connect 127.0.0.1:PORT @@ -96,6 +97,7 @@ Code: `crates/ui-egui/src/agent_chat/`. | `settings.rs` | Preferences → AI and the Add agent dialog. | | `process.rs` | The agent as a child process in a process group of its own; stopping it ends the group. | | `discover.rs` | Which agents are installed, their versions, whether they look signed in. | +| `markdown.rs`, `markdown_view.rs` | The agent's text as Markdown: a bounded reader, and its drawing (parsed once per item, again only when the text changes). | | `gate.rs` | What the agent's tool requests may do: run, wait for Allow/Deny, or never. | | `mod.rs` | The conversation, turns (undo as one step, the per-turn limit), held requests. | | `panel.rs` | The panel: docking, minimising, picker, sign-in, conversation, input. | @@ -208,7 +210,7 @@ returns the whole state, for tests and screenshots. | Area | Work | |---|---| -| Conversation | Markdown rendering, diffs, history per design, resume (`session/load`) | +| Conversation | Diffs, history per design, resume (`session/load`) | | Session controls | Model and mode pickers from `configOptions` / `modes`, slash commands | | Auth | An embedded terminal or "open a terminal here" for terminal logins on each OS; logout | | Discovery | Read the ACP registry; keychain-aware login check on macOS | diff --git a/docs/face-attachments.md b/docs/face-attachments.md index 50f39112e..6c22b96a9 100644 --- a/docs/face-attachments.md +++ b/docs/face-attachments.md @@ -24,8 +24,10 @@ has one: the persistent name the kernel's face history gives it, which says what and follows it through every later feature. That covers a Cut's walls and floor (`F5:side:l1`, `F5:top`), a chamfer face (`F7:blend:…`), each copy a pattern or mirror makes (`F4:top@F6.2`: the seed's face and the copy's instance), a side wall a Join merged from two -features (named after the first, answering to the other), and the pieces a later feature split -a face into (all pieces of one name on one oriented plane are that face). A lineage face's +features (named after the first, answering to the other), the pieces a later feature split +a face into (all pieces of one name on one oriented plane are that face), and the face Split Body +cuts with a plane (`F4:section` on each part: a construction plane, a sketch line or a plane given +outright, so a sketch on it follows the plane when a parameter moves it). A lineage face's plane is its current exact plane, measured in a frame that depends on the plane alone: its origin where the definition origin projects onto it, its x axis the first of the definition's X, Y and Z axes not steep to it (`|cos| < 0.6`), projected. The construction certificates diff --git a/docs/features.md b/docs/features.md index fc4add7d0..2af9de6fa 100644 --- a/docs/features.md +++ b/docs/features.md @@ -1,6 +1,6 @@ # Features -SolidCraft's commands by area, generated by `cargo xtask features` from the command registry (`solidcraft-cli commands`). **384 commands.** Planned (registered, not built yet): 1. Every command runs the same way from the toolbar, a script, `solidcraft-cli exec ''`, the control channel and MCP; parameters are in the [command reference](book/src/reference/commands.md) (`cargo xtask book`). Status and plans: [ROADMAP](../ROADMAP.md). +SolidCraft's commands by area, generated by `cargo xtask features` from the command registry (`solidcraft-cli commands`). **387 commands.** Planned (registered, not built yet): 1. Every command runs the same way from the toolbar, a script, `solidcraft-cli exec ''`, the control channel and MCP; parameters are in the [command reference](book/src/reference/commands.md) (`cargo xtask book`). Status and plans: [ROADMAP](../ROADMAP.md). ## Sketch (103) @@ -150,10 +150,11 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Align | `solid.align` | SOLID › MODIFY | | Remove | `solid.remove` | SOLID › MODIFY | -## Surfaces (17, 1 planned) +## Surfaces (18, 1 planned) | Command | Id | Toolbar | |---|---|---| +| Boundary Surface | `surface.boundary` | SURFACE › CREATE | | Patch | `surface.patch` | SURFACE › CREATE | | Stitch | `surface.stitch` | SURFACE › MODIFY | | Thicken | `surface.thicken` | SURFACE › CREATE | @@ -248,7 +249,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Break Link | `component.break_link` | – | | List Links | `component.links` | – | -## Assembly joints (15) +## Assembly joints (16) | Command | Id | Toolbar | |---|---|---| @@ -262,6 +263,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Gear | `joint.gear` | SOLID › ASSEMBLE | | Rack and Pinion | `joint.rack_pinion` | SOLID › ASSEMBLE | | Screw | `joint.screw` | SOLID › ASSEMBLE | +| Cam | `joint.cam` | SOLID › ASSEMBLE | | Joint Limits | `joint.limits` | – | | Edit Joint | `joint.edit` | – | | Delete Joint | `joint.delete` | – | @@ -485,13 +487,14 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | List Faces | `model.faces` | – | | List Threads | `model.threads` | – | -## `motion.*` (7) +## `motion.*` (8) | Command | Id | Toolbar | |---|---|---| | Motion Study | `motion.study` | SOLID › ASSEMBLE | | Play Motion Study | `motion.play` | – | | Export Motion Study | `motion.export` | – | +| Export Motion Animation | `motion.export_animation` | – | | Motion Trace | `motion.trace` | SOLID › ASSEMBLE | | Keep Motion Trace | `motion.trace.keep` | – | | List Motion Studies | `motion.list` | – | diff --git a/docs/localization.md b/docs/localization.md index 16c0f14ba..ab2cced75 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -1,7 +1,7 @@ # UI localization -SolidCraft embeds its translations and works offline. English, Japanese, German, French, Korean, -Russian, Ukrainian, Turkish and Chinese are currently registered in `crates/ui-egui/src/i18n.rs`. Adding a language requires an +SolidCraft embeds its translations and works offline. English, Japanese, German, French, Galician, Korean, +Brazilian Portuguese, Russian, Ukrainian, Turkish and Chinese are currently registered in `crates/ui-egui/src/i18n.rs`. Adding a language requires an embedded catalog and one registration there; the preferences selector and validation use the same registry. @@ -31,8 +31,8 @@ that looks untranslated. Two guards catch that in the build: - `every_complete_catalog_carries_every_english_message` — adding a key to `en.json` without giving it to a complete catalog fails the tests. English is the source catalog, - Japanese and Chinese are delivered complete; German, Korean, Russian, French, Ukrainian and Turkish are - partial — their gaps fall back to English and are reported by `cargo xtask i18n` without + Japanese and Chinese are delivered complete; German, Galician, Korean, Brazilian Portuguese, Russian, French, Ukrainian and + Turkish are partial — their gaps fall back to English and are reported by `cargo xtask i18n` without failing the build. A new label needs en, ja, zh, de and ko; Russian, French and Ukrainian may follow later. - `every_toolbar_tab_and_panel_is_in_the_english_catalog` — tabs and panels reach the UI as bare diff --git a/docs/mcp.md b/docs/mcp.md index 4085cd84a..3f44efa31 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -149,7 +149,7 @@ They cover the workflow, the command shapes, how to verify with `measure`, and t | `measure` | `body?` or `items?` | Volume (mm³), area (mm²), centre of mass, bbox and topology counts per body, with totals. With `items` (one or two selections as `execute` takes them: `face`, `edge`, `vertex`, `sketch_curve`, `profile`), the picked geometry instead: see below. | | `body_topology` | `body` | Edges (index, midpoint, length, ends) and faces (index, name, area, centroid, normal, `point`, and for a cylindrical face its `cylinder`: `origin`, `axis`, `radius`). An edge midpoint is the `[x,y,z]` that picks that edge for fillet and chamfer. A face's `point` lies on it and picks it (its centroid may not: that of a face with a hole is in the hole); a face's `name` picks it for the commands that take faces (`face.delete`, `solid.shell`, `solid.draft`, `solid.offset_face`, `solid.split_face`, `solid.replace_face`, and `face` of `sheet.convert`). | | `set_parameter` | `name`, `value` (number or expression), `unit?`, `comment?` | Create or change a user parameter and recompute; reports `recomputed` (features rebuilt), `restored` (features whose earlier result for the same inputs was reused, e.g. a value set back) and features that now fail. | -| `screenshot` | `view?` (iso, top, front, back, bottom, left, right, home, fit, or a named view saved with `view.save`), `camera?` (`{target, yaw, pitch, distance, fov?}`, as `view.apply`), `path?`, `width?`, `height?`, `source?` (window, model), `grid?`, `axes?` | A PNG image content block. Headless: a render with the viewport's pipelines on a headless GPU device (see `solidcraft-cli gpu`; with no adapter, the CPU rasterizer, without analysis colours), fitted to the model, or from the named view or camera; the reply's `renderer` says which (`gpu`, `gpu-software`, `cpu`, with a `warning` for `cpu`). Bridged: the app window (default) or a model render with the app's camera; a named view or camera moves the app's viewport there first (`execute` `view.apply` does the same without a screenshot). `grid: false` and `axes: false` leave the ground grid (it lies on Z 0 and cuts through a part that straddles it) and the origin's axes out of a model render; axes hidden with `browser.visibility` stay out whatever `axes` says. Bridged, a screenshot that gives `grid` or `axes` is a model render, which follows the app's Grid and Origin switches for what it does not give; `source: "window"` with either is an error. | +| `screenshot` | `view?` (iso, top, front, back, bottom, left, right, home, fit, or a named view saved with `view.save`), `camera?` (`{target, yaw, pitch, distance, fov?}`, as `view.apply`), `path?`, `width?`, `height?`, `source?` (window, model), `grid?`, `axes?` | A PNG image content block. Headless: a render with the viewport's pipelines on a headless GPU device (see `solidcraft-cli gpu`; with no adapter, the CPU rasterizer, without analysis colours), fitted to the model, or from the named view or camera; the reply's `renderer` says which (`gpu`, `gpu-software`, `cpu`, with a `warning` for `cpu`). Bridged: the app window (default) or a model render with the app's camera; a named view or camera moves the app's viewport there first (`execute` `view.apply` does the same without a screenshot). `grid: false` and `axes: false` leave the ground grid (it lies on Z 0 and cuts through a part that straddles it) and the origin's axes out of a model render; axes hidden with `browser.visibility` stay out whatever `axes` says. Bridged, a screenshot that gives `grid` or `axes` is a model render, which follows the app's Grid and Origin switches for what it does not give; `source: "window"` with either is an error. A window that is minimised or on another macOS Space presents no frame: with no `source` the reply is a model render and says so (`fallback`); `source: "window"` is an error saying why, at once. Agents that don't need the app's chrome can ask for `source: "model"`. | | `export` | `path`, `format?` (step, 3mf, 3mf-tagged, stl, stla, obj, urdf), `bodies?`, `mesh_prefix?`, `effort?`, `velocity?` | STEP, 3MF or mesh export; URDF writes the whole assembly with its meshes next to it (`docs/urdf.md`). | | `undo`, `redo` | — | Undo / redo one change. | | `crash_reports` | `id?`, `limit?` | The crash reports on this computer, newest first; with `id`, the whole report (backtrace, command, recent commands, `design_path`/`replay_path`). See [crash-reports.md](crash-reports.md). | diff --git a/docs/render-environment-sampling.md b/docs/render-environment-sampling.md new file mode 100644 index 000000000..bebe99d1c --- /dev/null +++ b/docs/render-environment-sampling.md @@ -0,0 +1,144 @@ +# HDR environment sampling (#1693) + +Source implementation and opt-in CPU direct-light consumer are prepared. No +executed HDR-lit PNG, test, full gate or delivered HDRI feature is claimed. The +existing default preview remains unchanged. + +`lighting::environment_sampling::EnvironmentPreparation` borrows an existing +`DecodedHdr`. It checks bounded 2:1 dimensions and original pixel allocation +capacity, then validates at most 16,384 pixels per step. The caller supplies a +fallible work/cancellation callback, charged for each inspection. Errors consume +preparation; `finish` refuses incomplete validation. No decoder, cache, CDF, +pixel clone, worker or pool is added. The existing owner and admission lease must +outlive the borrowed view. `retained_pixel_bytes` reports capacity, not length; +the host charges the owner for its retained lifetime. Captured image storage is +released before PNG publication; retained capture metadata has its own Record lease. + +## Coordinates and estimator + +Directions point away from the shading point. The map is Z-up: +Z is north, +`phi=atan2(y,x)`, `u=wrap(phi/(2*pi))`, `v=acos(z)/pi`. Nearest lookup uses +half-open texel cells centred on `((x+.5)/width,(y+.5)/height)`. Longitude wraps, +the south pole clamps to the last row, and an exact pole chooses longitude zero +before rotation. Positive rotation turns the environment about +Z toward +Y; +lookup subtracts that rotation. There is no extra orientation inherited from an +external application's conventions. + +The first proposal samples uniform z in (-1,1) and phi in (0,2*pi). Since +`dOmega=dphi*dz`, its PDF is `1/(4*pi)` per steradian everywhere. The PDF remains +normalized for black maps, without a division by total image brightness. Constant +maps preserve their radiance. This is not importance sampling; small bright +sources can have high variance. Nearest lookup is intentionally not bilinear +filtering or a claim of antialiasing. Floating-point boundary rounding can still +produce a pole, whose lookup is defined. + +`direct_sample_linear_srgb` returns an unoccluded `BRDF*cos*Li/pdf` estimate. +The geometric normal excludes incident and view directions crossing the original surface; +the shading normal affects the BRDF and cosine. The consumer owns visibility and +averages exactly once over the requested environment sample count. The helper +does not apply exposure, mapping, sRGB encoding or a sample-count division. + +## Colour policy + +Decoded HDR is linear RGB in its SOURCE space. RGBE decoding has already divided +by the file's exposure and colour correction; sampling never repeats either. +Source-space lookup is explicitly named `radiance_source_rgb`. + +The initial lighting adapter admits only explicit `PRIMARIES` values matching +sRGB/D65: `0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290`. It uses these linear +channels directly, without applying the sRGB transfer curve. Missing primaries +and all other primaries refuse illumination; default Radiance RGB is not silently +relabeled sRGB. Supporting other primaries requires a separately validated gamut +and white-point conversion. No clipping or invented conversion is used here. + +## CPU consumer source and remaining integration + +The new branch starts from actual upstream history. The separately qualified RT2 +source is not a commit parent or an executed validation result for this module. +Integration must use its real prerequisite commit or an explicitly recorded +source overlay before its own gates; no copied build outputs. + +1. Capture the admitted existing HDR source and preserve its original encoded allocation. + Include encoded/decoded retained capacities, request clones and state in the + existing 384 MiB job and 512 MiB shared admission. Capture metadata keeps its + Record-owned lease after frame eviction. Refuse unsupported primaries before publication. +2. Incremental preparation calls the SAME cumulative job work budget and cancel + token. The implemented owned adapter moves `EnvironmentInput` through host work + into one existing `HdrDecodeTask`. The image task owns its completed `DecodedHdr` + and creates short-lived borrowed views, without a self-referential borrow or a + second decoded copy. Decoding validates corrected texels incrementally; internal + views check shape and capacity without rescanning every texel for each sample. + Execution and visual acceptance remain pending. +3. At an opaque hit, each environment direct sample creates one positive-minimum + secondary visibility ray from the shared geometric offset. Reuse the existing + resumable traversal cursor, charging every sample and traversal unit. Add visible + estimates in linear space and divide by environment sample count once. +4. Primary misses remain equal to the requested display background. The + `radiance_linear_srgb` API is available for later secondary-miss transport; + reflection continuation is not connected in this consumer. Combining environment + next-event estimates and rough-specular paths that miss requires matched MIS + or a documented partition of the two terms; until implemented, refuse that + combination. Do not count the same environment specular energy twice. +5. Add environment illumination to existing direct lights without adding another + ambient term. Exposure, Reinhard and sRGB transfer remain a single final step. + Image/task/host cancellation must publish no partial successful frame. + +Original analytic tests generate RGBE bytes at runtime: constant map and PDF, +single bright cell solid angle, black map, axes/rotation/seam/poles, cancellation +and shared-budget failure, decoder corrections, unsupported primaries, hostile +options/directions and an independent white-conductor hemispherical integral. +They have NOT RUN. No external assets, dependencies or persistence fields added. + +Mathematical references only; no code or figures copied: +[PBRT, Infinite Area Lights](https://pbr-book.org/4ed/Light_Sources/Infinite_Area_Lights) +for radiance and solid-angle estimators (its image mapping is different), and +[W3C CSS Color 4, sRGB](https://www.w3.org/TR/css-color-4/#predefined-sRGB) +for the sRGB/D65 primary coordinates and the distinction from encoded sRGB. + +## Opt-in request (not yet executed) + +`render.preflight` / `render.start` accept an `environment` object alongside +`integrator:"raytrace"`, for example: + +```json +{"integrator":"raytrace","raytrace":{"lights":[]},"environment":{"path":"original-srgb.hdr","rotation_radians":0,"intensity":1,"samples":64}} +``` + +The input path uses the existing scoped, bounded VFS reader and `HdrSource`. +The captured source is passed separately to `CpuHost::submit_with_environment`, +never serialized or cloned into job status. A separate fixed-size `EnvironmentInfo` +records the SHA-256 digest, numerical header, controls and explicit colour policy in +preflight and status, without the source path or pixels. Encoded capacity, exact decoded storage, +scanline storage and bounded state are added before the shared reservation; +allocators that exceed admitted scanline/decoded capacities refuse. Direct-light +visibility uses the existing positive-minimum ray and resumable cursor. Primary +misses retain the exact requested background. Samples use deterministic z/phi +stratum centres (one sample uses a fixed interior point); finite-count quadrature +can be biased and is not a convergence or unbiased-rendering claim. + +The standalone HDR checkpoint has no reflection continuation. This isolated +combined source connects secondary environment misses and explicitly selected +metallic rough reflectors or ideal mirrors; see +[the integration contract](render-hdr-reflections-integration.md). Mixed/diffuse +rough HDR combinations and unknown optics fields refuse. No MIS, transmission, +texture, emissive geometry, GPU or saved HDR environment is advertised. Existing +saved environment controls remain refused; runtime controls are explicit above. + +Seven consumer source regressions complement the nine analytic/input regressions: +an image-task PNG oracle and deterministic/background checks, decode/visibility +cancellation and work exhaustion, native captured-source ownership, four-unit +quanta, all traversal-to-shading transitions, engine rendering after source-file +removal compared with unlit geometry, and capture-metadata lease release after +PNG eviction. All 16 tests remain NOT RUN. + +Consumer review repairs: environment cursor continuation charges traversal without +an additional shading debit; each pixel quantum remains at most four shared work +units. Both request resolvers require `Hdri` when a source is captured. Only the +native feature-on raytrace descriptor advertises this narrow environment path. +Preflight and job status retain fixed-size SHA-256 bytes, bounded header numbers, +controls and explicit colour policy; neither the input path nor image bytes are +retained there. Fixed metadata is charged to the Record-owned lease independently +of the PNG, while captured image storage stays under the work lease. Preflight +includes retained request metadata in its combined per-job estimate. A regression +withdraws the actual HDR file and compares lit geometry against the same unlit job. +All tests remain NOT RUN. diff --git a/docs/render-hdr-reflections-integration.md b/docs/render-hdr-reflections-integration.md new file mode 100644 index 000000000..0d423ab0e --- /dev/null +++ b/docs/render-hdr-reflections-integration.md @@ -0,0 +1,152 @@ +# HDR radiance in scene reflections (#1693 + #1658) + +This is an isolated source integration of the reviewed HDR and reflection units. +Neither prerequisite is represented as a fictional commit parent. The separate +source-overlay receipts identify them; their original worktrees and checkpoints +remain unchanged. No compilation, executed test or visible result is claimed here. + +This central candidate combines the direct-image, specular reflection, +anisotropic-core and HDR consumer contributions over one real upstream merge. +It also includes the coordinate-plane depth correction, deterministic-primary +shading reuse and the stratified reflection sequence described below. Earlier +source-specific checks and images are historical; all gates and visible evidence +must be established again on the final integrated source. No prerequisite's +source-overlay identity is represented as a Git implementation parent. + +## Disjoint lighting paths + +A camera ray that misses geometry still writes the requested background exactly. +It does not see the environment emitter and does not pass that background through +exposure. A reflected secondary ray that misses geometry reads the existing +owned environment through `radiance_linear_srgb(direction)` and adds +`throughput * Li` to its linear path radiance. Reflection sampling already put +`specular_BRDF * incident_cosine / matching_PDF` into that throughput; do not +divide by a second environment PDF at the miss. Mirror is an explicit delta +event with its existing Fresnel weight, independent of minimum roughness. + +Selected mirror/rough reflectors receive no environment next-event estimate. +Nonselected opaque hits retain the existing environment direct-light estimator +and visibility. This partitions the environment contribution at each hit, without +MIS or double counting the same specular environment paths. Existing directional +direct lighting remains separate: there is no emissive geometry or infinite +directional-light intersection on a reflected miss. At the fixed bounce cap, +untraced continuation is discarded, as in the original finite-depth preview. + +The first HDR+rough combination admits only fully metallic (`metallic == 1`) +selected bodies and every effective face override. Dielectric, partly metallic +or scalar face responses refuse in engine preflight, host admission and direct +task construction. This conservative body-wide check also refuses a mixed body +whose unvisited face is nonmetallic. Without this restriction, omitting the +environment next-event term would silently lose diffuse illumination. Supporting +those responses requires an explicit diffuse/specular partition or validated MIS. +Explicit mirrors retain their declared ideal-reflection/Fresnel intent. + +The isotropic GGX sampler, its outgoing PDF, null below-surface samples and +specular throughput are unchanged from the pinned reflection unit. The integrated +planar anisotropic adjunct replaces only the selected face's matched rough sampler +and directional direct BRDF. There is no retry, PDF renormalization or diffuse-over- +specular-PDF mixture. Both samplers preserve the same HDR miss contract. + +## Reflection sequence and deterministic primary reuse + +The reflection variate generator receives the actual requested count R in 1..64 +and rejects ordinals outside that count. It visits each radial stratum once using +a shared 32-bit midpoint jitter, with a pixel/bounce digital shift of a base-two +radical-inverse azimuth. Both coordinates remain strictly open. Exact dyadic +azimuth coverage applies only to power-of-two R; other counts retain radial +coverage only. Changing R changes the radial sequence, so there is no progressive +prefix, independent-draw, unbiasedness or universal variance-reduction guarantee. + +NDF mapping, PDF, specular weights and null-event accounting are unchanged. +Every null attempt still contributes zero to the original R divisor. R-attempt +and bounce bounds are unchanged; actual outgoing paths, null outcomes and work +can differ with the directions. Five new source tests exercise the production +generator, including the white-conductor mean 1-ln(2), second moment 3-4ln(2) +and a derived 1/R quadrature bound for that specific monotone fixture. Existing +tests that retain the test-only hash control do not certify the new generator. +The production image's independent weight check uses the new sequence. + +The current primary generator uses fixed pixel centers. A nonselected primary +surface's direct/environment shading is therefore reused across reflection +samples, while retaining the original ordered scalar sums, per-add radiance +bound, divisor and single display transform. Selected reflectors and secondary +paths retain their full sampling. Future jitter, film or time-varying inputs +must revoke that repeatability proof. No antialiasing or film capability follows +from this optimization. Seven source tests cover its color, work and refusal +contracts; none has executed on this central candidate. Equal-R visible quality +and actual-work comparisons remain required for the new reflection sequence. + +## Ownership, budgets and colour + +The same captured source, decoder, decoded pixels, host pool and work budget are +used. `RaytraceOptions::retained_bytes` now accounts for original light capacities, +reflection selector slots and selector string capacities in one calculation used +by engine preflight and host admission. Fixed HDR capture metadata keeps the +Record lease; captured image storage stays under the work lease and is released +before PNG publication. The combined 384 MiB job limit and 512 MiB pool remain. + +One existing decoder state is held in a fallibly allocated capacity-one vector, +with a checked 4096-byte state bound, covered by the existing 8192-byte HDR state +allowance. This keeps its scanline-scale array out of the image task's inline +metadata as the reflection cursor state grows. It is not another decoder, cache, +loader, worker or pool. Actual vector capacity must be one. Completion drops that +slot; decoded/scanline capacities and source capacities retain their prior checks. +A source regression checks the combined image task fits its 4096-byte host slot; +that test has NOT RUN. + +Preparation, traversal and reflection continuation charge the shared cumulative +work budget and observe cancellation. Cursor-to-shading transitions yield before +another debit. HDR misses remain linear; finite radiance caps apply before the +sample average and single exposure/Reinhard/sRGB output transform. Primary +background is independent. Only explicit sRGB/D65 HDR primaries are admitted; +default/unknown Radiance primaries and unsupported optics remain refused. + +## Added source regressions and remaining validation + +Five source tests cover: a white ideal mirror receiving constant HDR exactly once; +unchanged camera background; rough-metal output from independent normal-view +GGX sample weights and deterministic variates; a broad bright cell rotating in +world space; rejection of mixed/diffuse rough responses; retained selector +capacities/task layout; and cancellation/work exhaustion during secondary +transport. All previous HDR and reflection test sources are retained unchanged. +These tests have NOT RUN, and the prepared PNG comparisons are not screenshots. + +Before publication, integrate real prerequisite history, run the combined +default/feature checks, Clippy/wasm and required project gates, then produce and +inspect exact-build native images. The original constant and bright-cell HDR +fixtures carry MIT OR Apache-2.0 attribution; no external assets are added here. + +## Planar anisotropic hooks (source only) + +The Kernel-authored core and `PlanarTarget::sample` bridge are adopted from pinned +#1694 source; its reference ImageTask is not copied. One image task captures an +authoritative optional mesh face tag per primitive, binds at most two targets by +captured body ordinal AND exact body name AND face tag, and caches their validated +planar frames. A missing tag or identity mismatch refuses instead of retargeting +by plane geometry. Strict planarity can conservatively refuse imported/rotated +roundoff. Face appearance `surface: None` replaces body PBR with the scalar +response; it never inherits a metal response for admission. + +At a rough selected hit, a bound target supplies the existing matched anisotropic +specular direction/PDF/weight. Equal axes delegate the existing isotropic sampler. +Other faces use the original rough sampler. Directional direct light uses the +bound anisotropic BRDF. HDR next-event lighting is still isotropic, so HDR plus +anisotropy on a non-reflector is rejected in preflight/host/task. The supported +HDR combination requires a rough reflection selection and the same fully metallic +body/ALL-face rule. A delta mirror plus anisotropic rough axes is rejected even +without HDR. No anisotropic HDR direct estimator is advertised. + +Original target-name capacities join the same retained request calculation and +Record lease. Fixed cached targets and request clones fit the conservative bounded +state allowance; primitive face tags are included in actual primitive size. +Task construction repeats at most two 4096-triangle target validations, debiting +the existing cumulative work/cancellation callback. Pixel traversal and sampling +keep the existing one-unit yields, including secondary hits and final shadows. + +The prior five HDR/reflection tests remain, with three added combination tests: +equal-axis HDR reflection matches isotropic PNG bytes; unsupported direct/mirror +combinations refuse; and an actual anisotropic secondary hit into another body +yields within one unit (four per public quantum) and observes cancellation. +Kernel's core/face tests and v4 continuation regressions are also retained from +pinned source. Every added/adopted test is NOT RUN in this integration. Independent +source review and the combined execution/visual gates remain pending. diff --git a/docs/render-raytrace-core.md b/docs/render-raytrace-core.md new file mode 100644 index 000000000..a9c98c272 --- /dev/null +++ b/docs/render-raytrace-core.md @@ -0,0 +1,121 @@ +# Optional CPU triangle visibility core (RT1, #1368) + +This page documents the RT1 numerical core, not the complete image consumer. +The [RT2 image contract](render-raytrace-image.md) covers native jobs and hard +shadows. The [combined HDR/reflection integration](render-hdr-reflections-integration.md) +extends that consumer; its capabilities do not change this core's standalone scope. +See the RT2 page's current integration limits before treating historical source +checks as validation of the combined revision. + + +`solidcraft-render` exposes `raytrace` only with the explicit `raytrace-cpu` +feature. The feature is **off by default** and adds no dependencies. This page +describes the core alone. The separate [RT2 consumer](render-raytrace-image.md) +connects it to the existing image executor; neither unit adds a worker pool or +persisted settings. This numerical core alone does not render an image or implement cast shadows, progressive +transport, soft shadows, textures, HDRI, glass, denoising or GPU tracing. + +The source is original safe Rust using elementary slab, barycentric and binary +tree mathematics. No Blender/Cycles, PBRT or other tracer source was consulted +or adapted. Only L0 `Vec3` geometry and the existing render cancellation token +are consumed; no truck, B-rep or SolidCore interface is involved. + +## Geometry and hit policy + +Inputs are already world-space tessellation in millimetres. Instance transforms +must not be applied again. Each admitted `Ray` normalizes its finite nonzero +direction using scaled arithmetic; its closed finite `[min, max]` interval is +therefore measured in millimetres. Origins and triangle vertices are limited to +`+/-1e12` mm; maximum ray distance is `4e12` mm. Ray direction magnitudes are not +subject to a fixed small-vector epsilon. + +`Triangle` admits coincident and collinear vertices, which produce no hits. +Intersection projects into the plane perpendicular to the dominant ray axis, +applies a shear, and evaluates closed-edge barycentrics. Both sides can hit. +Geometric normals and the front-face flag are returned separately from any +future shading normal. Zero projected area is a miss, including geometry that +collapses in f64 arithmetic; this is not an exact CAD predicate or a universal +watertightness guarantee. No fixed determinant threshold masks small triangles. +Analytic source tests cover scales from `1e-120` to `1e11` mm. + +Closest-hit ties at exactly equal computed distance choose the lowest captured +input ordinal. That ordinal is **not a persistent CAD face identifier**: the +later consumer must preserve its own triangle-to-appearance mapping. Shared +edges and vertices are included; no artificial half-open coverage rule is +introduced. Ray origins are not offset automatically. In particular, `min=0` +allows a hit at the origin; RT2 must explicitly define a scale-aware self-hit +policy for shadow rays without erasing thin geometry. + +Boxes use closed slab overlap and special-case zero/signed-zero directions. +Almost-parallel division may produce infinity, which is clipped against the +finite ray interval; the implementation does not multiply zero by an infinite +reciprocal. Triangle boxes expand outward by one representable floating-point +step, rather than a fixed millimetre tolerance. + +## Bounded preparation + +`BvhBuilder` takes ownership of a vector of admitted triangles. Input capacity, +not just input length, participates in memory admission. It reserves ordinal, +flat-node and pending-task buffers before constructing the hierarchy. There is +no sorting copy of the scene, recursion, unbounded partition retry or hidden +secondary worker. All buffer allocation is fallible. + +`step(operations, cancel)` accepts 1–4096 operations. Each operation initializes +one ordinal, scans one primitive's bounds/centroid, partitions one ordinal, or +performs a constant-size state/node transition. Work and cancellation are +checked before every operation. Source scanning and partitioning are resumable, +so a large node does not hide a full-scene operation inside one step. + +The split plane is the midpoint of the widest centroid extent, with X/Y/Z tie +order. Partitioning is deterministic. An empty partition falls back to the +middle of the existing ordinal range. The private task stack is bounded by +depth; at the depth cap a leaf retains its remaining range. `finish()` refuses +an incomplete builder; partial acceleration structures are not published. + +Defaults allow 100,000 triangles, 128 MiB logical memory, 10 million operations, +depth 32 and leaves of eight primitives. Hard admission caps are one million +triangles, 512 MiB, one billion operations, depth 48 and leaf target 64. Checked +arithmetic rejects overflow before allocations. Maximum node reservation is +`2*N-1`; empty scenes reserve no nodes. If a platform returns larger Vec capacities, +those capacities are checked again before use. + +The memory figure includes owned triangle capacity, ordinal/node/task capacities, +fixed builder/BVH metadata and one traversal stack. It is a logical buffer bill, +not allocator-overhead/RSS measurement and not an acquired host lease. The RT2 +image consumer must admit these bytes through the existing host pool together +with capture, output, encoding and any other job resources. No such integration +is claimed here. + +## Queries and cancellation + +`closest_hit` and `any_hit` use a fixed 49-slot traversal stack. They check the +existing cancellation token and consume a caller-owned `WorkBudget` for every +node visit and primitive test. One budget can span many rays. Budget exhaustion +returns `TraceError::WorkLimit`; it never returns the best hit found so far as +if traversal had completed. Any-hit stops at a real primitive hit. A leaf at the +depth cap can be large, but each primitive still has its own work/cancel check. + +These are bounded synchronous queries, not an installed cooperative browser +renderer. Host scheduling, per-job wall deadlines, late-result identity and +publication/cancellation policy remain responsibilities of the existing job +system and the RT2 consumer. Default builds do not compile or initialize this +module and ordinary modelling/opening/saving routes are unchanged by RT1. + +## Validation status and next unit + +The source includes analytic distance/barycentric/normal tests, tiny/huge and +grazing cases, shared-edge ties, slab/parallel cases, BVH-versus-brute-force +seeded closest/any-hit comparisons, hostile float admission, deterministic +incremental stepping, depth/degenerate termination and work/memory/cancellation +checks. These are planned executable checks, **not passing results until run**. + +Required validation before publication: project quality gates, default and +feature-enabled render tests/strict Clippy, and feature-enabled wasm checking. +The current source-only preparation intentionally does not run Cargo while +another owner holds the shared machine's build window. + +RT2 is the separate useful image unit: explicitly selected opaque CPU visibility +and cast shadows, using the existing camera/scene and host ownership/accounting. +That unit needs an original native scene and completed output, cancellation and +two-document/late-result checks, unsupported-optics refusal and measured costs. +Nothing in this core alone satisfies that visible acceptance milestone. diff --git a/docs/render-raytrace-image.md b/docs/render-raytrace-image.md new file mode 100644 index 000000000..5f37537b6 --- /dev/null +++ b/docs/render-raytrace-image.md @@ -0,0 +1,162 @@ +# CPU ray visibility and hard shadows (RT2) + +## Current combined integration boundary (2026-10-16) + +The sections below describe the original RT2 direct-image stage. In the combined +source, [HDR/reflection integration](render-hdr-reflections-integration.md) adds +selected ideal/rough-specular reflections and certified planar anisotropy. +[Environment sampling](render-environment-sampling.md) describes the earlier +standalone direct estimator; the combined page specifies the connected reflection +path and its disjoint HDR estimators. [HDR input](render-hdr-input.md) remains the +bounded decoder route. Only explicit sRGB/D65 primaries are admitted for lighting. +HDR plus rough reflections requires fully metallic selected bodies and all +effective face responses. HDR plus anisotropy requires the supported rough +reflection combination; direct anisotropic HDR and anisotropic delta mirrors +refuse. Those additions do not imply MIS, GI or unrestricted material transport. + +The opt-in `solidcraft-engine/raytrace-cpu` feature forwards the render feature. +The current native host selects `cpu-raytrace` only for explicit +`integrator: "raytrace"`; raster remains the default, and cooperative/browser +hosts refuse ray tracing. Use the same preflight/start/status/cancel/export +commands and job identity described in [product-image jobs](render-jobs.md). +Preflight does not reserve a queue slot or memory; start repeats admission. +The existing CLI `render` wrapper does not accept `--integrator` or +`--raytrace-options`; it submits settings and transparency through the default +raster route. Use engine commands through a persistent native MCP session with +the compiled feature and installed host for this ray tracing workflow. A one-shot +CLI process is not a durable asynchronous job host. The current Render workspace +UI also submits settings and transparency without selecting the ray tracing +integrator. Its ordinary buttons do not establish a ray tracing UI workflow; +that UI and GPU ray tracing are not qualified by the headless MCP evidence. + +Primary rays still use fixed pixel centers. More reflection samples do not +provide geometric antialiasing. The retained raster scratch estimate does not +mean ray tracing performs raster supersampling. This consumer does not connect +texture sampling, glass/refraction/transmission, area lights, point/spot lights +or LED strips; separate modules are not evidence of integration. Output remains +opaque Preview/Image/PNG, without EXR or GPU ray tracing. Existing shared-host +limits remain: 262,144 triangles, 128 MiB retained source geometry, 384 MiB job +admission and a 512 MiB shared pool. These are not total CAD-process RSS limits. +HDR buffers, reflection selectors and actual retained capacities join the same +ownership/accounting; the common cumulative work cap remains 1,000,000,000. + +This combined candidate has not been compiled, tested or rendered. It includes +the exact-coordinate-plane depth correction. On its earlier isolated source, +the Rust witness failed before the correction and passed afterwards; that source +passed 222 feature-on and 147 feature-off render tests plus scoped Clippy/wasm. +Those historical results do not qualify this candidate after main integration, +primary-shading reuse and reflection-sequence changes. General oblique and +near-edge robustness remain outside the coordinate-plane correction's scope. + +The original combined source's full CI ended incomplete at its fixed deadline. +Known modelling golden failures remain recorded separately; do not attribute +their cause to rendering without paired baseline evidence. An earlier optional +960x540 request exhausted the billion-unit cap without producing a PNG; smaller +drafts do not qualify that request. No cap, assertion, tolerance, ignore or +golden-baseline change is implied, and presentation readiness remains pending. + +Before publication, execute the relevant regressions, complete current +`cargo xtask ci` and wasm checks, and inspect exact-build native visibility, +shadow, reflection and HDR output. Historical results and source review alone +do not qualify the final combined revision. The stage-specific validation text +below is historical scope, not a current pass/fail report. + + +This opt-in slice of #1368 follows the phased render design in #620. It connects +SolidCraft's original RT1 triangle/BVH core to immutable product captures and the +existing image-job host. The `raytrace-cpu` Cargo feature is off by default. +Implementation is under review; tests, native PNG acceptance and full CI for this +integration remain pending. Historical RT1 results do not qualify this new consumer. + +## Runtime contract + +`render.preflight` and `render.start` accept `integrator: "raster"` (the default) or +`"raytrace"`. Optional `raytrace` settings contain `lights`, `exposure_ev` and +`shadows`, plus an optional `preset` (`neutral`, `warm_cool`, `key_rim`). +A preset and an explicit lights list are mutually exclusive, including an empty +list. Presets use original hard directional-light compositions, not calibrated +color-temperature claims. These values belong to the request, not the saved document or render +setup. A build without the feature refuses raytracing before geometry capture. +The initial image executor is native-only; no browser performance is claimed. + +Each light has a world-space `direction: [x,y,z]` pointing **towards the light**, +linear-sRGB `color: [r,g,b]` and relative `intensity`. Directions are normalized; +all numbers must be finite. At most eight lights and eight retained slots are +accepted, colors are in [0,1], intensity in [0,64], exposure in [-16,16] EV. +Omitting lights uses the existing three-light studio. An empty list is darkness. +These are relative radiances, not measured lux or watts. Background color remains +independent of illumination and exposure. + +The scene must be opaque, including face overrides; transparent backgrounds are +refused. Captured world positions are used once, preserving occurrence placement. +Scalar colors become linear-sRGB opaque dielectric surfaces (roughness 0.7, IOR +1.5); explicit opaque surfaces retain their metal fraction, roughness and IOR. +This scalar fallback differs from the legacy raster shading and is not a measured +material fit. Density and engineering properties do not change. + +The camera uses the existing pixel rays and the same scene-radius near/far policy +as product rasterization. Primary rays start on the near plane; shadow rays have +independent finite intervals. There is one center sample per output pixel, so edge +quality can differ from the supersampled raster image. Shading uses interpolated +normals with a geometric-normal fallback and hemisphere checks. + +Per-light BVH visibility supplies hard shadows to the existing opaque BRDF. Linear +contributions are summed, exposure is applied once, then Reinhard and the piecewise +sRGB transfer are applied once. Shadows can be disabled without changing the BRDF. +No SSAO is multiplied into this output. No indirect lighting, soft shadows, +reflection transport, texture sampling, HDRI lighting, refraction, absorption, +emission transport or denoising is implemented here. IOR controls opaque Fresnel; +it does not make glass. Unsupported requested capabilities must fail explicitly. + +## Work and memory + +The same native queue, worker, cancellation token and 512 MiB host reservation are +used. There is no additional worker pool. Admission retains the conservative raster +geometry/pixel/codec estimate and adds BVH input/nodes/order/build stack, per-triangle +surface/normals/vertices and 8 KiB for task/light/traversal state. Total admission +must remain within 384 MiB including the checked sum of work and retained request +allocations. Original directional-light capacities keep a separate lease from the +same pool for the job-handle lifetime, even after PNG eviction. Actual buffer capacities may not exceed the planned +capacities; the builder's actual reservation is checked before continuing. + +One cumulative maximum of one billion work units covers preparation, BVH build, +primary and all shadow traversal. Builder operations are debited into that same +budget. Exhaustion and cancellation are typed failures, never truncated visibility +or a partial successful image. Each traversal step visits at most one node or +primitive; each preparation step examines at most one face override. A task call +performs at most four such units, or four PNG rows. These are work bounds, not a +hard real-time or operating-system memory guarantee. + +Shadow origins are reconstructed from triangle barycentrics. Component-wise +floating-point rounding bounds projected onto the geometric normal and one outward +representable step replace a fixed world-space epsilon. Secondary intervals require +a strictly positive representable distance to exclude signed zero after subnormal +interpolation. This avoids displacing a +Z-plane merely because X is large. Floating-point geometry still has finite +resolution; thin blockers, self-intersection and translated scenes require tests. + +PNG encoding reuses the bounded cancellable row encoder. Captured geometry, +acceleration data, pixels and light buffers are released before successful output +is returned; the host drops task state before shrinking to the retained PNG lease. +Cancelled or failed jobs preserve the previous successful frame. + +## Provenance and acceptance + +RT1 was copied, with its owner's authorization, from the existing isolated +`rt1-raytrace-core` contribution. Its original source remains untouched. The new +resumable cursor and image consumer are original Rust additions; the source receipt +records the exact adopted hashes. No external rendering engine, shader source, +commercial CAD asset or new dependency is introduced. + +Regressions cover typed cumulative-work exhaustion, resumable traversal parity, +near/far camera policy in both projections/up axes, translated thin occluders, +self-shadow avoidance, runtime refusal and captured-resource release. Lighting tests +use analytic Lambert values and independently masked colored lights. Actual test +counts, compiler results and original-scene PNG review must be reported only after +execution. The draft PR stays unqualified until those gates complete. + +Beyond the original direct-image stage, HDR/reflection connections are described +at the top of this page. Qualified texture resources, role-correct material maps, +progressive transport and explicit glass/medium semantics remain separate work. +Community feedback is welcome on bounded latency, +normal handling, energy loss in the preview BRDF and reproducible acceptance scenes. diff --git a/docs/step-import.md b/docs/step-import.md index 3dcca34d1..6640a3505 100644 --- a/docs/step-import.md +++ b/docs/step-import.md @@ -12,6 +12,24 @@ Every import (STEP, IGES, 3MF, STL, OBJ; inserted, dropped, opened as a new desi A STEP **assembly** keeps its structure: each product under the file's root becomes a component nested under the import's, named after the product, at the place the file gives it. A part (or sub-assembly) the file places more than once becomes **one component with an occurrence per placement**: the Import feature builds the part once and skips the file's later copies (`skip` in the feature, format 22), and the occurrences show it everywhere else. The reply adds `subcomponents` (how many components were made below the import's) and `rigid_joints`. +The Browser reuses body, sketch and construction-plane membership, child lists and resolved placements while the +camera moves. Large assemblies keep their tree open without resolving every part and +folder again on each frame. Geometry edits, assembly changes and uncaptured or reverted +positions refresh those queries; selection, visibility and locking are read live. + +Hover picking pauses while the mouse moves the view and resumes when navigation stops. +A 3D mouse moving the view leaves it on: the pointer hand is free, so preselection and +clicks keep working while the other hand turns the view. Picking uses the cached body +bounds directly in model order, so finding each body's bounds does not scan the assembly +again. + +Hovering an assembly's Browser row retains its whole-body highlight buffers during +rotation, panning and zoom; the GPU transforms those buffers with the camera. The +origin and construction widgets resize independently. Whole-body +highlight generation scans each mesh once rather than scanning it again for every +face. Sketch profile feedback still updates its projected curves and lift toward +the eye as the view changes. + The contents of an imported assembly are **rigid by default**: rigid joints (a rigid group, its glyphs not drawn) hold each part where the file put it in its parent, so moving the import's component moves everything, and an inner part doesn't move on its own; joint degrees of freedom count the whole import as one body. To joint the parts one by one, release them with **Unlock Contents** on the component's browser menu (`component.unlock {component}`), one undo step. Undo takes a whole import away in one step. Designs saved before imports made components keep their Import where it is (no component is made for it) and rebuild as they did. diff --git a/docs/view-dxf.md b/docs/view-dxf.md index 9fa3e3fd5..17ef1bf09 100644 --- a/docs/view-dxf.md +++ b/docs/view-dxf.md @@ -1,8 +1,22 @@ # Export the current view as DXF Choose **File → Export Current View as DXF…**, choose whether to omit hidden edges or -export them as dashed lines, then choose **Export DXF…** and a destination. The hidden-edge -choice is remembered between runs. The Japanese menu is **ファイル → 現在の表示をDXFでエクスポート…**. +export them as dashed lines, set **Curve tolerance**, then choose **Export DXF…** and a +destination. Both settings are remembered. The Japanese menu is +**ファイル → 現在の表示をDXFでエクスポート…**. + +On desktop, the export runs on a background worker while the window continues repainting +and responding to its title-bar controls. A progress card shows mesh preparation, surface +preparation, projection, hidden-line removal and writing, with a count and progress bar for +the current stage. **Cancel** stops at the next mesh or traversal checkpoint; a single +meshing call or sort may need to finish first. The model waits during the export and remains +unchanged on success, failure and cancellation. Individual control-channel +`file.export_view_dxf` commands use the same worker. +The browser's export still runs synchronously on its single thread. + +An export replaces its destination atomically only after the complete drawing is ready. +Cancellation that takes effect before the final write preserves any previous file. Once +that atomic write starts, it finishes; a late Cancel reports the completed save. The drawing uses the camera when Export is pressed, including roll, the world's up axis and perspective. Only shown bodies are exported, at their current component/occurrence @@ -15,7 +29,9 @@ Coordinates are 2D, Z=0, in millimetres. Orthographic views retain 1:1 dimension view plane. Perspective views retain foreshortening, projected onto the plane through the camera target; they are intended for illustrations rather than dimensioned fabrication. Curves and curved silhouettes are approximated with straight segments at a default -model-space chord tolerance of 0.01 mm. This is not an exact analytic curve export. +model-space chord tolerance of 0.01 mm. The setting accepts 0.0001–1 mm; smaller values +produce finer curves and generally need more time and memory. This is not an exact analytic +curve export or a tolerance guarantee for the original imported surfaces. The AutoCAD 2000 ASCII DXF contains `VISIBLE` (continuous) and, when requested, `HIDDEN` (2 mm dashes / 1 mm gaps) layers. Hidden curves use connected `LWPOLYLINE` entities with @@ -29,6 +45,18 @@ are excluded; curved-body silhouettes are included. Very complex drawings fail w error rather than returning an incomplete export. If geometry crosses the perspective camera's eye plane, zoom out before exporting. +Repeated component placements share their export mesh and triangle hierarchy. Each placement +keeps its own edge choices, position and orientation; no bodies are fused or omitted to reduce +the workload. A hierarchy over placed parts rejects unrelated occluders before searching a +part's triangles. Already hidden intervals are skipped, and a fully hidden line stops searching. +Desktop mesh preparation and independent line queries use at most eight computation workers; +the browser runs serially. Export memory, candidate lines, output lines and total occlusion +work remain bounded, and exceeding a budget returns an error without writing a partial drawing. + Programmatic callers use `file.export_view_dxf` with `camera: Camera`, `hidden: "omit"` or `"dashed"`, optional `tolerance` (0.0001–1 mm) and optional `path`. Without `path`, the command returns the DXF text. The command does not modify the design or its undo history. +The result also includes `stats`: placed body and shared mesh counts, source triangle count, +retained mesh bytes, worker limit, candidate segment count, occlusion work, and preparation, +projection and occlusion times in milliseconds. These timings exclude STEP import and DXF +serialization; the worker limit is a maximum, not a claim that every worker was busy. diff --git a/skills/solidcraft-mechanisms/SKILL.md b/skills/solidcraft-mechanisms/SKILL.md index 14562cbda..a9c2fcff7 100644 --- a/skills/solidcraft-mechanisms/SKILL.md +++ b/skills/solidcraft-mechanisms/SKILL.md @@ -42,6 +42,7 @@ Written against SolidCraft `main` after 0.11.1, which counts the degrees of free ## Linked and closed motion - **Motion links:** `joint.motion_link {"a":..., "b":..., "ratio":r, "offset":o}` sets b = r·a + o, clamped to b's own limits. `ratio` is b's units per a's: a pinion that moves its rack 0.5 mm per degree takes `ratio: 0.5`. `offset` is in b's units: degrees for an angle, mm for a distance, or an expression. A mirrored part takes `ratio: -1`, and limits mirrored too. Chains (a drives b, b drives c) work in any order of creation. Drive only the head of a chain. - **Gears, racks and screws:** links whose ratio comes from radii or a pitch, kept up to date when they change. `joint.gear {"a":..., "b":..., "ra":r1, "rb":r2}` turns b r1/r2 as far as a, the other way (`internal: true`: the same way). `joint.rack_pinion {"a":pinion, "b":rack, "radius":r}` moves the rack r·θ. `joint.screw {"joint":cylindrical, "pitch":p}` (or `a`, `b` for a revolute and a slider) advances p per turn. A size is mm, an expression (`"m*z1/2"`), or a round face `{"occurrence":..., "circle":[x,y,z]}` whose radius is read again after every edit. `reverse: true` turns b the other way (a left-hand thread). The driven joint keeps where it is. Drive a, never b. +- **Cams:** `joint.cam {"a":camJoint, "b":follower, "profile":{"sketch":"CamSketch"}}` (or `{"edges":[[x,y,z]]}` on the cam's body) makes a slider or revolute follower ride the cam's outline. `follower`: `knife` (default), `roller` with `radius` (mm, an expression or the roller's round face), `flat`. A revolute follower needs `tip` (its knife's point or roller's centre). The table is worked out again after every edit; the follower keeps where it is, so model it touching. Drive the cam, never the follower. - **Closed loops:** an actuator between a frame and a hinged panel takes three joints besides the hinge: - a revolute root pin (frame and barrel) - a slider (barrel and rod), with z along the actuator from root to tip on both origins, both at the root pin, and the stroke as its limits @@ -63,7 +64,7 @@ Written against SolidCraft `main` after 0.11.1, which counts the degrees of free - **Each stop:** solve for where the limit is reached, and compare with the value the drive stopped at. Stops are found by bisection, so they land within about 0.01 degrees. - **Links:** b must equal r·a + o exactly, unless that is outside b's limits; then b sits at the limit and the mirror stops following. - **The whole motion:** `motion.play` at a few steps, or one `motion.export`, and compare the poses with the values you planned. -- **Look:** when the server is bridged, `screenshot` after `motion.play` shows the app window at that step. +- **Look:** when the server is bridged, `screenshot` after `motion.play` shows the app window at that step. `motion.export_animation {"study":..., "path":"tour.gif"}` (or `joint`, `from`, `to`) writes the whole motion as an animated GIF without changing the design. ## Save - Drive the joints back to the pose you planned to keep (`motion.play` at step 0, or `joint.drive`), then `save {path}`. diff --git a/skills/solidcraft-mechanisms/reference.md b/skills/solidcraft-mechanisms/reference.md index aee1fa9bf..1d59a920b 100644 --- a/skills/solidcraft-mechanisms/reference.md +++ b/skills/solidcraft-mechanisms/reference.md @@ -64,6 +64,7 @@ A slider's value grows as b moves along +z of its origin. Give its two origins t - `joint.rigid_group` joins every occurrence to the first one with a rigid as-built joint. - `joint.motion_link`: b = ratio·a + offset, clamped to b's limits. `ratio` is in b's units per a's: mm per degree when an angle drives a distance (a pinion of pitch radius r moves its rack r·π/180 mm per degree), degrees per mm the other way, and a plain factor between two angles or two distances. `offset` is in b's units: degrees for an angle, mm for a distance, or an expression such as `"10 deg"`. `joint.list` gives each link's `ratio` the same way and its `offset` with its `unit`. `ia`/`ib` pick a value of a multi-value joint (default 0). `joint.delete {"link": n}` removes link n (its index in `joint.list` `links`). - `joint.gear {a, b, ra, rb, internal?, reverse?}`, `joint.rack_pinion {a, b, radius, reverse?}` and `joint.screw {joint | a, b; pitch, reverse?}` make a motion link whose ratio comes from its sizes: gears -ra/rb (+ra/rb internal), a rack r mm per radian of its pinion (either joint may be `a`), a screw pitch per turn. Each size is mm, an expression, or `{occurrence, circle: [x,y,z]}`: the radius of the round face there, read again whenever the design changes. The reply gives `link` (its index) and `ratio` as `joint.list` does; `link: n` in the params replaces link n and keeps its offset. A new coupling's offset keeps b where it is. `joint.list` `links` carry the `coupling` and an `error` when it can't be worked out (a picked face gone: the last ratio stays). A value two links would set, or a coupling that would drive its own driver, is refused. +- `joint.cam {a, b, profile, follower?, radius?, tip?, flip?, link?}`: a is the cam's revolute joint, b a slider or revolute follower. `profile` is `{sketch, index?}` (a closed profile of a sketch in the cam's component) or `{edges: [[x,y,z]...], occurrence?}` (edges of the cam's body; one edge continues around its closed loop in the plane). The reply gives `link`, `lift: {min, max, rise, unit}` (b's travel over a turn), `reverse` (the side it rides from; `flip: true` takes the other) and, for a slider, `follower_offset`. `joint.list` `links` show `lift` instead of `ratio` for a cam. - `joint.drive`: `values` drives the values it lists, in order (`Spindle` above is cylindrical: 30 degrees, then 5 mm), and `value` the first; values left out keep theirs, or follow in a closed loop. Values are clamped to the limits. The reply gives `values` as `joint.list` does (`{name, value, unit, limits}`), and `moved`; when the joint can move nothing, a `reason`. - `joint.reach` (inverse kinematics): moves the joints on the occurrence's chain so its point `at` (world, where it is now; default: the centre of its bodies) gets to `point`, from the pose it is in to the nearest one, within limits, through motion links, and with closed loops kept closed. `z` with `axis` (world, now; default its own z) also turns that axis. `joints: [...]` moves only those (loop followers still follow). The reply: `reached`, `error_mm` (and `error_deg`), `point` where it ended, `values` of the joints that moved, `moved`, and when short, `stopped_by_limit: [{joint, value, limit}]` or `stopped_by_loop: {joint}`. A part that nothing moves answers `moved: false` with a `reason`. Contact sets are not checked; check with `contact.check` afterwards. - `motion.study {"study":..., ...}` edits a study; `keys` given replace all keys. @@ -127,6 +128,8 @@ The same pattern moved the solar wings of the SELENE rover (`Rover-v7.solidcraft | `joint.drive` answers `moved: false`, or `motion.play` lists the joint under `unmoved` | Read `reason`. Most often the chain is joined to nothing grounded: `unconnected` names the part, and `joint.list` lists the chain under `floating`, its occurrences with `dof: 6`. Ground it, join it, or `joint.rigid_group` it with the structure. | | A drive stops short, `stopped_by_loop` | A loop reached a limit or can't close further; `joint` names the joint that stopped it. Check the limits against your stroke numbers. | | A gear, rack or screw turns its partner the wrong way | The joints' axes point opposite ways (or the rack lies on the other side of the pinion). Run the command again with `reverse: true` and `link: n`. | +| `joint.cam` says the follower's line misses the cam | The slider's line (through `tip` when given) passes beside the cam at some angle. Pick the follower's tip, or move its slider's axis over the cam. | +| A cam's follower rides the wrong flank or sinks into the cam | It took the other side of the cam's axis (`reverse` in the reply): run `joint.cam` again with `flip: true` and `link: n`. | | `already follows a motion link` from `joint.gear` | A joint follows one link at most. Make the joint that already follows the driving one (`a`), as in a gear train G1 → G2 → G3. | | A linked joint stops following | Its value is clamped to its own limits. Hinge 2 in the example has `[[-60, 0]]`, so a drive of Hinge below 0 leaves it at 0. Give a mirrored joint the mirrored limits. | | `joint.reach` answers `reached: false` | The point is out of reach: `point` and `error_mm` give the nearest pose. `stopped_by_limit` names the limits it rests on, `stopped_by_loop` the loop that can't follow further; with neither, the chain can't get there at all (too far, or out of its plane). | @@ -151,4 +154,6 @@ The same pattern moved the solar wings of the SELENE rover (`Rover-v7.solidcraft ## Showing it moving -Bridged to the app, `motion.play {"study":..., "step":s}` moves the user's viewport, and `screenshot` captures the window at each step. To record outside MCP, drive the app's control channel (`docs/control-protocol.md`): `engine.execute` with `motion.play`, then `ui.screenshot` with a `path`, once per frame. +`motion.export_animation {"study":..., "path":"tour.gif"}` draws the whole motion as an animated GIF in one call, headless or bridged, and changes nothing: `{"joint":..., "from":0, "to":90, "path":...}` animates a drive instead. A path that does not end in `.gif` is a folder for PNG frames (`frame-0001.png`, ...). Pass `camera` (the reply of `ui.camera`, or any of its fields), `width`/`height` (default 800 x 500), `samples` (frames; default the study's steps + 1, or 100), `fps` (default 20), and `grid: false` / `axes: false` for a clean background. The reply is small: `frames`, `bytes`, and `stopped_at` with `stopped_by_loop`/`stopped_by_contact` where the motion first stopped short. + +Bridged to the app, `motion.play {"study":..., "step":s}` moves the user's viewport, and `screenshot` captures the window at that step. diff --git a/skills/solidcraft-modeling/reference.md b/skills/solidcraft-modeling/reference.md index 7cab578e0..27624cdfe 100644 --- a/skills/solidcraft-modeling/reference.md +++ b/skills/solidcraft-modeling/reference.md @@ -75,7 +75,7 @@ Distances are unsigned. Draw the geometry on the correct side first, and the dim | `sketch.slot.overall` / `sketch.slot.center_to_center` | `p0`, `p1` (overall ends / arc centres), `width` | Ids and dof are in the "Ids" section above. | | `solid.fillet` / `solid.chamfer` | `edges:[[x,y,z]]`, `radius` / `distance` | The pick snaps to the **nearest** edge, with no distance limit and no error, so check that the face count changed. One pick takes the whole tangent chain: a rounded rim needs 1 point, not 8. | | `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 (see Order in `SKILL.md`). | -| `solid.hole` | `position:[x,y,z]` on a face + `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. | +| `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. | | `solid.pattern.rectangular` | `features`, `dir1`, `count1`, `spacing1` (+ `dir2`, `count2`, `spacing2`) | Spacing takes expressions and follows parameters. | | `solid.pattern.circular` | `features`, `axis` (`"Z"` or `{origin, dir}`), `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]`, `plane` (`XY`/`XZ`/`YZ`, a construction plane, or `{origin, normal}` whose origin may use length expressions) | Follows parameters. Mirror and pattern features cannot be mirrored or patterned again. | diff --git a/tests/action_matrix/baseline.json b/tests/action_matrix/baseline.json index 312a39241..96bda7320 100644 --- a/tests/action_matrix/baseline.json +++ b/tests/action_matrix/baseline.json @@ -4805,32 +4805,32 @@ "design": "load" }, "oracle/22-split-body": { - "Cyl (1)/F2:bottom": "!face.extrude face.hole !face.offset_plane !face.press_pull face.shell !face.sketch", - "Cyl (1)/F2:bottom|F2:side:c1": "edge.chamfer edge.fillet edge.normal_plane edge.project", - "Cyl (1)/F2:bottom|F4:face:2": "edge.chamfer edge.fillet edge.normal_plane edge.project", - "Cyl (1)/F2:side:c1": "curved.axis curved.tangent_plane", - "Cyl (1)/F2:side:c1|F4:face:3": "edge.chamfer edge.fillet edge.normal_plane edge.project", - "Cyl (1)/F4:face:2": "curved.axis curved.tangent_plane", - "Cyl (1)/F4:face:2|F4:face:3": "edge.chamfer edge.fillet edge.normal_plane edge.project", - "Cyl (1)/F4:face:3": "!face.extrude face.hole !face.offset_plane !face.press_pull face.shell !face.sketch", + "Cyl (1)/F2:bottom": "face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", + "Cyl (1)/F2:bottom|F2:side:c1#1": "edge.chamfer edge.fillet edge.normal_plane edge.project", + "Cyl (1)/F2:bottom|F2:side:c1#2": "edge.chamfer edge.fillet edge.normal_plane edge.project", + "Cyl (1)/F2:side:c1#1": "curved.axis curved.tangent_plane", + "Cyl (1)/F2:side:c1#1|F4:section": "edge.chamfer edge.fillet edge.normal_plane edge.project", + "Cyl (1)/F2:side:c1#2": "curved.axis curved.tangent_plane", + "Cyl (1)/F2:side:c1#2|F4:section": "edge.chamfer edge.fillet edge.normal_plane edge.project", + "Cyl (1)/F4:section": "!face.extrude face.hole face.offset_plane !face.press_pull face.shell face.sketch", "Cyl (1)/body": "body.copy body.mirror body.move body.pattern", - "Cyl (1)/v[F2:bottom & F2:side:c1 & F4:face:2]": "vertex.point", - "Cyl (1)/v[F2:bottom & F2:side:c1 & F4:face:2] (2)": "vertex.point", - "Cyl (1)/v[F2:side:c1 & F4:face:2 & F4:face:3]": "vertex.point", - "Cyl (1)/v[F2:side:c1 & F4:face:2 & F4:face:3] (2)": "vertex.point", + "Cyl (1)/v[F2:bottom & F2:side:c1#1 & F2:side:c1#2]": "vertex.point", + "Cyl (1)/v[F2:bottom & F2:side:c1#1 & F2:side:c1#2] (2)": "vertex.point", + "Cyl (1)/v[F2:side:c1#1 & F2:side:c1#2 & F4:section]": "vertex.point", + "Cyl (1)/v[F2:side:c1#1 & F2:side:c1#2 & F4:section] (2)": "vertex.point", "Cyl/F2:side:c1#1": "curved.axis curved.tangent_plane", "Cyl/F2:side:c1#1|F2:top": "edge.chamfer edge.fillet edge.normal_plane edge.project", - "Cyl/F2:side:c1#1|F4:face:3": "edge.chamfer edge.fillet edge.normal_plane edge.project", + "Cyl/F2:side:c1#1|F4:section": "edge.chamfer edge.fillet edge.normal_plane edge.project", "Cyl/F2:side:c1#2": "curved.axis curved.tangent_plane", "Cyl/F2:side:c1#2|F2:top": "edge.chamfer edge.fillet edge.normal_plane edge.project", - "Cyl/F2:side:c1#2|F4:face:3": "edge.chamfer edge.fillet edge.normal_plane edge.project", - "Cyl/F2:top": "!face.extrude face.hole !face.offset_plane !face.press_pull face.shell !face.sketch", - "Cyl/F4:face:3": "!face.extrude face.hole !face.offset_plane !face.press_pull face.shell !face.sketch", + "Cyl/F2:side:c1#2|F4:section": "edge.chamfer edge.fillet edge.normal_plane edge.project", + "Cyl/F2:top": "face.extrude face.hole face.offset_plane face.press_pull face.shell face.sketch", + "Cyl/F4:section": "!face.extrude face.hole face.offset_plane !face.press_pull face.shell face.sketch", "Cyl/body": "body.copy body.mirror body.move body.pattern", "Cyl/v[F2:side:c1#1 & F2:side:c1#2 & F2:top]": "vertex.point", "Cyl/v[F2:side:c1#1 & F2:side:c1#2 & F2:top] (2)": "vertex.point", - "Cyl/v[F2:side:c1#1 & F2:side:c1#2 & F4:face:3]": "vertex.point", - "Cyl/v[F2:side:c1#1 & F2:side:c1#2 & F4:face:3] (2)": "vertex.point", + "Cyl/v[F2:side:c1#1 & F2:side:c1#2 & F4:section]": "vertex.point", + "Cyl/v[F2:side:c1#1 & F2:side:c1#2 & F4:section] (2)": "vertex.point", "design": "load" }, "oracle/23-bracket-multifeature": { diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json index 0d0b7e1bf..abe78e514 100644 --- a/tests/robustness/goldens.json +++ b/tests/robustness/goldens.json @@ -10,28 +10,28 @@ "6": {"area":11580.298484,"bodies":1,"edges":28,"error":"offset: a corner whose faces don't meet the same way after t","faces":13,"outcome":"failed","rejected":0,"shells":1,"steps":["box","hole","join box","join cylinder","cut cylinder","shell"],"unsupported":1,"volume":69137.260899}, "7": {"area":7462.861065,"bodies":3,"edges":72,"error":null,"faces":32,"outcome":"ok","rejected":0,"shells":3,"steps":["extruded profile","join box","cut cylinder","join box","circular pattern","hole"],"unsupported":0,"volume":32823.69121}, "8": {"area":2865.472237,"bodies":1,"edges":24,"error":null,"faces":10,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut cylinder"],"unsupported":0,"volume":10024.247951}, - "9": {"area":2434.461263,"bodies":1,"edges":38,"error":"lumps: shell boundaries intersect or touch; cavity ownership","faces":17,"outcome":"failed","rejected":0,"shells":2,"steps":["revolved section","chamfer","fillet","join box","cut sphere","rectangular pattern","rectangular pattern","cut box"],"unsupported":4,"volume":6547.123554}, - "10": {"area":2786.620097,"bodies":1,"edges":44,"error":null,"faces":18,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","cut box","chamfer","hole"],"unsupported":0,"volume":6668.9804}, + "9": {"area":2302.184081,"bodies":2,"edges":38,"error":null,"faces":17,"outcome":"ok","rejected":1,"shells":2,"steps":["revolved section","chamfer","fillet","join box","cut sphere","rectangular pattern","rectangular pattern","cut box"],"unsupported":3,"volume":6417.156832}, + "10": {"area":2809.248846,"bodies":1,"edges":39,"error":null,"faces":16,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","cut box","fillet","hole"],"unsupported":0,"volume":6696.329905}, "11": {"area":7858.300481,"bodies":1,"edges":33,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","hole","rectangular pattern","fillet"],"unsupported":0,"volume":34605.048259}, "12": {"area":4668.664174,"bodies":2,"edges":59,"error":null,"faces":25,"outcome":"ok","rejected":0,"shells":2,"steps":["extruded profile","chamfer","join cylinder","join box","cut cylinder","circular pattern"],"unsupported":3,"volume":11874.471611}, - "13": {"area":1967.991667,"bodies":3,"edges":85,"error":null,"faces":37,"outcome":"ok","rejected":1,"shells":3,"steps":["revolved section","cut cylinder","join box","rectangular pattern","cut cylinder","cut box","fillet","hole"],"unsupported":0,"volume":2647.948638}, + "13": {"area":2101.521015,"bodies":1,"edges":103,"error":null,"faces":41,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","cut cylinder","join box","rectangular pattern","cut cylinder","cut box","fillet","hole"],"unsupported":0,"volume":2396.939548}, "14": {"area":10553.267409,"bodies":1,"edges":43,"error":null,"faces":20,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","fillet"],"unsupported":0,"volume":10369.008764}, - "15": {"area":1957.859861,"bodies":1,"edges":49,"error":null,"faces":21,"outcome":"ok","rejected":1,"shells":2,"steps":["revolved section","fillet","cut box","rectangular pattern","cut sphere","cut cylinder","cut sphere"],"unsupported":0,"volume":4723.415743}, + "15": {"area":2312.730168,"bodies":1,"edges":39,"error":null,"faces":15,"outcome":"ok","rejected":2,"shells":1,"steps":["revolved section","cut box","rectangular pattern","cut sphere","cut cylinder","cut sphere","join cylinder"],"unsupported":0,"volume":5728.661237}, "16": {"area":8872.873884,"bodies":3,"edges":49,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":3,"steps":["box","join cylinder","circular pattern","hole"],"unsupported":0,"volume":44953.403148}, - "17": {"area":6048.425782,"bodies":1,"edges":48,"error":null,"faces":19,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut box","shell","cut cylinder"],"unsupported":0,"volume":2968.53154}, + "17": {"area":6022.921702,"bodies":1,"edges":48,"error":null,"faces":19,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut box","shell","cut cylinder"],"unsupported":0,"volume":2981.269959}, "18": {"area":5524.583817,"bodies":4,"edges":98,"error":"boolean Cut: the operation failed: no result","faces":44,"outcome":"failed","rejected":0,"shells":4,"steps":["extruded profile","join cylinder","circular pattern","cut cylinder","hole","cut cylinder","hole","circular pattern"],"unsupported":0,"volume":21568.016672}, - "19": {"area":5939.094997,"bodies":1,"edges":68,"error":null,"faces":23,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","cut sphere","shell"],"unsupported":0,"volume":2943.015294}, + "19": {"area":3440.869757,"bodies":1,"edges":42,"error":null,"faces":16,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","chamfer","cut sphere"],"unsupported":0,"volume":5909.174021}, "20": {"area":5727.101189,"bodies":1,"edges":116,"error":null,"faces":45,"outcome":"ok","rejected":1,"shells":1,"steps":["extruded profile","fillet","cut box","cut cylinder","hole","circular pattern","cut box"],"unsupported":0,"volume":17142.727051}, - "21": {"area":5857.763125,"bodies":2,"edges":51,"error":null,"faces":22,"outcome":"ok","rejected":0,"shells":2,"steps":["revolved section","join box","hole","fillet","fillet","hole"],"unsupported":0,"volume":18878.613005}, - "22": {"area":4634.476813,"bodies":2,"edges":108,"error":null,"faces":40,"outcome":"ok","rejected":0,"shells":2,"steps":["revolved section","join box","join box","join box","rectangular pattern","cut cylinder"],"unsupported":0,"volume":7855.560098}, + "21": {"area":5814.791707,"bodies":1,"edges":56,"error":null,"faces":22,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","join box","hole","fillet","hole","cut box"],"unsupported":1,"volume":19153.734422}, + "22": {"area":4634.449436,"bodies":2,"edges":138,"error":null,"faces":54,"outcome":"ok","rejected":0,"shells":2,"steps":["revolved section","join box","join box","join box","rectangular pattern","cut cylinder"],"unsupported":0,"volume":7855.479914}, "23": {"area":1795.696192,"bodies":1,"edges":16,"error":null,"faces":7,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut sphere"],"unsupported":0,"volume":3198.694598}, - "24": {"area":13432.401041,"bodies":1,"edges":86,"error":null,"faces":35,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","chamfer","hole","cut box","cut sphere","cut sphere","shell"],"unsupported":0,"volume":9985.17442}, - "25": {"area":6134.243434,"bodies":1,"edges":48,"error":null,"faces":19,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","shell"],"unsupported":0,"volume":5828.585617}, - "26": {"area":6805.258418,"bodies":2,"edges":48,"error":null,"faces":20,"outcome":"ok","rejected":0,"shells":2,"steps":["revolved section","join box","cut cylinder","rectangular pattern","cut sphere"],"unsupported":0,"volume":21188.329272}, + "24": {"area":8910.288004,"bodies":1,"edges":64,"error":null,"faces":20,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","chamfer","hole","cut box","cut sphere","cut sphere","hole"],"unsupported":1,"volume":32456.126515}, + "25": {"area":7142.717684,"bodies":1,"edges":48,"error":null,"faces":19,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","shell"],"unsupported":0,"volume":7012.754625}, + "26": {"area":6461.702601,"bodies":1,"edges":56,"error":null,"faces":22,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","join box","cut cylinder","rectangular pattern","cut sphere"],"unsupported":0,"volume":21188.159601}, "27": {"area":11263.08174,"bodies":3,"edges":99,"error":null,"faces":42,"outcome":"ok","rejected":0,"shells":4,"steps":["box","chamfer","cut sphere","cut sphere","join box","circular pattern","hole","join box"],"unsupported":0,"volume":49451.079636}, "28": {"area":2394.691384,"bodies":1,"edges":15,"error":null,"faces":9,"outcome":"ok","rejected":0,"shells":2,"steps":["revolved section","join cylinder"],"unsupported":0,"volume":5902.121375}, "29": {"area":6965.599057,"bodies":1,"edges":74,"error":null,"faces":30,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","shell","join cylinder"],"unsupported":0,"volume":3977.885339}, - "30": {"area":853.525389,"bodies":1,"edges":23,"error":null,"faces":10,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","chamfer"],"unsupported":0,"volume":1337.14821}, + "30": {"area":850.154862,"bodies":1,"edges":21,"error":null,"faces":9,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","chamfer"],"unsupported":0,"volume":1327.098159}, "31": {"area":10221.945046,"bodies":3,"edges":68,"error":null,"faces":29,"outcome":"ok","rejected":2,"shells":3,"steps":["box","cut box","fillet","join box","circular pattern","cut box","circular pattern","hole"],"unsupported":0,"volume":56397.581359}, "32": {"area":3220.802769,"bodies":1,"edges":51,"error":null,"faces":19,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut sphere","cut box","cut box","join box"],"unsupported":0,"volume":7565.955897}, "33": {"area":5286.736353,"bodies":2,"edges":59,"error":null,"faces":27,"outcome":"ok","rejected":0,"shells":3,"steps":["revolved section","fillet","join box","cut cylinder","chamfer","join box","chamfer","fillet"],"unsupported":2,"volume":13858.467983}, @@ -46,7 +46,7 @@ "42": {"area":5486.877622,"bodies":1,"edges":51,"error":null,"faces":20,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut box","cut cylinder","rectangular pattern"],"unsupported":0,"volume":19095.106157}, "43": {"area":3492.988343,"bodies":1,"edges":72,"error":null,"faces":26,"outcome":"ok","rejected":2,"shells":1,"steps":["extruded profile","cut cylinder","rectangular pattern","fillet","hole","rectangular pattern","join cylinder"],"unsupported":1,"volume":7528.548742}, "44": {"area":7972.435566,"bodies":1,"edges":36,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","shell","cut sphere"],"unsupported":0,"volume":7622.184366}, - "45": {"area":14416.876392,"bodies":2,"edges":60,"error":"boolean Union: implausible result volume ","faces":29,"outcome":"failed","rejected":0,"shells":3,"steps":["revolved section","join cylinder","fillet","shell","cut box","join box"],"unsupported":1,"volume":14286.791174}, + "45": {"area":14203.038747,"bodies":2,"edges":60,"error":"boolean Union: implausible result volume ","faces":29,"outcome":"failed","rejected":0,"shells":3,"steps":["revolved section","join cylinder","fillet","shell","cut box","join box"],"unsupported":1,"volume":14081.345577}, "46": {"area":3445.162934,"bodies":1,"edges":99,"error":null,"faces":31,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","join cylinder","hole","cut cylinder","rectangular pattern","cut box","cut cylinder"],"unsupported":0,"volume":6232.317935}, "47": {"area":3098.575625,"bodies":1,"edges":42,"error":null,"faces":16,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","fillet","cut sphere","fillet"],"unsupported":0,"volume":8834.297438}, "48": {"area":9651.031297,"bodies":1,"edges":66,"error":null,"faces":28,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","hole","circular pattern","join box","shell","cut box"],"unsupported":2,"volume":7044.773463}, @@ -64,7 +64,7 @@ "60": {"area":3443.328607,"bodies":1,"edges":39,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut sphere"],"unsupported":0,"volume":11779.204543}, "61": {"area":5020.413153,"bodies":1,"edges":36,"error":"boolean Cut: the operation failed: no result","faces":15,"outcome":"failed","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","shell","rectangular pattern"],"unsupported":0,"volume":4906.628538}, "62": {"area":8771.003732,"bodies":1,"edges":60,"error":null,"faces":23,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut cylinder","circular pattern","cut box","cut box","join cylinder"],"unsupported":2,"volume":40107.001728}, - "63": {"area":3198.797259,"bodies":1,"edges":84,"error":null,"faces":30,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","join box","cut cylinder","hole","cut cylinder","join box","fillet"],"unsupported":0,"volume":7075.892751}, + "63": {"area":4316.842909,"bodies":1,"edges":100,"error":null,"faces":38,"outcome":"ok","rejected":0,"shells":3,"steps":["revolved section","join box","cut cylinder","hole","cut cylinder","join box","rectangular pattern"],"unsupported":3,"volume":8229.233195}, "64": {"area":4088.335645,"bodies":1,"edges":36,"error":null,"faces":14,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","fillet","join cylinder"],"unsupported":0,"volume":8495.220295}, "65": {"area":8436.255548,"bodies":1,"edges":37,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut cylinder","fillet","rectangular pattern","circular pattern","circular pattern","fillet","cut box"],"unsupported":0,"volume":45143.475817}, "66": {"area":9222.76638,"bodies":1,"edges":99,"error":null,"faces":37,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","join box","join box","join box","cut sphere","cut box"],"unsupported":1,"volume":35217.203139}, @@ -76,10 +76,10 @@ "72": {"area":5770.270336,"bodies":2,"edges":44,"error":null,"faces":20,"outcome":"ok","rejected":1,"shells":2,"steps":["box","join cylinder","hole","join box","join box","cut box","cut cylinder","cut cylinder"],"unsupported":0,"volume":16081.801492}, "73": {"area":6868.162117,"bodies":1,"edges":40,"error":"offset: a corner whose faces don't meet the same way after t","faces":18,"outcome":"failed","rejected":0,"shells":1,"steps":["extruded profile","join box","shell"],"unsupported":1,"volume":36461.939381}, "74": {"area":9294.57311,"bodies":1,"edges":18,"error":null,"faces":9,"outcome":"ok","rejected":0,"shells":1,"steps":["box","hole"],"unsupported":0,"volume":55866.183074}, - "75": {"area":7893.117931,"bodies":1,"edges":27,"error":null,"faces":11,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut cylinder","chamfer","rectangular pattern","rectangular pattern","cut box"],"unsupported":0,"volume":38757.62083}, - "76": {"area":899.010133,"bodies":1,"edges":29,"error":null,"faces":13,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","fillet","cut cylinder"],"unsupported":0,"volume":1745.3677}, - "77": {"area":12157.059928,"bodies":1,"edges":126,"error":null,"faces":54,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","hole","circular pattern","rectangular pattern","circular pattern","join cylinder"],"unsupported":0,"volume":64306.616746}, - "78": {"area":2510.733756,"bodies":1,"edges":36,"error":"offset: a corner whose faces don't meet the same way after t","faces":14,"outcome":"failed","rejected":0,"shells":1,"steps":["revolved section","cut cylinder","cut box","shell"],"unsupported":0,"volume":3707.416641}, + "75": {"area":7890.438301,"bodies":1,"edges":31,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut cylinder","chamfer","rectangular pattern","rectangular pattern","cut box"],"unsupported":0,"volume":38753.33959}, + "76": {"area":853.668183,"bodies":1,"edges":32,"error":null,"faces":14,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","chamfer","cut cylinder"],"unsupported":1,"volume":1680.708844}, + "77": {"area":10824.299347,"bodies":1,"edges":60,"error":null,"faces":26,"outcome":"ok","rejected":3,"shells":1,"steps":["revolved section","fillet","cut cylinder","rectangular pattern","cut box","cut cylinder"],"unsupported":1,"volume":57744.413197}, + "78": {"area":2423.235496,"bodies":1,"edges":34,"error":"offset: a corner whose faces don't meet the same way after t","faces":14,"outcome":"failed","rejected":0,"shells":1,"steps":["revolved section","cut cylinder","cut box","shell"],"unsupported":0,"volume":3707.429306}, "79": {"area":13585.252616,"bodies":1,"edges":27,"error":null,"faces":12,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut cylinder","join cylinder"],"unsupported":0,"volume":104810.763072}, "80": {"area":8652.533342,"bodies":1,"edges":20,"error":null,"faces":9,"outcome":"ok","rejected":0,"shells":1,"steps":["box","fillet","fillet"],"unsupported":0,"volume":37387.449469}, "81": {"area":4001.847983,"bodies":2,"edges":75,"error":null,"faces":29,"outcome":"ok","rejected":1,"shells":2,"steps":["revolved section","cut sphere","circular pattern","rectangular pattern","hole","join cylinder","join box","cut sphere"],"unsupported":2,"volume":13139.658749}, @@ -91,11 +91,11 @@ "87": {"area":4853.708989,"bodies":1,"edges":24,"error":null,"faces":10,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut box","rectangular pattern"],"unsupported":0,"volume":18568.611108}, "88": {"area":3947.799648,"bodies":1,"edges":18,"error":null,"faces":8,"outcome":"ok","rejected":0,"shells":1,"steps":["box","hole"],"unsupported":0,"volume":12788.04706}, "89": {"area":2512.5,"bodies":1,"edges":12,"error":null,"faces":6,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut box"],"unsupported":0,"volume":5906.25}, - "90": {"area":9703.747183,"bodies":1,"edges":30,"error":null,"faces":12,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","hole"],"unsupported":0,"volume":46947.022876}, - "91": {"area":3989.788869,"bodies":1,"edges":46,"error":null,"faces":18,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","cut cylinder","fillet"],"unsupported":0,"volume":9777.743569}, + "90": {"area":9676.011803,"bodies":1,"edges":30,"error":null,"faces":12,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","hole"],"unsupported":0,"volume":46965.837216}, + "91": {"area":3958.046518,"bodies":1,"edges":50,"error":null,"faces":20,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","cut cylinder","fillet"],"unsupported":0,"volume":9721.244548}, "92": {"area":2855.139217,"bodies":1,"edges":30,"error":null,"faces":12,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","chamfer","cut sphere"],"unsupported":0,"volume":9814.30292}, "93": {"area":7266.404017,"bodies":7,"edges":111,"error":null,"faces":51,"outcome":"ok","rejected":0,"shells":7,"steps":["extruded profile","fillet","chamfer","join box","circular pattern","rectangular pattern","cut cylinder"],"unsupported":0,"volume":12734.393171}, - "94": {"area":3505.055926,"bodies":1,"edges":73,"error":null,"faces":27,"outcome":"ok","rejected":1,"shells":1,"steps":["revolved section","cut cylinder","hole","rectangular pattern","cut box","cut box","join box"],"unsupported":1,"volume":5900.505082}, + "94": {"area":3480.70333,"bodies":1,"edges":61,"error":null,"faces":26,"outcome":"ok","rejected":1,"shells":2,"steps":["revolved section","cut cylinder","fillet","hole","rectangular pattern","cut box","cut box"],"unsupported":0,"volume":5456.446856}, "95": {"area":2425.131626,"bodies":1,"edges":19,"error":"boolean Cut: the operation failed: no result; the operation ","faces":9,"outcome":"failed","rejected":0,"shells":1,"steps":["revolved section","hole","fillet","cut cylinder","cut sphere"],"unsupported":0,"volume":7106.301922} }, "notes": [ @@ -127,6 +127,8 @@ {"reason":"#1490: when the last-resort nudge fails both ways, two more screw axes are tried; seed 63's final box join (its face 0.00005 mm off the half-ring's cut face) now builds instead of being refused with an implausible volume, and the design goes on to its fillet","seeds":[63]}, {"reason":"a prism cut in a column round the tool (prism_local): seed 65's rectangular pattern (step 4, a second half-cylinder groove overlapping the first, in a block with a rounded vertical edge) is now built by the exact 2D route in a column clear of the round, where the B-rep tries left it with split edges. The step's part has the 10 faces, 24 edges and 16 vertices it should (28 edges and 18 vertices before), and its volume is 45145.383 mm³ against 45145.214 (exactly 45145.103, both within the mesh measure); the generator then picks other edges for its step 7 fillet, so the run ends on another design (45143.48 mm³, 15 faces)","seeds":[65]}, {"reason":"Seed 31: #1581 no longer maps a pick on an earlier round's seam to some other nearby edge; the second fillet's selection includes the smooth seam at [2, 27.5, 13.5] beside the first round, which is now refused (no corner to round) instead of silently re-rounding a different edge at 1 mm, so the run goes on to a hole. Seed 83: #1316 was recorded before its branch took in #1495; with #1495's shell (an open face next to a concave edge no longer cuts the wall past it) the shelled part keeps more wall (6217 to 6339 mm3), its edges differ, and the 2.5 mm fillet of the first run is not picked; a later fillet is refused as not supported yet (an end face parallel to the edge)","seeds":[31,83]}, -{"reason":"the 2D route sews a cut whose outline has a point a hair from a segment's end (text-recut): seed 53's shell (step 3, a 2 mm shell of an extruded L with an arc side, opened at the notch's inner face) builds its cavity by the 2D route in 77 ms, where it took the B-rep path (2.4 s) and gave a part 336 mm³ lighter, which a box can't then be intersected with (no result). Its section at mid height is 338.27 mm² (a distance-rule raster of the profile gives 343.7, rounding the cavity's concave corners); the generator then builds the step 4 fillet it refused before, so the run goes on another way (16954.55 mm³, 48 faces)","seeds":[53]} +{"reason":"the 2D route sews a cut whose outline has a point a hair from a segment's end (text-recut): seed 53's shell (step 3, a 2 mm shell of an extruded L with an arc side, opened at the notch's inner face) builds its cavity by the 2D route in 77 ms, where it took the B-rep path (2.4 s) and gave a part 336 mm³ lighter, which a box can't then be intersected with (no result). Its section at mid height is 338.27 mm² (a distance-rule raster of the profile gives 343.7, rounding the cavity's concave corners); the generator then builds the step 4 fillet it refused before, so the run goes on another way (16954.55 mm³, 48 faces)","seeds":[53]}, + {"reason":"#726 (#1687): a full revolve of a profile off the axis comes out with its planar faces whole, so the revolved section has fewer faces and edges. The fuzz generator picks edges and faces by index, so from their second step these seeds build different designs. Replaying each new design's commands on main and on this branch: seeds 45, 77 and 94 end the same; in seed 21 a box joined onto the ring's flat top now fuses with it, where main kept two touching shells that a later hole split into two bodies.","seeds":[21,45,77,94]}, + {"reason":"#726 (#1718): a partial revolve made as a new body comes out with its planar faces whole, so the revolved section has fewer faces and edges. The fuzz generator picks edges and faces by index, so from their second step these seeds build different designs (seed 24's shell now picks the centroid of a whole 270 deg annulus, which lies in the bore, so it is refused and the run goes on). Replaying each new design's commands on main and on this branch: 12 seeds end the same; in seeds 13 and 26 a box joined onto a flat revolved face now fuses with it (main kept two touching shells that a later step split into two bodies), seed 15's last cylinder join, which main refuses, now builds, and seed 78's cut box no longer leaves 87.5 mm² of extra area (the end cap's); seed 63 refuses the same fillet on both and ends with nearly the same body. Seed 9 now ends ok instead of failing, but its new design ends the same on main. No seed gains a failure.","seeds":[9,10,13,15,17,19,22,24,25,26,30,63,75,76,78,90,91]} ] } diff --git a/vendor/README.md b/vendor/README.md index 3d4a592f1..d3c24a17a 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -149,6 +149,20 @@ Changes: compares the two. - `lib.rs`: compiler warnings no longer fail the build. Example, test and bench targets are dropped (their sources are not vendored). +- `tessellation/triangulation.rs`: adaptive division also splits a cell that bows off its + corners' plane by more than the chord tolerance (a quarter of its twist `p00 - p01 - p10 + + p11`, across that plane, at the middle). A bilinear patch equals the blend of its corners the + division compared against, so a twisted ruled face (a loft between polylines) went out as two + triangles per face (#1666); a flat cell such as a cone's trapezoid between rulings is not split. +- `tessellation/triangulation.rs`: a shell's face meshes share their edges' points exactly. A + face's mesh puts each point at its parameters on the face's own surface, so a point of an edge + that lies off a surface within tolerance (an intersection-curve sample whose projection did not + converge, an imported edge) came out in a different place on each of the edge's faces, and the + exported mesh had a crack there. In display and export meshes (`Deflection::rulings`), a + vertex at a point of a face's boundary loops that is farther than `TOLERANCE` from the nearest + point of the face's edges now goes to that point, when it is within the chord tolerance + (`onto_edges`). Points within `TOLERANCE` stay on the surface, so exact geometry meshes as + before. The meshes Boolean operations intersect keep truck's points. ## matext4cgmath 0.1.0 (Apache-2.0, © RICOS Co. Ltd., https://github.com/ricosjp/matext4cgmath) diff --git a/vendor/truck-meshalgo/src/tessellation/triangulation.rs b/vendor/truck-meshalgo/src/tessellation/triangulation.rs index b1b9b5a60..9ab3306fa 100644 --- a/vendor/truck-meshalgo/src/tessellation/triangulation.rs +++ b/vendor/truck-meshalgo/src/tessellation/triangulation.rs @@ -389,7 +389,14 @@ fn shell_create_polygon( .collect::>>(); let polygon: Option = (|| { let boundary = PolyBoundary::new(preboundary?, &surface, tol); - Some(trimming_tessellation(surface, &boundary, tol, cap)) + let mut mesh = trimming_tessellation(surface, &boundary, tol, cap); + // Display and export meshes only, as the ruling grid lines: the meshes Boolean + // operations intersect keep truck's points. + if tol.rulings { + let points: Vec = wires.iter().flat_map(Wire::edge_iter).flat_map(|e| e.curve().0).collect(); + onto_edges(&mut mesh, &boundary, &points, tol.chord); + } + Some(mesh) })(); // SolidCraft: faces with seam edges (a loop running along an edge both ways, as STEP // writes cylinders) are valid here; `debug_new` asserts simple loops in debug builds. @@ -400,6 +407,42 @@ fn shell_create_polygon( new_face } +/// SolidCraft: a face's mesh puts every point where its own surface passes the point's +/// parameters, and a boundary point's parameters are those its edge point projects to. An edge +/// that lies on a surface only within tolerance (a sample of an intersection curve whose +/// projection did not converge, an imported edge) then puts the point it shares with the next +/// face in a different place on each face, and the shell's mesh cracks there. Each vertex at a +/// point of the boundary loops (the same parameters, as the triangulation got them) that is +/// farther than `TOLERANCE` from the nearest point of the face's edges goes to that point, when +/// it is within `tol`, so the faces of an edge have the very same points along it. Within +/// `TOLERANCE` the points are already the same, and a face keeps them on its surface: grid +/// points can lie on a boundary between its points (the ruling lines of a plane), and moving +/// only the boundary points would bend the boundary there. +fn onto_edges(mesh: &mut PolygonMesh, boundary: &PolyBoundary, points: &[Point3], tol: f64) { + let key = |x: f64, y: f64| [spade_round(x).to_bits(), spade_round(y).to_bits()]; + let loops: rustc_hash::FxHashSet<[u64; 2]> = boundary.0.iter().flatten().map(|p| key(p.x, p.y)).collect(); + let on_loops: Vec = mesh.uv_coords().iter().map(|uv| loops.contains(&key(uv.x, uv.y))).collect(); + let cell = |p: Point3| [p.x, p.y, p.z].map(|x| (x / tol).floor() as i64); + let mut grid: HashMap<[i64; 3], Vec> = HashMap::default(); + points.iter().for_each(|p| grid.entry(cell(*p)).or_default().push(*p)); + for (p, _) in mesh.positions_mut().iter_mut().zip(on_loops).filter(|(_, on)| *on) { + let c = cell(*p); + let mut best = (tol * tol, None); + for d in (0..27).map(|k| [k % 3 - 1, k / 3 % 3 - 1, k / 9 - 1]) { + let near = [c[0].saturating_add(d[0]), c[1].saturating_add(d[1]), c[2].saturating_add(d[2])]; + for q in grid.get(&near).into_iter().flatten() { + let d2 = q.distance2(*p); + if d2 <= best.0 { + best = (d2, Some(*q)); + } + } + } + if let Some(q) = best.1.filter(|_| best.0 > TOLERANCE2) { + *p = q; + } + } +} + #[derive(Debug, Default, Clone)] struct PolyBoundaryPiece(Vec); @@ -971,7 +1014,14 @@ fn bounded_surface_division(surface: &S, (ur, vr): ((f64, let pt10 = surface.subs(u[1], v[0]).to_vec(); let pt11 = surface.subs(u[1], v[1]).to_vec(); let pt = Point3::from_vec(pt00 * (1.0 - p) * (1.0 - q) + pt01 * (1.0 - p) * q + pt10 * p * (1.0 - q) + pt11 * p * q); - let far = p0.distance2(pt) > tol * tol; + // SolidCraft (#1666): a cell is drawn as two triangles, not as the bilinear blend + // of its corners. A twisted cell (a bilinear patch is the blend exactly, so `pt` + // never tells) bows off its corners' plane by a quarter of its twist at the middle, + // across that plane: a cone's trapezoid between two rulings is flat and needs none. + let normal = (pt10 - pt00).cross(pt01 - pt00); + let bow = (pt00 - pt01 - pt10 + pt11).dot(normal) * 0.25; + let twisted = normal.magnitude2() > 0.0 && bow * bow > tol * tol * normal.magnitude2(); + let far = p0.distance2(pt) > tol * tol || twisted; // Which direction bends: refine only that one (a cylinder needs no division // along its rulings). let (su, sv) = ([surface.subs(u[0], v0), surface.subs(u[1], v0)], [surface.subs(u0, v[0]), surface.subs(u0, v[1])]);