diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index d05b6cad..f828a3c5 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -222,6 +222,9 @@ fn main() { let _ = ui_state_store::FILE.set(file.clone()); } let prefs = saved_prefs(ui_file.as_deref(), persistence_path.as_deref()); + + // The worker pool's size can only be set before its first job + prefs.apply_work_threads(); prefs.apply_resource_limits(); let session = initial_session(&args); let title_bar = TitleBar::decide(prefs.system_title_bar); diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index e390c239..c92c37a3 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -160,6 +160,7 @@ pub fn shade(s: &Session) -> Shade { ViewMode::Channel(c) => (1, c.index() as u32), ViewMode::MeshMap(_) | ViewMode::Mask(_) => (2, 0), ViewMode::UvChecker => (3, 0), + ViewMode::NormalHeightMesh => (4, 0), }; Shade { height_strength: s.doc.project.texture_sets.get(s.ts()).map(|t| t.atlas_height_strength()).unwrap_or(1.0), diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index f8826b44..24ca4107 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -5,6 +5,7 @@ use super::model_patch; use std::collections::BTreeMap; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, OnceLock}; use texturecraft_core::BakePaintTarget; @@ -65,6 +66,8 @@ pub(super) fn specs() -> Vec { type MeshFile = (String, Vec); static GPU_TRACER: OnceLock> = OnceLock::new(); +/// Whether bakes may use the installed GPU tracer (Settings > Enable GPU raytracing). +static GPU_RAYTRACING: AtomicBool = AtomicBool::new(true); /// Cast bake rays with `tracer` (the apps install the render crate's GPU baker at start-up); /// the first call wins. @@ -72,6 +75,17 @@ pub fn install_gpu_tracer(tracer: Arc) { let _ = GPU_TRACER.set(tracer); } +/// Let bakes cast their rays on the installed GPU tracer (`true`, the default) or keep them on +/// the CPU (`false`). Applies to bakes started afterwards. +pub fn set_gpu_raytracing(enabled: bool) { + GPU_RAYTRACING.store(enabled, Ordering::Relaxed); +} + +/// The tracer a bake starting now uses: the installed one while GPU raytracing is on, else none (the CPU) +fn chosen_tracer(installed: Option<&Arc>, enabled: bool) -> Option> { + installed.filter(|_| enabled).cloned() +} + /// A mesh file name made unique among `taken` (and safe as a project file entry). fn unique_name(file_name: &str, taken: &[&str]) -> String { let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh"); @@ -125,7 +139,7 @@ impl Session { let excluded_tiles: Vec<_> = set.uv_tiles.iter().filter(|tile| set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid?.block(*tile)).collect(); let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() }; - let tracer = GPU_TRACER.get().cloned(); + let tracer = chosen_tracer(GPU_TRACER.get(), GPU_RAYTRACING.load(Ordering::Relaxed)); Ok(BakeTask { low_base_color, ts: texture_set, @@ -723,3 +737,32 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { session.update(); Ok(json!({ "baked": sets, "tracer": tracers })) } + +#[cfg(test)] +mod gpu_raytracing_tests { + use super::*; + + struct NamedTracer; + + impl Tracer for NamedTracer { + fn name(&self) -> String { + "gpu".into() + } + + fn scene<'a>( + &'a self, + _: &[texturecraft_bake::tracing::TraceMesh<'a>], + ) -> std::result::Result, texturecraft_bake::BakeError> { + Err(texturecraft_bake::BakeError::Tracer("test tracer".into())) + } + } + + #[test] + fn bakes_use_the_installed_gpu_tracer_only_while_gpu_raytracing_is_on() { + let installed: Arc = Arc::new(NamedTracer); + + assert_eq!(chosen_tracer(Some(&installed), true).map(|tracer| tracer.name()), Some("gpu".to_string())); + assert!(chosen_tracer(Some(&installed), false).is_none(), "off keeps the rays on the CPU"); + assert!(chosen_tracer(None, true).is_none(), "no installed tracer bakes on the CPU"); + } +} diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index bfe9b22c..ef9dc935 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -22,7 +22,7 @@ pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; pub use high_poly_missed::{HIDDEN_HIGH_POLY_VERTEX, high_poly_missed}; pub use merged_high::MergedHigh; -pub use mesh_map_command::{install_gpu_tracer, meshes_json, settings_params}; +pub use mesh_map_command::{install_gpu_tracer, meshes_json, set_gpu_raytracing, settings_params}; pub use model_patch::settings_patch; pub use streamed_bake::StreamedBake; pub use streamed_map::StreamedMap; diff --git a/crates/engine/src/camera_cmds.rs b/crates/engine/src/camera_cmds.rs index 44a9dd48..4c7ab698 100644 --- a/crates/engine/src/camera_cmds.rs +++ b/crates/engine/src/camera_cmds.rs @@ -54,6 +54,52 @@ pub fn specs() -> Vec { 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!( + "camera.rotation", + "Camera rotation", + [], + None, + "{mode: constrained|free} → the camera (constrained keeps the horizon level; free turns the camera about its own axes, so the model can be turned over)", + always, + |s, p| match strp(p, "mode") { + Some("constrained") => rotation(s, false), + Some("free") => rotation(s, true), + _ => Err(bad("camera.rotation", "`mode` is constrained or free")), + } + ), + cmd!("camera.rotation.free", "Free rotation", ["Viewport"], None, "{}", always, |s, _| rotation(s, true)), + cmd!("camera.rotation.constrained", "Constrained rotation", ["Viewport"], None, "{}", always, |s, _| rotation(s, false)), + cmd!( + "camera.snapRotate", + "Camera snap rotate", + [], + None, + "{yaw?, pitch? (whole 90° steps, default 0)} → the camera, turned in steps around the model: the angles first go to the nearest step. The pitch stops at the orbit's ±89° limit. The viewport's gesture for it is Alt+Shift+left drag", + always, + |s, p| snap_rotate(s, f32p(p, "yaw").unwrap_or(0.0), f32p(p, "pitch").unwrap_or(0.0)) + ), + cmd!("camera.snapRotate.left", "Camera snap rotate left", ["Viewport"], None, "{}", always, |s, _| snap_rotate(s, -1.0, 0.0)), + cmd!("camera.snapRotate.right", "Camera snap rotate right", ["Viewport"], None, "{}", always, |s, _| snap_rotate(s, 1.0, 0.0)), + cmd!("camera.snapRotate.up", "Camera snap rotate up", ["Viewport"], None, "{}", always, |s, _| snap_rotate(s, 0.0, 1.0)), + cmd!("camera.snapRotate.down", "Camera snap rotate down", ["Viewport"], None, "{}", always, |s, _| snap_rotate(s, 0.0, -1.0)), + cmd!( + "camera.next", + "Next camera", + ["Viewport"], + None, + "{} → the camera: the next saved camera (after the last, the first; from a view that is no saved camera, the first)", + has_cameras, + |s, _| step_camera(s, 1) + ), + cmd!( + "camera.previous", + "Previous camera", + ["Viewport"], + None, + "{} → the camera: the previous saved camera (before the first, the last; from a view that is no saved camera, the last)", + has_cameras, + |s, _| step_camera(s, -1) + ), cmd!("viewport.focusAt", "Focus depth of field here", [], None, "{x, y (viewport pixels), viewport?: [w, h]}", always, focus_at), ] } @@ -80,6 +126,9 @@ fn apply(view: &mut OrbitCamera, c: &Camera) { view.distance = ok(c.distance).map_or(view.distance, |d| d.clamp(r * 0.05, r * 200.0)); view.fov = ok(c.fov).map_or(view.fov, |f| f.clamp(5.0, 150.0)); view.ortho = c.ortho; + + // A free camera looks level through the saved view + view.set_angles(view.yaw, view.pitch); } /// The saved camera the view is at, if any. @@ -175,11 +224,46 @@ fn fixed_view(s: &mut Session, name: &str) -> Result { 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(); + let yaw = current + (yaw.to_radians() - current + turn * 0.5).rem_euclid(turn) - turn * 0.5; + s.camera.set_angles(yaw, pitch.to_radians()); crate::execute(s, "viewport.frame", &Value::Null) } +/// Constrained or free rotation; the direction of view stays. +fn rotation(s: &mut Session, free: bool) -> Result { + s.camera.set_free(free); + s.revision = s.revision.wrapping_add(1); + Ok(crate::view_cmds::camera_json(s)) +} + +/// Turn the camera `yaw` and `pitch` steps of 90° around the model. Angles between steps go to +/// the nearest one first, so repeated calls walk the steps. +fn snap_rotate(s: &mut Session, yaw: f32, pitch: f32) -> Result { + let step = std::f32::consts::FRAC_PI_2; + let limit = 89f32.to_radians(); + let c = &mut s.camera; + let next_yaw = ((c.yaw / step).round() + yaw.round()) * step; + let next_pitch = (((c.pitch / step).round() + pitch.round()) * step).clamp(-limit, limit); + c.set_angles(next_yaw, next_pitch); + s.revision = s.revision.wrapping_add(1); + Ok(crate::view_cmds::camera_json(s)) +} + +/// The next (`d` = 1) or previous (`d` = -1) saved camera, wrapping round. From a view that is +/// no saved camera, next goes to the first and previous to the last. +fn step_camera(s: &mut Session, d: i64) -> Result { + let saved = s.doc.project.cameras.len() as i64; + if saved == 0 { + return Err(bad("camera.next", "the project has no saved cameras")); + } + let to = match current(s) { + Some(i) => (i as i64 + d).rem_euclid(saved), + None if d > 0 => 0, + None => saved - 1, + }; + select(s, &json!({ "index": to })) +} + /// Switch to a perspective or orthographic projection; position and rotation stay. fn projection(s: &mut Session, ortho: bool) -> Result { s.camera.ortho = ortho; @@ -381,4 +465,89 @@ mod tests { assert_eq!(s.doc.project.display.dof.focus_distance, d); assert!(execute(&mut s, "viewport.focusAt", &json!({"x": 1, "y": 1})).is_err(), "nothing under the corner"); } + + #[test] + fn free_rotation_turns_the_model_over_and_constrained_stops_at_the_pole() { + let mut s = session(); + let undo_before = execute(&mut s, "edit.history", &Value::Null).unwrap(); + assert_eq!(execute(&mut s, "camera.get", &Value::Null).unwrap()["rotation"], "constrained"); + execute(&mut s, "camera.orbit", &json!({"dy": 170})).unwrap(); + assert!(s.camera.up().y > 0.99 && s.camera.pitch <= 89f32.to_radians() + 1e-6, "constrained keeps the horizon"); + + execute(&mut s, "camera.set", &json!({"yaw": 0, "pitch": 0})).unwrap(); + assert_eq!(execute(&mut s, "camera.rotation", &json!({"mode": "free"})).unwrap()["rotation"], "free"); + let eye = s.camera.eye(); + execute(&mut s, "camera.orbit", &json!({"dy": 170})).unwrap(); + assert!(s.camera.up().y < -0.9, "the model is turned over: {}", s.camera.up()); + assert!((s.camera.eye() - eye).length() > 1.0); + + // Back to constrained: level again, still looking from the same side + execute(&mut s, "camera.rotation.constrained", &Value::Null).unwrap(); + assert!(!s.camera.free && s.camera.up().y == 1.0); + assert!(execute(&mut s, "camera.rotation", &json!({"mode": "spin"})).is_err()); + assert_eq!(execute(&mut s, "edit.history", &Value::Null).unwrap(), undo_before, "the view is not an undo step"); + } + + #[test] + fn a_free_camera_is_put_level_by_fixed_views_and_set_angles() { + let mut s = session(); + execute(&mut s, "camera.rotation.free", &Value::Null).unwrap(); + execute(&mut s, "camera.orbit", &json!({"dx": 30, "dy": 120})).unwrap(); + execute(&mut s, "camera.view.front", &Value::Null).unwrap(); + let looking_from = (s.camera.eye() - s.camera.target).normalize(); + assert!(looking_from.z > 0.999 && s.camera.up().y > 0.999, "front view, level: {looking_from}"); + } + + #[test] + fn snap_rotate_walks_the_90_degree_steps() { + let mut s = session(); + execute(&mut s, "camera.set", &json!({"yaw": 10, "pitch": 5})).unwrap(); + execute(&mut s, "camera.snapRotate", &json!({"yaw": 1})).unwrap(); + assert!((s.camera.yaw.to_degrees() - 90.0).abs() < 1e-3 && s.camera.pitch.abs() < 1e-6, "nearest step, then one step"); + execute(&mut s, "camera.snapRotate.right", &Value::Null).unwrap(); + assert!((s.camera.yaw.to_degrees() - 180.0).abs() < 1e-3); + execute(&mut s, "camera.snapRotate.left", &Value::Null).unwrap(); + assert!((s.camera.yaw.to_degrees() - 90.0).abs() < 1e-3); + execute(&mut s, "camera.snapRotate.up", &Value::Null).unwrap(); + execute(&mut s, "camera.snapRotate.up", &Value::Null).unwrap(); + assert!((s.camera.pitch.to_degrees() - 89.0).abs() < 1e-3, "the pitch stops at the orbit limit"); + execute(&mut s, "camera.snapRotate.down", &Value::Null).unwrap(); + assert!(s.camera.pitch.abs() < 1e-6, "the limit counts as the top step"); + } + + #[test] + fn next_and_previous_camera_walk_the_saved_cameras_and_wrap() { + let mut s = session(); + assert!(execute(&mut s, "camera.next", &Value::Null).is_err(), "no saved cameras: nothing to go to"); + for (name, yaw) in [("A", 20), ("B", 40), ("C", 60)] { + execute(&mut s, "camera.set", &json!({"yaw": yaw})).unwrap(); + execute(&mut s, "camera.add", &json!({"name": name})).unwrap(); + } + execute(&mut s, "camera.orbit", &json!({"dx": 5})).unwrap(); + let current = |s: &mut Session| execute(s, "camera.list", &Value::Null).unwrap()["current"].clone(); + assert_eq!(current(&mut s), Value::Null); + for want in [0, 1, 2] { + execute(&mut s, "camera.next", &Value::Null).unwrap(); + assert_eq!(current(&mut s), want); + } + execute(&mut s, "camera.next", &Value::Null).unwrap(); + assert_eq!(current(&mut s), 0, "after the last one: the first"); + execute(&mut s, "camera.previous", &Value::Null).unwrap(); + assert_eq!(current(&mut s), 2, "before the first one: the last"); + execute(&mut s, "camera.previous", &Value::Null).unwrap(); + assert_eq!(current(&mut s), 1); + execute(&mut s, "camera.orbit", &json!({"dx": 5})).unwrap(); + execute(&mut s, "camera.previous", &Value::Null).unwrap(); + assert_eq!(current(&mut s), 2, "from a view that is no saved camera, previous goes to the last"); + } + + #[test] + fn the_combined_normal_view_is_a_view_mode() { + let mut s = session(); + execute(&mut s, "viewport.view", &json!({"mode": "normalHeightMesh"})).unwrap(); + assert_eq!(s.view, crate::ViewMode::NormalHeightMesh); + assert_eq!(s.view.label(), "Normal+height+mesh"); + execute(&mut s, "viewport.view", &json!({"mode": "material"})).unwrap(); + assert_eq!(s.view, crate::ViewMode::Material); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6f89804a..4294f873 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -81,8 +81,8 @@ pub use fill_mode::FillMode; pub use path_tool::PathState; pub use project_cmds::sample_session; pub use session::{ - CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState, ViewMode, history_label, - stroke_template, + CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState, + ViewMode, history_label, stroke_template, }; pub use set_cmds::{ResizeOutput, ResizeTask}; pub use solo::Solo; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index f8ce6c32..2e0e1ecc 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -150,8 +150,14 @@ pub enum ViewMode { UvChecker, /// One layer's mask, in grayscale (Alt+click a mask). Mask(LayerId), + /// The surface normal the shading uses, unlit: the mesh normal turned by the Height + /// channel's slope and the Normal channel ("Normal+height+mesh"). + NormalHeightMesh, } +/// The view picker's entry for [`ViewMode::NormalHeightMesh`] +pub const NORMAL_HEIGHT_MESH_LABEL: &str = "Normal+height+mesh"; + impl ViewMode { pub fn label(&self) -> String { match self { @@ -160,6 +166,7 @@ impl ViewMode { ViewMode::MeshMap(m) => m.id().into(), ViewMode::UvChecker => "UV checker".into(), ViewMode::Mask(_) => "Layer mask".into(), + ViewMode::NormalHeightMesh => NORMAL_HEIGHT_MESH_LABEL.into(), } } } diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 36e9a642..30c30efc 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -35,10 +35,34 @@ pub fn specs() -> Vec { cmd!("viewport.previousChannel", "Display previous channel", ["Viewport"], Some("Shift+C"), "{}", always, |s, _| cycle_channel(s, -1)), cmd!("viewport.nextMeshMap", "Display next mesh map", ["Viewport"], Some("B"), "{}", always, |s, _| cycle_map(s, 1)), cmd!("viewport.previousMeshMap", "Display previous mesh map", ["Viewport"], Some("Shift+B"), "{}", always, |s, _| cycle_map(s, -1)), - cmd!("viewport.view", "Set view mode", [], None, "{mode: material|uvChecker|mask||map:, layer? (for mask)}", always, view), - cmd!("camera.set", "Set camera", [], None, "{yaw?, pitch? (degrees), distance?, fov?, target?: [x,y,z], ortho?}", always, camera_set), + cmd!( + "viewport.view", + "Set view mode", + [], + None, + "{mode: material|uvChecker|normalHeightMesh (the normal the shading uses: mesh normal, Height channel slope and Normal channel; 2D view: the tangent-space normal)|mask||map:, layer? (for mask)}", + always, + view + ), + cmd!( + "camera.set", + "Set camera", + [], + None, + "{yaw?, pitch? (degrees), distance?, fov?, target?: [x,y,z], ortho?, rotation?: constrained|free (a free camera also rolls and turns over)}", + always, + camera_set + ), cmd!("camera.get", "Get camera", [], None, "{}", always, |s, _| Ok(camera_json(s))), - cmd!("camera.orbit", "Orbit camera", [], None, "{dx?, dy? (degrees)}", always, orbit), + cmd!( + "camera.orbit", + "Orbit camera", + [], + None, + "{dx?, dy? (degrees)} (turns the camera about the target; a free camera about its own axes)", + always, + orbit + ), cmd!( "display.set", "Display settings", @@ -173,6 +197,7 @@ fn view(s: &mut Session, p: &Value) -> Result { let v = match m { "material" => ViewMode::Material, "uvChecker" | "uv" | "checker" => ViewMode::UvChecker, + "normalHeightMesh" => ViewMode::NormalHeightMesh, "mask" => { let id = crate::commands::layer_param(s, "viewport.view", p)?; if s.doc.project.layer(id)?.mask.is_none() { @@ -193,16 +218,23 @@ pub(crate) fn camera_json(s: &Session) -> Value { json!({ "yaw": c.yaw.to_degrees(), "pitch": c.pitch.to_degrees(), "distance": c.distance, "fov": c.fov, "target": c.target.to_array(), "eye": c.eye().to_array(), "ortho": c.ortho, + "rotation": if c.free { "free" } else { "constrained" }, }) } fn camera_set(s: &mut Session, p: &Value) -> Result { let c = &mut s.camera; - if let Some(v) = f32p(p, "yaw") { - c.yaw = v.to_radians(); + match strp(p, "rotation") { + Some("free") => c.set_free(true), + Some("constrained") => c.set_free(false), + Some(o) => return Err(bad("camera.set", format!("unknown rotation `{o}`: constrained or free"))), + None => {} } - if let Some(v) = f32p(p, "pitch") { - c.pitch = v.clamp(-89.0, 89.0).to_radians(); + if f32p(p, "yaw").is_some() || f32p(p, "pitch").is_some() { + // A free camera is put level at the angles + let yaw = f32p(p, "yaw").map_or(c.yaw, f32::to_radians); + let pitch = f32p(p, "pitch").map_or(c.pitch, |v| v.clamp(-89.0, 89.0).to_radians()); + c.set_angles(yaw, pitch); } if let Some(v) = f32p(p, "distance") { c.distance = v.clamp(c.scene_radius * 0.05, c.scene_radius * 200.0); diff --git a/crates/formats/src/fonts.rs b/crates/formats/src/fonts.rs index fbd27985..b1e4cf99 100644 --- a/crates/formats/src/fonts.rs +++ b/crates/formats/src/fonts.rs @@ -33,19 +33,24 @@ pub fn system_fonts() -> Vec { } fn font_dirs() -> Vec { + let (mut dirs, user) = font_folders(); + dirs.extend(user); + dirs +} + +/// The folders installed fonts are read from: the system's, then the user's own. +pub fn font_folders() -> (Vec, Vec) { let home = std::env::var_os("HOME").map(PathBuf::from); if cfg!(windows) { - let mut v = vec![PathBuf::from(std::env::var_os("WINDIR").unwrap_or_else(|| "C:\\Windows".into())).join("Fonts")]; - v.extend(std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Microsoft\\Windows\\Fonts"))); - v + let system = vec![PathBuf::from(std::env::var_os("WINDIR").unwrap_or_else(|| "C:\\Windows".into())).join("Fonts")]; + let user = std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Microsoft\\Windows\\Fonts")).into_iter().collect(); + (system, user) } else if cfg!(target_os = "macos") { - let mut v = vec![PathBuf::from("/System/Library/Fonts"), PathBuf::from("/Library/Fonts")]; - v.extend(home.map(|h| h.join("Library/Fonts"))); - v + let system = vec![PathBuf::from("/System/Library/Fonts"), PathBuf::from("/Library/Fonts")]; + (system, home.map(|h| h.join("Library/Fonts")).into_iter().collect()) } else { - let mut v = vec![PathBuf::from("/usr/share/fonts"), PathBuf::from("/usr/local/share/fonts")]; - v.extend(home.iter().flat_map(|h| [h.join(".local/share/fonts"), h.join(".fonts")])); - v + let system = vec![PathBuf::from("/usr/share/fonts"), PathBuf::from("/usr/local/share/fonts")]; + (system, home.iter().flat_map(|h| [h.join(".local/share/fonts"), h.join(".fonts")]).collect()) } } diff --git a/crates/geom/src/camera.rs b/crates/geom/src/camera.rs index 1f4156c9..8adfc847 100644 --- a/crates/geom/src/camera.rs +++ b/crates/geom/src/camera.rs @@ -1,6 +1,6 @@ //! Orbit camera (texture painting navigation) and picking rays. -use glam::{Mat4, Vec2, Vec3, Vec4}; +use glam::{Mat4, Quat, Vec2, Vec3, Vec4}; use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] @@ -18,11 +18,29 @@ pub struct OrbitCamera { /// Orthographic projection instead of perspective. #[serde(default)] pub ortho: bool, + /// Free (trackball) rotation: the camera turns about its own axes and can roll and turn + /// over. Constrained rotation (the default) keeps the horizon level. + #[serde(default)] + pub free: bool, + /// The camera's orientation while `free` (the eye sits at `target + orient * Z * distance`). + /// `yaw` and `pitch` follow it, so a mode switch back keeps the direction of view. + #[serde(default)] + pub orient: Quat, } impl Default for OrbitCamera { fn default() -> Self { - OrbitCamera { target: Vec3::ZERO, yaw: 0.0, pitch: 0.12, distance: 5.0, fov: 40.0, scene_radius: 1.0, ortho: false } + OrbitCamera { + target: Vec3::ZERO, + yaw: 0.0, + pitch: 0.12, + distance: 5.0, + fov: 40.0, + scene_radius: 1.0, + ortho: false, + free: false, + orient: Self::orientation_from_angles(0.0, 0.12), + } } } @@ -35,17 +53,55 @@ pub struct Ray { impl OrbitCamera { pub fn eye(&self) -> Vec3 { + if self.free { + return self.target + self.orient * Vec3::Z * self.distance; + } let (sy, cy) = self.yaw.sin_cos(); let (sp, cp) = self.pitch.sin_cos(); self.target + Vec3::new(cp * sy, sp, cp * cy) * self.distance } + /// The screen's up direction: the world's up while constrained, the camera's own when free. + pub fn up(&self) -> Vec3 { + if self.free { self.orient * Vec3::Y } else { Vec3::Y } + } + + /// The camera's orientation from yaw and pitch (what constrained rotation looks through). + pub fn orientation_from_angles(yaw: f32, pitch: f32) -> Quat { + Quat::from_rotation_y(yaw) * Quat::from_rotation_x(-pitch) + } + + /// Put the camera at `yaw` and `pitch` (radians), level; a free camera loses its roll. + pub fn set_angles(&mut self, yaw: f32, pitch: f32) { + self.yaw = yaw; + self.pitch = pitch; + self.orient = Self::orientation_from_angles(yaw, pitch); + } + + /// Switch between free and constrained rotation. The direction of view stays; going back to + /// constrained drops the roll. + pub fn set_free(&mut self, free: bool) { + if free && !self.free { + self.orient = Self::orientation_from_angles(self.yaw, self.pitch); + } + self.free = free; + } + + /// Take yaw and pitch from the free orientation (pitch inside the orbit's limit). + fn angles_from_orient(&mut self) { + let v = self.orient * Vec3::Z; + self.pitch = v.y.clamp(-1.0, 1.0).asin().clamp(-89f32.to_radians(), 89f32.to_radians()); + if v.x.hypot(v.z) > 1e-4 { + self.yaw = v.x.atan2(v.z); + } + } + pub fn forward(&self) -> Vec3 { (self.target - self.eye()).try_normalize().unwrap_or(Vec3::NEG_Z) } pub fn view(&self) -> Mat4 { - Mat4::look_at_rh(self.eye(), self.target, Vec3::Y) + Mat4::look_at_rh(self.eye(), self.target, self.up()) } pub fn proj(&self, aspect: f32) -> Mat4 { @@ -74,6 +130,13 @@ impl OrbitCamera { } pub fn orbit(&mut self, dx: f32, dy: f32) { + if self.free { + // Trackball: turn about the camera's own up and right axes, so the model can be + // turned over + self.orient = (self.orient * Quat::from_rotation_y(-dx) * Quat::from_rotation_x(-dy)).normalize(); + self.angles_from_orient(); + return; + } self.yaw -= dx; self.pitch = (self.pitch + dy).clamp(-89f32.to_radians(), 89f32.to_radians()); } @@ -81,7 +144,7 @@ impl OrbitCamera { /// Pan by a screen fraction (dx, dy in viewport heights). pub fn pan(&mut self, dx: f32, dy: f32) { let f = self.forward(); - let right = f.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + let right = f.cross(self.up()).try_normalize().unwrap_or(Vec3::X); let up = right.cross(f); let scale = self.distance * (self.fov.to_radians() * 0.5).tan() * 2.0; self.target += (-right * dx + up * dy) * scale; @@ -137,4 +200,32 @@ mod tests { assert!(c.distance > 0.0 && c.distance.is_finite()); let _ = c.proj(f32::NAN); } + + #[test] + fn constrained_orbit_keeps_the_horizon_and_free_orbit_turns_over() { + let mut c = OrbitCamera::default(); + c.orbit(0.0, 10.0); + assert!(c.up() == Vec3::Y && c.pitch <= 89f32.to_radians() + 1e-6, "constrained stops at the pole"); + + let mut c = OrbitCamera::default(); + c.set_free(true); + let before = c.eye(); + // Half a turn over the top: the model ends up upside down + c.orbit(0.0, std::f32::consts::PI); + assert!(c.up().y < -0.99, "the camera is upside down: {}", c.up()); + assert!((c.eye() - before).length() > 1.0, "the eye went round"); + assert!((c.view() * c.target.extend(1.0)).z < 0.0, "the target stays in front of the camera"); + } + + #[test] + fn switching_rotation_mode_keeps_the_direction_of_view() { + let mut c = OrbitCamera { yaw: 0.7, pitch: 0.3, ..OrbitCamera::default() }; + let eye = c.eye(); + c.set_free(true); + assert!((c.eye() - eye).length() < 1e-4, "free keeps the view"); + c.orbit(0.2, -0.1); + c.set_free(false); + assert!(c.eye().is_finite() && (c.eye() - c.target).length() > 0.0); + assert!(((c.eye() - c.target).normalize().y - c.pitch.sin()).abs() < 1e-4, "yaw and pitch follow the free orientation"); + } } diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 1a57790f..888b7110 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -473,6 +473,11 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { return unlit(raw_out(aux.rgb)); } + if (mode == 4) { + // The normal the shading uses (mesh, height slope and normal channel), as a world-space normal + return unlit(raw_out(n * 0.5 + 0.5)); + } + if (mode == 3) { let c = floor(uv * UV_CHECKER_CELLS); let chk = (c.x + c.y) - 2.0 * floor((c.x + c.y) * 0.5); @@ -670,6 +675,21 @@ fn fs_uv(i: VOut) -> @location(0) vec4 { return raw_out(textureSample(t_aux, samp, i.uv).rgb); } + if (mode == 4) { + // The tangent-space normal the shading uses: the height slope turned by the normal channel + let dims = vec2(textureDimensions(t_height)); + let ts = 1.0 / dims; + let hl = textureSample(t_height, samp, i.uv - vec2(ts.x, 0.0)).r; + let hr = textureSample(t_height, samp, i.uv + vec2(ts.x, 0.0)).r; + let hu = textureSample(t_height, samp, i.uv - vec2(0.0, ts.y)).r; + let hd = textureSample(t_height, samp, i.uv + vec2(0.0, ts.y)).r; + let k = g.mode.z * dims.x / 16.0 * tile_scale(i.uv); + let n_height = normalize(vec3(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0)); + var n_detail = clamp(textureSample(t_nrm, samp, i.uv).rgb, vec3(-1.0), vec3(1.0)); + n_detail.y *= g.mode.w; + return raw_out(rnm(n_height, normalize(n_detail)) * 0.5 + 0.5); + } + if (mode == 3) { let c = floor(i.uv * UV_CHECKER_CELLS); let chk = (c.x + c.y) - 2.0 * floor((c.x + c.y) * 0.5); diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 845de3df..f293bc1c 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -112,6 +112,17 @@ fn exposure_brightens_the_material_but_not_data_views() { assert!(r.abs_diff(188) <= 1, "base color channel shows the raw value, got {r}"); } +#[test] +fn the_combined_normal_view_shows_the_shading_normal_unlit() { + let Some((mut h, frame)) = setup() else { return }; + let base = render(&mut h, &frame, "normal_view_material"); + let combined = shaded(&frame, |s| s.view_mode = 4); + let a = render(&mut h, &combined, "normal_height_mesh"); + let b = render(&mut h, &shaded(&combined, |s| s.exposure_ev = 2.0), "normal_height_mesh_ev2"); + assert_ne!(a.px, base.px, "the view differs from the lit material"); + assert_eq!(a.px, b.px, "a data view ignores exposure"); +} + #[test] fn post_effects() { let Some((mut h, frame)) = setup() else { return }; diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index b9101e93..059af550 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,10 +1,11 @@ use egui::{Align, Layout, RichText, Sense, Stroke, Ui, UiBuilder, vec2}; use egui_phosphor::regular as icon; +use serde_json::json; use texturecraft_engine::core::{BakeSettings, BakedMap}; use crate::TextureCraftApp; use crate::docking::Panel; -use crate::i18n::{baked_map_label, tr}; +use crate::i18n::{baked_map_label, tr, trf}; use crate::theme::Tokens; /// Height of one baker row, in points @@ -18,6 +19,8 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe app.ui.dock.focus(Panel::CommonSettings); } + presets_menu(app, ui, settings); + ui.add_space(4.0); check_all(ui, settings); ui.separator(); @@ -31,6 +34,62 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe } } +/// The Presets menu: save the active set's settings under a name, load or delete a saved one, copy to all sets +fn presets_menu(app: &mut TextureCraftApp, ui: &mut Ui, settings: &BakeSettings) { + ui.menu_button(format!("{} {}", icon::SLIDERS_HORIZONTAL, tr("Presets")), |ui| { + ui.set_min_width(220.0); + ui.horizontal(|ui| { + let name_edit = egui::TextEdit::singleline(&mut app.ui.bake_preset_name).hint_text(tr("Preset name")).desired_width(130.0); + let enter = ui.add(name_edit).lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)); + let can_save = !app.ui.bake_preset_name.trim().is_empty(); + if (ui.add_enabled(can_save, egui::Button::new(tr("Save Preset"))).clicked() || (enter && can_save)) + && app.ui.save_bake_preset(&app.ui.bake_preset_name.clone(), settings) + { + app.ui.bake_preset_name.clear(); + } + }); + + ui.separator(); + if app.ui.bake_presets.is_empty() { + ui.weak(tr("No saved presets")); + } + + let mut load = None; + let mut delete = None; + for preset in &app.ui.bake_presets { + ui.horizontal(|ui| { + if ui.button(&preset.name).on_hover_text(tr("Load this preset into the active texture set")).clicked() { + load = Some(preset.settings.clone()); + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let label = trf("Delete preset {name}", &[("name", &preset.name)]); + if crate::widgets::icon_button(ui, icon::TRASH, &label, false, ui.spacing().interact_size.y).clicked() { + delete = Some(preset.name.clone()); + } + }); + }); + } + + if let Some(preset) = load { + app.run("bake.settings", crate::bake_presets::apply_params(json!(app.session.ts()), &preset)); + ui.close(); + } + if let Some(name) = delete { + app.ui.delete_bake_preset(&name); + } + + ui.separator(); + if ui + .button(tr("Apply to All Texture Sets")) + .on_hover_text(tr("Copy the active texture set's bake settings to every texture set. Each keeps its Include in Bake choice.")) + .clicked() + { + app.run("bake.settings", crate::bake_presets::apply_params(json!("all"), settings)); + ui.close(); + } + }); +} + /// Enable every map, or disable them all when every map is already enabled fn check_all(ui: &mut Ui, settings: &mut BakeSettings) { let enabled_count = BakedMap::ALL.into_iter().filter(|map| settings.maps.is_enabled(*map)).count(); diff --git a/crates/ui-egui/src/bake_presets.rs b/crates/ui-egui/src/bake_presets.rs new file mode 100644 index 00000000..2c32e7d9 --- /dev/null +++ b/crates/ui-egui/src/bake_presets.rs @@ -0,0 +1,64 @@ +//! Named bake presets: the settings of one texture set saved under a name, loaded into any +//! set later, or copied to all of them. They persist with `UiState`. + +use serde::{Deserialize, Serialize}; +use serde_json::json; +use texturecraft_engine::core::BakeSettings; + +use crate::state::UiState; + +/// Bake settings saved under a name. Loading one keeps each texture set's own Include in Bake flag. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct BakePreset { + pub name: String, + pub settings: BakeSettings, +} + +impl UiState { + pub fn bake_preset(&self, name: &str) -> Option<&BakePreset> { + self.bake_presets.iter().find(|preset| preset.name == name.trim()) + } + + /// Save `settings` under `name` (surrounding spaces ignored), replacing a preset of that name; false for an empty name + pub fn save_bake_preset(&mut self, name: &str, settings: &BakeSettings) -> bool { + let name = name.trim(); + if name.is_empty() { + return false; + } + + let preset = BakePreset { name: name.to_string(), settings: settings.clone() }; + match self.bake_presets.iter().position(|saved| saved.name == name) { + Some(index) => self.bake_presets[index] = preset, + None => self.bake_presets.push(preset), + } + true + } + + pub fn delete_bake_preset(&mut self, name: &str) { + self.bake_presets.retain(|preset| preset.name != name); + } +} + +/// The `bake.settings` parameters that put `settings` on texture sets `ts` (an index, a list or "all"), keeping their Include in Bake flags +pub fn apply_params(ts: serde_json::Value, settings: &BakeSettings) -> serde_json::Value { + json!({ "ts": ts, "model": settings, "preserveEnabled": true }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn saving_twice_replaces_and_empty_names_are_refused() { + let mut ui = UiState::default(); + let mut settings = BakeSettings::default(); + assert!(!ui.save_bake_preset(" ", &settings)); + assert!(ui.save_bake_preset(" Fast ", &settings)); + settings.common.antialiasing = texturecraft_engine::core::BakeAntialiasing::Subsampling8x8; + assert!(ui.save_bake_preset("Fast", &settings)); + assert_eq!(ui.bake_presets.len(), 1); + assert_eq!(ui.bake_preset("Fast").unwrap().settings, settings); + ui.delete_bake_preset("Fast"); + assert!(ui.bake_presets.is_empty()); + } +} diff --git a/crates/ui-egui/src/bake_report.rs b/crates/ui-egui/src/bake_report.rs new file mode 100644 index 00000000..2e6994d7 --- /dev/null +++ b/crates/ui-egui/src/bake_report.rs @@ -0,0 +1,79 @@ +//! What a finished bake tells: how many maps it made, how long it took and which sets failed. + +use crate::i18n::{tr, trf}; + +/// The tally of the bake running now (the clock is the app's frame time, in seconds) +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BakeReport { + pub started: f64, + /// Maps stored into texture sets so far + pub maps: usize, + /// Texture sets whose bake failed + pub failed: Vec, +} + +impl BakeReport { + pub fn started(now: f64) -> Self { + BakeReport { started: now, ..Default::default() } + } + + /// The toast text, the Log line and whether the toast is an error (some set failed) + pub fn summary(&self, now: f64) -> (String, String, bool) { + let time = duration_text((now - self.started).max(0.0)); + let line = if self.failed.is_empty() { + format!("Bake finished: {} maps in {time}", self.maps) + } else { + format!("Bake finished: {} maps in {time}, {} failed", self.maps, self.failed.len()) + }; + let text = if self.failed.is_empty() { + trf("Baked {maps} maps in {time}", &[("maps", &self.maps), ("time", &time)]) + } else { + let failed = self.failed.len(); + format!( + "{} {}", + trf("Baked {maps} maps in {time}, {failed} failed.", &[("maps", &self.maps), ("time", &time), ("failed", &failed)]), + tr("Failures are listed in the Log.") + ) + }; + (text, line, !self.failed.is_empty()) + } +} + +/// "850 ms", "12.3 s" or "2 min 5 s" +fn duration_text(seconds: f64) -> String { + if seconds < 1.0 { + format!("{} ms", (seconds * 1000.0).round() as u32) + } else if seconds < 60.0 { + format!("{seconds:.1} s") + } else { + let whole = seconds.round() as u64; + format!("{} min {} s", whole / 60, whole % 60) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn success_names_maps_and_time() { + let report = BakeReport { started: 10.0, maps: 6, failed: vec![] }; + let (text, line, failed) = report.summary(22.34); + assert_eq!(text, "Baked 6 maps in 12.3 s"); + assert_eq!(line, "Bake finished: 6 maps in 12.3 s"); + assert!(!failed); + } + + #[test] + fn failures_are_counted_and_point_to_the_log() { + let report = BakeReport { started: 0.0, maps: 3, failed: vec![1, 2] }; + let (text, _, failed) = report.summary(125.0); + assert_eq!(text, "Baked 3 maps in 2 min 5 s, 2 failed. Failures are listed in the Log."); + assert!(failed); + } + + #[test] + fn short_times_show_milliseconds() { + assert_eq!(duration_text(0.85), "850 ms"); + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index c5dc53bf..894f47d3 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -120,6 +120,7 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para // The Export dialog cannot operate after Close if id == "file.close" { app.ui.windows.export = false; + app.ui.windows.mesh_export_options = false; } // A command that moved the camera takes over from a glide in progress; a projection switch joins it diff --git a/crates/ui-egui/src/display_settings.rs b/crates/ui-egui/src/display_settings.rs new file mode 100644 index 00000000..360a15ed --- /dev/null +++ b/crates/ui-egui/src/display_settings.rs @@ -0,0 +1,240 @@ +//! The Display Settings panel: the view mode, then environment, camera, post effect and viewer settings on one scrolling page + +use egui::{RichText, Ui}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::camera_cmds::DEFAULT_CAMERA; +use texturecraft_engine::core::ToneMapping; +use texturecraft_engine::core::project::{DisplaySettings, ENV_RESOURCE_PREFIX}; +use texturecraft_render::ibl::ENVIRONMENTS; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::section_page::{self, PageSection}; +use crate::theme::Tokens; +use crate::unavailable; +use crate::widgets::{combo, icon_button, section_with_reset, slider}; + +/// The page's sections, in the reference's tab order +pub(crate) const SECTIONS: [PageSection; 4] = [ + PageSection { icon: ic::MOUNTAINS, title: "Environment settings" }, + PageSection { icon: ic::VIDEO_CAMERA, title: "Camera settings" }, + PageSection { icon: ic::FUNCTION, title: "Post effects" }, + PageSection { icon: ic::CHECKERBOARD, title: "Viewer settings" }, +]; + +/// What the reference's shadow opacity slider shows; TextureCraft's shadows have no opacity yet +const SHADOWS_OPACITY_SHOWN: f32 = 90.0; + +/// Indent of the rows under a sub-heading (Environment, Shadows) +const ROW_INDENT: f32 = 12.0; + +/// The Display Settings panel body (a dock tab or rail popup) +pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { + ui.horizontal(|ui| { + ui.label(tr("View mode")); + crate::viewport::view_mode_picker(app, ui, "display_view_mode", ui.available_width()); + }); + + let mut display = app.session.doc.project.display.clone(); + let before = display.clone(); + let mut import_hdr = false; + section_page::show(ui, "display_settings", &SECTIONS, |ui, index| match index { + 0 => import_hdr = environment(app, ui, &mut display), + 1 => camera(app, ui, &mut display), + 2 => post_effects(ui, &mut display), + _ => viewer(app, ui, &mut display), + }); + + if display != before { + if display.fov != before.fov { + app.session.camera.fov = display.fov; + } + app.session.doc.project.display = display; + } + if import_hdr { + let ctx = ui.ctx().clone(); + crate::web_files::import_environment(app, &ctx); + } +} + +/// A sub-heading inside a section, as the reference's "Environment" and "Shadows" +fn sub_heading(ui: &mut Ui, text: &str) { + let tokens = Tokens::get(ui.ctx()); + ui.add_space(4.0); + ui.label(RichText::new(text).color(tokens.text_strong)); +} + +/// Rows indented under a sub-heading +fn indented(ui: &mut Ui, add: impl FnOnce(&mut Ui)) { + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT); + ui.vertical(add); + }); +} + +/// Environment and Shadows; true when Import HDR was picked +fn environment(app: &TextureCraftApp, ui: &mut Ui, display: &mut DisplaySettings) -> bool { + let mut import_hdr = false; + sub_heading(ui, tr("Environment")); + indented(ui, |ui| { + import_hdr = environment_map(app, ui, display); + unavailable::checkbox(ui, false, tr("Override environment map color space")); + unavailable::greyed(ui, |ui| egui::ComboBox::from_id_salt("env_color_space").width(ui.available_width()).selected_text(tr("Auto")).show_ui(ui, |_| {})); + slider(ui, tr("Environment Opacity"), &mut display.env_opacity, 0.0..=1.0, 2); + slider(ui, tr("Environment Exposure (EV)"), &mut display.env_exposure, -5.0..=5.0, 2); + slider(ui, tr("Environment Blur"), &mut display.env_blur, 0.0..=1.0, 2); + slider(ui, tr("Environment Rotation"), &mut display.env_rotation, 0.0..=360.0, 0); + unavailable::combo(ui, tr("Environment Alignment"), tr("World")); + }); + + sub_heading(ui, tr("Shadows")); + indented(ui, |ui| { + ui.checkbox(&mut display.shadows, tr("Shadows")).on_hover_text(tr("Key light (shadow-casting light, direct only)")); + unavailable::combo(ui, tr("Computation mode"), tr("Lightweight")); + unavailable::slider(ui, tr("Shadows opacity"), SHADOWS_OPACITY_SHOWN, 0.0..=100.0, 0); + }); + import_hdr +} + +/// The Environment Map button and its list: the built-in environments, the project's HDR images and Import HDR; true when Import HDR was picked +fn environment_map(app: &TextureCraftApp, ui: &mut Ui, display: &mut DisplaySettings) -> bool { + let mut hdrs: Vec<&String> = app.session.images.iter().filter(|(_, image)| !image.srgb).map(|(name, _)| name).collect(); + hdrs.sort(); + let shown = display.environment_resource().unwrap_or(&display.environment).to_string(); + let mut import_hdr = false; + ui.horizontal(|ui| { + ui.label(tr("Environment Map")); + let button = ui.add_sized([ui.available_width(), ui.spacing().interact_size.y], egui::Button::new(shown).truncate()); + egui::Popup::menu(&button).id(ui.make_persistent_id("environment_map_list")).show(|ui| { + for environment in ENVIRONMENTS { + ui.selectable_value(&mut display.environment, environment.to_string(), environment); + } + ui.separator(); + for name in hdrs { + ui.selectable_value(&mut display.environment, format!("{ENV_RESOURCE_PREFIX}{name}"), name.as_str()); + } + import_hdr = ui + .selectable_label(false, format!("{} {}", ic::FILE_ARROW_UP, tr("Import HDR..."))) + .on_hover_text(tr("Use an equirectangular .hdr or .exr image as the environment")) + .clicked(); + }); + }); + import_hdr +} + +/// The camera preset and its restore, the lens, the saved cameras and depth of field +fn camera(app: &mut TextureCraftApp, ui: &mut Ui, display: &mut DisplaySettings) { + let current = texturecraft_engine::camera_cmds::current(&app.session); + let names: Vec = app.session.doc.project.cameras.iter().map(|camera| camera.name.clone()).collect(); + let shown = current.and_then(|index| names.get(index)).map_or(tr(DEFAULT_CAMERA), String::as_str).to_string(); + ui.horizontal(|ui| { + ui.label(tr("Preset")); + let restore_width = ui.spacing().interact_size.x * 1.5; + egui::ComboBox::from_id_salt("display_camera_preset").width((ui.available_width() - restore_width).max(60.0)).selected_text(shown).show_ui(ui, |ui| { + if ui.selectable_label(current.is_none(), tr(DEFAULT_CAMERA)).clicked() { + app.run("camera.select", json!({})); + } + for (index, name) in names.iter().enumerate() { + if ui.selectable_label(current == Some(index), name).clicked() { + app.run("camera.select", json!({"index": index})); + } + } + }); + + // Back to the preset's own view, after orbiting away from it + let restore = ui.button(tr("Restore")).on_hover_text(tr("Return to the preset's view")); + if restore.clicked() { + let params = current.map_or_else(|| json!({}), |index| json!({"index": index})); + app.run("camera.select", params); + } + }); + + slider(ui, tr("Field of view (deg)"), &mut display.fov, 5.0..=120.0, 0); + let mut ortho = app.session.camera.ortho; + if ui.checkbox(&mut ortho, tr("Orthographic")).changed() { + app.run("camera.set", json!({"ortho": ortho})); + } + let tone_mapping_name = |tone_mapping: ToneMapping| match tone_mapping { + ToneMapping::Linear => tr("Linear"), + ToneMapping::AcesFilmic => tr("ACES filmic"), + }; + combo(ui, tr("Tone mapping"), tone_mapping_name(display.tone_mapping), |ui| { + for tone_mapping in [ToneMapping::Linear, ToneMapping::AcesFilmic] { + ui.selectable_value(&mut display.tone_mapping, tone_mapping, tone_mapping_name(tone_mapping)); + } + }); + cameras(app, ui); + + sub_heading(ui, tr("Depth of field")); + ui.checkbox(&mut display.dof.enabled, tr("Depth of field (viewport and Rendering mode)")); + ui.add_enabled_ui(display.dof.enabled, |ui| { + let far = (app.session.camera.distance * 4.0).max(display.dof.focus_distance); + slider(ui, tr("Focus distance"), &mut display.dof.focus_distance, 0.0..=far, 2) + .on_hover_text(tr("Depth of the sharp plane along the view (0: the orbit center)")); + slider(ui, tr("Aperture"), &mut display.dof.aperture, 0.0..=1.0, 3) + .on_hover_text(tr("Lens size: how quickly things blur away from the focus distance")); + let picking = crate::viewport::focus_picking(ui.ctx()); + if ui.selectable_label(picking, format!("{} {}", ic::CROSSHAIR_SIMPLE, tr("Pick focus in the viewport"))).clicked() { + crate::viewport::set_focus_picking(ui.ctx(), !picking); + } + }); +} + +/// The camera list: rename (edit the name), view or delete saved and imported cameras, save the +/// current view. +fn cameras(app: &mut TextureCraftApp, ui: &mut Ui) { + let current = texturecraft_engine::camera_cmds::current(&app.session); + let names: Vec = app.session.doc.project.cameras.iter().map(|c| c.name.clone()).collect(); + for (i, name) in names.iter().enumerate() { + ui.horizontal(|ui| { + if icon_button(ui, ic::VIDEO_CAMERA, tr("View through this camera"), current == Some(i), 20.0).clicked() { + app.run("camera.select", json!({"index": i})); + } + // The name being typed lives in egui's memory until the field loses focus. + let id = ui.scope_id().with(("camera_name", i)); + let mut text = ui.data(|d| d.get_temp::(id)).unwrap_or_else(|| name.clone()); + let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(ui.available_width() - 26.0)); + if r.changed() { + ui.data_mut(|d| d.insert_temp(id, text.clone())); + } + if r.lost_focus() { + ui.data_mut(|d| d.remove::(id)); + if text.trim() != name && !text.trim().is_empty() { + app.run("camera.rename", json!({"index": i, "to": text.trim()})); + } + } + if icon_button(ui, ic::TRASH, tr("Delete this camera"), false, 20.0).clicked() { + app.run("camera.remove", json!({"index": i})); + } + }); + } + if ui.button(format!("{} {}", ic::PLUS, tr("Save view as camera"))).clicked() { + app.run("camera.add", json!({})); + } +} + +/// The post effects switch and amounts, with a reset on their header +fn post_effects(ui: &mut Ui, display: &mut DisplaySettings) { + // The switch gates all four amounts (the engine has one switch for the group); each amount 0 leaves that effect out + let post_effect_fields = |d: &DisplaySettings| (d.post_effects, d.bloom, d.vignette, d.sharpen, d.grain); + let post_effect_defaults = post_effect_fields(&DisplaySettings::default()); + if section_with_reset(ui, "sec_post_effects", tr("Post effects"), false, post_effect_fields(display) == post_effect_defaults, |ui| { + ui.checkbox(&mut display.post_effects, tr("Post effects (viewport and Rendering mode)")); + ui.add_enabled_ui(display.post_effects, |ui| { + slider(ui, tr("Glow"), &mut display.bloom, 0.0..=1.0, 2).on_hover_text(tr("Bright areas bleed light into their surroundings")); + slider(ui, tr("Vignette"), &mut display.vignette, 0.0..=1.0, 2).on_hover_text(tr("Darkens the corners of the view")); + slider(ui, tr("Sharpen"), &mut display.sharpen, 0.0..=1.0, 2).on_hover_text(tr("Brings out fine detail")); + slider(ui, tr("Film grain"), &mut display.grain, 0.0..=1.0, 2).on_hover_text(tr("Adds fine noise over the view")); + }); + }) { + (display.post_effects, display.bloom, display.vignette, display.sharpen, display.grain) = post_effect_defaults; + } +} + +/// The wireframes and temporal anti-aliasing +fn viewer(app: &mut TextureCraftApp, ui: &mut Ui, display: &mut DisplaySettings) { + ui.checkbox(&mut app.ui.wireframe_3d, tr("Show wireframe in the 3D view")); + ui.checkbox(&mut app.ui.uv_wireframe, tr("Show UV wireframe in the 2D view")); + ui.checkbox(&mut display.taa, tr("Temporal anti-aliasing (refines the 3D view while it is still)")); +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 13d39465..ab0d0e39 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -38,14 +38,16 @@ pub enum Panel { Shader, History, Log, + Export, } /// Window ▸ Views items and the panels they show or hide. -pub const VIEWS: [(&str, Panel); 12] = [ +pub const VIEWS: [(&str, Panel); 13] = [ ("ui.view.assets", Panel::Assets), ("ui.view.bakeMaps", Panel::MeshMapSettings), ("ui.view.bakeSettings", Panel::CommonSettings), ("ui.view.display", Panel::Display), + ("ui.view.export", Panel::Export), ("ui.view.history", Panel::History), ("ui.view.layers", Panel::Layers), ("ui.view.log", Panel::Log), @@ -70,7 +72,7 @@ impl Panel { } } - pub const ALL: [Panel; 13] = [ + pub const ALL: [Panel; 14] = [ Panel::Viewport, Panel::Assets, Panel::MeshMapSettings, @@ -84,6 +86,7 @@ impl Panel { Panel::Shader, Panel::History, Panel::Log, + Panel::Export, ]; pub fn name(self) -> &'static str { @@ -101,6 +104,7 @@ impl Panel { Panel::Shader => "Shader Settings", Panel::History => "History", Panel::Log => "Log", + Panel::Export => "Export", } } @@ -111,6 +115,7 @@ impl Panel { Panel::Shader => 1.0, Panel::History => 2.0, Panel::Log => 3.0, + Panel::Export => 4.0, _ => return None, }; Some([960.0, 90.0 + 50.0 * slot, 300.0, 380.0]) @@ -481,7 +486,7 @@ const PANEL_BODY_MARGIN: Margin = Margin::symmetric(8, 4); /// The body of every panel except the viewport, in the dock or on the rail pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { // No project open: the library and the log work, the other panels about a project stay empty - let works_empty = matches!(panel, Panel::Assets | Panel::Log | Panel::Layers | Panel::TextureSetList | Panel::Properties); + let works_empty = matches!(panel, Panel::Assets | Panel::Log | Panel::Layers | Panel::TextureSetList | Panel::Properties | Panel::Export); if !app.session.project_open && !works_empty { return; } @@ -497,11 +502,12 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { Panel::TextureSetSettings => crate::dock::texture_set_settings(app, ui), Panel::Properties => crate::dock::properties(app, ui), - // Display and Shader Settings scroll here, as tall as their contents; History and Log scroll their own lists - Panel::Display => egui::ScrollArea::vertical().id_salt("dock-display").auto_shrink([false, true]).show(ui, |ui| crate::windows::display(app, ui)).inner, - Panel::Shader => egui::ScrollArea::vertical().id_salt("dock-shader").auto_shrink([false, true]).show(ui, |ui| crate::windows::shader(app, ui)).inner, + // Display and Shader Settings scroll one page under their section tabs; History and Log scroll their own lists + Panel::Display => crate::display_settings::body(app, ui), + Panel::Shader => crate::shader_settings::body(app, ui), Panel::History => crate::windows::history(app, ui), - Panel::Log => crate::windows::log(app, ui), + Panel::Log => crate::log_panel::body(app, ui), + Panel::Export => crate::export_panel::body(app, ui), Panel::Viewport => {} }); } @@ -542,6 +548,34 @@ impl DockContent for Panels<'_> { fn floating_size(&self, _panel: &Panel) -> Option { Some(vec2(300.0, 380.0)) } + + fn group_header_width(&self, panels: &[Panel], active: &Panel, floating: bool, _strip_width: f32) -> f32 { + if redocks(panels, active, floating) { DOCK_BUTTON_SIZE + DOCK_BUTTON_MARGIN } else { 0.0 } + } + + /// A rail panel floating on its own carries the Dock button that sends it back to the rail + fn group_header(&mut self, ui: &mut Ui, panels: &[Panel], active: &Panel, floating: bool) { + if !redocks(panels, active, floating) { + return; + } + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked() { + self.app.ui.dock.close(*active); + } + }); + } +} + +/// Size of the Dock button in a floating rail panel's tab strip +const DOCK_BUTTON_SIZE: f32 = 22.0; + +/// Room right of the Dock button, so it clears the strip's end +const DOCK_BUTTON_MARGIN: f32 = 6.0; + +/// Whether a floating window holds one rail panel alone: its Dock button closes it back onto the rail +fn redocks(panels: &[Panel], active: &Panel, floating: bool) -> bool { + floating && panels.len() == 1 && crate::rail_popup::is_rail_panel(*active) } #[cfg(test)] @@ -604,6 +638,18 @@ mod tests { } } + #[test] + fn a_layout_saved_before_the_export_panel_still_loads() { + let mut saved = serde_json::to_value(default_workspace()).unwrap(); + let hidden = saved["hidden"].as_array_mut().unwrap(); + hidden.retain(|entry| entry[0] != "Export"); + assert!(!saved.to_string().contains("\"Export\"")); + + let dock = Dock::from_value(saved); + assert!(!dock.replaced_unreadable(), "the saved layout is kept"); + assert!(dock.workspace().hidden.iter().any(|(panel, _)| *panel == Panel::Export), "Export joins it, closed"); + } + #[test] fn the_viewport_stays_put() { let mut dock = Dock::default(); diff --git a/crates/ui-egui/src/export_panel.rs b/crates/ui-egui/src/export_panel.rs new file mode 100644 index 00000000..ad9a6534 --- /dev/null +++ b/crates/ui-egui/src/export_panel.rs @@ -0,0 +1,59 @@ +//! The Export panel on the rail: where to send the project, then Export Mesh and Export Textures + +use egui::{RichText, Ui}; +use egui_phosphor::regular as ic; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::theme::{Tokens, caption}; +use crate::unavailable; +use crate::widgets::primary_button; + +/// The SEND TO rows: none has a counterpart in TextureCraft yet +pub const SEND_TO: [&str; 3] = ["Export to image editor", "Send to compositing app", "Send to 3D staging app"]; + +/// Width of the Export Mesh and Export Textures buttons +const EXPORT_BUTTON_WIDTH: f32 = 176.0; + +/// Size of the Configure button beside a SEND TO row +const CONFIGURE_SIZE: f32 = 20.0; + +/// Space between the SEND TO and EXPORT parts +const PART_GAP: f32 = 12.0; + +/// The Export panel body (a rail popup or dock tab); its buttons need an open project +pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + ui.label(caption(&tr("Send to").to_uppercase())); + for (index, target) in SEND_TO.into_iter().enumerate() { + ui.horizontal(|ui| { + unavailable::greyed(ui, |ui| ui.add(egui::Button::new(tr(target)).frame(false))); + + // The reference's second row has a Configure button + if index == 1 { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + unavailable::greyed(ui, |ui| { + ui.add( + egui::Button::new(RichText::new(ic::GEAR).color(tokens.text_dim)).frame(false).min_size(egui::vec2(CONFIGURE_SIZE, CONFIGURE_SIZE)), + ) + }); + }); + } + }); + } + + ui.add_space(PART_GAP); + ui.label(caption(&tr("Export").to_uppercase())); + let project_open = app.session.project_open; + ui.vertical_centered(|ui| { + let size = [EXPORT_BUTTON_WIDTH, ui.spacing().interact_size.y]; + if ui.add_enabled(project_open, egui::Button::new(tr("Export Mesh...")).min_size(size.into())).clicked() { + app.ui.windows.mesh_export_options = true; + app.ui.rail_panel = None; + } + if ui.add_enabled(project_open, primary_button(ui, tr("Export Textures...")).min_size(size.into())).clicked() { + app.ui.windows.export = true; + app.ui.rail_panel = None; + } + }); +} diff --git a/crates/ui-egui/src/file_dialogs.rs b/crates/ui-egui/src/file_dialogs.rs index 3c9df8c0..ce41b16b 100644 --- a/crates/ui-egui/src/file_dialogs.rs +++ b/crates/ui-egui/src/file_dialogs.rs @@ -44,26 +44,43 @@ pub struct Asked { pub struct FileDialogs { dialogs: craft_dialogs::Dialogs, asked: Vec, + /// Requests are answered by an override instead of a native dialog. + overridden: bool, + /// The app has no native window (the test harness): a native dialog must never open. + headless: bool, } impl FileDialogs { /// The dialogs of the app whose context is `ctx`: an answer wakes its event loop. pub fn new(ctx: egui::Context) -> FileDialogs { - FileDialogs { dialogs: craft_dialogs::Dialogs::new(Arc::new(move || ctx.request_repaint())), asked: Vec::new() } + FileDialogs { dialogs: craft_dialogs::Dialogs::new(Arc::new(move || ctx.request_repaint())), asked: Vec::new(), overridden: false, headless: false } } /// Answers every request with `answer_with` instead of a native dialog (tests). pub fn set_override(&mut self, answer_with: Option) { + self.overridden = answer_with.is_some(); self.dialogs.set_override(answer_with); } + /// For an app without a native window (the test harness): never open a native dialog. Every + /// request is answered Cancelled until a test sets its own override. + pub(crate) fn without_window(&mut self) { + self.headless = true; + self.set_override(Some(Box::new(|_| Answer::Cancelled))); + } + /// Requests that have not been answered yet. pub fn pending(&self) -> usize { self.asked.len() } /// Shows the next dialog asked for. Call at the end of every frame with the window. + #[expect(clippy::panic, reason = "only an app without a window whose test removed the override gets here")] pub fn show_pending(&mut self, frame: &eframe::Frame) { + // Guards the user's desktop: whatever was asked (open, save, folder), a window-less app never shows a system dialog + if self.headless && !self.overridden && !self.asked.is_empty() { + panic!("a file dialog would open in an app without a window and no file dialog override: set one with `file_dialogs.set_override`"); + } self.dialogs.show_pending(Some(frame)); } } @@ -74,7 +91,12 @@ impl TextureCraftApp { /// another project has been opened since. Returns false, and drops `then`, when the same dialog /// is already showing or waiting. #[track_caller] + #[expect(clippy::panic, reason = "only an app without a window whose test removed the override gets here")] pub(crate) fn ask_file(&mut self, dialog: FileDialog, bound: Bound, then: impl FnOnce(&mut TextureCraftApp, Vec) + 'static) -> bool { + // Guards the user's desktop: a test without an override would open a real system dialog + if self.file_dialogs.headless && !self.file_dialogs.overridden { + panic!("a file dialog was asked for in an app without a window and no file dialog override: set one with `file_dialogs.set_override`"); + } let project = (bound == Bound::Project).then_some(self.session.project_id); let key = AskKey { request: Request::File(dialog.clone()), project, origin: Location::caller() }; if self.file_dialogs.asked.contains(&key) { @@ -109,3 +131,48 @@ impl TextureCraftApp { } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn app() -> TextureCraftApp { + let session = texturecraft_engine::Session::closed().unwrap(); + TextureCraftApp::new(&eframe::CreationContext::_new_kittest(egui::Context::default()), session) + } + + #[test] + fn an_app_without_a_window_answers_cancelled_instead_of_opening_a_dialog() { + let mut app = app(); + let answered = std::rc::Rc::new(std::cell::Cell::new(None)); + let seen = answered.clone(); + assert!(app.ask_file(FileDialog::save().file_name("layout.json"), Bound::App, move |_, paths| seen.set(Some(paths.len())))); + let frame = eframe::Frame::_new_kittest(); + for _ in 0..100 { + app.file_dialogs.show_pending(&frame); + app.run_file_dialog_answers(); + if answered.get().is_some() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(answered.get(), Some(0), "Cancelled: no paths"); + } + + #[test] + #[should_panic(expected = "no file dialog override")] + fn an_app_without_a_window_and_without_an_override_refuses_to_open_a_dialog() { + let mut app = app(); + app.file_dialogs.set_override(None); + app.ask_file(FileDialog::folder(), Bound::App, |_, _| {}); + } + + #[test] + #[should_panic(expected = "no file dialog override")] + fn a_dialog_queued_before_the_override_was_removed_still_never_opens() { + let mut app = app(); + app.ask_file(FileDialog::save().file_name("layout.json"), Bound::App, |_, _| {}); + app.file_dialogs.set_override(None); + app.file_dialogs.show_pending(&eframe::Frame::_new_kittest()); + } +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 84a5a31f..bbbea0ec 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -72,8 +72,12 @@ pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'sta } } -/// Switch the UI language (unknown codes fall back to English). +/// The saved language that follows the operating system's (Settings > Language > Default (System Language)). +pub const SYSTEM_LANGUAGE: &str = ""; + +/// Switch the UI language ([`SYSTEM_LANGUAGE`] follows the system; unknown codes fall back to English). pub fn set_language(code: &str) { + let code = if code == SYSTEM_LANGUAGE { system_language() } else { code }; CURRENT.store(LANGUAGES.iter().position(|l| l.code.eq_ignore_ascii_case(code) && available(l.code)).unwrap_or(0), Ordering::Relaxed); } @@ -151,6 +155,12 @@ pub fn os_language() -> &'static str { locale.map_or("en", |l| language_for_locale(&l)) } +/// [`os_language`] read once: the language is applied every frame. +fn system_language() -> &'static str { + static SYSTEM: OnceLock<&'static str> = OnceLock::new(); + SYSTEM.get_or_init(os_language) +} + /// Tests that switch the global UI language, or draw the UI under it, run one at a time. #[cfg(test)] pub(crate) static TEST_LANGUAGE: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -279,6 +289,17 @@ mod tests", } } + #[test] + fn the_system_language_setting_speaks_the_operating_system_language() { + let _language = LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + set_language(SYSTEM_LANGUAGE); + let shown = current().code; + set_language("en"); + + let expected = if available(os_language()) { os_language() } else { "en" }; + assert_eq!(shown, expected); + } + #[test] fn embedded_catalogs_are_valid() { assert!(I18N.check_all().is_empty(), "{:?}", I18N.check_all()); diff --git a/crates/ui-egui/src/id_color_pick.rs b/crates/ui-egui/src/id_color_pick.rs index c4e99a65..f26c4320 100644 --- a/crates/ui-egui/src/id_color_pick.rs +++ b/crates/ui-egui/src/id_color_pick.rs @@ -87,6 +87,7 @@ fn view_params(view: ViewMode) -> Value { ViewMode::Channel(channel) => json!({"mode": channel.id()}), ViewMode::MeshMap(map) => json!({"mode": format!("map:{}", map.id())}), ViewMode::UvChecker => json!({"mode": "uvChecker"}), + ViewMode::NormalHeightMesh => json!({"mode": "normalHeightMesh"}), ViewMode::Mask(layer) => json!({"mode": "mask", "layer": layer.0}), } } diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index cee050ba..44dca307 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -1,6 +1,6 @@ //! Keyboard shortcuts: every menu item and every command a key can run, the user's //! overrides (`UiState::keymap`, id → "Ctrl+Shift+E" or "" for unbound), conflict detection and -//! the shortcut editor window (Edit ▸ Settings ▸ Keyboard, Help ▸ Shortcuts list). +//! the shortcut editor window (Help ▸ Shortcuts list) and the Edit ▸ Settings ▸ Shortcuts page. use std::collections::BTreeMap; @@ -261,10 +261,75 @@ pub fn captured(mods: Modifiers, key: Key) -> bool { } const CAPTURE: &str = "keymap_capture"; +/// The binding Settings > Shortcuts waits a key combination for. +const SETTINGS_CAPTURE: &str = "settings_keymap_capture"; /// Whether the editor is waiting for a key combination (global shortcuts pause meanwhile). pub fn capturing(ctx: &egui::Context) -> bool { - ctx.data(|d| d.get_temp::(Id::unique(CAPTURE))).is_some() + ctx.data(|d| d.get_temp::(Id::unique(CAPTURE)).is_some() || d.get_temp::(Id::unique(SETTINGS_CAPTURE)).is_some()) +} + +/// Settings > Shortcuts stops waiting for a key combination (another page, OK or Cancel). +pub(crate) fn stop_settings_capture(ctx: &egui::Context) { + ctx.data_mut(|d| d.remove::(Id::unique(SETTINGS_CAPTURE))); +} + +/// Settings > Shortcuts: one row per bindable item with its name, its shortcut in `keymap` and +/// a pencil that waits for the new key combination (Esc cancels). `recorder` reads the pressed +/// keys as the app's shortcuts do; `edited` follows `keymap` to show shared shortcuts. +pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bindings, edited: &mut Bindings) { + let ctx = ui.ctx().clone(); + let tk = Tokens::get(&ctx); + let capture_id = Id::unique(SETTINGS_CAPTURE); + let mut capture: Option = ctx.data(|d| d.get_temp(capture_id)); + if let (Some(i), Some(sc)) = (capture, pressed(&ctx, recorder)) { + if (sc.logical_key != Key::Escape || !sc.modifiers.is_none()) + && let Some(b) = bindings().get(i) + { + rebind(keymap, b, &format_shortcut(&sc)); + } + capture = None; + } + edited.sync(keymap, craft_keymap::egui::platform(&ctx)); + + let cell = |ui: &mut egui::Ui, width: f32, add: &mut dyn FnMut(&mut egui::Ui)| { + ui.allocate_ui_with_layout(vec2(width, 22.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(width); + add(ui); + }); + }; + for (i, b) in bindings().iter().enumerate() { + let waiting = capture == Some(i); + ui.horizontal(|ui| { + cell(ui, 330.0, &mut |ui| { + ui.add(egui::Label::new(tr(b.label)).truncate()).on_hover_text(tr(b.group)); + }); + cell(ui, 150.0, &mut |ui| { + if waiting { + ui.label(RichText::new(tr("Press a key...")).color(tk.accent)); + } else { + ui.label(shortcut(keymap, b).unwrap_or("")); + } + if let Some(other) = edited.conflict(b) { + ui.label(RichText::new(ic::WARNING).color(tk.danger)) + .on_hover_text(trf("Also bound to {item} ({menu})", &[("item", &tr(other.label)), ("menu", &tr(other.group))])); + } + }); + let edit = trf("Edit the shortcut of {item}", &[("item", &tr(b.label))]); + if icon_button(ui, ic::PENCIL_SIMPLE, &edit, waiting, 20.0).clicked() { + capture = if waiting { None } else { Some(i) }; + } + }); + } + + ctx.data_mut(|d| match capture { + Some(i) => { + d.insert_temp(capture_id, i); + } + None => { + d.remove::(capture_id); + } + }); } /// The first key press this frame as a shortcut. @@ -406,6 +471,7 @@ pub fn fixed_gestures() -> Vec<(String, String)> { let keyed = |template: &str| trf(template, &[("key", &stencil)]); vec![ (tr("Alt + LMB drag").into(), tr("Orbit").into()), + (tr("Alt + Shift + LMB drag").into(), tr("Camera snap rotate").into()), (tr("RMB drag").into(), tr("Orbit (3D view)").into()), (tr("MMB drag / Alt + MMB").into(), tr("Pan").into()), (tr("Wheel / Alt + RMB drag").into(), tr("Zoom").into()), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 94643a0e..0320280c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -11,12 +11,16 @@ mod angle_dial; mod ask; mod bake_job; pub mod bake_mode; +pub mod bake_presets; +mod bake_report; mod bake_scene; mod color_selection_editor; pub mod control; mod decal_drop; +mod display_settings; pub mod dock; pub mod docking; +mod export_panel; pub mod export_templates; #[cfg(not(target_arch = "wasm32"))] pub mod file_dialogs; @@ -39,9 +43,11 @@ mod levels_handle; mod levels_properties; mod line_snap; mod list_action; +pub mod log_panel; mod mask_preview_image; mod material_preview_image; pub mod menus; +mod mesh_export_options; mod name_error; mod named_layout; pub mod named_layouts; @@ -75,6 +81,9 @@ mod resource_picker_tile; mod running_bake; pub mod saved_search; mod screen_color_pick; +mod section_page; +pub mod settings_window; +pub mod shader_settings; pub mod shelf; mod shelf_entry; mod shelf_folders; @@ -95,6 +104,7 @@ mod tile_edits; pub mod titlebar; pub mod toolbar; pub mod ui_state_store; +pub mod unavailable; #[cfg(not(target_arch = "wasm32"))] pub(crate) mod updates_ui; pub mod uv_paint_point; @@ -167,6 +177,8 @@ pub struct TextureCraftApp { /// Texture sets the GPU could not hold, and the text of the one sticky toast naming them. pub(crate) gpu_memory: (Vec, Option), pub bake: Option, + /// What the bake running now has done so far, for the summary when it ends + pub bake_report: bake_report::BakeReport, /// The Import PBR textures dialog while it is open. pub pbr_import: Option, pub resize: Option, @@ -227,6 +239,8 @@ pub struct TextureCraftApp { pub(crate) prompt_saved: bool, /// The resolved keymap and its key dispatcher. pub(crate) bindings: keymap::Bindings, + /// The shortcuts Settings > Shortcuts edits, resolved to show shared shortcuts. + pub(crate) settings_bindings: keymap::Bindings, } /// The UI state to start with: the saved one, whose tool settings go to `session`, else the defaults in the OS language @@ -238,7 +252,7 @@ pub(crate) fn start_ui(saved: Option, session: &mut Session) -> UiState } None => { let mut ui = UiState::default(); - ui.prefs.language = i18n::os_language().into(); + ui.prefs.language = i18n::SYSTEM_LANGUAGE.into(); ui } } @@ -277,6 +291,7 @@ impl TextureCraftApp { toasts: Vec::new(), gpu_memory: (Vec::new(), None), bake: None, + bake_report: Default::default(), pbr_import: None, resize: None, link_cooks: Vec::new(), @@ -311,7 +326,13 @@ impl TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] prompt_saved: false, bindings: keymap::Bindings::default(), + settings_bindings: keymap::Bindings::default(), }; + // The test harness has no window: its file dialogs answer Cancelled, never on the desktop + #[cfg(not(target_arch = "wasm32"))] + if cc.winit_window().is_none() { + app.file_dialogs.without_window(); + } app.ui.rename = None; app.ui.windows.new_project = false; i18n::set_language(&app.ui.prefs.language); @@ -345,7 +366,9 @@ impl TextureCraftApp { self.ui.prefs.apply_resource_limits(); // 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 glides = ["camera.select", "camera.bookmark", "camera.view", "camera.next", "camera.previous", "camera.snapRotate"] + .iter() + .any(|prefix| id.starts_with(prefix)); let before = self.session.camera; let glide_from = glides.then_some(before); match texturecraft_engine::execute(&mut self.session, id, ¶ms) { @@ -365,6 +388,7 @@ impl TextureCraftApp { if id == "file.close" { self.ui.mode = state::Mode::Painting; self.ui.windows.export = false; + self.ui.windows.mesh_export_options = false; } match glide_from { @@ -435,6 +459,7 @@ impl TextureCraftApp { } let total = sets.len(); + self.bake_report = bake_report::BakeReport::started(self.last_time); self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id }); } @@ -528,19 +553,24 @@ impl TextureCraftApp { match running.receiver.try_recv() { Ok(Ok(output)) => { job.current = None; - if let Err(error) = self.session.apply_streamed_bake(set_index, output) { - self.toast(error.to_string(), true); + let maps = output.maps.len(); + match self.session.apply_streamed_bake(set_index, output) { + Ok(()) => self.bake_report.maps += maps, + Err(error) => self.bake_failed(set_index, &error.to_string()), } } Ok(Err(error)) => { + // The worker's error ends the whole bake; the maps of the sets before it stay + self.bake_failed(set_index, &error.to_string()); self.cancel_bake(); - self.toast(error.to_string(), true); + self.finish_bake_report(); return; } Err(std::sync::mpsc::TryRecvError::Empty) => return, Err(std::sync::mpsc::TryRecvError::Disconnected) => { + self.bake_failed(set_index, i18n::tr("The bake worker stopped")); self.cancel_bake(); - self.toast(i18n::tr("The bake worker stopped"), true); + self.finish_bake_report(); return; } } @@ -551,7 +581,7 @@ impl TextureCraftApp { if job.queue.is_empty() { self.bake = None; self.session.bake_preview_end(); - self.toast(i18n::tr("Mesh maps baked"), false); + self.finish_bake_report(); return; } @@ -576,10 +606,23 @@ impl TextureCraftApp { job.current = Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total }); } } - Err(error) => self.toast(error.to_string(), true), + Err(error) => self.bake_failed(set_index, &error.to_string()), } } + /// Note a texture set whose bake failed: one Log line, counted in the summary + fn bake_failed(&mut self, set_index: usize, error: &str) { + self.session.log.push(format!("Bake of texture set {set_index} failed: {error}")); + self.bake_report.failed.push(set_index); + } + + /// The toast that ends a bake (maps baked, time, failures) and its line in the Log + fn finish_bake_report(&mut self) { + let (text, line, failed) = self.bake_report.summary(self.last_time); + self.session.log.push(line); + self.toast(text, failed); + } + /// Cancel the active worker, discard queued sets and restore the view. The current set's /// preview maps are discarded; previously applied sets keep their results and undo steps. pub fn cancel_bake(&mut self) { @@ -733,8 +776,8 @@ impl TextureCraftApp { /// Whether command `id` puts the camera at a place it names (a view, a saved camera, explicit values or /// framing), so a glide toward an earlier destination must not go on even when the camera is already there fn sets_camera(id: &str) -> bool { - matches!(id, "camera.set" | "camera.orbit" | "camera.select") - || ["camera.view.", "camera.bookmark", "viewport.frame"].iter().any(|prefix| id.starts_with(prefix)) + matches!(id, "camera.set" | "camera.orbit" | "camera.select" | "camera.next" | "camera.previous") + || ["camera.view.", "camera.bookmark", "camera.snapRotate", "camera.rotation", "viewport.frame"].iter().any(|prefix| id.starts_with(prefix)) } /// A smooth move of the viewport camera (see [`TextureCraftApp::run`]). @@ -757,6 +800,7 @@ impl TextureCraftApp { let mut c = b; c.target = a.target.lerp(b.target, e); c.yaw = mix(a.yaw, b.yaw); + c.orient = a.orient.slerp(b.orient, e); c.pitch = mix(a.pitch, b.pitch); c.distance = mix(a.distance, b.distance); c.fov = mix(a.fov, b.fov); @@ -924,10 +968,16 @@ pub fn data_folder(pref: &str) -> std::path::PathBuf { std::path::Path::new(&home).join("Documents").join("TextureCraft") } +/// The data folder in use (Settings › Folders › Data folder). +#[cfg(not(target_arch = "wasm32"))] +pub fn data_dir() -> std::path::PathBuf { + DATA_FOLDER.get().cloned().unwrap_or_else(|| data_folder("")) +} + /// `` in the data folder in use (Settings › Folders › Data folder). #[cfg(not(target_arch = "wasm32"))] pub fn user_dir(sub: &str) -> std::path::PathBuf { - DATA_FOLDER.get().cloned().unwrap_or_else(|| data_folder("")).join(sub) + data_dir().join(sub) } /// Folder holding the user's smart materials. diff --git a/crates/ui-egui/src/log_panel.rs b/crates/ui-egui/src/log_panel.rs new file mode 100644 index 00000000..fe3a5311 --- /dev/null +++ b/crates/ui-egui/src/log_panel.rs @@ -0,0 +1,70 @@ +//! The Log panel: the session's messages under a General and an Assets tab, one per channel + +use egui::{RichText, Ui}; +use serde::{Deserialize, Serialize}; + +use crate::TextureCraftApp; +use crate::i18n::tr; + +/// The Log panel's channels, one tab each +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum LogChannel { + /// Everything that is not about assets: projects, exports, bakes, the UI + #[default] + General, + /// Loading and importing resources, templates, presets and materials + Assets, +} + +impl LogChannel { + pub const ALL: [LogChannel; 2] = [LogChannel::General, LogChannel::Assets]; + + pub fn name(self) -> &'static str { + match self { + LogChannel::General => "General", + LogChannel::Assets => "Assets", + } + } +} + +/// How messages about assets begin: a resource that does not decode, a skipped template or +/// preset, and the warnings of a PBR folder or MaterialX import +pub const ASSET_PREFIXES: [&str; 6] = ["resource ", "Project template skipped: ", "Export template skipped: ", "Brush preset skipped: ", "PBR ", "MaterialX "]; + +/// The channel a log message belongs to +pub fn channel_of(message: &str) -> LogChannel { + if ASSET_PREFIXES.iter().any(|prefix| message.starts_with(prefix)) { LogChannel::Assets } else { LogChannel::General } +} + +/// The Log panel body (a dock tab or rail popup) +pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { + ui.horizontal(|ui| { + for channel in LogChannel::ALL { + if ui.selectable_label(app.ui.log_channel == channel, tr(channel.name())).clicked() { + app.ui.log_channel = channel; + } + } + }); + ui.separator(); + + let shown = app.ui.log_channel; + egui::ScrollArea::vertical().id_salt(("log", shown.name())).auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { + for line in app.session.log.iter().filter(|line| channel_of(line) == shown) { + ui.label(RichText::new(line).monospace()); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn asset_messages_go_to_the_assets_channel() { + assert_eq!(channel_of("resource stone.png: unsupported format"), LogChannel::Assets); + assert_eq!(channel_of("Brush preset skipped: broken.json"), LogChannel::Assets); + assert_eq!(channel_of("PBR bricks: no roughness map"), LogChannel::Assets); + assert_eq!(channel_of("Saved /tmp/a.tcraft"), LogChannel::General); + assert_eq!(channel_of("Exported 4 textures to /tmp"), LogChannel::General); + } +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 16755672..deda8819 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -68,6 +68,7 @@ pub const CATALOG: &[Item] = &[ sub("Window", "Views", "Assets", "ui.view.assets", None), sub("Window", "Views", "Common Settings", "ui.view.bakeSettings", None), sub("Window", "Views", "Display Settings", "ui.view.display", None), + sub("Window", "Views", "Export", "ui.view.export", None), sub("Window", "Views", "History", "ui.view.history", None), sub("Window", "Views", "Layers", "ui.view.layers", None), sub("Window", "Views", "Log", "ui.view.log", None), @@ -108,12 +109,14 @@ pub const CATALOG: &[Item] = &[ it("Viewport", "3D/2D views", "ui.layout.split", Some("F1")), it("Viewport", "3D view only", "ui.layout.3d", Some("F2")), it("Viewport", "2D view only", "ui.layout.2d", Some("F3")), + it("Viewport", "Swap 3D/2D", "ui.layout.swap", Some("F4")), sep("Viewport"), it("Viewport", "Navigation buttons", "ui.navButtons", None), sep("Viewport"), it("Viewport", "Enable quick mask", "viewport.quickMask", Some("Y")), it("Viewport", "Edit quick mask", "viewport.quickMask.edit", Some("U")), it("Viewport", "Invert quick mask", "viewport.quickMask.invert", Some("Ctrl+Shift+I")), + it("Help", "Release notes...", "ui.help.releaseNotes", None), it("Help", "Documentation...", "ui.help.docs", None), it("Help", "Shortcuts list...", "ui.help.shortcuts", None), sep("Help"), @@ -121,6 +124,7 @@ pub const CATALOG: &[Item] = &[ it("Help", "ArtCraft website...", "ui.help.website", None), it("Help", "Report a bug...", "ui.help.bug", None), it("Help", "Show log...", "ui.view.log", None), + it("Help", "Export log...", "ui.help.exportLog", None), sep("Help"), #[cfg(not(target_arch = "wasm32"))] it("Help", "Check for Updates...", "ui.help.checkForUpdates", None), @@ -193,6 +197,9 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { match id { "ui.newProject" => app.ui.windows.new_project = true, "ui.export" => app.ui.windows.export = true, + + // The mesh export options come first; their Export leads to the file choice + "file.exportMesh" => app.ui.windows.mesh_export_options = true, "ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close), #[cfg(not(target_arch = "wasm32"))] "ui.projectConfig" => crate::project_config::open(app), @@ -218,6 +225,7 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { "ui.layout.split" => app.ui.layout = ViewLayout::Split, "ui.layout.3d" => app.ui.layout = ViewLayout::Only3D, "ui.layout.2d" => app.ui.layout = ViewLayout::Only2D, + "ui.layout.swap" => app.ui.swap_views = !app.ui.swap_views, "ui.help.shortcuts" => app.ui.windows.shortcuts = true, "ui.about" => app.ui.windows.about = true, #[cfg(not(target_arch = "wasm32"))] @@ -225,6 +233,8 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { "ui.help.discord" => ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft")), "ui.help.website" => ctx.open_url(egui::OpenUrl::new_tab("https://getartcraft.com/apps/texturecraft")), "ui.help.docs" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/texturecraft#readme")), + "ui.help.releaseNotes" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/texturecraft/releases")), + "ui.help.exportLog" => crate::windows::export_log(app), "ui.help.bug" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/texturecraft/issues")), _ => { if crate::windows::file_action(app, ctx, id) { diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs new file mode 100644 index 00000000..70909b67 --- /dev/null +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -0,0 +1,56 @@ +//! File > Export Mesh asks for the mesh export options first; Export then leads to the file choice + +use egui::Ui; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::unavailable; +use crate::widgets::primary_button; + +/// Indent of an option's checkbox under its choice +const OPTION_INDENT: f32 = 20.0; + +/// Width of the Cancel and Export buttons +const BUTTON_WIDTH: f32 = 130.0; + +/// The prompt, while File > Export Mesh waits on it +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + if !app.ui.windows.mesh_export_options { + return; + } + + let mut open = true; + let (mut export, mut cancel) = (false, false); + crate::windows::dialog("mesh_export_options", tr("Mesh Export Options"), &mut open).show(ctx, |ui| { + // TextureCraft exports the mesh as it is: triangulated, without displacement + ui.add(egui::RadioButton::new(true, tr("Without displacement/tessellation"))); + option(ui, true, tr("Apply triangulation")); + unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation")))); + option(ui, true, tr("Recompute vertex normals")); + ui.add_space(8.0); + + // One row keeps the window to its contents; a bare right-to-left layout fills the screen height + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let size = egui::vec2(BUTTON_WIDTH, ui.spacing().interact_size.y); + export = ui.add(primary_button(ui, tr("Export")).min_size(size)).clicked(); + cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(size)).clicked(); + }); + }); + }); + + if export { + app.ui.windows.mesh_export_options = false; + crate::windows::file_action(app, ctx, "file.exportMesh"); + } else if cancel || !open { + app.ui.windows.mesh_export_options = false; + } +} + +/// A greyed option under a choice, ticked as the reference shows it +fn option(ui: &mut Ui, checked: bool, label: &str) { + ui.horizontal(|ui| { + ui.add_space(OPTION_INDENT); + unavailable::checkbox(ui, checked, label); + }); +} diff --git a/crates/ui-egui/src/nav_buttons.rs b/crates/ui-egui/src/nav_buttons.rs index 7940dbf9..c291e0ab 100644 --- a/crates/ui-egui/src/nav_buttons.rs +++ b/crates/ui-egui/src/nav_buttons.rs @@ -6,7 +6,7 @@ use crate::i18n::tr; pub use crate::nav_button::NavButton; pub use crate::nav_view::NavView; use crate::theme::Tokens; -use crate::viewport::{DRAG_ZOOM_PER_POINT, ORBIT_RADIANS_PER_POINT, UV_VIEW_MAX_ZOOM, UV_VIEW_MIN_ZOOM, UV_WHEEL_ZOOM_PER_POINT}; +use crate::viewport::{DRAG_ZOOM_PER_POINT, UV_VIEW_MAX_ZOOM, UV_VIEW_MIN_ZOOM, UV_WHEEL_ZOOM_PER_POINT}; use egui::{Area, CursorIcon, Order, PointerButton, Rect, Sense, Ui, Vec2, pos2, vec2}; /// Button side, gap between buttons and the distance from the view's right edge, in points @@ -88,9 +88,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, view: NavView fn apply(app: &mut TextureCraftApp, rect: Rect, view: NavView, button: NavButton, delta: Vec2) { let size = rect.size(); match (view, button) { - (NavView::Scene, NavButton::Orbit) => app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT), + (NavView::Scene, NavButton::Orbit) => crate::viewport::orbit(app, delta), (NavView::Scene, NavButton::Pan) => app.session.camera.pan(delta.x / size.y, delta.y / size.y), - (NavView::Scene, NavButton::Zoom) => app.session.camera.zoom(-delta.y * DRAG_ZOOM_PER_POINT), + (NavView::Scene, NavButton::Zoom) => app.session.camera.zoom(-delta.y * DRAG_ZOOM_PER_POINT * app.ui.prefs.drag_zoom_scale()), (NavView::Uv, NavButton::Pan) => { app.ui.uv_pan[0] += delta.x / size.x * 2.0; app.ui.uv_pan[1] -= delta.y / size.y * 2.0; diff --git a/crates/ui-egui/src/rail_popup.rs b/crates/ui-egui/src/rail_popup.rs index 506d20d7..3a954fe4 100644 --- a/crates/ui-egui/src/rail_popup.rs +++ b/crates/ui-egui/src/rail_popup.rs @@ -1,4 +1,4 @@ -//! The rail's panels open in a popup beside their rail icon, one at a time; dragging its title docks or floats the panel +//! The rail's panels open in a popup beside their rail icon, one at a time; Undock or dragging its title floats or docks the panel use egui::{Id, Pos2, Rect, RichText, Sense, Ui}; use egui_phosphor::regular as ic; @@ -11,7 +11,8 @@ use crate::theme::Tokens; use crate::widgets::icon_button; /// The rail's panels, top to bottom, with their icons and Window ▸ Views ids -pub(crate) const RAIL_PANELS: [(Panel, &str, &str); 5] = [ +pub(crate) const RAIL_PANELS: [(Panel, &str, &str); 6] = [ + (Panel::Export, ic::EXPORT, "ui.view.export"), (Panel::Log, ic::FILE_TEXT, "ui.view.log"), (Panel::Display, ic::MONITOR, "ui.view.display"), (Panel::Shader, ic::SLIDERS_HORIZONTAL, "ui.view.shader"), @@ -34,9 +35,12 @@ const LIST_HEIGHT: f32 = 400.0; /// Gap between the popup and the rail const RAIL_GAP: f32 = 4.0; -/// Size of the close button in the popup's title row +/// Size of the Undock and Close buttons in the popup's title row const TITLE_BUTTON_SIZE: f32 = 22.0; +/// Gap between the Undock and Close buttons +const TITLE_BUTTON_GAP: f32 = 4.0; + /// The popup's area, whose rect egui remembers between frames fn area_id() -> Id { Id::unique("rail_popup") @@ -169,12 +173,13 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let frame = egui::Frame::popup(&ctx.global_style()).fill(tokens.panel).stroke(egui::Stroke::new(1.0, tokens.accent)); let (top_right, width) = placement(ctx, strip, icon); let mut closed = false; + let mut undocked = false; let mut dragged_from = None; egui::Area::new(area_id()).order(egui::Order::Foreground).pivot(egui::Align2::RIGHT_TOP).fixed_pos(top_right).show(ctx, |ui| { frame.show(ui, |ui| { ui.set_width(width - frame.total_margin().sum().x); let title_top = ui.cursor().top(); - (closed, dragged_from) = title_row(ui, &tokens, panel); + (closed, undocked, dragged_from) = title_row(ui, &tokens, panel); ui.separator(); // Keep the title, frame and body on screen even when the window is shorter than the usual popup @@ -186,6 +191,12 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if closed { app.ui.rail_panel = None; + } else if undocked { + // The floating window opens where the popup was, at its size + app.ui.rail_panel = None; + if let Some(rect) = shown { + app.ui.dock.float_at(panel, [rect.left(), rect.top(), rect.width(), rect.height()]); + } } else if let Some(title) = dragged_from { app.ui.rail_panel = None; let rect = shown.unwrap_or(title); @@ -226,16 +237,19 @@ fn body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel, available_height: }); } -/// The panel's name, which drags like a tab, and a close button: whether it was clicked, and where a drag started -fn title_row(ui: &mut Ui, tokens: &Tokens, panel: Panel) -> (bool, Option) { +/// The panel's name in capitals, which drags like a tab, then Undock and Close: whether each was clicked, and where a drag started +fn title_row(ui: &mut Ui, tokens: &Tokens, panel: Panel) -> (bool, bool, Option) { let row = ui.horizontal(|ui| { - ui.label(RichText::new(tr(panel.name())).strong().color(tokens.text_strong)); - ui.add_space((ui.available_width() - TITLE_BUTTON_SIZE).max(0.0)); - icon_button(ui, ic::X, tr("Close"), false, TITLE_BUTTON_SIZE) + ui.label(RichText::new(tr(panel.name()).to_uppercase()).strong().color(tokens.text_strong)); + ui.add_space((ui.available_width() - 2.0 * TITLE_BUTTON_SIZE - TITLE_BUTTON_GAP).max(0.0)); + let undock = icon_button(ui, ic::ARROW_SQUARE_OUT, tr("Undock"), false, TITLE_BUTTON_SIZE); + ui.add_space(TITLE_BUTTON_GAP); + let close = icon_button(ui, ic::X, tr("Close"), false, TITLE_BUTTON_SIZE); + (undock, close) }); - let (row, close) = (row.response.rect, row.inner); - let title = Rect::from_min_max(row.min, egui::pos2(close.rect.left(), row.bottom())); + let (row, (undock, close)) = (row.response.rect, row.inner); + let title = Rect::from_min_max(row.min, egui::pos2(undock.rect.left(), row.bottom())); let drag = ui.interact(title, ui.scope_id().with("rail_popup_title"), Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); - (close.clicked(), drag.drag_started().then_some(title)) + (close.clicked(), undock.clicked(), drag.drag_started().then_some(title)) } diff --git a/crates/ui-egui/src/section_page.rs b/crates/ui-egui/src/section_page.rs new file mode 100644 index 00000000..7fa75f3a --- /dev/null +++ b/crates/ui-egui/src/section_page.rs @@ -0,0 +1,125 @@ +//! A settings panel as one scrolling page: its section tabs jump to a section, and scrolling highlights the section in view + +use egui::Ui; + +use crate::i18n::tr; +use crate::theme::caption; +use crate::widgets::icon_button; + +/// One section of a page: its tab's icon, and its title (the tab's tooltip and, in capitals, the section's heading) +pub(crate) struct PageSection { + pub icon: &'static str, + pub title: &'static str, +} + +/// Size of a section tab +const TAB_SIZE: f32 = 28.0; + +/// A section counts as reached once its heading is this close to the top of the view, in points +const REACHED_TOLERANCE: f32 = 4.0; + +/// Space above every section heading after the first +const SECTION_GAP: f32 = 10.0; + +/// What a page remembers between frames +#[derive(Clone, Default)] +struct PageState { + /// Where each section's heading starts in the scrolled content + tops: Vec, + /// The highlighted tab + active: usize, + /// A tab clicked on the last frame, whose section the view scrolls to on this one + jump: Option, + /// The clicked section stays highlighted while the view stays where the jump left it, even when the page cannot scroll that far + pinned: Option<(usize, f32)>, +} + +/// The section tabs, then the sections in one scroll area; `body` draws section `index` under its heading +pub(crate) fn show(ui: &mut Ui, id_salt: &str, sections: &[PageSection], mut body: impl FnMut(&mut Ui, usize)) { + let id = ui.make_persistent_id(("section_page", id_salt)); + let mut state = ui.data(|data| data.get_temp::(id)).unwrap_or_default(); + + ui.horizontal(|ui| { + for (index, section) in sections.iter().enumerate() { + if icon_button(ui, section.icon, tr(section.title), state.active == index, TAB_SIZE).clicked() { + state.jump = Some(index); + } + } + }); + ui.separator(); + + let mut area = egui::ScrollArea::vertical().id_salt(id.with("scroll")).auto_shrink([false, true]); + let jumped = state.jump.take().and_then(|index| state.tops.get(index).map(|top| (index, *top))); + if let Some((_, top)) = jumped { + area = area.vertical_scroll_offset(top); + } + + let output = area.show(ui, |ui| { + let origin = ui.min_rect().top(); + let mut tops = Vec::with_capacity(sections.len()); + for (index, section) in sections.iter().enumerate() { + if index > 0 { + ui.add_space(SECTION_GAP); + ui.separator(); + } + tops.push(ui.cursor().top() - origin); + ui.label(caption(&tr(section.title).to_uppercase())); + body(ui, index); + } + tops + }); + + let offset = output.state.clamped_offset().y; + let bottom = (output.content_size.y - output.inner_rect.height()).max(0.0); + state.tops = output.inner; + if let Some((index, _)) = jumped { + state.pinned = Some((index, offset)); + } + + state.active = active_section(&state.tops, offset, bottom, &mut state.pinned); + ui.data_mut(|data| data.insert_temp(id, state)); +} + +/// The section whose heading the view has passed last, the last one once the view is at the bottom, or a clicked one while the view stays put +fn active_section(tops: &[f32], offset: f32, bottom: f32, pinned: &mut Option<(usize, f32)>) -> usize { + if let Some((index, pinned_offset)) = *pinned { + if (offset - pinned_offset).abs() <= REACHED_TOLERANCE && index < tops.len() { + return index; + } + + *pinned = None; + } + + let last = tops.len().saturating_sub(1); + if bottom > 0.0 && offset >= bottom - REACHED_TOLERANCE { + return last; + } + + tops.iter().rposition(|top| *top <= offset + REACHED_TOLERANCE).unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_section_the_view_passed_last_is_active() { + let tops = [0.0, 300.0, 700.0]; + let mut pinned = None; + assert_eq!(active_section(&tops, 0.0, 900.0, &mut pinned), 0); + assert_eq!(active_section(&tops, 299.0, 900.0, &mut pinned), 1, "within the tolerance"); + assert_eq!(active_section(&tops, 500.0, 900.0, &mut pinned), 1); + assert_eq!(active_section(&tops, 900.0, 900.0, &mut pinned), 2, "the bottom shows the last section"); + } + + #[test] + fn a_clicked_section_stays_active_until_the_view_moves() { + let tops = [0.0, 300.0, 700.0]; + + // The page cannot scroll to the last heading: the jump stops at the bottom, 400 + let mut pinned = Some((2, 400.0)); + assert_eq!(active_section(&tops, 400.0, 0.0, &mut pinned), 2); + assert_eq!(active_section(&tops, 100.0, 400.0, &mut pinned), 0); + assert!(pinned.is_none(), "scrolling away ends the pin"); + } +} diff --git a/crates/ui-egui/src/settings_window.rs b/crates/ui-egui/src/settings_window.rs new file mode 100644 index 00000000..282e281e --- /dev/null +++ b/crates/ui-egui/src/settings_window.rs @@ -0,0 +1,705 @@ +//! Edit > Settings: the General, Shortcuts and Libraries pages chosen in the left column. Changes +//! wait in a working copy until OK applies and keeps them; Cancel or closing the window drops them. + +use egui::{Color32, Response, RichText, Ui, vec2}; +use egui_phosphor::regular as ic; + +use crate::TextureCraftApp; +#[cfg(not(target_arch = "wasm32"))] +use crate::file_dialogs::{Bound, FileDialog}; +use crate::i18n::{LANGUAGES, SYSTEM_LANGUAGE, n_, tr, trf}; +use crate::keymap::Keymap; +use crate::state::{CAMERA_SPEED_RANGE, LibraryLocation, Prefs}; +use crate::theme::{Accent, Brightness, Tokens, caption}; +use crate::unavailable::NOT_AVAILABLE; +use crate::widgets::icon_button; + +/// The Libraries page's note on when locations can change. +pub const PROJECT_OPEN_NOTE: &str = n_("Library locations can't be added/removed when a project is opened."); + +/// The width of the left column of a row and of a page's controls. +const LABEL_WIDTH: f32 = 176.0; +const CONTROL_WIDTH: f32 = 340.0; +const PAGE_WIDTH: f32 = 560.0; +const PAGE_HEIGHT: f32 = 520.0; +/// The page buttons of the left column. +const PAGE_BUTTON: egui::Vec2 = vec2(84.0, 80.0); +const PAGE_ICON_SIZE: f32 = 44.0; + +/// A page of the Settings window. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum SettingsPage { + #[default] + General, + Shortcuts, + Libraries, +} + +impl SettingsPage { + pub const ALL: [SettingsPage; 3] = [SettingsPage::General, SettingsPage::Shortcuts, SettingsPage::Libraries]; + + pub fn label(self) -> &'static str { + match self { + SettingsPage::General => n_("General"), + SettingsPage::Shortcuts => n_("Shortcuts"), + SettingsPage::Libraries => n_("Libraries"), + } + } + + fn icon(self) -> &'static str { + match self { + SettingsPage::General => ic::GEAR, + SettingsPage::Shortcuts => ic::KEYBOARD, + SettingsPage::Libraries => ic::GRID_FOUR, + } + } +} + +/// What the Settings window shows and edits until OK or Cancel. +#[derive(Clone, Debug, PartialEq)] +pub struct SettingsDraft { + pub page: SettingsPage, + pub prefs: Prefs, + pub keymap: Keymap, + /// The shortcuts when the window opened: OK applies only what the Shortcuts page changed, + /// so a shortcut rebound meanwhile in Help > Shortcuts stays. + pub keymap_at_open: Keymap, + /// The Libraries page's Name and Path fields. + pub library_name: String, + pub library_path: String, +} + +impl SettingsDraft { + fn of(app: &TextureCraftApp) -> SettingsDraft { + SettingsDraft { + page: SettingsPage::General, + prefs: app.ui.prefs.clone(), + keymap: app.ui.keymap.clone(), + keymap_at_open: app.ui.keymap.clone(), + library_name: String::new(), + library_path: String::new(), + } + } + + /// Whether the Name and Path fields make a new location: both filled, a name not taken yet. + pub fn can_add_library(&self) -> bool { + let name = self.library_name.trim(); + !name.is_empty() + && !self.library_path.trim().is_empty() + && !built_in_locations().iter().any(|(built_in, _)| built_in == name) + && !self.prefs.libraries.iter().any(|location| location.name == name) + } +} + +/// A folder picked for the working copy. +#[cfg(not(target_arch = "wasm32"))] +enum Pick { + DataFolder, + LibraryPath, +} + +/// The Settings window, while `windows.settings` is set. +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + if !app.ui.windows.settings { + // Closed from elsewhere (Reset UI, a layout, the control channel): drop the edits and stop waiting for a key + if app.ui.windows.settings_draft.take().is_some() { + crate::keymap::stop_settings_capture(ctx); + } + return; + } + + let mut draft = app.ui.windows.settings_draft.take().unwrap_or_else(|| SettingsDraft::of(app)); + let mut open = true; + let (mut ok, mut cancel) = (false, false); + #[cfg(not(target_arch = "wasm32"))] + let mut pick = None; + let project_open = app.session.project_open; + let gpu = app.render_state.as_ref().map(|render_state| render_state.adapter.get_info().name); + + // A language whose script no font draws is listed by its English name and disabled + let drawable = LANGUAGES.each_ref().map(|l| crate::fonts::Script::of_language(l.code).is_none_or(|s| app.fonts.covers(s))); + #[cfg(not(target_arch = "wasm32"))] + let resources = settings_resources(ctx); + + crate::windows::window("settings", tr("Settings"), &mut open).resizable(false).show(ctx, |ui| { + // The window keeps to the column and the page; the OK and Cancel row would widen it otherwise + ui.set_max_width(PAGE_BUTTON.x + PAGE_WIDTH + 32.0); + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(PAGE_BUTTON.x); + for page in SettingsPage::ALL { + if page_button(ui, page, draft.page == page).clicked() { + draft.page = page; + } + ui.add_space(6.0); + } + }); + ui.add_space(8.0); + egui::ScrollArea::vertical() + .id_salt(("settings_page", draft.page as u8)) + .auto_shrink([false, false]) + .min_scrolled_height(PAGE_HEIGHT) + .max_height(PAGE_HEIGHT) + .show(ui, |ui| { + ui.vertical(|ui| { + ui.set_width(PAGE_WIDTH); + match draft.page { + SettingsPage::General => { + general( + ui, + &mut draft.prefs, + &drawable, + gpu.as_deref(), + #[cfg(not(target_arch = "wasm32"))] + resources, + #[cfg(not(target_arch = "wasm32"))] + &mut pick, + ); + } + SettingsPage::Shortcuts => { + ui.label(caption(tr("ACTIONS"))); + ui.add_space(4.0); + crate::keymap::actions_page(ui, &mut draft.keymap, &app.bindings, &mut app.settings_bindings); + } + SettingsPage::Libraries => { + libraries( + ui, + &mut draft, + project_open, + #[cfg(not(target_arch = "wasm32"))] + &mut pick, + ); + } + } + }); + }); + }); + ui.separator(); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(100.0, 0.0))).clicked(); + ok = ui.add(egui::Button::new(tr("OK")).min_size(vec2(100.0, 0.0))).clicked(); + }); + }); + }); + + if draft.page != SettingsPage::Shortcuts || ok || cancel || !open { + crate::keymap::stop_settings_capture(ctx); + } + if ok { + apply(app, draft); + } else if !(cancel || !open) { + app.ui.windows.settings_draft = Some(draft); + } + app.ui.windows.settings = !(ok || cancel || !open); + + #[cfg(not(target_arch = "wasm32"))] + if let Some(pick) = pick { + ask_folder(app, pick); + } +} + +/// OK: the working copy becomes the settings in use. +fn apply(app: &mut TextureCraftApp, draft: SettingsDraft) { + let libraries_changed = draft.prefs.libraries != app.ui.prefs.libraries; + app.ui.prefs = draft.prefs; + let ids: std::collections::BTreeSet<&String> = draft.keymap.keys().chain(draft.keymap_at_open.keys()).collect(); + for id in ids.into_iter().filter(|id| draft.keymap.get(*id) != draft.keymap_at_open.get(*id)) { + match draft.keymap.get(id) { + Some(shortcut) => app.ui.keymap.insert(id.clone(), shortcut.clone()), + None => app.ui.keymap.remove(id), + }; + } + app.ui.prefs.apply_resource_limits(); + + // The shelf reads the saved materials of the locations again + if libraries_changed { + app.library = None; + } +} + +/// The folder dialog of the data folder or of the Libraries page's Path, answered into the working copy. +#[cfg(not(target_arch = "wasm32"))] +fn ask_folder(app: &mut TextureCraftApp, pick: Pick) { + let Some(draft) = &app.ui.windows.settings_draft else { return }; + match pick { + Pick::DataFolder => { + let start = crate::data_folder(&draft.prefs.data_folder); + app.ask_file(FileDialog::folder().directory(start), Bound::App, |app, paths| { + if let (Some(dir), Some(draft)) = (paths.first(), app.ui.windows.settings_draft.as_mut()) { + draft.prefs.data_folder = dir.display().to_string(); + } + }); + } + Pick::LibraryPath => { + let start = Some(std::path::PathBuf::from(draft.library_path.trim())).filter(|path| path.is_dir()).unwrap_or_else(crate::data_dir); + app.ask_file(FileDialog::folder().directory(start), Bound::App, |app, paths| { + if let (Some(dir), Some(draft)) = (paths.first(), app.ui.windows.settings_draft.as_mut()) { + draft.library_path = dir.display().to_string(); + } + }); + } + } +} + +/// A page of the left column: a big icon over its caption, the caption highlighted when chosen. +fn page_button(ui: &mut Ui, page: SettingsPage, selected: bool) -> Response { + let tk = Tokens::get(ui.ctx()); + let label = tr(page.label()); + let (rect, response) = ui.allocate_exact_size(PAGE_BUTTON, egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, selected, label)); + let icon_color = if selected { + tk.accent + } else if response.hovered() { + tk.text_strong + } else { + tk.text + }; + let painter = ui.painter(); + painter.text(rect.center_top() + vec2(0.0, 4.0), egui::Align2::CENTER_TOP, page.icon(), egui::FontId::proportional(PAGE_ICON_SIZE), icon_color); + let text_color = if selected { tk.accent } else { tk.text }; + let text = painter.text(rect.center_bottom() - vec2(0.0, 6.0), egui::Align2::CENTER_BOTTOM, label, egui::FontId::proportional(12.5), text_color); + if selected { + painter.rect_stroke(text.expand2(vec2(3.0, 1.0)), 2.0, egui::Stroke::new(1.0, tk.accent), egui::StrokeKind::Outside); + } + response +} + +/// `response` of a disabled control says the function is not available yet. +fn not_available(response: Response) -> Response { + response.on_disabled_hover_text(tr(NOT_AVAILABLE)) +} + +/// A row of a section: `label` on the left, `control` beside it. +fn row(ui: &mut Ui, label: &str, control: impl FnOnce(&mut Ui, egui::Id) -> R) -> R { + ui.horizontal(|ui| { + ui.add_space(12.0); + let label = ui + .vertical(|ui| { + ui.set_width(LABEL_WIDTH); + ui.add(egui::Label::new(label).wrap()) + }) + .inner; + control(ui, label.id) + }) + .inner +} + +/// A section caption with the space above it. +fn section(ui: &mut Ui, title: &str) { + ui.add_space(10.0); + ui.label(caption(tr(title))); + ui.add_space(2.0); +} + +/// A disabled check box in the right column of a row labelled `label`. +fn disabled_check(ui: &mut Ui, label: egui::Id, mut checked: bool) { + not_available(ui.add_enabled(false, egui::Checkbox::without_text(&mut checked)).labelled_by(label)); +} + +/// A disabled check box with its text. +fn disabled_text_check(ui: &mut Ui, text: &str, mut checked: bool) { + ui.horizontal(|ui| { + ui.add_space(12.0); + not_available(ui.add_enabled(false, egui::Checkbox::new(&mut checked, tr(text)))); + }); +} + +/// A slider row: `label` and the value above the track, whole steps shown without decimals. +fn speed_slider(ui: &mut Ui, label: &str, value: &mut f32, width: f32) -> Response { + ui.vertical(|ui| { + ui.set_width(width); + let decimals = if value.fract() == 0.0 { 0 } else { 1 }; + let response = crate::widgets::slider(ui, label, value, CAMERA_SPEED_RANGE, decimals); + + // Tenths: the shown value is the value used + *value = ((*value * 10.0).round() / 10.0).clamp(*CAMERA_SPEED_RANGE.start(), *CAMERA_SPEED_RANGE.end()); + response + }) + .inner +} + +/// The General page. +fn general( + ui: &mut Ui, + p: &mut Prefs, + drawable: &[bool], + gpu: Option<&str>, + #[cfg(not(target_arch = "wasm32"))] (available_cores, available_ram_bytes): (u32, u64), + #[cfg(not(target_arch = "wasm32"))] pick: &mut Option, +) { + let tk = Tokens::get(ui.ctx()); + section(ui, n_("INTERFACE OPTIONS")); + row(ui, tr("Language"), |ui, label| { + let selected = if p.language == SYSTEM_LANGUAGE { + tr("Default (System Language)") + } else { + LANGUAGES.iter().find(|l| l.code == p.language).map_or(tr("Default (System Language)"), |l| l.name) + }; + egui::ComboBox::from_id_salt("settings_language") + .width(CONTROL_WIDTH) + .height(320.0) + .selected_text(selected) + .show_ui(ui, |ui| { + ui.selectable_value(&mut p.language, SYSTEM_LANGUAGE.to_owned(), tr("Default (System Language)")); + for (l, ok) in LANGUAGES.iter().zip(drawable).filter(|(l, _)| crate::i18n::available(l.code)) { + let item = egui::Button::selectable(l.code == p.language, if *ok { l.name } else { l.english }); + if ui.add_enabled(*ok, item).on_disabled_hover_text(tr("No font on this system can show this language")).clicked() { + p.language = l.code.to_owned(); + } + } + }) + .response + .labelled_by(label); + }); + row(ui, tr("Show keyboard helper"), |ui, label| disabled_check(ui, label, true)); + row(ui, tr("Show world axes"), |ui, label| disabled_check(ui, label, true)); + row(ui, tr("Background color"), |ui, _| { + for gray in [0x1e, 0x26] { + let swatch = egui::Button::new("").fill(Color32::from_gray(gray)).min_size(vec2(38.0, 18.0)); + not_available(ui.add_enabled(false, swatch)); + not_available(ui.add_enabled(false, egui::Button::new(ic::EYEDROPPER).frame(false))); + ui.add_space(10.0); + } + }); + row(ui, tr("Only display the selected material when painting"), |ui, label| disabled_check(ui, label, false)); + row(ui, tr("Viewport Scaling"), |ui, label| { + ui.add_enabled_ui(false, |ui| { + not_available( + egui::ComboBox::from_id_salt("settings_viewport_scaling").width(CONTROL_WIDTH).selected_text(tr("Auto")).show_ui(ui, |_| {}).response, + ) + .labelled_by(label); + }); + }); + + section(ui, n_("LAYER STACK OPTIONS")); + ui.horizontal(|ui| { + ui.add_space(12.0); + ui.add_enabled_ui(false, |ui| { + let mut uv_scale = 1.0; + ui.vertical(|ui| { + ui.set_width(PAGE_WIDTH - 24.0); + not_available(crate::widgets::slider(ui, tr("Default UV scale for materials"), &mut uv_scale, 0.0..=10.0, 0)); + }); + }); + }); + disabled_text_check(ui, n_("Use simplified thumbnails (improves performance)"), true); + + section(ui, n_("CAMERA OPTIONS")); + let speed_width = CONTROL_WIDTH + 12.0; + ui.horizontal(|ui| { + ui.add_space(12.0); + speed_slider(ui, tr("Rotation speed"), &mut p.rotation_speed, speed_width); + }); + for (label, speed, inverse) in [(tr("Zoom speed"), &mut p.zoom_speed, &mut p.zoom_inverse), (tr("Wheel speed"), &mut p.wheel_speed, &mut p.wheel_inverse)] { + ui.horizontal(|ui| { + ui.add_space(12.0); + speed_slider(ui, label, speed, speed_width); + ui.add_space(8.0); + ui.checkbox(inverse, tr("Inverse direction")); + }); + } + + section(ui, n_("BAKING OPTIONS")); + disabled_text_check(ui, n_("Save preprocessed scene files"), true); + disabled_text_check(ui, n_("Enable live preview baking process"), true); + ui.horizontal(|ui| { + ui.add_space(12.0); + ui.checkbox(&mut p.gpu_raytracing, tr("Enable GPU raytracing")) + .on_hover_text(tr("Bakes cast their rays on the graphics card when one is available. Off, they run on the CPU.")); + }); + + section(ui, n_("PREVIEW OPTIONS")); + row(ui, tr("Local cache directory"), |ui, label| { + ui.add_enabled_ui(false, |ui| { + let mut path = String::new(); + not_available(ui.add(egui::TextEdit::singleline(&mut path).desired_width(CONTROL_WIDTH - 24.0))).labelled_by(label); + not_available(ui.add(egui::Button::new("R").frame(false))); + }); + }); + row(ui, tr("Local cache budget (in MB)"), |ui, label| { + let mut budget = 4000_u32; + ui.spacing_mut().item_spacing.x = 2.0; + not_available(ui.add_enabled(false, egui::Button::new("−").frame(false))); + not_available(ui.add_enabled(false, egui::Button::new("+").frame(false))); + not_available(ui.add_enabled(false, egui::DragValue::new(&mut budget))).labelled_by(label); + }); + row(ui, tr("Material preview shader"), |ui, _| { + let text = format!("{}\n{}", tr("Select a preview shader"), tr("(default)")); + not_available(ui.add_enabled(false, egui::Button::new(text).min_size(vec2(CONTROL_WIDTH, 40.0)))); + }); + + section(ui, n_("TEMPORARY FILES")); + row(ui, tr("Cache directory"), |ui, label| { + #[cfg(not(target_arch = "wasm32"))] + let mut path = std::env::temp_dir().display().to_string(); + #[cfg(target_arch = "wasm32")] + let mut path = String::new(); + ui.add_enabled_ui(false, |ui| { + not_available(ui.add(egui::TextEdit::singleline(&mut path).desired_width(CONTROL_WIDTH - 24.0))).labelled_by(label); + not_available(ui.add(egui::Button::new("R").frame(false))); + }); + }); + + section(ui, n_("SPARSE VIRTUAL TEXTURE")); + disabled_text_check(ui, n_("Hardware support acceleration"), true); + + section(ui, n_("IRAY HARDWARE")); + disabled_text_check(ui, gpu.unwrap_or(n_("no GPU")), true); + disabled_text_check(ui, n_("CPU"), false); + + // TextureCraft's own settings, after the reference sections + section(ui, n_("APPEARANCE")); + row(ui, tr("Interface scale"), |ui, label| { + ui.add(egui::Slider::new(&mut p.ui_scale, 0.75..=2.0).fixed_decimals(2)).labelled_by(label); + }); + row(ui, tr("Brightness"), |ui, label| { + egui::ComboBox::from_id_salt("settings_brightness") + .width(140.0) + .selected_text(tr(p.brightness.label())) + .show_ui(ui, |ui| { + for b in Brightness::ALL { + ui.selectable_value(&mut p.brightness, b, tr(b.label())); + } + }) + .response + .labelled_by(label); + }); + row(ui, tr("Accent color"), |ui, _| { + for a in Accent::ALL { + let (rect, resp) = ui.allocate_exact_size(vec2(20.0, 20.0), egui::Sense::click()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, p.accent == a, tr(a.label()))); + let ring = if p.accent == a { + tk.text_strong + } else if resp.hovered() { + tk.text_dim + } else { + Color32::TRANSPARENT + }; + ui.painter().circle(rect.center(), 6.5, a.colors(tk.dark).0, egui::Stroke::NONE); + ui.painter().circle_stroke(rect.center(), 9.0, egui::Stroke::new(1.5, ring)); + if resp.on_hover_text(tr(a.label())).clicked() { + p.accent = a; + } + } + }); + #[cfg(not(target_arch = "wasm32"))] + { + row(ui, tr("Title bar"), |ui, _| { + ui.checkbox(&mut p.system_title_bar, tr("System title bar (applies on restart)")) + .on_hover_text(tr("Use the operating system's window frame and buttons instead of TextureCraft's own title bar")); + }); + } + + section(ui, n_("VIEWPORT")); + row(ui, tr("Texture resolution"), |ui, _| { + ui.horizontal(|ui| { + for (v, l) in [(0u8, tr("Full")), (1, tr("Half")), (2, tr("Quarter"))] { + ui.selectable_value(&mut p.viewport_texture, v, l); + } + }) + .response + .on_hover_text(tr( + "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", + )); + }); + + section(ui, n_("RESOURCES")); + #[cfg(not(target_arch = "wasm32"))] + { + row(ui, tr("Max CPU threads for work"), |ui, label| { + ui.add(egui::DragValue::new(&mut p.work_threads).range(0..=available_cores)) + .labelled_by(label) + .on_hover_text(tr("Threads that paint, bake and export. 0 uses every CPU thread. Applies on restart.")); + }); + row(ui, tr("Cores kept for the UI"), |ui, label| { + ui.add(egui::DragValue::new(&mut p.reserved_cores).range(0..=available_cores)).labelled_by(label); + }); + row(ui, tr("Max RAM while saving"), |ui, label| { + ui.add(egui::DragValue::new(&mut p.save_ram_percent).range(1..=100).suffix(" %")).labelled_by(label); + let budget_bytes = texturecraft_engine::formats::save_ram_budget(available_ram_bytes, p.save_ram_percent); + ui.label(format!("≈ {:.2} GiB", budget_bytes as f64 / (1_u64 << 30) as f64)); + }); + } + row(ui, tr("Max project size on open"), |ui, label| { + ui.add(egui::DragValue::new(&mut p.project_open_limit_gib).range(1..=u32::MAX).suffix(" GiB")) + .labelled_by(label) + .on_hover_text(tr("Maximum decompressed project data. Increase this limit to open larger projects.")); + }); + #[cfg(not(target_arch = "wasm32"))] + { + note(ui, tr("Saving uses the other cores and at most this share of the free RAM. At least one core always works.")); + } + + #[cfg(not(target_arch = "wasm32"))] + { + section(ui, n_("AUTOSAVE")); + row(ui, tr("Autosave every"), |ui, label| { + ui.add(egui::DragValue::new(&mut p.autosave_minutes).range(0..=120).suffix(format!(" {}", tr("min")))).labelled_by(label); + }); + note(ui, &trf("0 turns autosave off. Copies go to {folder}", &[("folder", &crate::user_dir("autosave").display())])); + + section(ui, n_("FOLDERS")); + row(ui, tr("Data folder"), |ui, label| { + let default = crate::data_folder("").display().to_string(); + ui.add(egui::TextEdit::singleline(&mut p.data_folder).hint_text(default).desired_width(CONTROL_WIDTH - 30.0)).labelled_by(label); + if ui.button("...").on_hover_text(tr("Choose the data folder")).clicked() { + *pick = Some(Pick::DataFolder); + } + }); + for (label, dir) in [(tr("Smart materials"), crate::library_dir()), (tr("UI layouts"), crate::user_dir("layouts"))] { + row(ui, label, |ui, _| ui.label(RichText::new(dir.display().to_string()).small().color(tk.text_dim))); + } + note( + ui, + tr( + "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", + ), + ); + } +} + +/// A small dim note under a section's rows. +#[cfg(not(target_arch = "wasm32"))] +fn note(ui: &mut Ui, text: &str) { + let tk = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.add_space(12.0); + ui.add(egui::Label::new(RichText::new(text).small().color(tk.text_dim)).wrap()); + }); +} + +/// The built-in library locations as (name, path): the user's assets in the data folder, the +/// assets built into TextureCraft, and the font folders text alphas read. +pub fn built_in_locations() -> Vec<(String, String)> { + let mut out = Vec::new(); + #[cfg(not(target_arch = "wasm32"))] + out.push(("your_assets".to_owned(), crate::data_dir().display().to_string())); + out.push(("starter_assets".to_owned(), tr("(built in)").to_owned())); + #[cfg(not(target_arch = "wasm32"))] + { + let (system, user) = texturecraft_engine::formats::fonts::font_folders(); + let joined = |dirs: Vec| dirs.iter().map(|dir| dir.display().to_string()).collect::>().join("; "); + out.push(("system_fonts".to_owned(), joined(system))); + out.push(("user_fonts".to_owned(), joined(user))); + } + out +} + +/// `text` cut at its start with "…" to fit `width` points in `font`. +fn elide_start(ui: &Ui, text: &str, font: &egui::FontId, width: f32) -> String { + let fits = |text: &str| ui.painter().layout_no_wrap(text.to_owned(), font.clone(), Color32::WHITE).rect.width() <= width; + if fits(text) { + return text.to_owned(); + } + let chars: Vec = text.chars().collect(); + let shown = |from: usize| format!("…{}", chars.get(from..).unwrap_or_default().iter().collect::()); + + // The longest tail that fits; every shorter tail fits too + let (mut low, mut high) = (1, chars.len()); + while low < high { + let mid = low + (high - low) / 2; + if fits(&shown(mid)) { + high = mid; + } else { + low = mid + 1; + } + } + shown(low) +} + +/// The Libraries page. +fn libraries(ui: &mut Ui, draft: &mut SettingsDraft, project_open: bool, #[cfg(not(target_arch = "wasm32"))] pick: &mut Option) { + let tk = Tokens::get(ui.ctx()); + // The browser has no folders to add + let can_change = !project_open && !cfg!(target_arch = "wasm32"); + section(ui, n_("LIBRARY LOCATIONS")); + ui.horizontal(|ui| { + ui.vertical(|ui| { + row(ui, tr("Name"), |ui, label| { + ui.add_enabled(can_change, egui::TextEdit::singleline(&mut draft.library_name).desired_width(CONTROL_WIDTH)).labelled_by(label); + }); + row(ui, tr("Path"), |ui, label| { + ui.add_enabled(can_change, egui::TextEdit::singleline(&mut draft.library_path).desired_width(CONTROL_WIDTH - 24.0)).labelled_by(label); + let browse = ui.add_enabled(can_change, egui::Button::new("...").frame(false)).on_hover_text(tr("Choose the folder")); + #[cfg(not(target_arch = "wasm32"))] + if browse.clicked() { + *pick = Some(Pick::LibraryPath); + } + #[cfg(target_arch = "wasm32")] + not_available(browse); + }); + }); + let add = ui.add_enabled_ui(can_change && draft.can_add_library(), |ui| icon_button(ui, ic::PLUS, tr("Add the location"), false, 24.0)).inner; + let add = if cfg!(target_arch = "wasm32") { not_available(add) } else { add }; + if add.clicked() { + draft.prefs.libraries.push(LibraryLocation { name: draft.library_name.trim().to_owned(), path: draft.library_path.trim().to_owned() }); + draft.library_name.clear(); + draft.library_path.clear(); + } + }); + ui.horizontal(|ui| { + ui.add_space(12.0); + ui.label(tr(PROJECT_OPEN_NOTE)); + }); + ui.add_space(6.0); + + let mut remove = None; + egui::Frame::new().fill(tk.field).inner_margin(6.0).corner_radius(3.0).show(ui, |ui| { + ui.set_width(PAGE_WIDTH - 12.0); + ui.label(tr("Locations:")); + let font = egui::TextStyle::Body.resolve(ui.style()); + let built_in = built_in_locations(); + let added = draft.prefs.libraries.iter().map(|location| (location.name.clone(), location.path.clone())); + for (i, (name, path)) in built_in.iter().cloned().chain(added).enumerate() { + let is_built_in = i < built_in.len(); + ui.horizontal(|ui| { + let left = egui::Layout::left_to_right(egui::Align::Center); + ui.allocate_ui_with_layout(vec2(120.0, 24.0), left, |ui| { + ui.set_min_width(120.0); + ui.add(egui::Label::new(RichText::new(&name).strong()).truncate()); + }); + let shown = elide_start(ui, &path, &font, 260.0); + ui.allocate_ui_with_layout(vec2(270.0, 24.0), left, |ui| { + ui.set_min_width(270.0); + ui.label(RichText::new(shown).italics()).on_hover_text(&path); + }); + + // New assets are saved to the user's assets; another default needs the asset model to choose + let is_default = i == 0 && !cfg!(target_arch = "wasm32"); + let radio = ui.add_enabled(is_default, egui::RadioButton::new(is_default, tr("Default"))); + not_available(radio); + let label = trf("Remove {name}", &[("name", &name)]); + let minus = ui.add_enabled_ui(can_change && !is_built_in, |ui| icon_button(ui, ic::MINUS, &label, false, 20.0)).inner; + let minus = if is_built_in { not_available(minus) } else { minus }; + if minus.clicked() { + remove = i.checked_sub(built_in.len()); + } + }); + } + }); + if let Some(index) = remove + && index < draft.prefs.libraries.len() + { + draft.prefs.libraries.remove(index); + } +} + +/// The logical CPUs and free RAM, read once a second while Settings is open (not every frame). +#[cfg(not(target_arch = "wasm32"))] +fn settings_resources(ctx: &egui::Context) -> (u32, u64) { + let id = egui::Id::unique("settings_resources"); + let now = ctx.input(|input| input.time); + ctx.request_repaint_after(std::time::Duration::from_secs(1)); + + if let Some((sampled_at, cores, available_ram_bytes)) = ctx.data(|data| data.get_temp::<(f64, u32, u64)>(id)) + && (0.0..1.0).contains(&(now - sampled_at)) + { + return (cores, available_ram_bytes); + } + + let (cores, available_ram_bytes) = texturecraft_engine::formats::available_save_resources(); + let cores = u32::try_from(cores).unwrap_or(u32::MAX); + ctx.data_mut(|data| data.insert_temp(id, (now, cores, available_ram_bytes))); + (cores, available_ram_bytes) +} diff --git a/crates/ui-egui/src/shader_settings.rs b/crates/ui-egui/src/shader_settings.rs new file mode 100644 index 00000000..b4b9c055 --- /dev/null +++ b/crates/ui-egui/src/shader_settings.rs @@ -0,0 +1,251 @@ +//! The Shader Settings panel: the shader and its instance name, then shader parameters and displacement on one scrolling page + +use egui::{RichText, Ui, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::core::project::DisplaySettings; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::section_page::{self, PageSection}; +use crate::theme::Tokens; +use crate::unavailable::{self, NOT_AVAILABLE}; +use crate::widgets::{color_swatch, combo, section, slider}; + +/// The page's sections, in the reference's tab order +pub(crate) const SECTIONS: [PageSection; 2] = + [PageSection { icon: ic::GLOBE_HEMISPHERE_WEST, title: "Shader parameters" }, PageSection { icon: ic::DIAMOND, title: "Displacement & tessellation" }]; + +/// The shader TextureCraft draws with, the one its shader button names +pub const CURRENT_SHADER: &str = "open-pbr"; + +/// The shader choice lists these, as the reference's list shows them; the names it cuts short stay cut short +pub const SHADER_TYPES: [&str; 17] = [ + "asm-...", + "clay", + "dota-2", + "non-p...", + CURRENT_SHADER, + "pbr-ca...", + "pbr-co...", + "pbr-m...", + "pbr-m...", + "pbr-m...", + "pbr-m...", + "pbr-m...", + "pbr-m...", + "pbr-sp...", + "pbr-ve...", + "vraymt...", + "vraymt...", +]; + +/// The shader choice's search starts as the reference's: shaders only +pub const SHADER_QUERY: &str = "u:shader"; + +/// The reference's default instance name +const INSTANCE_NAME: &str = "Main shader"; + +/// Wide enough for the longer shader model name +const SHADER_MODEL_COMBO_WIDTH: f32 = 260.0; + +/// Width of the scatter color swatch +const SCATTER_SWATCH_WIDTH: f32 = 44.0; + +/// Index of refraction slider range: air to well past diamond (2.42) +const INDEX_OF_REFRACTION_RANGE: std::ops::RangeInclusive = 1.0..=3.0; + +/// Values the reference's panel shows for controls TextureCraft lacks +const SCATTER_ANISOTROPY_SHOWN: f32 = 0.1; +const SUBDIVISION_COUNT_SHOWN: f32 = 1.0; + +/// Size of a tile in the shader choice, and the columns it has +const SHADER_TILE_SIZE: egui::Vec2 = vec2(64.0, 64.0); +const SHADER_TILE_COLUMNS: usize = 5; + +/// Size of the shader choice's reset button +const RESET_QUERY_SIZE: f32 = 22.0; + +/// The Shader Settings panel body (a dock tab or rail popup) +pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { + header(ui); + + let mut display = app.session.doc.project.display.clone(); + let before = display.clone(); + section_page::show(ui, "shader_settings", &SECTIONS, |ui, index| match index { + 0 => shader_parameters(ui, &mut display), + _ => displacement(ui, &mut display), + }); + + if display != before { + app.session.doc.project.display = display; + } +} + +/// Undo and Redo of the shader's settings, the shader button and the instance name +fn header(ui: &mut Ui) { + ui.columns(2, |columns| { + let width = columns[0].available_width(); + unavailable::greyed(&mut columns[0], |ui| ui.add_sized([width, ui.spacing().interact_size.y], egui::Button::new(tr("Undo")))); + unavailable::greyed(&mut columns[1], |ui| ui.add_sized([width, ui.spacing().interact_size.y], egui::Button::new(tr("Redo")))); + }); + + let shader = ui.add_sized([ui.available_width(), ui.spacing().interact_size.y], egui::Button::new(CURRENT_SHADER)); + egui::Popup::menu(&shader).id(ui.make_persistent_id("shader_choice")).show(shader_choice); + + ui.horizontal(|ui| { + ui.label(tr("Instance name")); + let mut name = tr(INSTANCE_NAME).to_string(); + unavailable::greyed(ui, |ui| ui.add(egui::TextEdit::singleline(&mut name).desired_width(ui.available_width()))); + }); +} + +/// The shader choice under the shader button: a search, and a tile for each shader the reference lists (only the current one works) +fn shader_choice(ui: &mut Ui) { + let query_id = ui.make_persistent_id("shader_query"); + let mut query = ui.data(|data| data.get_temp::(query_id)).unwrap_or_else(|| SHADER_QUERY.to_string()); + ui.horizontal(|ui| { + let field_width = SHADER_TILE_SIZE.x * SHADER_TILE_COLUMNS as f32 - RESET_QUERY_SIZE; + ui.add(egui::TextEdit::singleline(&mut query).desired_width(field_width)); + if crate::widgets::icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Reset"), false, RESET_QUERY_SIZE).clicked() { + query = SHADER_QUERY.to_string(); + } + }); + ui.data_mut(|data| data.insert_temp(query_id, query.clone())); + + egui::Grid::new("shader_types").spacing(vec2(4.0, 4.0)).show(ui, |ui| { + let mut shown = 0; + for name in SHADER_TYPES.iter().filter(|name| matches_query(name, &query)) { + let tile = egui::Button::selectable(*name == CURRENT_SHADER, RichText::new(format!("{}\n{name}", ic::SPHERE))).min_size(SHADER_TILE_SIZE); + if *name == CURRENT_SHADER { + if ui.add(tile).clicked() { + ui.close(); + } + } else { + ui.add_enabled(false, tile).on_disabled_hover_text(tr(NOT_AVAILABLE)); + } + + shown += 1; + if shown % SHADER_TILE_COLUMNS == 0 { + ui.end_row(); + } + } + }); +} + +/// Whether a shader's name has every word of the query; `u:` words name the resource kind, which every entry is +pub fn matches_query(name: &str, query: &str) -> bool { + query.split_whitespace().filter(|word| !word.starts_with("u:")).all(|word| name.to_lowercase().contains(&word.to_lowercase())) +} + +/// Base Surface, Specular, Transmission and Subsurface +fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings) { + let tokens = Tokens::get(ui.ctx()); + section(ui, "shader_base_surface", tr("Base Surface"), true, |ui| { + shader_model(ui, display); + slider(ui, tr("AO Intensity"), &mut display.ao_intensity, 0.0..=1.0, 2); + }); + section(ui, "shader_specular", tr("Specular"), true, |ui| { + unavailable::checkbox(ui, false, tr("Enable anisotropy")); + slider(ui, tr("Index of refraction"), &mut display.ior, INDEX_OF_REFRACTION_RANGE, 2).on_hover_text(tr( + "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + )); + unavailable::checkbox(ui, false, tr("Enable specular color")); + }); + section(ui, "shader_transmission", tr("Transmission"), true, |ui| { + unavailable::checkbox(ui, false, tr("Enable transmission")); + }); + section(ui, "shader_subsurface", tr("Subsurface"), true, |ui| { + unavailable::checkbox(ui, true, tr("Enable")); + slider(ui, tr("Subsurface radius"), &mut display.scatter_radius, 0.0..=1.0, 3) + .on_hover_text(tr("How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)")); + unavailable::slider(ui, tr("Subsurface scatter anisotropy"), SCATTER_ANISOTROPY_SHOWN, -1.0..=1.0, 1); + unavailable::checkbox(ui, false, tr("Use thickness map")); + ui.horizontal(|ui| { + ui.label(RichText::new(tr("Scatter color")).color(tokens.text)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + color_swatch(ui, "shader_scatter_color", &mut display.scatter_color, SCATTER_SWATCH_WIDTH) + }) + }) + .response + .on_hover_text(tr("Color of the light that travels under the surface (each channel goes as far as its value)")); + }); +} + +/// TextureCraft's two material models, with what each reads and how it lights +fn shader_model(ui: &mut Ui, display: &mut DisplaySettings) { + let model_name = |spec_gloss: bool| if spec_gloss { tr("TextureCraft PBR - Specular Glossiness") } else { tr("TextureCraft PBR - Metallic Roughness") }; + let channels = if display.spec_gloss { + tr("Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).") + } else { + tr("Base color, Metallic, Roughness and Specular level.") + }; + let model_text = tr( + "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", + ); + let optional = tr( + "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", + ); + + egui::ComboBox::from_id_salt("shader_model") + .width(SHADER_MODEL_COMBO_WIDTH.min(ui.available_width())) + .selected_text(model_name(display.spec_gloss)) + .show_ui(ui, |ui| { + for spec_gloss in [false, true] { + ui.selectable_value(&mut display.spec_gloss, spec_gloss, model_name(spec_gloss)); + } + }) + .response + .on_hover_text(format!("{model_text} {channels} {optional}")); +} + +/// The displacement switch, parallax, the displacement source and the tessellation, with Restore defaults +fn displacement(ui: &mut Ui, display: &mut DisplaySettings) { + ui.checkbox(&mut display.displacement, tr("Enable")).on_hover_text(tr( + "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", + )); + ui.checkbox(&mut display.parallax, tr("Parallax occlusion (height channel)")) + .on_hover_text(tr("Offsets the textures by the height channel, at the height to normal strength")); + + section(ui, "shader_displacement", tr("Displacement"), true, |ui| { + // The height channel is the only source TextureCraft displaces by + combo(ui, tr("Source Channel"), tr("Height"), |ui| { + let _ = ui.selectable_label(true, tr("Height")); + }); + unavailable::combo(ui, tr("Scale unit"), tr("Normalized")); + unavailable::slider(ui, tr("Scale amount"), 0.0, -1.0..=1.0, 0); + }); + section(ui, "shader_tessellation", tr("Tessellation"), true, |ui| { + unavailable::combo(ui, tr("Subdivision Mode"), tr("Uniform")); + unavailable::slider(ui, tr("Subdivision Count"), SUBDIVISION_COUNT_SHOWN, 1.0..=6.0, 0); + }); + + // One row keeps the button to its height; a bare right-to-left layout fills the page + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let defaults = DisplaySettings::default(); + let at_default = display.displacement == defaults.displacement && display.parallax == defaults.parallax; + if ui.add_enabled(!at_default, egui::Button::new(tr("Restore defaults"))).clicked() { + display.displacement = defaults.displacement; + display.parallax = defaults.parallax; + } + }); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_query_matches_every_word_but_the_kind() { + assert!(matches_query(CURRENT_SHADER, SHADER_QUERY)); + assert!(matches_query(CURRENT_SHADER, "u:shader open")); + assert!(matches_query("pbr-sp...", "PBR")); + assert!(!matches_query("clay", "u:shader pbr")); + } + + #[test] + fn the_list_names_the_current_shader_once() { + assert_eq!(SHADER_TYPES.iter().filter(|name| **name == CURRENT_SHADER).count(), 1); + } +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index cb35ec8d..89370183 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -424,7 +424,7 @@ pub(crate) fn categories(items: &[T], category: impl Fn(&T) -> &'static str) out } -/// Read the user's saved smart materials (desktop library folder) unless they are already listed +/// Read the user's saved smart materials (desktop library folder and the added library locations) unless they are already listed #[cfg(not(target_arch = "wasm32"))] fn scan_library(app: &mut TextureCraftApp) { if app.library.is_some() { @@ -435,9 +435,16 @@ fn scan_library(app: &mut TextureCraftApp) { path.extension() .is_some_and(|extension| extension == "tcmat" || extension == MCMAT_EXT || extension == texturecraft_engine::smart_masks::SMART_MASK_EXT) }; - let mut files: Vec = - std::fs::read_dir(crate::library_dir()).map(|dir| dir.flatten().map(|entry| entry.path()).filter(saved_asset).collect()).unwrap_or_default(); + // The library folder, then each location added in Settings > Libraries + let added = app.ui.prefs.libraries.iter().map(|location| std::path::PathBuf::from(location.path.trim())); + let mut files: Vec = std::iter::once(crate::library_dir()) + .chain(added.filter(|path| path.is_absolute())) + .flat_map(|folder| { + std::fs::read_dir(folder).map(|dir| dir.flatten().map(|entry| entry.path()).filter(saved_asset).collect::>()).unwrap_or_default() + }) + .collect(); files.sort(); + files.dedup(); app.library = Some(files); } @@ -776,4 +783,25 @@ mod tests { assert!(galley.size().x <= width); assert_eq!(galley.rows[0].glyphs.last().map(|glyph| glyph.chr), Some('…')); } + + /// Saved smart materials in a location added in Settings > Libraries are listed with the library folder's + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_shelf_lists_saved_materials_of_added_library_locations() { + let dir = std::env::temp_dir().join(format!("tc-shelf-added-library-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let saved = dir.join("Rusty Plate.tcmat"); + std::fs::write(&saved, b"").unwrap(); + std::fs::write(dir.join("notes.txt"), b"").unwrap(); + let session = texturecraft_engine::Session::closed().unwrap(); + let mut app = TextureCraftApp::new(&eframe::CreationContext::_new_kittest(egui::Context::default()), session); + app.ui.prefs.libraries.push(crate::state::LibraryLocation { name: "plates".into(), path: dir.display().to_string() }); + + scan_library(&mut app); + let listed = app.library.clone().unwrap_or_default(); + let _ = std::fs::remove_dir_all(&dir); + + assert!(listed.contains(&saved), "{listed:?}"); + assert!(!listed.iter().any(|path| path.extension().is_some_and(|extension| extension == "txt")), "only saved assets are listed"); + } } diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs index 8fef12d9..96f5c25f 100644 --- a/crates/ui-egui/src/shelf_panes.rs +++ b/crates/ui-egui/src/shelf_panes.rs @@ -10,14 +10,13 @@ use crate::i18n::{n_, tr}; use crate::saved_search::SavedSearch; use crate::shelf::TABS; use crate::theme::Tokens; +use crate::unavailable::NOT_AVAILABLE; use crate::widgets::icon_button; const COLUMN_FRACTION: f32 = 0.45; const COLUMN_MIN_WIDTH_POINTS: f32 = 110.0; const SPLITTER_HEIGHT_POINTS: f32 = 6.0; const PANE_MIN_HEIGHT_POINTS: f32 = 40.0; -/// The hint on rows whose function TextureCraft lacks -pub(crate) const NOT_AVAILABLE: &str = n_("Not available yet"); /// The reference's built-in saved searches after "All", shown greyed until they work const BUILT_IN_SEARCHES: [&str; 3] = [n_("Favorites"), n_("3D Assets"), n_("Flattened layers")]; /// The reference's font libraries after the asset libraries, shown greyed until they work diff --git a/crates/ui-egui/src/shelf_tabs.rs b/crates/ui-egui/src/shelf_tabs.rs index 6e097f77..f7187dc2 100644 --- a/crates/ui-egui/src/shelf_tabs.rs +++ b/crates/ui-egui/src/shelf_tabs.rs @@ -72,7 +72,7 @@ fn collapsed(ui: &mut Ui, picked: &mut usize, counts: &[usize], size: f32) { } } - ui.add_enabled(false, egui::Button::selectable(false, tr(FONTS))).on_disabled_hover_text(tr(crate::shelf_panes::NOT_AVAILABLE)); + ui.add_enabled(false, egui::Button::selectable(false, tr(FONTS))).on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE)); ui.separator(); if ui.button(tr(SHOW_ALL)).clicked() { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 509acdc3..7f964238 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -79,9 +79,15 @@ pub struct Windows { /// Browser File › Export Mesh: the download format choice. #[serde(default)] pub export_mesh: bool, + /// File › Export Mesh: the Mesh Export Options prompt before the file choice + #[serde(skip)] + pub mesh_export_options: bool, /// Edit > Project Configuration: what is chosen so far, applied by OK. #[serde(skip)] pub project_config: Option, + /// Edit > Settings: the page and the settings edited so far, applied by OK. + #[serde(skip)] + pub settings_draft: Option, /// What waits on the unsaved-changes dialog: save, don't save or cancel. #[serde(skip)] pub unsaved: Option, @@ -111,7 +117,7 @@ pub struct Prefs { pub ui_scale: f32, /// Minutes between autosaves of a modified project (0: off; desktop). pub autosave_minutes: u32, - /// UI language code (`i18n::LANGUAGES`). + /// UI language code (`i18n::LANGUAGES`), or `i18n::SYSTEM_LANGUAGE` to follow the system. pub language: String, /// Viewport texture resolution: 0 full, 1 half, 2 quarter of each texture set's size (lighter /// on GPU memory and uploads for 4K and 8K sets; painting and export keep full resolution). @@ -132,8 +138,36 @@ pub struct Prefs { pub project_open_limit_gib: u32, /// Percent of the free RAM a project save may hold at once (desktop; 1 to 100). pub save_ram_percent: u8, + /// Worker threads for painting, baking and export (desktop; 0: one per logical CPU). Read at + /// startup, before the first parallel job. + pub work_threads: u32, + /// 3D view orbit speed; [`DEFAULT_ROTATION_SPEED`] is the built-in speed. + pub rotation_speed: f32, + /// 3D view drag zoom speed (1 is the built-in speed) and whether it runs the other way. + pub zoom_speed: f32, + pub zoom_inverse: bool, + /// 3D view mouse wheel zoom speed (1 is the built-in speed) and whether it runs the other way. + pub wheel_speed: f32, + pub wheel_inverse: bool, + /// Bakes cast their rays on the GPU when one is available (else on the CPU). + pub gpu_raytracing: bool, + /// Library locations the user added (Settings > Libraries), after the built-in ones. + pub libraries: Vec, } +/// A folder the user added as a library: its name and path. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct LibraryLocation { + pub name: String, + pub path: String, +} + +/// The orbit speed the built-in navigation runs at. +pub const DEFAULT_ROTATION_SPEED: f32 = 2.0; +/// The range of the camera speed sliders. +pub const CAMERA_SPEED_RANGE: std::ops::RangeInclusive = 0.1..=10.0; + impl Default for Prefs { fn default() -> Self { Prefs { @@ -148,16 +182,57 @@ impl Default for Prefs { reserved_cores: 1, project_open_limit_gib: texturecraft_engine::formats::DEFAULT_PROJECT_OPEN_LIMIT_GIB, save_ram_percent: 50, + work_threads: 0, + rotation_speed: DEFAULT_ROTATION_SPEED, + zoom_speed: 1.0, + zoom_inverse: false, + wheel_speed: 1.0, + wheel_inverse: false, + gpu_raytracing: true, + libraries: Vec::new(), } } } +/// `value` as a camera speed: inside the sliders' range, the default for a value that is not a number. +fn camera_speed(value: f32, default: f32) -> f32 { + if value.is_finite() { value.clamp(*CAMERA_SPEED_RANGE.start(), *CAMERA_SPEED_RANGE.end()) } else { default } +} + impl Prefs { /// Apply resource preferences before commands or file workers can start. pub fn apply_resource_limits(&self) { texturecraft_engine::formats::set_project_open_limit_gib(self.project_open_limit_gib); #[cfg(not(target_arch = "wasm32"))] texturecraft_engine::formats::set_save_resources(self.reserved_cores as usize, self.save_ram_percent); + texturecraft_engine::bake::set_gpu_raytracing(self.gpu_raytracing); + } + + /// Size the shared worker pool to `work_threads` (0 keeps one thread per logical CPU). Only + /// the first call of a process can do this, before any parallel work: true when it did. + #[cfg(not(target_arch = "wasm32"))] + pub fn apply_work_threads(&self) -> bool { + if self.work_threads == 0 { + return false; + } + rayon::ThreadPoolBuilder::new().num_threads(self.work_threads as usize).build_global().is_ok() + } + + /// The 3D view's orbit per dragged point, relative to the built-in speed. + pub fn orbit_scale(&self) -> f32 { + camera_speed(self.rotation_speed, DEFAULT_ROTATION_SPEED) / DEFAULT_ROTATION_SPEED + } + + /// The 3D view's drag zoom relative to the built-in speed; negative when inverted. + pub fn drag_zoom_scale(&self) -> f32 { + let speed = camera_speed(self.zoom_speed, 1.0); + if self.zoom_inverse { -speed } else { speed } + } + + /// The 3D view's wheel zoom relative to the built-in speed; negative when inverted. + pub fn wheel_zoom_scale(&self) -> f32 { + let speed = camera_speed(self.wheel_speed, 1.0); + if self.wheel_inverse { -speed } else { speed } } } @@ -301,6 +376,9 @@ pub struct UiState { pub blend_clipboard: Option>, pub mode: Mode, pub layout: ViewLayout, + /// The split layout shows the 2D view on the left and the 3D view on the right + #[serde(default)] + pub swap_views: bool, /// The 3D view's share of the viewport width in the split layout #[serde(default = "default_split_ratio")] pub split_ratio: f32, @@ -387,9 +465,18 @@ pub struct UiState { /// Panel arrangements saved under a name (Window > Layouts), in the order they were saved #[serde(default)] pub named_layouts: Vec, + /// Bake settings saved under a name (Mesh Map Bakers > Presets), in the order they were saved + #[serde(default)] + pub bake_presets: Vec, + /// The name typed in the bake presets menu + #[serde(skip)] + pub bake_preset_name: String, /// The save, replace or manage dialog of the named layouts #[serde(skip)] pub layout_dialog: Option, + /// The Log panel's shown channel tab + #[serde(default)] + pub log_channel: crate::log_panel::LogChannel, } impl UiState { @@ -435,6 +522,7 @@ impl UiState { self.keymap = keep.keymap; self.tool_settings = keep.tool_settings; self.named_layouts = keep.named_layouts; + self.bake_presets = keep.bake_presets; self.layout_dialog = None; self.rename = None; @@ -451,6 +539,7 @@ impl Default for UiState { UiState { mode: Mode::Painting, layout: ViewLayout::Split, + swap_views: false, split_ratio: default_split_ratio(), dock: Dock::default(), rail_panel: None, @@ -488,7 +577,10 @@ impl Default for UiState { tool_settings: Default::default(), bake_visualization: crate::bake_mode::BakeVisualizationToggles::default(), named_layouts: Vec::new(), + bake_presets: Vec::new(), + bake_preset_name: String::new(), layout_dialog: None, + log_channel: crate::log_panel::LogChannel::default(), } } } @@ -497,6 +589,40 @@ impl Default for UiState { mod tests { use super::*; + #[test] + fn camera_speeds_scale_the_built_in_navigation_and_inverse_flips_it() { + let mut prefs = Prefs::default(); + assert_eq!((prefs.orbit_scale(), prefs.drag_zoom_scale(), prefs.wheel_zoom_scale()), (1.0, 1.0, 1.0), "the defaults keep the built-in speeds"); + + prefs.rotation_speed = 4.0; + prefs.zoom_speed = 0.5; + prefs.zoom_inverse = true; + prefs.wheel_inverse = true; + assert_eq!((prefs.orbit_scale(), prefs.drag_zoom_scale(), prefs.wheel_zoom_scale()), (2.0, -0.5, -1.0)); + + // Values from an edited settings file stay usable + prefs.rotation_speed = f32::NAN; + prefs.wheel_speed = 1e9; + assert_eq!(prefs.orbit_scale(), 1.0); + assert_eq!(prefs.wheel_zoom_scale(), -*CAMERA_SPEED_RANGE.end()); + } + + #[test] + fn settings_saved_before_the_new_options_load_their_defaults() { + let prefs: Prefs = serde_json::from_str(r#"{"autosave_minutes": 5}"#).unwrap(); + assert_eq!(prefs.autosave_minutes, 5); + assert_eq!((prefs.rotation_speed, prefs.zoom_speed, prefs.wheel_speed), (2.0, 1.0, 1.0)); + assert!(prefs.gpu_raytracing && !prefs.zoom_inverse && !prefs.wheel_inverse); + assert_eq!(prefs.work_threads, 0); + assert!(prefs.libraries.is_empty()); + } + + #[test] + fn the_first_run_follows_the_system_language() { + let mut session = texturecraft_engine::Session::closed().unwrap(); + assert_eq!(crate::start_ui(None, &mut session).prefs.language, crate::i18n::SYSTEM_LANGUAGE); + } + #[test] fn adopting_a_layout_keeps_recent_files_export_settings_and_shortcuts() { let mut ui = UiState { recent: vec!["a.tcraft".into()], ..UiState::default() }; diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 76a5c742..ab58384a 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -76,8 +76,8 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { /// Width of `view_buttons`, so the bar knows when to move them into the scrolling strip fn view_buttons_width(button_size: f32, spacing: f32) -> f32 { - // Two icons, two dropdowns, one separator and the four gaps between them - 2.0 * button_size + 2.0 * icon_dropdown_button_width(button_size) + BAR_SEPARATOR_WIDTH + 4.0 * spacing + // Two icons, three dropdowns, one separator and the five gaps between them + 2.0 * button_size + 3.0 * icon_dropdown_button_width(button_size) + BAR_SEPARATOR_WIDTH + 5.0 * spacing } /// View buttons in a right-to-left layout: the layout, then the camera type, then the screenshot and UV checker @@ -99,11 +99,14 @@ fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } }); ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); - ui.add_enabled_ui(project_open, |ui| projection_dropdown(app, ui)); + ui.add_enabled_ui(project_open, |ui| { + rotation_dropdown(app, ui); + projection_dropdown(app, ui); + }); layout_dropdown(app, ui); } -/// The 3D/2D, 3D-only and 2D-only layouts, showing the current one's icon +/// The 3D/2D, 3D-only and 2D-only layouts and the swap, showing the current one's icon fn layout_dropdown(app: &mut TextureCraftApp, ui: &mut egui::Ui) { const LAYOUTS: [(ViewLayout, &str, &str, &str); 3] = [ (ViewLayout::Split, ic::SQUARE_SPLIT_HORIZONTAL, "3D/2D views", "ui.layout.split"), @@ -120,6 +123,9 @@ fn layout_dropdown(app: &mut TextureCraftApp, ui: &mut egui::Ui) { chosen = Some(command); } } + if dropdown_row(ui, ic::ARROWS_LEFT_RIGHT, tr("Swap 3D/2D"), shortcut_of(&app.ui.keymap, "ui.layout.swap"), false) { + chosen = Some("ui.layout.swap"); + } }); if let Some(command) = chosen { @@ -146,6 +152,28 @@ fn projection_dropdown(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } } +/// Constrained (horizon stays level) or free (trackball) camera rotation +fn rotation_dropdown(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let modes = [ + (false, ic::ARROWS_HORIZONTAL, "Constrained rotation", "camera.rotation.constrained"), + (true, ic::ARROWS_CLOCKWISE, "Free rotation", "camera.rotation.free"), + ]; + let free = app.session.camera.free; + let (_, icon, label, _) = modes.iter().find(|(choice, ..)| *choice == free).unwrap_or(&modes[0]); + let mut chosen = None; + icon_dropdown(ui, "view_rotation", icon, tr(label), |ui| { + for (choice, icon, label, command) in modes { + if dropdown_row(ui, icon, tr(label), shortcut_of(&app.ui.keymap, command), free == choice) { + chosen = Some(command); + } + } + }); + + if let Some(command) = chosen { + crate::menus::invoke(app, &ui.ctx().clone(), command); + } +} + /// An icon button with a caret that opens `menu` below it, highlighted while open fn icon_dropdown(ui: &mut egui::Ui, id_salt: &str, icon: &str, tooltip: &str, menu: impl FnOnce(&mut egui::Ui)) { let button_size = ui.spacing().interact_size.y; @@ -476,16 +504,13 @@ const RAIL_ICON_GAP: f32 = 4.0; /// Padding inside the rail's card around its icons, as the tool shelf's const RAIL_CARD_PADDING: egui::Margin = egui::Margin::symmetric(3, 6); -/// The icon rail: Export, then the rail panels that are not in the dock, each opening its popup +/// The icon rail: the rail panels that are not in the dock (Export first), each opening its popup pub fn rail(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let tokens = Tokens::get(ui.ctx()); egui::Panel::right("rail").resizable(false).exact_size(RAIL_WIDTH).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { card(ui, &tokens, egui::Margin { left: 0, right: GUTTER, top: GUTTER, bottom: GUTTER }, RAIL_CARD_PADDING, |ui| { ui.spacing_mut().item_spacing.y = RAIL_ICON_GAP; crate::rail_popup::begin_rail(ui.ctx(), ui.max_rect()); - if icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, RAIL_ICON_SIZE).clicked() { - app.ui.windows.export = !app.ui.windows.export; - } // A panel in the dock, docked or floating, leaves the rail until it is closed there for (panel, icon, id) in crate::rail_popup::RAIL_PANELS { diff --git a/crates/ui-egui/src/unavailable.rs b/crates/ui-egui/src/unavailable.rs new file mode 100644 index 00000000..43d4f77d --- /dev/null +++ b/crates/ui-egui/src/unavailable.rs @@ -0,0 +1,32 @@ +//! Reference controls whose function TextureCraft lacks: shown greyed, with a hint on hover + +use egui::{Response, Ui}; + +use crate::i18n::{n_, tr}; + +/// The hover hint of a control that is shown for parity but does nothing yet +pub const NOT_AVAILABLE: &str = n_("Not available yet"); + +/// Add `add`'s controls greyed out, with the hint on hover over any of them +pub(crate) fn greyed(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { + let shown = ui.add_enabled_ui(false, add); + shown.response.on_disabled_hover_text(tr(NOT_AVAILABLE)); + shown.inner +} + +/// A greyed checkbox showing `checked` +pub(crate) fn checkbox(ui: &mut Ui, checked: bool, label: &str) -> Response { + let mut shown = checked; + ui.add_enabled(false, egui::Checkbox::new(&mut shown, label)).on_disabled_hover_text(tr(NOT_AVAILABLE)) +} + +/// A greyed labelled dropdown showing `value` +pub(crate) fn combo(ui: &mut Ui, label: &str, value: &str) { + greyed(ui, |ui| crate::widgets::combo(ui, label, value, |_| {})); +} + +/// A greyed slider at `value` +pub(crate) fn slider(ui: &mut Ui, label: &str, value: f32, range: std::ops::RangeInclusive, decimals: usize) { + let mut shown = value; + greyed(ui, |ui| crate::widgets::slider(ui, label, &mut shown, range, decimals)); +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4c453f04..3f7b7774 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -120,13 +120,14 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let divider_x = split_divider_x(app, ui, full); let left = Rect::from_min_max(full.min, pos2(divider_x - SPLIT_LINE_HALF_WIDTH, full.max.y)); let right = Rect::from_min_max(pos2(divider_x + SPLIT_LINE_HALF_WIDTH, full.min.y), full.max); + let (rect_3d, rect_2d) = if app.ui.swap_views { (right, left) } else { (left, right) }; // Each view draws only on its side, so overlays such as the texture set name stay out of a narrow neighbour let clip = ui.clip_rect(); - ui.set_clip_rect(left.intersect(clip)); - view_3d(app, ui, left, &mut sync); - ui.set_clip_rect(right.intersect(clip)); - view_2d(app, ui, right, &mut sync); + ui.set_clip_rect(rect_3d.intersect(clip)); + view_3d(app, ui, rect_3d, &mut sync); + ui.set_clip_rect(rect_2d.intersect(clip)); + view_2d(app, ui, rect_2d, &mut sync); ui.set_clip_rect(clip); split_divider_grab(ui, full, divider_x); let line = Stroke::new(SPLIT_LINE_HALF_WIDTH * 2.0, tokens.chrome); @@ -165,10 +166,9 @@ fn empty_views(app: &mut TextureCraftApp, ui: &mut Ui) { ViewLayout::Only2D => vec![(full, "v2d")], ViewLayout::Split => { let middle = (full.left() + full.width() * 0.5).round(); - vec![ - (Rect::from_min_max(full.min, pos2(middle - SPLIT_LINE_HALF_WIDTH, full.max.y)), "v3d"), - (Rect::from_min_max(pos2(middle + SPLIT_LINE_HALF_WIDTH, full.min.y), full.max), "v2d"), - ] + let left = Rect::from_min_max(full.min, pos2(middle - SPLIT_LINE_HALF_WIDTH, full.max.y)); + let right = Rect::from_min_max(pos2(middle + SPLIT_LINE_HALF_WIDTH, full.min.y), full.max); + if app.ui.swap_views { vec![(left, "v2d"), (right, "v3d")] } else { vec![(left, "v3d"), (right, "v2d")] } } }; @@ -203,8 +203,12 @@ fn clamp_split_ratio(ratio: f32, width: f32) -> f32 { fn split_divider_x(app: &mut TextureCraftApp, ui: &Ui, full: Rect) -> f32 { // The 2D view's left edge, beside the line, sits on a whole pixel let pixels_per_point = ui.ctx().pixels_per_point(); + // The ratio is the 3D view's share, so a swap moves the divider to the other side of the width + let swapped = app.ui.swap_views; let divider_x = |ratio: f32| { - let unsnapped = full.left() + full.width() * clamp_split_ratio(ratio, full.width()); + let left_share = clamp_split_ratio(ratio, full.width()); + let left_share = if swapped { 1.0 - left_share } else { left_share }; + let unsnapped = full.left() + full.width() * left_share; (unsnapped + SPLIT_LINE_HALF_WIDTH).round_to_pixels(pixels_per_point) - SPLIT_LINE_HALF_WIDTH }; let old_x = divider_x(app.ui.split_ratio); @@ -218,7 +222,8 @@ fn split_divider_x(app: &mut TextureCraftApp, ui: &Ui, full: Rect) -> f32 { // `max` and `min` rather than `clamp`, so a NaN bound from a corrupt saved zoom can't panic let (min_x, max_x) = divider_range_keeping_uv_size(&app.ui, full, old_x, pixels_per_point); let target_x = pointer.x.max(min_x).min(max_x); - app.ui.split_ratio = clamp_split_ratio((target_x - full.left()) / full.width(), full.width()); + let left_share = (target_x - full.left()) / full.width(); + app.ui.split_ratio = clamp_split_ratio(if swapped { 1.0 - left_share } else { left_share }, full.width()); let new_x = divider_x(app.ui.split_ratio); keep_uv_view_on_screen(&mut app.ui, full, old_x, new_x); } @@ -269,8 +274,9 @@ const STENCIL_OUTLINE_DASH: f32 = 5.0; const STENCIL_OUTLINE_GAP: f32 = 4.0; /// The 2D view's width when the split divider is at `divider_x` -fn uv_view_width(full: Rect, divider_x: f32) -> f32 { - (full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0) +fn uv_view_width(full: Rect, divider_x: f32, swapped: bool) -> f32 { + let width = if swapped { divider_x - full.left() } else { full.right() - divider_x }; + (width - SPLIT_LINE_HALF_WIDTH).max(1.0) } /// The share of the 2D view's height that a zoom of 1 fills at `width`: the view fits the texture to its narrower side @@ -281,19 +287,24 @@ fn uv_view_fit(full: Rect, width: f32) -> f32 { /// The divider positions where the 2D zoom that keeps the texture's screen size stays inside the 2D zoom range fn divider_range_keeping_uv_size(ui_state: &crate::state::UiState, full: Rect, old_x: f32, pixels_per_point: f32) -> (f32, f32) { // The zoom times the fit is the texture's screen size, which a divider drag keeps - let screen_zoom = ui_state.uv_zoom * uv_view_fit(full, uv_view_width(full, old_x)); + let screen_zoom = ui_state.uv_zoom * uv_view_fit(full, uv_view_width(full, old_x, ui_state.swap_views)); // Whole pixels, rounded inward, so snapping the divider to a pixel can't step past the range let narrowest_view = (full.height() * screen_zoom / UV_VIEW_MAX_ZOOM * pixels_per_point).ceil() / pixels_per_point; let widest_view = (full.height() * screen_zoom / UV_VIEW_MIN_ZOOM * pixels_per_point).floor() / pixels_per_point; + if ui_state.swap_views { + // The 2D view is on the left: the divider moves right to widen it + let edge = full.left() + SPLIT_LINE_HALF_WIDTH; + return (edge + narrowest_view, edge + widest_view); + } let edge = full.right() - SPLIT_LINE_HALF_WIDTH; (edge - widest_view, edge - narrowest_view) } -/// Keeps the 2D view's texture at the same size and offset from the view's centre when the divider moves its left edge from `old_x` to `new_x` +/// Keeps the 2D view's texture at the same size and offset from the view's centre when the divider moves its edge from `old_x` to `new_x` fn keep_uv_view_on_screen(ui_state: &mut crate::state::UiState, full: Rect, old_x: f32, new_x: f32) { - let (old_width, new_width) = (uv_view_width(full, old_x), uv_view_width(full, new_x)); + let (old_width, new_width) = (uv_view_width(full, old_x, ui_state.swap_views), uv_view_width(full, new_x, ui_state.swap_views)); ui_state.uv_zoom *= uv_view_fit(full, old_width) / uv_view_fit(full, new_width); // The horizontal pan is in half view widths @@ -306,11 +317,12 @@ fn split_divider_grab(ui: &Ui, full: Rect, divider_x: f32) { ui.interact(zone, split_divider_id(ui), Sense::drag()).on_hover_and_drag_cursor(egui::CursorIcon::ResizeHorizontal); } -/// The shader's view modes (`Shade::view_mode`): the material, one channel, the aux texture (mesh map, mask or quick mask), the UV checker +/// The shader's view modes (`Shade::view_mode`): the material, one channel, the aux texture (mesh map, mask or quick mask), the UV checker, the combined normal const VIEW_MODE_MATERIAL: u32 = 0; const VIEW_MODE_CHANNEL: u32 = 1; const VIEW_MODE_AUX_TEXTURE: u32 = 2; const VIEW_MODE_UV_CHECKER: u32 = 3; +const VIEW_MODE_NORMAL_HEIGHT_MESH: u32 = 4; fn shade(app: &TextureCraftApp) -> Shade { let (view_mode, channel) = match app.session.view { @@ -319,6 +331,7 @@ fn shade(app: &TextureCraftApp) -> Shade { ViewMode::Channel(selected_channel) => (VIEW_MODE_CHANNEL, selected_channel.index() as u32), ViewMode::MeshMap(_) | ViewMode::Mask(_) => (VIEW_MODE_AUX_TEXTURE, 0), ViewMode::UvChecker => (VIEW_MODE_UV_CHECKER, 0), + ViewMode::NormalHeightMesh => (VIEW_MODE_NORMAL_HEIGHT_MESH, 0), }; let set_index = app.session.ts(); let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); @@ -511,6 +524,13 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { }); } + view_mode_picker(app, &mut child, &format!("{id}_mode"), VIEW_PICKER_WIDTH); +} + +/// The view-mode picker of a view's header and of Display Settings: the material, the channels, the mesh maps and the UV checker +pub(crate) fn view_mode_picker(app: &mut TextureCraftApp, child: &mut Ui, id_salt: &str, width: f32) { + let project_open = app.session.project_open; + // Bake mode lights the project mesh with the neutral material unless the painted one is asked for let baking = app.ui.mode == crate::state::Mode::Baking; let neutral = baking && app.session.view == ViewMode::Material && app.ui.bake_visualization.neutral_shown; @@ -523,7 +543,7 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { // The picker stays greyed without project maps child.add_enabled_ui(project_open, |child| { - egui::ComboBox::from_id_salt(format!("{id}_mode")).width(VIEW_PICKER_WIDTH).selected_text(tr(&label)).show_ui(child, |ui| { + egui::ComboBox::from_id_salt(id_salt).width(width).selected_text(tr(&label)).show_ui(child, |ui| { if baking && ui.selectable_label(neutral, tr("Neutral Material")).clicked() { app.ui.bake_visualization.neutral_shown = true; app.run("viewport.view", json!({"mode": "material"})); @@ -550,6 +570,9 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { app.run("viewport.view", json!({"mode": channel.id()})); } } + if ui.selectable_label(app.session.view == ViewMode::NormalHeightMesh, tr(texturecraft_engine::NORMAL_HEIGHT_MESH_LABEL)).clicked() { + app.run("viewport.view", json!({"mode": "normalHeightMesh"})); + } ui.separator(); mesh_map_entries(app, ui); ui.separator(); @@ -685,10 +708,18 @@ fn snapped_orbit(app: &mut TextureCraftApp, delta: egui::Vec2) { 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); + let radians_per_point = ORBIT_RADIANS_PER_POINT * app.ui.prefs.orbit_scale(); + *yaw -= delta.x * radians_per_point; + *pitch = (*pitch + delta.y * radians_per_point).clamp(-step, step); + + // A free camera is put level on the step + camera.set_angles((*yaw / step).round() * step, ((*pitch / step).round() * step).clamp(-limit, limit)); +} + +/// Orbit the 3D view by a drag of `delta` points at the Settings rotation speed. +pub(crate) fn orbit(app: &mut TextureCraftApp, delta: egui::Vec2) { + let radians_per_point = ORBIT_RADIANS_PER_POINT * app.ui.prefs.orbit_scale(); + app.session.camera.orbit(delta.x * radians_per_point, delta.y * radians_per_point); } fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { @@ -719,17 +750,17 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if shift { snapped_orbit(app, delta); } else { - app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT); + orbit(app, delta); } } else if response.dragged_by(PointerButton::Secondary) { app.camera_glide = None; if alt { - app.session.camera.zoom(-delta.y * DRAG_ZOOM_PER_POINT); + app.session.camera.zoom(-delta.y * DRAG_ZOOM_PER_POINT * app.ui.prefs.drag_zoom_scale()); } else if shift { let display = &mut app.session.doc.project.display; display.env_rotation = (display.env_rotation + delta.x * LIGHT_DEGREES_PER_POINT).rem_euclid(360.0); } else { - app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT); + orbit(app, delta); } } @@ -753,7 +784,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin scale_brush_by_wheel(app, scroll); } else { app.camera_glide = None; - app.session.camera.zoom(scroll * WHEEL_ZOOM_PER_POINT); + app.session.camera.zoom(scroll * WHEEL_ZOOM_PER_POINT * app.ui.prefs.wheel_zoom_scale()); } } } @@ -770,7 +801,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if gesture.num_touches >= 3 { app.session.camera.pan(moved.x / size.y, moved.y / size.y); } else { - app.session.camera.orbit(moved.x * ORBIT_RADIANS_PER_POINT, moved.y * ORBIT_RADIANS_PER_POINT); + orbit(app, moved); } if gesture.zoom_delta.is_finite() && gesture.zoom_delta > 0.0 { app.session.camera.zoom(gesture.zoom_delta.ln()); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 3c507dc3..1d49b22a 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -1,31 +1,28 @@ -//! Floating windows and dockable display, shader, history and log panels +//! Floating windows and the dockable History panel -use egui::{Color32, RichText, Ui, vec2}; +use egui::{RichText, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::core::ToneMapping; -use texturecraft_engine::core::project::{DisplaySettings, ENV_RESOURCE_PREFIX}; use texturecraft_engine::geom::primitives::BUILTINS; -use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; #[cfg(not(target_arch = "wasm32"))] use crate::file_dialogs::{Bound, FileDialog}; -use crate::i18n::LANGUAGES; use crate::i18n::{tr, tr_history, trf}; use crate::new_project_advanced::COMBO_WIDTH; use crate::state::Mode; -use crate::theme::{Accent, Brightness, Tokens, caption}; -use crate::widgets::{color_swatch, combo, icon_button, primary_button, section, section_with_reset, slider}; +use crate::theme::{Tokens, caption}; +use crate::widgets::primary_button; pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { new_project(app, ctx); about(app, ctx); - settings(app, ctx); + crate::settings_window::show(app, ctx); #[cfg(not(target_arch = "wasm32"))] crate::project_config::show(app, ctx); crate::keymap::window(app, ctx); crate::windows::export(app, ctx); + crate::mesh_export_options::show(app, ctx); #[cfg(target_arch = "wasm32")] export_mesh(app, ctx); crate::pbr_import::window(app, ctx); @@ -203,200 +200,6 @@ pub(crate) fn dialog<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Win .anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0)) } -/// The Display Settings panel body (a dock tab). -pub(crate) fn display(app: &mut TextureCraftApp, ui: &mut Ui) { - let ctx = ui.ctx().clone(); - let mut d = app.session.doc.project.display.clone(); - let before = d.clone(); - ui.label(caption(tr("Environment settings"))); - let mut hdrs: Vec<&String> = app.session.images.iter().filter(|(_, i)| !i.srgb).map(|(k, _)| k).collect(); - hdrs.sort(); - let mut import_hdr = false; - let shown = d.environment_resource().unwrap_or(&d.environment).to_string(); - combo(ui, tr("Environment map"), shown, |ui| { - for e in ENVIRONMENTS { - ui.selectable_value(&mut d.environment, e.to_string(), e); - } - ui.separator(); - for name in hdrs { - ui.selectable_value(&mut d.environment, format!("{ENV_RESOURCE_PREFIX}{name}"), name.as_str()); - } - import_hdr = ui - .selectable_label(false, format!("{} {}", ic::FILE_ARROW_UP, tr("Import HDR..."))) - .on_hover_text(tr("Use an equirectangular .hdr or .exr image as the environment")) - .clicked(); - }); - slider(ui, tr("Environment opacity"), &mut d.env_opacity, 0.0..=1.0, 2); - slider(ui, tr("Environment exposure (EV)"), &mut d.env_exposure, -5.0..=5.0, 2); - slider(ui, tr("Environment blur"), &mut d.env_blur, 0.0..=1.0, 2); - slider(ui, tr("Environment rotation"), &mut d.env_rotation, 0.0..=360.0, 0); - ui.checkbox(&mut d.shadows, tr("Key light (shadow-casting light, direct only)")); - ui.add_space(6.0); - ui.label(caption(tr("Camera settings"))); - slider(ui, tr("Field of view (deg)"), &mut d.fov, 5.0..=120.0, 0); - let mut ortho = app.session.camera.ortho; - if ui.checkbox(&mut ortho, tr("Orthographic")).changed() { - app.run("camera.set", json!({"ortho": ortho})); - } - let tone_mapping_name = |tone_mapping: ToneMapping| match tone_mapping { - ToneMapping::Linear => tr("Linear"), - ToneMapping::AcesFilmic => tr("ACES filmic"), - }; - combo(ui, tr("Tone mapping"), tone_mapping_name(d.tone_mapping), |ui| { - for tone_mapping in [ToneMapping::Linear, ToneMapping::AcesFilmic] { - ui.selectable_value(&mut d.tone_mapping, tone_mapping, tone_mapping_name(tone_mapping)); - } - }); - cameras(app, ui); - ui.add_space(6.0); - ui.label(caption(tr("Depth of field"))); - ui.checkbox(&mut d.dof.enabled, tr("Depth of field (viewport and Rendering mode)")); - ui.add_enabled_ui(d.dof.enabled, |ui| { - let far = (app.session.camera.distance * 4.0).max(d.dof.focus_distance); - slider(ui, tr("Focus distance"), &mut d.dof.focus_distance, 0.0..=far, 2) - .on_hover_text(tr("Depth of the sharp plane along the view (0: the orbit center)")); - slider(ui, tr("Aperture"), &mut d.dof.aperture, 0.0..=1.0, 3).on_hover_text(tr("Lens size: how quickly things blur away from the focus distance")); - let picking = crate::viewport::focus_picking(ui.ctx()); - if ui.selectable_label(picking, format!("{} {}", ic::CROSSHAIR_SIMPLE, tr("Pick focus in the viewport"))).clicked() { - crate::viewport::set_focus_picking(ui.ctx(), !picking); - } - }); - ui.add_space(6.0); - - // The switch gates all four amounts (the engine has one switch for the group); each amount 0 leaves that effect out - let post_effect_fields = |d: &DisplaySettings| (d.post_effects, d.bloom, d.vignette, d.sharpen, d.grain); - let post_effect_defaults = post_effect_fields(&DisplaySettings::default()); - if section_with_reset(ui, "sec_post_effects", tr("Post effects"), false, post_effect_fields(&d) == post_effect_defaults, |ui| { - ui.checkbox(&mut d.post_effects, tr("Post effects (viewport and Rendering mode)")); - ui.add_enabled_ui(d.post_effects, |ui| { - slider(ui, tr("Glow"), &mut d.bloom, 0.0..=1.0, 2).on_hover_text(tr("Bright areas bleed light into their surroundings")); - slider(ui, tr("Vignette"), &mut d.vignette, 0.0..=1.0, 2).on_hover_text(tr("Darkens the corners of the view")); - slider(ui, tr("Sharpen"), &mut d.sharpen, 0.0..=1.0, 2).on_hover_text(tr("Brings out fine detail")); - slider(ui, tr("Film grain"), &mut d.grain, 0.0..=1.0, 2).on_hover_text(tr("Adds fine noise over the view")); - }); - }) { - (d.post_effects, d.bloom, d.vignette, d.sharpen, d.grain) = post_effect_defaults; - } - ui.add_space(6.0); - ui.label(caption(tr("Viewer settings"))); - ui.checkbox(&mut app.ui.wireframe_3d, tr("Show wireframe in the 3D view")); - ui.checkbox(&mut app.ui.uv_wireframe, tr("Show UV wireframe in the 2D view")); - ui.checkbox(&mut d.taa, tr("Temporal anti-aliasing (refines the 3D view while it is still)")); - if d != before { - if d.fov != before.fov { - app.session.camera.fov = d.fov; - } - app.session.doc.project.display = d; - } - if import_hdr { - crate::web_files::import_environment(app, &ctx); - } -} - -/// The camera list: rename (edit the name), view or delete saved and imported cameras, save the -/// current view. -fn cameras(app: &mut TextureCraftApp, ui: &mut Ui) { - let current = texturecraft_engine::camera_cmds::current(&app.session); - let names: Vec = app.session.doc.project.cameras.iter().map(|c| c.name.clone()).collect(); - for (i, name) in names.iter().enumerate() { - ui.horizontal(|ui| { - if icon_button(ui, ic::VIDEO_CAMERA, tr("View through this camera"), current == Some(i), 20.0).clicked() { - app.run("camera.select", json!({"index": i})); - } - // The name being typed lives in egui's memory until the field loses focus. - let id = ui.scope_id().with(("camera_name", i)); - let mut text = ui.data(|d| d.get_temp::(id)).unwrap_or_else(|| name.clone()); - let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(ui.available_width() - 26.0)); - if r.changed() { - ui.data_mut(|d| d.insert_temp(id, text.clone())); - } - if r.lost_focus() { - ui.data_mut(|d| d.remove::(id)); - if text.trim() != name && !text.trim().is_empty() { - app.run("camera.rename", json!({"index": i, "to": text.trim()})); - } - } - if icon_button(ui, ic::TRASH, tr("Delete this camera"), false, 20.0).clicked() { - app.run("camera.remove", json!({"index": i})); - } - }); - } - if ui.button(format!("{} {}", ic::PLUS, tr("Save view as camera"))).clicked() { - app.run("camera.add", json!({})); - } -} - -/// Wide enough for the longer shader model name -const SHADER_MODEL_COMBO_WIDTH: f32 = 260.0; - -/// Width of the scatter color swatch -const SCATTER_SWATCH_WIDTH: f32 = 44.0; - -/// Index of refraction slider range: air to well past diamond (2.42) -const INDEX_OF_REFRACTION_RANGE: std::ops::RangeInclusive = 1.0..=3.0; - -/// The Shader Settings panel body (a dock tab) -pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) { - let tokens = Tokens::get(ui.ctx()); - let mut display = app.session.doc.project.display.clone(); - let before = display.clone(); - - let model_name = |spec_gloss: bool| if spec_gloss { tr("TextureCraft PBR - Specular Glossiness") } else { tr("TextureCraft PBR - Metallic Roughness") }; - let channels = if display.spec_gloss { - tr("Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).") - } else { - tr("Base color, Metallic, Roughness and Specular level.") - }; - let model_text = tr( - "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", - ); - let optional = tr( - "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", - ); - - egui::ComboBox::from_id_salt("shader_model") - .width(SHADER_MODEL_COMBO_WIDTH) - .selected_text(model_name(display.spec_gloss)) - .show_ui(ui, |ui| { - for spec_gloss in [false, true] { - ui.selectable_value(&mut display.spec_gloss, spec_gloss, model_name(spec_gloss)); - } - }) - .response - .on_hover_text(format!("{model_text} {channels} {optional}")); - ui.add_space(6.0); - - ui.checkbox(&mut display.parallax, tr("Parallax occlusion (height channel)")) - .on_hover_text(tr("Offsets the textures by the height channel, at the height to normal strength")); - ui.checkbox(&mut display.displacement, tr("Displacement (height channel)")).on_hover_text(tr( - "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", - )); - slider(ui, tr("AO intensity"), &mut display.ao_intensity, 0.0..=1.0, 2); - ui.add_space(6.0); - - section(ui, "shader_subsurface", tr("Subsurface scattering"), true, |ui| { - ui.horizontal(|ui| { - ui.label(RichText::new(tr("Scatter color")).color(tokens.text)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - color_swatch(ui, "shader_scatter_color", &mut display.scatter_color, SCATTER_SWATCH_WIDTH) - }) - }) - .response - .on_hover_text(tr("Color of the light that travels under the surface (each channel goes as far as its value)")); - slider(ui, tr("Scatter radius"), &mut display.scatter_radius, 0.0..=1.0, 3) - .on_hover_text(tr("How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)")); - }); - section(ui, "shader_transmission", tr("Transmission"), true, |ui| { - slider(ui, tr("Index of refraction"), &mut display.ior, INDEX_OF_REFRACTION_RANGE, 2).on_hover_text(tr( - "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", - )); - }); - - if display != before { - app.session.doc.project.display = display; - } -} - /// The History panel body (a dock tab) pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); @@ -563,187 +366,6 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { } } -#[cfg(not(target_arch = "wasm32"))] -fn settings_resources(ctx: &egui::Context) -> (u32, u64) { - let id = egui::Id::unique("settings_resources"); - let now = ctx.input(|input| input.time); - ctx.request_repaint_after(std::time::Duration::from_secs(1)); - - // Query the operating system once a second while Settings is open, rather than every frame - if let Some((sampled_at, cores, available_ram_bytes)) = ctx.data(|data| data.get_temp::<(f64, u32, u64)>(id)) - && (0.0..1.0).contains(&(now - sampled_at)) - { - return (cores, available_ram_bytes); - } - - let (cores, available_ram_bytes) = texturecraft_engine::formats::available_save_resources(); - let cores = u32::try_from(cores).unwrap_or(u32::MAX); - ctx.data_mut(|data| data.insert_temp(id, (now, cores, available_ram_bytes))); - (cores, available_ram_bytes) -} - -fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { - let tk = Tokens::get(ctx); - let mut open = app.ui.windows.settings; - - // A language whose script no font draws is listed by its English name and disabled - let drawable = LANGUAGES.each_ref().map(|l| crate::fonts::Script::of_language(l.code).is_none_or(|s| app.fonts.covers(s))); - #[cfg(not(target_arch = "wasm32"))] - let mut pick_data_folder = false; - window("settings", tr("Settings"), &mut open).default_width(360.0).show(ctx, |ui| { - let p = &mut app.ui.prefs; - - // Every section is a two-column form: labels on the left, controls aligned beside them - let form = |id: &str| egui::Grid::new(id).num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(120.0); - ui.label(caption(tr("Interface"))); - form("settings_interface").show(ui, |ui| { - ui.label(tr("Language")); - let current = crate::i18n::current(); - egui::ComboBox::from_id_salt("language").width(180.0).height(320.0).selected_text(current.name).show_ui(ui, |ui| { - for (l, ok) in LANGUAGES.iter().zip(drawable).filter(|(l, _)| crate::i18n::available(l.code)) { - let item = egui::Button::selectable(l.code == current.code, if ok { l.name } else { l.english }); - if ui.add_enabled(ok, item).on_disabled_hover_text(tr("No font on this system can show this language")).clicked() { - p.language = l.code.to_owned(); - } - } - }); - ui.end_row(); - ui.label(tr("Interface scale")); - ui.add(egui::Slider::new(&mut p.ui_scale, 0.75..=2.0).fixed_decimals(2)); - ui.end_row(); - ui.label(tr("Brightness")); - egui::ComboBox::from_id_salt("brightness").width(140.0).selected_text(tr(p.brightness.label())).show_ui(ui, |ui| { - for b in Brightness::ALL { - ui.selectable_value(&mut p.brightness, b, tr(b.label())); - } - }); - ui.end_row(); - ui.label(tr("Accent color")); - ui.horizontal(|ui| { - for a in Accent::ALL { - let (rect, resp) = ui.allocate_exact_size(vec2(20.0, 20.0), egui::Sense::click()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, p.accent == a, tr(a.label()))); - let ring = if p.accent == a { - tk.text_strong - } else if resp.hovered() { - tk.text_dim - } else { - Color32::TRANSPARENT - }; - ui.painter().circle(rect.center(), 6.5, a.colors(tk.dark).0, egui::Stroke::NONE); - ui.painter().circle_stroke(rect.center(), 9.0, egui::Stroke::new(1.5, ring)); - if resp.on_hover_text(tr(a.label())).clicked() { - p.accent = a; - } - } - }); - ui.end_row(); - #[cfg(not(target_arch = "wasm32"))] - { - ui.label(tr("Title bar")); - ui.checkbox(&mut p.system_title_bar, tr("System title bar (applies on restart)")) - .on_hover_text(tr("Use the operating system's window frame and buttons instead of TextureCraft's own title bar")); - ui.end_row(); - } - }); - ui.add_space(8.0); - ui.label(caption(tr("Viewport"))); - form("settings_viewport").show(ui, |ui| { - ui.label(tr("Texture resolution")); - ui.horizontal(|ui| { - for (v, l) in [(0u8, tr("Full")), (1, tr("Half")), (2, tr("Quarter"))] { - ui.selectable_value(&mut p.viewport_texture, v, l); - } - }) - .response - .on_hover_text(tr( - "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", - )); - ui.end_row(); - }); - ui.add_space(8.0); - ui.label(caption(tr("Project"))); - #[cfg(not(target_arch = "wasm32"))] - let (available_cores, available_ram_bytes) = settings_resources(ctx); - form("settings_project").show(ui, |ui| { - #[cfg(not(target_arch = "wasm32"))] - { - ui.label(tr("Autosave every")); - ui.add(egui::DragValue::new(&mut p.autosave_minutes).range(0..=120).suffix(format!(" {}", tr("min")))); - ui.end_row(); - let label = ui.label(tr("Cores kept for the UI")); - ui.add(egui::DragValue::new(&mut p.reserved_cores).range(0..=available_cores)).labelled_by(label.id); - ui.end_row(); - } - - let label = ui.label(tr("Max project size on open")); - ui.add(egui::DragValue::new(&mut p.project_open_limit_gib).range(1..=u32::MAX).suffix(" GiB")) - .labelled_by(label.id) - .on_hover_text(tr("Maximum decompressed project data. Increase this limit to open larger projects.")); - ui.end_row(); - - #[cfg(not(target_arch = "wasm32"))] - { - let label = ui.label(tr("Max RAM while saving")); - ui.horizontal(|ui| { - ui.add(egui::DragValue::new(&mut p.save_ram_percent).range(1..=100).suffix(" %")).labelled_by(label.id); - let budget_bytes = texturecraft_engine::formats::save_ram_budget(available_ram_bytes, p.save_ram_percent); - ui.label(format!("≈ {:.2} GiB", budget_bytes as f64 / (1_u64 << 30) as f64)); - }); - ui.end_row(); - } - }); - #[cfg(not(target_arch = "wasm32"))] - { - ui.label(RichText::new(tr("Saving uses the other cores and at most this share of the free RAM. At least one core always works.")).small().color(tk.text_dim)); - ui.label( - RichText::new(trf("0 turns autosave off. Copies go to {folder}", &[("folder", &crate::user_dir("autosave").display())])) - .small() - .color(tk.text_dim), - ); - ui.add_space(8.0); - ui.label(caption(tr("Folders"))); - form("settings_folders").show(ui, |ui| { - ui.label(tr("Data folder")); - ui.horizontal(|ui| { - let default = crate::data_folder("").display().to_string(); - ui.add(egui::TextEdit::singleline(&mut p.data_folder).hint_text(default).desired_width(260.0)); - if ui.button("...").clicked() { - pick_data_folder = true; - } - }); - ui.end_row(); - for (label, dir) in [(tr("Smart materials"), crate::library_dir()), (tr("UI layouts"), crate::user_dir("layouts"))] { - ui.label(label); - ui.label(RichText::new(dir.display().to_string()).small().color(tk.text_dim)); - ui.end_row(); - } - }); - ui.label( - RichText::new(tr( - "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", - )) - .small() - .color(tk.text_dim), - ); - ui.add_space(8.0); - } - ui.label(caption(tr("Keyboard"))); - if ui.button(tr("Edit keyboard shortcuts...")).on_hover_text(tr("Rebind any menu item, tool or command")).clicked() { - app.ui.windows.shortcuts = true; - } - }); - app.ui.windows.settings = open; - #[cfg(not(target_arch = "wasm32"))] - if pick_data_folder { - app.ask_file(FileDialog::folder().directory(crate::data_folder(&app.ui.prefs.data_folder)), Bound::App, |app, paths| { - if let Some(d) = paths.first() { - app.ui.prefs.data_folder = d.display().to_string(); - } - }); - } -} - /// Browser File › Export Mesh: pick the download format #[cfg(target_arch = "wasm32")] fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) { @@ -794,13 +416,61 @@ fn about(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.windows.about = open; } -/// The Log panel body (a dock tab) -pub(crate) fn log(app: &mut TextureCraftApp, ui: &mut Ui) { - egui::ScrollArea::vertical().auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { - for line in &app.session.log { - ui.label(RichText::new(line).monospace()); +/// The text Help ▸ Export log... saves: a header with the export time, then every log line with +/// its level. The session log keeps plain lines with no time or level of their own, so every line +/// is written as `INFO`. +pub(crate) fn log_text(lines: &[String], exported_at: &str) -> String { + let mut out = format!("TextureCraft log, exported {exported_at}\n"); + for line in lines { + out.push_str(&format!("[{exported_at}] INFO {line}\n")); + } + out +} + +/// The current UTC time as `YYYY-MM-DD HH:MM:SS`. +#[cfg(not(target_arch = "wasm32"))] +fn now_utc() -> String { + let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64); + utc_text(secs) +} + +#[cfg(target_arch = "wasm32")] +fn now_utc() -> String { + utc_text((js_sys::Date::now() / 1000.0) as i64) +} + +/// Unix seconds as `YYYY-MM-DD HH:MM:SS` (UTC). +fn utc_text(secs: i64) -> String { + let (days, rest) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); + // Civil date from a day count (proleptic Gregorian) + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02} {:02}:{:02}:{:02}", rest / 3600, rest % 3600 / 60, rest % 60) +} + +/// Help ▸ Export log...: saves the whole log to a text file chosen in a save dialog. +pub(crate) fn export_log(app: &mut TextureCraftApp) { + let text = log_text(&app.session.log, &now_utc()); + #[cfg(not(target_arch = "wasm32"))] + app.ask_file(FileDialog::save().filter(tr("Text file"), &["txt"]).file_name("texturecraft-log.txt"), Bound::App, move |app, paths| { + let Some(path) = paths.first() else { return }; + match std::fs::write(path, &text) { + Ok(()) => app.toast(trf("Exported the log to {path}", &[("path", &path.display().to_string())]), false), + Err(e) => app.toast(trf("Could not export the log: {error}", &[("error", &e.to_string())]), true), } }); + #[cfg(target_arch = "wasm32")] + match crate::web_files::download("texturecraft-log.txt", text.as_bytes()) { + Ok(()) => app.toast(tr("Exported the log"), false), + Err(e) => app.toast(trf("Could not export the log: {error}", &[("error", &e)]), true), + } } // --------------------------------------------------------------------------------------------- @@ -1088,7 +758,7 @@ pub(crate) fn export_params(app: &TextureCraftApp) -> serde_json::Value { } fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[texturecraft_engine::formats::ExportPreset]) { - ui.label(caption(tr("General export parameters"))); + ui.label(caption(tr("General Export Parameters"))); egui::Grid::new("exp_grid").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { // The browser downloads the files instead #[cfg(not(target_arch = "wasm32"))] @@ -1147,9 +817,9 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur }); ui.end_row(); ui.label(tr("Size")); - let sz = if app.ui.export.size == 0 { tr("Based on each texture set's size").to_string() } else { format!("{0} x {0}", app.ui.export.size) }; + let sz = if app.ui.export.size == 0 { tr("Based on each Texture Set's size").to_string() } else { format!("{0} x {0}", app.ui.export.size) }; egui::ComboBox::from_id_salt("exp_size").width(360.0).selected_text(sz).show_ui(ui, |ui| { - ui.selectable_value(&mut app.ui.export.size, 0, tr("Based on each texture set's size")); + ui.selectable_value(&mut app.ui.export.size, 0, tr("Based on each Texture Set's size")); for r in [256u32, 512, 1024, 2048, 4096, 8192] { ui.selectable_value(&mut app.ui.export.size, r, format!("{r} x {r}")); } @@ -1178,6 +848,13 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur } }); ui.end_row(); + }); + + // The reference's two switches; TextureCraft's own normal map and colour space overrides follow them + crate::unavailable::checkbox(ui, false, tr("Export USD asset")); + crate::unavailable::checkbox(ui, false, tr("Export shaders parameters")); + ui.add_space(8.0); + egui::Grid::new("exp_grid_more").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { ui.label(tr("Normal map format")); let nf = match app.ui.export.normal_format.as_str() { "openGl" => "OpenGL", @@ -1202,6 +879,18 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur }); } +/// Height of the Export textures window's tab body, above its buttons +const EXPORT_BODY_HEIGHT: f32 = 440.0; + +/// How many files the export writes for the ticked texture sets +fn selected_texture_count(app: &mut TextureCraftApp) -> usize { + let mut params = export_params(app); + params["ts"] = json!("all"); + let Ok(plan) = texturecraft_engine::execute(&mut app.session, "export.plan", ¶ms) else { return 0 }; + let skipped = |file: &serde_json::Value| file.get("ts").and_then(serde_json::Value::as_u64).is_some_and(|ts| app.ui.export.skip.contains(&(ts as usize))); + plan.as_array().into_iter().flatten().filter(|file| !skipped(file)).count() +} + pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = Tokens::get(ctx); if !app.ui.windows.export { @@ -1212,7 +901,7 @@ pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let mut do_export = false; let presets = texturecraft_engine::formats::builtin_presets(); - dialog("export_textures", tr("Export textures"), &mut open).fixed_size(vec2(820.0, 430.0)).show(ctx, |ui| { + dialog("export_textures", tr("Export textures"), &mut open).fixed_size(vec2(900.0, 520.0)).show(ctx, |ui| { // Nothing to export without a project if !app.session.project_open { ui.label(tr("No project is open")); @@ -1221,14 +910,21 @@ pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.horizontal(|ui| { for (i, t) in [tr("Settings"), tr("Output templates"), tr("List of exports")].iter().enumerate() { - if ui.selectable_label(app.ui.export.tab == i as u8, caption(t)).clicked() { + if ui.selectable_label(app.ui.export.tab == i as u8, caption(&t.to_uppercase())).clicked() { app.ui.export.tab = i as u8; } } + + // Tick every texture set again + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Include all")).clicked() { + app.ui.export.skip.clear(); + } + }); }); ui.separator(); - ui.allocate_ui_with_layout(vec2(ui.available_width(), 360.0), egui::Layout::left_to_right(egui::Align::Min), |ui| { - ui.set_height(360.0); + ui.allocate_ui_with_layout(vec2(ui.available_width(), EXPORT_BODY_HEIGHT), egui::Layout::left_to_right(egui::Align::Min), |ui| { + ui.set_height(EXPORT_BODY_HEIGHT); if app.ui.export.tab == 1 { crate::export_templates::tab(app, ui, &presets); return; @@ -1236,7 +932,9 @@ pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.vertical(|ui| { ui.set_width(180.0); - ui.label(RichText::new(tr("Texture sets")).strong()); + + // The settings apply to every texture set; there are no per-set settings yet + let _ = ui.selectable_label(true, RichText::new(tr("Global settings")).strong()); for i in 0..app.session.set_count() { let name = app.session.doc.project.texture_sets.get(i).map(|t| t.name.clone()).unwrap_or_default(); let mut on = !app.ui.export.skip.contains(&i); @@ -1275,6 +973,7 @@ pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { }); ui.add_space(8.0); ui.separator(); + let selected = selected_texture_count(app); ui.horizontal(|ui| { if ui.button(tr("Reset all")).clicked() { app.ui.export = crate::state::ExportUi::default(); @@ -1283,9 +982,15 @@ pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { if ui.add(primary_button(ui, tr("Export"))).clicked() { do_export = true; } + + // The settings are kept with the interface, so saving them closes the window without exporting + if ui.button(tr("Save settings")).on_hover_text(tr("Keep these settings for the next export")).clicked() { + app.ui.windows.export = false; + } if ui.button(tr("Cancel")).clicked() { app.ui.windows.export = false; } + ui.label(trf("{n} textures selected for export", &[("n", &selected)])); }); }); }); @@ -1427,3 +1132,15 @@ mod tests { assert!(h.query_all_by_label("Remove layer").count() > 0); } } + +#[cfg(test)] +mod log_export_tests { + use super::*; + + #[test] + fn utc_text_formats_known_instants() { + assert_eq!(utc_text(0), "1970-01-01 00:00:00"); + assert_eq!(utc_text(1_709_164_799), "2024-02-28 23:59:59"); + assert_eq!(utc_text(1_709_164_800), "2024-02-29 00:00:00"); + } +} diff --git a/crates/ui-egui/tests/it/bake_presets.rs b/crates/ui-egui/tests/it/bake_presets.rs new file mode 100644 index 00000000..ae98652a --- /dev/null +++ b/crates/ui-egui/tests/it/bake_presets.rs @@ -0,0 +1,165 @@ +//! Bake presets (save, load, delete), "Apply to All Texture Sets" and the summary toast when a bake finishes. + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakeAntialiasing, BakeResolution, BakedMap}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake = Default::default(); + texture_set.bake.common.resolution = BakeResolution::R64; + texture_set.bake.maps.select([BakedMap::Id]); + } + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness.state_mut().ui.dock.focus(Panel::MeshMapBakers); + harness.run_steps(3); + harness +} + +fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).click(); + harness.run_steps(3); +} + +fn open_menu(harness: &mut Harness<'_, TextureCraftApp>) { + harness.get_by_label_contains("Presets").click(); + harness.run_steps(3); +} + +fn save_preset(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + open_menu(harness); + harness.state_mut().ui.bake_preset_name = name.to_string(); + harness.run_steps(2); + click(harness, "Save Preset"); +} + +fn antialiasing(harness: &Harness<'_, TextureCraftApp>, set: usize) -> BakeAntialiasing { + harness.state().session.doc.project.texture_sets[set].bake.common.antialiasing +} + +#[test] +fn a_saved_preset_loads_back_into_the_active_set_as_one_undo_step() { + let mut harness = harness(); + harness.state_mut().session.doc.project.texture_sets[0].bake.common.antialiasing = BakeAntialiasing::Subsampling4x4; + save_preset(&mut harness, "Final"); + assert_eq!(harness.state().ui.bake_presets.len(), 1); + assert_eq!(harness.state().ui.bake_presets[0].name, "Final"); + assert!(harness.state().ui.bake_preset_name.is_empty(), "the name field is cleared"); + + harness.state_mut().session.doc.project.texture_sets[0].bake.common.antialiasing = BakeAntialiasing::None; + let steps = harness.state().session.history_labels().len(); + open_menu(&mut harness); + click(&mut harness, "Final"); + + assert_eq!(antialiasing(&harness, 0), BakeAntialiasing::Subsampling4x4); + assert_eq!(antialiasing(&harness, 1), BakeAntialiasing::None, "only the active set loads it"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1); + harness.state_mut().session.undo().unwrap(); + assert_eq!(antialiasing(&harness, 0), BakeAntialiasing::None); +} + +#[test] +fn loading_a_preset_keeps_the_sets_include_in_bake_flag() { + let mut harness = harness(); + save_preset(&mut harness, "Plain"); + harness.state_mut().session.doc.project.texture_sets[0].bake.common.is_enabled = false; + open_menu(&mut harness); + click(&mut harness, "Plain"); + assert!(!harness.state().session.doc.project.texture_sets[0].bake.common.is_enabled); +} + +#[test] +fn saving_under_an_existing_name_replaces_it_and_delete_removes_it() { + let mut harness = harness(); + save_preset(&mut harness, "Fast"); + harness.state_mut().session.doc.project.texture_sets[0].bake.common.antialiasing = BakeAntialiasing::Subsampling2x2; + save_preset(&mut harness, "Fast"); + assert_eq!(harness.state().ui.bake_presets.len(), 1); + assert_eq!(harness.state().ui.bake_presets[0].settings.common.antialiasing, BakeAntialiasing::Subsampling2x2); + + open_menu(&mut harness); + harness.get_by_role_and_label(Role::Button, "Delete preset Fast").click(); + harness.run_steps(3); + assert!(harness.state().ui.bake_presets.is_empty()); +} + +#[test] +fn presets_survive_the_saved_ui_state() { + let mut harness = harness(); + save_preset(&mut harness, "Keep"); + let json = serde_json::to_string(&harness.state().ui).unwrap(); + let back: texturecraft_ui_egui::UiState = serde_json::from_str(&json).unwrap(); + assert_eq!(back.bake_presets, harness.state().ui.bake_presets); +} + +#[test] +fn apply_to_all_copies_the_active_sets_settings_and_keeps_each_include_flag() { + let mut harness = harness(); + { + let session = &mut harness.state_mut().session; + let first = &mut session.doc.project.texture_sets[0].bake; + first.common.antialiasing = BakeAntialiasing::Subsampling8x8; + first.maps.select([BakedMap::Id, BakedMap::Height]); + session.doc.project.texture_sets[1].bake.common.is_enabled = false; + } + assert_ne!(antialiasing(&harness, 1), BakeAntialiasing::Subsampling8x8); + + open_menu(&mut harness); + click(&mut harness, "Apply to All Texture Sets"); + + let second = &harness.state().session.doc.project.texture_sets[1].bake; + assert_eq!(second.common.antialiasing, BakeAntialiasing::Subsampling8x8); + assert_eq!(second.maps.enabled().collect::>(), vec![BakedMap::Id, BakedMap::Height]); + assert!(!second.common.is_enabled, "Include in Bake stays as it was"); + harness.state_mut().session.undo().unwrap(); + assert_ne!(antialiasing(&harness, 1), BakeAntialiasing::Subsampling8x8, "one undo step"); +} + +fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { + for _ in 0..4000 { + harness.run_steps(1); + if harness.state().bake.is_none() { + return; + } + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("the bake did not finish"); +} + +#[test] +fn a_finished_bake_toasts_maps_and_time_and_logs_them() { + let mut harness = harness(); + harness.state_mut().start_bake(vec![0]); + run_to_the_end(&mut harness); + + let toast = harness.state().toasts.last().expect("a summary toast"); + assert!(toast.text.starts_with("Baked 1 maps in "), "{}", toast.text); + assert!(!toast.error); + assert!(harness.state().session.log.last().unwrap().starts_with("Bake finished: 1 maps in ")); +} + +#[test] +fn a_failed_set_makes_an_error_toast_that_points_to_the_log() { + let mut harness = harness(); + { + let set = &mut harness.state_mut().session.doc.project.texture_sets[1]; + set.uv_tiles = vec![1001]; + set.bake_excluded_tiles.insert(1001); + } + harness.state_mut().start_bake(vec![0, 1]); + run_to_the_end(&mut harness); + + let toast = harness.state().toasts.last().expect("a summary toast"); + assert!(toast.error); + assert!(toast.text.contains("1 failed") && toast.text.contains("Log"), "{}", toast.text); + let log = &harness.state().session.log; + assert!(log.iter().any(|line| line.starts_with("Bake of texture set 1 failed")), "{log:?}"); +} diff --git a/crates/ui-egui/tests/it/camera_views.rs b/crates/ui-egui/tests/it/camera_views.rs index 3148c55f..23bfaf26 100644 --- a/crates/ui-egui/tests/it/camera_views.rs +++ b/crates/ui-egui/tests/it/camera_views.rs @@ -273,3 +273,75 @@ fn the_wheel_during_a_glide_is_not_overwritten_by_it() { }; assert!(end_distance(100.0) != end_distance(0.0), "the wheel zoom stays"); } + +#[test] +fn the_rotation_dropdown_switches_to_free_rotation_and_alt_drag_turns_the_model_over() { + let mut h = harness(); + assert!(!h.state().session.camera.free); + h.get_by_label("Constrained rotation").click(); + h.run_steps(2); + h.get_by_label_contains("Free rotation").click(); + h.run_steps(2); + assert!(h.state().session.camera.free, "the dropdown picks free rotation"); + + // A long vertical drag goes over the pole: the horizon is no longer level + let center = h.state().viewport_rect.center(); + drag(&mut h, center, vec2(0.0, 300.0), Modifiers::ALT); + let camera = h.state().session.camera; + assert!(camera.up().y < 0.0, "the model is turned over: {}", camera.up()); +} + +#[test] +fn constrained_rotation_keeps_the_horizon_on_the_same_drag() { + let mut h = harness(); + let center = h.state().viewport_rect.center(); + drag(&mut h, center, vec2(0.0, 300.0), Modifiers::ALT); + let camera = h.state().session.camera; + assert!(camera.up().y == 1.0 && camera.pitch <= 89f32.to_radians() + 1e-6); +} + +#[test] +fn snap_rotate_and_next_camera_are_bindable_and_a_bound_key_runs_them() { + let ids = ["camera.snapRotate.right", "camera.next", "camera.previous", "camera.rotation.free", "camera.rotation.constrained"]; + for id in ids { + assert!(texturecraft_ui_egui::keymap::bindings().iter().any(|binding| binding.id == id), "{id} can be bound"); + } + let mut h = harness(); + h.state_mut().run("camera.set", json!({"yaw": 0, "pitch": 0})); + h.state_mut().ui.keymap.insert("camera.snapRotate.right".into(), "F12".into()); + h.run_steps(2); + press(&mut h, Key::F12); + h.run_steps(30); + let camera = h.state().session.camera; + assert!((camera.yaw - FRAC_PI_2).abs() < 1e-3, "one step to the right: {}", camera.yaw); +} + +#[test] +fn next_and_previous_camera_commands_move_between_saved_cameras() { + let mut h = harness(); + for (name, yaw) in [("A", 20), ("B", 50)] { + h.state_mut().run("camera.set", json!({"yaw": yaw})); + h.state_mut().run("camera.add", json!({"name": name})); + } + h.state_mut().run("camera.select", json!({})); + h.run_steps(2); + h.state_mut().run("camera.next", json!({})); + h.run_steps(30); + assert!((h.state().session.camera.yaw.to_degrees() - 20.0).abs() < 0.5); + h.state_mut().run("camera.next", json!({})); + h.run_steps(30); + assert!((h.state().session.camera.yaw.to_degrees() - 50.0).abs() < 0.5); + h.state_mut().run("camera.previous", json!({})); + h.run_steps(30); + assert!((h.state().session.camera.yaw.to_degrees() - 20.0).abs() < 0.5); +} + +#[test] +fn the_view_picker_offers_the_combined_normal_view() { + let mut h = harness(); + h.get_all_by_role(egui::Role::ComboBox).find(|node| node.value().as_deref() == Some("Material")).expect("the view picker").click(); + h.run_steps(2); + h.get_by_label("Normal+height+mesh").click(); + h.run_steps(2); + assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::NormalHeightMesh); +} diff --git a/crates/ui-egui/tests/it/display_post_effects.rs b/crates/ui-egui/tests/it/display_post_effects.rs index 61c44c34..fcbd4ea4 100644 --- a/crates/ui-egui/tests/it/display_post_effects.rs +++ b/crates/ui-egui/tests/it/display_post_effects.rs @@ -34,7 +34,11 @@ fn app() -> Harness<'static, TextureCraftApp> { .click(); harness.run_steps(SETTLE_FRAMES); assert!(harness.query_by_label(SWITCH).is_none(), "the section starts folded"); - harness.get_by_label(SECTION).click(); + // The section's header, not the page's Post effects tab (a small icon) above it, scrolled into the page first + let widest = |a: &egui_kittest::Node<'_>, b: &egui_kittest::Node<'_>| a.rect().width().total_cmp(&b.rect().width()); + harness.get_all_by_label(SECTION).max_by(widest).unwrap().scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + harness.get_all_by_label(SECTION).max_by(widest).unwrap().click(); harness.run_steps(SETTLE_FRAMES * 3); harness.hover_at(egui::pos2(5.0, 5.0)); harness.run_steps(SETTLE_FRAMES); diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs index 5c13c6d8..6eaf3bc6 100644 --- a/crates/ui-egui/tests/it/file_dialogs.rs +++ b/crates/ui-egui/tests/it/file_dialogs.rs @@ -27,6 +27,16 @@ fn invoke(h: &mut Harness<'_, TextureCraftApp>, id: &str) { texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, id); } +/// The file dialog behind a menu item; Export Mesh's comes after its options prompt, whose Export asks for it this way +fn ask_file_of(h: &mut Harness<'_, TextureCraftApp>, id: &str) { + if id == "file.exportMesh" { + let ctx = h.ctx.clone(); + assert!(texturecraft_ui_egui::windows::file_action(h.state_mut(), &ctx, id)); + } else { + invoke(h, id); + } +} + /// A path in a new temporary folder. fn temp_file(test: &str, name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("texturecraft-file-dialogs-{test}-{}", std::process::id())); @@ -147,7 +157,7 @@ fn answered_after_the_project_changed(ask: impl FnOnce(&mut Harness<'_, TextureC fn every_project_dialog_does_nothing_for_a_replaced_project() { let file = temp_file("replaced-actions", "chosen.obj"); for id in ["material.load", "resource.import", "file.importMaterialX", "file.exportMesh", "file.reimportMesh"] { - let h = answered_after_the_project_changed(|h| invoke(h, id), &file); + let h = answered_after_the_project_changed(|h| ask_file_of(h, id), &file); assert!(h.state().toasts.iter().any(|t| t.error && t.text.starts_with(PROJECT_CHANGED)), "{id}"); assert!(!file.exists(), "{id} wrote nothing"); } diff --git a/crates/ui-egui/tests/it/help_menu_664.rs b/crates/ui-egui/tests/it/help_menu_664.rs new file mode 100644 index 00000000..d79ee5c2 --- /dev/null +++ b/crates/ui-egui/tests/it/help_menu_664.rs @@ -0,0 +1,103 @@ +//! Help ▸ Release notes... opens the releases page; Help ▸ Export log... saves the log to a text file; +//! Help ▸ Join the community (Discord)... opens the community Discord. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::Session; +use texturecraft_engine::geom::primitives; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::Answer; + +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + session.log.push("first line".into()); + session.log.push("second line".into()); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + h +} + +fn click_help_item(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + h.get_by_label("Help").click(); + h.run_steps(3); + h.get_by_label(label).click(); + h.run_steps(4); +} + +#[test] +fn release_notes_opens_the_releases_page() { + let mut h = harness(); + h.get_by_label("Help").click(); + h.run_steps(3); + h.get_by_label("Release notes...").click(); + + // The open-url command is in the output of the frame that handled the click only + h.step(); + let opened = h + .output() + .platform_output + .commands + .iter() + .any(|c| matches!(c, egui::OutputCommand::OpenUrl(u) if u.url == "https://github.com/storytold/texturecraft/releases")); + assert!(opened, "the releases page was opened"); +} + +const DISCORD: &str = "https://discord.gg/artcraft"; + +fn opened(h: &Harness<'_, TextureCraftApp>, url: &str) -> bool { + h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::OpenUrl(u) if u.url == url)) +} + +#[test] +fn join_the_community_opens_the_discord() { + let mut h = harness(); + h.get_by_label("Help").click(); + h.run_steps(3); + h.get_by_label("Join the community (Discord)...").click(); + h.step(); + assert!(opened(&h, DISCORD), "the community Discord was opened"); +} + +#[test] +fn join_the_community_is_bindable_and_a_bound_key_opens_the_discord() { + assert!(texturecraft_ui_egui::keymap::bindings().iter().any(|b| b.id == "ui.help.discord"), "ui.help.discord can be bound"); + let mut h = harness(); + h.state_mut().ui.keymap.insert("ui.help.discord".into(), "F12".into()); + h.run_steps(2); + h.event(egui::Event::Key { key: egui::Key::F12, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.step(); + assert!(opened(&h, DISCORD), "the bound key opened the community Discord"); +} + +#[test] +fn export_log_writes_every_line_with_time_and_level() { + let mut h = harness(); + let dir = std::env::temp_dir().join(format!("texturecraft-help-menu-664-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("log.txt"); + let answer = file.clone(); + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()])))); + click_help_item(&mut h, "Export log..."); + + let text = std::fs::read_to_string(&file).expect("the log file was written"); + let lines: Vec<&str> = text.lines().collect(); + assert!(lines[0].starts_with("TextureCraft log, exported ")); + let logged = h.state().session.log.clone(); + assert!(logged.len() >= 2); + for (written, line) in lines[1..].iter().zip(&logged) { + assert!(written.starts_with("[20"), "time first: {written}"); + assert!(written.contains("] INFO "), "level: {written}"); + assert!(written.ends_with(line.as_str()), "{written}"); + } + assert_eq!(lines.len(), logged.len() + 1); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_canceled_export_log_dialog_writes_nothing() { + let mut h = harness(); + h.state_mut().file_dialogs.set_override(Some(Box::new(|_| Answer::Cancelled))); + click_help_item(&mut h, "Export log..."); + assert!(h.state().toasts.is_empty()); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index d58f564b..57cf6649 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -4,6 +4,7 @@ mod alpha_parameters; mod bake_job_mesh; mod bake_mode; +mod bake_presets; mod brush_drag; mod brush_section_reset; mod camera_views; @@ -27,6 +28,7 @@ mod filter_picker; mod frame_selection; mod generator_panel; mod gradient_map_menu; +mod help_menu_664; mod history_panel; mod inactive_set_hint; mod layer_blending_options; @@ -50,6 +52,7 @@ mod rail; mod reference_order; mod rename_anchor; mod reset_ui; +mod settings_window; mod shelf_click; mod shelf_drop; mod shelf_hover_preview; @@ -58,6 +61,7 @@ mod shift_lines_2d; mod shift_lines_3d; mod shortcut_gestures; mod shortcut_keys; +mod side_panels; mod skew_paint; mod smudge_channels; mod snapped_lines; diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs index 0016e8e9..3e758c4e 100644 --- a/crates/ui-egui/tests/it/rail.rs +++ b/crates/ui-egui/tests/it/rail.rs @@ -33,7 +33,7 @@ const SETTLE_FRAMES: usize = 3; // A setting only Shader Settings shows, and one only Display Settings shows const SHADER_SETTING: &str = "Index of refraction"; -const DISPLAY_SETTING: &str = "Environment opacity"; +const DISPLAY_SETTING: &str = "Environment Opacity"; fn app() -> Harness<'static, TextureCraftApp> { app_of_size(WINDOW_SIZE) @@ -96,11 +96,11 @@ fn popup_close_button(harness: &Harness<'_, TextureCraftApp>) -> Option, name: &str) -> Option { let close = popup_close_button(harness)?; harness - .get_all_by_label(name) + .get_all_by_label(&name.to_uppercase()) .map(|node| node.rect()) .find(|title| title.right() < close.left() && (close.top()..=close.bottom()).contains(&title.center().y)) } @@ -160,7 +160,8 @@ fn the_close_button_a_press_outside_and_escape_close_it() { assert!(popup_closed(&harness), "Close"); click_rail(&mut harness, "Log"); - harness.get_by_label("Assets").click(); + // The Assets panel's tab, left of the viewport and clear of the popup (the Log has an Assets tab too) + harness.get_all_by_label("Assets").min_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().click(); harness.run_steps(SETTLE_FRAMES); assert!(popup_closed(&harness), "a press outside"); @@ -288,11 +289,11 @@ fn opening_the_window_menu_closes_the_rail_popup() { fn escape_closes_a_dropdown_before_its_rail_popup() { let mut harness = app(); click_rail(&mut harness, "Display Settings"); - let environment_row = harness.get_by_label("Environment map").rect(); + let environment_row = harness.get_by_label("Environment Map").rect(); harness - .get_all_by_role(Role::ComboBox) - .find(|combo| (combo.rect().center().y - environment_row.center().y).abs() < 1.0) - .expect("the environment dropdown") + .get_all_by_role(Role::Button) + .find(|button| button.rect().left() > environment_row.right() && (button.rect().center().y - environment_row.center().y).abs() < 2.0) + .expect("the Environment Map button") .click(); harness.run_steps(SETTLE_FRAMES); diff --git a/crates/ui-egui/tests/it/reference_order.rs b/crates/ui-egui/tests/it/reference_order.rs index 2afce36d..ae85cd92 100644 --- a/crates/ui-egui/tests/it/reference_order.rs +++ b/crates/ui-egui/tests/it/reference_order.rs @@ -38,9 +38,9 @@ fn every_menu_lists_its_items_in_the_reference_order() { "File: New project... | Open... | - | Open sample project... | - | Close | - | Save | Save as... | More save options > Save a copy... | Remove unused resources... | - | Import resources... | Import MaterialX material... | Import PBR texture folder... | Import material... | Export Textures... | Export Mesh... | - | Quit", "Edit: Undo | Redo | Project Configuration... | Reimport mesh | Settings...", "Mode: Bake Mesh Maps | Painting | Rendering (path traced)", - "Window: Views > Assets | Views > Common Settings | Views > Display Settings | Views > History | Views > Layers | Views > Log | Views > Mesh Map Bakers | Views > Mesh Map Settings | Views > Properties | Views > Shader Settings | Views > Texture Sets | Views > Texture Set Settings | - | Save UI Layout > Save current layout... | Load UI Layout | Layouts > Save current layout as... | Layouts > Manage layouts... | - | Hide UI | Reset panel layout | Reset UI", - "Viewport: Display material | Display next channel | Display previous channel | Display next mesh map | Display previous mesh map | UV checker | - | Frame texture set | Show entire mesh | Front view | Back view | Left view | Right view | Top view | Bottom view | - | Perspective | Orthographic | - | 3D/2D views | 3D view only | 2D view only | - | Navigation buttons | - | Enable quick mask | Edit quick mask | Invert quick mask", - "Help: Documentation... | Shortcuts list... | - | Join the community (Discord)... | ArtCraft website... | Report a bug... | Show log... | - | Check for Updates... | About TextureCraft...", + "Window: Views > Assets | Views > Common Settings | Views > Display Settings | Views > Export | Views > History | Views > Layers | Views > Log | Views > Mesh Map Bakers | Views > Mesh Map Settings | Views > Properties | Views > Shader Settings | Views > Texture Sets | Views > Texture Set Settings | - | Save UI Layout > Save current layout... | Load UI Layout | Layouts > Save current layout as... | Layouts > Manage layouts... | - | Hide UI | Reset panel layout | Reset UI", + "Viewport: Display material | Display next channel | Display previous channel | Display next mesh map | Display previous mesh map | UV checker | - | Frame texture set | Show entire mesh | Front view | Back view | Left view | Right view | Top view | Bottom view | - | Perspective | Orthographic | - | 3D/2D views | 3D view only | 2D view only | Swap 3D/2D | - | Navigation buttons | - | Enable quick mask | Edit quick mask | Invert quick mask", + "Help: Release notes... | Documentation... | Shortcuts list... | - | Join the community (Discord)... | ArtCraft website... | Report a bug... | Show log... | Export log... | - | Check for Updates... | About TextureCraft...", ]; let actual: Vec = menus::TOP .iter() @@ -76,7 +76,7 @@ fn the_tool_shelf_keeps_the_reference_order() { fn the_right_bar_keeps_the_reference_order() { let harness = harness(texturecraft_engine::sample_session(256, 64).unwrap()); let bar = buttons_in(&harness, 1562.0..1600.0); - let order = ["Export textures", "Log", "Display Settings", "Shader Settings", "History"]; + let order = ["Export", "Log", "Display Settings", "Shader Settings", "History"]; let row_positions: Vec = order.iter().map(|name| named(&bar, name).unwrap_or_else(|| panic!("{name} on the bar: {bar:?}")).0).collect(); assert!(row_positions.windows(2).all(|pair| pair[0] < pair[1]), "{row_positions:?}"); @@ -90,7 +90,7 @@ fn the_blank_screen_enables_what_the_reference_enables() { assert!(named(&shelf, name).unwrap().2, "{name} should be disabled with no project"); } let bar = buttons_in(&harness, 1562.0..1600.0); - for name in ["Export textures", "Log", "Display Settings", "Shader Settings", "History"] { + for name in ["Export", "Log", "Display Settings", "Shader Settings", "History"] { assert!(!named(&bar, name).unwrap().2, "{name} on the right bar stays enabled"); } @@ -150,6 +150,7 @@ fn the_blank_screen_menus_match_the_measured_enabled_states() { "ui.view.textureSetList", "ui.view.textureSetSettings", "ui.view.display", + "ui.view.export", "ui.view.history", "ui.view.log", "ui.view.shader", diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs new file mode 100644 index 00000000..dd922f95 --- /dev/null +++ b/crates/ui-egui/tests/it/settings_window.rs @@ -0,0 +1,296 @@ +//! Edit > Settings: the General, Shortcuts and Libraries pages, OK and Cancel. + +use egui::{Event, Key, Modifiers, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::Session; +use texturecraft_ui_egui::settings_window::{PROJECT_OPEN_NOTE, SettingsPage}; +use texturecraft_ui_egui::state::{LibraryLocation, UiState}; +use texturecraft_ui_egui::unavailable::NOT_AVAILABLE; +use texturecraft_ui_egui::{TextureCraftApp, menus}; + +#[path = "../../src/ui_state_store/memory_storage.rs"] +mod memory_storage; +use memory_storage::MemoryStorage; + +/// The section captions of the General page, top to bottom. +const SECTIONS: [&str; 13] = [ + "INTERFACE OPTIONS", + "LAYER STACK OPTIONS", + "CAMERA OPTIONS", + "BAKING OPTIONS", + "PREVIEW OPTIONS", + "TEMPORARY FILES", + "SPARSE VIRTUAL TEXTURE", + "IRAY HARDWARE", + "APPEARANCE", + "VIEWPORT", + "RESOURCES", + "AUTOSAVE", + "FOLDERS", +]; + +fn harness(session: Session) -> Harness<'static, TextureCraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The exact-text checks need English, whatever the OS language is + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + h +} + +fn open_settings(h: &mut Harness<'_, TextureCraftApp>) { + let ctx = h.ctx.clone(); + menus::invoke(h.state_mut(), &ctx, "ui.settings"); + h.run_steps(4); +} + +fn page(h: &Harness<'_, TextureCraftApp>) -> Option { + h.state().ui.windows.settings_draft.as_ref().map(|draft| draft.page) +} + +/// Scroll the page to the widget labelled `label`, then click it. +fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + h.get_by_label(label).scroll_to_me(); + h.run_steps(3); + h.get_by_label(label).click(); + h.run_steps(4); +} + +fn toggled(h: &Harness<'_, TextureCraftApp>, label: &str) -> bool { + h.get_by_label(label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +/// The text field labelled `label`, focused and given `text`. +fn type_into(h: &mut Harness<'_, TextureCraftApp>, label: &str, text: &str) { + h.get_by_role_and_label(Role::TextInput, label).focus(); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, label).type_text(text); + h.run_steps(2); +} + +#[test] +fn the_left_column_switches_between_the_three_pages() { + let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); + open_settings(&mut h); + assert_eq!(page(&h), Some(SettingsPage::General)); + assert!(toggled(&h, "General"), "the chosen page is highlighted"); + assert!(!toggled(&h, "Shortcuts")); + assert!(h.query_by_label("INTERFACE OPTIONS").is_some()); + + click(&mut h, "Shortcuts"); + assert_eq!(page(&h), Some(SettingsPage::Shortcuts)); + assert!(h.query_by_label("ACTIONS").is_some()); + assert!(h.query_by_label("INTERFACE OPTIONS").is_none()); + + click(&mut h, "Libraries"); + assert_eq!(page(&h), Some(SettingsPage::Libraries)); + assert!(h.query_by_label("LIBRARY LOCATIONS").is_some()); + assert!(h.query_by_label(PROJECT_OPEN_NOTE).is_some()); + + click(&mut h, "General"); + assert_eq!(page(&h), Some(SettingsPage::General)); +} + +#[test] +fn the_general_page_lists_the_reference_sections_in_order_without_privacy() { + let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); + open_settings(&mut h); + + // Rows below the scrolled view are laid out too, in page order + let mut shown: Vec = h + .query_all(egui_kittest::kittest::by().predicate(|node| node.label().or_else(|| node.value()).is_some_and(|text| SECTIONS.contains(&text.as_str())))) + .filter_map(|node| node.accesskit_node().label().or_else(|| node.accesskit_node().value())) + .collect(); + // A label on screen also has a node for its text run + shown.dedup(); + assert_eq!(shown, SECTIONS.map(String::from).to_vec()); + assert!(h.query_by_label("PRIVACY").is_none(), "no Privacy section"); + assert!(h.query_by_label("Automatically send usage statistics").is_none()); +} + +#[test] +fn the_general_page_starts_at_the_reference_defaults() { + let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); + open_settings(&mut h); + h.state_mut().ui.windows.settings_draft.as_mut().unwrap().prefs.language = texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE.into(); + h.run_steps(3); + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Language").value().as_deref(), Some("Default (System Language)")); + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Viewport Scaling").value().as_deref(), Some("Auto")); + assert_eq!(h.get_by_role_and_label(Role::SpinButton, "Local cache budget (in MB)").accesskit_node().numeric_value(), Some(4000.0)); + for label in [ + "Show keyboard helper", + "Show world axes", + "Use simplified thumbnails (improves performance)", + "Save preprocessed scene files", + "Enable live preview baking process", + "Enable GPU raytracing", + "Hardware support acceleration", + ] { + assert!(toggled(&h, label), "{label} is ticked"); + } + for label in ["Only display the selected material when painting", "CPU"] { + assert!(!toggled(&h, label), "{label} is not ticked"); + } + assert!(h.query_all_by_label("Inverse direction").all(|node| node.accesskit_node().toggled() == Some(egui::accesskit::Toggled::False))); + + let prefs = texturecraft_ui_egui::state::Prefs::default(); + assert_eq!((prefs.rotation_speed, prefs.zoom_speed, prefs.wheel_speed), (2.0, 1.0, 1.0)); +} + +#[test] +fn a_control_the_app_lacks_is_disabled_and_says_so_on_hover() { + let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); + h.ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); + open_settings(&mut h); + let away = h.get_by_role_and_label(Role::Tab, "Libraries").rect().center(); + for label in [ + "Show keyboard helper", + "Show world axes", + "Only display the selected material when painting", + "Use simplified thumbnails (improves performance)", + "Save preprocessed scene files", + "Enable live preview baking process", + "Hardware support acceleration", + "CPU", + ] { + h.hover_at(away); + h.run_steps(3); + assert!(h.query_by_label(NOT_AVAILABLE).is_none(), "no hint before hovering {label}"); + h.get_by_label(label).scroll_to_me(); + h.run_steps(3); + let node = h.get_by_label(label); + assert!(node.accesskit_node().is_disabled(), "{label} is disabled"); + node.hover(); + h.run_steps(6); + assert!(h.query_by_label(NOT_AVAILABLE).is_some(), "hovering {label} says it is not available yet"); + } + for step in ["−", "+"] { + assert!(h.query_all_by_label(step).any(|node| node.accesskit_node().is_disabled()), "the cache budget's {step} is disabled"); + } + assert!(!h.get_by_label("Enable GPU raytracing").accesskit_node().is_disabled(), "GPU raytracing switches bakes to the CPU"); + for label in ["Rotation speed", "Zoom speed", "Wheel speed"] { + assert!(h.query_by_label(label).is_some(), "{label} is shown"); + } +} + +#[test] +fn cancel_drops_the_changes_and_ok_applies_and_keeps_them() { + let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); + let before = h.state().ui.prefs.clone(); + open_settings(&mut h); + h.get_by_role_and_label(Role::SpinButton, "Autosave every").set_value_accesskit(25.0); + click(&mut h, "Enable GPU raytracing"); + h.run_steps(2); + assert_eq!(h.state().ui.prefs, before, "edits wait for OK"); + click(&mut h, "Cancel"); + assert!(!h.state().ui.windows.settings && h.state().ui.windows.settings_draft.is_none(), "Cancel closes the window"); + assert_eq!(h.state().ui.prefs, before, "Cancel drops the edits"); + + open_settings(&mut h); + assert_eq!( + h.get_by_role_and_label(Role::SpinButton, "Autosave every").accesskit_node().numeric_value(), + Some(f64::from(before.autosave_minutes)), + "a new window starts from the settings in use" + ); + h.get_by_role_and_label(Role::SpinButton, "Autosave every").set_value_accesskit(25.0); + h.get_by_role_and_label(Role::SpinButton, "Max CPU threads for work").set_value_accesskit(1.0); + h.get_by_role_and_label(Role::SpinButton, "Max project size on open").set_value_accesskit(12.0); + h.run_steps(2); + h.query_all_by_label("Inverse direction").next().unwrap().scroll_to_me(); + h.run_steps(3); + h.query_all_by_label("Inverse direction").next().unwrap().click(); + h.run_steps(2); + click(&mut h, "Enable GPU raytracing"); + click(&mut h, "OK"); + + let prefs = h.state().ui.prefs.clone(); + assert!(!h.state().ui.windows.settings, "OK closes the window"); + assert_eq!((prefs.autosave_minutes, prefs.work_threads, prefs.project_open_limit_gib), (25, 1, 12)); + assert!(prefs.zoom_inverse && !prefs.wheel_inverse && !prefs.gpu_raytracing); + assert!(prefs.drag_zoom_scale() < 0.0, "inverted zoom runs the other way"); + + let mut storage = MemoryStorage::default(); + eframe::App::save(h.state_mut(), &mut storage); + let restored: UiState = serde_json::from_str(&storage.values["ui.json"]).unwrap(); + assert_eq!(restored.prefs, prefs, "the settings are kept between runs"); +} + +#[test] +fn a_shortcut_edited_on_the_shortcuts_page_applies_on_ok() { + let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); + open_settings(&mut h); + click(&mut h, "Shortcuts"); + let save = texturecraft_ui_egui::keymap::bindings().iter().find(|b| b.id == "file.save").unwrap(); + click(&mut h, &format!("Edit the shortcut of {}", save.label)); + assert!(h.query_by_label("Press a key...").is_some(), "the row waits for a key"); + h.event(Event::Key { key: Key::F5, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + let edited = h.state().ui.windows.settings_draft.as_ref().unwrap().keymap.get("file.save").cloned(); + assert_eq!(edited.as_deref(), Some("F5"), "the row takes the pressed key"); + assert!(h.query_by_label("Press a key...").is_none(), "the row stops waiting"); + assert!(!h.state().ui.keymap.contains_key("file.save"), "the shortcut waits for OK"); + + // Help > Shortcuts rebinds another item while Settings is open + h.state_mut().ui.keymap.insert("ui.about".into(), "F9".into()); + + click(&mut h, "OK"); + assert_eq!(h.state().ui.keymap.get("file.save").map(String::as_str), Some("F5")); + assert_eq!(h.state().ui.keymap.get("ui.about").map(String::as_str), Some("F9"), "OK keeps a shortcut changed elsewhere"); +} + +#[test] +fn a_library_location_is_added_removed_and_kept() { + let mut h = harness(Session::closed().unwrap()); + let folder = std::env::temp_dir().join(format!("tc-settings-library-{}", std::process::id())); + open_settings(&mut h); + click(&mut h, "Libraries"); + for name in ["your_assets", "starter_assets"] { + assert!(h.query_by_label(name).is_some(), "{name} is listed"); + assert!(h.get_by_label(&format!("Remove {name}")).accesskit_node().is_disabled(), "{name} is built in"); + } + + type_into(&mut h, "Name", "my_assets"); + type_into(&mut h, "Path", &folder.display().to_string()); + click(&mut h, "Add the location"); + assert!(h.query_by_label("my_assets").is_some(), "the new location is listed"); + click(&mut h, "OK"); + let added = LibraryLocation { name: "my_assets".into(), path: folder.display().to_string() }; + assert_eq!(h.state().ui.prefs.libraries, vec![added]); + + let mut storage = MemoryStorage::default(); + eframe::App::save(h.state_mut(), &mut storage); + let restored: UiState = serde_json::from_str(&storage.values["ui.json"]).unwrap(); + assert_eq!(restored.prefs.libraries, h.state().ui.prefs.libraries, "added locations are kept between runs"); + + open_settings(&mut h); + click(&mut h, "Libraries"); + click(&mut h, "Remove my_assets"); + click(&mut h, "OK"); + assert!(h.state().ui.prefs.libraries.is_empty()); +} + +#[test] +fn library_locations_cannot_change_while_a_project_is_open() { + let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); + open_settings(&mut h); + click(&mut h, "Libraries"); + assert!(h.get_by_role_and_label(Role::TextInput, "Name").accesskit_node().is_disabled()); + assert!(h.get_by_label("Add the location").accesskit_node().is_disabled()); +} + +#[test] +fn closing_the_window_from_elsewhere_stops_waiting_for_a_key() { + let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); + open_settings(&mut h); + click(&mut h, "Shortcuts"); + let save = texturecraft_ui_egui::keymap::bindings().iter().find(|b| b.id == "file.save").unwrap(); + click(&mut h, &format!("Edit the shortcut of {}", save.label)); + assert!(texturecraft_ui_egui::keymap::capturing(&h.ctx), "the row waits for a key"); + + // Reset UI, a layout or the control channel can close the window + h.state_mut().ui.windows.settings = false; + h.run_steps(3); + assert!(!texturecraft_ui_egui::keymap::capturing(&h.ctx), "shortcuts work again"); + assert!(h.state().ui.windows.settings_draft.is_none()); +} diff --git a/crates/ui-egui/tests/it/shortcut_gestures.rs b/crates/ui-egui/tests/it/shortcut_gestures.rs index 4f900746..fdcddf9f 100644 --- a/crates/ui-egui/tests/it/shortcut_gestures.rs +++ b/crates/ui-egui/tests/it/shortcut_gestures.rs @@ -25,6 +25,8 @@ fn the_gesture_grid_of_the_shortcut_window_lists_the_stencil_clone_line_and_path "Path: remove the selected or last point", "Path: cancel it", "Shift + RMB drag", + "Alt + Shift + LMB drag", + "Camera snap rotate", ] { assert!(h.query_by_label(text).is_some(), "the overview lacks {text}"); } diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs new file mode 100644 index 00000000..11350ed8 --- /dev/null +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -0,0 +1,304 @@ +//! The rail's side panels as in the reference: Undock and Dock, the Export panel and its two exports, the Log's channel +//! tabs, the Display and Shader Settings rows, the shader choice and the section tabs that follow the scrolling + +use egui::{Event, Modifiers, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::file_dialogs::Answer; +use texturecraft_ui_egui::state::UiState; +use texturecraft_ui_egui::unavailable::NOT_AVAILABLE; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// The rail is the last 38 points of the window +const RAIL_LEFT_EDGE: f32 = WINDOW_SIZE.x - 38.0; + +/// Frames for the first layout and fonts to settle, and for a click to land +const STARTUP_FRAMES: usize = 4; +const SETTLE_FRAMES: usize = 3; + +/// Frames for a tooltip to appear under a resting pointer +const TOOLTIP_FRAMES: usize = 30; + +fn app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// The rail icon of the panel named `name` +fn rail_icon<'h>(harness: &'h Harness<'_, TextureCraftApp>, name: &str) -> Option> { + let is_panel = |label: &str| label == name || label.starts_with(&format!("{name} (")); + harness + .get_all_by_role(Role::Button) + .find(|button| button.rect().min.x >= RAIL_LEFT_EDGE && button.accesskit_node().label().is_some_and(|label| is_panel(&label))) +} + +fn click_rail(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + rail_icon(harness, name).expect("the panel's icon on the rail").click(); + harness.run_steps(SETTLE_FRAMES); +} + +/// The button labelled `label` left of the rail (the rail has its own Export icon) +fn button_left_of_rail<'h>(harness: &'h Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'h> { + harness + .get_all_by_role(Role::Button) + .find(|button| button.rect().max.x < RAIL_LEFT_EDGE && button.accesskit_node().label().as_deref() == Some(label)) + .unwrap_or_else(|| panic!("the {label} button")) +} + +fn is_floating(harness: &Harness<'_, TextureCraftApp>, panel: Panel) -> bool { + harness.state().ui.dock.workspace().layout.floating.iter().any(|window| window.contains(&panel)) +} + +/// Hover the control labelled `label` until its tooltip shows, and tell whether that says it is not available yet +fn says_not_available(harness: &mut Harness<'_, TextureCraftApp>, label: &str) -> bool { + let at = harness.get_all_by_label(label).next().unwrap_or_else(|| panic!("{label}")).rect().center(); + harness.hover_at(at); + harness.run_steps(TOOLTIP_FRAMES); + harness.query_by_label(NOT_AVAILABLE).is_some() +} + +fn is_on(node: &egui_kittest::Node<'_>) -> bool { + node.accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn undock_floats_the_panel_dock_returns_it_to_the_rail_and_the_float_persists() { + let mut harness = app(); + click_rail(&mut harness, "History"); + + button_left_of_rail(&harness, "Undock").click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(harness.state().ui.dock.is_visible(Panel::History) && is_floating(&harness, Panel::History), "History floats on its own"); + assert!(harness.state().ui.rail_panel.is_none(), "the popup closed"); + assert!(rail_icon(&harness, "History").is_none(), "a floating panel leaves the rail"); + + // The floating window is part of the saved interface state + let saved = serde_json::to_value(&harness.state().ui).unwrap(); + let restored: UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(restored.dock, harness.state().ui.dock); + assert!(restored.dock.workspace().layout.floating.iter().any(|window| window.contains(&Panel::History))); + + button_left_of_rail(&harness, "Dock").click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(!harness.state().ui.dock.is_open(Panel::History), "Dock closes the floating window"); + assert!(rail_icon(&harness, "History").is_some(), "History is back on the rail"); + click_rail(&mut harness, "History"); + assert_eq!(harness.state().ui.rail_panel, Some(Panel::History), "and opens from it again"); +} + +#[test] +fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { + let mut harness = app(); + click_rail(&mut harness, "Export"); + + assert_eq!(harness.state().ui.rail_panel, Some(Panel::Export)); + assert!(!harness.state().ui.windows.export, "the rail opens the Export panel, not a window"); + for label in ["SEND TO", "EXPORT", "Export to image editor", "Send to compositing app", "Send to 3D staging app"] { + assert!(harness.query_all_by_label(label).next().is_some(), "{label}"); + } + assert!(says_not_available(&mut harness, "Send to compositing app")); + + button_left_of_rail(&harness, "Export Textures...").click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(harness.state().ui.windows.export, "Export Textures... opens the Export textures window"); + for label in + ["SETTINGS", "OUTPUT TEMPLATES", "LIST OF EXPORTS", "Include all", "Global settings", "General Export Parameters", "Reset all", "Save settings"] + { + assert!(harness.query_by_label(label).is_some(), "{label}"); + } + assert!(harness.query_by_label_contains("textures selected for export").is_some()); + assert!(says_not_available(&mut harness, "Export USD asset")); + + harness.get_by_label("Save settings").click(); + harness.run_steps(SETTLE_FRAMES); + assert!(!harness.state().ui.windows.export, "Save settings closes the window"); + + click_rail(&mut harness, "Export"); + button_left_of_rail(&harness, "Export Mesh...").click(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_label("Mesh Export Options").is_some(), "Export Mesh... asks for the options first"); +} + +#[test] +fn export_mesh_asks_the_options_then_the_file() { + let mut harness = app(); + let dir = std::env::temp_dir().join(format!("texturecraft-side-panels-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("mesh.obj"); + let _ = std::fs::remove_file(&file); + let answer = file.clone(); + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()])))); + + let ctx = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &ctx, "file.exportMesh"); + harness.run_steps(SETTLE_FRAMES); + + assert!(harness.query_by_label("Mesh Export Options").is_some()); + assert_eq!(harness.state().file_dialogs.pending(), 0, "no file is asked for before the options"); + for label in ["Without displacement/tessellation", "With displacement/tessellation", "Apply triangulation", "Recompute vertex normals"] { + assert!(harness.query_by_label(label).is_some(), "{label}"); + } + assert!(says_not_available(&mut harness, "With displacement/tessellation")); + + button_left_of_rail(&harness, "Export").click(); + harness.run_steps(SETTLE_FRAMES * 3); + + assert!(harness.query_by_label("Mesh Export Options").is_none(), "Export closes the options"); + assert!(file.exists(), "the mesh went to the picked file"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Whether the Log lists `line` (the status bar under it repeats the last message) +fn log_lists(harness: &Harness<'_, TextureCraftApp>, line: &str) -> bool { + harness.query_all_by_label(line).any(|node| node.rect().bottom() < STATUS_BAR_TOP) +} + +/// The status bar is the window's bottom 22 points +const STATUS_BAR_TOP: f32 = WINDOW_SIZE.y - 22.0; + +#[test] +fn the_log_tabs_show_one_channel_each() { + let mut harness = app(); + harness.state_mut().session.log.push("Saved /somewhere/project.tcraft".into()); + harness.state_mut().session.log.push("resource stone.png: not an image".into()); + click_rail(&mut harness, "Log"); + + assert!(harness.query_by_label("General").is_some()); + assert!(log_lists(&harness, "Saved /somewhere/project.tcraft")); + assert!(!log_lists(&harness, "resource stone.png: not an image"), "asset messages wait under Assets"); + + // The Log's own Assets tab, right of the dock's Assets panel tab + harness.get_all_by_label("Assets").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(log_lists(&harness, "resource stone.png: not an image")); + assert!(!log_lists(&harness, "Saved /somewhere/project.tcraft")); +} + +#[test] +fn display_settings_show_the_reference_rows() { + let mut harness = app(); + harness.state_mut().ui.dock.focus(Panel::Display); + harness.run_steps(STARTUP_FRAMES); + + for label in [ + "View mode", + "ENVIRONMENT SETTINGS", + "Environment", + "Environment Map", + "Override environment map color space", + "Environment Opacity", + "Environment Exposure (EV)", + "Environment Blur", + "Environment Rotation", + "Environment Alignment", + "Shadows", + "Computation mode", + "Shadows opacity", + "CAMERA SETTINGS", + "Preset", + "Restore", + ] { + assert!(harness.query_all_by_label(label).next().is_some(), "{label}"); + } + + let combo_value = |harness: &Harness<'_, TextureCraftApp>, value: &str| { + harness.get_all_by_role(Role::ComboBox).any(|combo| combo.accesskit_node().value().as_deref() == Some(value)) + }; + for value in ["Auto", "World", "Lightweight", "Default camera"] { + assert!(combo_value(&harness, value), "a dropdown shows {value}"); + } + assert!(!harness.state().session.doc.project.display.shadows, "shadows start off"); + assert!(says_not_available(&mut harness, "Override environment map color space")); +} + +#[test] +fn shader_settings_show_the_reference_rows_and_the_shader_choice() { + let mut harness = app(); + harness.state_mut().ui.dock.focus(Panel::Shader); + harness.run_steps(STARTUP_FRAMES); + + for label in [ + "Undo", + "Redo", + "open-pbr", + "Instance name", + "SHADER PARAMETERS", + "Base Surface", + "AO Intensity", + "Specular", + "Enable anisotropy", + "Index of refraction", + "Enable specular color", + "Transmission", + "Enable transmission", + "Subsurface", + "Subsurface radius", + "Subsurface scatter anisotropy", + "Use thickness map", + ] { + assert!(harness.query_all_by_label(label).next().is_some(), "{label}"); + } + assert_eq!(harness.state().session.doc.project.display.ior, 1.5, "the reference's index of refraction"); + assert!(says_not_available(&mut harness, "Enable anisotropy")); + + harness.get_by_role_and_label(Role::Button, "open-pbr").click(); + harness.run_steps(SETTLE_FRAMES); + + let tiles: Vec = + texturecraft_ui_egui::shader_settings::SHADER_TYPES.iter().map(|name| format!("{}\n{name}", egui_phosphor::regular::SPHERE)).collect(); + for name in &tiles { + assert!(harness.query_all_by_label(name).next().is_some(), "{name:?} is listed"); + } + assert_eq!(harness.query_all_by_label(&tiles[7]).count(), 6, "six entries read pbr-m..."); + let query = harness + .get_all_by_role(Role::TextInput) + .any(|field| field.accesskit_node().value().as_deref() == Some(texturecraft_ui_egui::shader_settings::SHADER_QUERY)); + assert!(query, "the search starts at shaders"); + let open_pbr = harness.get_by_label(&tiles[4]); + assert!(!open_pbr.accesskit_node().is_disabled() && is_on(&open_pbr), "open-pbr is the current shader"); + assert!(harness.get_by_label(&tiles[1]).accesskit_node().is_disabled(), "the others are not available yet"); +} + +#[test] +fn scrolling_highlights_the_section_tab_and_a_tab_jumps_to_its_section() { + let mut harness = app(); + click_rail(&mut harness, "Display Settings"); + let tab = |harness: &Harness<'_, TextureCraftApp>, name: &str| is_on(&harness.get_by_role_and_label(Role::Button, name)); + + assert!(tab(&harness, "Environment settings"), "the first section is highlighted at the top"); + + harness.get_by_role_and_label(Role::Button, "Viewer settings").click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(tab(&harness, "Viewer settings") && !tab(&harness, "Environment settings"), "the clicked tab is highlighted"); + let heading = harness.get_by_label("VIEWER SETTINGS").rect(); + assert!(harness.ctx.content_rect().contains_rect(heading), "the page scrolled to Viewer settings"); + + // Scroll back up a little: the Camera or Post effects heading is the one passed last + let over_page = heading.center(); + harness.hover_at(over_page); + for _ in 0..40 { + harness.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, 60.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: Modifiers::NONE, + }); + harness.run_steps(1); + } + harness.run_steps(12); + + assert!(tab(&harness, "Environment settings"), "back at the top, Environment settings is highlighted again"); + assert!(!tab(&harness, "Viewer settings")); +} diff --git a/crates/ui-egui/tests/it/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs index 4e8c0364..29c3cbae 100644 --- a/crates/ui-egui/tests/it/split_divider.rs +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -227,3 +227,51 @@ fn dragging_the_divider_keeps_the_uv_texture_size_and_offset_on_screen() { assert!((0.1..=40.0).contains(&stopped_zoom), "zoom {zoom} stopped at {stopped_zoom}"); } } + +/// Press F4, the default key of Swap 3D/2D +fn press_f4(harness: &mut Harness<'_, TextureCraftApp>) { + harness.event(Event::Key { key: egui::Key::F4, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + harness.event(Event::Key { key: egui::Key::F4, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); +} + +#[test] +fn f4_swaps_the_views_and_both_still_work_and_the_state_is_saved() { + let mut harness = split_app(); + let rect_3d = harness.state().viewport_rect; + let y = rect_3d.center().y; + assert!(!harness.state().ui.swap_views); + + press_f4(&mut harness); + assert!(harness.state().ui.swap_views, "F4 swaps"); + let swapped_3d = harness.state().viewport_rect; + assert!(swapped_3d.left() > rect_3d.center().x, "3D is on the right now: {swapped_3d:?}"); + + // 2D is on the left: a drag there paints, a right-drag in 3D orbits + let (tiles, angles) = (painted_tiles(&harness), camera_angles(&harness)); + let left_x = rect_3d.left() + 200.0; + drag(&mut harness, PointerButton::Primary, pos2(left_x, y), pos2(left_x, y + 40.0)); + assert!(painted_tiles(&harness) > tiles, "the 2D view on the left paints"); + let right_x = swapped_3d.center().x; + drag(&mut harness, PointerButton::Secondary, pos2(right_x, y), pos2(right_x - 120.0, y)); + assert_ne!(camera_angles(&harness), angles, "the 3D view on the right orbits"); + + // The divider drags on the swapped sides and the 3D view's share follows + let divider = swapped_3d.left() - 1.0; + drag(&mut harness, PointerButton::Primary, pos2(divider, y), pos2(divider + 100.0, y)); + assert!((harness.state().viewport_rect.left() - 1.0 - (divider + 100.0)).abs() < 0.5, "the divider follows the pointer"); + assert!(harness.state().ui.split_ratio < 0.5, "the 3D view got narrower"); + + // Saved with the UI state, and F4 swaps back + let mut ui_state = harness.state().ui.clone(); + let json = serde_json::to_string(&ui_state).unwrap(); + ui_state = serde_json::from_str(&json).unwrap(); + assert!(ui_state.swap_views); + press_f4(&mut harness); + assert!(!harness.state().ui.swap_views); + assert!( + harness.state().viewport_rect.right() < rect_3d.right() + 400.0 && harness.state().viewport_rect.left() == rect_3d.left(), + "3D is back on the left" + ); +} diff --git a/crates/ui-egui/tests/it/symmetry.rs b/crates/ui-egui/tests/it/symmetry.rs index 620300a1..030e709a 100644 --- a/crates/ui-egui/tests/it/symmetry.rs +++ b/crates/ui-egui/tests/it/symmetry.rs @@ -25,7 +25,7 @@ const VIEW_CORNER_INSET: f32 = 40.0; fn app_harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(1024, 256).unwrap(); let mut harness = - Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + Harness::builder().with_size(egui::vec2(1760.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().session.tool.tool = Tool::Paint; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/project_limits.rs b/crates/ui-egui/tests/project_limits.rs index 7363a5dd..c6c3e34a 100644 --- a/crates/ui-egui/tests/project_limits.rs +++ b/crates/ui-egui/tests/project_limits.rs @@ -31,10 +31,11 @@ fn resource_settings_follow_hardware_persist_and_apply_before_control_requests() assert_eq!(formats::project_open_limit_gib(), 16, "saved preferences apply during startup"); harness.run_steps(3); - assert_eq!(harness.state().ui.prefs.reserved_cores, available_cores, "preferences from a larger machine are clamped"); + let edited = |harness: &Harness<'_, TextureCraftApp>| harness.state().ui.windows.settings_draft.as_ref().unwrap().prefs.clone(); + assert_eq!(edited(&harness).reserved_cores, available_cores, "preferences from a larger machine are clamped"); harness.get_by_role_and_label(egui::Role::SpinButton, "Cores kept for the UI").set_value_accesskit(f64::from(u32::MAX)); harness.run_steps(3); - assert_eq!(harness.state().ui.prefs.reserved_cores, available_cores, "editing cannot exceed this machine's CPU count"); + assert_eq!(edited(&harness).reserved_cores, available_cores, "editing cannot exceed this machine's CPU count"); assert!(harness.query_by_label("≈ 8.00 GiB").is_some(), "50% of 16 GiB is shown beside the percentage"); harness.get_by_role_and_label(egui::Role::SpinButton, "Max RAM while saving").set_value_accesskit(25.0); harness.run_steps(3); @@ -42,7 +43,11 @@ fn resource_settings_follow_hardware_persist_and_apply_before_control_requests() harness.get_by_role_and_label(egui::Role::SpinButton, "Max project size on open").set_value_accesskit(24.0); harness.run_steps(3); - assert_eq!(formats::project_open_limit_gib(), 24, "the input field applies the edited value"); + assert_eq!(formats::project_open_limit_gib(), 16, "an edit waits for OK"); + harness.get_by_label("OK").click(); + harness.run_steps(3); + assert_eq!(formats::project_open_limit_gib(), 24, "OK applies the edited value"); + assert_eq!(harness.state().ui.prefs.reserved_cores, available_cores); let context = egui::Context::default(); let reply = control::handle(harness.state_mut(), &context, "ui.set", &serde_json::json!({"prefs": {"project_open_limit_gib": 32}})); diff --git a/crates/ui-egui/tests/shader_panel.rs b/crates/ui-egui/tests/shader_panel.rs index 805420cb..9ca472c9 100644 --- a/crates/ui-egui/tests/shader_panel.rs +++ b/crates/ui-egui/tests/shader_panel.rs @@ -23,7 +23,7 @@ fn shader_settings_leave_the_height_strength_to_the_texture_set_settings() { harness.state_mut().ui.dock.focus(Panel::Shader); harness.run_steps(STARTUP_FRAMES); - assert!(harness.query_by_label("AO intensity").is_some(), "the Shader Settings panel is shown"); + assert!(harness.query_by_label("AO Intensity").is_some(), "the Shader Settings panel is shown"); // Texture Set Settings, the slider's other home, sits behind Layers in the default layout, so any match is in Shader Settings assert!(!harness.state().ui.dock.is_visible(Panel::TextureSetSettings), "Texture Set Settings is behind Layers"); assert!(harness.query_by_label("Height to normal strength").is_none()); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index eab48e4e..fdaca016 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -857,3 +857,39 @@ fn tile_generator_gradient_map_snapshot() { assert!(harness.query_by_label_contains("Add color").is_some()); save(&mut harness, &output_dir, "tile-generator-gradient-map"); } + +/// Edit > Settings: the General page, then the Shortcuts and Libraries pages +#[test] +#[ignore] +fn settings_pages_snapshot() { + use texturecraft_ui_egui::settings_window::SettingsPage; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let session = texturecraft_engine::sample_session(128, 32).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.windows.settings = true; + save(&mut harness, &output_dir, "settings-general"); + + // The rest of the General page, a page height further down each time + let page = harness.get_by_label("INTERFACE OPTIONS").rect().center() + egui::vec2(150.0, 100.0); + for part in 2..=4 { + harness.hover_at(page); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -480.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + }); + save(&mut harness, &output_dir, &format!("settings-general-{part}")); + } + for (page, name) in [(SettingsPage::Shortcuts, "settings-shortcuts"), (SettingsPage::Libraries, "settings-libraries")] { + if let Some(draft) = harness.state_mut().ui.windows.settings_draft.as_mut() { + draft.page = page; + } + save(&mut harness, &output_dir, name); + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 23bf09f3..fe43d3ce 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -86,6 +86,12 @@ before the edit is applied as one undo step. `model` still replaces the complete when combined, `patch` follows `model`, then the flat command parameters apply. Omitting `ts` still targets the active set for scripts that need individual control. +Bake presets are saved settings in the UI state (Mesh Map Bakers > Presets). Loading one is +`bake.settings {ts: , model: , preserveEnabled: true}`; Apply to All +Texture Sets is the same with `ts: "all"` and the active set's `model`. Both are one undo step. +When a bake started in the app ends, a toast gives the maps baked, the time and the failed sets, and +the session log gets `Bake finished: N maps in T` and `Bake of texture set N failed: `. + The bake texture-set list shows visibility eyes and expandable UV tile rows. Visibility affects the viewport independently of bake inclusion. Its resolution menus edit the texture-set size (`textureSet.resolution`) and individual tile overrides (`textureSet.tile.resolution`), independently @@ -155,11 +161,12 @@ keeps its state in a throwaway file. | `session.inspect` | | project, mesh, texture sets, layer stack, tool, camera, display, history | | `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | | `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled}` | -| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question). `{"id": "ui.layout.apply", "name": ""}` switches to a panel layout saved under Window > Layouts (panels only; mode, zoom and wireframes stay) and errors when no layout has that name | +| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a panel layout saved under Window > Layouts (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) | +| `ui.menu.invoke` ids `ui.help.releaseNotes`, `ui.help.exportLog` | `{id}` | Help > Release notes... opens the releases page in the browser; Help > Export log... asks where to save the log as a text file (a save dialog, like the menu click) | | `ui.reset` | | resets the panels, view layout, zoom and every other view setting at once, without the question the Reset UI menu item asks; settings and shortcuts stay | | `ui.bake.start` | `{ts?: index \| [indices]}` (default: the sets ticked in Bake mode) | Opens Bake mode and bakes in the background like the Bake button: the 3D view shows the maps landing on the model as they finish (see *Live bake preview*). → the `bake.preview` state. Errors when a bake is already running | | `ui.bake.cancel` | | Stops the running bake; the set being baked keeps the maps it had, sets already finished stay applied, and the previous view mode comes back | -| `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History` and `Log`; `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame; `system_title_bar` `true` has the system draw the title bar from the next start), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds) | `null` | +| `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History`, `Log` and `Export` (a floating window holding one right-bar panel is that panel undocked); `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame; `system_title_bar` `true` has the system draw the title bar from the next start), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds), `log_channel` the Log panel's tab (`General` or `Assets`) | `null` | | `viewport.screenshot` | `{view?: "3d" \| "2d"}` | `{width, height, png}` (PNG, base64) | | `ui.screenshot` | | `{width, height, png}` of the whole window, after the next frame | | `ui.resize` | `{width, height}` | Sets the window's inner size in points (640–7680), leaving maximized state; for recordings and screenshots at a fixed size | @@ -241,6 +248,13 @@ Settings bounds the reserved-core input to the available logical CPU count and s save budget in GiB beside the RAM percentage. The readout refreshes once a second from currently available RAM; a save calculates its budget when it starts. +Other preferences set through `ui.set {"prefs": {...}}`: `language` (`""` follows the system +language), `work_threads` (worker threads for painting, baking and export; 0 uses every logical +CPU; read at startup), `rotation_speed` (default 2), `zoom_speed` and `wheel_speed` (default 1, +each from 0.1 to 10) with `zoom_inverse` and `wheel_inverse`, `gpu_raytracing` (false keeps bake +rays on the CPU) and `libraries` (added library locations as `{"name", "path"}`; the shelf lists +the saved smart materials and masks in each folder). + ## MCP server `texturecraft-cli mcp` speaks MCP on stdin/stdout (stdout carries only protocol messages). @@ -496,10 +510,26 @@ frames the whole mesh. Both return the camera like `camera.get`. `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) +shortcut, bindable in Settings ▸ Shortcuts). `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. +`camera.rotation {mode: constrained|free}` (or `camera.rotation.constrained` / `camera.rotation.free`, +Viewport menu and the rotation dropdown of the top bar) picks the orbit: constrained (the default) keeps +the horizon level and stops at the poles; free is a trackball that turns the camera about its own axes, +so the model can be turned over and rolled. `camera.get` shows it as `rotation`; `camera.set` takes +`rotation` too. Switching keeps the direction of view; going back to constrained drops the roll. Saved +cameras, fixed views and `camera.set` yaw/pitch put a free camera level. `camera.snapRotate {yaw?, pitch?}` +(whole 90° steps; the angles first go to the nearest step) is the command behind the Alt+Shift+left drag +("Camera snap rotate"); `camera.snapRotate.left|right|up|down` are its menu forms. `camera.next` and +`camera.previous` go to the next or previous saved camera (wrapping; from a view that is no saved +camera, the first or the last). The commands have no default keys and are bindable in Settings ▸ Keyboard. +None is an undo step. + +`viewport.view {mode: "normalHeightMesh"}` is the combined "Normal+height+mesh" view: the surface normal +the shading uses (mesh normal, Height channel slope and Normal channel), unlit; the 2D view shows its +tangent-space form. + ## 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 57f28206..91ede43e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -134,6 +134,12 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA edited): drop one from the Assets panel on a slot of the Texture Set Settings, or pick it from the slot's menu. A UV-tiled set takes one image per tile, named with its tile number (`ao.1001.png`, `ao.1002.png`…): drop or pick any one of them. +- **Bake presets:** Mesh Map Bakers > Presets saves the active texture set's bake settings under a + name, loads one back into the active set (its Include in Bake choice stays) and deletes it. + Presets are kept between sessions. **Apply to All Texture Sets** copies the active set's settings, + including its map list, to every set. When a bake ends, a toast names the maps baked, the time + and the failed sets (an error toast that points to the Log if any); the Log gets the same line + and one line per failed set. - **Live bake preview:** while the app bakes, each mesh map shows on the model as soon as it is finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), @@ -143,6 +149,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA override and OpenGL or DirectX normals. - **Output template editor:** build your own presets with per-channel packing, converted maps and per-channel inversion, and share them as JSON. +- **Export panel** on the right bar: *Export Mesh...* asks for the mesh export options, then for + the file; *Export Textures...* opens the Export textures window (Settings, Output templates and + List of exports, *Include all*, *Save settings* and the number of textures the export writes). - **Mesh export** to OBJ with an MTL material library and its maps (PBR extension keys for roughness, metallic, normal and coat; UV-tiled sets keep their UDIM UVs and export their maps through Export textures), textured GLB (with clear coat and sheen) and USD (with clear coat). @@ -162,7 +171,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - 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 show the entire mesh, Shift+F to frame the active texture set (a floor plane or other helper geometry stays out of the view and the orbit pivot), - M / C / B to cycle views. Orbit, pan and zoom buttons in the corner of each view do the same with a + M / C / B to cycle views. Choose **free (trackball) or constrained rotation** in the top bar (free + turns the model over; commands for stepped turns and for the next / previous saved camera can be + bound in Settings), and the **Normal+height+mesh** view in the view picker. Orbit, pan and zoom buttons in the corner of each view do the same with a plain drag, so a pen and tablet can navigate without a keyboard or wheel (Viewport menu ▸ Navigation buttons hides them). - **Perspective (F5) or orthographic (F6)** projection, and **front, back, left, right, top and @@ -172,18 +183,31 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA ## Interface +- **Swap 3D/2D** (F4, Viewport menu and the layout dropdown, rebindable) puts the 2D view on the left and the 3D view on the right in the split layout. Painting, the divider and the views' headers work on both sides, and the choice is kept with the UI state. - A modern look in **four brightness levels** (dark, medium dark, medium light and light) with - **seven accent colors**, set in Settings › Interface. + **seven accent colors**, set in Settings › General › Appearance. - **Its own title bar** with the app icon, menus and window buttons on Windows (and on Linux desktops that leave the frame to the app, such as GNOME), the macOS traffic lights over the same - strip, and Settings › Interface › System title bar for the system's frame instead. + strip, and Settings › General › Appearance › System title bar for the system's frame instead. - **Dockable, tabbed and floating panels**, saved layouts, and panels that reopen where you closed - them. + them. The right bar's panels (Export, Log, Display Settings, Shader Settings, History) pop out + beside it; *Undock* makes one a floating window, and its *Dock* button puts it back on the bar. +- **Display and Shader Settings** are one scrolling page each: their section tabs jump to a + section, and scrolling highlights the tab of the section in view. +- A **Log** panel with a *General* and an *Assets* tab: asset messages (resources that do not + decode, skipped templates and presets, PBR folder and MaterialX import warnings) go under Assets. - **No project at launch**: empty views, panels and toolbars until you create or open one (File › New project, Open, Recent projects, Open sample project); File › Close returns to that state. - A **data folder** of your choice for autosaves, smart materials, presets, templates and UI - layouts, on any drive (Settings › Folders; `Documents/TextureCraft` by default). + layouts, on any drive (Settings › General › Folders; `Documents/TextureCraft` by default). +- A **Settings window** (Edit › Settings) with General, Shortcuts and Libraries pages; changes + apply on OK and Cancel drops them. General holds the language (or the system's), the 3D view's + rotation, zoom and wheel speeds with inverse directions, GPU or CPU bake rays, resource limits + (worker threads, cores kept for the UI, RAM while saving, project size on open) and the autosave + interval. Shortcuts rebinds any command. Libraries adds or removes folders whose saved smart + materials and masks the shelf lists. - A **shortcut editor** with conflict detection, listing every menu item and every command a key can run (commands that need a path, name or similar are left out), and every shortcut shown in its tooltip. +- **Help menu:** Release notes... opens the project's releases page in the browser; Export log... saves the whole log (every channel, one line each with time and level) to a text file chosen in a save dialog. - A **History** panel: click any step to go back to it, or forward again to an undone one. - **10 languages:** English, French, German, Spanish, Portuguese, Italian, Japanese, Chinese, Korean and Arabic, switchable live. diff --git a/docs/parity.md b/docs/parity.md index 70d417f8..529f0fe6 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). -**73 of 73 menu items live (100%).** +**77 of 77 menu items live (100%).** ## File @@ -49,6 +49,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Views ▸ Assets | `ui.view.assets` | | live | | Views ▸ Common Settings | `ui.view.bakeSettings` | | live | | Views ▸ Display Settings | `ui.view.display` | | live | +| Views ▸ Export | `ui.view.export` | | live | | Views ▸ History | `ui.view.history` | | live | | Views ▸ Layers | `ui.view.layers` | | live | | Views ▸ Log | `ui.view.log` | | live | @@ -89,6 +90,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | 3D/2D views | `ui.layout.split` | F1 | live | | 3D view only | `ui.layout.3d` | F2 | live | | 2D view only | `ui.layout.2d` | F3 | live | +| Swap 3D/2D | `ui.layout.swap` | F4 | live | | Navigation buttons | `ui.navButtons` | | live | | Enable quick mask | `viewport.quickMask` | Y | live | | Edit quick mask | `viewport.quickMask.edit` | U | live | @@ -98,12 +100,14 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Item | Id | Shortcut | Status | |---|---|---|---| +| Release notes... | `ui.help.releaseNotes` | | live | | Documentation... | `ui.help.docs` | | live | | Shortcuts list... | `ui.help.shortcuts` | | live | | Join the community (Discord)... | `ui.help.discord` | | live | | ArtCraft website... | `ui.help.website` | | live | | Report a bug... | `ui.help.bug` | | live | | Show log... | `ui.view.log` | | live | +| Export log... | `ui.help.exportLog` | | live | | Check for Updates... | `ui.help.checkForUpdates` | | live | | About TextureCraft... | `ui.about` | | live | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 622852ba..6879972b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -55,6 +55,39 @@ The relevant implementations are [layer rows, menus and fill/brush editors](../c [display settings](../crates/core/src/project.rs), and [smart-mask commands](../crates/engine/src/smart_masks.rs). +## Side panels ([#642](https://github.com/storytold/texturecraft/issues/642)) + +**UI + tests** (`crates/ui-egui/tests/it/side_panels.rs`). The right bar lists Export, Log, +Display Settings, Shader Settings and History in the reference order (Texture Set Settings follows +when it is not docked). Each opens a popup beside the bar with its title in capitals, an *Undock* +button that turns it into a floating window, and *Close*. A floating rail panel has a *Dock* button +that closes it back onto the bar; the float is saved with the UI state. + +- **Export:** SEND TO lists three targets and a Configure button, all greyed with "Not available + yet". The reference names other products there; TextureCraft says *Export to image editor*, + *Send to compositing app* and *Send to 3D staging app*. EXPORT has *Export Mesh...* (the + *Mesh Export Options* prompt, then the file choice) and *Export Textures...* (the Export textures + window: *Global settings* above the texture sets, *General Export Parameters*, *Export USD asset* + and *Export shaders parameters* greyed, *Include all*, *Save settings* and "N textures selected + for export"). The prompt's *With displacement/tessellation* choice and both option checkboxes are + greyed; TextureCraft exports the mesh as it is. +- **Log:** *General* and *Assets* tabs. Messages are sorted by how they begin (see + `log_panel::ASSET_PREFIXES`); the status bar still shows the latest message of either. +- **Display Settings:** *View mode* above the section tabs; Environment settings (Environment Map, + Opacity, Exposure (EV), Blur, Rotation; *Override environment map color space* with *Auto*, + *Environment Alignment* *World*), Shadows (*Shadows*; *Computation mode* *Lightweight* and + *Shadows opacity* 90 greyed) and Camera settings (*Preset* and *Restore* work on the saved + cameras). Post effects and Viewer settings keep TextureCraft's own controls. The reference's + fifth tab is not shown in the screenshot and is left out. Colour management stays greyed. +- **Shader Settings:** greyed *Undo*, *Redo* and *Instance name* (*Main shader*); the *open-pbr* + button opens the shader choice with the reference's search (*u:shader*) and its 17 entries as + the screenshot shows them, names cut short included. Only *open-pbr* works. Shader parameters + (Base Surface, Specular, Transmission, Subsurface) and Displacement & tessellation (Enable, + Displacement, Tessellation, *Restore defaults*) follow the reference; rows TextureCraft cannot + drive are greyed. Its own Metallic Roughness / Specular Glossiness model choice, Scatter color and + Parallax occlusion stay in the fitting sections. *Quality*, *Horizon fade* and the cut-off + "Enable d..." row are hidden in the reference screenshot and are left out. + ## Partial areas | ID | Area | Observed limit | Next check | @@ -62,6 +95,11 @@ The relevant implementations are [layer rows, menus and fill/brush editors](../c | UI-12 | Generator depth and property coverage | **UI + source.** The picker contains seven kinds. Switching to Position, changing Global balance and duplicating the effect worked. Shared global adjustments, resolution and input slots already exist; that does not establish the richer generator/control inventory in [#374](https://github.com/storytold/texturecraft/issues/374) | Audit each generator's inputs, micro-detail behavior and controls against the reference; do not count seven shared implementations as equivalent to its whole catalog | | UI-13 | Narrow workspace readability | **UI.** At 1280 × 800 the app rendered, both views stayed visible and the toolbar exposed scroll arrows. Layer names/types became heavily truncated, the layer toolbar wrapped, and Properties needed scrolling. This was not an input-failure or docking-persistence test | Repeat the editing tasks at smaller sizes, widen/rearrange panels, check full-name tooltips and keyboard access, and retain the layout after restart. Since then: the Layers toolbar stays on one row at 1280 × 800 (its channel box shrinks), and a cut-short layer name or type shows in full on hover. Properties scrolling and restart persistence are unchanged | | UI-14 | Assets panel filters | **UI + source.** The type dropdown lists the reference entries in its order, Fonts and Show all included. Saved searches and Filter by path are separate scrollable panes with a divider that supports pointer and keyboard resizing and saves its position with the UI state ([#640](https://github.com/storytold/texturecraft/issues/640)). Fonts, the built-in saved searches Favorites, 3D Assets and Flattened layers, and the System fonts and User fonts libraries are listed but greyed with "Not available yet" | Give fonts, favorites, 3D assets and flattened layers real assets, then enable those rows and check that each one filters the grid | +| UI-15 | Edit > Settings ([#637](https://github.com/storytold/texturecraft/issues/637)) | **Source + headless UI tests.** The window has the reference's General, Shortcuts and Libraries pages with OK and Cancel, and the General sections in its order (no Privacy section: TextureCraft sends no usage data). Language (with Default (System Language)), the camera rotation, zoom and wheel speeds with Inverse direction, Enable GPU raytracing, the Shortcuts page and adding or removing library locations work. Show keyboard helper, Show world axes, Background color, Only display the selected material when painting, Viewport Scaling, Default UV scale for materials, simplified thumbnails, the other baking options, the preview cache and shader, the temporary cache directory, sparse virtual texture and the IRAY HARDWARE choices are shown disabled with "Not available yet". A location's Default choice is fixed to your_assets. TextureCraft's own settings (appearance, viewport textures, resources, autosave, folders) follow the reference sections | Run the window in the native app; wire each disabled control as its function lands | + +Bake workflow (issue [#651](https://github.com/storytold/texturecraft/issues/651)): Mesh Map Bakers +has a Presets menu (save, load, delete named bake settings; Apply to All Texture Sets) and a finished +bake shows a summary toast (maps baked, time, failed sets, pointing to the Log on failure). Broader properties/filter work remains tracked in [#433](https://github.com/storytold/texturecraft/issues/433). Its individual rows need checking @@ -78,7 +116,7 @@ list, not a feature-completion denominator. | F02 Paint in 3D | UI | Pass | A mouse drag produced a visible stroke in 3D and its UV representation; inspection showed a Paint stroke undo step and painted tiles | | F03 Paint in 2D | UI | Pass | A separate UV-view drag increased painted tiles from 7 to 21 per active channel and changed the visible image | | F04 Undo and redo | UI | Pass | Ctrl+Z restored 7 tiles and history depth 2; Ctrl+Y restored 21 tiles and depth 3 | -| F05 View switching | UI | Pass | F2 selected Only3D, F3 Only2D and F1 Split; the screenshots changed accordingly | +| F05 View switching | UI | Pass | F2 selected Only3D, F3 Only2D and F1 Split; the screenshots changed accordingly. F4 (Swap 3D/2D) puts 2D on the left and 3D on the right | | F06 Brush gesture | UI | Pass | Ctrl+right-drag changed size from 8 to about 12.94 and hardness from 50 to about 38. This also demonstrates that diagonal movement changes both parameters; pen precision was not tested | | F07 Shelf search and material application | UI | Pass | Searching for car and dragging Car Paint onto the mesh added a red fill layer and an Add Car Paint history step | | F08 Fill layer and black mask | UI | Pass | Layer toolbar added a fill; the layer-name context menu added a black mask and selected the mask target | @@ -130,3 +168,11 @@ fidelity. The new `.spp` reader is a future goal, not a tested capability. No implementation fixes were made in this assessment. The build from the earlier pass was reused; the full Rust tests, clippy, wasm and other operating-system builds were not rerun. + +## Camera and view (2026-11-18) + +Closes the camera gaps of [#649](https://github.com/storytold/texturecraft/issues/649): +constrained / free (trackball) rotation, the "Camera snap rotate" commands next to the +Alt+Shift+left drag (which already existed), bindable next / previous saved camera (the +Ctrl+1 ... Ctrl+9 slots stay), and the "Normal+height+mesh" entry of the view picker. +Free rotation uses the same Alt+left drag (and right drag) as the constrained one.