SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Render: fit the product inside the picture's frame, after the saved setup loads (#5763) (#5764)
Kevin Ravensberg295bd0e1659f
diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rsindex 71b6699362..de8a6f6973 100644--- a/crates/engine/src/cmd/render.rs+++ b/crates/engine/src/cmd/render.rs@@ -74,7 +74,7 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("render.camera.get", "Inspect Render Camera", get_camera).icon("camera").noundo().params("No parameters. Returns the explicitly defined current view camera, or null if the session has no camera override. No camera is fitted, no job is started and no saved setup or engineering document is changed."),CommandSpec::new("render.camera.fit", "Frame Render Subject", fit_camera).icon("camera").noundo()- .params("No parameters. Fits the current camera to the visible product bounds through the shared Camera::fit contract; changes only view state, not a saved setup, rendering job, stage or engineering geometry."),+ .params("aspect?: the picture's width over its height, 0.000001 to 1000000 (default 1). Fits the current camera to the visible product bounds through the shared Camera::fit contract, moving back for a picture taller than wide so its sides hold the product too; changes only view state, not a saved setup, rendering job, stage or engineering geometry."),CommandSpec::new("render.preset.resolve", "Review Native Studio", studio_presets::resolve).icon("render_scene").noundo().params("id: NATIVE-STUDIO-001..025; name; set?: typed GPU setup patch; expected_revision?:u64. Resolves original built-in HDR/rig/passive ground with conservative geometry clearance, returns all replacements and preserved fields without mutation. Unbound SCENE-* concepts are not accepted."),CommandSpec::new("render.preset.apply", "Apply Native Studio", studio_presets::apply).icon("render_scene")@@ -169,13 +169,20 @@ fn get_camera(s: &mut Session, params: &Value) -> Result<Value> {}fn fit_camera(s: &mut Session, params: &Value) -> Result<Value> {- if !params.as_object().is_some_and(|p| p.is_empty()) {- return Err(bad("render.camera.fit", "expected an empty parameter object"));- }+ let aspect = match params.as_object() {+ Some(p) if p.is_empty() => 1.0,+ Some(p) if p.len() == 1 && p.contains_key("aspect") => match p["aspect"].as_f64() {+ // The range a preview frame can show (`frame_rect` in the Render workspace).+ Some(a) if (1e-6..=1e6).contains(&a) => a,+ _ => return Err(bad("render.camera.fit", "aspect must be a number from 0.000001 to 1000000: the picture's width over its height")),+ },+ _ => return Err(bad("render.camera.fit", "expected an empty parameter object or {aspect}")),+ };let scene = crate::product_scene::extract(s)?;let mut camera = s.camera.unwrap_or_default();- if !scene.bounds.is_empty() {- camera.fit(&scene.bounds);+ // Publish only a valid fitted camera; the previous one stays otherwise.+ if !camera.fit_aspect(&scene.bounds, aspect) && !scene.bounds.is_empty() {+ return Err(bad("render.camera.fit", "the product cannot be framed at this aspect: the fitted camera is out of range"));}s.camera = Some(camera);Ok(json!({"camera":camera,"empty":scene.bounds.is_empty(),"document_changed":false}))diff --git a/crates/engine/src/cmd/render/job_tests.rs b/crates/engine/src/cmd/render/job_tests.rsindex cb1b4620f9..02ee106a08 100644--- a/crates/engine/src/cmd/render/job_tests.rs+++ b/crates/engine/src/cmd/render/job_tests.rs@@ -1183,9 +1183,26 @@ fn registered_product_camera_fit_changes_only_view_and_keeps_orientation() {assert_eq!(fitted["document_changed"], false);let after = s.camera.unwrap();assert_eq!((after.yaw, after.pitch, after.roll), (camera.yaw, camera.pitch, camera.roll));+ // A picture taller than wide moves the camera back by the ratio, keeping the orientation+ // and the target; a wide one is the plain fit.+ let tall = s.execute("render.camera.fit", &json!({"aspect":0.5})).unwrap();+ assert_eq!(tall["document_changed"], false);+ let back = s.camera.unwrap();+ assert!((back.distance - 2.0 * after.distance).abs() < 1e-9, "{} vs {}", back.distance, after.distance);+ assert_eq!((back.yaw, back.pitch, back.roll, back.target), (after.yaw, after.pitch, after.roll, after.target));+ s.execute("render.camera.fit", &json!({"aspect":2.0})).unwrap();+ assert_eq!(s.camera.unwrap(), after);assert_eq!(s.doc.to_json(), doc);assert_eq!(s.undo.len(), undo);+ // Hostile aspects are refused and leave the finite camera, the document and undo alone:+ // a subnormal one would otherwise divide the fitted distance into infinity.+ for aspect in [json!(0), json!(-1), json!(1e-320), json!(1e-7), json!(1e7), json!("tall")] {+ assert!(s.execute("render.camera.fit", &json!({"aspect":aspect})).is_err(), "aspect {aspect}");+ assert_eq!(s.camera.unwrap(), after);+ }assert!(s.execute("render.camera.fit", &json!({"scale":0})).is_err());+ assert_eq!(s.doc.to_json(), doc);+ assert_eq!(s.undo.len(), undo);}#[test]diff --git a/crates/render/src/camera.rs b/crates/render/src/camera.rsindex f87407d48f..bc32aacdea 100644--- a/crates/render/src/camera.rs+++ b/crates/render/src/camera.rs@@ -502,6 +502,28 @@ impl Camera {let r = (b.diagonal() * 0.5).max(1.0);self.distance = if self.fov > 0.0 { r / (self.fov * 0.5).sin() * 1.1 } else { r / 0.4 * 1.15 };}+ /// [`Camera::fit`] for a picture of `aspect` (width over height). The fit frames the+ /// bounding sphere by the picture's height; a picture taller than wide also needs it inside+ /// the sides, so the camera moves back by the ratio (the orthographic width grows with the+ /// distance; in perspective the sphere's angular radius shrinks with it, which the fit's+ /// margin covers). A wide picture, or an aspect that is not a positive number, keeps the+ /// plain fit. Returns false, leaving the camera alone, when there is nothing to fit or the+ /// fitted camera would not be valid (a distance that overflows).+ pub fn fit_aspect(&mut self, b: &Aabb3, aspect: f64) -> bool {+ if b.is_empty() {+ return false;+ }+ let mut fitted = *self;+ fitted.fit(b);+ if aspect.is_finite() && aspect > 0.0 && aspect < 1.0 {+ fitted.distance /= aspect;+ }+ if !fitted.is_valid() {+ return false;+ }+ *self = fitted;+ true+ }/// The same camera looking from direction `back` (target → eye). Straight up or down/// keeps the yaw, rounded to the nearest quarter turn so the view stays square.pub fn looking_from(&self, back: Vec3) -> Camera {@@ -863,6 +885,20 @@ mod tests {}}+ /// A fit whose distance would overflow (a subnormal aspect, a huge product) is refused+ /// and leaves the finite camera as it was.+ #[test]+ fn fit_aspect_refuses_an_overflowing_fit() {+ let before = Camera { distance: 80.0, ..Default::default() };+ let small = Aabb3 { min: Vec3::ZERO, max: Vec3::new(40.0, 30.0, 20.0) };+ let huge = Aabb3 { min: Vec3::new(-1e307, -1e307, -1e307), max: Vec3::new(1e307, 1e307, 1e307) };+ for (b, aspect) in [(&small, 1e-320), (&huge, 1e-6)] {+ let mut c = before;+ assert!(!c.fit_aspect(b, aspect), "aspect {aspect}");+ assert_eq!(c, before);+ }+ }+#[test]fn fit_and_hostile() {let mut c = Camera::default();diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 5b4bed9111..e58e1c0283 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -2301,7 +2301,7 @@ impl SolveApp {fn try_fitted_bounds(&self, cam: Camera, bounds: &solidcraft_engine::geom::Aabb3) -> Option<Camera> {let layout = self.viewport.layout.as_ref()?;if render_workspace::active(self) {- return viewport_layout::fit_product_bounds(cam, bounds, layout);+ return viewport_layout::fit_product_bounds(cam, bounds, &render_workspace::picture_layout(self, layout));}viewport_layout::fit_bounds(cam, bounds, layout, self.view_fov())}diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rsindex 14d56646eb..b09ab22aff 100644--- a/crates/ui-egui/src/render_workspace.rs+++ b/crates/ui-egui/src/render_workspace.rs@@ -652,22 +652,26 @@ pub fn enter(app: &mut SolveApp, render: bool) -> Result<(), String> {return Err(crate::i18n::tr("render.error_finish_operation").into());}app.run("render.scene", json!({}))?;- if !active(app) {+ let entering = !active(app);+ if entering {app.render_workspace.design_camera = Some((app.cam, app.ui.perspective));app.ui.tab = "RENDER".into();select_stage(app, app.render_workspace.view.stage.key());if app.render_workspace.view.selection == RenderSelection::Nothing {selection_editor(app, &RenderSelection::Nothing);}- let scene = solidcraft_engine::product_scene::extract(&app.session).map_err(|e| e.to_string())?;- if !scene.bounds.is_empty() {- app.fit_bounds(scene.bounds);- }}setups::refresh_dirty(app);if app.render_workspace.revision != app.session.revision && !app.render_workspace.view.dirty {setups::load(app);}+ // Fit once the setup in effect is known: the fit frames that image's aspect.+ if entering {+ let scene = solidcraft_engine::product_scene::extract(&app.session).map_err(|e| e.to_string())?;+ if !scene.bounds.is_empty() {+ app.fit_bounds(scene.bounds);+ }+ }#[cfg(not(target_arch = "wasm32"))]app.render_workspace.start_deferred_path_host();} else {@@ -1908,6 +1912,20 @@ fn hash_surface(surface: Option<solidcraft_engine::render::surface::OpaqueSurfac}}+/// The image's width over its height.+pub fn image_aspect(setup: &RenderSetup) -> f64 {+ f64::from(setup.width.max(1)) / f64::from(setup.height.max(1))+}++/// `layout` seen from the picture: while Frame shows the picture's frame the preview projects+/// into that frame, not the viewport, so a fit that keeps the product inside this layout keeps+/// it inside the image. Elsewhere the preview fills the viewport and the layout is unchanged.+pub(crate) fn picture_layout(app: &SolveApp, layout: &crate::viewport_layout::Layout) -> crate::viewport_layout::Layout {+ let Some(frame) = shot::preview_rect(app, layout.viewport) else { return layout.clone() };+ // The same 16-point margin the viewport's fit keeps inside its free area.+ crate::viewport_layout::Layout { viewport: frame, drawable: layout.drawable.intersect(frame.shrink(16.0)), ..layout.clone() }+}+/// The size the product preview draws at for a viewport of `full` physical pixels: the full/// size when the viewport executor admits it, else the largest size at the same aspect it does./// Without an executor the request is left for resolution to report.diff --git a/crates/ui-egui/src/render_workspace_inspector.rs b/crates/ui-egui/src/render_workspace_inspector.rsindex 81750b42d9..ffc21d715b 100644--- a/crates/ui-egui/src/render_workspace_inspector.rs+++ b/crates/ui-egui/src/render_workspace_inspector.rs@@ -1654,9 +1654,10 @@ fn base_appearance(app: &mut SolveApp, ui: &mut egui::Ui) {mod tests;pub(super) fn fit_subject(app: &mut SolveApp) -> Result<(), String> {- // Capture the current navigation orientation before the engine's view command.+ // Capture the current navigation orientation before the engine's view command, which fits+ // the product to the picture's aspect: what the preview frames and Export PNG writes.app.run("render.camera.set", json!({"camera":app.cam}))?;- app.run("render.camera.fit", json!({}))?;+ app.run("render.camera.fit", json!({"aspect":super::image_aspect(&app.render_workspace.view.draft)}))?;app.follow_view_request(false);app.fit_view();Ok(())diff --git a/crates/ui-egui/src/render_workspace_tests.rs b/crates/ui-egui/src/render_workspace_tests.rsindex f5b05014d7..350d765833 100644--- a/crates/ui-egui/src/render_workspace_tests.rs+++ b/crates/ui-egui/src/render_workspace_tests.rs@@ -6407,3 +6407,85 @@ fn the_field_of_view_rescales_only_the_design_view() {assert!(h.app.ui.perspective);assert!((size(h.app.cam, 1.2) / size(design, 0.6) - 1.0).abs() < 1e-9, "the design view keeps its size: {:?}", h.app.cam);}++/// Fit Product keeps the whole product inside the image, whatever its aspect: a picture+/// taller than wide moves the camera back so the sides hold it too.+#[test]+fn fit_aspect_keeps_the_product_inside_a_tall_image() {+ use solidcraft_engine::geom::{Aabb3, Vec3};+ let bounds = Aabb3 { min: Vec3::new(-30.0, -30.0, -30.0), max: Vec3::new(30.0, 30.0, 30.0) };+ let radius = bounds.diagonal();+ for fov in [0.0, std::f64::consts::FRAC_PI_4] {+ let mut landscape = Camera { fov, ..Default::default() };+ assert!(landscape.fit_aspect(&bounds, 2.0));+ let mut plain = Camera { fov, ..Default::default() };+ plain.fit(&bounds);+ assert_eq!(landscape, plain, "a wide picture keeps the standard fit");+ for aspect in [0.5, 0.25] {+ let mut cam = Camera { fov, ..Default::default() };+ assert!(cam.fit_aspect(&bounds, aspect));+ for p in corners(&bounds) {+ let q = cam.view_proj(aspect, radius).apply(p);+ let (x, y) = (q[0] / q[3], q[1] / q[3]);+ assert!(x.abs() <= 1.0 && y.abs() <= 1.0, "fov {fov}, aspect {aspect}: corner {p:?} projects to ({x}, {y}), outside the picture");+ }+ }+ // Nothing to fit leaves the camera alone.+ let mut cam = Camera { fov, distance: 123.0, ..Default::default() };+ assert!(!cam.fit_aspect(&Aabb3::EMPTY, 0.5));+ assert_eq!(cam.distance, 123.0);+ }+}++fn corners(b: &solidcraft_engine::geom::Aabb3) -> Vec<solidcraft_engine::geom::Vec3> {+ let mut out = Vec::new();+ 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.push(solidcraft_engine::geom::Vec3::new(x, y, z));+ }+ }+ }+ out+}++/// Entering Render fits the product to the setup in effect, not to the draft that setup+/// replaces: in a cold workspace whose saved Studio setup is portrait (1024 × 4096) the fit+/// waits for the setup to load, so with Frame open the product sits inside the final 1:4+/// picture, in orthographic and in perspective, and leaving Render gives the Design camera+/// back.+#[test]+fn entering_render_fits_a_saved_portrait_setup_inside_its_final_frame() {+ for fov in [0.0, 0.8] {+ let mut h = Harness::new();+ h.app.run("solid.box", json!({"length":60,"width":20,"height":20})).unwrap();+ let name = h.app.render_workspace.view.name.clone();+ h.app.run("render.settings.set", json!({"name":name,"set":{"width":1024,"height":4096}})).unwrap();+ h.app.ui.perspective = fov > 0.0;+ h.app.cam.fov = fov;+ h.frames(2);+ let design = (h.app.cam, h.app.ui.perspective);+ let draft = &h.app.render_workspace.view.draft;+ assert_ne!((draft.width, draft.height), (1024, 4096), "the cold draft is still the default");+ h.app.render_workspace.view.stage = Stage::Frame;+ enter(&mut h.app, true).unwrap();+ h.frames(3);+ assert!(shot::overlay_visible(&h.app));+ let draft = &h.app.render_workspace.view.draft;+ assert_eq!((draft.width, draft.height), (1024, 4096), "the saved setup is in effect");+ let frame = shot::preview_rect(&h.app, h.app.viewport.rect.unwrap()).unwrap();+ assert!((frame.width() / frame.height() - 0.25).abs() < 1e-3, "{frame:?}");+ let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap();+ let cam = h.app.cam;+ let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(cam.target);+ for p in corners(&scene.bounds) {+ let (x, y, _) = cam.to_screen(p, f64::from(frame.width()), f64::from(frame.height()), radius).unwrap();+ assert!(+ (0.0..=f64::from(frame.width())).contains(&x) && (0.0..=f64::from(frame.height())).contains(&y),+ "fov {fov}: corner {p:?} at ({x}, {y}) outside the {frame:?} picture"+ );+ }+ enter(&mut h.app, false).unwrap();+ assert_eq!((h.app.cam, h.app.ui.perspective), design, "fov {fov}: leaving Render restores the Design camera");+ }+}diff --git a/docs/render-workspace.md b/docs/render-workspace.mdindex 940f5e7259..2284dd96b3 100644--- a/docs/render-workspace.md+++ b/docs/render-workspace.md@@ -331,6 +331,13 @@ Orbit around, zoom to the cursor, the SpaceMouse, the middle double-click, F6 anview or navigation cube all work and**Fit Product** frames visible product bodies without including sketches or selection.+While Frame shows the picture's frame, **Fit Product** and the fit on entering Render keep+the product inside that frame rather than the viewport, so a picture taller than wide moves+the camera back. The fit on entering waits for the saved setup to load, so it frames that+setup's aspect, not the draft it replaces. `render.camera.fit` takes the picture's `aspect`+(width over height, 0.000001 to 1000000, default 1) and refuses a fit whose camera would be+out of range, leaving the current camera as it was.+Preview drafts do not make the document dirty until saved. Unknown backend preferencesand unsupported modes remain saved intent: the strict resolver reports the unsupportedviewport request. **Use Integrated Preview** is an explicit draft change, never an