diff --git a/crates/engine/src/camera_cmds.rs b/crates/engine/src/camera_cmds.rs index 9c44c06e5..8eb3f72f3 100644 --- a/crates/engine/src/camera_cmds.rs +++ b/crates/engine/src/camera_cmds.rs @@ -37,6 +37,23 @@ pub fn specs() -> Vec { cmd!("camera.bookmark7", "Go to camera 7", ["Viewport"], Some("Ctrl+7"), "{}", always, |s, _| bookmark(s, 6)), cmd!("camera.bookmark8", "Go to camera 8", ["Viewport"], Some("Ctrl+8"), "{}", always, |s, _| bookmark(s, 7)), cmd!("camera.bookmark9", "Go to camera 9", ["Viewport"], Some("Ctrl+9"), "{}", always, |s, _| bookmark(s, 8)), + cmd!( + "camera.view", + "Fixed view", + [], + None, + "{view: front|back|left|right|top|bottom} → the camera (looks at the mesh from that side and frames it; the projection stays)", + always, + |s, p| fixed_view(s, strp(p, "view").ok_or_else(|| bad("camera.view", "`view` is required"))?) + ), + cmd!("camera.view.front", "Front view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "front")), + cmd!("camera.view.back", "Back view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "back")), + cmd!("camera.view.left", "Left view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "left")), + cmd!("camera.view.right", "Right view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "right")), + cmd!("camera.view.top", "Top view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "top")), + cmd!("camera.view.bottom", "Bottom view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "bottom")), + cmd!("camera.perspective", "Perspective", ["Viewport"], Some("F5"), "{}", always, |s, _| projection(s, false)), + cmd!("camera.orthographic", "Orthographic", ["Viewport"], Some("F6"), "{}", always, |s, _| projection(s, true)), cmd!("viewport.focusAt", "Focus depth of field here", [], None, "{x, y (viewport pixels), viewport?: [w, h]}", always, focus_at), ] } @@ -141,6 +158,31 @@ fn select(s: &mut Session, p: &Value) -> Result { Ok(crate::view_cmds::camera_json(s)) } +/// The fixed views: name, yaw and pitch in degrees. Yaw 0 puts the eye on +Z (the front), yaw 90 +/// on +X (the right side); top and bottom stop at the orbit's ±89° pitch limit. +pub const VIEWS: [(&str, f32, f32); 6] = + [("front", 0.0, 0.0), ("back", 180.0, 0.0), ("left", -90.0, 0.0), ("right", 90.0, 0.0), ("top", 0.0, 89.0), ("bottom", 0.0, -89.0)]; + +/// Look at the mesh from fixed view `name` and frame it, keeping the projection. The yaw is the +/// one nearest the current yaw, so the desktop UI's glide takes the short way round. +fn fixed_view(s: &mut Session, name: &str) -> Result { + let Some(&(_, yaw, pitch)) = VIEWS.iter().find(|(view, ..)| *view == name) else { + return Err(bad("camera.view", format!("unknown view `{name}`: one of front, back, left, right, top, bottom"))); + }; + let current = if s.camera.yaw.is_finite() { s.camera.yaw } else { 0.0 }; + let turn = std::f32::consts::TAU; + s.camera.yaw = current + (yaw.to_radians() - current + turn * 0.5).rem_euclid(turn) - turn * 0.5; + s.camera.pitch = pitch.to_radians(); + crate::execute(s, "viewport.frame", &Value::Null) +} + +/// Switch to a perspective or orthographic projection; position and rotation stay. +fn projection(s: &mut Session, ortho: bool) -> Result { + s.camera.ortho = ortho; + s.revision = s.revision.wrapping_add(1); + Ok(crate::view_cmds::camera_json(s)) +} + /// Shortcut slot `slot` (0-based): the n-th saved camera, in list order. fn bookmark(s: &mut Session, slot: usize) -> Result { if slot >= s.doc.project.cameras.len() { @@ -238,6 +280,72 @@ mod tests { assert!(ids.iter().all(|c| c.shortcut.is_some())); } + #[test] + fn fixed_views_look_from_their_side_frame_the_mesh_and_keep_the_projection() { + let mut s = session(); + execute(&mut s, "camera.set", &json!({"yaw": 37, "pitch": 21, "distance": 9, "target": [0.4, -0.3, 0.2]})).unwrap(); + let (lo, hi) = s.mesh.bounds(); + let mut framed = s.camera; + framed.frame(lo, hi); + let sides = [("front", Vec3::Z), ("back", Vec3::NEG_Z), ("left", Vec3::NEG_X), ("right", Vec3::X), ("top", Vec3::Y), ("bottom", Vec3::NEG_Y)]; + for ortho in [false, true] { + execute(&mut s, "camera.set", &json!({"ortho": ortho})).unwrap(); + for (view, side) in sides { + // Through the parameterized command and through the menu command alike + let menu_id = format!("camera.view.{view}"); + for (id, params) in [("camera.view", json!({"view": view})), (menu_id.as_str(), Value::Null)] { + execute(&mut s, "camera.orbit", &json!({"dx": 123, "dy": 17})).unwrap(); + let back = execute(&mut s, id, ¶ms).unwrap(); + let looking_from = (s.camera.eye() - s.camera.target).normalize(); + assert!(looking_from.dot(side) > 0.999, "{id} {view}: the eye is on the {side} side, not at {looking_from}"); + assert_eq!(s.camera.ortho, ortho, "{id} {view} keeps the projection"); + assert!((s.camera.target - framed.target).length() < 1e-5, "{view} centres the mesh"); + assert!((s.camera.distance - framed.distance).abs() < 1e-4, "{view} frames the mesh"); + assert_eq!(back["ortho"], ortho); + } + } + } + // Orbit still works from a fixed view, and a view is not an undo step. + let steps = s.history_labels().len(); + execute(&mut s, "camera.view.top", &Value::Null).unwrap(); + assert!((s.camera.pitch - 89f32.to_radians()).abs() < 1e-6, "top stops at the orbit limit"); + execute(&mut s, "camera.orbit", &json!({"dx": 30, "dy": -40})).unwrap(); + assert!((s.camera.pitch - 49f32.to_radians()).abs() < 1e-5 && s.camera.yaw.to_degrees().rem_euclid(360.0) > 1.0); + assert_eq!(s.history_labels().len(), steps); + } + + #[test] + fn fixed_views_take_the_nearest_turn_and_reject_unknown_views() { + let mut s = session(); + execute(&mut s, "camera.set", &json!({"yaw": 715})).unwrap(); + execute(&mut s, "camera.view", &json!({"view": "front"})).unwrap(); + assert!((s.camera.yaw - 720f32.to_radians()).abs() < 1e-4, "two whole turns, not a spin back to 0: {}", s.camera.yaw.to_degrees()); + let before = s.camera; + assert!(execute(&mut s, "camera.view", &json!({"view": "sideways"})).is_err()); + assert!(execute(&mut s, "camera.view", &json!({})).is_err(), "`view` is required"); + assert!(execute(&mut s, "camera.view", &json!({"view": 3})).is_err()); + assert_eq!(s.camera, before, "a rejected view leaves the camera"); + let menu: Vec<_> = crate::command_specs().iter().filter(|c| c.id.starts_with("camera.view.")).collect(); + assert_eq!(menu.len(), 6); + assert!(menu.iter().all(|c| c.shortcut.is_none() && c.menu == ["Viewport"]), "no default keys: users bind their own"); + } + + #[test] + fn perspective_and_orthographic_change_only_the_projection() { + let mut s = session(); + execute(&mut s, "camera.set", &json!({"yaw": 30, "pitch": 10, "distance": 4})).unwrap(); + let before = s.camera; + let r = execute(&mut s, "camera.orthographic", &Value::Null).unwrap(); + assert!(s.camera.ortho && r["ortho"] == true); + assert_eq!(OrbitCamera { ortho: false, ..s.camera }, before, "position and rotation stay"); + execute(&mut s, "camera.orthographic", &Value::Null).unwrap(); + assert!(s.camera.ortho, "a second press keeps it orthographic: two actions, not a toggle"); + execute(&mut s, "camera.perspective", &Value::Null).unwrap(); + assert_eq!(s.camera, before); + let key = |id: &str| crate::find(id).and_then(|c| c.shortcut); + assert_eq!((key("camera.perspective"), key("camera.orthographic")), (Some("F5"), Some("F6"))); + } + #[test] fn cameras_round_trip_through_the_project_file() { let mut s = session(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index b95788d37..d156ee6d0 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -95,8 +95,15 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: & "command.run" => { let Some(id) = p.get("id").and_then(Value::as_str) else { return err("`id` is required") }; let params = p.get("params").cloned().unwrap_or(Value::Null); + let before = app.session.camera; match texturecraft_engine::execute(&mut app.session, id, ¶ms) { - Ok(v) => ok(v), + Ok(v) => { + // A command that moved the camera takes over from a glide in progress, which would put it back + if app.session.camera != before { + app.camera_glide = None; + } + ok(v) + } Err(e) => err(e), } } diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 6129dbc72..1081c8f92 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -529,10 +529,11 @@ mod tests { #[test] fn a_stored_shortcut_replaces_the_default_and_an_empty_one_unbinds() { let mut keymap = Keymap::new(); - keymap.insert("file.save".into(), "F5".into()); + // F7 is bound to nothing else, so the stored shortcut alone decides (F5 is Perspective) + keymap.insert("file.save".into(), "F7".into()); keymap.insert("edit.undo".into(), String::new()); let resolved = bindings_for(&keymap); - assert_eq!(resolved.command_of(&press(Key::F5, Modifiers::NONE)).as_deref(), Some("file.save")); + assert_eq!(resolved.command_of(&press(Key::F7, Modifiers::NONE)).as_deref(), Some("file.save")); assert_eq!(resolved.command_of(&press(Key::S, Modifiers::COMMAND)), None); assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND)), None); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 74d925807..17bafe909 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -132,6 +132,8 @@ pub struct TextureCraftApp { pub session: Session, /// A smooth move to a saved camera in progress. camera_glide: Option, + /// Yaw and pitch an Alt+Shift drag has reached before snapping to 90° steps (see `viewport`). + orbit_snap: Option<(f32, f32)>, pub ui: UiState, /// Where `ui` is saved between runs ui_store: ui_state_store::UiStateStore, @@ -225,6 +227,7 @@ impl TextureCraftApp { let mut app = TextureCraftApp { camera_glide: None, + orbit_snap: None, session, ui, ui_store, @@ -295,17 +298,31 @@ impl TextureCraftApp { pub fn run(&mut self, id: &str, params: Value) -> Option { self.ui.prefs.apply_resource_limits(); - // Going to a saved camera glides there; the control channel and CLI jump straight away - let glide_from = (id.starts_with("camera.select") || id.starts_with("camera.bookmark")).then_some(self.session.camera); + // Going to a saved camera or a fixed view glides there; the control channel and CLI jump straight away + let glides = id.starts_with("camera.select") || id.starts_with("camera.bookmark") || id.starts_with("camera.view"); + let glide_from = glides.then_some(self.session.camera); match texturecraft_engine::execute(&mut self.session, id, ¶ms) { Ok(v) => { // A pending dialog must not import its old source into the replacement project if matches!(id, "file.open" | "file.close" | "project.new" | "project.sample") { self.pbr_import = None; } - if let Some(from) = glide_from.filter(|f| *f != self.session.camera) { - self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time }); - self.session.camera = from; + match glide_from { + Some(from) if from != self.session.camera => { + self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time }); + self.session.camera = from; + } + // Already at the destination: drop a glide an earlier command in the same frame started + Some(_) => self.camera_glide = None, + None => {} + } + + // The glide would put back the projection it recorded, so it follows the switch + if matches!(id, "camera.perspective" | "camera.orthographic") + && let Some(glide) = &mut self.camera_glide + { + glide.from.ortho = self.session.camera.ortho; + glide.to.ortho = self.session.camera.ortho; } Some(v) } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9c66fd45a..2506ed356 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -88,6 +88,15 @@ pub const CATALOG: &[Item] = &[ it("Viewport", "UV checker", "ui.uvChecker", None), sep("Viewport"), it("Viewport", "Show entire mesh", "viewport.frame", Some("F")), + it("Viewport", "Front view", "camera.view.front", None), + it("Viewport", "Back view", "camera.view.back", None), + it("Viewport", "Left view", "camera.view.left", None), + it("Viewport", "Right view", "camera.view.right", None), + it("Viewport", "Top view", "camera.view.top", None), + it("Viewport", "Bottom view", "camera.view.bottom", None), + sep("Viewport"), + it("Viewport", "Perspective", "camera.perspective", Some("F5")), + it("Viewport", "Orthographic", "camera.orthographic", Some("F6")), sep("Viewport"), it("Viewport", "3D/2D views", "ui.layout.split", Some("F1")), it("Viewport", "3D view only", "ui.layout.3d", Some("F2")), @@ -256,6 +265,8 @@ fn menu_item(app: &mut TextureCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, "ui.mode.paint" => Some(app.ui.mode == Mode::Painting), "ui.mode.bake" => Some(app.ui.mode == Mode::Baking), "ui.mode.render" => Some(app.ui.mode == Mode::Rendering), + "camera.perspective" => Some(!app.session.camera.ortho), + "camera.orthographic" => Some(app.session.camera.ortho), id => crate::docking::view_panel(id).map(|p| app.ui.dock.is_open(p)), }; if let Some(c) = checked { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index d7030d9ce..05d5a14db 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -546,6 +546,19 @@ const MAX_STENCIL_SCALE: f32 = 10.0; /// Smallest viewport the camera projects into, so a collapsed view keeps a usable aspect (points) const MIN_CAMERA_VIEWPORT: f32 = 16.0; +/// Alt+Shift+left drag: orbit in 90° steps. The drag's own yaw and pitch follow the pointer; the +/// camera takes the nearest step, with the pitch held inside the orbit's ±89° limit. +fn snapped_orbit(app: &mut TextureCraftApp, delta: egui::Vec2) { + let step = std::f32::consts::FRAC_PI_2; + let limit = 89f32.to_radians(); + let camera = &mut app.session.camera; + let (yaw, pitch) = app.orbit_snap.get_or_insert((camera.yaw, camera.pitch)); + *yaw -= delta.x * ORBIT_RADIANS_PER_POINT; + *pitch = (*pitch + delta.y * ORBIT_RADIANS_PER_POINT).clamp(-step, step); + camera.yaw = (*yaw / step).round() * step; + camera.pitch = ((*pitch / step).round() * step).clamp(-limit, limit); +} + fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { let response = ui.interact(rect, ui.scope_id().with("view3d"), Sense::click_and_drag()); app.viewport_rect = rect; @@ -566,10 +579,18 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if stencil_drag || adjusting { // The stencil or the brush changes instead of the camera } else if response.dragged_by(PointerButton::Middle) { + app.camera_glide = None; app.session.camera.pan(delta.x / size.y, delta.y / size.y); } else if alt && response.dragged_by(PointerButton::Primary) { - app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT); + // Navigating takes over from a glide in progress, which would put the camera back + app.camera_glide = None; + if shift { + snapped_orbit(app, delta); + } else { + app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT); + } } else if response.dragged_by(PointerButton::Secondary) { + app.camera_glide = None; if alt { app.session.camera.zoom(-delta.y * DRAG_ZOOM_PER_POINT); } else if shift { @@ -580,6 +601,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } + // The next snapping drag starts again from where the camera is + if !(alt && shift && response.dragged_by(PointerButton::Primary)) { + app.orbit_snap = None; + } + if response.hovered() { let scroll = ui.input(|input| input.smooth_scroll_delta.y); if scroll != 0.0 { @@ -590,6 +616,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } } else { + app.camera_glide = None; app.session.camera.zoom(scroll * WHEEL_ZOOM_PER_POINT); } } @@ -602,6 +629,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.session.cancel_stroke(); } + app.camera_glide = None; let moved = gesture.translation_delta; if gesture.num_touches >= 3 { app.session.camera.pan(moved.x / size.y, moved.y / size.y); diff --git a/crates/ui-egui/tests/it/camera_views.rs b/crates/ui-egui/tests/it/camera_views.rs new file mode 100644 index 000000000..ebbbbbb93 --- /dev/null +++ b/crates/ui-egui/tests/it/camera_views.rs @@ -0,0 +1,230 @@ +//! F5 and F6 switch the projection, the Viewport menu goes to fixed views, and Alt+Shift+drag orbits +//! in 90° steps. + +use std::f32::consts::FRAC_PI_2; + +use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; +use serde_json::json; +use texturecraft_ui_egui::TextureCraftApp; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +fn press(h: &mut Harness<'_, TextureCraftApp>, key: Key) { + h.event(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// Drag with the left button and `modifiers` from `from` by `by` in a few moves. +fn drag(h: &mut Harness<'_, TextureCraftApp>, from: Pos2, by: egui::Vec2, modifiers: Modifiers) { + h.event(Event::ModifiersChanged(modifiers)); + h.hover_at(from); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }); + h.run_steps(2); + for k in 1..=4 { + h.hover_at(from + by * (k as f32 / 4.0)); + h.run_steps(1); + } + h.event(Event::PointerButton { pos: from + by, button: PointerButton::Primary, pressed: false, modifiers }); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(3); +} + +#[test] +fn f6_switches_to_orthographic_and_f5_back_to_perspective_keeping_the_view() { + let mut h = harness(); + h.state_mut().run("camera.set", json!({"yaw": 30, "pitch": 15})); + h.run_steps(2); + let before = h.state().session.camera; + assert!(!before.ortho); + press(&mut h, Key::F6); + let camera = h.state().session.camera; + assert!(camera.ortho, "F6 is orthographic"); + assert_eq!((camera.yaw, camera.pitch, camera.distance, camera.target), (before.yaw, before.pitch, before.distance, before.target)); + press(&mut h, Key::F6); + assert!(h.state().session.camera.ortho, "F6 again stays orthographic: not a toggle"); + press(&mut h, Key::F5); + assert_eq!(h.state().session.camera, before, "F5 is perspective"); +} + +#[test] +fn the_viewport_menu_goes_to_the_front_view_and_orbit_works_afterwards() { + let mut h = harness(); + h.state_mut().run("camera.set", json!({"yaw": 70, "pitch": 30, "ortho": true})); + h.run_steps(2); + // The menu bar's "Viewport", above the dock's tab of the same name + h.get_all_by_label("Viewport").min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap().click(); + h.run_steps(2); + h.get_by_label_contains("Front view").click(); + // The UI glides there over about a third of a second + h.run_steps(6); + let camera = h.state().session.camera; + let looking_from = (camera.eye() - camera.target).normalize(); + assert!(looking_from.z > 0.999, "the eye is in front of the mesh: {looking_from}"); + assert!(camera.ortho, "the projection stays"); + + let center = h.state().viewport_rect.center(); + drag(&mut h, center, vec2(60.0, 30.0), Modifiers::ALT); + let orbited = h.state().session.camera; + assert!(orbited.yaw != camera.yaw && orbited.pitch != camera.pitch, "Alt+drag still orbits"); +} + +#[test] +fn alt_shift_drag_orbits_in_quarter_turns() { + let mut h = harness(); + h.state_mut().run("camera.set", json!({"yaw": 17, "pitch": 11})); + h.run_steps(2); + let center = h.state().viewport_rect.center(); + let at_step = |angle: f32, steps: f32| (angle - steps * FRAC_PI_2).abs() < 1e-5; + + // A short drag stays at the nearest quarter turn: straight on, level + drag(&mut h, center, vec2(10.0, 5.0), Modifiers::ALT | Modifiers::SHIFT); + let camera = h.state().session.camera; + assert!(at_step(camera.yaw, 0.0) && at_step(camera.pitch, 0.0), "yaw {} pitch {}", camera.yaw.to_degrees(), camera.pitch.to_degrees()); + + // A long drag to the left turns a quarter: the eye moves to the right side + drag(&mut h, center, vec2(-200.0, 0.0), Modifiers::ALT | Modifiers::SHIFT); + let camera = h.state().session.camera; + assert!(at_step(camera.yaw, 1.0) && at_step(camera.pitch, 0.0), "yaw {} pitch {}", camera.yaw.to_degrees(), camera.pitch.to_degrees()); + + // Dragging down far enough looks from above, at the orbit's 89° limit + drag(&mut h, center, vec2(0.0, 200.0), Modifiers::ALT | Modifiers::SHIFT); + let camera = h.state().session.camera; + assert!(at_step(camera.yaw, 1.0) && (camera.pitch - 89f32.to_radians()).abs() < 1e-5, "pitch {}", camera.pitch.to_degrees()); +} + +/// A harness whose frames are 10 ms apart, so a 0.35 s glide spans about 35 frames and a drag fits inside it. +fn slow_glide_harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_step_dt(0.01).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +/// Start the glide to the front view from a turned camera. +fn start_front_glide(h: &mut Harness<'_, TextureCraftApp>) { + h.state_mut().run("camera.set", json!({"yaw": 70, "pitch": 30})); + h.run_steps(2); + h.state_mut().run("camera.view.front", json!({})); + h.run_steps(2); +} + +#[test] +fn f6_during_a_glide_keeps_the_orthographic_projection_when_the_glide_ends() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + assert!(!h.state().session.camera.ortho); + press(&mut h, Key::F6); + h.run_steps(60); + let camera = h.state().session.camera; + let looking_from = (camera.eye() - camera.target).normalize(); + assert!(looking_from.z > 0.999, "the glide still reaches the front view: {looking_from}"); + assert!(camera.ortho, "F6 pressed during the glide is not undone when it ends"); + + // And back: F5 during a glide to a view of an orthographic camera + start_front_glide(&mut h); + press(&mut h, Key::F5); + h.run_steps(60); + assert!(!h.state().session.camera.ortho, "F5 pressed during the glide is not undone either"); +} + +#[test] +fn a_view_that_returns_to_the_starting_camera_cancels_the_glide_of_the_earlier_view() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + h.run_steps(60); + // Back, then Front again before a frame runs: the camera is already at the front + h.state_mut().run("camera.view.back", json!({})); + h.state_mut().run("camera.view.front", json!({})); + h.run_steps(60); + let camera = h.state().session.camera; + let looking_from = (camera.eye() - camera.target).normalize(); + assert!(looking_from.z > 0.999, "the camera stays at the front instead of gliding to the back: {looking_from}"); +} + +#[test] +fn a_camera_command_from_the_control_channel_during_a_glide_is_not_overwritten_by_it() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + let context = h.ctx.clone(); + let reply = texturecraft_ui_egui::control::handle(h.state_mut(), &context, "command.run", &json!({"id": "camera.set", "params": {"yaw": 20, "pitch": 10}})); + assert_eq!(reply["ok"], true, "{reply}"); + h.run_steps(60); + let camera = h.state().session.camera; + assert!( + (camera.yaw.to_degrees() - 20.0).abs() < 1e-3 && (camera.pitch.to_degrees() - 10.0).abs() < 1e-3, + "yaw {} pitch {}", + camera.yaw.to_degrees(), + camera.pitch.to_degrees() + ); +} + +#[test] +fn a_control_command_that_leaves_the_camera_alone_does_not_stop_the_glide() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + let context = h.ctx.clone(); + let reply = texturecraft_ui_egui::control::handle(h.state_mut(), &context, "command.run", &json!({"id": "camera.get", "params": {}})); + assert_eq!(reply["ok"], true, "{reply}"); + h.run_steps(60); + let camera = h.state().session.camera; + let looking_from = (camera.eye() - camera.target).normalize(); + assert!(looking_from.z > 0.999, "the glide still reaches the front view: {looking_from}"); +} + +#[test] +fn alt_shift_drag_during_a_glide_is_not_overwritten_by_it() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + let center = h.state().viewport_rect.center(); + drag(&mut h, center, vec2(-100.0, 0.0), Modifiers::ALT | Modifiers::SHIFT); + h.run_steps(60); + let camera = h.state().session.camera; + assert!( + (camera.yaw - FRAC_PI_2).abs() < 1e-5 && camera.pitch.abs() < 1e-5, + "the snapped orbit stays: yaw {} pitch {}", + camera.yaw.to_degrees(), + camera.pitch.to_degrees() + ); +} + +#[test] +fn alt_drag_during_a_glide_is_not_overwritten_by_it() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + let center = h.state().viewport_rect.center(); + drag(&mut h, center, vec2(-200.0, 0.0), Modifiers::ALT); + h.run_steps(60); + let camera = h.state().session.camera; + // The glide ends at yaw 0 and pitch 0; the drag turned the camera away from the front by far more than a degree + assert!(camera.yaw.abs() > 0.1, "the orbit stays: yaw {}", camera.yaw.to_degrees()); +} + +#[test] +fn the_wheel_during_a_glide_is_not_overwritten_by_it() { + let end_distance = |scroll: f32| { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + let center = h.state().viewport_rect.center(); + h.hover_at(center); + h.run_steps(1); + if scroll != 0.0 { + h.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, scroll), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: Modifiers::NONE, + }); + } + h.run_steps(80); + h.state().session.camera.distance + }; + assert!(end_distance(100.0) != end_distance(0.0), "the wheel zoom stays"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 4f4543043..c5d348b08 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -5,6 +5,7 @@ mod bake_job_mesh; mod bake_mode; mod brush_drag; mod brush_section_reset; +mod camera_views; mod close_unsaved; mod color_picker; mod color_selection_editor; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 98272ddc5..9e5c59f50 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -378,6 +378,15 @@ is at), `camera.select {index? | name?}` restores one, `camera.rename {index? | go to the first nine. Commands jump straight to the view; the desktop UI glides there over about a third of a second. +## Camera views and projection + +`camera.view {view}` looks at the mesh from one side (`front` from +Z, `back`, `left` from -X, +`right`, `top` and `bottom` at the orbit's ±89° pitch limit) and frames it; the projection stays. +`camera.view.front` … `camera.view.bottom` do the same without params (Viewport menu, no default +shortcut, bindable in Settings ▸ Keyboard). `camera.perspective` (F5) and `camera.orthographic` (F6) +change only the projection; position and rotation stay. None of them is an undo step. In the 3D +view, Alt+Shift+left drag orbits in 90° steps. + ## MaterialCraft materials A `.mcmat` portable material (MaterialCraft's format, read here by `formats::mcmat`; the manifest is diff --git a/docs/features.md b/docs/features.md index 139d6a27f..599953b6a 100644 --- a/docs/features.md +++ b/docs/features.md @@ -135,8 +135,10 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA light, environment importance sampling, displaced geometry, a denoiser and one-click PNG save, traced on the GPU (compute shaders, about 25× the CPU tracer, desktop and WebGPU) or on the CPU. -- View any channel, any baked mesh map, or a UV checker; Alt+drag to orbit, middle-drag to pan, - wheel to zoom, F to frame, M / C / B to cycle views. +- View any channel, any baked mesh map, or a UV checker; Alt+drag to orbit (Alt+Shift+drag in 90° + steps), middle-drag to pan, wheel to zoom, F to frame, M / C / B to cycle views. +- **Perspective (F5) or orthographic (F6)** projection, and **front, back, left, right, top and + bottom views** that frame the mesh (Viewport menu; bind your own keys in Settings). - **3D and UV wireframes** that show the mesh's own polygons: quads and n-gons from OBJ, FBX, COLLADA, USD, Alembic and PLY files keep their edges, without the triangulation's diagonals. diff --git a/docs/parity.md b/docs/parity.md index 8ef5389af..b34318560 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -2,7 +2,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Each row is a menu item of the target menu layout with TextureCraft's command id; **live** means the id is implemented. Feature parity beyond menus is tracked in [`ROADMAP.md`](../ROADMAP.md). -**60 of 60 menu items live (100%).** +**68 of 68 menu items live (100%).** ## File @@ -74,6 +74,14 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Display previous mesh map | `viewport.previousMeshMap` | Shift+B | live | | UV checker | `ui.uvChecker` | | live | | Show entire mesh | `viewport.frame` | F | live | +| Front view | `camera.view.front` | | live | +| Back view | `camera.view.back` | | live | +| Left view | `camera.view.left` | | live | +| Right view | `camera.view.right` | | live | +| Top view | `camera.view.top` | | live | +| Bottom view | `camera.view.bottom` | | live | +| Perspective | `camera.perspective` | F5 | live | +| Orthographic | `camera.orthographic` | F6 | live | | 3D/2D views | `ui.layout.split` | F1 | live | | 3D view only | `ui.layout.3d` | F2 | live | | 2D view only | `ui.layout.2d` | F3 | live |