diff --git a/assets/locales/pending/perspective-field-of-view.json b/assets/locales/pending/perspective-field-of-view.json new file mode 100644 index 000000000..6a65028cb --- /dev/null +++ b/assets/locales/pending/perspective-field-of-view.json @@ -0,0 +1,26 @@ +{ + "en": { + "prefs.perspective_fov": "Field of view" + }, + "ar": { + "prefs.perspective_fov": "مجال الرؤية" + }, + "de": { + "prefs.perspective_fov": "Sichtfeld" + }, + "he": { + "prefs.perspective_fov": "שדה ראייה" + }, + "ja": { + "prefs.perspective_fov": "画角" + }, + "ko": { + "prefs.perspective_fov": "시야각" + }, + "vi": { + "prefs.perspective_fov": "Trường nhìn" + }, + "zh": { + "prefs.perspective_fov": "视场角" + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 98cb282c2..e8f78d78a 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -48,7 +48,7 @@ use std::time::Duration; use serde_json::{Value, json}; use solidcraft_engine::io::vfs; -use solidcraft_engine::render::StandardView; +use solidcraft_engine::render::{Camera, StandardView}; use solidcraft_engine::{batch_params, timing}; use crate::SolveApp; @@ -1135,7 +1135,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> /// `ui.camera`: the viewport's orbit camera (`target`, `yaw`, `pitch`, `roll` in radians, /// `distance` in mm, `fov`, `up`), or a new one. A field left out keeps its value, so a reply -/// passed back sets the same view again. `fit`: frame the listed occurrences (ids or names; +/// passed back sets the same view again. `fov` is the angle the window draws with (see [`drawn`]). `fit`: frame the listed occurrences (ids or names; /// `root`: the bodies outside every component), or everything (`true`), keeping the direction; /// `false` frames nothing. /// Nothing changes when a field is refused. @@ -1149,10 +1149,10 @@ fn camera(app: &mut SolveApp, p: &Value) -> Result { if let Some(k) = o.keys().find(|k| !FIELDS.contains(&k.as_str())) { return Err(format!("unknown camera field `{k}` (it takes {})", FIELDS.join(", "))); } - let mut cam = app.cam; + let mut cam = drawn(app); let sets = o.keys().any(|k| k != "fit"); if sets { - let mut v = serde_json::to_value(app.cam).map_err(|e| e.to_string())?; + let mut v = serde_json::to_value(cam).map_err(|e| e.to_string())?; for (k, x) in o.iter().filter(|(k, _)| *k != "fit") { v[k] = x.clone(); } @@ -1164,10 +1164,11 @@ fn camera(app: &mut SolveApp, p: &Value) -> Result { // Straight up or down keeps a heading, as the standard views do. let lim = std::f64::consts::FRAC_PI_2 - 1e-6; cam.pitch = cam.pitch.clamp(-lim, lim); - // Perspective and the up axis are settings the camera follows, not its own. - if cam.fov != app.cam.fov { - return Err("`fov` follows the perspective setting (ui.set {perspective})".into()); + // Perspective, its angle and the up axis are settings the camera follows, not its own. + if cam.fov != drawn(app).fov { + return Err("`fov` follows Perspective view (ui.set {perspective}) and its angle (ui.prefs {perspective_fov})".into()); } + cam.fov = app.cam.fov; if cam.up != app.cam.up { return Err("`up` follows the up axis preference (ui.prefs {up_axis})".into()); } @@ -1190,7 +1191,7 @@ fn camera(app: &mut SolveApp, p: &Value) -> Result { }; // A read leaves a view change that is animating alone. if !sets && fit.is_none() { - return serde_json::to_value(app.cam).map_err(|e| e.to_string()); + return serde_json::to_value(drawn(app)).map_err(|e| e.to_string()); } app.cancel_view_animation(); app.viewport.orbit_free = None; @@ -1200,7 +1201,17 @@ fn camera(app: &mut SolveApp, p: &Value) -> Result { Some(Some(b)) => app.fit_bounds(b), None => {} } - serde_json::to_value(app.cam).map_err(|e| e.to_string()) + serde_json::to_value(drawn(app)).map_err(|e| e.to_string()) +} + +/// The camera as the window draws it: with the view's angle ([`SolveApp::view_fov`]), or in Render +/// with the Render camera's own. +fn drawn(app: &SolveApp) -> Camera { + let mut cam = app.cam; + if !crate::render_workspace::active(app) { + cam.fov = app.view_fov(); + } + cam } /// An occurrence by id or name (or a component's name: its first occurrence); 0 is the root. @@ -2203,6 +2214,25 @@ mod tests { assert!(r["ok"] == false && empty.app.cam == before, "{r}"); } + /// With Perspective view on, `ui.camera` reports the angle the window draws with (#5364) and + /// its reply replays; another angle is refused, naming the preference. A sketch draws parallel. + #[test] + fn ui_camera_reports_the_drawn_angle_and_its_reply_replays() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.set", json!({"perspective": true})); + h.call("ui.prefs", json!({"perspective_fov": 1.0})); + let read = h.call("ui.camera", Value::Null); + assert_eq!(read["result"]["fov"], json!(1.0), "{read}"); + let stored = h.app.cam.fov; + let again = h.call("ui.camera", read["result"].clone()); + assert_eq!(again["result"], read["result"], "the reply replays"); + assert_eq!(h.app.cam.fov, stored, "the camera's own angle is left as it was"); + let refused = h.call("ui.camera", json!({"fov": 0.6})); + assert!(refused["ok"] == false && refused["error"].as_str().unwrap().contains("ui.prefs {perspective_fov}"), "{refused}"); + h.app.run("sketch.create", json!({"plane": "XY"})).unwrap(); + assert_eq!(h.call("ui.camera", Value::Null)["result"]["fov"], json!(0.0), "a sketch draws parallel"); + } + /// `ui.start` params set what a dialog opens on: Drive Joints on a joint (by name or id) at /// the given values, driving nothing yet. A param it doesn't take is refused and closes it. #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index eb34a618d..bb3885fc7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2053,6 +2053,13 @@ impl SolveApp { self.picking_sketch_plane() || self.dialog.as_ref().is_some_and(|d| d.inputs.get(d.active).is_some_and(|i| i.accept & selection::PLANES != 0)) } + /// The field of view the view is drawn with: the `perspective_fov` preference while the view is + /// in perspective ([`Self::perspective_view`]), and 0 (parallel) otherwise. The one place the + /// drawn angle is decided. + pub fn view_fov(&self) -> f64 { + if self.perspective_view() { prefs::perspective_fov(&self.preferences) } else { 0.0 } + } + /// Is the view drawn in perspective? The perspective preference, except while a sketch is /// open (always orthographic) or when the #2682 mode is on: then the view is orthographic /// exactly when the camera faces a standard axis view, and perspective otherwise. @@ -2185,10 +2192,13 @@ impl SolveApp { if render_workspace::active(self) { return viewport_layout::fit_product_bounds(cam, bounds, layout).unwrap_or(cam); } - return viewport_layout::fit_bounds(cam, bounds, layout, self.perspective_view()).unwrap_or(cam); + return viewport_layout::fit_bounds(cam, bounds, layout, self.view_fov()).unwrap_or(cam); } + // Framed at the angle the view draws with, keeping the camera's own. let previous = cam; + cam.fov = self.view_fov(); cam.fit(bounds); + cam.fov = previous.fov; if cam.is_valid() { cam } else { previous } } diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 1c575d3d2..d9a886f22 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -746,6 +746,36 @@ pub fn apply_file_limits(p: &Prefs) { } } +/// Perspective view's default field of view (about 34°), in radians. +const PERSPECTIVE_FOV: f64 = 0.6; + +/// The field of view Perspective view draws with: the preference, or the default when a saved +/// value is outside the accepted range (a hand edit). +pub fn perspective_fov(p: &Prefs) -> f64 { + if accepted::perspective_fov(p) { p.perspective_fov } else { PERSPECTIVE_FOV } +} + +/// Perspective view keeps the target's size when its angle changes (#5364): the distance scales by +/// tan(old/2) / tan(new/2), so the angle changes the depth, not the zoom. Called every frame and +/// after `ui.prefs`, so every way the angle changes (the slider, Cancel, Restore Defaults, a script) +/// goes through it. A parallel view keeps the last perspective angle, and while Render is open the +/// camera is Render's own, so the change waits until the design view is back. +pub(crate) fn follow_view_fov(app: &mut SolveApp) { + let fov = app.view_fov(); + if fov <= 0.0 || crate::render_workspace::active(app) { + return; + } + let old = std::mem::replace(&mut app.prefs_window.drawn_fov, fov); + if old > 0.0 && old != fov { + let k = (old * 0.5).tan() / (fov * 0.5).tan(); + app.cam.distance *= k; + if let Some(anim) = &mut app.cam_anim { + anim.from.distance *= k; + anim.to.distance *= k; + } + } +} + /// The browser sidebar's first width, and the width [`Prefs::default`] restores; the panel /// itself clamps what the user drags to its own range. pub const DEFAULT_BROWSER_WIDTH: f32 = 250.0; @@ -965,6 +995,9 @@ preference_settings! { show_view_angles: bool = false, PAGE_GRAPHICS; /// Show world X/Y/Z component dimensions beside the total distance in Measure. measure_axis_distances: bool = true, PAGE_GRAPHICS => check_id("settings.measure_axis_distances"); + /// Perspective view's vertical field of view in radians (#5364), 15° to 90°. The view reads a + /// saved value outside that range as the default ([`perspective_fov`]). + perspective_fov: f64 = PERSPECTIVE_FOV, PAGE_GRAPHICS, accept(15f64.to_radians()..=90f64.to_radians()); /// Decimals shown for lengths and angles. length_decimals: u8 = 2, PAGE_DESIGN; angle_decimals: u8 = 1, PAGE_DESIGN; @@ -1328,6 +1361,8 @@ pub struct PrefsWindow { snapshot: Option, /// The up axis preference the view follows now (applied when it changes, and at startup). applied_up: Option, + /// The perspective angle the view was last drawn with ([`follow_view_fov`]); 0 before the first. + drawn_fov: f64, /// The search text of the interface font list. font_filter: String, /// Search text on the Plugins page. @@ -1810,6 +1845,7 @@ pub fn apply(app: &mut SolveApp, ctx: &egui::Context) { if app.prefs_window.applied_up.as_deref() != Some(app.preferences.up_axis.as_str()) { up_axis_changed(app); } + follow_view_fov(app); if app.preferences.theme == "system" && let Some(t) = ctx.system_theme() { @@ -2906,6 +2942,8 @@ pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result {} } if button.is_some() { + // Cancel and Restore Defaults can change the angle too. + follow_view_fov(app); out = serde_json::to_value(&app.preferences).map_err(|e| e.to_string())?; } if let Some(o) = out.as_object_mut() { @@ -3323,6 +3361,9 @@ pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result Result egui::Rect { + h.call("ui.prefs", json!({"open": "Graphics"})); + let label = crate::i18n::tr("prefs.perspective_fov"); + reveal_preference(h, &format!("dialog:slider:{label}")); + crate::scenario::rect_of(&format!("dialog:slider_track:{label}")).expect("the Field of view slider") + } + + /// Graphics › Field of view (#5364): the kit slider in whole degrees, dragged or typed, written + /// back in radians. While the view can't draw in perspective (Perspective view off, and no + /// perspective-while-orbiting mode, #2682) it changes nothing, and Cancel puts it back. + #[test] + fn the_field_of_view_slider_drags_and_types_whole_degrees() { + let mut h = crate::scenario::Harness::new(); + for (perspective, auto_ortho) in [(false, false), (true, false), (false, true)] { + h.call("ui.set", json!({"perspective": perspective})); + h.app.ui.auto_ortho_faces = auto_ortho; + let track = graphics_slider(&mut h); + press(&mut h, pos2(track.left() + 4.0, track.center().y), true); + h.app.synthetic.push(Event::PointerMoved(pos2(track.left() + track.width() * 0.75, track.center().y))); + h.frames(3); + press(&mut h, pos2(track.left() + track.width() * 0.75, track.center().y), false); + let degrees = h.app.preferences.perspective_fov.to_degrees(); + if perspective || auto_ortho { + assert!((degrees - degrees.round()).abs() < 1e-9 && (35.0..=90.0).contains(°rees), "{degrees}"); + } else { + assert_eq!(h.app.preferences.perspective_fov, PERSPECTIVE_FOV, "disabled while Perspective view is off"); + } + h.call("ui.prefs", json!({"button": "cancel"})); + assert_eq!(h.app.preferences.perspective_fov, PERSPECTIVE_FOV, "Cancel restores the angle"); + } + let track = graphics_slider(&mut h); + press(&mut h, pos2(track.right() + 30.0, track.center().y), true); + press(&mut h, pos2(track.right() + 30.0, track.center().y), false); + h.app.synthetic.push(Event::Text("40.4".into())); + h.app.synthetic.push(Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.frames(3); + assert!( + (h.app.preferences.perspective_fov - 40f64.to_radians()).abs() < 1e-9, + "typed 40.4 keeps to 40°: {}", + h.app.preferences.perspective_fov + ); + h.call("ui.prefs", json!({"button": "ok"})); + } + + /// `ui.prefs {perspective_fov}` takes 15° to 90° in radians and refuses anything else, changing + /// nothing; a saved value the view can't use (a hand edit) draws at the default, never a broken view. + #[test] + fn hostile_angles_are_refused_or_drawn_at_the_default() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.set", json!({"perspective": true})); + for fine in [15f64.to_radians(), 90f64.to_radians(), 1.0] { + assert_eq!(h.call("ui.prefs", json!({"perspective_fov": fine}))["ok"], true, "{fine}"); + assert_eq!(h.app.view_fov(), fine); + } + let before = (h.app.preferences.clone(), h.app.cam); + for bad in [ + json!(-1.0), + json!(0.0), + json!(14.9f64.to_radians()), + json!(90.1f64.to_radians()), + json!(std::f64::consts::PI), + json!(1e308), + json!(-1e308), + json!("x"), + json!(null), + json!([1]), + ] { + let r = h.call("ui.prefs", json!({"perspective_fov": bad})); + assert_eq!(r["ok"], false, "{bad}: {r}"); + assert_eq!((h.app.preferences.clone(), h.app.cam), before, "{bad} changes nothing"); + } + for saved in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, 0.0, 0.1, 2.0, std::f64::consts::PI, 1e308] { + h.app.preferences.perspective_fov = saved; + h.frames(2); + assert_eq!(h.app.view_fov(), PERSPECTIVE_FOV, "{saved} draws at the default"); + assert!(h.app.cam.is_valid(), "{saved}: {:?}", h.app.cam); + } + // A fuzz pass: any bit pattern, and values spread over -1…3 rad, through `ui.prefs` and saved. + let range = 15f64.to_radians()..=90f64.to_radians(); + let mut x: u64 = 0x5364; + for i in 0..2000 { + x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let v = if i % 2 == 0 { f64::from_bits(x) } else { (x >> 11) as f64 / (1u64 << 53) as f64 * 4.0 - 1.0 }; + let accepted = set(&mut h.app, &json!({"perspective_fov": v})).is_ok(); + assert_eq!(accepted, range.contains(&v), "{v}"); + h.app.preferences.perspective_fov = v; + follow_view_fov(&mut h.app); + assert!(range.contains(&h.app.view_fov()) && h.app.cam.is_valid(), "{v}: {:?}", h.app.cam); + } + let read = lenient(&json!({"perspective_fov": "wide", "ui_scale": 1.5})); + assert_eq!((read.perspective_fov, read.ui_scale), (PERSPECTIVE_FOV, 1.5), "an unreadable angle costs that setting only"); + } + + /// The target keeps its size when the angle changes, by every path (`ui.prefs`, Cancel, Restore + /// Defaults), and a parallel view or a sketch keeps the last perspective angle until it's back. + #[test] + fn the_view_keeps_its_size_when_the_angle_changes() { + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 20})).unwrap(); + h.call("ui.set", json!({"perspective": true})); + h.frames(3); + let half = |h: &crate::scenario::Harness| { + let mut cam = h.app.cam; + cam.fov = h.app.view_fov(); + cam.half_height() + }; + let (size, distance) = (half(&h), h.app.cam.distance); + h.call("ui.prefs", json!({"open": "Graphics"})); + for fov in [15f64.to_radians(), 1.0, 90f64.to_radians()] { + h.call("ui.prefs", json!({"perspective_fov": fov})); + assert!((half(&h) / size - 1.0).abs() < 1e-9, "{fov}: {} vs {size}", half(&h)); + } + h.call("ui.prefs", json!({"button": "cancel"})); + assert!((h.app.cam.distance / distance - 1.0).abs() < 1e-9, "Cancel restores the angle and the size"); + h.call("ui.prefs", json!({"perspective_fov": 1.2})); + h.call("ui.prefs", json!({"open": "Graphics", "button": "defaults"})); + h.call("ui.prefs", json!({"button": "ok"})); + assert_eq!(h.app.preferences.perspective_fov, PERSPECTIVE_FOV); + assert!(!h.app.ui.perspective, "the page's Restore Defaults turns Perspective view off too"); + // A parallel view keeps the last perspective angle: back in perspective, the default angle + // draws at the first size, and an angle changed while it's off is followed once it's on. + h.call("ui.set", json!({"perspective": true})); + h.frames(2); + assert!((h.app.cam.distance / distance - 1.0).abs() < 1e-9, "Restore Defaults restores the size"); + h.call("ui.set", json!({"perspective": false})); + h.frames(2); + let parallel = h.app.cam.distance; + h.call("ui.prefs", json!({"perspective_fov": 1.2})); + assert_eq!(h.app.cam.distance, parallel, "parallel: nothing to rescale yet"); + h.call("ui.set", json!({"perspective": true})); + h.frames(2); + assert!((half(&h) / size - 1.0).abs() < 1e-9); + h.app.run("sketch.create", json!({"plane": "XY"})).unwrap(); + h.call("ui.prefs", json!({"perspective_fov": 0.6})); + h.app.finish_sketch(); + h.frames(2); + assert!((half(&h) / size - 1.0).abs() < 1e-9); + } + + /// A view change that is animating when the angle changes ends at the same size too: both its + /// ends are rescaled with the camera. + #[test] + fn an_animating_view_change_is_rescaled_too() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.set", json!({"perspective": true})); + h.frames(2); + let to = solidcraft_engine::render::Camera { distance: 300.0, ..h.app.cam }; + h.app.cam_anim = Some(solidcraft_engine::render::CameraAnim::new(h.app.cam, to, h.app.now)); + let from = h.app.cam; + set(&mut h.app, &json!({"perspective_fov": 1.0})).unwrap(); + let k = (0.6f64 * 0.5).tan() / 0.5f64.tan(); + let anim = h.app.cam_anim.as_ref().expect("still animating"); + assert!((anim.to.distance - 300.0 * k).abs() < 1e-9 && (anim.from.distance - from.distance * k).abs() < 1e-9, "{:?}", (anim.from, anim.to)); + } + + /// A script's Cancel puts the view's size back at once, before any frame runs, so a `ui.camera` + /// read straight after it gives the restored view. + #[test] + fn cancel_restores_the_size_before_the_next_frame() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.set", json!({"perspective": true})); + h.frames(2); + let distance = h.app.cam.distance; + let mut raw = |method: &str, params: serde_json::Value| { + let (req, _rx) = crate::control::ControlRequest::new(method, params); + match crate::control::handle(&mut h.app, &h.ctx, &req) { + crate::control::Outcome::Done(v) => v, + _ => serde_json::Value::Null, + } + }; + raw("ui.prefs", json!({"open": "Graphics", "perspective_fov": 1.2})); + raw("ui.prefs", json!({"button": "cancel"})); + let cam = raw("ui.camera", serde_json::Value::Null); + assert!((cam["result"]["distance"].as_f64().unwrap() / distance - 1.0).abs() < 1e-9, "{cam}"); + } + + /// The angle is kept between runs. + #[test] + fn the_angle_is_kept_across_a_restart() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.prefs", json!({"perspective_fov": 1.1})); + h.step(&json!({"restart": "close"})).unwrap(); + assert_eq!(h.app.preferences.perspective_fov, 1.1); + } +} diff --git a/crates/ui-egui/src/prefs/graphics.rs b/crates/ui-egui/src/prefs/graphics.rs index 92b82c783..ac2414171 100644 --- a/crates/ui-egui/src/prefs/graphics.rs +++ b/crates/ui-egui/src/prefs/graphics.rs @@ -164,6 +164,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if let Some(left) = columns.get_mut(0) { ui_kit::checkbox(left, crate::i18n::tr_label("Grid"), &mut app.ui.show_grid); ui_kit::checkbox(left, crate::i18n::tr_label("Perspective view"), &mut app.ui.perspective); + left.add_enabled_ui(app.ui.perspective || app.ui.auto_ortho_faces, |ui| field_of_view_row(app, ui)); setting::show_frame_rate(app, left).on_hover_text(app.tr("settings.frame_rate_note")); left.add_enabled_ui(app.preferences.show_frame_rate, |ui| { ui_kit::checkbox(ui, app.tr("ui.frame_rate_details"), &mut app.preferences.frame_rate_details) @@ -208,3 +209,17 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::text(ui, &renderer, ui_kit::Text::Inline); }); } + +/// Perspective view's Field of view (#5364): the kit slider in degrees, typed or dragged, kept to +/// whole degrees and written back in radians. No step on the slider itself: it would round the +/// default 0.6 (34.4°) just by being drawn, so an untouched angle stays exactly as saved. +fn field_of_view_row(app: &mut SolveApp, ui: &mut egui::Ui) { + let mut degrees = perspective_fov(&app.preferences).to_degrees(); + ui_kit::row(ui, app.tr("prefs.perspective_fov"), |ui| { + let response = ui_kit::slider(ui, &mut degrees, 15.0..=90.0, ui_kit::Slider { format: |v| format!("{v:.0}°"), ..Default::default() }); + if response.changed() { + app.preferences.perspective_fov = degrees.round().to_radians(); + } + response + }); +} diff --git a/crates/ui-egui/src/render_workspace_inspector.rs b/crates/ui-egui/src/render_workspace_inspector.rs index fe4ab4117..a3ba0c721 100644 --- a/crates/ui-egui/src/render_workspace_inspector.rs +++ b/crates/ui-egui/src/render_workspace_inspector.rs @@ -712,7 +712,8 @@ fn camera_controls(app: &mut SolveApp, ui: &mut egui::Ui) { let mut camera = before; let mut perspective = camera.fov > 0.0; if ui_kit::checkbox(ui, app.tr("render.perspective"), &mut perspective).changed() { - camera.fov = if perspective { std::f64::consts::FRAC_PI_4 } else { 0.0 }; + // On at the Field of view preference's angle (#5364); a saved setup keeps its own. + camera.fov = if perspective { crate::prefs::perspective_fov(&app.preferences) } else { 0.0 }; } if perspective { let mut fov = camera.fov.to_degrees(); diff --git a/crates/ui-egui/src/render_workspace_tests.rs b/crates/ui-egui/src/render_workspace_tests.rs index ea8a43c70..f5b05014d 100644 --- a/crates/ui-egui/src/render_workspace_tests.rs +++ b/crates/ui-egui/src/render_workspace_tests.rs @@ -1403,6 +1403,7 @@ fn clicked_render_workspace_saves_one_setup_and_restores_design_view() { for language in ["en", "de", "ko", "ru"] { let mut h = Harness::new(); h.app.preferences.language = language.into(); + h.app.preferences.perspective_fov = 50f64.to_radians(); h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); h.app.session.mark_saved(); h.frames(3); @@ -1421,6 +1422,7 @@ fn clicked_render_workspace_saves_one_setup_and_restores_design_view() { h.step(&json!({"click":{"handle":"render:scene:frame"}})).unwrap(); assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Camera); h.step(&json!({"widget":perspective})).unwrap(); + assert_eq!(h.app.cam.fov, 50f64.to_radians(), "{language}: Perspective takes the Field of view preference's angle (#5364)"); assert!(!h.app.session.is_dirty(), "preview edits are staged"); h.step(&json!({"widget":save})).unwrap(); assert_eq!(h.app.session.undo.len(), undo + 1); @@ -6380,3 +6382,28 @@ fn geometry_budget_change_retries_cached_admission_without_document_changes() { assert_eq!(state.preview_upload_bytes, Some(bytes as usize)); assert!(state.scene_error.is_none()); } + +/// The Field of view preference (#5364) rescales the design view only: navigating the result image +/// turns Perspective view off and on around it without a rescale, and an angle changed while Render +/// is open leaves Render's camera alone and reaches the design view when it's back. +#[test] +fn the_field_of_view_rescales_only_the_design_view() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.call("ui.set", json!({"perspective": true})); + h.frames(3); + let design = h.app.cam; + let size = |cam: Camera, fov: f64| Camera { fov, ..cam }.half_height(); + enter(&mut h.app, true).unwrap(); + h.frames(2); + with_result_camera(&mut h.app, |app| app.cam.distance *= 1.0); + h.frames(2); + let render = h.app.cam; + h.call("ui.prefs", json!({"perspective_fov": 1.2})); + h.frames(2); + assert_eq!(h.app.cam, render, "Render's camera is its own"); + enter(&mut h.app, false).unwrap(); + h.frames(2); + 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); +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index fc813273d..6bac2b54c 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -482,7 +482,7 @@ pub fn projection(app: &SolveApp, rect: Rect) -> Proj { let mut cam = app.cam; // Render owns an explicit product camera, including its saved/custom FOV. if !crate::render_workspace::active(app) { - cam.fov = if app.perspective_view() { 0.6 } else { 0.0 }; + cam.fov = app.view_fov(); } let aspect = rect.width() as f64 / rect.height().max(1.0) as f64; Proj { cam, vp: cam.view_proj_bounds(aspect, &scene_bounds(app)), rect } @@ -2233,7 +2233,7 @@ pub(crate) fn pick_cached(app: &mut SolveApp, proj: &Proj, pos: Pos2) -> Vec Option { - fit_with_fov(cam, bounds, layout, if perspective { 0.6 } else { 0.0 }) -} - /// Product cameras keep the authored lens while framing the free canvas. pub(crate) fn fit_product_bounds(cam: Camera, bounds: &Aabb3, layout: &Layout) -> Option { - fit_with_fov(cam, bounds, layout, cam.fov) + fit_bounds(cam, bounds, layout, cam.fov) } -fn fit_with_fov(mut cam: Camera, bounds: &Aabb3, layout: &Layout, fov: f64) -> Option { +pub(crate) fn fit_bounds(mut cam: Camera, bounds: &Aabb3, layout: &Layout, fov: f64) -> Option { let perspective = fov > 0.0; if !fov.is_finite() || !(0.0..std::f64::consts::PI).contains(&fov) { return None; diff --git a/crates/ui-egui/src/viewport_layout_tests.rs b/crates/ui-egui/src/viewport_layout_tests.rs index b09c5fbef..c9efd7937 100644 --- a/crates/ui-egui/src/viewport_layout_tests.rs +++ b/crates/ui-egui/src/viewport_layout_tests.rs @@ -64,16 +64,17 @@ fn thin_rotated_bounds_fit_using_the_original_full_projection() { assert!(layout.axis_view.is_positive() && layout.navigation.is_positive(), "{layout:?}"); assert!(!layout.drawable.intersect(dock).is_positive()); assert!(!layout.axis_view.intersect(layout.navigation).is_positive()); - for perspective in [false, true] { + // Parallel, the default angle, and the ends of the Field of view preference (#5364). + for fov in [0.0, 0.6, 15f64.to_radians(), 90f64.to_radians()] { for view in [StandardView::Top, StandardView::Iso, StandardView::Right] { let mut cam = Camera::default(); cam.set_view(view); let bounds = Aabb3 { min: Vec3::new(-30.0, -1.0, -2.0), max: Vec3::new(70.0, 2.0, 3.0) }; - let fit = fit_bounds(cam, &bounds, &layout, perspective).unwrap(); + let fit = fit_bounds(cam, &bounds, &layout, fov).unwrap(); assert_eq!((cam.yaw, cam.pitch, cam.up), (fit.yaw, fit.pitch, fit.up)); - assert_eq!(fit_bounds(fit, &bounds, &layout, perspective).unwrap(), fit); + assert_eq!(fit_bounds(fit, &bounds, &layout, fov).unwrap(), fit); let mut effective = fit; - effective.fov = if perspective { 0.6 } else { 0.0 }; + effective.fov = fov; let radius = (bounds.diagonal() * 0.5 + bounds.center().dist(fit.target)).max(effective.half_height() * 2.0).max(10.0); for x in [bounds.min.x, bounds.max.x] { for y in [bounds.min.y, bounds.max.y] { @@ -148,9 +149,9 @@ fn measured_palette_fit_exposes_endpoints_and_layout_changes_preserve_manual_vie fn hostile_or_empty_fit_keeps_the_existing_camera_valid() { let cam = Camera::default(); let measured = layout(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)), &[], 1.0, crate::prefs::NavigatorStyle::Axes, true); - assert!(fit_bounds(cam, &Aabb3::EMPTY, &measured, false).is_none()); + assert!(fit_bounds(cam, &Aabb3::EMPTY, &measured, 0.0).is_none()); let bad = Aabb3 { min: Vec3::new(f64::NAN, 0.0, 0.0), max: Vec3::new(1.0, 1.0, 1.0) }; - assert!(fit_bounds(cam, &bad, &measured, true).is_none()); + assert!(fit_bounds(cam, &bad, &measured, 0.6).is_none()); let mut app = crate::SolveApp::new(Default::default(), Default::default()); let tiny = layout(Rect::from_min_size(pos2(0.0, 0.0), vec2(5.0, 5.0)), &[], 1.0, crate::prefs::NavigatorStyle::Axes, true); app.viewport.layout = Some(tiny); diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index 3e3748b9e..775e38908 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -160,6 +160,10 @@ Preferences (File › Preferences) hold the theme, workspace layout, the units o visual style and autosave. Graphics › Colour vision gives the colours that carry a meaning (sketch states, axes, bends, analyses, icons) values for a weak red, green or blue sense: Protan, Deutan or Tritan. In a mode, the faces Draft and Accessibility Analysis mark as failing are striped too. +Graphics › Viewport › **Perspective view** draws the view with perspective, and its **Field of view** +(15° to 90°, about 34° by default) sets how strong the perspective is. The model keeps its size in the +view when the angle changes: a wider angle brings the camera closer. A sketch you are editing is always +drawn without perspective. Command messages and errors show for a few seconds in the status chip at the bottom left of the view. Click the chip, or choose Help › **Messages…**, for every message of the session: newest first, errors in red, each line selectable, with **Copy all** for a bug report. Help › Keyboard Shortcuts lists every key, and File › Keyboard Shortcuts changes them. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b6946cc79..d2146e14e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -326,7 +326,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox. | `ui.inspect` | — | UI state, pending file picker (`file_picker_busy`; compatibility alias `file_dialog_open`, no path), what is hidden (`visibility`: bodies, origin and construction items, sketches, joints (`hidden_joints`, joint ids); set it with the `browser.visibility` command), viewport rect, camera, active tool/dialog, the status line (`status`: text and whether it is an error), hover, renderer, timings, what the GPU drew last frame (`draw`: `draw_calls`, `triangles`, `line_segments`, `supersampled`; null without a GPU) and the graphics `adapter`, live preview (`active`, `busy`, `error`, `ms`, bodies it stands in for) | | `ui.set` | any `UiState` field (`tab`, `perspective`, `showGrid`, `dark`, `layout`, …), and the browser's view of the design, saved with it: `showOrigin` (the Origin folder's eye), `showSketches` (the design's Sketches folder, `c0/sketches` in `hiddenFolders`), `hiddenBodies`, `hiddenOrigin`, `hiddenSketches`, `shownSketches`, `hiddenJoints`, `hiddenFolders`, `hiddenProfiles`, `shownDims`, `lockedBodies` (whole lists; `browser.visibility` changes single items) | `dark: false` switches to the light theme; `layout: "floating"` (default) or `"compact"` (`"docked"` is also accepted) selects the transient shell layout without saving a preference. Scenarios use `{"call":"ui.set","params":{"layout":"docked"}}` | | `ui.view` | `view`: `front`, `back`, `top`, `bottom`, `left`, `right`, `iso`, `home`, `fit`; `animate` (bool, default false: snap) | | -| `ui.camera` | `target?`: `[x, y, z]` (mm), `yaw?`, `pitch?`, `roll?` (radians), `distance?` (mm), `fov?`, `up?`; `fit?`: `true`, `false` or `[occurrence id or name…]` (`root`: the bodies outside every component) | the viewport's orbit camera: it looks at `target` from `distance` away; `yaw` 0 looks along +Y (from the front), `pitch` is the elevation (±π/2: straight down or up), `roll` turns the image. Fields given are set first (the others keep their values), then `fit` frames the listed occurrences (or everything), keeping the direction. The reply, passed back, sets the same view again, so a framing can be stored and replayed. `fov` and `up` follow the perspective setting (`ui.set`) and the up axis preference (`ui.prefs`) and can't change here; a refused field changes nothing | +| `ui.camera` | `target?`: `[x, y, z]` (mm), `yaw?`, `pitch?`, `roll?` (radians), `distance?` (mm), `fov?`, `up?`; `fit?`: `true`, `false` or `[occurrence id or name…]` (`root`: the bodies outside every component) | the viewport's orbit camera: it looks at `target` from `distance` away; `yaw` 0 looks along +Y (from the front), `pitch` is the elevation (±π/2: straight down or up), `roll` turns the image. Fields given are set first (the others keep their values), then `fit` frames the listed occurrences (or everything), keeping the direction. The reply, passed back, sets the same view again, so a framing can be stored and replayed. `fov` is the angle the view is drawn with: 0 (parallel) with Perspective view off or while a sketch is open, else `perspective_fov`; in Render, the Render camera's own. `fov` and `up` follow the perspective setting (`ui.set`), its angle (`ui.prefs {perspective_fov}`) and the up axis preference (`ui.prefs`) and can't change here; a refused field changes nothing | | `ui.start` | `command`, `params?` | like a toolbar click: starts the sketch tool or dialog for the command. `params` sets what the dialog opens on, and nothing runs until OK: `joint.drive` takes `joint` (id or name; without it, the joint picked in the browser, else the first joint that moves; a rigid joint opens to say why it has nothing to drive, with an Edit Joint button, handle `drive:edit_joint`) and `values` (numbers in degrees or millimetres, or expressions); `motion.study` takes `study` (id or name), which opens that study to edit and chart. A command that takes no params is refused before it starts; a param the dialog doesn't take is refused and the dialog closes | | `ui.click` | `x`, `y` (screen points), `button?`: left/right/middle, `shift?`, `ctrl?`, `double?` | real pointer input | | `ui.move` | `x`, `y`, `shift?`, `alt?`, `ctrl?`, `cmd?` | pointer movement without a button; modifiers apply until the next synthetic move/click; a move with omitted modifiers releases them. With `nav: "touchpad"`, Shift pans and Alt/Option orbits. | @@ -412,6 +412,7 @@ One setting per line, sorted by name. A change that adds a setting adds its own - `origin_plane_names` (`xyz` (default) or `top_front_right`: the browser, dialogs and lists call the origin planes Top, Front and Right; their ids, commands and saved designs keep XY, XZ and YZ) - `pan_reverse_x` (default false: horizontal scrolling pans the other way) - `pan_reverse_y` (default false: vertical scrolling pans the other way) +- `perspective_fov` (Perspective view's vertical field of view in radians, 0.2618…1.5708 (15°…90°), default 0.6; when it changes, the camera's distance scales so the view keeps its size) - `placement_handles` (default false: handles on the preview of a Rest, Boss or Snap Fit that move it across the model and turn it) - `right_drag_orbits` (default true; false: a right drag the mouse preset would orbit leaves the camera alone, #6492) - `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle)